classWeatherTools{@Tool(description ="Get current weather for a location")publicStringgetWeather(@ToolParam(description ="The city name")String city){return"Current weather in "+ city +": Sunny, 25°C";}}// 使用方式ChatClient.create(chatModel).prompt("What's the weather in Beijing?").tools(newWeatherTools()).call();
2)Functions模式:通过@Bean注解定义工具,通过functions方法绑定工具
@ConfigurationpublicclassToolConfig{@Bean@Description("Get current weather for a location")publicFunction<WeatherRequest,WeatherResponse>weatherFunction(){return request ->newWeatherResponse("Weather in "+ request.getCity()+": Sunny, 25°C");}}// 使用方式ChatClient.create(chatModel).prompt("What's the weather in Beijing?").functions("weatherFunction").call();
publicclassFileOperationTool{privatefinalString FILE_DIR =FileConstant.FILE_SAVE_DIR +"/file";@Tool(description ="Read content from a file")publicStringreadFile(@ToolParam(description ="Name of the file to read")String fileName){String filePath = FILE_DIR +"/"+ fileName;try{returnFileUtil.readUtf8String(filePath);}catch(Exception e){return"Error reading file: "+ e.getMessage();}}@Tool(description ="Write content to a file")publicStringwriteFile(@ToolParam(description ="Name of the file to write")String fileName,@ToolParam(description ="Content to write to the file")String content){String filePath = FILE_DIR +"/"+ fileName;try{// 创建目录FileUtil.mkdir(FILE_DIR);FileUtil.writeUtf8String(content, filePath);return"File written successfully to: "+ filePath;}catch(Exception e){return"Error writing to file: "+ e.getMessage();}}}
编写测试类:
@SpringBootTestpublicclassFileOperationToolTest{@TestpublicvoidtestReadFile(){FileOperationTool tool =newFileOperationTool();String fileName ="耄耄爱哈气";String result = tool.readFile(fileName);assertNotNull(result);}@TestpublicvoidtestWriteFile(){FileOperationTool tool =newFileOperationTool();String fileName ="耄耄爱哈气.txt";String content ="https://chengfushi.blog.csdn.net/";String result = tool.writeFile(fileName, content);assertNotNull(result);}}
publicclassWebScrapingTool{@Tool(description ="Scrape the content of a web page")publicStringscrapeWebPage(@ToolParam(description ="URL of the web page to scrape")String url){try{Document doc =Jsoup.connect(url).get();return doc.html();}catch(IOException e){return"Error scraping web page: "+ e.getMessage();}}}
3)编写测试类
@SpringBootTestpublicclassWebScrapingToolTest{@TestpublicvoidtestScrapeWebPage(){WebScrapingTool tool =newWebScrapingTool();String url ="https://chengfushi.blog.csdn.net/";String result = tool.scrapeWebPage(url);assertNotNull(result);}}
publicclassTerminalOperationTool{@Tool(description ="Execute a command in the terminal")publicStringexecuteTerminalCommand(@ToolParam(description ="Command to execute in the terminal")String command){StringBuilder output =newStringBuilder();try{ProcessBuilder builder =newProcessBuilder("cmd.exe","/c", command);// Process process = Runtime.getRuntime().exec(command);Process process = builder.start();try(BufferedReader reader =newBufferedReader(newInputStreamReader(process.getInputStream()))){String line;while((line = reader.readLine())!=null){
output.append(line).append("\n");}}int exitCode = process.waitFor();if(exitCode !=0){
output.append("Command execution failed with exit code: ").append(exitCode);}}catch(IOException|InterruptedException e){
output.append("Error executing command: ").append(e.getMessage());}return output.toString();}}
2)编写单元测试代码:
@SpringBootTestpublicclassTerminalOperationToolTest{@TestpublicvoidtestExecuteTerminalCommand(){TerminalOperationTool tool =newTerminalOperationTool();String command ="dir";String result = tool.executeTerminalCommand(command);assertNotNull(result);}}
publicclassResourceDownloadTool{@Tool(description ="Download a resource from a given URL")publicStringdownloadResource(@ToolParam(description ="URL of the resource to download")String url,@ToolParam(description ="Name of the file to save the downloaded resource")String fileName){String fileDir =FileConstant.FILE_SAVE_DIR +"/download";String filePath = fileDir +"/"+ fileName;try{// 创建目录FileUtil.mkdir(fileDir);// 使用 Hutool 的 downloadFile 方法下载资源HttpUtil.downloadFile(url,newFile(filePath));return"Resource downloaded successfully to: "+ filePath;}catch(Exception e){return"Error downloading resource: "+ e.getMessage();}}}
publicclassPDFGenerationTool{@Tool(description ="Generate a PDF file with given content")publicStringgeneratePDF(@ToolParam(description ="Name of the file to save the generated PDF")String fileName,@ToolParam(description ="Content to be included in the PDF")String content){String fileDir =FileConstant.FILE_SAVE_DIR +"/pdf";String filePath = fileDir +"/"+ fileName;try{// 创建目录FileUtil.mkdir(fileDir);// 创建 PdfWriter 和 PdfDocument 对象try(PdfWriter writer =newPdfWriter(filePath);PdfDocument pdf =newPdfDocument(writer);Document document =newDocument(pdf)){// 自定义字体(需要人工下载字体文件到特定目录)// String fontPath = Paths.get("src/main/resources/static/fonts/simsun.ttf")// .toAbsolutePath().toString();// PdfFont font = PdfFontFactory.createFont(fontPath,// PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);// 使用内置中文字体PdfFont font =PdfFontFactory.createFont("STSongStd-Light","UniGB-UCS2-H");
document.setFont(font);// 创建段落Paragraph paragraph =newParagraph(content);// 添加段落并关闭文档
document.add(paragraph);}return"PDF generated successfully to: "+ filePath;}catch(IOException e){return"Error generating PDF: "+ e.getMessage();}}}