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

使用Llama Index对比Uber与Lyft风险因子时遇SubQuestionList验证错误

解决SubQuestionQueryEngine的JSON解析失败问题

1. 强制Azure OpenAI输出严格JSON格式

Azure OpenAI偶尔会输出额外解释性文本,破坏JSON结构。初始化LLM时需明确指定JSON输出格式,并将temperature设为0降低随机性:

from llama_index.llms.azure_openai import AzureOpenAI

llm = AzureOpenAI(
    engine="你的部署名称",
    temperature=0.0,
    model_kwargs={"response_format": {"type": "json_object"}}
)

2. 自定义子问题生成Prompt模板

默认模板对Azure OpenAI的适配性不足,修改prompt明确要求仅输出符合规范的JSON数组:

from llama_index.query_engine.sub_question_query_engine import SubQuestionGenerator
from llama_index.prompts import PromptTemplate

sub_question_prompt = PromptTemplate(
    """
    给定原始问题,生成一组用于回答该问题的子问题,每个子问题对应一个特定数据源。
    仅输出JSON格式的子问题数组,无任何额外文本。
    示例输出:
    [
        {"sub_question": "Uber的风险因子有哪些?", "tool_name": "uber_engine"},
        {"sub_question": "Lyft的风险因子有哪些?", "tool_name": "lyft_engine"}
    ]
    原始问题:{question}
    数据源:{tools}
    """
)

sub_q_generator = SubQuestionGenerator.from_defaults(
    llm=llm,
    prompt=sub_question_prompt
)

sub_query_engine = SubQuestionQueryEngine.from_defaults(
    query_engine_tools=[uber_tool, lyft_tool],
    sub_question_generator=sub_q_generator,
    llm=llm
)

3. 添加JSON解析容错逻辑

若LLM仍偶尔输出不符合格式的内容,可通过正则提取响应中的JSON部分,避免解析失败:

import re
import json
from typing import List
from llama_index.query_engine.sub_question_query_engine import SubQuestionGenerator, SubQuestion
from llama_index.tools.query_engine import QueryEngineTool

class CustomSubQuestionGenerator(SubQuestionGenerator):
    def generate_sub_questions(self, question: str, tools: List[QueryEngineTool]) -> List[SubQuestion]:
        response = self._llm.predict(self.prompt, question=question, tools=tools)
        # 提取响应中的JSON数组部分
        json_match = re.search(r"\[.*\]", response, re.DOTALL)
        if not json_match:
            raise ValueError("LLM响应中未找到有效JSON")
        clean_json = json_match.group(0)
        # 解析并转换为SubQuestion对象
        sub_question_dicts = json.loads(clean_json)
        return [SubQuestion(**sq) for sq in sub_question_dicts]

# 使用自定义生成器初始化查询引擎
sub_q_generator = CustomSubQuestionGenerator.from_defaults(llm=llm, prompt=sub_question_prompt)
sub_query_engine = SubQuestionQueryEngine.from_defaults(
    query_engine_tools=[uber_tool, lyft_tool],
    sub_question_generator=sub_q_generator,
    llm=llm
)

4. 检查Azure OpenAI模型版本

确保使用gpt-3.5-turbo-1106、gpt-4-1106-preview这类原生支持JSON格式输出的新版本模型,旧版本对JSON格式的稳定性支持较差。


内容的提问来源于stack exchange,提问作者Stetco Oana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:41:09