Skip to content

Commit

Permalink
docs: Updated SQLite example to use LCEL and SQLChatMessageHistory (#…
Browse files Browse the repository at this point in the history
…16094)

- **Description:** Updated the SQLite example integration notebook to
latest standards
- **Issue:**
[15664](#15664)
  - **Dependencies:** None
  - **Twitter handle:** @DaveDeCaprio
  • Loading branch information
DaveDeCaprio authored Jan 17, 2024
1 parent f406dc3 commit 9c2f1f0
Showing 1 changed file with 131 additions and 100 deletions.
231 changes: 131 additions & 100 deletions docs/docs/integrations/memory/sqlite.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -16,172 +16,203 @@
},
{
"cell_type": "code",
"execution_count": 1,
"id": "d0a07a30-028f-4e16-8b11-45b2416f7b0f",
"execution_count": null,
"id": "5c923f56-24a9-4f8f-9b91-138cc025c47e",
"metadata": {},
"outputs": [],
"source": [
"%pip install --upgrade --quiet sqlite3"
"# os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
"# os.environ[\"LANGCHAIN_API_KEY\"] = getpass.getpass()"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "db59b901",
"metadata": {
"id": "2wUMSUoF8ffn"
},
"outputs": [],
"cell_type": "markdown",
"id": "61fda020-23a2-4605-afad-58260535ec8c",
"metadata": {},
"source": [
"from langchain.chains import ConversationChain\n",
"from langchain.memory import ConversationEntityMemory\n",
"from langchain.memory.entity import SQLiteEntityStore\n",
"from langchain.memory.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE\n",
"from langchain_openai import OpenAI"
"## Usage\n",
"\n",
"To use the storage you need to provide only 2 things:\n",
"\n",
"1. Session Id - a unique identifier of the session, like user name, email, chat id etc.\n",
"2. Connection string - a string that specifies the database connection. For SQLite, that string is `slqlite:///` followed by the name of the database file. If that file doesn't exist, it will be created."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "ca6dee29",
"execution_count": 1,
"id": "4576e914a866fb40",
"metadata": {
"id": "8TpJZti99gxV"
"ExecuteTime": {
"end_time": "2023-08-28T10:04:38.077748Z",
"start_time": "2023-08-28T10:04:36.105894Z"
},
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"entity_store = SQLiteEntityStore()\n",
"llm = OpenAI(temperature=0)\n",
"memory = ConversationEntityMemory(llm=llm, entity_store=entity_store)\n",
"conversation = ConversationChain(\n",
" llm=llm,\n",
" prompt=ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n",
" memory=memory,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "f9b4c3a0",
"metadata": {
"id": "HEAHG1L79ca1"
},
"source": [
"Notice the usage of `EntitySqliteStore` as parameter to `entity_store` on the `memory` property."
"from langchain_community.chat_message_histories import SQLChatMessageHistory\n",
"\n",
"chat_message_history = SQLChatMessageHistory(\n",
" session_id=\"test_session_id\", connection_string=\"sqlite:///sqlite.db\"\n",
")\n",
"\n",
"chat_message_history.add_user_message(\"Hello\")\n",
"chat_message_history.add_ai_message(\"Hi\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "297e78a6",
"execution_count": 2,
"id": "b476688cbb32ba90",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 437
"ExecuteTime": {
"end_time": "2023-08-28T10:04:38.929396Z",
"start_time": "2023-08-28T10:04:38.915727Z"
},
"id": "BzXphJWf_TAZ",
"outputId": "de7fc966-e0fd-4daf-a9bd-4743455ea774"
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
"Prompt after formatting:\n",
"\u001b[32;1m\u001b[1;3mYou are an assistant to a human, powered by a large language model trained by OpenAI.\n",
"\n",
"You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n",
"\n",
"You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.\n",
"\n",
"Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.\n",
"\n",
"Context:\n",
"{'Deven': 'Deven is working on a hackathon project with Sam.', 'Sam': 'Sam is working on a hackathon project with Deven.'}\n",
"\n",
"Current conversation:\n",
"\n",
"Last line:\n",
"Human: Deven & Sam are working on a hackathon project\n",
"You:\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"' That sounds like a great project! What kind of project are they working on?'"
"[HumanMessage(content='Hello'), AIMessage(content='Hi')]"
]
},
"execution_count": 3,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conversation.run(\"Deven & Sam are working on a hackathon project\")"
"chat_message_history.messages"
]
},
{
"cell_type": "markdown",
"id": "e400509a-1957-4d1d-bbd6-01e8dc3dccb3",
"metadata": {},
"source": [
"## Chaining\n",
"\n",
"We can easily combine this message history class with [LCEL Runnables](/docs/expression_language/how_to/message_history)\n",
"\n",
"To do this we will want to use OpenAI, so we need to install that. We will also need to set the OPENAI_API_KEY environment variable to your OpenAI key.\n",
"\n",
"```bash\n",
"pip install -U langchain-openai\n",
"\n",
"export OPENAI_API_KEY='sk-xxxxxxx'\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "6558418b-0ece-4d01-9661-56d562d78f7a",
"metadata": {},
"outputs": [],
"source": [
"from typing import Optional\n",
"\n",
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langchain_core.runnables.history import RunnableWithMessageHistory\n",
"from langchain_openai import ChatOpenAI"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "7e71f1dc",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"id": "YsFE3hBjC6gl",
"outputId": "56ab5ca9-e343-41b5-e69d-47541718a9b4"
},
"id": "82149122-61d3-490d-9bdb-bb98606e8ba1",
"metadata": {},
"outputs": [],
"source": [
"prompt = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\"system\", \"You are a helpful assistant.\"),\n",
" MessagesPlaceholder(variable_name=\"history\"),\n",
" (\"human\", \"{question}\"),\n",
" ]\n",
")\n",
"\n",
"chain = prompt | ChatOpenAI()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "2df90853-b67c-490f-b7f8-b69d69270b9c",
"metadata": {},
"outputs": [],
"source": [
"chain_with_history = RunnableWithMessageHistory(\n",
" chain,\n",
" lambda session_id: SQLChatMessageHistory(\n",
" session_id=session_id, connection_string=\"sqlite:///sqlite.db\"\n",
" ),\n",
" input_messages_key=\"question\",\n",
" history_messages_key=\"history\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "0ce596b8-3b78-48fd-9f92-46dccbbfd58b",
"metadata": {},
"outputs": [],
"source": [
"# This is where we configure the session id\n",
"config = {\"configurable\": {\"session_id\": \"<SQL_SESSION_ID>\"}}"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "38e1423b-ba86-4496-9151-25932fab1a8b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Deven is working on a hackathon project with Sam.'"
"AIMessage(content='Hello Bob! How can I assist you today?')"
]
},
"execution_count": 4,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conversation.memory.entity_store.get(\"Deven\")"
"chain_with_history.invoke({\"question\": \"Hi! I'm bob\"}, config=config)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "316f2e8d",
"execution_count": 10,
"id": "2ee4ee62-a216-4fb1-bf33-57476a84cf16",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Sam is working on a hackathon project with Deven.'"
"AIMessage(content='Your name is Bob! Is there anything specific you would like assistance with, Bob?')"
]
},
"execution_count": 5,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"conversation.memory.entity_store.get(\"Sam\")"
"chain_with_history.invoke({\"question\": \"Whats my name\"}, config=config)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b85f8427",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
Expand Down

0 comments on commit 9c2f1f0

Please sign in to comment.