案例:
- package com.jinhei;
-
- import com.fasterxml.jackson.databind.JsonNode;
- import com.fasterxml.jackson.databind.ObjectMapper;
-
- import java.io.FileWriter;
- import java.io.IOException;
-
- /**
- * 代理工具类 - 为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());
- }
- }
- }
复制代码 假设 jsonInput 是这样的JSON字符串:
- {
- "name": "张三",
- "age": 25,
- "address": {
- "city": "北京",
- "street": "长安街"
- }
- }
复制代码
执行 JsonNode rootNode = objectMapper.readTree(jsonInput); 后,会生成一个树形结构的 JsonNode 对象。
之后可以通过以下方式提取数据:
rootNode.get("name").asText() → "张三"
rootNode.get("age").asInt() → 25
rootNode.get("address").get("city").asText() → "北京"
就像把JSON解析成一个可遍历的对象树,方便后续提取任意字段。
|