llama_index 我想将聊天记录存储在本地安装的PostgreSQL中,

o8x7eapl  于 4个月前  发布在  PostgreSQL
关注(0)|答案(3)|浏览(112)

问题验证

  • 我已经在文档和discord上寻找答案。

问题

所以,我正在尝试创建一个执行不同公司文档的RAG的聊天机器人。
我想使用chat_session_id将chat_session存储在postgres表中。
此外,当我从表中检索数据回来时,我希望将其转换为

[List[ChatMessage]]

,并将其传递给我的ContextChatEngine

chat_engine = ContextChatEngine.from_defaults(
        memory=memory,
        retriever=index.as_retriever(),
    )

nnt7mjpx

nnt7mjpx1#

SiddharthMurjani,你可以将聊天记录转换为json/字符串格式,然后将其存储在你需要的地方。
例如:

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)
mpgws1up

mpgws1up2#

感谢@logan-markewich!

sg3maiej

sg3maiej3#

将聊天会话存储在具有 chat_session_id 的PostgreSQL表中,从表中检索数据并将其转换为Python中的 List[ChatMessage] ,然后将检索到的数据传递给您的 ContextChatEngine ,您可以按照以下步骤操作:

  1. 定义PostgreSQL表模式:
CREATE TABLE chat_sessions (
    chat_session_id SERIAL PRIMARY KEY,
    session_key VARCHAR(255) NOT NULL,
    message JSONB NOT NULL
);
  1. 在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)
  1. 将检索到的数据传递给 ContextChatEngine:
session_key = 'example_session_key'
messages = chat_store.get_messages(session_key)
chat_engine.process_messages(messages)

此代码设置了一个基于PostgreSQL的聊天存储,检索聊天消息,将它们转换为 List[ChatMessage] ,并将它们传递给 ContextChatEngine1(https://github.com/run-llama/llama_index/blob/main/llama-index-legacy/llama_index/legacy/storage/chat_store/base.py)2(https://github.com/run-llama/llama_index/blob/main/llama-index-legacy/llama_index/legacy/storage/chat_store/simple_chat_store.py)。

  • 要继续与 Dosu 交谈,请提及 @dosu。*

相关问题