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

使用LangChain调用GPT-OSS模型时结构化输出无效问题求助

问题:结构化输出验证失败(模型返回非JSON内容)

我用LangChain结合Hyperbolic提供的GPT-OSS模型做答案评估,要求模型返回符合<EvalResult> Pydantic schema的JSON对象(包含4个整数字段),但模型经常返回<think>这类非JSON内容,触发以下验证错误:

Invalid JSON: expected value at line 1 column 1 [type=json_invalid, input_value='<think>We need to evalua...']

当前实现代码

模型定义

gpt_oss_120b_hb = ChatOpenAI(
model="openai/gpt-oss-120b",
openai_api_key=HYPERBOLIC_API_KEY,
base_url="https://api.hyperbolic.xyz/v1",
temperature=1,
model_kwargs={"top_p": 1, "max_completion_tokens": 256},)

eval_model_structured = gpt_oss_120b_hb.with_structured_output(EvalResult)

提示词

evaluation_prompt = ChatPromptTemplate.from_messages([
(
    "system",
    "You are a trained evaluator. Respond ONLY with a valid JSON object matching this format, and do not include any other text:\n"
),
(
    "user",
    "Evaluate the following response.\n\nQuestion:\n{question}\n\nAnswer:\n{answer}\n\n"
),])

链结构

eval_chain = evaluation_prompt | eval_model_structured

解决方法

  • 强化提示词约束
    明确禁止模型生成<think>标签或解释性文本,同时加入格式示例,让模型更清晰要求:

    evaluation_prompt = ChatPromptTemplate.from_messages([
    (
        "system",
        "你是专业评估员,**仅返回符合<EvalResult>格式的JSON对象**,禁止生成<think>标签、解释性文字或任何额外内容。示例输出:\n{\"field1\": 1, \"field2\": 0, \"field3\": 5, \"field4\": 3}"
    ),
    (
        "user",
        "Evaluate the following response.\n\nQuestion:\n{question}\n\nAnswer:\n{answer}\n\n"
    ),])
    
  • 降低随机性参数
    当前temperature=1和top_p=1会让模型输出随机性过高,调整为低随机性参数,减少额外内容生成:

    gpt_oss_120b_hb = ChatOpenAI(
    model="openai/gpt-oss-120b",
    openai_api_key=HYPERBOLIC_API_KEY,
    base_url="https://api.hyperbolic.xyz/v1",
    temperature=0.1,  # 降低随机性
    model_kwargs={"top_p": 0.3, "max_completion_tokens": 256},)
    
  • 添加输出后处理逻辑
    在链中加入清洗步骤,过滤掉非JSON内容,只提取有效JSON部分:

    import re
    from langchain.schema.output_parser import StrOutputParser
    
    def extract_json(output):
        # 匹配JSON对象
        json_match = re.search(r'\{.*\}', output, re.DOTALL)
        if json_match:
            return json_match.group()
        return output
    
    # 修改链结构,加入后处理
    eval_chain = evaluation_prompt | eval_model_structured | StrOutputParser() | extract_json
    
  • 强制结构化输出参数
    尝试在model_kwargs中添加response_format参数,强制模型返回JSON:

    gpt_oss_120b_hb = ChatOpenAI(
    model="openai/gpt-oss-120b",
    openai_api_key=HYPERBOLIC_API_KEY,
    base_url="https://api.hyperbolic.xyz/v1",
    temperature=0.1,
    model_kwargs={
        "top_p": 0.3, 
        "max_completion_tokens": 256,
        "response_format": {"type": "json_object"}  # 强制JSON输出
    },)
    

内容的提问来源于stack exchange,提问作者Sankalp Dhupar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 13:12:38