Google Gemini Pro集成工具后无法回答非工具类请求问题求助
解决Google Gemini Pro集成工具后无法回答非工具类问题的方案
问题原因
开启enable_automatic_function_calling=True后,Gemini Pro会默认优先尝试用提供的工具处理所有请求,当没有匹配工具时就返回无法完成请求,不会自动 fallback 到自身通用知识库回答问题。
解决方案
方案1:配置自动判断的函数调用策略
通过function_calling_config设置mode="auto",让模型自行决定是否需要调用工具,无需工具的问题直接用自身知识回答。
修改后的代码示例:
import google.generativeai as genai def multiply(a: float, b: float): """returns a * b.""" return a * b model = genai.GenerativeModel( model_name='gemini-1.0-pro', tools=[multiply], # 配置函数调用策略为自动判断 function_calling_config={"mode": "auto"} ) chat = model.start_chat(enable_automatic_function_calling=True) # 测试非工具类问题 response = chat.send_message('who is the president of usa') print(response.text) # 输出:Joe Biden # 测试工具类问题 response = chat.send_message('计算3.5乘以4的结果') print(response.text) # 输出:14.0
方案2:手动控制工具调用逻辑
如果需要更精细的规则控制,可以关闭自动函数调用,手动解析模型的工具调用请求,判断是否执行工具,无需工具的问题直接返回模型原生回答。
代码示例:
import google.generativeai as genai def multiply(a: float, b: float): """returns a * b.""" return a * b model = genai.GenerativeModel( model_name='gemini-1.0-pro', tools=[multiply] ) chat = model.start_chat() def process_query(query): response = chat.send_message(query) # 检查是否存在工具调用请求 if response.candidates[0].content.parts[0].function_call: func_call = response.candidates[0].content.parts[0].function_call if func_call.name == "multiply": args = func_call.args result = multiply(args["a"], args["b"]) # 将工具结果返回给模型,让其整理成自然语言回答 follow_up = chat.send_message(genai.protos.FunctionResponse( name="multiply", response={"result": result} )) return follow_up.text else: # 无工具调用需求,直接返回模型回答 return response.text # 测试非工具类问题 print(process_query('who is the president of usa')) # 输出:Joe Biden # 测试工具类问题 print(process_query('计算3.5乘以4的结果')) # 输出:14.0
说明
方案1简洁高效,利用Gemini内置逻辑即可解决核心问题;方案2适合需要自定义工具触发规则的场景,比如添加额外的问题匹配条件。
内容的提问来源于stack exchange,提问作者Naitik Singhal
相关产品推荐
相关产品推荐

