LangChain Agent SQL memory conversation history using MongoDB

Muhammad Tri Wibowo
1 min readFeb 27, 2024

--

llm = ChatOpenAI(
temperature=0,
streaming=True,
model_name=os.environ.get('LLM_GPT_MODEL', 'gpt-4-1106-preview'),
max_tokens=1000,
timeout=30
)
db = SQLDatabase.from_uri(os.environ['POSTGRES_URI'])
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
mongo_history = MongoDBChatMessageHistory(
connection_string="mongodb+srv://xxx:xxxx@xxxx.xxxx.mongodb.net",
session_id="new_session"
)
conversational_memory = ConversationBufferMemory(
chat_memory=mongo_history
memory_key='history',
return_messages=False
)

suffix = """Begin!

Relevant pieces of previous conversation:
{history}
(You do not need to use these pieces of information if not relevant)

Question: {input}
Thought: I should look at the tables in the database to see what I can query. Then I should query the schema of the most relevant tables.
{agent_scratchpad}"""
agent_executor = create_sql_agent(
toolkit=toolkit,
llm=llm,
agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
suffix = suffix,
input_variables=["input", "agent_scratchpad", "history"],
agent_executor_kwargs={'memory': conversational_memory}
)
Question : Barang apa dengan penjualan tertinggi omsetnya?
Answer : Produk ABC

Question : Berapa total omset barang tersebut?
Answer : 29047943000.0

Question : Berapa jumlah barang tersebut yang terjual?
Answer : 18260936.0

referece :

How to add memory to SQLDatabaseChain? · Issue #6918 · langchain-ai/langchain (github.com)

using MongoDBChatMessageHistory with agent and RetrievalQA throws value is not a valid dict error · Issue #5834 · langchain-ai/langchain (github.com)

--

--

No responses yet