Neo4j

Neo4j 支持两种不同的代理框架上下文提供程序模式。 它们共享图形数据库,但使用单独的包和数据流。

图案 Behavior
GraphRAG 使用矢量、全文或混合检索搜索现有索引知识图,并使用 Cypher 遍历相关实体。
永久性内存 从对话中提取实体、事实、首选项和推理,并构建可在会话之间召回的知识图。

基于现有知识图谱的 GraphRAG

Neo4j GraphRAG 上下文提供程序使用 Neo4j 知识图将检索扩充生成(RAG)功能添加到 Agent Framework 代理。 它支持矢量、全文和混合搜索模式,使用可选的图形遍历通过自定义 Cypher 查询来扩充相关实体的结果。

有关其他托管检索服务,请参阅 Foundry IQ(Azure AI 搜索)和 Microsoft Foundry。

对于实体之间的关系很重要的知识图方案,此提供程序检索相关的子图而不是独立文本区块,从而为代理提供更丰富的上下文来生成响应。

为什么将 Neo4j 用于 GraphRAG?

  • 图谱增强检索:标准矢量搜索返回独立区块;图形遍历遵循与相关实体的连接,为代理提供更丰富的上下文。
  • 灵活的搜索模式:在单个查询中合并矢量相似性、关键字/BM25 和图形遍历。
  • 自定义检索查询:使用 Cypher 查询可以准确控制要遍历的关系以及要返回的上下文。

Prerequisites

  • 配置矢量或全文索引的 Neo4j 实例(自托管或 Neo4j AuraDB)
  • 具有已部署聊天模型和嵌入模型的 Azure AI Foundry 项目(例如 text-embedding-3-small)
  • 环境变量集:NEO4J_URI、、NEO4J_USERNAMENEO4J_PASSWORD、AZURE_AI_SERVICES_ENDPOINT、AZURE_AI_EMBEDDING_NAME
  • 已配置 Azure CLI 凭据 (az login)
  • .NET 8.0 或更高版本

Installation

dotnet add package Neo4j.AgentFramework.GraphRAG

Usage

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.OpenAI;
using Microsoft.Extensions.AI;
using Neo4j.AgentFramework.GraphRAG;
using Neo4j.Driver;

// Read connection details from environment variables
var neo4jSettings = new Neo4jSettings();
var azureEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_SERVICES_ENDPOINT")!;

// Create embedding generator
var credential = new DefaultAzureCredential();
var azureClient = new AzureOpenAIClient(new Uri(azureEndpoint), credential);

IEmbeddingGenerator<string, Embedding<float>> embedder = azureClient
    .GetEmbeddingClient("text-embedding-3-small")
    .AsIEmbeddingGenerator();

// Create Neo4j driver
await using var driver = GraphDatabase.Driver(
    neo4jSettings.Uri, AuthTokens.Basic(neo4jSettings.Username, neo4jSettings.Password!));

// Create the Neo4j context provider
await using var provider = new Neo4jContextProvider(driver, new Neo4jContextProviderOptions
{
    IndexName = "chunkEmbeddings",
    IndexType = IndexType.Vector,
    EmbeddingGenerator = embedder,
    TopK = 5,
    RetrievalQuery = """
        MATCH (node)-[:FROM_DOCUMENT]->(doc:Document)
        OPTIONAL MATCH (doc)<-[:FILED]-(company:Company)
        RETURN node.text AS text, score, doc.title AS title, company.name AS company
        ORDER BY score DESC
        """,
});

// Create an agent with the provider
AIAgent agent = azureClient
    .GetChatClient("gpt-4o")
    .AsIChatClient()
    .AsBuilder()
    .UseAIContextProviders(provider)
    .BuildAIAgent(new ChatClientAgentOptions
    {
        ChatOptions = new ChatOptions
        {
            Instructions = "You are a financial analyst assistant.",
        },
    });

var session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("What risks does Acme Corp face?", session));

