如何将 chatgpt 连接到 mysql 数据库并让它能够解析数据并给我一个连贯的响应?

问题描述 投票:0回答:0

我已经设法将 mySQL 数据库和 chatGPT 连接到同一个地方,但我似乎无法让机器人解析数据库中的数据并学习?是因为 mysql 数据的结构方式吗?该数据库是一个只有杂货商品和价格的虚拟数据库,像“商品 x 的价格是多少”这样的简单任务似乎会迫使机器人退回到其默认设置并放弃数据库。

我已确认数据库已连接,我正在尝试通过 gpt 3.5 turbo 运行它。代码看起来有点像这样:

def get_chat_response(user_input):
    messages.append({"role": "user", "content": user_input})
    response = openai.ChatCompletion.create(
         model = "gpt-3.5-turbo",
        messages = messages
     )
    ChatGPT_reply = response["choices"][0]["message"]["content"]
    messages.append({"role": "assistant", "content": ChatGPT_reply})
    return ChatGPT_reply


def execute_sql_query(query):
        try:
            with conn.cursor() as cursor:
                cursor.execute(query)
                results = cursor.fetchmany(10)
                return results
        except Exception as e:
            print(f"Error executing SQL query: {e}")
            return None

count_query = "SELECT name, price FROM tesco.groceries"
prompt = "What would you like to know about the grocery list?"
user_input = input(prompt)
if "price" in user_input and "name" in user_input:
    item_name = user_input.split()[-1]
    query = f"SELECT price FROM tesco.groceries WHERE name LIKE '%{item_name}%'"
    results = execute_sql_query(query)
    if results:
        price = results[0]["price"]
        response = f"The price of {item_name} is {price}."
    else:
        response = f"Sorry, I couldn't find the price of {item_name}."
elif "suggest" in user_input:
    query = f"SELECT name, price FROM tesco.groceries WHERE name LIKE '%{user_input}%'"
    results = execute_sql_query(query)
    item_names = [f"{r[0]} ({r[1]})".lower() for r in results]
    prompt = "Here are some items you can ask me about:\n" + "\n".join(item_names[:5])
    response = get_chat_response(prompt)
else:
    response = "I'm sorry, I'm not sure what you're asking. Please try asking again with a different question."
print(response)

无论我问什么,它都默认为“对不起,我不确定你在问什么。请换个问题再问一次。”

mySQL 中的数据以典型的“名称”、“价格”为标题,相应的数据为行。

python mysql chatgpt-api
© www.soinside.com 2019 - 2024. All rights reserved.