快速开始:5 分钟跑通第一个 Agent
从零开始,用最简单的代码创建你的第一个 Agent4J 程序。
快速开始:5 分钟跑通第一个 Agent
准备工作
在开始之前,你需要:
- Java 17 或更高版本:Agent4J 使用了 Java 17 的新特性
- Maven 或 Gradle:用来管理依赖
- 一个 LLM API Key:OpenAI、Anthropic 或任何 OpenAI 兼容的 API
如果你还没有 API Key,可以先用一些免费的额度,比如 OpenAI 新用户送的 $5,或者 DeepSeek 的免费额度。
添加依赖
Maven
<dependency>
<groupId>ink.icoding.llm</groupId>
<artifactId>agent4j</artifactId>
<version>2.1</version>
</dependency>
Gradle
implementation 'ink.icoding.llm:agent4j:2.1'
就是这么简单。没有其他依赖需要添加,Agent4J 会自动引入 Jackson 和 OkHttp。
第一个 Agent:Hello World
让我们从最简单的例子开始:
import ink.icoding.llm.agent.AgentClient;
import ink.icoding.llm.agent.AgentResultHandler;
import ink.icoding.llm.core.entity.ModelType;
import ink.icoding.llm.core.model.LLMModel;
public class HelloWorld {
public static void main(String[] args) {
// 1. 创建 LLM 模型
LLMModel llm = LLMModel.create(
ModelType.OpenAI,
"https://token-plan-cn.xiaomimimo.com",
"mimo-v-2.5-pro",
"your-api-key-here"
);
// 2. 创建 Agent
AgentClient agent = new AgentClient();
agent.setName("MyAgent");
agent.setDescription("一个简单的助手");
agent.setModel(llm);
// 3. 发送消息并处理响应
agent.createSession()
.command("你好,请用中文介绍一下你自己")
.then(new AgentResultHandler() {
public void onMessage(String msg) {
System.out.print(msg);
}
})
.error(e -> e.printStackTrace());
}
}
运行这段代码,你会看到 Agent 的自我介绍。
代码解析
让我一行一行解释:
第一步:创建 LLM 模型
LLMModel llm = LLMModel.create(
ModelType.OpenAI, // 模型类型
"https://token-plan-cn.xiaomimimo.com", // API 地址
"mimo-v-2.5-pro", // 模型名称
"your-api-key-here" // API Key
);
LLMModel 是 Agent4J 对 LLM 的抽象。它支持多种模型提供商:
ModelType.OpenAI:OpenAI 或任何 OpenAI 兼容的 APIModelType.Anthropic:Anthropic ClaudeModelType.OpenAIResponse:OpenAI Responses API
第二步:创建 Agent
AgentClient agent = new AgentClient();
agent.setName("MyAgent");
agent.setDescription("一个简单的助手");
agent.setModel(llm);
AgentClient 是 Agent 的核心类。你需要给它一个名字、一个描述(这个描述会告诉 LLM 它是什么角色),以及一个 LLM 模型。
第三步:发送消息
agent.createSession()
.command("你好,请用中文介绍一下你自己")
.then(new AgentResultHandler() {
public void onMessage(String msg) {
System.out.print(msg);
}
})
.error(e -> e.printStackTrace());
这里有几个概念:
createSession():创建一个会话。每个会话都有独立的对话历史.command():发送一条命令(用户消息).then():处理 Agent 的响应.error():处理可能的错误
AgentResultHandler 是一个回调接口,onMessage 方法会在 LLM 流式输出文本时被调用。
第二个 Agent:带工具的助手
一个只能聊天的 Agent 没什么意思。让我们给它加上工具,让它能读写文件:
import ink.icoding.llm.agent.AgentClient;
import ink.icoding.llm.agent.AgentResultHandler;
import ink.icoding.llm.agent.builtin.skill.BuiltInSkills;
import ink.icoding.llm.core.entity.ModelType;
import ink.icoding.llm.core.model.LLMModel;
public class FileAgent {
public static void main(String[] args) {
// 1. 创建 LLM 模型
LLMModel llm = LLMModel.create(
ModelType.OpenAI,
"https://token-plan-cn.xiaomimimo.com",
"mimo-v-2.5-pro",
"your-api-key-here"
);
// 2. 创建 Agent 并添加内置技能
AgentClient agent = new AgentClient();
agent.setName("FileHelper");
agent.setDescription("一个能读写文件的助手");
agent.setModel(llm);
// 添加所有内置技能
agent.getSkills().addAll(BuiltInSkills.all());
// 3. 让 Agent 帮你整理文件
agent.createSession()
.command("请列出当前目录下的所有文件,并告诉我有哪些是 Java 文件")
.then(new AgentResultHandler() {
public void onMessage(String msg) {
System.out.print(msg);
}
public void onTool(ToolDescriptor tool, ToolStatus status) {
System.out.println("[" + status + "] " + tool.getName());
}
})
.error(e -> e.printStackTrace());
}
}
新增的代码
agent.getSkills().addAll(BuiltInSkills.all());
这一行代码给 Agent 添加了所有内置技能:
- FileSystem:读写文件、搜索文件、浏览目录
- CommandExecution:执行 Shell 命令
- Orchestration:创建计划、生成子 Agent
有了这些技能,Agent 就能帮你做很多事情了。
新增的回调
public void onTool(ToolDescriptor tool, ToolStatus status) {
System.out.println("[" + status + "] " + tool.getName());
}
当 Agent 调用工具时,onTool 方法会被调用。ToolStatus 有三种状态:
PREPARING:准备调用工具CALLING:正在调用工具COMPLETED:工具调用完成
这让你能看到 Agent 的思考和执行过程。
第三个 Agent:流式响应
在实际应用中,你可能想要实时显示 Agent 的输出。Agent4J 支持 SSE(Server-Sent Events)流式响应:
agent.createSession()
.command("写一首关于编程的诗")
.then(new AgentResultHandler() {
public void onMessage(String msg) {
// 实时打印每个字符
System.out.print(msg);
}
public void onThink(String think) {
// LLM 的思考过程
System.out.println("\n[思考] " + think);
}
})
.error(e -> e.printStackTrace());
onThink 方法会接收到 LLM 的思考过程(如果模型支持的话)。这对于调试和理解 Agent 的决策很有帮助。
运行环境要求
- Java 17+:Agent4J 使用了 Java 17 的特性,如 text block、record 等
- 网络连接:需要访问 LLM API
- 文件权限:如果使用 FileSystem 技能,需要有相应的文件读写权限
常见问题
Q: 我可以用国产大模型吗?
可以!只要它支持 OpenAI 兼容的 API 格式。比如 DeepSeek、Qwen、GLM 等:
LLMModel llm = LLMModel.create(
ModelType.OpenAI,
"https://api.deepseek.com", // DeepSeek 的 API 地址
"deepseek-chat", // 模型名称
"sk-your-deepseek-key"
);
Q: 我可以同时使用多个模型吗?
可以!你可以创建多个 LLMModel 实例,然后给不同的 Agent 分配不同的模型:
LLMModel mimo = LLMModel.create(ModelType.OpenAI, "https://token-plan-cn.xiaomimimo.com", "mimo-v-2.5-pro", "your-api-key");
LLMModel claude = LLMModel.create(ModelType.Anthropic, "https://api.anthropic.com", "claude-sonnet-4", "sk-...");
AgentClient agent1 = new AgentClient();
agent1.setModel(mimo);
AgentClient agent2 = new AgentClient();
agent2.setModel(claude);
Q: 如何处理长时间运行的任务?
Agent4J 的工具调用默认有 60 秒超时。对于更长的任务,你可以:
- 使用
create_plan将任务拆分成多个步骤 - 使用
create_sub_agent将子任务分配给子 Agent
这些高级特性我会在后面的文章中详细介绍。
下一步
现在你已经成功创建了第一个 Agent!接下来,你可以:
如果你想直接看一个完整的实战案例,可以跳转到 实战案例:用 Agent4J 构建全栈项目。