### Quick Start: Initialize and Use DynamoDBStore Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/store/dynamodb/DynamoDBStore.md Initialize the DynamoDBStore with a table name and region, set up the table, and perform basic put and get operations. ```python from langgraph_checkpoint_aws import DynamoDBStore # Create a store instance store = DynamoDBStore(table_name="my-store-table", region_name="us-east-1") # Setup the table (creates it if it doesn't exist) store.setup() # Store and retrieve data store.put(("users", "123"), "prefs", {"theme": "dark"}) item = store.get(("users", "123"), "prefs") print(item.value) # {"theme": "dark"} ``` -------------------------------- ### Install Specific Development Components Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Install specific sets of development tools as needed. ```bash make install_dev # Basic development tools ``` ```bash make install_test # Testing tools ``` ```bash make install_lint # Linting tools ``` ```bash make install_typing # Type checking tools ``` ```bash make install_codespell # Spell checking tools ``` -------------------------------- ### Install Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/checkpoint/dynamodb/README.md Installs project dependencies using uv sync. ```bash # Install dependencies uv sync ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Install all development dependencies for the project. ```bash make install_all ``` -------------------------------- ### Initialize DynamoDBStore Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/dynamodb_store.ipynb Create and setup a DynamoDBStore instance. Ensure AWS credentials are configured. ```python from langgraph_checkpoint_aws import DynamoDBStore # Create a store instance # region_name is required unless AWS_DEFAULT_REGION or AWS_REGION env var is set store = DynamoDBStore(table_name="my-langgraph-store", region_name="us-east-1") # Setup the table (creates it if it doesn't exist) store.setup() ``` -------------------------------- ### Start Valkey Server with Docker Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_cache.ipynb Provides instructions to start a Valkey server using Docker. It also outlines the cache configuration details for host, port, memory, and TTL. ```python print("🐳 Start Valkey with Docker:") print(" docker run --name valkey-cache-demo -p 6379:6379 -d valkey/valkey-bundle:latest") print("\nšŸ”§ Cache Configuration:") print(" • Host: localhost") print(" • Port: 6379") print(" • Memory: In-memory caching for maximum speed") print(" • TTL: Configurable expiration (default: 1 hour)") print("\n⚔ ValkeyCache provides ultra-fast response caching") ``` -------------------------------- ### Verify Package Installation Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_store.ipynb Checks if all essential Langchain and Valkey related packages are installed. Lists any missing packages and provides installation instructions. ```python import sys required_packages = [ 'langchain', 'langchain_aws', 'langchain_core', 'langgraph', 'langgraph_checkpoint_aws', 'valkey' ] print("šŸ” Checking installed packages...\n") missing_packages = [] for package in required_packages: try: __import__(package) print(f"āœ… {package}") except ImportError: print(f"āŒ {package} - NOT INSTALLED") missing_packages.append(package) if missing_packages: print(f"\nāš ļø Missing packages: {', '.join(missing_packages)}") print("\nPlease install them using:") print("pip install valkey langchain-aws langchain langgraph 'langgraph-checkpoint-aws[valkey]' langchain-community") else: print("\nāœ… All required packages are installed!") ``` -------------------------------- ### Start Valkey Docker Container Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Commands to start Valkey using Docker, either with the latest bundle or a custom configuration file. ```bash # Start Valkey with required modules docker run --name valkey-bundle -p 6379:6379 -d valkey/valkey-bundle:latest # Or with custom configuration docker run --name valkey-custom \ -p 6379:6379 \ -v $(pwd)/valkey.conf:/etc/valkey/valkey.conf \ -d valkey/valkey-bundle:latest ``` -------------------------------- ### Install and Import Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_saver.ipynb Install the necessary packages and import the required modules for LangGraph, Valkey, and Amazon Bedrock integration. ```python # Install required packages # Base package with Valkey support: # !pip install 'langgraph-checkpoint-aws[valkey]' # # Or individual packages: # !pip install langchain-aws langgraph langchain valkey orjson import os import getpass from typing import Annotated, Sequence from typing_extensions import TypedDict from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage, RemoveMessage from langchain_aws import ChatBedrockConverse from langgraph.graph import StateGraph, START, END from langgraph.graph.message import add_messages # Import Valkey saver from langgraph_checkpoint_aws import ValkeySaver from valkey import Valkey print("āœ… All dependencies imported successfully!") print("šŸ—„ļø Valkey saver ready for persistent memory") ``` -------------------------------- ### Install Required Packages Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store_async_patterns.ipynb Installs necessary Python packages for using ValkeyStore with LangChain and AWS. ```python # Install required packages # !pip install langgraph-checkpoint-aws langchain-aws boto3 valkey ``` -------------------------------- ### Verify Package Installation Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_saver.ipynb Checks if all required Python packages for the AgentCore Valkey Checkpointer are installed. Lists missing packages and provides installation instructions. ```python import sys required_packages = [ 'langchain', 'langchain_aws', 'langchain_core', 'langgraph', 'langgraph_checkpoint_aws', 'valkey' ] print("šŸ” Checking installed packages...\n") missing_packages = [] for package in required_packages: try: __import__(package) print(f"āœ… {package}") except ImportError: print(f"āŒ {package} - NOT INSTALLED") missing_packages.append(package) if missing_packages: print(f"\nāš ļø Missing packages: {', '.join(missing_packages)}") print("\nPlease install them using:") print("pip install valkey langchain-aws langchain langgraph 'langgraph-checkpoint-aws[valkey]'") else: print("\nāœ… All required packages are installed!") ``` -------------------------------- ### Async ValkeyStore Usage for Data Operations Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Shows how to use an asynchronous ValkeyStore for setting up, putting, and getting data. Includes namespace and key usage. ```python from langgraph_checkpoint_aws import AsyncValkeyStore from datetime import datetime # Async ValkeyStore usage async with AsyncValkeyStore.from_conn_string("valkey://localhost:6379") as store: namespace = ("example",) key = "key" data = { "message": "Sample message", "timestamp": datetime.now().isoformat(), "status": "success" } await store.setup() await store.aput(namespace, key, data) result = await store.aget(namespace, key) ``` -------------------------------- ### Install Required Packages Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_saver.ipynb Installs necessary packages for AgentCore Valkey Checkpointer functionality. Use quotes around the package name for zsh shell. ```bash pip install valkey langchain-aws langchain langgraph 'langgraph-checkpoint-aws[valkey]' ``` -------------------------------- ### Valkey Indexing Performance Configurations Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Example configurations for different performance requirements, including high-speed, high-accuracy, and exact search modes. ```python # High-speed configuration (prioritize speed) speed_config = { "collection_name": "fast_search", "index_type": "hnsw", "hnsw_m": 8, # Fewer connections "hnsw_ef_construction": 100, # Faster construction "hnsw_ef_runtime": 10, # Fast queries } # High-accuracy configuration (prioritize recall) accuracy_config = { "collection_name": "precise_search", "index_type": "hnsw", "hnsw_m": 32, # More connections "hnsw_ef_construction": 400, # Better construction "hnsw_ef_runtime": 50, # More thorough search } # Balanced configuration (good speed/accuracy trade-off) balanced_config = { "collection_name": "balanced_search", "index_type": "hnsw", "hnsw_m": 16, # Default connections "hnsw_ef_construction": 200, # Default construction "hnsw_ef_runtime": 20, # Moderate search width } # Exact search configuration (perfect accuracy) exact_config = { "collection_name": "exact_search", "index_type": "flat", # No HNSW parameters needed } ``` -------------------------------- ### Install Required Packages Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_store.ipynb Installs the necessary Python packages for using Valkey with Langchain and Langgraph. Ensure quotes are used for zsh shell compatibility. ```bash pip install valkey langchain-aws langchain langgraph 'langgraph-checkpoint-aws[valkey]' langchain-community ``` -------------------------------- ### Initialize and invoke ChatBedrockConverse Source: https://github.com/langchain-ai/langchain-aws/blob/main/README.md Example of initializing the Bedrock chat model and invoking it with a prompt. ```python from langchain_aws import ChatBedrockConverse # Initialize the Bedrock chat model model = ChatBedrockConverse( model="us.anthropic.claude-sonnet-4-5-20250929-v1:0" ) # Invoke the model response = model.invoke("Hello! How are you today?") print(response) ``` -------------------------------- ### Install LangGraph with Valkey Support Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_cache.ipynb Install the necessary packages for LangGraph with Valkey support. This includes the base package or individual components. ```python # Install required packages # Base package with Valkey support: # !pip install 'langgraph-checkpoint-aws[valkey]' # # Or individual packages: # !pip install langchain-aws langgraph langchain valkey orjson ``` -------------------------------- ### Quick Setup for AWS Bedrock Chat Source: https://github.com/langchain-ai/langchain-aws/blob/main/llms-full.txt Quickly set up and use the ChatBedrock model for chat interactions. Requires AWS credentials to be configured. ```python from langchain_aws import ChatBedrock # Initialize with Claude 3.5 Sonnet llm = ChatBedrock( model_id="anthropic.claude-3-5-sonnet-20241022-v2:0", region_name="us-east-1", model_kwargs={ "max_tokens": 1000, "temperature": 0.7 } ) # Use it response = llm.invoke("Explain quantum computing in simple terms") print(response.content) ``` -------------------------------- ### Quick Start with DynamoDBSaver Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/checkpoint/dynamodb/README.md Initialize DynamoDBSaver and integrate it with a LangGraph application for state persistence. Ensure your AWS credentials and region are configured. ```python from langgraph_checkpoint_aws import DynamoDBSaver from langgraph.graph import StateGraph # Initialize checkpointer checkpointer = DynamoDBSaver( table_name="my-checkpoints", region_name="us-east-1" ) # Use with LangGraph graph = StateGraph(state_schema) # ... define your graph ... app = graph.compile(checkpointer=checkpointer) # Run with persistence config = {"configurable": {"thread_id": "user-123"}} result = app.invoke(input_data, config) ``` -------------------------------- ### Import Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_saver.ipynb Imports necessary libraries for the AgentCore Valkey Checkpointer example, including time, typing, chat models, tools, agents, and the AgentCoreValkeySaver. ```python import time from typing import Dict, Any from langchain.chat_models import init_chat_model from langchain.tools import tool from langchain.agents import create_agent # Note: If you see a Pylance import error below, it's a false positive. # The import works correctly at runtime - the package is properly installed. from langgraph_checkpoint_aws import AgentCoreValkeySaver print("āœ… All dependencies imported successfully!") ``` -------------------------------- ### Configure and Initialize ValkeyStore Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store.ipynb Sets up a Valkey vector index with optimized HNSW parameters and establishes a connection to the Valkey instance. Requires a running Valkey server and appropriate environment variables. ```python def create_valkey_index_config() -> ValkeyIndexConfig: """Create optimized vector index configuration for enterprise use.""" config: ValkeyIndexConfig = { "collection_name": "enterprise_memory_vectors", "dims": VECTOR_DIMENSION, "embed": embeddings, "distance_metric": "COSINE", "index_type": "HNSW", # Optimized HNSW parameters for enterprise performance "hnsw_m": 32, # Higher M for better recall "hnsw_ef_construction": 400, # Higher ef_construction for better index quality # Searchable fields for hybrid queries "fields": [ "user_id", "memory_type", "importance", "created_at", "updated_at", "content", "tags", "version"] } logger.info(f"āœ… Vector index configuration created: {config["collection_name"]}") logger.info(f"šŸ“ Dimension: {config["dims"]}, Algorithm: {config["index_type"]}") return config valkey_client = None store = None try: # Initialize Valkey client with enterprise configuration valkey_client = valkey.from_url( VALKEY_URL, # Enterprise connection settings socket_connect_timeout=10, socket_timeout=10, retry_on_timeout=True, health_check_interval=30 ) # Test connection valkey_client.ping() logger.info("āœ… Valkey connection established") # Create ValkeyStore with optional vector configuration vector_config = create_valkey_index_config() store = ValkeyStore( valkey_client, ttl={"default_ttl": TTL_SECONDS, "refresh_on_read": True}, index=vector_config ) store.setup() logger.info("āœ… ValkeyStore initialized with vector search") except Exception as e: logger.error(f"āŒ Valkey Client initialization failed: {e}") logger.info("šŸ’” Ensure Valkey is running: docker run -p 6379:6379 -d valkey/valkey") raise ``` -------------------------------- ### Install langchain-agentcore-codeinterpreter Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/agentcore-codeinterpreter/README.md Install the package using pip. This command installs the necessary libraries for integrating with AgentCore Code Interpreter. ```bash pip install langchain-agentcore-codeinterpreter ``` -------------------------------- ### Install langgraph-checkpoint-aws Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/checkpoint/agentcore/README.md Install the package using pip. Ensure Python 3.9+ and compatible versions of langgraph and boto3 are installed. ```bash pip install langgraph-checkpoint-aws ``` -------------------------------- ### Basic ValkeyStore Usage with Index Configuration Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Demonstrates setting up a ValkeyStore with a basic HNSW index configuration, storing documents, and performing a search. Includes default TTL. ```python with ValkeyStore.from_conn_string( "valkey://localhost:6379", index={ "collection_name": "my_documents", "dims": 1536, "embed": embeddings, "fields": ["text", "author"], "timezone": "UTC", "index_type": "hnsw" }, ttl={"default_ttl": 60.0} # 1 hour TTL ) as store: # Setup vector search index store.setup() # Store documents store.put( ("documents", "user123"), "report_1", { "text": "Machine learning report on customer behavior analysis...", "tags": ["ml", "analytics", "report"], "author": "data_scientist" } ) # Search documents results = store.search( ("documents",), query="machine learning customer analysis", filter={"author": "data_scientist"}, limit=10 ) ``` -------------------------------- ### Basic AgentCore Valkey Checkpointer Setup Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/checkpoint/valkey/agentcore/README.md Demonstrates setting up AgentCoreValkeySaver with a connection string and integrating it with a LangGraph agent. Includes session ID, actor ID, and namespace configuration. ```python from langgraph_checkpoint_aws import AgentCoreValkeySaver from langgraph.prebuilt import create_react_agent # Create checkpointer with connection string with AgentCoreValkeySaver.from_conn_string( "valkey://localhost:6379", ttl_seconds=3600, # 1 hour TTL pool_size=10 ) as checkpointer: # Create LangGraph agent graph = create_react_agent( model=llm, tools=tools, checkpointer=checkpointer ) # AgentCore-style configuration config = { "configurable": { "thread_id": "user-session-123", # Session ID "actor_id": "assistant-agent", # Agent/Actor ID (REQUIRED) "checkpoint_ns": "production", # Namespace } } # Use the agent response = graph.invoke({"messages": [...]}, config) ``` -------------------------------- ### Install dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_memory_checkpointer.ipynb Install the required langchain and langchain-aws packages. ```python %pip install langchain langchain-aws ``` -------------------------------- ### DynamoDBStore Initialization Options Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/store/dynamodb/DynamoDBStore.md Demonstrates different ways to initialize the DynamoDBStore, including using a boto3 session with explicit credentials, relying on environment variables, and specifying a custom endpoint URL for local development. ```APIDOC ## DynamoDBStore Initialization Examples ### Option 1: Using boto3 session with explicit credentials ```python import boto3 from langgraph_checkpoint_aws.store.dynamodb import DynamoDBStore session = boto3.Session( aws_access_key_id="YOUR_ACCESS_KEY", aws_secret_access_key="YOUR_SECRET_KEY", region_name="us-east-1", ) store = DynamoDBStore(table_name="my-store", boto3_session=session) store.setup() ``` ### Option 2: Using Environment Variables ```python # Ensure AWS credentials and region are set in environment variables before running # export AWS_ACCESS_KEY_ID=... # export AWS_SECRET_ACCESS_KEY=... # export AWS_DEFAULT_REGION=us-east-1 from langgraph_checkpoint_aws.store.dynamodb import DynamoDBStore store = DynamoDBStore(table_name="my-store") store.setup() ``` ### Option 3: Custom Endpoint URL (e.g., for DynamoDB Local) ```python from langgraph_checkpoint_aws.store.dynamodb import DynamoDBStore store = DynamoDBStore( table_name="my-store", region_name="us-east-1", endpoint_url="http://localhost:8000", ) store.setup() ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/dynamodb_store.ipynb Install the required packages for LangGraph AWS integration. ```python # Install required packages # %pip install langgraph-checkpoint-aws boto3 ``` -------------------------------- ### Install AgentCore CLI and Scaffold Project Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/agents/competitive_research_agent.ipynb Installs the AgentCore CLI globally and scaffolds a new project for deployment. It configures the project for LangChain, Bedrock, and containerized builds, skipping initial dependency installation. ```bash # Install the AgentCore CLI globally (one-time) !npm install -g @aws/agentcore !agentcore --version ``` ```bash # Scaffold the project: # --framework LangChain_LangGraph → closest template to Deep Agents # --build Container → required for browser/interpreter tooling # --memory none → we manage AgentCore Memory manually # --skip-install → we'll install deps + generate lock file ourselves PROJECT_NAME = "DeepResearchAgent" !agentcore create \ --name {PROJECT_NAME} \ --framework LangChain_LangGraph \ --model-provider Bedrock \ --memory none \ --build Container \ --defaults \ --skip-install # Inspect what was created !ls -la {PROJECT_NAME}/ !ls -la {PROJECT_NAME}/app/{PROJECT_NAME}/ ``` -------------------------------- ### Configuration Settings Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_saver.ipynb Sets up configuration parameters including the Valkey URL and the language model ID. ```python # Configuration VALKEY_URL = "valkey://localhost:6379" MODEL_ID = "us.anthropic.claude-sonnet-4-5-20250929-v1:0" print("šŸ“‹ Configuration:") print(f" - Valkey URL: {VALKEY_URL}") print(f" - Model ID: {MODEL_ID}") ``` -------------------------------- ### Install LangChain AWS Package Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/models/nova_hybrid_reasoning.ipynb Install the necessary LangChain AWS package to use ChatBedrockConverse. ```python %pip install -qU langchain-aws ``` -------------------------------- ### Initialize Valkey Server Configuration Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_saver.ipynb Define the connection string and TTL settings for the Valkey instance. ```python print("🐳 Start Valkey with Docker:") print(" docker run --name valkey-memory-demo -p 6379:6379 -d valkey/valkey-bundle:latest") print("\nšŸ”§ Configuration:") print(" • Host: localhost") print(" • Port: 6379") print(" • TTL: 1 hour (configurable)") print("\nāœ… ValkeySaver provides persistent, scalable memory storage") VALKEY_URL = "valkey://localhost:6379" TTL_SECONDS = 3600 # 1 hour ``` -------------------------------- ### Install LangChain AWS packages Source: https://github.com/langchain-ai/langchain-aws/blob/main/README.md Commands to install the core AWS integration packages via pip. ```bash pip install langchain-aws ``` ```bash pip install langgraph-checkpoint-aws ``` ```bash pip install langchain-agentcore-codeinterpreter ``` -------------------------------- ### Initialize ValkeySaver Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Set up the ValkeySaver using a Valkey client connection, with optional TTL and custom serialization. ```python valkey_client = Valkey.from_url("valkey://localhost:6379") ValkeySaver( client: valkey_client, ttl: float | None = None, # TTL in seconds serde: SerializerProtocol | None = None # Custom serialization ) ``` -------------------------------- ### Install langchain-aws Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/aws/README.md Install the langchain-aws package using pip. Ensure you have the necessary AWS credentials configured. ```bash pip install -U langchain-aws ``` -------------------------------- ### Valkey Connection and Initialization Logs Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store.ipynb Logs indicating a successful Valkey connection and the initialization of the vector index configuration. Shows the dimension and algorithm used for the vector index. ```python INFO:__main__:āœ… Valkey connection established INFO:__main__:āœ… Vector index configuration created: enterprise_memory_vectors INFO:__main__:šŸ“ Dimension: 1024, Algorithm: HNSW INFO:__main__:āœ… ValkeyStore initialized with vector search ``` -------------------------------- ### Install Langchain and Langchain-AWS Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/tools/bedrock_agentcore_browser.ipynb Installs the necessary Python packages for Langchain and the AWS integration, including the browser toolkit. ```python %pip install -q langgraph langchain 'langchain-aws[tools]' ``` -------------------------------- ### Install LangGraph Checkpoint AWS Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Install the base package or include optional Valkey support via pip. ```bash # Base package (includes Bedrock AgentCore Memory components) pip install langgraph-checkpoint-aws # Optional Valkey support pip install 'langgraph-checkpoint-aws[valkey]' ``` -------------------------------- ### Create Code Interpreter Toolkit Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/tools/bedrock_agentcore_code_interpreter.ipynb Initialize the toolkit asynchronously and list available tools. ```python # Create the code interpreter toolkit # This is an async function as it sets up the tools toolkit, code_tools = await create_code_interpreter_toolkit(region="us-west-2") # Display available tools print(f"Available code interpreter tools: {[tool.name for tool in code_tools]}") ``` -------------------------------- ### Initialize Cache Hit Performance Demo Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_cache.ipynb Prints the header for the cache hit performance demonstration section. ```python print("⚔ DEMO: Cache Hit Performance - The Magic Happens!") print("=" * 60) ``` -------------------------------- ### Initialize Async Valkey Store with Vector Search Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store_async_patterns.ipynb Sets up an asynchronous Valkey client and configures a vector search index. Use this for applications requiring real-time vector similarity search. ```python valkey_client = None async_store = None try: # Initialize Valkey client with enterprise configuration valkey_client = valkey.from_url( VALKEY_CONN_STRING, # Enterprise connection settings socket_connect_timeout=10, socket_timeout=10, retry_on_timeout=True, health_check_interval=30 ) # Test connection valkey_client.ping() logger.info("āœ… Valkey connection established") # Create index configuration for vector search index_config : ValkeyIndexConfig = { "collection_name": "enterprise_memory_vectors", "dims": VECTOR_DIMENSION, # Match embedding dimensions "embed":embeddings, "distance_metric": "COSINE", "index_type": "HNSW", # Searchable fields for hybrid queries "fields": ["user_id", "category", "priority"], } # Initialize AsyncValkeyStore async_store = AsyncValkeyStore( valkey_client, index=index_config, ) await async_store.setup() logger.info(f"āœ… AsyncValkeyStore configured with vector search: {index_config["collection_name"]}") logger.info(f" Connection: {VALKEY_CONN_STRING}") logger.info(f"šŸ“ Dimension: {index_config["dims"]}, Algorithm: {index_config["index_type"]}") except Exception as e: logger.error(f"āŒ Valkey Client initialization failed: {e}") logger.info("šŸ’” Ensure Valkey is running: docker run -p 6379:6379 -d valkey/valkey") raise ``` -------------------------------- ### Install Required Packages Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/dynamodb_saver.ipynb Installs the necessary packages for LangGraph, Langchain-AWS, and DynamoDB support. Ensure you have the correct package for your needs. ```python # Install required packages # Base package with Dynamodb support: # !pip install 'langgraph-checkpoint-aws' # # Individual packages, for langgraph application: # !pip install langchain-aws langgraph langchain import os import getpass from typing import Annotated, Sequence from typing_extensions import TypedDict from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage, RemoveMessage from langchain_aws import ChatBedrockConverse from langgraph.graph import StateGraph, START, END from langgraph.graph.message import add_messages # Import DynamoDB saver from langgraph_checkpoint_aws import DynamoDBSaver import boto3 print("āœ… All dependencies imported successfully!") print("šŸ—„ļø DynamoDB saver ready for persistent memory") ``` -------------------------------- ### Initialize Valkey Clients Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_valkey_store.ipynb Create separate Valkey clients for checkpointing and memory storage. Ensure the VALKEY_ENDPOINT environment variable is set. ```python print("šŸ”— Creating Valkey clients...") # Create separate clients for checkpoint and store checkpoint_client = Valkey.from_url( f"valkey://{VALKEY_ENDPOINT}", decode_responses=False, max_connections=20 ) store_client = Valkey.from_url( f"valkey://{VALKEY_ENDPOINT}", decode_responses=False, max_connections=20 ) print("āœ… Valkey clients created successfully!") print(f" - Checkpoint client: max_connections=20") print(f" - Store client: max_connections=20") ``` -------------------------------- ### Initialize ChatBedrock and model arguments Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/inmemory/semantic_cache.ipynb Sets up model-specific arguments for ChatBedrock, including temperature, top_k, top_p, and stop sequences. ```python # Create the Anthropic Model model_kwargs = { "temperature": 0, "top_k": 250, "top_p": 1, "stop_sequences": ["\n\nHuman:"] } ``` -------------------------------- ### Install Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/agents/competitive_research_agent.ipynb Installs the necessary Python packages for LangChain AWS integration, Deep Agents, Bedrock AgentCore, and LangGraph checkpointing. ```python # Install dependencies %pip install -q "langchain-aws[tools]" deepagents bedrock-agentcore langgraph-checkpoint-aws ``` -------------------------------- ### Import necessary libraries Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/tools/bedrock_agentcore_browser.ipynb Imports core Langchain components for agent creation, LLM initialization, and the Bedrock browser toolkit. Sets up basic logging. ```python import logging from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain_aws.tools import create_browser_toolkit # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ``` -------------------------------- ### Initialize Logging and Imports Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/tools/bedrock_agentcore_code_interpreter.ipynb Configure logging and import the required LangChain modules. ```python import logging from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain_aws.tools import create_code_interpreter_toolkit # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ``` -------------------------------- ### Install Langchain-AWS and Boto3 Source: https://github.com/langchain-ai/langchain-aws/blob/main/llms-full.txt Install the necessary packages for LangChain AWS integration and AWS SDK for Python. This command is typically run in a notebook environment. ```python %%capture --no-stderr %pip install --quiet -U langchain-aws boto3 ``` -------------------------------- ### Configure ValkeyStore and Indexing Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Define the ValkeyStore client, vector search index configuration, and TTL settings. ```python ValkeyStore( client: Valkey, index: ValkeyIndexConfig | None = None, # Valkey-specific vector search configuration ttl: TTLConfig | None = None # TTL configuration ) # ValkeyIndexConfig - Enhanced vector search configuration from langgraph_checkpoint_aws.store.valkey import ValkeyIndexConfig index_config = { # Basic configuration "collection_name": "my_documents", # Index collection name "dims": 1536, # Vector dimensions "embed": embeddings, # Embedding model "fields": ["text", "content"], # Fields to index # Valkey-specific configuration "timezone": "UTC", # Timezone for operations (default: "UTC") "index_type": "hnsw", # Algorithm: "hnsw" or "flat" (default: "hnsw") # HNSW performance tuning parameters "hnsw_m": 16, # Connections per layer (default: 16) "hnsw_ef_construction": 200, # Construction search width (default: 200) "hnsw_ef_runtime": 10, # Runtime search width (default: 10) } # TTL Configuration ttl_config = { "default_ttl": 60.0 # Default TTL in minutes } ``` -------------------------------- ### Demonstrate Enterprise Vector Search Patterns Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store.ipynb Shows how to initialize enterprise memory objects, store them with embeddings, and execute vector searches with optional user filters. ```python def demonstrate_enterprise_patterns(): """Demonstrate enterprise ValkeyStore patterns with real-world scenarios.""" print("šŸ¢ Enterprise ValkeyStore + Bedrock Vector Search Demo") print("=" * 60) # Create sample enterprise memories enterprise_memories = [ EnterpriseMemory( memory_id="mem_001", user_id="enterprise_user_001", content="Alice Johnson is a Senior Software Engineer specializing in machine learning and data science at TechCorp.", memory_type="fact", importance=0.9, tags=["professional", "role", "expertise"], metadata={"source": "hr_system", "verified": True} ), EnterpriseMemory( memory_id="mem_002", user_id="enterprise_user_001", content="Alice prefers Python for data analysis and has extensive experience with TensorFlow and PyTorch.", memory_type="preference", importance=0.8, tags=["programming", "tools", "preference"], metadata={"confidence": 0.95, "last_updated": "2024-01-15"} ), EnterpriseMemory( memory_id="mem_003", user_id="enterprise_user_001", content="Alice is currently working on a natural language processing project for customer sentiment analysis.", memory_type="context", importance=0.7, tags=["current_project", "nlp", "sentiment_analysis"], metadata={"project_id": "PROJ-2024-001", "status": "active"} ), EnterpriseMemory( memory_id="mem_004", user_id="enterprise_user_001", content="Alice wants to learn more about large language models and transformer architectures for her next project.", memory_type="goal", importance=0.6, tags=["learning", "llm", "transformers", "goal"], metadata={"target_date": "2024-06-01", "priority": "high"} ), EnterpriseMemory( memory_id="mem_005", user_id="enterprise_user_002", content="Bob Smith is a DevOps Engineer with expertise in Kubernetes, AWS, and CI/CD pipelines.", memory_type="fact", importance=0.9, tags=["professional", "devops", "cloud"], metadata={"source": "hr_system", "verified": True} ) ] # 1. Store memories with embeddings print("\n1ļøāƒ£ Storing Enterprise Memories with Vector Embeddings:") stored_count = 0 for memory in enterprise_memories: try: success = memory_manager.store_memory_sync(memory) if success: stored_count += 1 print(f" āœ… {memory.memory_id}: {memory.content[:50]}... ({memory.memory_type})") else: print(f" āŒ Failed to store {memory.memory_id}") except Exception as e: print(f" āš ļø Error storing {memory.memory_id}: {e}") print(f"\n šŸ“Š Successfully stored {stored_count}/{len(enterprise_memories)} memories") # 2. Vector search demonstrations if stored_count > 0: print("\n2ļøāƒ£ Vector Search Demonstrations:") search_queries = [ { "query": "machine learning and data science expertise", "description": "Find professionals with ML/DS skills", "user_filter": None }, { "query": "Python programming and TensorFlow experience", "description": "Search for Python and TensorFlow knowledge", "user_filter": "enterprise_user_001" }, { "query": "cloud infrastructure and DevOps", "description": "Find DevOps and cloud expertise", "user_filter": None }, { "query": "learning goals and future projects", "description": "Search for learning objectives", "user_filter": None } ] for i, search_item in enumerate(search_queries, 1): print(f"\n šŸ” Search {i}: {search_item['description']}") print(f" Query: '{search_item['query']}'") try: results = memory_manager.vector_search_sync( query=search_item["query"], user_id=search_item["user_filter"], limit=3, similarity_threshold=0.5 ) if results: print(f" šŸ“Š Found {len(results)} relevant results:") for result in results: print(f" • [{result.memory.memory_type}] {result.memory.content[:60]}...") ``` -------------------------------- ### Configure AWS Targets and Install Dependencies Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/agents/competitive_research_agent.ipynb Automatically detects AWS account and region, writes to aws-targets.json, and installs CDK dependencies using npm. Ensure PROJECT_NAME is set. ```python import json import boto3 import os # Auto-detect account and region account = boto3.client("sts").get_caller_identity()["Account"] region = os.environ.get("AWS_REGION", "us-west-2") # Write aws-targets.json targets = [{"name": "default", "description": "Default target", "account": account, "region": region}] targets_path = f"{PROJECT_NAME}/agentcore/aws-targets.json" with open(targets_path, "w") as f: json.dump(targets, f, indent=2) print(f"āœ… aws-targets.json: account={account}, region={region}") # Install CDK dependencies !cd {PROJECT_NAME}/agentcore/cdk && npm install print("\nāœ… CDK dependencies installed") ``` -------------------------------- ### Connect to MemoryDB Cluster Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/inmemory/retriever.ipynb Imports and connection setup for the MemoryDB cluster. ```python from redis.cluster import RedisCluster as MemoryDBCluster ``` ```python endpoint = "" rc = MemoryDBCluster( host=f"{endpoint}", port=6379, ssl=True, decode_responses=True, ssl_cert_reqs="none" ) rc.ping() rc.flushall() ``` -------------------------------- ### ValkeyStore Configuration Source: https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/README.md Initializes a vector store with specific index and TTL configurations. ```APIDOC ## ValkeyStore ### Description Initializes the ValkeyStore for vector search operations. ### Parameters - **client** (Valkey) - Required - The Valkey client instance. - **index** (ValkeyIndexConfig) - Optional - Valkey-specific vector search configuration. - **ttl** (TTLConfig) - Optional - TTL configuration. ### ValkeyIndexConfig - **collection_name** (str) - Required - Index collection name. - **dims** (int) - Required - Vector dimensions. - **embed** (Any) - Required - Embedding model. - **fields** (list) - Required - Fields to index. - **timezone** (str) - Optional - Timezone (default: "UTC"). - **index_type** (str) - Optional - Algorithm: "hnsw" or "flat" (default: "hnsw"). - **hnsw_m** (int) - Optional - Connections per layer (default: 16). - **hnsw_ef_construction** (int) - Optional - Construction search width (default: 200). - **hnsw_ef_runtime** (int) - Optional - Runtime search width (default: 10). ``` -------------------------------- ### Manage AgentCore Toolkits Source: https://github.com/langchain-ai/langchain-aws/blob/main/llms-full.txt Install packages and perform cleanup operations for AgentCore tools. ```python tools_by_name["install_packages"].invoke({ "packages": ["requests", "beautifulsoup4"] }, config=config) # Cleanup when done await toolkit.cleanup() ``` -------------------------------- ### Initialize ValkeyCache for Optimal Performance Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_cache.ipynb Creates and configures a ValkeyCache instance with optimized settings for performance. It includes connection testing, setting a cache prefix for namespacing, and defining a default Time-To-Live (TTL). Includes instructions for running Valkey if initialization fails. ```python def create_valkey_cache(): """Create and configure ValkeyCache for optimal performance.""" try: # Create Valkey client with optimized settings valkey_client = Valkey.from_url( VALKEY_URL, decode_responses=False, # Better performance for binary data socket_connect_timeout=5, socket_timeout=5 ) # Test connection valkey_client.ping() # Initialize cache with performance settings cache = ValkeyCache( client=valkey_client, prefix="llm_cache:", # Namespace for organization ttl=DEFAULT_TTL # Default TTL in seconds ) print("āœ… ValkeyCache initialized successfully") print(f" šŸ·ļø Cache prefix: {cache.prefix}") print(f" ā° Default TTL: {cache.ttl} seconds") print(f" šŸ”— Connection: Active") return cache except Exception as e: print(f"āŒ Failed to initialize ValkeyCache: {e}") print("šŸ’” Make sure Valkey is running:") print(" docker run --name valkey-cache-demo -p 6379:6379 -d valkey/valkey:latest") raise # Create the cache instance cache = create_valkey_cache() ``` -------------------------------- ### Configure and initialize checkpointer and model Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_memory_checkpointer.ipynb Set up the AWS region, memory ID, and model ID to initialize the checkpointer and Bedrock LLM. ```python REGION = "us-west-2" MEMORY_ID = "YOUR_MEMORY_ID" MODEL_ID = "us.anthropic.claude-sonnet-4-20250514-v1:0" # Initialize checkpointer for state persistence checkpointer = AgentCoreMemorySaver(MEMORY_ID, region_name=REGION) # Initialize Bedrock LLM model = init_chat_model(MODEL_ID, model_provider="bedrock_converse", region_name=REGION) ``` -------------------------------- ### Batch Operations Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/dynamodb_store.ipynb Perform multiple put or get operations in a single batch request. ```python from langgraph.store.base import PutOp, GetOp, SearchOp # Perform multiple operations in a batch ops = [ PutOp(namespace=("batch",), key="item1", value={"value": 1}), PutOp(namespace=("batch",), key="item2", value={"value": 2}), PutOp(namespace=("batch",), key="item3", value={"value": 3}), ] results = store.batch(ops) print(f"Batch operation completed: {len(results)} operations") # Get multiple items get_ops = [ GetOp(namespace=("batch",), key="item1"), GetOp(namespace=("batch",), key="item2"), GetOp(namespace=("batch",), key="item3"), ] items = store.batch(get_ops) for item in items: if item: print(f" - {item.key}: {item.value}") ``` -------------------------------- ### Invoke the agent Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/agents/inline_agent_runnable_roc.ipynb Execute the runnable with a list of messages to get the agent's response. ```python # Invoke the inlineAgent output = runnable.invoke(messages) print(output) ``` -------------------------------- ### Imports and Configuration for Async ValkeyStore Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store_async_patterns.ipynb Sets up necessary imports and configuration variables for using AsyncValkeyStore, including connection strings, embedding dimensions, namespaces, and AWS region. Allows choosing between mock and real embeddings. ```python import asyncio import time from typing import List, Dict, Any, Optional from dataclasses import dataclass, field from datetime import datetime import logging # LangChain and AWS imports from langchain_core.embeddings import Embeddings from langchain_aws import BedrockEmbeddings # ValkeyStore imports import valkey from langgraph_checkpoint_aws import AsyncValkeyStore, ValkeyIndexConfig # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Configuration VALKEY_CONN_STRING = "valkey://localhost:6379" # Update for your environment VECTOR_DIMENSION = 1024 # Titan Text Embeddings v2: 1024, v1: 1536 NAMESPACE = ("async_demo",) AWS_REGION = "us-east-1" # Embedding mode: 'mock' (default, no AWS credentials needed) or 'bedrock' (production) EMBEDDING_MODE = "mock" # Change to "bedrock" for production with real embeddings print("āœ… Imports complete") ``` -------------------------------- ### Initialize EnterpriseMemoryManager Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store.ipynb Initializes the EnterpriseMemoryManager with embeddings. This setup is necessary before using memory management features. ```python memory_manager = EnterpriseMemoryManager(embeddings) print("āœ… EnterpriseMemoryManager ready") print(f"šŸŽÆ Embeddings: {type(embeddings).__name__}") print(f"šŸ” Vector search: {'āœ… Enabled' if context_manager_working else 'āŒ Unavailable'}") ``` -------------------------------- ### Production FastAPI App with Async Valkey Store Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store_async_patterns.ipynb This snippet outlines a production-ready FastAPI application structure using `AsyncValkeyStore`. It includes setup for startup events and defines API endpoints for search and health checks, demonstrating how to integrate Valkey Store into a live web service. ```python from fastapi import FastAPI, HTTPException from langgraph_checkpoint_aws import AsyncValkeyStore app = FastAPI() store = AsyncValkeyStore(conn_string=CONN_STRING, ...) @app.on_event("startup") async def startup(): # Store is ready - async context handles connections pass @app.get("/search/{user_id}") async def search(user_id: str, query: str): results = await store.asearch( namespace_prefix=("prefs", user_id), query=query, limit=10 ) return {"results": [asdict(r) for r in results]} @app.get("/health") async def health(): # Quick connectivity check await store.asearch(("health",), "test", limit=1) return {"status": "ok"} ``` -------------------------------- ### Configure ValkeyStore and Bedrock Environment Source: https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/valkey_store.ipynb Initializes necessary imports, logging, and environment variables for Valkey and Bedrock integration. ```python # Install required packages # Base package with Valkey support: # !pip install 'langgraph-checkpoint-aws[valkey]' # Or individual packages: # !pip install langchain-aws langgraph valkey numpy boto3 orjson import os import json import time import numpy as np import logging from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Tuple, Union from dataclasses import dataclass, field from contextlib import contextmanager # AWS and LangChain imports import boto3 from botocore.exceptions import ClientError, NoCredentialsError from langchain_aws.embeddings import BedrockEmbeddings from langchain_core.embeddings import Embeddings # ValkeyStore and LangGraph imports from langgraph_checkpoint_aws import ValkeyStore, ValkeyIndexConfig from langgraph.store.base import Item import valkey # Configure logging for production logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Enterprise configuration AWS_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-west-2") VALKEY_URL = os.environ.get("VALKEY_URL", "valkey://localhost:6379") EMBEDDING_MODEL = "amazon.titan-embed-text-v2:0" VECTOR_DIMENSION = 1024 # Titan Text Embeddings v2 TTL_SECONDS = 30 * 24 * 3600 # 30 days print("āœ… Enterprise ValkeyStore + Bedrock environment configured") print(f"šŸŒ AWS Region: {AWS_REGION}") print(f"šŸ¤– Embedding Model: {EMBEDDING_MODEL}") print(f"šŸ“ Vector Dimension: {VECTOR_DIMENSION}") print(f"šŸ”— Valkey URL: {VALKEY_URL}") print("🐳 Start Valkey with Docker:") print(" docker run --name valkey-store-demo -p 6379:6379 -d valkey/valkey-bundle:latest") print("\nšŸ”§ ValkeyStore Configuration:") print(" • Host: localhost") print(" • Port: 6379") print(" • Serialization: JSON with orjson for performance") print(" • TTL: Configurable expiration (default: 30 days)") print(" • Namespaces: Organized storage with prefix patterns") print("\n⚔ ValkeyStore provides enterprise-grade persistent memory") ```