3. 大模型推理功能调用外部工具,根据执行结果返回用户文案——OpenAI FunctionCalling 案例详解

教学视频
4. 大模型推理功能调用外部工具,根据执行结果返回用户文案——OpenAI FunctionCalling 案例详解_哔哩哔哩_bilibili利用大模型的推理能力调用外部函数,比如查询天气预报、执行数据库操作等,大模型能够根据这些外部工具的执行结果用自然语言回复用户, 视频播放量 558、弹幕量 0、点赞数 3、投硬币枚数 0、收藏人数 12、转发人数 1, 视频作者 jiangliuer3264, 作者简介 ,相关视频:LLM如何“自主”调用工具?揭秘Function Calling真相!,【DeepSeek教程】清华大佬198小时讲完的DeepSeek教程,全程干货无废话!B站最用心的人工智能零基础系统教程,7 天掌握 国产AI,6.租赁 GPU 服务器并微调 Llama-Factory 模型,DeepSeek R1结构化输出,如何解决function call的问题?,【2025最新AI大模型】十分钟彻底搞懂AI大模型底层原理!带你从0构建对大模型的认知!小白也能看懂!,利用WPS多维表自动化推送消息至个人微信功能实现,DeepSeek本地部署后创建专属知识库——并在局域网中调用,练习两天半,从零实现DeepSeek-R1(基于Qwen2.5-0.5B和规则奖励模型,GRPO),从原理讲解到代码实现,解开DeepSeek-R1的神秘面纱,观众看完,会心一笑。,黑马程序员DeepSeek最新保姆级新手教程,AI大模型应用开发合集直播(一)https://www.bilibili.com/video/BV17jNmeKESF/

Ads:大模型中转平台,一个key调用国内外四十家公司上千大模型,相应快速,价格优惠,点击链接注册使用

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)

运行结果 

 

  文档链接:

https://cloud.189.cn/t/RRBbMfMJzqMr(访问码:p8oz)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ApiChain

扔个包子砸我一下吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值