1,定义工具
- package com.jinhei;
-
- import com.fasterxml.jackson.databind.JsonNode;
- import com.fasterxml.jackson.databind.ObjectMapper;
-
- import java.io.*;
- import java.util.ArrayList;
- import java.util.List;
-
- /**
- * 代理工具类 - 为AI提供可调用的功能
- */
- public class AgentTools {
- // JSON解释器 - 用来读懂JSON格式的数据
- private final ObjectMapper objectMapper = new ObjectMapper();
-
- /**
- * 将制定内容写入到本地文件中
- * @param jsonInput 包含 'filePath' 和 'content' 的 JSON 字符串
- * @return 执行结果
- */
- @Tool(description = "将指定内容写入本地文件") //这个注解告诉 AI , 这是一个可用的工具
- public String putFile(@ToolParam(description = "包含 'filePath' 和 'content' 的 JSON 字符串") String jsonInput) {
- //第一步: 尝试执行写文件操作(就像尝试完成一项任务)
- try {
- //1.1 解析JSON输入: 读懂"文件保存单"
- //把json字符串解析成树形结构, 方便提取数据
- JsonNode rootNode = objectMapper.readTree(jsonInput);
-
- //提取文件路径: 从"文件保存单"上面找到"保存位置"这一项
- String filePath = rootNode.get("filePath").asText();
-
- //提取文件内容: 从"文件保存单"上面找到"文件内容"这一项
- String content = rootNode.get("content").asText();
-
- //1.2执行写文件: 真正的把内容写到磁盘上
- try (FileWriter writer = new FileWriter(filePath)) {
- //把内容写到文件中
- writer.write(content);
- //成功!告诉AI任务完成了
- return String.format("成功将内容写入文件 '%s'", filePath);
- } catch (IOException e) {
- //写文件失败(比如磁盘没有权限或者磁盘满了等等)
- return String.format("写入文件 '%s' 时发生错误: '%s'", filePath, e.getMessage());
- }
-
- } catch (Exception e) {
- //解析json失败 (比如: AI给的格式不对, 缺少必要的字段)
- return String.format("解析 Action input 或执行 putFile 工具时出错: %s", e.getMessage());
- }
-
-
- }
-
- /**
- * 批量写入多个文件 (循环应用)
- */
- @Tool(description = "批量写入多个文件(循环应用)")
- public String batchPutFile(@ToolParam(description = "包含 'files' 数组的JSON字符串, 每个元素包含 'filePath' 和 'content'") String jsonInput) {
- try {
- //1.解析JSON输入: 读懂"批量文件保存单"
- JsonNode rootNode = objectMapper.readTree(jsonInput);
- JsonNode filesArray = rootNode.get("files");
-
- //2.检查结果
- if (filesArray == null || !filesArray.isArray()) {
- return "JSON 格式错误: 缺少 'files' 数组字段";
- }
-
- //3. 循环处理每个文件
- List<String> results = new ArrayList<>();
- int successCount = 0;
- int failCount = 0;
-
- for (JsonNode fileNode : filesArray) {
- String filePath = fileNode.get("filePath").asText();
- String content = fileNode.get("content").asText();
-
- //对每个文件执行写入的操作
- try (FileWriter writer = new FileWriter(filePath)) {
- writer.write(content);
- results.add(String.format("√ 成功写入: %s", filePath));
- successCount++;
- } catch (IOException e) {
- results.add(String.format("× 写入失败: %s - %s", filePath, e.getMessage()));
- failCount++;
- }
- }
-
- //4.汇总结果
- StringBuilder summary = new StringBuilder();
- summary.append(String.format("批量处理完成: 共 %d 个文件, 成功 %d 个, 失败 %d 个",
- filesArray.size(),successCount,failCount ));
-
- for (String result : results) {
- summary.append(result).append("\n");
- }
- return summary.toString();
- } catch (Exception e) {
- return String.format("批量写入文件时出错: %s", e.getMessage());
- }
- }
-
- /**
- * 读取本地文件中的内容
- */
- @Tool(description = "读取本地文件中的内容")
- public String getFile(@ToolParam(description = "包含 'filePath'的 JSON 字符串") String jsonInput) {
- try {
- //1.解析 JSON 输入
- JsonNode rootNode = objectMapper.readTree(jsonInput);
- String filePath = rootNode.get("filePath").asText();
-
- //2.检查文件是否存在
- File file = new File(filePath);
- if (!file.exists()) {
- return String.format("文件 %s 不存在", filePath);
- }
-
- //3.读取文件内容
- StringBuilder content = new StringBuilder();
- try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
- String line;
- while ((line = reader.readLine()) != null) {
- content.append(line).append("\n");
- }
- }
- return String.format("成功读取文件 '%s', 内容为: \n%s", filePath, content.toString());
- } catch (Exception e) {
- return String.format("读取文件 '%s' 时出错: %s", jsonInput, e.getMessage());
- }
- }
- }
复制代码 2,读取文件
- package com.jinhei;
-
- import com.alibaba.fastjson2.JSONObject;
- import com.jinhei.AgentTools;
- import com.jinhei.AiConfig;
- import com.jinhei.ToolUtil;
- import com.openai.client.OpenAIClient;
- import com.openai.client.okhttp.OpenAIOkHttpClient;
- import com.openai.models.chat.completions.ChatCompletion;
- import com.openai.models.chat.completions.ChatCompletionCreateParams;
-
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.HashMap;
-
- /**
- * 调用模型
- */
- public class AiChat {
- private static final String TEMPLATE = """
- 你是一位能力强大的 AI 助手,擅长通过逻辑推理与调用工具来解决问题。
-
- 你可以使用的工具如下:
- {tools}
-
- **重要: 你必须严格按照以下 JSON 格式返回工具调用请求: **
- ```json
- {
- "toolName": "工具名称",
- "params": "{参数 JSON 字符串}"
- }
- ```
-
- 注意:
- 1. 只能返回上述 JSON 格式, 不要添加任何解释文字
- 2. params 字段必须是字符串格式的 JSON
- 3. 不要使用markdown 代码块标记
-
- 当前用户的问题是:
- {input}
- """;
-
- public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- //第0步: 准备工作 - 注册可用的工具
- HashMap<String, Method> tools = new HashMap<>();
- tools.put("putFile", AgentTools.class.getMethod("putFile", String.class));
- tools.put("batchPutFile", AgentTools.class.getMethod("batchPutFile", String.class));
- tools.put("getFile", AgentTools.class.getMethod("getFile", String.class));
-
- //第1步: 创建AI客户端 - 建立与AI服务的连接通道
- OpenAIClient aiClient = OpenAIOkHttpClient.builder()
- .apiKey(AiConfig.API_KEY) //设置API密钥
- .baseUrl(AiConfig.BASE_URL) //设置服务地址
- .build();//建造完成
-
- //第2步: 准备要问的问题
- //2.1用户的实际问题
- String promptString = "读取D:\\\\ 中的result.txt的内容";
-
- //2.2 替换模板中的工具占位符
- String prompt = TEMPLATE.replace("{tools}", ToolUtil.getToolDescription(AgentTools.class));
-
- //2.3替换模板中的用户问题占位符
- prompt = prompt.replace("{input}", promptString);
-
- //第3步: 构建请求参数 - 把问题打包成AI能理解的格式
- ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
- .addUserMessage(prompt) //添加用户消息: 你说的话
- .model(AiConfig.LLM_NAME) //指定用哪个AI大模型来处理
- .build();//打包完成 - 准备发送
-
- //第4步: 发送请求并获取回复 - 把信寄出去, 等待回信
- ChatCompletion chatCompletion = aiClient.chat() //打开聊天功能
- .completions() //开启补全模式(AI回复)
- .create(params); //发送请求并等待响应
-
- //第5步: 提取AI的回答 - 拆开回信, 取出内容
- //5.1 获取AI返回的原始信息
- String message = chatCompletion.choices().get(0).message().content().get();
-
- //5.2清理消息格式
- message = message.replace("```tool_code", "");
- message = message.replace("```json", "");
- message = message.replace("```", "");
-
- //5.3解析JSON
- JSONObject jsonObject = JSONObject.parseObject(message);
-
- //获取工具的名称
- String toolName = jsonObject.getString("toolName");
- String toolParams = jsonObject.getString("params");
-
- //第6步: 执行工具调用
- //6.1 从工具注册表中找到对应的方法
- Method toolMethod = tools.get(toolName);
-
- //6.2创建工具实例并且执行方法
- Object result = toolMethod.invoke(new AgentTools(), toolParams);
-
- //第7步: 显示结果
- System.out.println(result);
-
- }
-
- }
复制代码
aiagent.zip
(22.17 KB, 下载次数: 0, 售价: 50 金豆)
|