使用Gemini-Pro函数调用时触发“Invalid constructor input for Tool”错误
问题分析
你遇到的TypeError是因为Google Gemini Python SDK要求传入tools参数的必须是SDK定义的工具对象,而非普通Python函数。SDK需要明确的函数元数据(如功能描述、参数类型说明)来让模型理解如何调用该函数,直接传函数对象无法满足这一要求。
解决方案
使用google.generativeai.Tool类包装你的函数,补充必要的元信息。以下是修正后的完整代码:
import google.generativeai as genai # 初始化SDK(替换为你的API密钥) genai.configure(api_key="YOUR_API_KEY") def getWordCount(sentence: str): return len(sentence.split(' ')) # 用Tool类包装函数,添加模型所需的元数据 word_count_tool = genai.Tool( function_declaration={ "name": "getWordCount", "description": "计算给定句子中的单词数量", "parameters": { "type": "object", "properties": { "sentence": { "type": "string", "description": "需要计算单词数的目标句子" } }, "required": ["sentence"] } }, function=getWordCount ) # 初始化模型并传入包装后的工具 model = genai.GenerativeModel(model_name='models/gemini-pro', tools=[word_count_tool]) # 示例:触发自动工具调用的对话流程 chat = model.start_chat(enable_automatic_function_calling=True) response = chat.send_message("请计算这句话的单词数:Hello world, this is a test sentence.") print(response.text)
关键说明
function_declaration是核心配置:它遵循OpenAPI规范,向模型传递函数的名称、用途、参数结构及必填项,这是模型能正确发起函数调用的前提。- 开启
enable_automatic_function_calling=True后,SDK会自动处理模型的函数调用请求,执行函数后将结果返回给模型生成最终回答。 - 所有Gemini系列模型的函数调用逻辑一致,修正后可在你列出的所有模型上正常运行。
内容的提问来源于stack exchange,提问作者renakre
相关产品推荐
相关产品推荐

