Spaces:
Sleeping
Sleeping
from langchain_openai import OpenAI | |
import os | |
import time | |
from langchain.cache import SQLAlchemyCache | |
from sqlalchemy import Column, Computed, Index, Integer, Sequence, String, create_engine | |
from sqlalchemy.orm import sessionmaker, declarative_base | |
from datetime import datetime | |
#load postgres engine | |
engine = create_engine("postgresql://postgres:sampath@localhost:5432/postgres") | |
Base = declarative_base() | |
class FeedBackCache(Base): | |
"""Postgres table for fulltext-indexed LLM Cache""" | |
__tablename__ = "veda_bot_feedback" | |
id = Column(Integer, Sequence("cache_id"), primary_key=True) | |
user_message = Column(String, nullable=True) | |
assistant_message = Column(String, nullable=True) | |
feedback_score = Column(String, nullable=True) | |
feedback_text = Column(String, nullable=True) | |
# Create the table in the database | |
Base.metadata.create_all(engine) | |
def write_to_db(u_message, a_message, f_score, f_text): | |
try: | |
# Create a sessionmaker bound to the engine | |
Session = sessionmaker(bind=engine) | |
# Create a session | |
session = Session() | |
message = FeedBackCache( | |
user_message=u_message["content"], | |
assistant_message=a_message["content"], | |
feedback_score=f_score, | |
feedback_text=f_text | |
) | |
# Add the instance to the session | |
session.add(message) | |
# Commit the session to persist the changes to the database | |
session.commit() | |
print("Feedback written to DB successfully!") | |
except Exception as e: | |
# If an error occurs, rollback the session and print the error message | |
session.rollback() | |
print("Error occurred while writing feedback to DB:", e) | |
finally: | |
# Close the session | |
session.close() | |
def current_time() -> str: | |
"""Return the current time as a string. Used as part of the session UUID.""" | |
# Get current date and time | |
current_datetime = datetime.now() | |
# Convert to a long number format | |
datetime_string = current_datetime.strftime("%Y%m%d%H%M%S") | |
return datetime_string |