当前位置: 首页 > news >正文

通过 ChatGPT 的 Function Call 查询数据库

 用 Function Calling 的方式实现手机流量包智能客服的例子。

def get_sql_completion(messages, model="gpt-3.5-turbo"):response = client.chat.completions.create(model=model,messages=messages,temperature=0,tools=[{  # 摘自 OpenAI 官方示例 https://github.com/openai/openai-cookbook/blob/main/examples/How_to_call_functions_with_chat_models.ipynb"type": "function","function": {"name": "ask_database","description": "Use this function to answer user questions about packages. \Output should be a fully formed SQL query.","parameters": {"type": "object","properties": {"query": {"type": "string","description": f"""SQL query extracting info to answer the user's question.SQL should be written using this database schema:{database_schema_string}The query should be returned in plain text, not in JSON.The query should only contain grammars supported by SQLite.""",}},"required": ["query"],}}}],)return response.choices[0].message
#  描述数据库表结构
database_schema_string = """
CREATE TABLE packages (id INT PRIMARY KEY NOT NULL, -- 主键,不允许为空package_name STR NOT NULL, -- 套餐名称,不允许为空monthly_fee INT NOT NULL, -- 月费,单位元,不允许为空flow_size INT NOT NULL, -- 流量大小,单位G,不允许为空condition STR -- 购买的限制条件,允许为空
);
"""
import sqlite3# 创建数据库连接
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()# 创建orders表
cursor.execute(database_schema_string)# 插入4条明确的模拟记录
mock_data = [(1, '经济套餐', 50, 10, None),(2, '畅游套餐', 180, 100, None),(3, '无限套餐', 300, 1000, None),(4, '校园套餐', 150, 200, '仅限在校生'),
]for record in mock_data:cursor.execute('''INSERT INTO packages (id, package_name, monthly_fee, flow_size, condition)VALUES (?, ?, ?, ?, ?)''', record)# 提交事务
conn.commit()
def ask_database(query):cursor.execute(query)records = cursor.fetchall()return recordsprompt = "请问流量最大的套餐是哪个?"
# prompt = "统计每月每件商品的销售额"
# prompt = "哪个用户消费最高?消费多少?"messages = [{"role": "system", "content": "基于 packages 表回答用户问题"},{"role": "user", "content": prompt}
]
print("====messages====")
print_json(messages)response = get_sql_completion(messages)
# print("====first Function Calling====")
# print_json(response)if response.content is None:response.content = ""
messages.append(response)
print("====Function Calling====")
print_json(response)if response.tool_calls is not None:tool_call = response.tool_calls[0]if tool_call.function.name == "ask_database":arguments = tool_call.function.argumentsargs = json.loads(arguments)print("====SQL====")print(args["query"])result = ask_database(args["query"])print("====DB Records====")print(result)messages.append({"tool_call_id": tool_call.id,"role": "tool","name": "ask_database","content": str(result)})response = get_sql_completion(messages)print("====最终回复====")print(response.content)

http://www.lryc.cn/news/294793.html

相关文章:

  • LLM(大语言模型)——大模型简介
  • SQLserver2008 r2 下载安装配置、使用、新建登录用户及通过Navicat远程连接
  • linux code server 网页版的vscode
  • 【leetcode100-086到090】【动态规划】一维五题合集2
  • 关闭Ubuntu 默认开启的自动安全更新
  • python统计文本 2022年9月青少年电子学会等级考试 中小学生python编程等级考试二级真题答案解析
  • HomeAssistant系统添加HACS插件商店与远程控制家中智能家居
  • 计算huggingface模型占用硬盘空间的实战代码
  • Leetcode 3031. Minimum Time to Revert Word to Initial State II
  • 游戏后端如何实现服务器之间的负载均衡?
  • es6中标签模板
  • 二级C语言笔试1
  • Spring MVC跨域设置
  • 基于Python的HTTP隧道安全性分析:魔法背后的锁与钥匙
  • linux的stat/lstat函数和目录遍历函数使用
  • HTTP MIME 类型
  • Mac OS中创建适合网络备份的加密镜像文件:详细步骤与参数选择
  • Java TreeSet 添加自定义对象 必须指定排序规则
  • vue - 指令(一)
  • 正则表达式 regex
  • iOS自动打包如何用Python实现
  • springboot161基于springboot的公交线路查询系统
  • 大白话介绍循环神经网络
  • GEE——如何利用降水数据绘制指定区域长时间序列的降水分布图和提取每个月(逐月)的降水平均数据
  • 【软件使用】【edge】如何让edge的某个网页作为应用安装
  • 四大最受欢迎游泳耳机品牌,全球最好的游泳耳机排行榜测评
  • Linux实验记录:使用BIND提供域名解析服务
  • 基于单片机的智能寻光小车设计
  • 数据结构——A/复杂度
  • 锐捷VSU和M-LAG介绍