Neo4j メモリ プロバイダー

Neo4j メモリ プロバイダーは、Agent Framework エージェントにナレッジ グラフによってサポートされる永続的なメモリを提供します。 静的ナレッジ ベースから取得する RAG プロバイダーとは異なり、メモリ プロバイダーはエージェントの対話を格納して呼び戻し、エンティティを自動的に抽出し、時間の経過と同時にナレッジ グラフを構築します。

プロバイダーは、次の 3 種類のメモリを管理します。

  • 短期メモリ: 会話履歴と最近のコンテキスト
  • 長期的なメモリ: 相互作用から抽出されたエンティティ、基本設定、ファクト
  • 推論メモリ: 過去の推論トレースとツールの使用パターン

エージェント メモリに Neo4j を使用する理由

  • ナレッジ グラフの永続性: メモリはフラット レコードではなく、接続されたエンティティとして格納されるため、エージェントは記憶しているものの間の関係を推論できます。
  • エンティティの自動抽出: 会話は、スキーマを手動で設計することなく、構造化されたエンティティとリレーションシップに解析されます。
  • セッション間の呼び戻し: ユーザー設定、ファクト、推論トレースはセッション間で保持され、コンテキスト プロバイダーを介して自動的に表示されます。

Neo4j は、Agent Framework 用に 2 つの個別の統合を提供します。 このプロバイダー (neo4j-agent-memory) は 、永続的なメモリ (エージェントの対話の格納と呼び戻し、エンティティの抽出、時間の経過に伴うナレッジ グラフの構築) 用です。 ベクター、フルテキスト、またはハイブリッド検索を使用した既存のナレッジ グラフからの GraphRAG については、 Neo4j GraphRAG コンテキスト プロバイダーを参照してください。

.NET パッケージ (AgentMemory) は、Neo4j Labs メモリ プロバイダーのコミュニティが管理する独立した.NET ポートであり、Neo4j Labs の公式パッケージではありません。 ソースと詳細については、AgentMemory (.NET) リポジトリを参照してください。

前提条件

  • Neo4j インスタンス (セルフホステッドまたは Neo4j AuraDB)
  • Azure OpenAI または Microsoft Foundry デプロイ (チャット モデル + 埋め込みモデル)
  • 環境変数セット: NEO4J_URINEO4J_USERNAMENEO4J_PASSWORDAZURE_OPENAI_ENDPOINT
  • 構成済みの Azure CLI 資格情報 (az login) または API キー
  • .NET 8.0 以降

Installation

dotnet add package AgentMemory
dotnet add package AgentMemory.AgentFramework

使用方法

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 は、各実行前に関連するメモリを呼び出し、後に新しいメモリを保持します。手動による配線は必要ありません
  • エンティティ抽出: 構成可能な抽出パイプラインを使用して会話からナレッジ グラフを構築する (AutoExtractOnPersist)
  • ユーザー設定の学習: 同じユーザーに対するまったく新しい AgentSession によって自動的に呼び戻される、ユーザーの基本設定、ファクト、エンティティを推論して格納します
  • メモリ ツール: MemoryToolFactoryAIFunctionを公開するため、モデルは明示的に検索、記憶、呼び戻しを行うことができます
  • 依存関係の挿入を前提にした設計: AddNeo4jAgentMemory(内部で Core + Neo4j を接続)と AddAgentMemoryFramework を使用して登録でき、Generic Host や ASP.NET Core アプリに自然に適合します
  • エージェント フレームワークを超えて: 同じライブラリは、Semantic Kernelおよび MCP クライアントとも統合され、組み込みの OpenTelemetry 可観測性が含まれています

リソース

前提条件

  • Neo4j インスタンス (セルフホステッドまたは Neo4j AuraDB)
  • デプロイされたチャット モデルを使用した Azure AI Foundry プロジェクト
  • OpenAI API キーまたは Azure OpenAI デプロイ (埋め込みとエンティティ抽出用)
  • 環境変数セット: NEO4J_URINEO4J_PASSWORDFOUNDRY_PROJECT_ENDPOINTFOUNDRY_MODELOPENAI_API_KEY
  • 構成された Azure CLI 資格情報 (az login)
  • Python 3.10 以降

Installation

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

使用方法

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)

主要な機能

  • 双方向: 呼び出し前に関連するコンテキストを自動的に取得し、応答後に新しいメモリを保存する
  • エンティティ抽出: マルチステージ抽出パイプラインを使用して会話からナレッジ グラフを構築する
  • ユーザー設定の学習: セッション間でユーザー設定を推論して格納する
  • メモリ ツール: エージェントは、メモリを明示的に検索し、基本設定を記憶し、エンティティ接続を見つけることができます

リソース

この機能の Go サポートは近日公開予定です。 最新の状態については、 Agent Framework Go リポジトリ を参照してください。

次のステップ