当前位置:   article > 正文

通过 ChatGPT 的 Function Call 查询数据库

通过 ChatGPT 的 Function Call 查询数据库

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57337?site
推荐阅读
相关标签
  

闽ICP备14008679号