带泪的微笑 發表於 2026-3-26 10:42:00

AI Agent 开发实战:用LangChain4j构建你的第一个Java智能体

<h2>前言</h2>
<p>AI Agent是2026年最热门的技术方向之一。本文用LangChain4j带你从零开始构建一个Java智能体,实现对话、工具调用和记忆功能。</p>
<h2>一、什么是AI Agent?</h2>
<p>AI Agent(智能体)是能够自主决策并执行任务的AI系统,核心能力:</p>
<ul>
<li><strong>理解意图</strong>:解析用户自然语言</li>
<li><strong>规划任务</strong>:分解复杂任务为步骤</li>
<li><strong>调用工具</strong>:使用外部API或函数</li>
<li><strong>记忆上下文</strong>:维护对话历史</li>
</ul>
<h2>二、环境准备</h2>
<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;
    &lt;artifactId&gt;langchain4j&lt;/artifactId&gt;
    &lt;version&gt;0.35.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;
    &lt;artifactId&gt;langchain4j-open-ai&lt;/artifactId&gt;
    &lt;version&gt;0.35.0&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
<h2>三、基础对话Agent</h2>
<pre><code>import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.UserMessage;

// 定义Agent接口
public interface ChatAgent {
    @UserMessage("{{it}}")
    String chat(String message);
}

// 创建Agent实例
ChatLanguageModel model = OpenAiChatModel.builder()
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .modelName("gpt-4")
    .build();

ChatAgent agent = AiServices.builder(ChatAgent.class)
    .chatLanguageModel(model)
    .build();

// 使用
String response = agent.chat("你好,请介绍一下Java线程池");
System.out.println(response);</code></pre>
<h2>四、带工具的Agent</h2>
<pre><code>import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.service.MemoryId;
import dev.langchain4j.service.UserMessage;

public interface ToolAgent {
    @UserMessage("{{it}}")
    String chat(@MemoryId String sessionId, String message);
}

// 定义工具类
public class WeatherTools {
   
    @Tool("获取指定城市的天气信息")
    public String getWeather(String city) {
      // 实际调用天气API
      return city + "今天晴,25°C";
    }
   
    @Tool("获取当前时间")
    public String getCurrentTime() {
      return LocalDateTime.now().toString();
    }
}

// 创建带工具的Agent
ToolAgent agent = AiServices.builder(ToolAgent.class)
    .chatLanguageModel(model)
    .tools(new WeatherTools())
    .chatMemoryProvider(memoryId -&gt; MessageWindowChatMemory.withMaxMessages(10))
    .build();

// Agent会自动判断何时调用工具
String response = agent.chat("session-1", "北京今天天气怎么样?");</code></pre>
<h2>五、带记忆的Agent</h2>
<pre><code>import dev.langchain4j.memory.chat.MessageWindowChatMemory;

// 为每个用户会话创建独立记忆
ChatMemory chatMemory = MessageWindowChatMemory.withMaxMessages(20);

ChatAgent agent = AiServices.builder(ChatAgent.class)
    .chatLanguageModel(model)
    .chatMemory(chatMemory)
    .build();

// 多轮对话保持上下文
agent.chat("我叫张三");// 记住名字
agent.chat("我叫什么?"); // 回答:你叫张三</code></pre>
<h2>六、流式输出</h2>
<pre><code>import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;

StreamingChatLanguageModel streamingModel = OpenAiStreamingChatModel.builder()
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .build();

// 实时输出,类似ChatGPT的效果
streamingModel.generate("写一首关于Java的诗", new StreamingResponseHandler() {
    @Override
    public void onNext(String token) {
      System.out.print(token);// 逐字输出
    }
   
    @Override
    public void onComplete(Response response) {
      System.out.println("\n输出完成");
    }
});</code></pre>
<h2>七、完整实战案例</h2>
<pre><code>@SpringBootApplication
public class AgentApplication {
   
    @Bean
    public ChatLanguageModel chatLanguageModel() {
      return OpenAiChatModel.builder()
            .apiKey("${openai.api-key}")
            .modelName("gpt-4")
            .build();
    }
   
    @Bean
    public Assistant assistant(ChatLanguageModel model) {
      return AiServices.builder(Assistant.class)
            .chatLanguageModel(model)
            .tools(new Calculator(), new WeatherService())
            .chatMemoryProvider(id -&gt; MessageWindowChatMemory.withMaxMessages(10))
            .build();
    }
}

@RestController
public class ChatController {
   
    @Autowired
    private Assistant assistant;
   
    @PostMapping("/chat")
    public String chat(@RequestBody ChatRequest request) {
      return assistant.chat(request.getSessionId(), request.getMessage());
    }
}</code></pre>
<h2>总结</h2>
<p>LangChain4j让Java开发者也能轻松构建AI Agent。核心步骤:</p>
<ol>
<li>定义Agent接口</li>
<li>配置语言模型</li>
<li>添加工具(可选)</li>
<li>配置记忆(可选)</li>
<li>构建并使用</li>
</ol>
<p>AI Agent正在改变软件开发方式,现在就开始构建你的第一个智能体吧!</p>
<p><em>本文由AI辅助创作。</em></p>

</div>
<div id="MySignature" role="contentinfo">
   

---

📌 **如果觉得文章对你有帮助,欢迎点赞👍收藏⭐!**

💬 有问题或建议?欢迎在评论区留言讨论~

🔗 更多技术干货请关注作者:弥烟袅绕

📚 本文地址:https://www.cnblogs.com/czlws/p/19774612<br><br>
来源:https://www.cnblogs.com/czlws/p/19774612
頁: [1]
查看完整版本: AI Agent 开发实战:用LangChain4j构建你的第一个Java智能体