{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "b646cf4a-18a8-4eb0-882e-4f087b779ffe", "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "os.environ['http_proxy'] = 'http://10.10.9.50:3000'\n", "os.environ['https_proxy'] = 'http://10.10.9.50:3000'\n", "os.environ['no_proxy'] = 'localhost,127.0.0.1'" ] }, { "cell_type": "markdown", "id": "8bb7790a-b2c5-46ac-a283-491529b2c0e5", "metadata": {}, "source": [ "## 1.描述外部函数" ] }, { "cell_type": "code", "execution_count": 2, "id": "72f06bfc-67d2-4c7b-a394-ffb6df2c5d9b", "metadata": {}, "outputs": [], "source": [ "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_weather_info\",\n", " \"description\": \"Get the weather information of a city\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"city\": {\n", " \"type\": \"string\",\n", " \"description\": \"The name of the city, e.g. Shanghai\",\n", " },\n", " },\n", " \"required\": [\"city\"],\n", " },\n", " }\n", " }\n", "]" ] }, { "cell_type": "markdown", "id": "48d76891-be79-4b3a-ae4d-9a4fd1f8b4c0", "metadata": {}, "source": [ "#### 初始化ZhipuAI" ] }, { "cell_type": "code", "execution_count": 3, "id": "e868149d-e207-4fa0-be87-2bd834778dfa", "metadata": {}, "outputs": [], "source": [ "from zhipuai import ZhipuAI\n", "client = ZhipuAI(api_key=\"cc28e0d694973a7276d02d6822e5958c.5h0H2TcNId2qBGBi\")" ] }, { "cell_type": "markdown", "id": "10b89c40-9e78-4aaf-900c-4501101a4bd9", "metadata": {}, "source": [ "## 2. 与模型交互,触发模型对函数的调用" ] }, { "cell_type": "code", "execution_count": 4, "id": "47b1fdaf-c013-42d2-b57b-51acc5c4bfed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'content': None, 'role': 'assistant', 'tool_calls': [{'id': 'call_9106863387107282637', 'function': {'arguments': '{\"city\": \"Beijing\"}', 'name': 'get_weather_info'}, 'type': 'function', 'index': 0}]}\n" ] } ], "source": [ "query = \"What is the weather like in Beijing?\"\n", "messages=[{\"role\": \"user\", \"content\": query}]\n", "response = client.chat.completions.create(\n", " model=\"GLM-4-Plus\",\n", " messages=messages,\n", " tools=tools,\n", " #这个地方我注释掉了,因为默认就是auto。\n", " #tool_choice=\"auto\", \n", " )\n", "message = response.dict()[\"choices\"][0][\"message\"]\n", "print(message)" ] }, { "cell_type": "markdown", "id": "6837d5b3-568c-4c2b-b3e3-29e55a1edc6b", "metadata": {}, "source": [ "## 3. 使用模型生成的参数调用函数" ] }, { "cell_type": "markdown", "id": "90c428ef-6e79-42b3-b6fd-5e135a0aef3c", "metadata": {}, "source": [ "### 3.1 先实现函数" ] }, { "cell_type": "code", "execution_count": 5, "id": "2e292953-6420-4120-aaba-88c0daca7030", "metadata": {}, "outputs": [], "source": [ "import requests\n", "\n", "def get_weather_info(city=\"Beijing\"):\n", " return {\"weather in beijing\": \"sunny\"}" ] }, { "cell_type": "markdown", "id": "14ee8b16-0a31-45b9-b86a-b9fd3e50b381", "metadata": {}, "source": [ "### 3.2 定义处理 Function call 的函数:" ] }, { "cell_type": "code", "execution_count": 6, "id": "51b83a05-efeb-4532-849c-19e0f1c3fe65", "metadata": {}, "outputs": [], "source": [ "def parse_function_call(model_response,messages):\n", " # 处理函数调用结果,根据模型返回参数,调用对应的函数。\n", " # 调用函数返回结果后构造tool message,再次调用模型,将函数结果输入模型\n", " # 模型会将函数调用结果以自然语言格式返回给用户。\n", " if model_response.choices[0].message.tool_calls:\n", " tool_call = model_response.choices[0].message.tool_calls[0]\n", " args = tool_call.function.arguments\n", " function_result = {}\n", " if tool_call.function.name == \"get_weather_info\":\n", " function_result = get_weather_info(**json.loads(args))\n", " messages.append({\n", " \"role\": \"tool\",\n", " \"content\": f\"{json.dumps(function_result)}\",\n", " \"tool_call_id\":tool_call.id\n", " })\n", " response = client.chat.completions.create(\n", " model=\"glm-4\", # 填写需要调用的模型名称\n", " messages=messages,\n", " tools=tools,\n", " )\n", " print(response.choices[0].message)\n", " messages.append(response.choices[0].message.model_dump())" ] }, { "cell_type": "code", "execution_count": 7, "id": "a3183e74-944d-4596-91b3-4caadbdf5718", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CompletionMessage(content=None, role='assistant', tool_calls=[CompletionMessageToolCall(id='call_9106863215308436029', function=Function(arguments='{\"city\":\"Beijing\"}', name='get_weather_info'), type='function', index=0)])\n", "CompletionMessage(content='According to the weather information API, the weather in Beijing is currently sunny.', role='assistant', tool_calls=None)\n" ] } ], "source": [ "# 清空对话\n", "messages = []\n", " \n", "messages.append({\"role\": \"user\", \"content\": \"What is the weather like in Beijing?\"})\n", " \n", "response = client.chat.completions.create(\n", " model=\"glm-4\", # 填写需要调用的模型名称\n", " messages=messages,\n", " tools=tools,\n", ")\n", "print(response.choices[0].message)\n", "messages.append(response.choices[0].message.model_dump())\n", " \n", "parse_function_call(response,messages)" ] }, { "cell_type": "code", "execution_count": 8, "id": "04d00aae-254f-4120-b657-b493d3a4f410", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'content': None,\n", " 'role': 'assistant',\n", " 'tool_calls': [{'id': 'call_9106863215308436029',\n", " 'function': {'arguments': '{\"city\":\"Beijing\"}', 'name': 'get_weather_info'},\n", " 'type': 'function',\n", " 'index': 0}]}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response.choices[0].message.model_dump()" ] }, { "cell_type": "code", "execution_count": null, "id": "87c09ed4-b719-4fd9-a151-6f0ffd93aed9", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "c9ab6bb0-1ebf-4358-ba09-12950bd4d107", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "python3.10(base)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.8" } }, "nbformat": 4, "nbformat_minor": 5 }