如何在最新版langchain4j中使用OpenAI Structured Outputs?
LangChain4J 支持 OpenAI Structured Outputs 及自定义参数设置方法
最新版 LangChain4J 已经支持 OpenAI 推出的 Structured Outputs 功能,完全可以通过配置 response_format 参数来获取可信的 JSON 格式响应,以下是具体实现方式:
1. 快速开启 JSON 结构化输出
如果只需要基础的 JSON 格式响应,可以直接使用 LangChain4J 内置的配置:
OpenAiChatModel model = OpenAiChatModel.builder() .apiKey("YOUR_API_KEY") .modelName("gpt-4o") // 需要使用支持 Structured Outputs 的模型版本,如 gpt-4o、gpt-4-turbo-2024-04-09 等 .responseFormat(ResponseFormat.jsonObject()) .build(); // 调用模型获取结构化响应 AiMessage response = model.generate("请列出3种常见的编程语言及其特点,以JSON格式返回");
2. 自定义 response_format 参数(含 Schema 指定)
如果需要更精准的结构控制(比如指定自定义 JSON Schema),可以通过 customizer 直接向 API 请求添加参数:
OpenAiChatModel model = OpenAiChatModel.builder() .apiKey("YOUR_API_KEY") .modelName("gpt-4o") .customizer(request -> { // 构造自定义的 response_format 参数,包含指定的 schema Map<String, Object> responseFormat = new HashMap<>(); responseFormat.put("type", "json_schema"); responseFormat.put("json_schema", Map.of( "name", "ProgrammingLanguageList", "schema", Map.of( "type", "object", "properties", Map.of( "languages", Map.of( "type", "array", "items", Map.of( "type", "object", "properties", Map.of( "name", Map.of("type", "string"), "feature", Map.of("type", "string") ), "required", List.of("name", "feature") ) ) ), "required", List.of("languages") ), "strict", true // 开启严格模式,确保输出完全符合 schema )); request.setResponseFormat(responseFormat); return request; }) .build();
注意事项
- 必须使用支持 Structured Outputs 的 OpenAI 模型版本,旧版本模型(如 gpt-3.5-turbo-16k)不兼容此功能。
- 开启
strict: true时,模型会严格遵循指定的 Schema 输出,若无法生成符合要求的内容会返回错误。
内容的提问来源于stack exchange,提问作者Rob Brown
相关产品推荐
相关产品推荐

