代码示例
中文exp-2809未验证
通过定义函数工具和处理函数调用,可以让 AI 模型执行各种外部操作:
Python SDK 安装 SDK # 安装最新版本 pip install zai-sdk # 或指定版本 pip install zai-sdk== 0.2.3 验证安装 import zai print (zai. __version__ ) 完整示例 import json from zai import ZhipuAiClient # 初始化客户端 client = ZhipuAiClient( api_key = 'YOUR_API_KEY' ) # 定义天气查询函数 def get_weather ( city : str ) -> dict : """获取指定城市的天气信息""" # 这里应该调用真实的天气 API weather_data = { "city" : city, "temperature" : "22°C" , "condition" : "晴天" , "humidity" : "65%" , "wind_speed" : "5 km/h" } return weather_data # 定义函数工具 tools = [ { "type" : "function" , "function" : { "name" : "get_weather" , "description" : "获取指定城市的当前天气信息" , "parameters" : { "type" : "object" , "properties" : { "city" : { "type" : "string" , "description" : "城市名称,例如:北京、上海" } }, "required" : [ "city" ] } } } ] # 发起对话请求 response = client.chat.completions.create( model = "glm-5.3" , # 使用支持函数调用的模型 messages = [ { "role" : "user" , "content" : "北京今天天气怎么样?" } ], tools = tools, # 传入函数工具 tool_choice = "auto" # 自动选择是否调用函数 ) # 处理函数调用 message = response.choices[ 0 ].message messages = [{ "role" : "user" , "content" : "北京今天天气怎么样?" }] messages.append(message.model_dump()) if message.tool_calls: for tool_call in message.tool_calls: if tool_call.function.name == "get_weather" : # 解析参数并调用函数 args = json.loads(tool_call.function.arguments) weather_result = get_weather(args.get( "city" )) # 将函数结果返回给模型 messages.append({ "role" : "tool" , "content" : json.dumps(weather_result, ensure_ascii = False ), "tool_call_id" : tool_call.id }) # 获取最终回答 final_response = client.chat.completions.create( model = "glm-5.3" , messages = messages, tools = tools ) print (final_response.choices[ 0 ].message.content) else : print (message.content)
复制后粘贴到 AI 对话框发送,本次对话全程生效
怎么用(对话型)复制后粘贴到对话框发送,本次对话全程生效。想长期用:支持自定义指令的产品(设置→个性化)可设为默认。