Neo4j

Neo4j는 두 가지 고유한 Agent Framework 컨텍스트 공급자 패턴을 지원합니다. 그래프 데이터베이스를 공유하지만 별도의 패키지와 데이터 흐름을 사용합니다.

Pattern 작동 방식
GraphRAG 벡터, 전체 텍스트 또는 하이브리드 검색을 사용하여 기존 인덱싱된 지식 그래프를 검색하고 Cypher를 사용하여 관련 엔터티를 트래버스할 수 있습니다.
영구 메모리 대화에서 엔터티, 팩트, 기본 설정 및 추론을 추출하고 세션 간에 회수할 수 있는 지식 그래프를 작성합니다.

기존 지식 그래프의 GraphRAG

Neo4j GraphRAG 컨텍스트 공급자는 Neo4j 지식 그래프를 사용하여 에이전트 프레임워크 에이전트에 검색 증강 생성(RAG) 기능을 추가합니다. 사용자 지정 Cypher 쿼리를 통해 관련 엔터티를 사용하여 결과를 보강하는 선택적 그래프 순회를 통해 벡터, 전체 텍스트 및 하이브리드 검색 모드를 지원합니다.

다른 관리되는 검색 서비스는 Azure AI 검색Microsoft Foundry를 참조하세요.

엔터티 간의 관계가 중요한 지식 그래프 시나리오의 경우 이 공급자는 격리된 텍스트 청크가 아닌 관련 하위 그래프를 검색하여 에이전트에게 응답을 생성하기 위한 보다 풍부한 컨텍스트를 제공합니다.

GraphRAG에 Neo4j를 사용하는 이유는 무엇인가요?

  • 그래프 향상된 검색: 표준 벡터 검색은 격리된 청크를 반환합니다. 그래프 순회는 표면 관련 엔터티에 대한 연결을 따라 에이전트에 보다 풍부한 컨텍스트를 제공합니다.
  • 유연한 검색 모드: 단일 쿼리에서 벡터 유사성, 키워드/BM25 및 그래프 순회를 결합합니다.
  • 사용자 지정 검색 쿼리: Cypher 쿼리를 사용하면 트래버스할 관계와 반환할 컨텍스트를 정확하게 제어할 수 있습니다.

사전 요구 사항

  • 벡터 또는 전체 텍스트 인덱스가 구성된 Neo4j 인스턴스(자체 호스팅 또는 Neo4j AuraDB)
  • 배포된 채팅 모델 및 포함 모델이 있는 Azure AI Foundry 프로젝트(예: text-embedding-3-small
  • 환경 변수 집합: NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD, AZURE_AI_SERVICES_ENDPOINTAZURE_AI_EMBEDDING_NAME
  • 구성된 Azure CLI 자격 증명(az login)
  • .NET 8.0 이상

설치

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

사전 요구 사항

  • 벡터 또는 전체 텍스트 인덱스가 구성된 Neo4j 인스턴스(자체 호스팅 또는 Neo4j AuraDB)
  • 배포된 채팅 모델 및 포함 모델이 있는 Azure AI Foundry 프로젝트(예: text-embedding-ada-002
  • 환경 변수 집합: NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORDFOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODELAZURE_AI_EMBEDDING_NAME
  • 구성된 Azure CLI 자격 증명(az login)
  • Python 3.10 이상

설치

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 리포지토리 를 참조하세요.

영구 에이전트 메모리

Neo4j 메모리 통합은 에이전트 상호 작용을 저장하고 회수하여 엔터티를 자동으로 추출하고 시간이 지남에 따라 지식 그래프를 작성합니다.

공급자는 다음을 관리합니다.

  • 단기 메모리: 대화 기록 및 최근 컨텍스트입니다.
  • 장기 메모리: 상호 작용에서 추출된 엔터티, 기본 설정 및 팩트입니다.
  • 추론 메모리: 과거 추론 추적 및 도구 사용 패턴.

에이전트 메모리에 Neo4j를 사용하는 이유는 무엇인가요?

  • 지식 그래프 지속성: 기억은 플랫 레코드가 아닌 연결된 엔터티로 저장되므로 에이전트는 기억된 정보 간의 관계를 추론할 수 있습니다.
  • 자동 엔터티 추출: 대화는 수동으로 정의된 스키마 없이 구조화된 엔터티 및 관계로 구문 분석됩니다.
  • 세션 간 회수: 기본 설정, 팩트 및 추론 추적은 컨텍스트 공급자를 통해 세션 및 표면에서 유지됩니다.

비고

.NET 패키지(AgentMemory)는 Neo4j Labs 메모리 공급자의 독립적인 커뮤니티 유지 관리 .NET 포트입니다. 공식 Neo4j Labs 패키지가 아닙니다. 원본 및 세부 정보는 AgentMemory(.NET) 리포지토리를 참조하세요.

사전 요구 사항

  • Neo4j 인스턴스(자체 호스팅 또는 Neo4j AuraDB).
  • 채팅 모델 및 포함 모델이 있는 Azure OpenAI 또는 Microsoft Foundry 배포입니다.
  • 환경 변수 집합: NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORDAZURE_OPENAI_ENDPOINT.
  • 구성된 자격 증명(또는 API 키)az login을 Azure CLI.
  • .NET 8.0 이상.

설치

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 ASP.NET Core 애플리케이션과 통합합니다.
  • 에이전트 프레임워크 외: 동일한 라이브러리는 의미 체계 커널 및 MCP 클라이언트와도 통합되며 OpenTelemetry 관찰 가능성을 포함합니다.

Resources

사전 요구 사항

  • 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 이상.

설치

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에 대해 문서화되지 않습니다. 최신 상태는 에이전트 프레임워크 Go 리포지토리 를 참조하세요.

다음 단계