Skip to content

Instantly share code, notes, and snippets.

@edelprino
Last active February 9, 2024 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edelprino/6f8ecd724f09cde0eb19e3fc7f12fa65 to your computer and use it in GitHub Desktop.
Save edelprino/6f8ecd724f09cde0eb19e3fc7f12fa65 to your computer and use it in GitHub Desktop.
from openai import OpenAI
import json
client = OpenAI(api_key="***************************")
SQL_MANAGER_PROMPT = """
You are the best SQL expert in the world and I need your help.
I want you to execute the request I will make from human language to a syntactically correct SQL query for MySQL 5.7.
Below I will provide you with the description of the tables so that you can understand which fields are being talked about in the request and produce correct queries:
Table `events`:
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| playhead | int(10) unsigned | NO | | NULL | |
| payload | longtext | NO | | NULL | |
| type | longtext | NO | | NULL | |
| recorded_on | varchar(32) | NO | | NULL | |
+-------------+------------------+------+-----+---------+----------------+
Use the tool "execute_query" for executing the query on the database
"""
def execute_query(query: str) -> str:
return "Query result for " + query
def sql_query_manager(request: str) -> str:
try:
response = client.chat.completions.create(
model="gpt-4-1106-preview",
messages=[{"role": "system", "content": SQL_MANAGER_PROMPT}, {"role": "user", "content": request}],
tools=[{
"type": "function",
"function": {
"name": "execute_query",
"description": "Execute query on mysql database",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The query to execute on mysql database"},
},
"required": ["query"]
}
}
}]
)
print(response)
if response.choices[0].finish_reason == "tool_calls":
print(response.choices[0].message.tool_calls[0].function.arguments)
arguments = json.loads(response.choices[0].message.tool_calls[0].function.arguments)
return execute_query(arguments["query"])
return response.choices[0].message.content
except Exception as e:
return f"There was an error: {e}"
print(sql_query_manager("Extract all events of type `ItemAdded` in the first week of November 2023."))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment