OpenAi FunctionCalling 案例详解

源码详细讲解 pdf 及教学视频下载链接:点击这里下载

FunctionCalling的单一函数调用

天气预报查询(今天长沙的天气如何?)

 1 import json
 2 import requests
 3 from openai import OpenAI
 4  
 5 client = OpenAI()
 6  
 7 location = "长沙"
 8  
 9 def get_current_weather(city):
10     url = "https://restapi.amap.com/v3/weather/weatherInfo?key=0f219ddb5f23d95ea1731fe653f906a3&city={city}".format(city=city)
11     response = requests.get(url)
12     result = eval(response.text)["lives"][0]
13     weather_info = {
14         "location": city,
15         "weather": result["weather"],
16         "temperature": result["temperature"],
17         "time": result["reporttime"]
18     }
19     return json.dumps(weather_info, ensure_ascii=False)
20  
21 messages = []
22 messages.append({"role":"system", "content":"你是一个查询天气的机器人,你需要根据用户提供的地址来回答当地的天气情况"})
23 messages.append({"role":"user", "content": f"""今天{location}的天气如何?"""})
24 tools = [{
25     "type":"function",
26     "function": {
27         "name":"get_current_weather",
28         "description": "获取给定位置的当前天气",
29         "parameters": {
30             "type": "object",
31             "properties": {
32                 "location": {
33                     "type": "string",
34                     "description": "城市或区,例如长沙"
35                 }
36             },
37             "required":["location"]
38         }
39     }
40 }]
41  
42 response = client.chat.completions.create(
43     model = "gpt-3.5-turbo",
44     messages = messages,
45     tools = tools
46 )
47  
48 messages.append(response.choices[0].message)
49 print(messages)
50 function_name = response.choices[0].message.tool_calls[0].function.name
51 print(function_name)
52 function_id = response.choices[0].message.tool_calls[0].id
53 print(function_id)
54 messages.append({
55     "tool_call_id": function_id,
56     "role": "tool",
57     "name": function_name,
58     "content": get_current_weather(location)
59 })
60 print(messages)
61  
62 response = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
63 print(response.choices[0].message.content)

View Code

运行结果

 Function call的多函数调用

查询学校课程对应的老师(帮我查询北京大学的中国历史课程是哪位老师(teacher)。)

  1 import json
  2 from openai import OpenAI
  3 client = OpenAI()
  4 tools = [{
  5     "type": "function",
  6     "function": {
  7         "name": "get_class_number",
  8         "description": "根据学校、课程查询上课编号",
  9         "parameters": {
 10             "type": "object",
 11             "properties": {
 12                 "school": {
 13                     "description": "学校",
 14                     "type": "string"
 15                 },
 16                 "course": {
 17                     "description": "课程",
 18                     "type": "string"
 19                 }
 20             },
 21             "required": ["school", "course"]
 22         }
 23     }
 24 }, {
 25     "type": "function",
 26     "function": {
 27         "name": "get_course_teacher",
 28         "description": "查询某课程的老师",
 29         "parameters": {
 30             "type": "object",
 31             "properties": {
 32                 "class_number": {
 33                     "description": "上课编号",
 34                     "type": "string"
 35                 }
 36             },
 37             "required": ["class_number"]
 38         },
 39     }
 40 }]
 41  
 42 def get_class_number(school: str, course: str):
 43     class_number = {
 44         "清华大学": {
 45             "高等数学": "MATH101",
 46             "线性代数": "MATH102",
 47         },
 48         "北京大学": {
 49             "大学英语": "ENG201",
 50             "中国历史": "HIST202",
 51         }
 52     }
 53     return {"class_number": class_number[school][course]}
 54  
 55 def get_course_teacher(class_number: str):
 56     course_teacher_mapping = {
 57         "MATH101": "张老师",
 58         "MATH102": "李老师",
 59         "ENG201": "王老师",
 60         "HIST202": "赵老师",
 61     }
 62     teacher = course_teacher_mapping.get(class_number)
 63     return {"teacher": teacher}
 64  
 65 messages = []
 66 messages = [
 67     {
 68         "role": "system",
 69         "content": "你是一位高效的教育助手,现在需要查询某高校的老师名称。"
 70     },
 71     {
 72         "role": "user",
 73         "content": "帮我查询北京大学的中国历史课程是哪位老师(teacher)。"
 74     }
 75 ]
 76  
 77 # 第一次调用
 78 first_response = client.chat.completions.create(
 79     model="gpt-3.5-turbo",
 80     messages=messages,
 81     tools=tools,
 82     tool_choice="auto",
 83 )
 84 print(first_response.choices[0].message)
 85  
 86 messages.append(first_response.choices[0].message)
 87  
 88 first_function = {}
 89 if first_response.choices[0].message.tool_calls:
 90     tool_call = first_response.choices[0].message.tool_calls[0]
 91     args = tool_call.function.arguments
 92     if tool_call.function.name == "get_class_number":
 93         first_function = get_class_number(**json.loads(args))
 94     if tool_call.function.name == "get_course_teacher":
 95         first_function = get_course_teacher(**json.loads(args))
 96  
 97 print(first_function)
 98  
 99 tool_call = first_response.choices[0].message.tool_calls[0]
