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

LangChain Agent获取柏林2024节假日列表仅返回单条数据问题排查

解决LangChain Agent仅返回单条柏林2024节假日数据的问题

核心原因

  • LLM未收到明确的返回完整列表指令,默认仅输出最后检索到的结果
  • StructuredOutputParser的格式提示不够严谨,未强制要求数组结构
  • SerpAPI调用后,LLM未对结果做完整整理就输出

具体修复步骤

1. 强化格式解析器的约束

明确让StructuredOutputParser要求返回字典列表,并给出清晰定义:

from langchain.output_parsers import StructuredOutputParser, ResponseSchema

response_schemas = [
    ResponseSchema(
        name="holidays", 
        description="柏林2024年所有节假日的完整列表,每个元素是包含'holiday'(节假日名称)和'date'(YYYY-MM-DD格式日期)的字典"
    ),
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions = output_parser.get_format_instructions()

2. 优化Agent的系统提示

在提示词中明确要求必须返回全部节假日,不能遗漏:

prompt = ChatPromptTemplate.from_messages([
    ("system", f"你需要获取柏林2024年的所有节假日及对应日期,严格按照以下格式返回完整列表:{format_instructions}"),
    ("human", "请获取柏林2024年的所有节假日及对应日期")
])

3. 调整Agent配置适配结构化输出

使用结构化聊天类型的Agent,同时开启中间步骤返回,便于排查工具调用是否完整:

agent = initialize_agent(
    tools=[serpapi_tool],
    llm=ChatOpenAI(temperature=0),
    agent_type="structured-chat-zero-shot-react-description",
    return_intermediate_steps=True,
    verbose=True
)

4. 添加输出格式校验

获取结果后校验是否为完整列表,避免格式错误:

result = agent.run(prompt.format_prompt().to_messages())
try:
    parsed_result = output_parser.parse(result)
    holidays_list = parsed_result.get("holidays", [])
    if isinstance(holidays_list, list) and len(holidays_list) > 1:
        print("完整节假日列表:", holidays_list)
    else:
        print("未获取到完整列表,请检查提示词或工具返回数据")
except Exception as e:
    print("格式解析错误:", e)

关键注意事项

  • 将LLM的temperature设为0,避免随机生成内容导致数据遗漏
  • 检查SerpAPI的搜索关键词,可改为"Berlin 2024 public holidays full list"确保工具返回完整数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:57:47