主要功能

  • 索引驱动:适用于任何 Neo4j 矢量或全文索引
  • 图形遍历:自定义 Cypher 查询可通过相关实体丰富搜索结果
  • 搜索模式:矢量(语义相似性)、全文(关键字/BM25)或混合(两者均组合)

Resources

Prerequisites

  • 配置矢量或全文索引的 Neo4j 实例(自托管或 Neo4j AuraDB)
  • 具有已部署聊天模型和嵌入模型的 Azure AI Foundry 项目(例如 text-embedding-ada-002)
  • 环境变量集:NEO4J_URI、、NEO4J_USERNAME、NEO4J_PASSWORDFOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL、AZURE_AI_EMBEDDING_NAME
  • 已配置 Azure CLI 凭据 (az login)
  • Python 3.11 或更高版本

Installation

pip install agent-framework-neo4j

Usage

import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from agent_framework_neo4j import Neo4jContextProvider, Neo4jSettings, AzureAISettings, AzureAIEmbedder
from azure.identity import DefaultAzureCredential
from azure.identity.aio import AzureCliCredential

# Reads NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD from environment variables
neo4j_settings = Neo4jSettings()

# Reads FOUNDRY_PROJECT_ENDPOINT, AZURE_AI_EMBEDDING_NAME from environment variables
azure_settings = AzureAISettings()

sync_credential = DefaultAzureCredential()
embedder = AzureAIEmbedder(
    endpoint=azure_settings.inference_endpoint,
    credential=sync_credential,
    model=azure_settings.embedding_model,
)

neo4j_provider = Neo4jContextProvider(
    uri=neo4j_settings.uri,
    username=neo4j_settings.username,
    password=neo4j_settings.get_password(),
    index_name=neo4j_settings.vector_index_name,
    index_type="vector",
    embedder=embedder,
    top_k=5,
    retrieval_query="""
        MATCH (node)-[:FROM_DOCUMENT]->(doc:Document)
        OPTIONAL MATCH (doc)<-[:FILED]-(company:Company)
        RETURN node.text AS text, score, doc.title AS title, company.name AS company
        ORDER BY score DESC
    """,
)

async with (
    neo4j_provider,
    AzureCliCredential() as credential,
    Agent(
        client=FoundryChatClient(
            credential=credential,
            project_endpoint=azure_settings.project_endpoint,
            model=os.environ["FOUNDRY_MODEL"],
        ),
        instructions="You are a financial analyst assistant.",
        context_providers=[neo4j_provider],
    ) as agent,
):
    session = agent.create_session()
    response = await agent.run("What risks does Acme Corp face?", session=session)

主要功能

  • 索引驱动:适用于任何 Neo4j 矢量或全文索引
  • 图遍历:自定义 Cypher 查询用相关实体丰富搜索结果
  • 搜索模式:矢量(语义相似性)、全文(关键字/BM25)或混合(两者均组合)

Resources

Go 存储库包含 Neo4j GraphRAG 示例。 它实现一个自定义上下文提供程序,该提供程序从全文索引中检索文本,并使用图形关系对其进行扩充。

配置 NEO4J_URI、 NEO4J_PASSWORD和(可选) NEO4J_USERNAME 和 NEO4J_FULLTEXT_INDEX_NAME。 默认值是 neo4j 和 search_chunks。 同时配置 Foundry 聊天部署和Azure凭据。

图和全文索引必须已存在,且其架构应符合该示例的预期。 此示例不会生成嵌入内容,也不会为图设置种子。 检索到的图谱上下文从保留的对话历史记录中排除,以便后续搜索使用对话轮次而不是较早的搜索结果。

有关先决条件,请参阅 Go RAG 配置指南 。 这是一个自定义检索示例,而不是内置的 Neo4j 矢量存储或内存连接器。

持久代理记忆

Neo4j 记忆集成可存储并检索智能体交互,自动提取实体,并逐步构建知识图谱。

