找回密码
 立即注册

3,批量写入和读取本地文件

[复制链接]
admin 发表于 4 天前 | 显示全部楼层 |阅读模式
1,定义工具

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

QQ|网站地图|Archiver|小黑屋|金黑网络 ( 粤ICP备2021124338号 )

网站建设,微信公众号小程序制作,商城系统开发,高端系统定制,app软件开发,智能物联网开发,直播带货系统等

Powered by Www.Jinhei.Cn

Copyright © 2013-2024 深圳市金黑网络技术有限公司 版权所有

快速回复 返回顶部 返回列表