### Complete Ecommerce Assistant Example Setup Source: https://neo4j.com/labs/agent-memory/how-to/integrations/langchain Imports and setup for a comprehensive e-commerce shopping assistant using Langchain, OpenAI, and Neo4j Agent Memory. This includes necessary tools, models, and memory configurations. ```python import json from datetime import datetime from langchain_openai import ChatOpenAI from langchain.agents import AgentExecutor, create_openai_functions_agent from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.tools import BaseTool from langchain.memory import ConversationBufferMemory from pydantic import BaseModel, Field from neo4j_agent_memory import MemoryClient, MemorySettings ``` -------------------------------- ### Project Setup and Dependency Installation Source: https://neo4j.com/labs/agent-memory/tutorials/mcp-server-typescript Initializes a new project directory, sets up a package.json, and installs required dependencies including the Agent Memory and MCP SDK, along with TypeScript development tools. ```bash mkdir my-memory-mcp && cd my-memory-mcp npm init -y npm install @neo4j-labs/agent-memory @modelcontextprotocol/sdk npm install --save-dev typescript tsx @types/node ``` -------------------------------- ### Project Setup: Install Dependencies Source: https://neo4j.com/labs/agent-memory/tutorials/conversation-memory Installs the necessary libraries for the shopping assistant project, including neo4j-agent-memory, openai, and python-dotenv. ```bash mkdir shopping-assistant cd shopping-assistant python -m venv venv source venv/bin/activate pip install neo4j-agent-memory[all] openai python-dotenv ``` -------------------------------- ### Project Setup and Dependencies Source: https://neo4j.com/labs/agent-memory/tutorials/knowledge-graph-typescript Initialize a new Node.js project and install necessary dependencies including Agent Memory, AI SDK, OpenAI, Zod, TypeScript, and tsx. ```bash mkdir kg-from-docs && cd kg-from-docs npm init -y npm install @neo4j-labs/agent-memory ai @ai-sdk/openai zod npm install --save-dev typescript tsx @types/node ``` -------------------------------- ### Set Up and Run Financial Advisor Application Source: https://neo4j.com/labs/agent-memory/how-to/integrations/google-cloud Install dependencies, load data, and start the financial advisor application. This involves setting environment variables for API keys and database credentials. ```bash cd examples/google-cloud-financial-advisor cp .env.example .env # Set GOOGLE_API_KEY, NEO4J_URI, NEO4J_PASSWORD make install && make load-data && make dev ``` -------------------------------- ### Project Setup Commands Source: https://neo4j.com/labs/agent-memory/tutorials/conversation-memory-typescript Installs necessary dependencies for a new TypeScript project, including the agent memory library and AI SDK. ```bash mkdir shopping-assistant && cd shopping-assistant npm init -y npm install @neo4j-labs/agent-memory ai @ai-sdk/openai npm install --save-dev typescript tsx @types/node ``` -------------------------------- ### Provider Resolution Example Source: https://neo4j.com/labs/agent-memory/explanation/why-provider-protocol Demonstrates how to specify a provider. The system prioritizes native adapters if installed, falling back to LiteLLM if only the LiteLLM extra is present. If both are installed, the native adapter takes precedence. ```python from_provider("openai/gpt-4o-mini") ``` -------------------------------- ### Quick Start with Neo4j Agent Memory SDK Source: https://neo4j.com/labs/agent-memory/sdks/python Initialize the MemoryClient with settings for Neo4j or NAMS. This example demonstrates adding a message to short-term memory, an entity to long-term memory, and retrieving context. ```python from neo4j_agent_memory import MemoryClient, MemorySettings settings = MemorySettings( neo4j={"uri": "bolt://localhost:7687", "password": "password"} ) async with MemoryClient(settings) as client: msg = await client.short_term.add_message("session-1", "user", "Hello") await client.long_term.add_entity("Alice", "PERSON") context = await client.get_context("hello") ``` -------------------------------- ### Complete OpenAI Agent with Neo4j Memory Example Source: https://neo4j.com/labs/agent-memory/how-to/integrations/openai-agents A full example demonstrating the setup and usage of an OpenAI agent with Neo4j memory. It covers context retrieval, tool creation, message handling, tool execution, and trace recording. ```python import asyncio import json from openai import OpenAI from neo4j_agent_memory import MemoryClient, MemorySettings, Neo4jConfig from neo4j_agent_memory.integrations.openai_agents import ( Neo4jOpenAIMemory, create_memory_tools, record_agent_trace, ) from neo4j_agent_memory.integrations.openai_agents.memory import execute_memory_tool openai_client = OpenAI() async def main(): settings = MemorySettings( neo4j=Neo4jConfig( uri="bolt://localhost:7687", username="neo4j", password="password", ) ) async with MemoryClient(settings) as client: memory = Neo4jOpenAIMemory( memory_client=client, session_id="demo-session", ) # Get context for system prompt context = await memory.get_context("Help user") # Create memory tools tools = create_memory_tools(memory) # Build messages messages = [ {"role": "system", "content": f"You are a helpful assistant.\n\n{context}"}, {"role": "user", "content": "I love Italian food. Can you remember that?"}, ] # Save user message await memory.save_message("user", messages[-1]["content"]) # Call OpenAI response = openai_client.chat.completions.create( model="gpt-4", messages=messages, tools=tools, ) assistant_message = response.choices[0].message # Handle tool calls if assistant_message.tool_calls: messages.append(assistant_message.model_dump()) for tool_call in assistant_message.tool_calls: result = await execute_memory_tool( memory=memory, tool_name=tool_call.function.name, arguments=json.loads(tool_call.function.arguments), ) messages.append({ "role": "tool", "content": result, "tool_call_id": tool_call.id, }) # Get final response response = openai_client.chat.completions.create( model="gpt-4", messages=messages, tools=tools, ) assistant_message = response.choices[0].message # Save assistant response await memory.save_message("assistant", assistant_message.content) print(f"Assistant: {assistant_message.content}") # Record the trace await record_agent_trace( memory=memory, messages=messages, task="Remember user food preference", success=True, ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Go client Source: https://neo4j.com/labs/agent-memory/tutorials/hosted-quickstart-typescript Install the official Neo4j Labs agent memory client for Go. ```go go get github.com/neo4j-labs/agent-memory-tck/clients/go ``` -------------------------------- ### Install Dependencies and Build Documentation Source: https://neo4j.com/labs/agent-memory/reference/deployment Installs project dependencies and builds the documentation locally. Alternatively, use the Makefile for the same operations. ```bash cd docs npm install # Build documentation npm run build # Or use Makefile from project root make docs-install make docs ``` -------------------------------- ### Trace Reasoning with MemoryClient Source: https://neo4j.com/labs/agent-memory/reference/api/reasoning Use MemoryClient to start, add steps to, record tool calls for, and complete a reasoning trace. This example demonstrates a full cycle of reasoning for a user request. ```python async with MemoryClient(settings) as client: # Start reasoning trace linked to user message trace = await client.reasoning.start_trace( session_id="user-123", task="Find Italian restaurants nearby", triggered_by_message_id=message.id, ) # Add reasoning step step = await client.reasoning.add_step( trace.id, thought="User wants Italian food. I should search for nearby restaurants.", action="search_restaurants", ) # Record tool call await client.reasoning.record_tool_call( step.id, tool_name="search_api", arguments={"cuisine": "Italian", "location": "nearby"}, result=[{"name": "La Trattoria", "rating": 4.5}], duration_ms=234.5, ) # Complete trace await client.reasoning.complete_trace( trace.id, outcome="Recommended La Trattoria based on high rating", success=True, ) # Later: find similar past reasoning similar = await client.reasoning.search_traces("restaurant recommendations") for trace, score in similar: print(f"[{score:.2f}] {trace.task}: {trace.outcome}") ``` -------------------------------- ### Create Project and Install Dependencies Source: https://neo4j.com/labs/agent-memory/tutorials/first-agent-memory-typescript Sets up a new project directory and installs necessary npm packages for the agent memory application. ```bash mkdir my-memory-agent && cd my-memory-agent npm init -y npm install @neo4j-labs/agent-memory ai @ai-sdk/openai ``` -------------------------------- ### Provider string to native adapter Source: https://neo4j.com/labs/agent-memory/reference/api/factory Use this to instantiate a provider when the corresponding native extra is installed. For example, `[openai]` for `openai/gpt-4o-mini`. ```python from neo4j_agent_memory.llm import from_provider provider = from_provider("openai/gpt-4o-mini") # Returns OpenAIProvider when [openai] is installed. ``` -------------------------------- ### Financial Document Assistant Example Source: https://neo4j.com/labs/agent-memory/how-to/integrations/llamaindex Complete example for setting up a financial services RAG application using LlamaIndex, OpenAI, and Neo4j for memory. ```python import json from datetime import datetime from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, Settings, ) from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core.agent import ReActAgent from llama_index.llms.openai import OpenAI from llama_index.core.memory import ChatMemoryBuffer from neo4j_agent_memory import MemoryClient, MemorySettings # --- Initialize --- settings = MemorySettings( neo4j={"uri": "bolt://localhost:7687", "username": "neo4j", "password": "password"} ) memory_client = MemoryClient(settings) # Note: call await memory_client.connect() before using in async context Settings.llm = OpenAI(model="gpt-4o", temperature=0) # --- Create Document Indexes --- ``` -------------------------------- ### Install @neo4j-labs/agent-memory Source: https://neo4j.com/labs/agent-memory/sdks/typescript Install the SDK using npm, pnpm, or bun. Requires Node.js 20+. ```bash npm install @neo4j-labs/agent-memory ``` ```bash # or pnpm add @neo4j-labs/agent-memory ``` ```bash bun add @neo4j-labs/agent-memory ``` -------------------------------- ### Install neo4j-agent-memory and LangChain Source: https://neo4j.com/labs/agent-memory/how-to/integrations/langchain Install the necessary libraries for integrating neo4j-agent-memory with LangChain and OpenAI. ```bash pip install neo4j-agent-memory langchain langchain-openai ``` -------------------------------- ### Install neo4j-agent-memory with pip Source: https://neo4j.com/labs/agent-memory/tutorials/nams-quickstart Install the neo4j-agent-memory library with NAMS support using pip. ```bash pip install 'neo4j-agent-memory[nams]>=0.4.0' ``` -------------------------------- ### Install C# client Source: https://neo4j.com/labs/agent-memory/tutorials/hosted-quickstart-typescript Install the official Neo4j Labs agent memory client for C# using the dotnet CLI. ```csharp dotnet add package Neo4j.AgentMemory ``` -------------------------------- ### Install R client Source: https://neo4j.com/labs/agent-memory/tutorials/hosted-quickstart-typescript Install the official Neo4j Labs agent memory client for R. ```r install.packages("neo4j.memory") # or: devtools::install_github("neo4j-labs/agent-memory-tck", subdir = "clients/rlang/neo4j.memory") ``` -------------------------------- ### Start MCP Server Source: https://neo4j.com/labs/agent-memory/reference/cli Basic command to start the MCP server. Requires a password for Neo4j connection. ```bash neo4j-agent-memory mcp serve [OPTIONS] ``` -------------------------------- ### Install Python client Source: https://neo4j.com/labs/agent-memory/tutorials/hosted-quickstart-typescript Install the official Neo4j Labs agent memory client for Python using uv or pip. ```python uv add neo4j-agent-memory-client # or: pip install neo4j-agent-memory-client ``` -------------------------------- ### Install Python SDK and set API key Source: https://neo4j.com/labs/agent-memory/getting-started Installs the Python SDK using pip and sets the API key environment variable for NAMS. ```python pip install neo4j-agent-memory export MEMORY_API_KEY=nams_... ``` -------------------------------- ### Start Neo4j Docker Container Source: https://neo4j.com/labs/agent-memory/tutorials/first-agent-memory If the Neo4j container is not running, use this command to start it. This is a prerequisite for the agent memory system. ```bash docker start neo4j-memory ``` -------------------------------- ### Install Neo4j Agent Memory for All Frameworks Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the Neo4j agent memory package with support for all available frameworks using pip. ```bash # All frameworks pip install neo4j-agent-memory[all] ``` -------------------------------- ### Set up Project Environment Source: https://neo4j.com/labs/agent-memory/tutorials/knowledge-graph Create a new project directory, set up a virtual environment, and install necessary Python packages. ```bash mkdir knowledge-graph-demo cd knowledge-graph-demo python -m venv venv source venv/bin/activate pip install neo4j-agent-memory[all] python-dotenv ``` -------------------------------- ### Serve Documentation Locally Source: https://neo4j.com/labs/agent-memory/reference/deployment Starts a local development server with live reload for the documentation. The Makefile provides an alternative command. ```bash npm run serve # Opens http://localhost:8080 with auto-refresh ``` ```bash make docs-serve ``` -------------------------------- ### Get Tracer Instance for Observability Source: https://neo4j.com/labs/agent-memory/faq Obtain a tracer instance from the neo4j_agent_memory.observability module. Ensure you specify the correct provider and project name for your tracing setup. ```python from neo4j_agent_memory.observability import get_tracer # Observability tracers are obtained from # ``neo4j_agent_memory.observability.get_tracer(...)``, not from # ``MemorySettings``. tracer = get_tracer( provider="opik", # or "opentelemetry" project_name="my-agent", ) ``` -------------------------------- ### MemoryClient Initialization Source: https://neo4j.com/labs/agent-memory/reference/typescript-api Demonstrates how to initialize the MemoryClient with default settings (reading from environment variables) and with custom options. ```APIDOC ## MemoryClient Initialization ### Description Instantiate the `MemoryClient` class. It can be initialized with zero configuration, automatically reading the API key from the `MEMORY_API_KEY` environment variable and targeting the default hosted NAMS endpoint. Alternatively, you can provide a configuration object to specify the endpoint, API key, token provider, transport protocol, request timeout, custom headers, and a logger. ### Usage **Zero-config:** ```typescript import { MemoryClient } from "@neo4j-labs/agent-memory"; // Zero-config: reads MEMORY_API_KEY from environment, targets hosted NAMS. const memory = new MemoryClient(); ``` **With options:** ```typescript import { MemoryClient } from "@neo4j-labs/agent-memory"; const memory = new MemoryClient({ endpoint: "https://memory.neo4jlabs.com/v1", apiKey: process.env.MEMORY_API_KEY, timeout: 30_000, headers: { "X-Trace-Id": traceId }, logger: (event) => console.log(event), }); ``` ### `MemoryClientOptions` Interface | Field | Type | Description | Default | |---|---|---|---| | `endpoint` | `string` | The NAMS REST endpoint. Auto-selects REST transport when ending in `/v\d+`. | `https://memory.neo4jlabs.com/v1` | | `apiKey` | `string` | Bearer token for `Authorization` header. | `process.env.MEMORY_API_KEY` | | `tokenProvider` | `() => string | Promise` | Dynamic token source (OAuth refresh, AWS STS, etc.). Overrides `apiKey`. | — | | `transport` | `"auto" | "bridge" | "rest"` | Force the wire protocol. `"auto"` selects based on endpoint shape. | `"auto"` | | `timeout` | `number` | Per-request timeout in milliseconds. | `30000` | | `headers` | `Record` | Extra request headers (User-Agent, trace headers, etc.). | — | | `logger` | `(event: LogEvent) => void` | Receives `request` / `response` / `error` events for observability. | — | TypeDoc: `MemoryClient` · `MemoryClientOptions` ``` -------------------------------- ### Complete Shopping Assistant Example Source: https://neo4j.com/labs/agent-memory/how-to/integrations/microsoft-agent Demonstrates a full implementation of a shopping assistant using Neo4j memory and Microsoft Agent. It includes setting up memory, creating chat clients, generating memory tools, and running an agent with a conversational loop. Tools are automatically invoked during agent.run(). ```python import asyncio from agent_framework import Message from agent_framework.azure import AzureOpenAIResponsesClient from neo4j_agent_memory import MemoryClient, MemorySettings from neo4j_agent_memory.integrations.microsoft_agent import ( Neo4jMicrosoftMemory, GDSConfig, GDSAlgorithm, create_memory_tools, record_agent_trace, ) async def main(): settings = MemorySettings( neo4j={"uri": "bolt://localhost:7687", "username": "neo4j", "password": "password"}, embedding={"provider": "openai", "api_key": "sk-..."}, # Replace with your actual API key ) gds_config = GDSConfig( enabled=True, expose_as_tools=[GDSAlgorithm.SHORTEST_PATH, GDSAlgorithm.NODE_SIMILARITY], fallback_to_basic=True, ) async with MemoryClient(settings) as client: # Create memory memory = Neo4jMicrosoftMemory( memory_client=client, session_id="shopping-session-1", user_id="user-123", gds_config=gds_config, ) # Create chat client chat_client = AzureOpenAIResponsesClient(model="gpt-4") # Create memory tools bound to the memory instance tools = create_memory_tools(memory, include_gds_tools=True) # Create agent — tools are callable, framework auto-invokes them agent = chat_client.as_agent( name="ShoppingAssistant", instructions="""You are a helpful shopping assistant. Use memory tools to remember preferences and provide personalized recommendations.""", tools=tools, context_providers=[memory.context_provider], ) # Conversation loop while True: user_input = input("You: ") if user_input.lower() in ("quit", "exit"): break # Save user message await memory.save_message("user", user_input) # Run agent — framework auto-invokes tools and returns final response response = await agent.run(Message("user", [user_input])) # Display response if response.text: await memory.save_message("assistant", response.text) print(f"Assistant: {response.text}") # Record trace for learning await record_agent_trace( memory=memory, messages=[ {"role": "user", "content": user_input}, {"role": "assistant", "content": response.text[:200] if response.text else ""}, ], task=user_input, outcome="success", success=True, ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Quick Start: GLiNER Entity Extraction with POLE+O Source: https://neo4j.com/labs/agent-memory/how-to/entity-extraction Use the built-in POLE+O schema for general-purpose entity extraction with GLiNER. Ensure `neo4j-agent-memory` is installed with the `gliner` extra, and configure your Neo4j connection settings. ```python from neo4j_agent_memory import MemoryClient, MemorySettings from neo4j_agent_memory.extraction import GLiNEREntityExtractor settings = MemorySettings( neo4j={"uri": "bolt://localhost:7687", "password": "password"} ) client = MemoryClient(settings) # Create extractor with POLE+O schema extractor = GLiNEREntityExtractor.for_poleo() text = """ Customer Jane Smith called about her order #12345 from Nike. She purchased Air Max 90 shoes last week from our Manhattan store. She mentioned she prefers next-day delivery for future orders. """ result = await extractor.extract(text) for entity in result.entities: print(f" {entity.name} ({entity.type}) - confidence: {entity.confidence:.2f}") ``` -------------------------------- ### Main Application Entry Point Source: https://neo4j.com/labs/agent-memory/tutorials/microsoft-agent-memory Sets up the main loop for the application, handling user input, agent interaction, and memory saving. Includes saving user messages, running the agent, displaying responses, and recording agent traces for learning. ```python """Main application entry point.""" import asyncio import json from agent_framework import Message from memory_config import create_memory from agent import create_agent from neo4j_agent_memory.integrations.microsoft_agent import record_agent_trace async def main(): session_id = "demo-session-1" user_id = "demo-user" print("Shopping Assistant") print("Type 'quit' to exit\n") # Create memory and agent memory = await create_memory(session_id, user_id) agent = await create_agent(memory) try: while True: user_input = input("You: ").strip() if user_input.lower() in ("quit", "exit"): break if not user_input: continue # Save user message await memory.save_message("user", user_input) # Run agent — framework auto-invokes tools and returns final response response = await agent.run(Message("user", [user_input])) # Display response if response.text: print(f"Assistant: {response.text}\n") await memory.save_message("assistant", response.text) # Record trace for learning await record_agent_trace( memory=memory, messages=[ {"role": "user", "content": user_input}, {"role": "assistant", "content": response.text[:200] if response.text else ""}, ], task=user_input, outcome="success", success=True, ) finally: await memory.memory_client.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Comprehensive Context with Preferences Source: https://neo4j.com/labs/agent-memory/how-to/preferences Retrieve a full context graph including messages, preferences, entities, and reasoning traces. This example shows how to include long-term preferences and filter them by specific categories when fetching context. ```python # Get comprehensive context including preferences context = await client.get_context( query="recommend running shoes", user_id="CUST-12345", include_short_term=True, # Recent conversation include_long_term=True, # Entities and preferences include_reasoning=True, # Past recommendations preference_categories=["brand", "style", "size"], ) # Format for agent prompt_context = f""" ## Recent Conversation {format_messages(context.messages)} ## Customer Preferences {format_preferences(context.preferences)} ## Previously Recommended Products {format_entities(context.entities, type="PRODUCT")} ## Past Successful Recommendations {format_reasoning_traces(context.reasoning_traces)} """ View all (9 more lines) ``` -------------------------------- ### Main Chat Loop Initialization Source: https://neo4j.com/labs/agent-memory/tutorials/conversation-memory Initializes the chat environment, gets user input for name, creates a user ID, and starts the main chat loop. Handles user input for messages, quitting, and viewing memory. ```python async def main(): """Main chat loop.""" await initialize() # Get user name print("\n" + "="*50) print("🛍️ Welcome to the Shopping Assistant!") print("="*50) name = input("\nWhat's your name? ").strip() if not name: name = "Guest" user_id = await get_or_create_user(name) session_id = f"chat-{datetime.now().strftime('%Y%m%d-%H%M%S')}" print(f"\n💬 Chat started (Session: {session_id})") print(" Type 'quit' to exit, 'memory' to see what I remember\n") while True: try: user_input = input(f"{name}: ").strip() except (KeyboardInterrupt, EOFError): break if not user_input: continue if user_input.lower() == "quit": break ``` -------------------------------- ### Create Project Directory and Virtual Environment Source: https://neo4j.com/labs/agent-memory/tutorials/strands-agent-quickstart Sets up the project directory and activates a Python virtual environment. Use the appropriate command for your operating system. ```bash mkdir strands-memory-agent cd strands-memory-agent python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Initialize and Access Reasoning Client Source: https://neo4j.com/labs/agent-memory/reference/api/reasoning Demonstrates how to initialize a MemoryClient and access the reasoning client for trace operations. Ensure you have the necessary settings configured. ```python async with MemoryClient(settings) as client: # Access via client reasoning = client.reasoning # Start a reasoning trace trace = await reasoning.start_trace( session_id="user-123", task="Find restaurant recommendations" ) ``` -------------------------------- ### Install neo4j-agent-memory Source: https://neo4j.com/labs/agent-memory/reference Install the neo4j-agent-memory package using pip. Options include basic installation, installation with all extras, or installation with specific extras. ```bash # Basic installation pip install neo4j-agent-memory ``` ```bash # With all extras pip install neo4j-agent-memory[all] ``` ```bash # Specific extras pip install neo4j-agent-memory[gliner,openai,cli] ``` -------------------------------- ### Install Hints and Debugging Source: https://neo4j.com/labs/agent-memory/reference/api/factory Provides guidance on installing necessary extras and debugging adapter resolution, including enabling debug logging and inspecting the returned provider type. ```APIDOC ## Install hints When no adapter is available, the `ImportError` message is provider-specific: ``` No llm adapter available for provider 'anthropic'. Install one of the following: pip install 'neo4j-agent-memory[anthropic]' # native adapter pip install 'neo4j-agent-memory[litellm]' # universal adapter (recommended) ``` ## Debugging which adapter you got Enable debug logging: ```python import logging logging.getLogger("neo4j_agent_memory.llm.factory").setLevel(logging.DEBUG) from neo4j_agent_memory.llm import from_provider provider = from_provider("openai/gpt-4o-mini") # DEBUG: from_provider: routing 'openai/gpt-4o-mini' to native OpenAIProvider ``` Or just inspect the type: ```python print(type(provider).__name__) # OpenAIProvider ``` ``` -------------------------------- ### Install neo4j-agent-memory with AWS support Source: https://neo4j.com/labs/agent-memory/how-to/integrations/aws-hybrid-memory Install the necessary package for AWS integration. This command installs the core library and the AWS-specific dependencies. ```bash pip install neo4j-agent-memory[aws] ``` -------------------------------- ### Install Core Neo4j Agent Memory Package Source: https://neo4j.com/labs/agent-memory/getting-started Install the main package using pip. This is the basic installation for the core functionality. ```bash pip install neo4j-agent-memory ``` -------------------------------- ### Configuration Precedence Example Source: https://neo4j.com/labs/agent-memory/reference/configuration Demonstrates how environment variables are used by default and how explicit Python arguments override them. ```python import os # Set environment variable os.environ["NAM_NEO4J__URI"] = "bolt://env-server:7687" # This will use the environment variable settings = MemorySettings() print(settings.neo4j.uri) # bolt://env-server:7687 # This will override the environment variable settings = MemorySettings( neo4j={"uri": "bolt://explicit-server:7687"} ) print(settings.neo4j.uri) # bolt://explicit-server:7687 ``` -------------------------------- ### Install GLiNER Optional Dependency Source: https://neo4j.com/labs/agent-memory/faq Install GLiNER as an optional dependency using pip or uv to enable advanced extraction features. This command installs the necessary packages. ```bash pip install neo4j-agent-memory[gliner] # or uv sync --all-extras ``` -------------------------------- ### Install Neo4j Agent Memory with Extraction and Sentence Transformers Source: https://neo4j.com/labs/agent-memory/how-to/running-without-an-llm Install the necessary packages for running neo4j-agent-memory with local extraction and sentence-transformers. This command also includes the Python package installation. ```bash pip install "neo4j-agent-memory[extraction,sentence-transformers]" python -m spacy download en_core_web_sm ``` -------------------------------- ### Start MCP Server with Profile Source: https://neo4j.com/labs/agent-memory/reference/mcp-tools Use the `neo4j-agent-memory mcp serve` command to start the server. Specify the `--profile` flag to select either the 'core' profile (6 tools) or the 'extended' profile (16 tools, default). ```bash neo4j-agent-memory mcp serve --profile core # 6 tools neo4j-agent-memory mcp serve --profile extended # 16 tools (default) ``` -------------------------------- ### Install Vercel CLI Source: https://neo4j.com/labs/agent-memory/reference/deployment Installs the Vercel command-line interface globally using npm. ```bash npm install -g vercel ``` -------------------------------- ### Provider string examples Source: https://neo4j.com/labs/agent-memory/reference/api/factory Illustrates how to use the `from_provider` factory with various model strings and configurations to obtain different provider instances. ```APIDOC ## Examples ### Provider string → native adapter ```python from neo4j_agent_memory.llm import from_provider provider = from_provider("openai/gpt-4o-mini") # Returns OpenAIProvider when [openai] is installed. ``` ### Universal fallback for an unsupported provider ```python provider = from_provider("groq/llama-3.1-70b-versatile") # Returns LiteLLMProvider (no native Groq adapter). ``` ### Force LiteLLM even when native is available ```python provider = from_provider("openai/gpt-4o", prefer_litellm=True) # Returns LiteLLMProvider, ignoring the native adapter. ``` ### Local Ollama via LiteLLM ```python provider = from_provider( "ollama/llama3.2", api_base="http://localhost:11434", ) ``` ### Custom dimensions for an unknown embedder ```python embedder = from_provider( "my-org/private-model", kind="embedding", dimensions=512, ) ``` ### Pass api_key explicitly ```python provider = from_provider( "anthropic/claude-3-5-sonnet-latest", api_key="sk-ant-...", ) ``` ``` -------------------------------- ### Create Sample Documents with Python Source: https://neo4j.com/labs/agent-memory/tutorials/knowledge-graph Use this Python script to create a 'documents' folder and populate it with sample financial documents. This is a prerequisite for many knowledge graph operations. ```python import os os.makedirs("documents", exist_ok=True) DOCUMENTS = { "company_profile_acme.txt": """ Acme Investment Holdings LLC is a mid-sized investment firm headquartered in New York City. Founded in 2010 by CEO Sarah Johnson, the firm manages approximately $2 billion in assets for institutional and high-net-worth clients. The firm specializes in technology and healthcare sector investments. Their flagship fund, Acme Growth Fund, has consistently outperformed the S&P 500 benchmark over the past five years. Key personnel include: - Sarah Johnson, CEO and Founder - Michael Chen, Chief Investment Officer - Lisa Park, Head of Research - Robert Williams, Chief Compliance Officer The firm has offices in New York, Boston, and San Francisco. """, "earnings_report_q4.txt": """ Q4 2024 Earnings Summary - Tech Sector Overview Apple Inc. (AAPL) reported record quarterly revenue of $119.6 billion, driven by strong iPhone 15 sales. CEO Tim Cook highlighted growth in services revenue and the Apple Vision Pro launch. Microsoft Corporation (MSFT) exceeded expectations with $62 billion in revenue. CEO Satya Nadella emphasized AI integration across products and strong Azure cloud growth of 28% year-over-year. NVIDIA Corporation (NVDA) continues to dominate the AI chip market with $22 billion in data center revenue. CEO Jensen Huang announced expanded partnerships with major cloud providers. Amazon.com Inc. (AMZN) reported $170 billion in revenue with AWS growing 13%. CEO Andy Jassy highlighted AI services adoption and retail efficiency improvements. Alphabet Inc. (GOOGL) achieved $86 billion revenue with YouTube and Cloud showing strong momentum. CEO Sundar Pichai announced Gemini AI integration across Google products. """, "market_analysis.txt": """ 2024 Technology Sector Analysis The technology sector experienced significant transformation in 2024, driven primarily by artificial intelligence investments. Morgan Stanley analyst Brian Nowak raised price targets for several AI-focused companies. Goldman Sachs technology analyst Eric Sheridan maintains overweight ratings on Microsoft, Alphabet, and Amazon, citing cloud computing and AI tailwinds. JPMorgan's semiconductor team, led by analyst Harlan Sur, upgraded NVIDIA to overweight following strong data center demand. The firm also initiated coverage on AMD with a buy rating. BlackRock, the world's largest asset manager, increased technology sector allocation in their model portfolios. CEO Larry Fink cited AI as a "defining technology trend" in the recent quarterly letter. Regional focus: - Silicon Valley remains the primary hub for AI innovation - Austin, Texas emerging as secondary tech hub - Seattle maintaining cloud computing leadership - New York strengthening fintech presence """, "client_meeting_notes.txt": """ Client Meeting Notes - Acme Investment Holdings Date: January 15, 2024 Attendees: Sarah Johnson (Acme), Michael Chen (Acme), John Smith (Client) Discussion Summary: John Smith, portfolio manager at Riverside Capital, discussed rebalancing their $50 million technology allocation. Current holdings include Apple, Microsoft, and NVIDIA representing 60% of the portfolio. Key points discussed: 1. Reduce concentration in NVIDIA given valuation concerns 2. Add exposure to cloud infrastructure through Amazon AWS 3. Consider Alphabet for AI/advertising diversification 4. Maintain Apple position for dividend income Sarah Johnson recommended a phased rebalancing over Q1 2024 to minimize market impact. Michael Chen will prepare detailed trade recommendations. Action items: - Michael Chen to send trade proposal by January 20 - John Smith to review with Riverside's risk committee - Follow-up call scheduled for January 25 Next meeting: February 15, 2024 for Q1 review """ } for filename, content in DOCUMENTS.items(): with open(f"documents/{filename}", "w") as f: f.write(content.strip()) print(f"Created {len(DOCUMENTS)} sample documents in ./documents/") ``` -------------------------------- ### Serve with Core Profile and Per-Day Session Strategy Source: https://neo4j.com/labs/agent-memory/reference/cli Starts the MCP server using the 'core' tool profile and a 'per_day' session strategy. Requires Neo4j password and a user ID. ```bash # Core profile (fewer tools), per-day session strategy. neo4j-agent-memory mcp serve \ --password mypw \ --profile core \ --session-strategy per_day \ --user-id alice ``` -------------------------------- ### Environment Variables and Application Setup Source: https://neo4j.com/labs/agent-memory/tutorials/microsoft-agent-memory Set the necessary environment variables for Neo4j and OpenAI API keys, then load sample data and run the main application script. ```bash # Set environment variables export NEO4J_URI=bolt://localhost:7687 export NEO4J_USERNAME=neo4j export NEO4J_PASSWORD=password export OPENAI_API_KEY=sk-your-key # Load sample data python load_data.py # Run the assistant python main.py ``` -------------------------------- ### Install OpenAI Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the OpenAI library if you encounter an 'ImportError: No module named 'openai''. ```bash # If you get "ImportError: No module named 'openai'" pip install openai ``` -------------------------------- ### Python Agent Memory Client Example Source: https://neo4j.com/labs/agent-memory/tutorials/first-agent-memory Demonstrates how to initialize a MemoryClient, store a user message, and retrieve the conversation. Requires environment variables to be set. ```python # agent.py import asyncio import os from dotenv import load_dotenv from neo4j_agent_memory import MemoryClient, MemorySettings # Load environment variables load_dotenv() async def main(): # Create memory settings settings = MemorySettings( neo4j={"uri": os.getenv("NEO4J_URI", "bolt://localhost:7687"), "username": os.getenv("NEO4J_USER", "neo4j"), "password": os.getenv("NEO4J_PASSWORD", "password123")} ) async with MemoryClient(settings) as client: print("✓ Connected to Neo4j!") # Store a test message message = await client.short_term.add_message( session_id="test-session-001", role="user", content="Hello! I'm looking for running shoes. I really like Nike products.", ) print(f"✓ Stored message: {message.id}") # Retrieve the message conversation = await client.short_term.get_conversation( session_id="test-session-001" ) print(f"✓ Retrieved {len(conversation.messages)} message(s)") for msg in conversation.messages: print(f" [{msg.role}]: {msg.content}") print("✓ Connection closed!") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install CrewAI Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the CrewAI library if you encounter an 'ImportError: No module named 'crewai''. ```bash # If you get "ImportError: No module named 'crewai'" pip install crewai ``` -------------------------------- ### Set Up Neo4j Docker Container Source: https://neo4j.com/labs/agent-memory/tutorials/microsoft-agent-memory Starts a local Neo4j instance using Docker, exposing the standard Neo4j ports. ```bash docker run -d \ --name neo4j \ -p 7474:7474 -p 7687:7687 \ -e NEO4J_AUTH=neo4j/password \ neo4j:5 ``` -------------------------------- ### Install Neo4j Agent Memory SDK Source: https://neo4j.com/labs/agent-memory/sdks/python Install the core Python SDK using pip or uv. For optional extras like extractors or framework integrations, use the `[all]` extra. ```bash pip install neo4j-agent-memory ``` ```bash # or, with uv: uv add neo4j-agent-memory ``` ```bash pip install "neo4j-agent-memory[all]" ``` -------------------------------- ### Install @neo4j-labs/agent-memory Source: https://neo4j.com/labs/agent-memory/reference/typescript-api Install the agent-memory package using npm, pnpm, or bun. Requires Node.js 20+. ```bash npm install @neo4j-labs/agent-memory # pnpm add @neo4j-labs/agent-memory # bun add @neo4j-labs/agent-memory ``` -------------------------------- ### Install neo4j-agent-memory and CrewAI Source: https://neo4j.com/labs/agent-memory/how-to/integrations/crewai Install the necessary libraries for integrating neo4j-agent-memory with CrewAI. This includes crewai and crewai-tools. ```bash pip install neo4j-agent-memory crewai crewai-tools ``` -------------------------------- ### Expected Output from Script Source: https://neo4j.com/labs/agent-memory/tutorials/nams-quickstart The expected output after running the quickstart Python script. ```text Messages: 2 Entity stored: Alice Traces: ['Recommend dinner'] ``` -------------------------------- ### ORGANIZATION Entity Examples Source: https://neo4j.com/labs/agent-memory/explanation/poleo-model Examples showing the classification of companies, institutions, and groups under the ORGANIZATION entity type. ```text "Apple Inc." → ORGANIZATION:COMPANY "Red Cross" → ORGANIZATION:NONPROFIT "FBI" → ORGANIZATION:GOVERNMENT "MIT" → ORGANIZATION:EDUCATIONAL "Book Club" → ORGANIZATION:GROUP ``` -------------------------------- ### Initialize MemoryClient with API Key (Node.js) Source: https://neo4j.com/labs/agent-memory/how-to/typescript/edge-runtime This is the zero-config initialization that works on Node.js, Bun, and Deno, reading the API key from `process.env`. ```typescript const client = new MemoryClient(); // reads MEMORY_API_KEY from process.env ``` -------------------------------- ### Basic Neo4jMemoryService Usage Source: https://neo4j.com/labs/agent-memory/how-to/integrations/google-cloud Demonstrates initializing Neo4jMemoryService and performing basic memory operations like adding a session and searching memory. ```python from neo4j_agent_memory import MemoryClient, MemorySettings from neo4j_agent_memory.integrations.google_adk import Neo4jMemoryService async with MemoryClient(settings) as client: # Create memory service memory_service = Neo4jMemoryService( memory_client=client, user_id="user-123", include_entities=True, include_preferences=True, ) # Store a conversation session session = { "id": "session-1", "messages": [ {"role": "user", "content": "I prefer dark mode"}, {"role": "assistant", "content": "Noted!"}, ] } await memory_service.add_session_to_memory(session) # Search across all memory types results = await memory_service.search_memory( query="user preferences", limit=10, ) for entry in results: print(f"[{entry.memory_type}] {entry.content}") ``` -------------------------------- ### Install TypeScript client Source: https://neo4j.com/labs/agent-memory/tutorials/hosted-quickstart-typescript Install the official Neo4j Labs agent memory client for TypeScript using npm. ```typescript npm install @neo4j-labs/agent-memory ``` -------------------------------- ### Create Shopping Assistant Agent with Memory Tools Source: https://neo4j.com/labs/agent-memory/tutorials/microsoft-agent-memory Defines the system prompt and creates product tools bound to a memory instance. The agent is then constructed using AzureOpenAIResponsesClient, incorporating both memory and product tools. ```python """Shopping assistant agent.""" import json from typing import Annotated from agent_framework import Agent, FunctionTool, Message, tool from agent_framework.azure import AzureOpenAIResponsesClient from neo4j_agent_memory.integrations.microsoft_agent import ( Neo4jMicrosoftMemory, create_memory_tools, record_agent_trace, ) SYSTEM_PROMPT = """You are a helpful shopping assistant. Your role is to: 1. Help customers find products that match their needs 2. Learn and remember their preferences (brands, styles, budget) 3. Provide personalized recommendations based on their history 4. Explain how products relate to each other When customers express preferences, use the remember_preference tool to save them. When recommending products, explain why they match the customer's preferences. """ def get_product_tools(memory: Neo4jMicrosoftMemory) -> list[FunctionTool]: """Create callable product tools bound to a memory instance.""" client = memory.memory_client @tool(name="search_products", description="Search for products matching a query") async def search_products( query: Annotated[str, "Search query describing the product"], category: Annotated[str | None, "Optional category filter"] = None, max_price: Annotated[float | None, "Optional maximum price"] = None, ) -> str: """Search products in the catalog.""" conditions = [] params: dict = {"query": query} if category: conditions.append("p.category = $category") params["category"] = category if max_price: conditions.append("p.price <= $max_price") params["max_price"] = max_price where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else "" cypher = f""" MATCH (p:Product) {where_clause} {"WHERE" if not where_clause else "AND"} (toLower(p.name) CONTAINS toLower($query) OR toLower(p.description) CONTAINS toLower($query)) RETURN p.name as name, p.price as price, p.category as category, p.brand as brand LIMIT 5 """ result = await client.graph.execute_read(cypher, params) products = [dict(r) for r in result] return json.dumps({"products": products, "count": len(products)}) return [search_products] async def create_agent(memory: Neo4jMicrosoftMemory) -> Agent: """Create the shopping assistant agent.""" chat_client = AzureOpenAIResponsesClient(model="gpt-4") # Create memory tools bound to the memory instance memory_tools = create_memory_tools(memory, include_gds_tools=bool(memory.gds)) # Create product tools bound to the memory instance product_tools = get_product_tools(memory) # Create agent — framework auto-invokes all callable tools return chat_client.as_agent( name="ShoppingAssistant", instructions=SYSTEM_PROMPT, tools=memory_tools + product_tools, context_providers=[memory.context_provider], ) ``` -------------------------------- ### Deploy Documentation via Vercel CLI Source: https://neo4j.com/labs/agent-memory/reference/deployment Deploys the documentation from the 'docs' directory using the Vercel CLI. Use the --prod flag for production deployments. ```bash cd docs vercel ``` ```bash vercel --prod ``` -------------------------------- ### Install neo4j-agent-memory and llama-index Source: https://neo4j.com/labs/agent-memory/how-to/integrations/llamaindex Install the necessary Python packages for neo4j-agent-memory and llama-index, including the OpenAI LLM integration. ```bash pip install neo4j-agent-memory llama-index llama-index-llms-openai ``` -------------------------------- ### Install Strands Agents Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the Strands Agents library if you encounter an 'ImportError: No module named 'strands''. ```bash # If you get "ImportError: No module named 'strands'" pip install strands-agents ``` -------------------------------- ### Set up Neo4j instance with Docker Source: https://neo4j.com/labs/agent-memory/tutorials/anthropic-and-local-embeddings Launches a Neo4j 5.11+ community edition instance using Docker, exposing the necessary ports and enabling the APOC plugin. This is a prerequisite for the agent memory system. ```bash docker run \ --name neo4j-memory \ -p 7474:7474 -p 7687:7687 \ -e NEO4J_AUTH=neo4j/password123 \ -e NEO4J_PLUGINS='["apoc"]' \ -d \ neo4j:5.26-community ``` -------------------------------- ### Initialize and Connect Memory Client Source: https://neo4j.com/labs/agent-memory/how-to/integrations/pydantic-ai Sets up and connects to the Neo4j memory client using provided settings. ```python async def main(): # Initialize memory client settings = MemorySettings( neo4j={"uri": "bolt://localhost:7687", "username": "neo4j", "password": "password"} ) memory_client = MemoryClient(settings) await memory_client.connect() ``` -------------------------------- ### Install Pydantic AI Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the Pydantic AI library if you encounter an 'ImportError: No module named 'pydantic_ai''. ```bash # If you get "ImportError: No module named 'pydantic_ai'" pip install pydantic-ai ``` -------------------------------- ### Install LlamaIndex Core Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the LlamaIndex core library if you encounter an 'ImportError: No module named 'llama_index''. ```bash # If you get "ImportError: No module named 'llama_index'" pip install llama-index-core ``` -------------------------------- ### Install LangChain Core Source: https://neo4j.com/labs/agent-memory/explanation/framework-comparison Install the LangChain core library if you encounter an 'ImportError: No module named 'langchain_core''. ```bash # If you get "ImportError: No module named 'langchain_core'" pip install langchain-core ```