import os, psycopg2, openai
def query_handler(query = None):
if query is None or query == "":
query = query.strip().replace('\n', ' ')
response = openai.Embedding.create(
engine="text-embedding-ada-002",
embedding = response.data[0].embedding
params = postgresql_url.split(',')
database, user, password, host, port = "test", "test", "test", "127.0.0.1", "5432"
print('POSTGRESQL_URL error: ' + postgresql_url)
k, v = pair[0].strip(), pair[1].strip()
con = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
sql = "select match_chunks(\'[" + ','.join([str(x) for x in embedding]) + "]\', 0.78, 5, 50)"
row = row[0][1:-2].split(',')[-2][1:-2].strip()
content = content + row + "\n---\n"
prompt = '''Pretend you are GPT-4 model , Act an database expert.
I will introduce a database scenario for which you will provide advice and related sql commands.
Please only provide advice related to this scenario. Based on the specific scenario from the documentation,
answer the question only using that information. Please note that if there are any updates to the database
syntax or usage rules, the latest content shall prevail. If you are uncertain or the answer is not explicitly
written in the documentation, please respond with "I'm sorry, I cannot assist with this.\n\n''' + "Context sections:\n" + \
content.strip().replace('\n', ' ') + "\n\nQuestion:\"\"\"" + query.replace('\n', ' ') + "\"\"\"\n\nAnswer:"
print('\n正在处理,请稍后。。。\n')
response = openai.ChatCompletion.create(
{"role": "user", "content": prompt}
print(response['choices'][0]['message']['content'])
os.environ['OPENAI_KEY'] = '-----------------------'
os.environ['POSTGRESQL_URL'] = 'host:127.0.0.1,port:5432,user:test,password:test,database:test'
openai_key = os.getenv('OPENAI_KEY')
postgresql_url = os.getenv('POSTGRESQL_URL')
openai.api_type = "azure"
openai.api_base = "https://example-endpoint.openai.azure.com"
openai.api_version = "2023-XX"
openai.api_key = openai_key
if openai_key is None or postgresql_url is None:
print('Missing environment variable OPENAI_KEY, POSTGRESQL_URL(host:127.XX.XX.XX,port:5432,user:XX,password:XX,database:XX)')
print('我是您的PostgreSQL AI助手,请输入您想查询的问题,例如:\n1、如何创建table?\n2、给我解释一下select语句?\n3、如何创建一个存储过程?')
query = input("\n输入您的问题:")
if __name__ == "__main__":