函数调用(Function Calling)高阶实战:让 Gemini 自主调用外部工具 API
让大模型拥有动手能力!手把手教你定义 Python 函数规范、教模型自主决策何时调用天气查询接口并整合最终回答全流程。
一、什么是函数调用?
大模型本身不能联网查实时股票或查询企业内网数据库。
函数调用允许你把自研的本地函数(Tools)告知模型。模型在理解用户提问后,会返回一个包含结构化参数的 JSON 指令,告诉你的程序:请执行这个函数并把结果交还给我!
二、核心实战代码框架
def get_current_weather(location: str):
return f"{location} 当前天气晴朗,气温 25 摄氏度"
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
tools=[get_current_weather]
)
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message("今天杭州天气怎么样?")
print(response.text)
开启自动函数调用后,SDK 会在后台自主完成参数提取、函数执行与最终语言润色,一气呵成!