Neo4j

Neo4j 支援兩種截然不同的代理框架上下文提供者模式。 它們共用一個圖形資料庫,但使用不同的套件和資料流。

Pattern 行為
GraphRAG 可透過向量、全文或混合檢索搜尋現有索引知識圖譜,並可透過 Cypher 遍歷相關實體。
持久性記憶 從對話中提取實體、事實、偏好與推理,並建立可跨會談回憶的知識圖譜。

從現有知識圖建立 GraphRAG

Neo4j GraphRAG 情境提供者透過 Neo4j 知識圖譜,為代理框架代理加入檢索增強生成(RAG)功能。 它支援向量、全文及混合式搜尋模式,並可選擇使用圖形遍歷,透過自訂 Cypher 查詢豐富相關實體的結果。

關於其他受管理檢索服務,請參見 Azure AI 搜尋服務 和 Microsoft Foundry。

對於實體間關係重要的知識圖譜情境,此提供者會擷取相關的子圖,而非孤立的文字區塊,為代理提供更豐富的回應脈絡。

為什麼要用 Neo4j 來做 GraphRAG?

  • 圖增強檢索:標準向量搜尋回傳孤立區塊;圖遍歷會跟隨與表面相關實體的連結,為代理人提供更豐富的上下文。
  • 彈性搜尋模式:將向量相似度、關鍵字/BM25 與圖形遍歷整合於單一查詢中。
  • 自訂檢索查詢:Cypher 查詢讓您精確控制要穿越哪些關係,以及回傳哪些上下文。

Prerequisites

  • 一個 Neo4j 實例(自架或 Neo4j AuraDB),且已設定向量或全文索引
  • 一個 Azure AI Foundry 專案,包含已部署的聊天模型和嵌入模型(例如 ) text-embedding-3-small
  • 環境變數設定:NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORDAZURE_AI_SERVICES_ENDPOINTAZURE_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 向量或全文索引
  • 圖周遊:自訂加密查詢以相關實體擴充搜尋結果
  • 搜尋模式:向量(語意相似)、全文(關鍵字/BM25)、或混合(兩者結合)

Resources

Prerequisites

  • 一個 Neo4j 實例(自架或 Neo4j AuraDB),且已設定向量或全文索引
  • 一個 Azure AI Foundry 專案,包含已部署的聊天模型和嵌入模型(例如 ) text-embedding-ada-002
  • 環境變數設定:NEO4J_URI, NEO4J_USERNAME, , NEO4J_PASSWORDFOUNDRY_PROJECT_ENDPOINTFOUNDRY_MODELAZURE_AI_EMBEDDING_NAME
  • Azure CLI 憑證已配置(az login)
  • Python 3.10 或更新版本

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 向量或全文索引
  • 圖周遊:自訂加密查詢以相關實體擴充搜尋結果
  • 搜尋模式:向量(語意相似)、全文(關鍵字/BM25)、或混合(兩者結合)

Resources

備註

Go 對此功能的支援即將推出。 最新狀態請參閱 Agent Framework Go 倉庫 。

持久代理記憶體

Neo4j 記憶體整合系統能儲存並回憶代理互動,自動擷取實體並隨時間建立知識圖譜。

供應商負責管理:

  • 短期記憶:對話歷史與近期背景。
  • 長期記憶:從互動中提取的實體、偏好與事實。
  • 推理記憶:過去推理痕跡與工具使用模式。

為什麼要用 Neo4j 來做代理記憶體?

  • 知識圖譜持續性:記憶以連結實體形式儲存,而非平面記錄,因此代理人能推理記憶資訊之間的關係。
  • 自動實體擷取:對話被解析成結構化的實體與關係,無需手動定義架構。
  • 跨會話回憶:偏好、事實與推理痕跡會持續存在於各會話間,並透過情境提供者浮現。

備註

.NET 套件AgentMemory()是 Neo4j Labs 記憶體提供者的獨立且由社群維護的 .NET 移植版本。 它不是官方的 Neo4j Labs 套件。 請參閱 AgentMemory (.NET) 儲存庫以獲得原始碼與詳細資訊。

Prerequisites

  • Neo4j 實例(自行託管或 Neo4j AuraDB)。
  • Azure OpenAI 或 Microsoft Foundry 部署,包含聊天模型和嵌入模型。
  • 環境變數設定: NEO4J_URI, NEO4J_USERNAME, NEO4J_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 應用程式整合。
  • Beyond Agent Framework:同一函式庫亦整合 語意核心 與 MCP 用戶端,並包含 OpenTelemetry 可觀察性。

Resources

Prerequisites

  • Neo4j 實例(自行託管或 Neo4j AuraDB)。
  • 一個 Microsoft Foundry 專案,配備已部署的聊天模式。
  • OpenAI API 金鑰或 Azure OpenAI 部署用於嵌入與實體擷取。
  • 環境變數設定:NEO4J_URI, NEO4J_PASSWORD, FOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODELOPENAI_API_KEY, , 。
  • Azure CLI 認證已完成設定(az login)。
  • Python 3.10 或更新版本。

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

備註

Neo4j GraphRAG 和記憶體整合目前沒有在 Agent Framework Go 上被正式說明。 最新狀態請參閱 Agent Framework Go 倉庫 。

下一步