通过fu过 Function Calling 查询数据库

2023-12-17 06:15

本文主要是介绍通过fu过 Function Calling 查询数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

from openai import OpenAI
import os
import json

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # 读取本地 .env 文件,里面定义了 OPENAI_API_KE

client = OpenAI(
api_key=os.getenv(“OPENAI_API_KEY”),
base_url=os.getenv(“OPENAI_BASE_URL”)
)

def get_sql_completion(messages, model=“gpt-3.5-turbo-1106”):
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 business.
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 orders (
id INT PRIMARY KEY NOT NULL, – 主键,不允许为空
customer_id INT NOT NULL, – 客户ID,不允许为空
product_id STR NOT NULL, – 产品ID,不允许为空
price DECIMAL(10,2) NOT NULL, – 价格,不允许为空
status INT NOT NULL, – 订单状态,整数类型,不允许为空。0代表待支付,1代表已支付,2代表已退款
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, – 创建时间,默认为当前时间
pay_time TIMESTAMP – 支付时间,可以为空
);
“”"

import sqlite3

创建数据库连接

conn = sqlite3.connect(‘:memory:’)
cursor = conn.cursor()

创建orders表

cursor.execute(database_schema_string)

插入5条明确的模拟记录

mock_data = [
(1, 1001, ‘TSHIRT_1’, 50.00, 0, ‘2023-10-12 10:00:00’, None),
(2, 1001, ‘TSHIRT_2’, 75.50, 1, ‘2023-10-16 11:00:00’, ‘2023-08-16 12:00:00’),
(3, 1002, ‘SHOES_X2’, 25.25, 2, ‘2023-10-17 12:30:00’, ‘2023-08-17 13:00:00’),
(4, 1003, ‘HAT_Z112’, 60.75, 1, ‘2023-10-20 14:00:00’, ‘2023-08-20 15:00:00’),
(5, 1002, ‘WATCH_X001’, 90.00, 0, ‘2023-10-28 16:00:00’, None)
]

for record in mock_data:
cursor.execute(‘’’
INSERT INTO orders (id, customer_id, product_id, price, status, create_time, pay_time)
VALUES (?, ?, ?, ?, ?, ?, ?)
‘’', record)

提交事务

conn.commit()

def ask_database(query):
cursor.execute(query)
records = cursor.fetchall()
return records

prompt = “上个月的销售额”

prompt = “统计每月每件商品的销售额”

prompt = “哪个用户消费最高?消费多少?”

messages = [
{“role”: “system”, “content”: “基于 order 表回答用户问题”},
{“role”: “user”, “content”: prompt}
]
response = get_sql_completion(messages)
if response.content is None:
response.content = “”
messages.append(response)
print(“Function Calling”)
print(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.arguments
args = 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)

这篇关于通过fu过 Function Calling 查询数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/503372

相关文章

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

C++11的函数包装器std::function使用示例

《C++11的函数包装器std::function使用示例》C++11引入的std::function是最常用的函数包装器,它可以存储任何可调用对象并提供统一的调用接口,以下是关于函数包装器的详细讲解... 目录一、std::function 的基本用法1. 基本语法二、如何使用 std::function

AutoGen Function Call 函数调用解析(一)

目录 一、AutoGen Function Call 1.1 register_for_llm 注册调用 1.2 register_for_execution 注册执行 1.3 三种注册方法 1.3.1 函数定义和注册分开 1.3.2 定义函数时注册 1.3.3  register_function 函数注册 二、实例 本文主要对 AutoGen Function Call

(function() {})();只执行一次

测试例子: var xx = (function() {     (function() { alert(9) })(); alert(10)     return "yyyy";  })(); 调用: alert(xx); 在调用的时候,你会发现只弹出"yyyy"信息,并不见弹出"10"的信息!这也就是说,这个匿名函数只在立即调用的时候执行一次,这时它已经赋予了给xx变量,也就是只是

js私有作用域(function(){})(); 模仿块级作用域

摘自:http://outofmemory.cn/wr/?u=http%3A%2F%2Fwww.phpvar.com%2Farchives%2F3033.html js没有块级作用域,简单的例子: for(var i=0;i<10;i++){alert(i);}alert(i); for循环后的i,在其它语言像c、java中,会在for结束后被销毁,但js在后续的操作中仍然能访

Win32函数调用约定(Calling Convention)

平常我们在C#中使用DllImportAttribute引入函数时,不指明函数调用约定(CallingConvention)这个参数,也可以正常调用。如FindWindow函数 [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]public static extern IntPtr FindWindow

rtklib.h : RTKLIB constants, types and function prototypes 解释

在 RTKLIB 中,rtklib.h 是一个头文件,包含了与 RTKLIB 相关的常量、类型和函数原型。以下是该头文件的一些常见内容和翻译说明: 1. 常量 (Constants) rtklib.h 中定义的常量通常包括: 系统常量: 例如,GPS、GLONASS、GALILEO 等系统的常量定义。 时间常量: 如一年、一天的秒数等。 精度常量: 如距离、速度的精度标准。 2. 类型

【AI大模型应用开发】2.1 Function Calling连接外部世界 - 入门与实战(1)

Function Calling是大模型连接外部世界的通道,目前出现的插件(Plugins )、OpenAI的Actions、各个大模型平台中出现的tools工具集,其实都是Function Calling的范畴。时下大火的OpenAI的GPTs,原理就是使用了Function Calling,例如联网检索、code interpreter。 本文带大家了解下Function calling,看

Vite + Vue3 +Vant4出现Toast is not a function

今天写前端的时候出现了这个问题搞了我一会 搜集原因: 1:是vant版本的问题,Toast()的方法是vant3版本的写法,而我用的是vant4,vant4中的写法改成了showToast()方法,改正过来 import {showToast} from "vant";  发现还是报错,说是找不到对应的样式文件 2:Vant 从 4.0 版本开始不再支持 babel-plugin-i

Ollama Qwen2 支持 Function Calling

默认 Ollama 中的 Qwen2 模型不支持 Function Calling,使用默认 Qwen2,Ollama 会报错。本文将根据官方模板对 ChatTemplate 进行改进,使得Qwen2 支持 Tools,支持函数调用。 Ollama 会检查对话模板中是否存在 Tools,如果不存在就会报错,下面的代码是 Ollama 解析模板的代码。 Ollama 3.1 是支持 Tools