LangChain4j框架

概述

LangChain4j 是流行的LangChain库的Java实现,专为构建基于大语言模型(LLM)的应用程序而设计。

核心概念

  • AI Services(AI服务):应用程序的主要入口点,将接口转换为由LLM驱动的服务
  • Tools(工具):可以被LLM调用的方法,扩展其能力(如我们看到的天气工具)
  • Memory(记忆):存储对话历史记录以支持连续对话
  • Chat Models(聊天模型):与各种LLM提供商(如OpenAI、Anthropic等)交互

使用

依赖

<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-spring-boot-starter</artifactId>
    <version>0.25.0</version>
</dependency>

<!-- 如果需要使用特定模型,还需要添加相应依赖 -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
    <version>0.25.0</version>
</dependency>

配置文件设置:

langchain4j.open-ai.chat-model.api-key=YOUR_API_KEY
langchain4j.open-ai.chat-model.model-name=gpt-3.5-turbo
langchain4j.open-ai.chat-model.temperature=0.7

创建AI Service接口

import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.spring.AiService;

@AiService
public interface Assistant {
    
    @SystemMessage("你是一个乐于助人的助手")
    String chat(@UserMessage String userMessage);
}

 定义工具类

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.stereotype.Component;

@Component
public class WeatherTools {
    
    @Tool(name = "getWeather", value = "返回给定城市的天气预报")
    public String getWeather(@P("应返回天气预报的城市") String city) {
        // 实际项目中这里应该调用真实的天气API
        return String.format("%s 的天气是晴天", city);
    }
}

在Controller中使用

import org.springframework.web.bind.annotation.*;
import dev.langchain4j.memory.chat.MessageHistoryChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;

@RestController
@RequestMapping("/assistant")
public class AssistantController {
    
    private final Assistant assistant;
    
    public AssistantController(Assistant assistant) {
        this.assistant = assistant;
    }
    
    @PostMapping("/chat")
    public String chat(@RequestParam String message) {
        return assistant.chat(message);
    }
}

 

为了保持对话上下文,可以添加内存支持:

import dev.langchain4j.memory.chat.MessageHistoryChatMemory;
import dev.langchain4j.service.MemoryId;

@AiService
public interface ChatAssistant {
    String chat(@MemoryId String sessionId, @UserMessage String userMessage);
}
@Configuration
public class AiConfig {
    
    @Bean
    public ChatMemory chatMemory() {
        return MessageHistoryChatMemory.withMaxMessages(10);
    }
}

 

注解说明

@Tool 注解

@Tool 注解用于将方法标记为AI代理可以执行的工具。主要特点:
用途:将方法注册为可被LLM代理调用的工具
参数:
name:指定呈现给LLM的工具名称
value:提供工具功能的描述,帮助LLM理解何时使用该工具

@P 注解

@P 注解用于描述工具方法的参数:
用途:为工具方法的参数提供描述性信息
作用:当LLM决定调用某个工具时,这些描述帮助LLM理解每个参数的含义和用途

内部原理

框架会在Spring容器中查找所有带有@Tool注解的bean,并将它们注册为可用工具。

注册后,框架会构造工具描述信息发送给LLM:

{
  "name": "getWeather",
  "description": "返回给定城市的天气预报",
  "parameters": {
    "type": "object",
    "properties": {
      "city": {
        "type": "string",
        "description": "应返回天气预报的城市"
      }
    },
    "required": ["city"]
  }
}

当用户提供消息时,例如:"北京的天气怎么样?",LLM会:

  • 分析用户消息的内容
  • 根据工具描述判断哪个工具最适合解决问题
  • 提取必要的参数值(如从消息中提取"北京"作为城市名)
  • 构造函数调用请求:
{
  "name": "getWeather",
  "arguments": {
    "city": "北京"
  }
}

框架接收到LLM的函数调用请求后:

  • 根据方法名匹配到具体的Java方法
  • 解析参数值(这里是"city"="北京")
  • 使用反射机制调用对应的方法
// 内部大致实现逻辑
Method method = findMethodByName("getWeather");
Object[] args = parseArguments(method, argumentsFromLLM);
Object result = method.invoke(weatherToolsInstance, args);

执行完工具方法后,框架会:

  • 获取方法执行结果
  • 将结果包装后返回给LLM
  • LLM结合工具执行结果和原始问题生成自然语言回答

其他

会调用多个工具吗

LangChain4j框架支持调用多个工具并整合结果

posted @ 2025-11-25 10:38  星光闪闪  阅读(17)  评论(0)    收藏  举报