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

ChatGoogleGenerativeAI绑定DuckDuckGo工具后调用返回空内容问题

问题解决:绑定DuckDuckGoSearch后LLM返回内容为空的问题

问题原因

你遇到的情况是正常逻辑——bind_tools仅让Gemini模型知晓可调用指定工具,但模型只会生成工具调用指令,不会自动执行工具、获取结果并生成最终回答。因此返回的content字段为空,但tool_calls中已包含正确的搜索调用指令。

解决方案

提供两种可行解决方式:

方法1:手动处理工具调用

自行解析工具调用指令,执行搜索后将结果传入LLM生成最终回答:

from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv
from langchain_community.tools import DuckDuckGoSearchRun

load_dotenv()

search = DuckDuckGoSearchRun()
llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", verbose=True)
llm_with_tools = llm.bind_tools([search])

# 生成工具调用指令
response = llm_with_tools.invoke('Which is largest state in India')

# 解析并执行工具调用,生成最终回答
if response.tool_calls:
    tool_call = response.tool_calls[0]
    if tool_call["name"] == "duckduckgo_search":
        search_result = search.invoke(tool_call["args"]["query"])
        final_response = llm.invoke(f"根据以下搜索结果回答问题:{search_result}\n问题:Which is largest state in India")
        print(final_response.content)

方法2:使用LangChain Agent(推荐)

借助Agent自动完成工具调用判断、结果获取及回答生成,这是LangChain的标准用法:

from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv
from langchain_community.tools import DuckDuckGoSearchRun
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate

load_dotenv()

search = DuckDuckGoSearchRun()
llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", verbose=True)

# 定义系统提示词
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是可使用工具的助手,根据用户问题,必要时调用工具获取信息后再回答。"),
    ("user", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

# 创建Agent及执行器
agent = create_tool_calling_agent(llm, [search], prompt)
agent_executor = AgentExecutor(agent=agent, tools=[search], verbose=True)

# 获取最终回答
response = agent_executor.invoke({"input": "Which is largest state in India"})
print(response["output"])

补充说明

  • 方法1适合需要自定义工具执行逻辑的场景,步骤清晰但代码量较多;
  • 方法2扩展性更强,Agent会自动处理工具调用全流程,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:50:13