提供程序管理以下内容:

  • 短期记忆:对话历史记录和最近上下文。
  • 长期记忆:从交互中提取的实体、首选项和事实。
  • 推理内存:过去的推理跟踪和工具使用模式。

为什么将 Neo4j 用于代理内存?

  • 知识图持久性:记忆存储为连接的实体,而不是平面记录,因此代理可以推理记住的信息之间的关系。
  • 自动实体提取:将对话解析为结构化实体和关系,而无需手动定义模式。
  • 跨会话召回:首选项、事实和推理跟踪可跨会话保留,并通过上下文提供程序呈现。

注释

.NET 包(AgentMemory)是 Neo4j Labs 内存提供程序的一个由社区独立维护的 .NET 移植版本。 这不是 Neo4j Labs 官方软件包。 有关源和详细信息,请参阅 AgentMemory (.NET) 存储库。

Prerequisites

  • Neo4j 实例(自行托管或 Neo4j AuraDB)。
  • 配备聊天模型和嵌入模型的 Azure OpenAI 或 Microsoft Foundry 部署。
  • 环境变量集:NEO4J_URI、、NEO4J_USERNAMENEO4J_PASSWORD. AZURE_OPENAI_ENDPOINT
  • 已配置的 Azure CLI 凭据(az login),或 API 密钥
  • .NET 8.0 或更高版本。

Installation

dotnet add package AgentMemory
dotnet add package AgentMemory.AgentFramework

Usage

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AgentMemory;
using AgentMemory.Abstractions.Services;
using AgentMemory.AgentFramework;
using AgentMemory.AgentFramework.Tools;

var builder = Host.CreateApplicationBuilder(args);

// Registers Core + Neo4j infrastructure in one call (reads NEO4J_URI / NEO4J_USERNAME /
// NEO4J_PASSWORD, falling back to local-dev defaults). Passing configureLlm opts in to
// LLM-backed entity/fact/preference extraction, using the IChatClient registered below.
builder.Services.AddNeo4jAgentMemory(
    configureMemory: _ => { },
    configureNeo4j: neo4j =>
    {
        neo4j.Uri = Environment.GetEnvironmentVariable("NEO4J_URI") ?? "bolt://localhost:7687";
        neo4j.Username = Environment.GetEnvironmentVariable("NEO4J_USERNAME") ?? "neo4j";
        neo4j.Password = Environment.GetEnvironmentVariable("NEO4J_PASSWORD") ?? "password";
    },
    configureLlm: _ => { });

// Any Microsoft.Extensions.AI-compatible chat + embedding client works
var azureClient = new AzureOpenAIClient(
    new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!), new DefaultAzureCredential());
builder.Services.AddSingleton(azureClient.GetChatClient("gpt-4o-mini").AsIChatClient());
builder.Services.AddSingleton(azureClient.GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator());

// AutoExtractOnPersist builds the knowledge graph from every conversation turn
builder.Services.AddAgentMemoryFramework(options =>
{
    options.AutoExtractOnPersist = true;
    options.ContextFormat.IncludeEntities = true;
    options.ContextFormat.IncludeFacts = true;
    options.ContextFormat.IncludePreferences = true;
});

using var host = builder.Build();
await using var scope = host.Services.CreateAsyncScope();
var services = scope.ServiceProvider;

// Bootstraps Neo4j schema/indexes on first run (idempotent)
await services.GetRequiredService<ISchemaBootstrapper>().BootstrapAsync();

var memoryProvider = services.GetRequiredService<Neo4jMemoryContextProvider>();
var memoryTools = services.GetRequiredService<MemoryToolFactory>().CreateAIFunctions();

// WithMemoryOwnerScoping wraps the whole invocation — recall, the tool-calling loop, and
// persistence — in the owner scope set by WithMemoryIdentity below, so no manual
// BeginOwnerScope call is needed around RunAsync.
AIAgent agent = services.GetRequiredService<IChatClient>().AsAIAgent(new ChatClientAgentOptions
{
    ChatOptions = new ChatOptions
    {
        Instructions = "You are a helpful assistant with persistent memory.",
        Tools = [.. memoryTools],
    },
    AIContextProviders = [memoryProvider],
}).WithMemoryOwnerScoping(services);

