蘭得糊塗 發表於 2026-3-30 09:37:00

使用Spring AI Alibaba构建智能体Agent

<h2 id="前言">前言</h2>
<p>随着大语言模型(LLM)技术的快速发展,构建智能Agent应用变得越来越简单。本文将通过两个实际的代码示例,展示如何使用Spring AI Alibaba框架构建功能丰富的天气查询Agent,从基础的测试实现到生产级的完整应用。</p>
<h2 id="技术栈概述">技术栈概述</h2>
<ul>
<li><strong>Spring AI Alibaba</strong>: 阿里巴巴开源的AI应用开发框架</li>
<li><strong>DashScope</strong>: 阿里云的AI模型服务平台</li>
<li><strong>React Agent</strong>: 基于ReAct(Reasoning and Acting)范式的智能代理</li>
</ul>
<h2 id="示例一simpletest---快速入门">示例一:SimpleTest - 快速入门</h2>
<h3 id="添加核心依赖">添加核心依赖</h3>
<pre><code class="language-pom">&lt;dependencies&gt;
      &lt;!-- Spring AI Alibaba Agent Framework --&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;com.alibaba.cloud.ai&lt;/groupId&gt;
          &lt;artifactId&gt;spring-ai-alibaba-agent-framework&lt;/artifactId&gt;
          &lt;version&gt;1.1.2.0&lt;/version&gt;
      &lt;/dependency&gt;

      &lt;!-- DashScope ChatModel 支持(如果使用其他模型,请跳转 Spring AI 文档选择对应的 starter) --&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;com.alibaba.cloud.ai&lt;/groupId&gt;
          &lt;artifactId&gt;spring-ai-alibaba-starter-dashscope&lt;/artifactId&gt;
          &lt;version&gt;1.1.2.0&lt;/version&gt;
      &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<h3 id="代码结构分析">代码结构分析</h3>
<pre><code class="language-java">@Test
void agentTest() throws GraphRunnerException {
    // 1. 初始化 DashScope API
    DashScopeApi dashScopeApi = DashScopeApi.builder()
            .apiKey(System.getenv("AliQwen_API"))
            .build();

    // 2. 创建 ChatModel
    ChatModel chatModel = DashScopeChatModel.builder()
            .dashScopeApi(dashScopeApi)
            .build();

    // 3. 定义天气工具
    ToolCallback weatherTool = FunctionToolCallback.builder("get_weather", new WeatherTool())
            .description("获取某个城市的天气")
            .inputType(String.class)
            .build();

    // 4. 构建React Agent
    ReactAgent agent = ReactAgent.builder()
            .name("weather_agent")
            .model(chatModel)
            .tools(weatherTool)
            .systemPrompt("你是一个非常有帮助的助手")
            .saver(new MemorySaver())
            .build();

    // 5. 调用Agent
    AssistantMessage response = agent.call("上海今天天气怎么样?");
    System.out.println(response.getText());
}
</code></pre>
<h3 id="核心特性">核心特性</h3>
<ol>
<li><strong>简洁的配置</strong>: 通过Builder模式快速构建Agent</li>
<li><strong>工具集成</strong>: 使用<code>FunctionToolCallback</code>将自定义函数包装为Agent可调用的工具</li>
<li><strong>内存存储</strong>: 使用<code>MemorySaver</code>保存对话历史</li>
<li><strong>中文支持</strong>: 完整的中文提示词和工具描述</li>
</ol>
<h3 id="自定义工具实现">自定义工具实现</h3>
<pre><code class="language-java">class WeatherTool implements BiFunction&lt;String, ToolContext, String&gt; {
    @Override
    public String apply(String city, ToolContext toolContext) {
      return city + "今天天气非常好!";
    }
}
</code></pre>
<p>这个简单的工具类展示了如何将业务逻辑封装为Agent可调用的函数。</p>
<h2 id="示例二realagent---真实的智能体">示例二:RealAgent - 真实的智能体</h2>
<h3 id="高级特性概览">高级特性概览</h3>
<p>相比SimpleTest,RealAgent展示了更多生产级特性:</p>
<ol>
<li><strong>精细的模型配置</strong></li>
<li><strong>多工具协同</strong></li>
<li><strong>结构化输出</strong></li>
<li><strong>对话上下文管理</strong></li>
</ol>
<h3 id="核心代码解析">核心代码解析</h3>
<h4 id="1-系统提示词设计">1. 系统提示词设计</h4>
<pre><code class="language-java">String SYSTEM_PROMPT = """
      你是一位擅长说**天气冷笑话/谐音梗**的专业天气预报员。
                  
      你可以使用两个工具:
                  
      - **get_weather_for_location**:用于获取指定地点的天气
      - **get_user_location**:用于获取用户当前所在位置
                  
      如果用户询问天气,**必须先确认地点**。
      如果从问题中能判断出他们指的是**自己所在的地方**,
      就使用 **get_user_location** 工具获取他们的位置。
      """;
