上篇文章我们学习了Function Calling的基本用法,本文我们更近一步,学习下怎样利用Function Calling将大模型与数据库打通。
知识背景:我算是对数据库的SQL语句很不熟悉,只会简单的单表操作,还不熟练,每次都得查半天。现在有了大模型应用,有了Function Calling,再也不用查半天资料才写一个SQL了,还能熟练地用多表查询了!
本文实战案例来自知乎的AGI课程。
0. 封装数据库查询接口
还是先本地定义一个查询数据库的接口,该接口接收SQL数据库操作语句,然后调用执行。
python代码解读复制代码# 创建数据库连接
import sqlite3
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
def ask_database(query):
cursor.execute(query)
records = cursor.fetchall()
return records
1. 数据库的Functions怎么定义
示例代码:
python代码解读复制代码
# 描述数据库表结构
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 -- 支付时间,可以为空
);
"""
def get_sql_completion(messages, model="gpt-3.5-turbo-1106"):
response = openai.chat.completions.create(
model=model,
messages=messages,
temperature=0, # 模型输出的随机性,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":