100 messages.append({
101     "role": "tool",
102     "tool_call_id": tool_call.id,
103     "content": str(json.dumps(first_function)),
104     "name": tool_call.function.name
105 })
106 print("***" * 40)
107 print(messages)
108 print("***" * 40)
109  
110 second_response = client.chat.completions.create(
111     model="gpt-3.5-turbo",
112     messages=messages,
113     tools=tools,
114     tool_choice="auto"
115 )
116 print(second_response.choices[0].message)
117  
118 messages.append(second_response.choices[0].message)
119 second_function = {}
120 if second_response.choices[0].message.tool_calls:
121     tool_call = second_response.choices[0].message.tool_calls[0]
122     args = tool_call.function.arguments
123     if tool_call.function.name == "get_class_number":
124         second_function = get_class_number(**json.loads(args))
125     if tool_call.function.name == "get_course_teacher":
126         second_function = get_course_teacher(**json.loads(args))
127  
128 print(second_function)
129 tool2_call = second_response.choices[0].message.tool_calls[0]
130 # 将函数的结果添加到messages中,继续送入模型问答
131 messages.append(
132     {
133         "role": "tool",
134         "tool_call_id": tool2_call.id,
135         "content": str(json.dumps(second_function)),
136         "name":tool2_call.function.name
137     }
138 )
139  
140 last_response = client.chat.completions.create(
141     model="gpt-3.5-turbo",
142     messages=messages,
143     tools=tools,
144     tool_choice="auto",
145 )
146 print(last_response.choices[0].message.content)

View Code

运行结果

 FunctionCalling调用SQL

查询一下最高工资的员工姓名及对应的工资

import json
import pymysql
from openai import OpenAI
 
client = OpenAI()
 
def connect_database(query):
    conn = pymysql.connect(
        host="localhost",
        port=3306,
        user="root",
        password="123456",
        database="school",
        charset="utf8mb4",
    )
    cursor = conn.cursor()
    cursor.execute(query)
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result
 
messages = []
messages.append({"role": "system", "content": "通过针对业务数据库生成 SQL 查询来回答用户的问题"})
messages.append({"role": "user", "content": "查询一下最高工资的员工姓名及对应的工资"})
 
response = client.chat.completions.create(
    messages=messages,
    model="gpt-3.5-turbo",
    tools=[
        {
            "type": "function",
            "function": {
                "name": "connect_database",
                "description": "使用此函数回答业务问题,要求输出是一个SQL查询语句",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "sql": {
                            "type": "string",
                            "description": f"SQL查询提取信息以回答用户的问题。"
                            f"查询应该以纯文本返回,而不是JSON。"
                            f"数据库的表为 emp 表。字段有 id,name,salary"
                            f"查询应该只包含MySQL支持的语法。",
                        }
                    },
                    "required": ["sql"],
                },
            }
        }
    ]
)
print("tool calls", response.choices[0].message.tool_calls[0])
 
messages.append(response.choices[0].message)
function_name = response.choices[0].message.tool_calls[0].function.name
function_id = response.choices[0].message.tool_calls[0].id
function_response = connect_database(
    json.loads(
        response.choices[0].message.tool_calls[0].function.arguments
    ).get("sql")
)
print("dbResult", function_response)
 
messages.append({
    "role": "tool",
    "tool_call_id": function_id,
    "name": function_name,
    "content": str(function_response),
})
last_response = client.chat.completions.create(
    messages=messages,
    model="gpt-3.5-turbo",
)
print(last_response.choices[0].message.content)
 

View Code

运行效果

 

源码详细讲解 pdf 及教学视频下载链接:点击这里下载

 
千百度
© 版权声明
THE END
喜欢就支持一下吧
点赞298 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容