OpenAi FunctionCalling 案例详解

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

FunctionCalling的单一函数调用

天气预报查询(今天长沙的天气如何?)
import json
import requests
from openai import OpenAIclient = 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.argumentsif 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.argumentsif 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 OpenAIclient = 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 resultmessages = []
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 及教学视频下载链接:点击这里下载 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1552774.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

鸿蒙开发知识点速记全解

入门 1、API涵盖应用框架、系统、媒体、图形、应用服务、AI六大领域。 应用框架相关Kit开放能力:Ability Kit(程序框架服务)、ArkUI(方舟UI框架)等。系统相关Kit开放能力:Universal Keystore Kit&#xf…

24-10-1-读书笔记(二十一)-《契诃夫文集》(四)下([俄] 契诃夫 [译] 汝龙) 我爱你,娜坚卡。

文章目录 《契诃夫文集》(四)下([俄] 契诃夫 [译] 汝龙 )目录阅读笔记记录总结 《契诃夫文集》(四)下([俄] 契诃夫 [译] 汝龙 ) 十月第一篇,放假了,挺高兴的&…

四、I/O控制方式

1.程序直接控制方式 完成一次读/写的过程 CPU千预频率 每次I/O的数据传输单位 数据流向 优缺点 CPU发出I/0命令后需要不断轮询 极高 字 设备→CPU→内存 内存→CPU→设备 优点:实现简单。在读/写指令之后,加上实现循环检查的一系列指令即可(因此才称为“程…

WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!

前言 今天大姚给大家分享一套基于.NET 8.0 LayUI的快速开发框架,项目完全开源、免费(MIT License)且开箱即用:WaterCloud。 可完全实现二次开发让开发更多关注业务逻辑。既能快速提高开发效率,帮助公司节省人力成本&…

Stable Diffusion绘画 | 来训练属于自己的模型:打标处理与优化

上一篇完成的打标工作,是为了获取提示词,让AI认识和学习图片的特征。 因此,合适、恰当、无误的提示词,对最终模型效果是相当重要的。 Tag 如何优化 通过软件自动生成的 Tag 只是起到快速建立大体架构的作用,里面会涉…

某大型公园定岗定编项目成功案例纪实

某大型公园定岗定编项目成功案例纪实 ——优化人力配置,实施灵活化人员调整策略,解决忙闲不均问题 【客户行业】文旅行业;事业单位;公园 【问题类型】定岗定编 【客户背景】 某大型公园随着上级政策的改变,公园取…

探索 PixiJS:强大的 2D 图形渲染库

探索 PixiJS:强大的 2D 图形渲染库 演示地址 演示地址 源码地址 源码地址 获取更多 获取更多 随着 Web 技术的发展,越来越多的开发者希望在网页中实现丰富的视觉效果和动画。PixiJS 作为一个高性能的 2D 渲染库,凭借其强大的功能和易用性…

文件名:\\?\C:\Windows\system32\inetsrv\config\applicationHost.config错误:无法写入配置文件

文件名: \\?\C:\Windows\system32\inetsrv\config\applicationHost.config 错误:无法写入配置文件 解决办法: 到C:\inetpub\history中找到最近一次的【CFGHISTORY_00000000XX】文件,点击进去找到applicationHost.config文件,用其覆盖C:\Win…

C++ 游戏开发

C游戏开发 C 是一种高效、灵活且功能强大的编程语言,因其性能和控制能力而在游戏开发中被广泛应用。许多著名的游戏引擎,如 Unreal Engine、CryEngine 和 Godot 等,都依赖于 C 进行核心开发。本文将详细介绍 C 在游戏开发中的应用&#xff0…

B. Brightness Begins Codeforces Round 976 (Div. 2)

原题 B. Brightness Begins 解析 Hint 1 第 i 个灯泡最终状态与 n 的大小无关 Hint 2 第 i 个灯泡最终状态与 i 的约数数量的奇偶性相关 Solution 对任意灯泡 i , 它的最终状态由其约数数量的奇偶性相关, 如果 i 有偶数个约数, 那么会是亮的, 否则会是暗的. 换句话说, 如…

使用Materialize制作unity的贴图,Materialize的简单教程,Materialize学习日志

Materialize 官网下载地址:http://boundingboxsoftware.com/materialize/ github源码地址:https://github.com/BoundingBoxSoftware/Materialize 下载地址:http://boundingboxsoftware.com/materialize/getkey.php 下载后解压运行exe即可 …

安装epic games错误码2738解决(安装ue错误码2738)

这个错误不好找到解决方案,尝试删除注册表以及通过电脑管家下载安装都不生效,仍然会错误2738。直到找到了这个解决方案。 1.cmd然后右键以管理员身份运行, 2.cd %windir%\syswow64进入该目录 3.reg delete “HKCU\SOFTWARE\Classes\Wow6432No…

C语言 | Leetcode C语言题解之题451题根据字符出现频率排序

题目: 题解: #define HASH_FIND_CHAR(head, findint, out) HASH_FIND(hh, head, findint, sizeof(char), out) #define HASH_ADD_CHAR(head, intfield, add) HASH_ADD(hh, head, intfield, sizeof(char), add)struct HashTable {char key;int val;UT_ha…

【STM32单片机_(HAL库)】4-4【定时器TIM】脉冲计数配置步骤及实验

脉冲计数配置步骤 1.硬件 STM32单片机最小系统按键模块 2.软件 定时器HAL驱动层文件添加counter驱动文件添加GPIO常用函数main.c程序 #include "sys.h" #include "delay.h" #include "led.h" #include "uart1.h" #include "…

6.3 API网关 架构模式 分类 和 应用实践

6.3 API网关 架构模式 分类 和 应用实践 目录概述需求: 设计思路实现思路分析1.反向代理模式2.微服务模式3.单体模式4.服务网格模式 分类:1.2.1 按功能分类3.2.2 按部署方式分类4.2.3 按协议支持分类: 应用实践: 参考资料和推荐阅…

Windows 开发工具使用技巧 QT使用安装和使用技巧 QT快捷键

一、QT配置 1. 安装 Qt 开发框架 1、下载 1、进入下载地址 下载地址1 (官方, 需注册账号): https://www.qt.io/download下载地址2(推荐): http://download.qt.io/http://download.qt.io/archive/qt/ (或更直接的…

植物叶片病害检测数据集 5100张 29类 带标注 voc yolo

植物叶片病害检测数据集 5100张 29类 带标注 voc yolo 植物叶片病害检测数据集 名称 植物叶片病害检测数据集 (Plant Leaf Disease Detection Dataset) 规模 图像数量:5154张图像。类别:29种病害类型。分类名: (图片张数,标注个数) Tomato…

【CSS3】css开篇基础(1)

1.❤️❤️前言~🥳🎉🎉🎉 Hello, Hello~ 亲爱的朋友们👋👋,这里是E绵绵呀✍️✍️。 如果你喜欢这篇文章,请别吝啬你的点赞❤️❤️和收藏📖📖。如果你对我的…

通信工程学习:什么是DQDB分布式队列双总线

DQDB:分布式队列双总线 DQDB(Distributed Queue Dual Bus),即分布式队列双总线,是美国电气电子工程师学会(IEEE)802.6标准中定义的一种城域网(MAN)数据链路层通信协议。该协议主要用于城域网的数据、语音和视频传输&am…

前端工程化17-邂逅原生的ajax、跨域、JSONP

5、邂逅原生的ajax 5.1、什么是ajax AJAX 全称为Asynchronous Javascript And XML,就是异步的 JS 和 XML。通过AJAX可以在浏览器中向服务器发送异步请求,最大的优势:页面无刷新获取数据。AJAX 不是新的编程语言,而是一种将现有的…