Harness 与 Agent 工程 · MCP与框架接入 · 2026-04-22

AI实践|基于 Spring AI 从0到1构建 AI Agent

从零开始构建AI Agent?这篇文章用代码说话,带你深入Spring AI的实践世界。

核心内容:

  1. 基于Spring AI的AI Agent开发全流程解析
  2. RAG检索增强生成与Function Calling工具调用的实现细节
  3. 多模块架构设计:从AgentCore到Command & Skill系统

前言

Linux说过一句很经典的话:Talk is cheap, show me the code.

最近在学习AI Agent开发的时候,填鸭式地被灌输了很多新知识,但是这些新知识就像是漂浮的“空中楼阁”,看得见但摸不着,只知道理论如此但是不知道具体实现为何物。计算机工程的事儿,往往真的听再多毫无体感,看一遍代码就基本一通百通,由此产生一个很神奇的想法:“最好的学习资料是代码,既然我要学AI Agent开发,那就让AI Agent本身帮我生成学习资料。”于是乎,便有了这篇文章,即我本文的项目代码几乎是由AI生成,我在其中的角色只是指挥家与验收员。

开始之前先作一些声明:

1、该项目本身纯作为学习用途的Demo,只是用作展示“理论背后看得见的代码”。

2、Agent的理解较为宽泛,从整体概念层面是包含LLM的,一般Agent开发往往指的是Harness开发,但本文不做具体区分。

3、不深入每个概念的设计哲学,如Skill的渐进式披露,主要关注于实现层面。

4、Function Calling:LLM本身不会调工具,工具调用都是Harness做的;实际上Function Calling是大地基,很多复杂能力都是作为tool的形式包装给LLM的,例如Skill与SubAgent调用。

快速开始

本项目是一个基于Spring AI的AI Agent应用(纯Demo,仅学习用途),集成了 RAG 检索增强生成、Function Calling 工具调用、MCP 协议、SubAgent 子代理、Skill 技能系统等核心能力。本文将从六个核心模块出发,深入剖析其架构设计和实现细节。

代码仓库

github地址:https://github.com/q644266189/aiagentdemo

git clone git@github.com:q644266189/aiagentdemo.git

环境要求

核心模块

模块 说明
AgentCore 核心编排器,具备意图识别、记忆管理与大模型调用等能力。
ChatMemory 对话记忆管理,支持三层上下文压缩(摘要压缩 → Assistant 裁剪 → 滑动窗口)。
Tool(Function Calling) 可插拔的工具注册机制,通过 InnerTool 统一接口注册,LLM 自主决策调用
RAG 完整的检索增强生成流水线:文档加载 → 文档分块 → 向量化 → 向量存储 → 多路召回(语义 + BM25 + 查询改写)→ RRF 融合 → Rerank 重排 → LLM → 内容生成
Command & Skill 两种 Markdown 驱动的 Prompt 模板机制:Command 由用户主动调用,Skill 本质作为Tool由 LLM 决策调用。
SubAgent 拥有独立记忆的子代理,支持内部 SubAgent 和外部 IdeaLab Agent 两种形态
MCP 双向 MCP 支持:作为 Client 动态连接外部 MCP 服务,作为 Server 对外暴露服务

配置

编辑 src/main/resources/application.properties,配置大模型 API

spring.ai.openai.base-url=https://open.bigmodel.cn/api/paas/v4spring.ai.openai.api-key=你的API密钥spring.ai.openai.chat.options.model=glm-4spring.ai.openai.embedding.options.model=embedding-3

访问

前端页面

启动成功后,打开浏览器访问:

http://localhost:8080

项目内置了一个完整的 Web 聊天界面(src/main/resources/static/index.html),支持:

API 直接调用

## 非流式对话curl -X POST http://localhost:8080/api/chat \ -H "Content-Type: application/json" \ -d '{"message": "你好,介绍一下你的能力", "sessionId": "test-001"}'# 流式对话(SSE)curl -X POST http://localhost:8080/api/chat/stream \ -H "Content-Type: application/json" \

一、核心编排器:AgentCore

AgentCore 是整个系统的"大脑",负责编排对话的完整流程:意图识别 → RAG 注入 → 记忆管理 → 模型调用 → 工具执行。

1.1 对话流程

用户输入 │ ▼意图识别(IntentRecognizer) │ 判断:这是知识问答还是通用对话? ▼RAG 注入(RagService) │ 如果是知识问答,检索知识库,将参考资料拼入上下文 ▼记忆管理(ChatMemory) │ 自动摘要压缩 → 构建消息列表 ▼模型调用(ChatClient + ToolCallbacks) │ LLM 决策:直接回答 or 调用工具? │ 如果调用工具 → 执行工具 → 将结果返回 LLM → 继续决策(ReAct 循环) ▼返回最终回复

