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

使用LangChain-OpenAI的file_search工具时出现AttributeError报错求助

问题排查:langchain-openai file_search工具触发AttributeError

报错信息

File "/backend/.venv/lib/python3.11/site-packages/langchain_openai/chat_models/base.py", line 3386, in _convert_responses_chunk_to_generation_chunk
    chunk.annotation.model_dump(exclude_none=True, mode="json")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'model_dump'

场景说明:未使用file_search工具时代码运行正常,添加该工具后触发上述错误。

相关代码

响应生成逻辑

prompt = chat_prompt
vectore_store_id = "vs_68341b563aac8191af2df101ef7066a6"

fileTool = {"type": "file_search", "vector_store_ids": [vectore_store_id]}

llm_with_tools =  self.llm.bind_tools([fileTool])

chain = prompt | llm_with_tools
output = ""
async for chunk in chain.astream(
    {
        "query": query,
        "question": question,
        "context": query_context,
        "history": log,
    },
):
    try:
        print(chunk.type)
        output += chunk.text()
        yield AIMessageChunk(content=chunk.text())
    except Exception:
        print("Err")

chat_prompt定义

@property
def chat_prompt(self):
    current_date = datetime.now().strftime("%B %d, %Y at %I:%M %p")

    messages = [
        SystemMessagePromptTemplate.from_template(
            "You are top mortgage subject matter expert working.\n"
        ),
        HumanMessagePromptTemplate.from_template("{query}"),
    ]

    prompt = ChatPromptTemplate(messages=messages)
    return prompt

依赖包版本

  • pydantic: 2.11.5
  • pydantic_core: 2.33.2
  • pydantic-settings: 2.9.1
  • langchain: 0.3.25
  • langchain-core: 0.3.61
  • langchain-openai: 0.3.16

排查与解决步骤

  1. 问题根源:报错源于OpenAI返回的工具调用chunk中,annotation字段是字典类型,但代码逻辑期望它是Pydantic模型实例,导致model_dump方法调用失败。直接用字典定义工具是主要诱因。

  2. 修复方案:

    • 使用官方工具类定义file_search:替换字典式工具定义,改用LangChain提供的FileSearch类,确保结构符合内部处理要求:
      from langchain_community.tools.file_search import FileSearch
      
      fileTool = FileSearch(vector_store_ids=[vectore_store_id])
      llm_with_tools = self.llm.bind_tools([fileTool])
      
    • 对齐依赖版本:当前langchain-openai与langchain、langchain-core版本存在兼容性风险,执行升级命令同步版本:
      pip install --upgrade langchain-openai langchain-core
      
    • 区分流式响应类型:工具调用的chunk与普通文本chunk结构不同,需在循环内做类型判断,避免盲目调用text()方法:
      async for chunk in chain.astream(...):
          try:
              print(chunk.type)
              if hasattr(chunk, 'text'):
                  output += chunk.text()
                  yield AIMessageChunk(content=chunk.text())
              elif chunk.type == 'tool_call':
                  # 可添加工具调用的自定义处理逻辑
                  pass
          except Exception as e:
              print(f"Error detail: {e}")
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:58:19