源码详细讲解 pdf 及教学视频下载链接:点击这里下载
FunctionCalling的单一函数调用
天气预报查询(今天长沙的天气如何?)
import json
import requests
from openai import OpenAI
client = OpenAI()
location = "长沙"
def get_current_weather(city):
url = "https://restapi.amap.com/v3/weather/weatherInfo?key=0f219ddb5f23d95ea1731fe653f906a3&city={city}".format(city=city)
response = requests.get(url)
result = eval(response.text)["lives"][0]
weather_info = {
"location": city,
"weather": result["weather"],
"temperature": result["temperature"],
"time": result["reporttime"]
}
return json.dumps(weather_info, ensure_ascii=False)
messages = []
messages.append({"role":"system", "content":"你是一个查询天气的机器人,你需要根据用户提供的地址来回答当地的天气情况"})
messages.append({"role":"user", "content": f"""今天{location}的天气如何?"""})
tools = [{
"type":"function",
"function": {
"name":"get_current_weather",
"description": "获取给定位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市或区,例如长沙"
}
},
"required":["location"]
}
}
}]
response = client.chat.completions.create(
model = "gpt-3.5-turbo",
messages = messages,
tools = tools
)
messages.append(response.choices[0].message)
print(messages)
function_name = response.choices[0].message.tool_calls[0].function.name
print(function_name)
function_id = response.choices[0].message.tool_calls[0].id
print(function_id)
messages.append({
"tool_call_id": function_id,
"role": "tool",
"name": function_name,
"content": get_current_weather(location)
})
print(messages)
response = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
print(response.choices[0].message.content)
运行结果
Function call的多函数调用
查询学校课程对应的老师(帮我查询北京大学的中国历史课程是哪位老师(teacher)。)
import json
from openai import OpenAI
client = OpenAI()
tools = [{
"type": "function",
"function": {
"name": "get_class_number",
"description": "根据学校、课程查询上课编号",
"parameters": {
"type": "object",
"properties": {
"school": {
"description": "学校",
"type": "string"
},
"course": {
"description": "课程",
"type": "string"
}
},
"required": ["school", "course"]
}
}
}, {
"type": "function",
"function": {
"name": "get_course_teacher",
"description": "查询某课程的老师",
"parameters": {
"type": "object",
"properties": {
"class_number": {
"description": "上课编号",
"type": "string"
}
},
"required": ["class_number"]
},
}
}]
def get_class_number(school: str, course: str):
class_number = {
"清华大学": {
"高等数学": "MATH101",
"线性代数": "MATH102",
},
"北京大学": {
"大学英语": "ENG201",
"中国历史": "HIST202",
}
}
return {"class_number": class_number[school][course]}
def get_course_teacher(class_number: str):
course_teacher_mapping = {
"MATH101": "张老师",
"MATH102": "李老师",
"ENG201": "王老师",
"HIST202": "赵老师",
}
teacher = course_teacher_mapping.get(class_number)
return {"teacher": teacher}
messages = []
messages = [
{
"role": "system",
"content": "你是一位高效的教育助手,现在需要查询某高校的老师名称。"
},
{
"role": "user",
"content": "帮我查询北京大学的中国历史课程是哪位老师(teacher)。"
}
]
# 第一次调用
first_response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
tools=tools,
tool_choice="auto",
)
print(first_response.choices[0].message)
messages.append(first_response.choices[0].message)
first_function = {}
if first_response.choices[0].message.tool_calls:
tool_call = first_response.choices[0].message.tool_calls[0]
args = tool_call.function.arguments
if tool_call.function.name == "get_class_number":
first_function = get_class_number(**json.loads(args))
if tool_call.function.name == "get_course_teacher":
first_function = get_course_teacher(**json.loads(args))
print(first_function)
tool_call = first_response.choices[0].message.tool_calls[0]
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(json.dumps(first_function)),
"name": tool_call.function.name
})
print("***" * 40)
print(messages)
print("***" * 40)
second_response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
tools=tools,
tool_choice="auto"
)
print(second_response.choices[0].message)
messages.append(second_response.choices[0].message)
second_function = {}
if second_response.choices[0].message.tool_calls:
tool_call = second_response.choices[0].message.tool_calls[0]
args = tool_call.function.arguments
if tool_call.function.name == "get_class_number":
second_function = get_class_number(**json.loads(args))
if tool_call.function.name == "get_course_teacher":
second_function = get_course_teacher(**json.loads(args))
print(second_function)
tool2_call = second_response.choices[0].message.tool_calls[0]
# 将函数的结果添加到messages中,继续送入模型问答
messages.append(
{
"role": "tool",
"tool_call_id": tool2_call.id,
"content": str(json.dumps(second_function)),
"name":tool2_call.function.name
}
)
last_response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
tools=tools,
tool_choice="auto",
)
print(last_response.choices[0].message.content)
运行结果
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)
运行结果
源码详细讲解 pdf 及教学视频下载链接:点击这里下载