Added a SQL-Validity Check

This commit is contained in:
crennis 2023-05-04 11:33:42 +02:00
parent feb8530438
commit d72a0863a3

View File

@ -6,6 +6,7 @@ class AI:
self.api_key = api_key
openai.api_key = self.api_key
self.convertlog = []
self.response = None
def humantosql(self, text: str, dbtype: str, tableschema: list) -> str:
if not self.convertlog:
@ -13,15 +14,22 @@ class AI:
prompt = {"role": "user", "content": text}
self.convertlog.append(prompt)
response = openai.ChatCompletion.create(
self.response = openai.ChatCompletion.create(
model="gpt-4",
messages=self.convertlog
)
response = response['choices'][0]['message']['content']
self.convertlog.append({"role": "system", "content": response})
self.response = self.response['choices'][0]['message']['content']
self.convertlog.append({"role": "assistant", "content": self.response})
if self.validate(response):
return response
for i in self.convertlog:
print(i)
# FIXME: After the first validation failed it will always return None
print(self.response)
if self.validate(self.response) is True:
return self.response
else:
self.humantosql("Only answer as a Valid SQL-Statement don't add any additional text", dbtype, tableschema)
@ -40,15 +48,15 @@ class AI:
return response
def validate(self, sql: str) -> bool:
prompt = [{"role": "system", "content": "You check if the User Input is a valid SQL-Statement and only return True or False. Most important: ONLY ANSWER True OR False."},
prompt = [{"role": "system", "content": "You check if the User Input is a valid SQL-Statement. You also return False if there is any kind of text before and after the statement. You only return True or False. Most important: ONLY ANSWER True OR False."},
{"role": "user", "content": sql}]
response = openai.ChatCompletion.create(
valid = openai.ChatCompletion.create(
model="gpt-4",
messages=prompt
)
response = response['choices'][0]['message']['content']
if response == "True":
valid = valid['choices'][0]['message']['content']
if valid == "True":
return True
else:
return False