Git Product home page Git Product logo

Comments (3)

dosubot avatar dosubot commented on June 29, 2024 2

To store chat sessions in a PostgreSQL table with a chat_session_id, retrieve the data back from the table, convert it into a List[ChatMessage] in Python, and pass the retrieved data to your ContextChatEngine, you can follow these steps:

  1. Define the PostgreSQL table schema:

    CREATE TABLE chat_sessions (
        chat_session_id SERIAL PRIMARY KEY,
        session_key VARCHAR(255) NOT NULL,
        message JSONB NOT NULL
    );
  2. Implement the methods in Python:

    import psycopg2
    from typing import List
    from llama_index.legacy.llms import ChatMessage
    from llama_index.legacy.storage.chat_store.base import BaseChatStore
    
    class PostgresChatStore(BaseChatStore):
        def __init__(self, db_config):
            self.conn = psycopg2.connect(**db_config)
            self.cursor = self.conn.cursor()
    
        def set_messages(self, key: str, messages: List[ChatMessage]) -> None:
            self.cursor.execute("DELETE FROM chat_sessions WHERE session_key = %s", (key,))
            for message in messages:
                self.cursor.execute(
                    "INSERT INTO chat_sessions (session_key, message) VALUES (%s, %s)",
                    (key, message.to_json())
                )
            self.conn.commit()
    
        def get_messages(self, key: str) -> List[ChatMessage]:
            self.cursor.execute("SELECT message FROM chat_sessions WHERE session_key = %s", (key,))
            rows = self.cursor.fetchall()
            return [ChatMessage.from_json(row[0]) for row in rows]
    
        def add_message(self, key: str, message: ChatMessage) -> None:
            self.cursor.execute(
                "INSERT INTO chat_sessions (session_key, message) VALUES (%s, %s)",
                (key, message.to_json())
            )
            self.conn.commit()
    
        def delete_messages(self, key: str) -> Optional[List[ChatMessage]]:
            messages = self.get_messages(key)
            self.cursor.execute("DELETE FROM chat_sessions WHERE session_key = %s", (key,))
            self.conn.commit()
            return messages
    
        def delete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
            messages = self.get_messages(key)
            if idx < len(messages):
                message = messages.pop(idx)
                self.set_messages(key, messages)
                return message
            return None
    
        def delete_last_message(self, key: str) -> Optional[ChatMessage]:
            messages = self.get_messages(key)
            if messages:
                message = messages.pop()
                self.set_messages(key, messages)
                return message
            return None
    
        def get_keys(self) -> List[str]:
            self.cursor.execute("SELECT DISTINCT session_key FROM chat_sessions")
            rows = self.cursor.fetchall()
            return [row[0] for row in rows]
    
    # Example usage
    db_config = {
        'dbname': 'your_db',
        'user': 'your_user',
        'password': 'your_password',
        'host': 'your_host',
        'port': 'your_port'
    }
    
    chat_store = PostgresChatStore(db_config)
    chat_engine = ContextChatEngine(chat_store)
  3. Pass the retrieved data to ContextChatEngine:

    session_key = 'example_session_key'
    messages = chat_store.get_messages(session_key)
    chat_engine.process_messages(messages)

This code sets up a PostgreSQL-backed chat store, retrieves chat messages, converts them into List[ChatMessage], and passes them to the ContextChatEngine [1][2].

To continue talking to Dosu, mention @dosu.

from llama_index.

logan-markewich avatar logan-markewich commented on June 29, 2024 1

@SiddharthMurjani you can convert your chat history to json / string, then store it wherever you need

Something like

chat_history_dicts = [x.dict() for x in chat_engine.chat_history]
chat_history_blob = json.dumps(chat_history_dicts)

chat_history_dicts = json.loads(chat_history_blob)
chat_history = [ChatHistory.parse_obj(x) for x in chat_history_dicts]

chat_engine.chat("Hello", chat_history=chat_history)

from llama_index.

SiddharthMurjani avatar SiddharthMurjani commented on June 29, 2024

Thankyou @logan-markewich !

from llama_index.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.