Grit
  • Welcome
  • gritholdings SDK
    • API Reference
    • Collection of Useful Prompts
  • Evaluation
    • Evaluators
  • Concepts
  • LangChain
  • LangGraph
  • Agent Architectures
    • Planner-Worker-Solver
  • Prompt Management
  • Memory
  • Guardrails
  • Others
    • AWS
      • AWS CDK
    • Migrating a Service to Docker
    • React
    • Salesforce
      • Object Reference
      • Writing Apex
      • Experience Cloud
    • Grit API Reference
    • Style Guide for Documentation and User Interface Text
Powered by GitBook
On this page
  • Saving Memory
  • Getting Memory

Memory

Saving Memory

This example shows inserting and updating a list to a memory.

from langgraph.store.memory import InMemoryStore
...
in_memory_store = InMemoryStore()
namespace_for_memory = (thread_id, "memories")
if not in_memory_store.get(namespace_for_memory, thread_id):
    in_memory_store.put(namespace_for_memory, thread_id, {})
if 'conversation_history' not in in_memory_store.get(
        namespace_for_memory, thread_id).value:
    in_memory_store.put(
        namespace_for_memory, thread_id, {'conversation_history': []})
conversation_history = in_memory_store.get(
    namespace_for_memory, thread_id).value['conversation_history']
new_message_list = []
new_message_list.append(f'user,{new_message}')
new_message_list.append(f'assistant,{gathered.content}')
memory = {'conversation_history': conversation_history + new_message_list}
in_memory_store.put(namespace_for_memory, thread_id, memory)

Getting Memory

namespace_for_memory = (thread_id, "memories")
memories_str = ''
memories = in_memory_store.get(namespace_for_memory, thread_id)
if memories and 'conversation_history' in memories.value:
    conversation_history = memories.value['conversation_history']
    memories_str += '<conversation_history>\n'
    for i, conversation_item in enumerate(conversation_history):
        role, text = conversation_item.split(',', 1)
        memories_str += f'<{role} index="{i}">{text}</{role}>\n'
    memories_str += '</conversation_history>\n\n'
PreviousPrompt ManagementNextGuardrails

Last updated 3 months ago