Google Generative AI函数调用报错:TypeError参数重复问题求助
错误原因及解决方法
错误原因
contents参数格式错误:generate_content要求contents是对话消息的列表,而非单个字典;同时消息中的parts也必须是列表,不能是单个字典。tools参数结构错误:嵌套的字典结构不符合Gemini Python SDK的要求,导致SDK解析时重复识别tools参数,触发"got multiple values for keyword argument 'tools'"错误。
修正后的代码
import google.generativeai as genai # 修正格式:contents是列表,parts是列表 datas = { "contents": [ { "role": "user", "parts": [{"text": "Where can I watch Oppenheimer today?"}] } ], # 修正tools结构:直接传入包含function_declarations的字典列表 "tools": [ { "function_declarations": [ { "name": "find_movies", "description": "find movie titles currently playing in theaters based on any description, genre, title words, etc.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616" }, "description": { "type": "string", "description": "Any kind of description including category or genre, title words, attributes, etc." } }, "required": ["description"] } } ] } ] } genai.configure(api_key="MY_API_KEY") model = genai.GenerativeModel('gemini-1.0-pro') response = model.generate_content(**datas) # 打印函数调用结果 print(response.candidates[0].content.parts[0].function_call)
更规范的写法(使用SDK工具类)
为避免格式错误,推荐使用SDK提供的类定义工具:
import google.generativeai as genai from google.generativeai.types import Tool, FunctionDeclaration genai.configure(api_key="MY_API_KEY") # 定义函数声明 find_movies_func = FunctionDeclaration( name="find_movies", description="find movie titles currently playing in theaters based on any description, genre, title words, etc.", parameters={ "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616" }, "description": { "type": "string", "description": "Any kind of description including category or genre, title words, attributes, etc." } }, "required": ["description"] } ) # 定义工具 tool = Tool(function_declarations=[find_movies_func]) # 调用模型 model = genai.GenerativeModel('gemini-1.0-pro') response = model.generate_content( contents=[{"role": "user", "parts": [{"text": "Where can I watch Oppenheimer today?"}]}], tools=[tool] ) print(response.candidates[0].content.parts[0].function_call)
内容的提问来源于stack exchange,提问作者Nohab
相关产品推荐
相关产品推荐

