langchain4j 指定格式返回
时间: 2025-05-10 12:26:35 浏览: 26
### 如何使用 LangChain4j 返回指定格式的结果
LangChain4j 是一种用于构建 Java 应用程序的语言模型框架,支持多种 API 和消息类型[^3]。通过该框架,开发者能够定义响应的格式并利用 `@Tool` 注解实现特定功能[^1]。
#### 使用 ResponseFormat 定义返回格式
为了使 LangChain4j 能够按照指定的 JSON Schema 格式返回结果,可以通过设置 `ResponseFormat` 来完成这一需求。以下是具体的操作方式:
1. **创建工具类**
需要在工具方法上添加 `@Tool` 注解,并为其提供必要的元数据。如果希望返回的数据遵循某种结构,则可以在注解中声明期望的 `responseFormat` 属性[^2]。
```java
import com.langchain4j.agent.tool.Tool;
public class MyTools {
@Tool(
name = "Get User Info",
description = "Fetches user information based on the provided ID.",
responseFormat = "{ 'userId': 'string', 'name': 'string', 'email': 'string' }"
)
public Map<String, String> getUserInfo(String userId) {
// Simulate fetching data from a database or external service.
return Map.of(
"userId", userId,
"name", "John Doe",
"email", "[email protected]"
);
}
}
```
2. **集成到 Agent 中**
创建一个代理实例并将上述工具注册进去。这样,在调用此工具时会自动验证其输出是否符合预设的 JSON Schema 结构。
```java
import com.langchain4j.agent.Agent;
import com.langchain4j.agent.chat.ChatAgentBuilder;
public class MainApp {
public static void main(String[] args) {
Agent agent = new ChatAgentBuilder()
.withTool(new MyTools())
.build();
System.out.println(agent.call("What is the info of user with id 123?"));
}
}
```
3. **处理 Void 方法的情况**
如果某些操作不需要实际返回值(即返回类型为 `void`),则可以根据约定发送固定的消息给 LLM 表明状态正常。例如,“Success”。
```java
import com.langchain4j.agent.tool.Tool;
public class LoggingTools {
@Tool(name = "Log Event", description = "Logs an event into the system.")
public void logEvent(String message) {
System.out.println(message);
// Automatically sends "Success" to indicate completion when no explicit value returned.
}
}
```
以上就是关于如何配置 LangChain4j 实现按需定制化返回结果的核心流程说明。
---
阅读全文
相关推荐


















