Appearance
LangChain with_structured_output 在 DeepSeek API 上报错 json_schema unavailable
问题
在 LangChain 中使用 ChatOpenAI() 配合 DeepSeek V3,调用 .with_structured_output(MyModel) 时报错:
response_format type 'json_schema' is unavailable for model 'deepseek-chat'根因
LangChain 的 with_structured_output() 默认使用 response_format: { type: "json_schema" } 来约束输出,而 DeepSeek API 尚不支持 json_schema 类型,只支持 json_object。
解决方案
方法一:指定 method="json_mode"(推荐)
python
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
class MyOutput(BaseModel):
name: str
score: int
llm = ChatOpenAI(
model="deepseek-chat",
openai_api_key="your-deepseek-key",
openai_api_base="https://api.deepseek.com/v1"
)
structured_llm = llm.with_structured_output(MyOutput, method="json_mode")
result = structured_llm.invoke("给我一个示例")方法二:在 system prompt 中强制指定 JSON 格式
python
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "请以 JSON 格式回复,包含字段: name(string), score(int)"),
("user", "{input}")
])
chain = prompt | llm
result = chain.invoke({"input": "给我一个示例"})对比:OpenAI 的
gpt-4o支持json_schema,DeepSeek 目前只到json_object级别。前者可以严格约束输出字段,后者需要依赖 prompt 引导。