Link to conceptual doc (#2641)

This commit is contained in:
William FH
2024-12-05 00:21:01 +00:00
committed by GitHub
parent f028984b2e
commit cd875291ad
13 changed files with 151 additions and 37 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -111,8 +111,8 @@ from langgraph_sdk import get_client
async def search_store():
client = get_client()
results = await client.store.search(
namespace=("memory", "facts"),
results = await client.store.search_items(
("memory", "facts"),
query="your search query",
limit=3 # number of results to return
)
+3
View File
@@ -236,6 +236,9 @@ Different applications require various types of memory. Although the analogy isn
[Semantic memory](https://en.wikipedia.org/wiki/Semantic_memory), both in humans and AI agents, involves the retention of specific facts and concepts. In humans, it can include information learned in school and the understanding of concepts and their relationships. For AI agents, semantic memory is often used to personalize applications by remembering facts or concepts from past interactions.
> Note: Not to be confused with "semantic search" which is a technique for finding similar content using "meaning" (usually as embeddings). Semantic memory is a term from psychology, referring to storing facts and knowledge, while semantic search is a method for retrieving information based on meaning rather than exact matches.
#### Profile
Semantic memories can be managed in different ways. For example, memories can be a single, continuously updated "profile" of well-scoped and specific information about a user, organization, or other entity (including the agent itself). A profile is generally just a JSON document with various key-value pairs you've selected to represent your domain.
+1
View File
@@ -120,6 +120,7 @@ These guides show how to use the prebuilt ReAct agent:
- [How to add a custom system prompt to a ReAct agent](create-react-agent-system-prompt.ipynb)
- [How to add human-in-the-loop processes to a ReAct agent](create-react-agent-hitl.ipynb)
- [How to create prebuilt ReAct agent from scratch](react-agent-from-scratch.ipynb)
- [How to add semantic search for long-term memory to a ReAct agent](memory/semantic-search.ipynb#using-in-create-react-agent)
## LangGraph Platform
+136 -27
View File
@@ -8,12 +8,15 @@
"\n",
"This guide shows how to enable semantic search in your agent's memory store. This lets search for items in the store by semantic similarity.\n",
"\n",
"!!! tip Prerequisites\n",
" This guide assumes familiarity with the [memory in LangGraph](https://langchain-ai.github.io/langgraph/concepts/memory/).\n",
"\n",
"First, install this guide's prerequisites."
]
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
@@ -23,7 +26,7 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
@@ -48,9 +51,18 @@
},
{
"cell_type": "code",
"execution_count": 25,
"execution_count": 2,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/ipykernel_83572/2318027494.py:5: LangChainBetaWarning: The function `init_embeddings` is in beta. It is actively being worked on, so the API may change.\n",
" embeddings = init_embeddings(\"openai:text-embedding-3-small\")\n"
]
}
],
"source": [
"from langchain.embeddings import init_embeddings\n",
"from langgraph.store.memory import InMemoryStore\n",
@@ -74,7 +86,7 @@
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
@@ -95,7 +107,7 @@
},
{
"cell_type": "code",
"execution_count": 27,
"execution_count": 4,
"metadata": {},
"outputs": [
{
@@ -122,12 +134,73 @@
"source": [
"## Using in your agent\n",
"\n",
"Add semantic search to any node by injecting the store:"
"Add semantic search to any node by injecting the store."
]
},
{
"cell_type": "code",
"execution_count": 40,
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What are you in the mood for? Since you love Italian food and pizza, would you like to order a pizza or try making one at home?"
]
}
],
"source": [
"from typing import Optional\n",
"\n",
"from langchain.chat_models import init_chat_model\n",
"from langgraph.store.base import BaseStore\n",
"\n",
"from langgraph.graph import START, MessagesState, StateGraph\n",
"\n",
"llm = init_chat_model(\"openai:gpt-4o-mini\")\n",
"\n",
"\n",
"def chat(state, *, store: BaseStore):\n",
" # Search based on user's last message\n",
" items = store.search(\n",
" (\"user_123\", \"memories\"), query=state[\"messages\"][-1].content, limit=2\n",
" )\n",
" memories = \"\\n\".join(item.value[\"text\"] for item in items)\n",
" memories = f\"## Memories of user\\n{memories}\" if memories else \"\"\n",
" response = llm.invoke(\n",
" [\n",
" {\"role\": \"system\", \"content\": f\"You are a helpful assistant.\\n{memories}\"},\n",
" *state[\"messages\"],\n",
" ]\n",
" )\n",
" return {\"messages\": [response]}\n",
"\n",
"\n",
"builder = StateGraph(MessagesState)\n",
"builder.add_node(chat)\n",
"builder.add_edge(START, \"chat\")\n",
"graph = builder.compile(store=store)\n",
"\n",
"for message, metadata in graph.stream(\n",
" input={\"messages\": [{\"role\": \"user\", \"content\": \"I'm hungry\"}]},\n",
" stream_mode=\"messages\",\n",
"):\n",
" print(message.content, end=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using in `create_react_agent`\n",
"\n",
"Add semantic search to your tool calling agent by injecting the store in the `state_modifier`. You can also use the store in a tool to let your agent manually store or search for memories."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
@@ -142,7 +215,7 @@
"from langgraph.prebuilt import create_react_agent\n",
"\n",
"\n",
"def add_memories(state, *, store: BaseStore):\n",
"def prepare_messages(state, *, store: BaseStore):\n",
" # Search based on user's last message\n",
" items = store.search(\n",
" (\"user_123\", \"memories\"), query=state[\"messages\"][-1].content, limit=2\n",
@@ -154,6 +227,7 @@
" ] + state[\"messages\"]\n",
"\n",
"\n",
"# You can also use the store directly within a tool!\n",
"def upsert_memory(\n",
" content: str,\n",
" *,\n",
@@ -161,6 +235,7 @@
" store: Annotated[BaseStore, InjectedToolArg],\n",
"):\n",
" \"\"\"Upsert a memory in the database.\"\"\"\n",
" # The LLM can use this tool to store a new memory\n",
" mem_id = memory_id or uuid.uuid4()\n",
" store.put(\n",
" (\"user_123\", \"memories\"),\n",
@@ -173,26 +248,28 @@
"agent = create_react_agent(\n",
" init_chat_model(\"openai:gpt-4o-mini\"),\n",
" tools=[upsert_memory],\n",
" state_modifier=add_memories,\n",
" # The state_modifier is run to prepare the messages for the LLM. It is called\n",
" # right before each LLM call\n",
" state_modifier=prepare_messages,\n",
" store=store,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 44,
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What are you in the mood for? Since you love Italian food and pizza, would you like some recommendations for a delicious pizza or a different Italian dish?"
"What are you in the mood for? Since you love Italian food and pizza, maybe something in that realm would be great! Would you like suggestions for a specific dish or restaurant?"
]
}
],
"source": [
"async for message, metadata in agent.astream(\n",
"for message, metadata in agent.stream(\n",
" input={\"messages\": [{\"role\": \"user\", \"content\": \"I'm hungry\"}]},\n",
" stream_mode=\"messages\",\n",
"):\n",
@@ -212,9 +289,31 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 8,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Expect mem 2\n",
"Item: mem2; Score (0.5895009051396596)\n",
"Memory: Ate alone at home\n",
"Emotion: felt a bit lonely\n",
"\n",
"Expect mem1\n",
"Item: mem1; Score (0.6207546534134083)\n",
"Memory: Had pizza with friends at Mario's\n",
"Emotion: felt happy and connected\n",
"\n",
"Expect random lower score (ravioli not indexed)\n",
"Item: mem1; Score (0.2686278787315685)\n",
"Memory: Had pizza with friends at Mario's\n",
"Emotion: felt happy and connected\n",
"\n"
]
}
],
"source": [
"# Configure store to embed both memory content and emotional context\n",
"store = InMemoryStore(\n",
@@ -276,7 +375,7 @@
},
{
"cell_type": "code",
"execution_count": 57,
"execution_count": 9,
"metadata": {},
"outputs": [
{
@@ -284,12 +383,12 @@
"output_type": "stream",
"text": [
"Expect mem1\n",
"Item: mem1; Score (0.3374698138722726)\n",
"Item: mem1; Score (0.3374968677940555)\n",
"Memory: I love spicy food\n",
"Context: At a Thai restaurant\n",
"\n",
"Expect mem2\n",
"Item: mem2; Score (0.3679447999059255)\n",
"Item: mem2; Score (0.36784461593247436)\n",
"Memory: The restaurant was too loud\n",
"Context: Dinner at an Italian place\n",
"\n"
@@ -353,9 +452,26 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 10,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Expect mem1\n",
"Item: mem1; Score (0.32269984224327286)\n",
"Memory: I love chocolate ice cream\n",
"Type: preference\n",
"\n",
"Expect low score (mem2 not indexed)\n",
"Item: mem1; Score (0.010241633698527089)\n",
"Memory: I love chocolate ice cream\n",
"Type: preference\n",
"\n"
]
}
],
"source": [
"store = InMemoryStore(index={\"embed\": embeddings, \"dims\": 1536, \"fields\": [\"memory\"]})\n",
"\n",
@@ -390,13 +506,6 @@
" print(f\"Memory: {r.value['memory']}\")\n",
" print(f\"Type: {r.value['type']}\\n\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
+2 -2
View File
@@ -43,7 +43,7 @@
"outputs": [],
"source": [
"%%capture --no-stderr\n",
"%pip install -U langgraph langchain_anthropic langsmith\n",
"%pip install -U langgraph langchain_anthropic langsmith langchain-community\n",
"%pip install -U sklearn langchain_openai"
]
},
@@ -632,7 +632,7 @@
"metadata": {},
"outputs": [],
"source": [
"from langchain.cache import InMemoryCache\n",
"from langchain_community.cache import InMemoryCache\n",
"from langchain.globals import set_llm_cache\n",
"\n",
"# Optional. If you are running into errors or rate limits and want to avoid repeated computation,\n",