将鸢尾花随机森林模型集成Gemini AI时遇TypeError错误求助
问题分析与解决:Gemini集成随机森林模型报错处理
错误含义解析
这个TypeError的核心原因是混用了两个不同Google AI库的工具类:你同时导入了google.generativeai(简称genai)和vertexai.preview.generative_models的相关类,但genai库的GenerativeModel只接受自身库定义的FunctionDeclaration/Tool类型,而你传入的是vertexai库的Tool对象,类型完全不匹配,因此触发了错误。和你怀疑的函数返回值格式无关,原函数返回字符串的逻辑是正确的。
修复方案
统一使用google.generativeai库的工具类,修改后的完整代码如下:
import google.generativeai as genai from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier # 配置Gemini API密钥 genai.configure(api_key="API KEY") # 加载并训练鸢尾花分类模型 iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) model = RandomForestClassifier(random_state=42) model.fit(X_train, y_train) def predict_iris_species(sepal_length, sepal_width, petal_length, petal_width): """ 根据花萼和花瓣的尺寸预测鸢尾花品种。 参数: sepal_length (float): 花萼长度(单位:厘米) sepal_width (float): 花萼宽度(单位:厘米) petal_length (float): 花瓣长度(单位:厘米) petal_width (float): 花瓣宽度(单位:厘米) 返回: str: 预测的鸢尾花品种名称 """ input_data = [[sepal_length, sepal_width, petal_length, petal_width]] prediction = model.predict(input_data) return str(iris.target_names[prediction[0]]) # 使用genai库的工具类定义函数调用 tools = [ genai.Tool( function_declarations=[ genai.FunctionDeclaration( name="predict_iris_species", description="根据花萼和花瓣的尺寸预测鸢尾花品种", parameters={ "type": "object", "properties": { "sepal_length": {"type": "number", "description": "花萼长度(单位:厘米)"}, "sepal_width": {"type": "number", "description": "花萼宽度(单位:厘米)"}, "petal_length": {"type": "number", "description": "花瓣长度(单位:厘米)"}, "petal_width": {"type": "number", "description": "花瓣宽度(单位:厘米)"} }, "required": ["sepal_length", "sepal_width", "petal_length", "petal_width"] } ) ] ) ] # 初始化Gemini模型并启动对话 llm = genai.GenerativeModel(model_name='gemini-1.5-flash', tools=tools) chat = llm.start_chat() response = chat.send_message("花萼长度5.1cm、花萼宽度3.5cm、花瓣长度1.4cm、花瓣宽度0.2cm的鸢尾花是什么品种?") print(response.text)
关键修改点说明
- 移除了
vertexai.preview.generative_models的所有导入,全程使用google.generativeai库的类 - 调整了
tools的定义方式:genai的Tool需放在列表中直接传入,内部的FunctionDeclaration也必须使用genai的类 - 保留原函数的返回值格式(字符串)即可,无需修改为JSON字典
内容的提问来源于stack exchange,提问作者myts999
相关产品推荐
相关产品推荐

