You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LangChain的ChatOpenAI中添加JSON模式参数?

在LangChain的ChatOpenAI中配置OpenAI的JSON模式参数

可以在LangChain的ChatOpenAI中配置response_format参数,但不能通过metadata传入,正确方式是使用model_kwargs参数传递原生OpenAI API的配置项。

原因说明

LangChain的ChatOpenAI类里,metadata字段用于存储额外元数据,并非传递API请求参数的入口。而model_kwargs才是专门用来传递原生OpenAI API额外参数(如response_format、top_p等)的字段。

正确配置示例

from langchain_openai import ChatOpenAI

chat_model = ChatOpenAI(
    openai_api_key=OPENAI_KEY,
    temperature=temperature,
    model=model,
    model_kwargs={
        "response_format": {"type": "json_object"}
    }
)

补充提示

启用JSON模式后,模型会被限制生成可解析的JSON对象字符串,建议同时在系统提示词中明确要求输出JSON格式(比如添加"You are a helpful assistant designed to output JSON."),确保输出符合预期。

内容的提问来源于stack exchange,提问作者Aditya 47B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:23:14