Comments (3)
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:
-
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 );
-
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)
-
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.
@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.
Thankyou @logan-markewich !
from llama_index.
Related Issues (20)
- [Bug]: TypeError: ColbertIndex._build_index_from_nodes() got an unexpected keyword argument 'index_name' HOT 3
- [Question]: Getting corresponding retrieved document information (metadata, text...) from a KnowledgeGraphRAGRetriever Query HOT 8
- [Question]: Where do I calculate the similarity between nodes in query and vector db when using faiss? HOT 1
- [Bug]: model_name vs. model in BedrockEmbedding doesn't throw an error HOT 2
- [Bug]: Perplexity LLM integration incorrectly recognizes chat model as a completion model HOT 1
- [Bug]: poetry version incompatibility between llama-index and core HOT 3
- [Question]: How do I load a KnowledgeGraphIndex from an existing Neptune Knowledge Graph without from_documents()? HOT 4
- [Bug]: FunctionCallingProgram ignores tool_choice parameter HOT 2
- [Bug]: Example for JSONalyze Query Engine fails with OperationalError: near "sql": syntax error HOT 3
- Inconsistent Embedding Reuse Behavior in VectorStoreIndex with DenseXRetrievalPack HOT 1
- [Question]: Benchmarking time it takes to chunk , embed documents , insert into vector database HOT 1
- [Question]: Inconsistency in Node Usage Between ElasticSearch and ChromaDB for VectorStoreIndex in Dense_x Retrieval HOT 2
- [Question]: multiple-PDF with local LLM llama3 HOT 2
- Multi Document Retriever not retrieving all information HOT 7
- [Bug]: ElasticSearch Vector Store : Timeout context manager should be used inside a task HOT 2
- [Bug]: KnowledgeGraphIndex.from_documents ignoring set llm HOT 8
- [Question]: How were the prompts and scoring logic define for AnswerRelevancyEvaluator, ContextRelevancyEvaluator, AnswerRelevancyEvaluator and FaithfulnessEvaluator HOT 1
- [Feature Request]: Opensearch efficient filtering HOT 1
- [Question]: Index created from a LanceDBVectorStore is not returning all nodes? HOT 11
- [Bug]: HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from llama_index.