核心代码(AgentCore.chat()):

public String chat(String sessionId, String userInput) { ChatMemory memory = getOrCreateMemory(sessionId); // 1. 意图识别 Intent intent = intentRecognizer.recognize(userInput); // 2. 如果是 RAG 意图,先检索知识库并注入上下文 if (intent == Intent.RAG && ragService.isKnowledgeLoaded()) { String ragContext = ragService.query(userInput); if (ragContext != null && !ragContext.isBlank()) { String enrichedInput = "以下是从知识库中检索到的相关参考资料," + "请结合这些资料回答用户的问题:\n\n" + ragContext + "\n\n用户问题:" + userInput; memory.addMessage(new UserMessage(enrichedInput)); } else { memory.addMessage(new UserMessage(userInput)); } } else { memory.addMessage(new UserMessage(userInput)); } // 3. 构建 Prompt 并Loop调用大模型(getMessages 内部自动触发摘要压缩) List<Message> messages = memory.getMessages(); Prompt prompt = new Prompt(messages, buildChatOptions()); ChatClient.ChatClientRequestSpec requestSpec = chatClient.prompt(prompt); if (!toolCallbacks.isEmpty()) { requestSpec.toolCallbacks(toolCallbacks.toArray(new ToolCallback[0])); } String response = requestSpec.call().content(); memory.addMessage(new AssistantMessage(response != null ? response : "")); return response != null ? response : "";}

1.2 Agent Loop

Spring AI已实现Agent Loop。

具体路径为

org.springframework.ai.chat.client.advisor.ToolCallAdvisor#adviseCall

Agent Loop代码片段

boolean isToolCall = false;do { // Before Call var processedChatClientRequest = ChatClientRequest.builder() .prompt(new Prompt(instructions, optionsCopy)) .context(chatClientRequest.context()) .build(); // Next Call processedChatClientRequest = this.doBeforeCall(processedChatClientRequest, callAdvisorChain); chatClientResponse = callAdvisorChain.copy(this).nextCall(processedChatClientRequest); chatClientResponse = this.doAfterCall(chatClientResponse, callAdvisorChain); // After Call // TODO: check that this tool call detection is sufficient for all chat models // that support tool calls. (e.g. Anthropic and Bedrock are checking for // finish status as well) ChatResponse chatResponse = chatClientResponse.chatResponse(); isToolCall = chatResponse != null && chatResponse.hasToolCalls(); if (isToolCall) { Assert.notNull(chatResponse, "redundant check that should never fail, but here to help NullAway"); ToolExecutionResult toolExecutionResult = this.toolCallingManager .executeToolCalls(processedChatClientRequest.prompt(), chatResponse); if (toolExecutionResult.returnDirect()) { // Return tool execution result directly to the application client. chatClientResponse = chatClientResponse.mutate() .chatResponse(ChatResponse.builder() .from(chatResponse) .generations(ToolExecutionResult.buildGenerations(toolExecutionResult)) .build()) .build(); // Interrupt the tool calling loop and return the tool execution // result directly to the client application instead of returning // it to the LLM. break; } instructions = this.doGetNextInstructionsForToolCall(processedChatClientRequest, chatClientResponse, toolExecutionResult); }}while (isToolCall); // loop until no tool calls are present

1.3 意图识别

IntentRecognizer 通过 LLM 判断用户输入的意图,目前支持两种:

意图识别前置的好处是:避免每次对话都触发 RAG 检索,节省不必要的向量检索和 Rerank 开销。

1.4 对话记忆:ChatMemory

每个 sessionId 对应一个独立的 ChatMemory 实例,天然支持多客户端并发。

ChatMemory 设计了三层递进的上下文压缩策略,防止对话过长导致 token 溢出或成本失控:

第一层:摘要压缩(智能压缩)

当历史消息超过 16 条时,自动将较早的消息通过 LLM 总结为一段 300 字以内的摘要,注入到 system prompt 中。原消息从 history 中移除。

核心代码(ChatMemory.getMessages() 和 compressIfNeeded()):

public List<Message> getMessages() { // 在构建消息列表之前,自动尝试摘要压缩 compressIfNeeded(); List<Message> messages = new ArrayList<>(); // 将原始 system prompt 与摘要合并为一条 SystemMessage if (syst…
— 以上为试看内容(约 40%),开通会员后阅读全文 —

原文出处:https://www.53ai.com/news/RAG/2026042241978.html