File size: 2,131 Bytes
9a19c9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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