使用 Agent
This content is not available in your language yet.
Feat AI 的 Agent 基于 ReAct(Reasoning + Acting)范式:模型先推理任务,再调用工具执行,根据结果继续推理,直到给出最终答案。本文说明如何创建 Agent、注册工具并执行任务。
- 创建一个可执行自然语言任务的 Agent
- 为 Agent 配置可用工具(如网页读取、搜索等)
- 执行一次任务并获取最终文本结果与状态
创建 Agent
Section titled “创建 Agent”通过 FeatAI.agent(opts -> ...) 得到的是基于 ReAct 的 FeatAgent 实现(当前为 ReActAgent)。在 opts 中至少要配置对话模型;若需调用网页、搜索等能力,需在此处注册相应工具。若直接使用 new ReActAgent() 无参构造,则会使用内置的默认工具集(如网页读取、搜索、文件操作)和默认模型。
import tech.smartboot.feat.ai.FeatAI;import tech.smartboot.feat.ai.agent.FeatAgent;
FeatAgent agent = FeatAI.agent(opts -> { opts.chatOptions().model(ChatModelVendor.GiteeAI.Qwen2_5_72B_Instruct); // 可选:opts.maxIterations(20);});若使用 Ollama,可配置 chatOptions().baseUrl(...).model(...),并确保本机已运行对应模型。
配置工具(可选)
Section titled “配置工具(可选)”Agent 通过 工具 与外界交互(读网页、搜资料、操作文件等)。在 AgentOptions 上注册实现 AgentTool 的工具即可:
FeatAgent agent = FeatAI.agent(opts -> { opts.chatOptions().model(...); opts.tool(new SearchTool()); // 搜索 opts.tool(new WebPageReaderTool()); // 读取网页 opts.tool(new FileOperationTool()); // 文件操作});Feat AI 内置部分工具(如 SearchTool、WebPageReaderTool),位于 tech.smartboot.feat.ai.agent.tools 包,可按需查阅源码与构造方式。自定义工具需实现 AgentTool 接口(名称、描述、参数、执行逻辑)。
FeatAgent#execute(String) 接收一句自然语言任务,返回 CompletableFuture<String>,结果为 Agent 给出的最终文本。可同步等待:
String result = agent.execute("从 https://smartboot.tech/smart-mqtt/ 中给我看看这款产品的定价是多少").get();System.out.println("最终结果:\n" + result);System.out.println("Agent 状态: " + agent.getState());执行过程中 Agent 会多次调用模型与工具,直到满足结束条件或达到 maxIterations。
完整示例(基于 feat-ai 测试)
Section titled “完整示例(基于 feat-ai 测试)”下面示例基于 feat-ai 模块的 ReActAgentTest,演示创建 Agent、执行任务并打印结果与状态(JDK 8 可运行):
import tech.smartboot.feat.ai.FeatAI;import tech.smartboot.feat.ai.agent.FeatAgent;import tech.smartboot.feat.ai.chat.ChatModelVendor;
import java.util.concurrent.ExecutionException;
public class AgentDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { FeatAgent agent = FeatAI.agent(opts -> { opts.chatOptions().model(ChatModelVendor.GiteeAI.Qwen2_5_72B_Instruct); opts.tool(new tech.smartboot.feat.ai.agent.tools.WebPageReaderTool()); });
String result = agent.execute( "从 https://smartboot.tech/smart-mqtt/ 中给我看看这款产品的定价是多少" ).get();
System.out.println("\n最终结果:\n" + result); System.out.println("\nAgent 最终状态: " + agent.getState()); }}| 配置 | 方法 | 说明 |
|---|---|---|
| 对话模型 | chatOptions() | 配置模型、baseUrl、API Key 等,与 对话与流式 一致 |
| 最大迭代 | maxIterations(int) | 限制推理+工具调用轮数,默认 20 |
| 工具 | tool(AgentTool) | 注册一个工具,可多次调用注册多个 |
| 提示词 | prompt(String) 或 prompt(Prompt) | 自定义 Agent 的系统提示/行为模板 |
| 钩子 | hook(Hook) | 在执行过程的关键节点插入自定义逻辑 |
- API Key:使用 Gitee AI 时必须设置
FEAT_AI_API_KEY。 - 超时与异常:
execute(...).get()会阻塞直到完成或异常;生产环境建议使用get(timeout, unit)或thenAccept等异步方式。 - 工具依赖:部分内置工具可能依赖外部服务(如搜索、网页抓取),需网络或额外配置;自定义工具需保证线程安全与异常处理。
- 迭代上限:复杂任务可能触及
maxIterations,可根据需要调大或优化提示词/工具设计。
- Feat AI 简介:ReAct 与能力概览
- 开始使用 Feat AI:依赖与对话模型配置
- 对话与流式:
ChatOptions详细用法 - 项目内:
feat-ai模块agent包下的ReActAgentTest、AgentTool、内置 tools