</code></pre>
<p>这个提示词体现了几个重要设计原则:</p>
<ul>
<li><strong>角色定位</strong>: 明确Agent的身份和特色</li>
<li><strong>工具说明</strong>: 清晰描述可用工具的功能</li>
<li><strong>行为约束</strong>: 规定了工具使用的逻辑顺序</li>
</ul>
<h4 id="2-模型参数优化">2. 模型参数优化</h4>
<pre><code class="language-java">ChatModel chatModel = DashScopeChatModel.builder()
      .dashScopeApi(dashScopeApi)
      .defaultOptions(DashScopeChatOptions.builder()
                .model(DashScopeChatModel.DEFAULT_MODEL_NAME)
                .temperature(0.5)      // 平衡创造性和准确性
                .maxToken(1000)      // 控制响应长度
                .build())
      .build();
</code></pre>
<h4 id="3-多工具协同">3. 多工具协同</h4>
<pre><code class="language-java">// 天气查询工具
ToolCallback getWeatherTool = FunctionToolCallback
      .builder("getWeatherForLocation", new WeatherForLocationTool())
      .description("获取一个给定城市的天气")
      .inputType(String.class)
      .build();

// 用户定位工具
ToolCallback getUserLocationTool = FunctionToolCallback
      .builder("getUserLocation", new UserLocationTool())
      .description("根据User Id获取用户位置")
      .inputType(String.class)
      .build();
</code></pre>
<h4 id="4-结构化输出配置">4. 结构化输出配置</h4>
<pre><code class="language-java">ReactAgent agent = ReactAgent.builder()
      // ... 其他配置
      .outputType(ResponseFormat.class)// 指定输出格式
      .hooks(humanInTheLoopHook)
      .build();
</code></pre>
<h4 id="5-对话上下文管理">5. 对话上下文管理</h4>
<pre><code class="language-java">RunnableConfig runnableConfig = RunnableConfig.builder()
      .threadId(Thread.currentThread().getId() + "")
      .build();

// 第一次调用
AssistantMessage response1 = agent.call("上海今天天气怎么样", runnableConfig);

// 第二次调用(保持上下文)
AssistantMessage response2 = agent.call("明天天气怎么样", runnableConfig);
</code></pre>
<p>通过<code>RunnableConfig</code>的<code>threadId</code>实现多轮对话的上下文保持。</p>
<h2 id="总结">总结</h2>
<p>通过这两个示例,我们可以看到Spring AI Alibaba框架在构建智能Agent应用方面的强大能力:</p>
<ul>
<li><strong>SimpleTest</strong>展示了快速原型开发的能力,适合概念验证和学习</li>
<li><strong>RealAgent</strong>则创建了一个基础的 ReactAgent,接下来可以:
<ul>
<li>探索更多的工具集成</li>
<li>学习如何使用不同的 Checkpoint 实现对话持久化</li>
<li>了解如何使用 Hooks 扩展 agent 功能</li>
<li>学习如何创建多 agent 系统</li>
</ul>
</li>
</ul>
<h2 id="参考资料">参考资料</h2>
<ul>
<li>Spring AI Alibaba官方文档</li>
<li>DashScope平台</li>
</ul><br><br>
来源:https://www.cnblogs.com/jucunqi/p/19793611
頁: [1]
查看完整版本: 使用Spring AI Alibaba构建智能体Agent