43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
|
import os
|
||
|
from mysql.connector import connect, Error
|
||
|
import logging
|
||
|
|
||
|
# Configure logging
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
def log_prompt_to_db(userid: str | None, ip: str, prompt: str, answer: str):
|
||
|
"""
|
||
|
Logs the user's prompt and the corresponding response to the database.
|
||
|
|
||
|
Args:
|
||
|
userid (str | None): User ID (optional, can be None).
|
||
|
ip (str): Client's IP address.
|
||
|
prompt (str): Full conversation history provided by the user.
|
||
|
answer (str): Response generated by the AI.
|
||
|
"""
|
||
|
try:
|
||
|
# Connect to the database using environment variables
|
||
|
connection = connect(
|
||
|
host=os.getenv("DB_HOST"),
|
||
|
port=int(os.getenv("DB_PORT", "3306")),
|
||
|
user=os.getenv("DB_USER"),
|
||
|
password=os.getenv("DB_PASSWORD"),
|
||
|
database=os.getenv("DB_NAME")
|
||
|
)
|
||
|
cursor = connection.cursor()
|
||
|
|
||
|
# SQL query to insert data
|
||
|
query = """
|
||
|
INSERT INTO user_prompts (userid, ip, prompt, answer)
|
||
|
VALUES (%s, %s, %s, %s)
|
||
|
"""
|
||
|
values = (userid, ip, prompt, answer)
|
||
|
cursor.execute(query, values)
|
||
|
|
||
|
# Commit the transaction and close resources
|
||
|
connection.commit()
|
||
|
cursor.close()
|
||
|
connection.close()
|
||
|
|
||
|
except Error as e:
|
||
|
logger.error(f"Error logging prompt to database: {e}")
|