var session = (await agent.CreateSessionAsync())
    .WithMemoryIdentity(userId: "user-123", sessionId: "session-1", applicationId: "my-app");

var response = await agent.RunAsync("Remember that I prefer window seats on flights.", session);

主要功能

  • 双向:Neo4jMemoryContextProvider 在每次运行之前召回相关记忆,并在运行后持久化新记忆。
  • 实体提取:可配置的提取管道从对话生成知识图。
  • 偏好学习:同一用户的新 AgentSession 可以召回偏好、事实和实体。
  • 内存工具:MemoryToolFactory 公开 AIFunction 实例,用于显式的搜索、记住和召回操作。
  • 优先支持依赖注入:AddNeo4jAgentMemory 和 AddAgentMemoryFramework 可与 Generic Host 和 ASP.NET Core 应用程序集成。
  • 除了代理框架:同一库还与语义内核和 MCP 客户端集成,并包括 OpenTelemetry 可观测性。

Resources

Prerequisites

  • Neo4j 实例(自行托管或 Neo4j AuraDB)。
  • 具有已部署聊天模型的 Microsoft Foundry 项目。
  • OpenAI API 密钥或 Azure OpenAI 部署,用于嵌入和实体提取。
  • 环境变量集:NEO4J_URI、、NEO4J_PASSWORDFOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODELOPENAI_API_KEY.
  • 已配置的 Azure CLI 凭据(az login)。
  • Python 3.11 或更高版本。

Installation

pip install neo4j-agent-memory[microsoft-agent]

Usage

import os
from pydantic import SecretStr
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity.aio import AzureCliCredential
from neo4j_agent_memory import MemoryClient, MemorySettings
from neo4j_agent_memory.integrations.microsoft_agent import (
    Neo4jMicrosoftMemory,
    create_memory_tools,
)

# Pass Neo4j and embedding configuration directly via constructor arguments.
# MemorySettings also supports loading from environment variables or .env files
# using the NAM_ prefix (e.g. NAM_NEO4J__URI, NAM_EMBEDDING__MODEL).
settings = MemorySettings(
    neo4j={
        "uri": os.environ["NEO4J_URI"],
        "username": os.environ.get("NEO4J_USERNAME", "neo4j"),
        "password": SecretStr(os.environ["NEO4J_PASSWORD"]),
    },
    embedding={
        "provider": "openai",
        "model": "text-embedding-3-small",
    },
)

memory_client = MemoryClient(settings)

async with memory_client:
    memory = Neo4jMicrosoftMemory.from_memory_client(
        memory_client=memory_client,
        session_id="user-123",
    )
    tools = create_memory_tools(memory)

    async with AzureCliCredential() as credential, Agent(
        client=FoundryChatClient(
            credential=credential,
            project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
            model=os.environ["FOUNDRY_MODEL"],
        ),
        instructions="You are a helpful assistant with persistent memory.",
        tools=tools,
        context_providers=[memory.context_provider],
    ) as agent:
        session = agent.create_session()
        response = await agent.run("Remember that I prefer window seats on flights.", session=session)

主要功能

  • 双向:在调用之前检索相关上下文,并在响应后保存新内存。
  • 实体提取:通过多阶段提取管道从对话中构建知识图谱。
  • 首选项学习:跨会话推断和存储用户首选项。
  • 内存工具:允许代理显式搜索内存、记住首选项和查找实体连接。

Resources

注释

Go SDK 不包括其他 SDK 中所述的专用 Neo4j 持久内存提供程序。 Go Neo4j GraphRAG 示例从现有图谱中检索;它不会在 Neo4j 中存储对话记忆。

后续步骤