1,注解
1.1方法注解
- package com.jinhei;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- /**
- * 工具方法注解
- * 用于标识一个方法为 AI 工具, 使其能够被 AI 助手调用
- */
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface Tool {
- /**
- * 工具方法的描述信息
- * 用于向 AI 助手说明该方法的功能
- * @return 方法的描述
- */
- String description();
- }
复制代码 1.2 参数注解
- package com.jinhei;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- /**
- * 工具参数注解
- * 用于标识工具的方法的参数, 提供参数的描述信息
- * 帮助 AI 助手理解每个参数的用途
- */
- @Target(ElementType.PARAMETER)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface ToolParam {
- /**
- * 参数的描述信息
- * 用于向 AI 助手说明该参数的含义和用途
- * @return 参数的描述
- */
- String description();
-
- }
复制代码 1.3 使用
- 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());
- }
- }
- }
复制代码
学习点:把json字符串解析成树形结构, 方便提取数据
https://www.jinhei.cn/thread-382-1-1.html
invoke()使用
https://www.jinhei.cn/thread-383-1-1.html
|