LangChainAvailable
LangChain Integration
Use the Memory Scope API as a memory store in your LangChain applications for persistent, scoped memory that respects user privacy and policy enforcement.
Installation
Install both the Memory Scope SDK and LangChain:
Installation
# Install both SDKs
pip install memory-scope langchain langchain-openaiCustom Memory Store
Create a custom LangChain memory store that uses the Memory Scope API:
Custom Memory Store
from langchain.memory import BaseMemory
from memory_scope import MemoryScopeClient
from memory_scope.exceptions import PolicyDeniedError
from typing import Dict, Any
class MemoryScopeStore(BaseMemory):
"""LangChain memory store using Memory Scope API"""
def __init__(self, user_id: str, api_key: str, scope: str = "conversation"):
super().__init__()
self.user_id = user_id
self.scope = scope
self.client = MemoryScopeClient(api_key=api_key)
self.revocation_token = None
@property
def memory_variables(self) -> list:
"""Return list of memory variable names"""
return ["history", "preferences", "constraints"]
def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
"""Load memory variables from Memory Scope API"""
memory_vars = {
"history": "",
"preferences": "",
"constraints": ""
}
# Load conversation history
try:
result = self.client.read_memory(
user_id=self.user_id,
scope=self.scope,
domain="history",
purpose="load conversation context for LangChain agent"
)
memory_vars["history"] = result.summary_text
self.revocation_token = result.revocation_token
except PolicyDeniedError:
pass
# Load preferences
try:
prefs = self.client.read_memory(
user_id=self.user_id,
scope="preferences",
domain=None,
purpose="load user preferences for LangChain agent"
)
memory_vars["preferences"] = str(prefs.summary_struct)
except PolicyDeniedError:
pass
# Load constraints
try:
constraints = self.client.read_memory(
user_id=self.user_id,
scope="constraints",
domain=None,
purpose="load user constraints for LangChain agent"
)
memory_vars["constraints"] = str(constraints.summary_struct)
except PolicyDeniedError:
pass
return memory_vars
def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
"""Save conversation context to Memory Scope API"""
# Store conversation turn
conversation_data = {
"input": str(inputs.get("input", "")),
"output": str(outputs.get("output", ""))
}
self.client.create_memory(
user_id=self.user_id,
scope=self.scope,
domain="history",
source="langchain_conversation",
value_json=conversation_data
)
def clear(self) -> None:
"""Clear memory by revoking access"""
if self.revocation_token:
self.client.revoke_memory(revocation_token=self.revocation_token)
self.revocation_token = NoneUsage Example
Use the custom memory store with a LangChain agent:
Usage Example
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
# Initialize memory store
memory = MemoryScopeStore(
user_id="user123",
api_key="your-memory-api-key",
scope="conversation"
)
# Initialize LLM
llm = ChatOpenAI(temperature=0, model="gpt-4")
# Define tools
tools = [
Tool(
name="Search",
func=lambda x: f"Search results for: {x}",
description="Search for information"
)
]
# Create agent with memory
agent = initialize_agent(
tools,
llm,
agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
memory=memory,
verbose=True
)
# Use the agent
response = agent.run("What are my food preferences?")
print(response)Storing User Preferences
Extract and store user preferences from conversations:
Extracting Preferences
def extract_and_store_preferences(user_id: str, conversation: str):
"""Extract preferences from conversation and store them"""
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(temperature=0)
# Extract preferences using LLM
prompt = f"""Extract user preferences from this conversation:
{conversation}
Return as JSON with keys: likes, dislikes, preferences.
If no preferences found, return empty dict."""
response = llm.invoke(prompt)
preferences = eval(response.content) # Parse JSON
# Store preferences
if preferences:
memory_client.create_memory(
user_id=user_id,
scope="preferences",
domain="food",
source="conversation_extraction",
value_json=preferences
)Best Practices
- Use appropriate scopes for different types of memory (conversation, preferences, etc.)
- Handle PolicyDeniedError when loading memory variables
- Store revocation tokens to allow users to revoke access
- Use domains to organize conversation history (e.g., by topic)
- Extract and store structured data from conversations
- Respect user constraints when generating responses
Policy Enforcement
The Memory Scope API automatically enforces policies when loading memories. If a purpose is not allowed for a scope, the memory won't be loaded, ensuring privacy compliance.
Related Resources