Redis

Redis는 SDK에서 다양한 컨텍스트 패턴을 지원합니다. .NET Redis 지원 검색을 RAG의 제네릭 TextSearchProvider 에 연결합니다. Agent Framework Redis 패키지는 Python 검색 가능한 메모리 및 대화 기록 공급자를 제공합니다.

Pattern API SDK 작동 방식
RAG TextSearchProvider Redis 검색 어댑터 사용 .NET 호출 전 또는 주문형 검색 도구를 통해 관련 Redis 콘텐츠를 검색합니다.
검색 가능한 메모리 RedisContextProvider Python 대화 세부 정보를 추출하고 전체 텍스트 또는 하이브리드 벡터 검색을 사용하여 관련 컨텍스트를 검색합니다.
대화 기록 RedisHistoryProvider Python 세션에 대한 정확한 메시지 기록을 유지 및 다시 로드합니다.

다음을 사용하여 RAG 추가 TextSearchProvider

.NET 공급자 독립적 TextSearchProvider 패턴을 사용합니다. 애플리케이션에서 선택한 Redis 클라이언트 또는 벡터 저장소 커넥터를 사용하여 검색 어댑터를 구현하고, Redis 결과를 TextSearchProvider.TextSearchResult매핑하고, 공급자를 통해 AIContextProviders연결합니다.

이 방법은 Redis 관련 에이전트 프레임워크 컨텍스트 공급자 패키지를 요구하지 않고 Redis 지원 RAG를 지원합니다.

패키지 설치

pip install agent-framework-redis --pre

검색 가능한 메모리 추가

에이전트가 이전 메시지를 재생하지 않고 선택한 관련 정보를 회수해야 하는 경우 이 패턴을 사용합니다.

사전 요구 사항

  • Redis Stack 또는 호환되는 관리되는 서비스와 같은 RediSearch 지원을 사용하는 Redis 배포입니다.
  • 샘플 에이전트에 대한 Microsoft Foundry 프로젝트 및 모델 배포입니다.
  • 하이브리드 벡터 검색을 사용하도록 설정할 때 포함 공급자입니다.

검색 가능한 메모리 구성

agent_iduser_id 사용하고 application_id메모리를 분할합니다. 하이브리드 검색을 원할 때 Redis 벡터라이저 및 벡터 필드 설정을 추가합니다.

# Create a provider with partition scope and OpenAI embeddings

# Please set OPENAI_API_KEY to use the OpenAI vectorizer.
# For chat responses, also set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL.

# We attach an embedding vectorizer so the provider can perform hybrid (text + vector)
# retrieval. If you prefer text-only retrieval, instantiate RedisContextProvider without the
# 'vectorizer' and vector_* parameters.
vectorizer = OpenAITextVectorizer(
    model="text-embedding-ada-002",
    api_config={"api_key": os.getenv("OPENAI_API_KEY")},
    cache=EmbeddingsCache(name="openai_embeddings_cache", redis_url=REDIS_URL),
)
# The provider manages persistence and retrieval. application_id/agent_id/user_id
# scope data for multi-tenant separation; thread_id (set later) narrows to a
# specific conversation.
provider = RedisContextProvider(
    source_id="redis_context",
    redis_url=REDIS_URL,
    index_name="redis_basics",
    application_id="matrix_of_kermits",
    agent_id="agent_kermit",
    user_id="kermit",
    redis_vectorizer=vectorizer,
    vector_field_name="vector",
    vector_algorithm="hnsw",
    vector_distance_metric="cosine",
)

에이전트에 메모리 연결

에 공급자를 추가합니다 context_providers. 공급자는 실행 후 대화형 세부 정보를 저장하고 나중에 실행하기 전에 관련 컨텍스트를 표시합니다.

# Create chat client for the agent
client = create_chat_client()
# Create agent wired to the Redis context provider. The provider automatically
# persists conversational details and surfaces relevant context on each turn.
agent = Agent(
    client=client,
    name="MemoryEnhancedAssistant",
    instructions=(
        "You are a helpful assistant. Personalize replies using provided context. "
        "Before answering, always check for stored context"
    ),
    tools=[],
    context_providers=[provider],
)

# Teach a user preference; the agent writes this to the provider's memory
query = "Remember that I enjoy glugenflorgle"
result = await agent.run(query)
print("User: ", query)
print("Agent: ", result)

# Ask the agent to recall the stored preference; it should retrieve from memory
query = "What do I enjoy?"
result = await agent.run(query)

대화 기록 유지

애플리케이션을 다시 시작한 후 또는 다른 인스턴스에서 세션이 전체 기록을 복구해야 하는 경우 이 패턴을 사용합니다.

사전 요구 사항

  • 를 통해 REDIS_URL연결할 수 있는 Redis 배포
  • 프로덕션 배포를 위한 TLS 및 인증된 Redis 사용자입니다.

를 통해 연결 RedisHistoryProvider 합니다.context_providers 공급자는 세션에 대한 메시지를 저장하고 보존된 메시지 수를 제한할 수 있습니다.

async def example_manual_memory_store() -> None:
    """Basic example of using Redis history provider."""
    print("=== Basic Redis History Provider Example ===")

    # Create Redis history provider
    redis_provider = RedisHistoryProvider(
        source_id="redis_basic_chat",
        redis_url=REDIS_URL,
    )

    # Create agent with Redis history provider
    agent = Agent(
        client=OpenAIChatClient(),
        name="RedisBot",
        instructions="You are a helpful assistant that remembers our conversation using Redis.",
        context_providers=[redis_provider],
    )

    # Create session
    session = agent.create_session()

    # Have a conversation
    print("\n--- Starting conversation ---")
    query1 = "Hello! My name is Alice and I love pizza."
    print(f"User: {query1}")
    response1 = await agent.run(query1, session=session)
    print(f"Agent: {response1.text}")

    query2 = "What do you remember about me?"
    print(f"User: {query2}")
    response2 = await agent.run(query2, session=session)
    print(f"Agent: {response2.text}")

클라이언트가 프로세스를 다시 시작한 후 동일한 논리 대화를 다시 시작해야 하는 경우 안정적인 세션 ID를 사용하고 신뢰할 수 있는 애플리케이션 스토리지에 serialize AgentSession 된 상태를 유지합니다.

비고

Redis 컨텍스트 공급자 통합은 현재 Agent Framework Go에 대해 문서화되지 않습니다. 최신 상태는 에이전트 프레임워크 Go 리포지토리 를 참조하세요.

프로덕션 고려 사항

  • 모델 출력이 아닌 인증된 애플리케이션 ID에서 테넌트, 검색, 메모리 및 세션 범위를 파생합니다.
  • TLS, Redis 인증 및 네트워크 격리를 사용합니다.
  • 테넌트 격리에 필요한 별도의 키 접두사 또는 배포를 사용합니다.
  • 필요한 내구성에 대한 지속성, 백업, 보존 및 제거를 구성합니다.
  • 검색된 메모리를 신뢰할 수 없는 입력으로 처리하고 간접 프롬프트 주입을 완화합니다.
  • 메시지를 유지하거나 검색 가능한 콘텐츠를 인덱싱하기 전에 중요한 콘텐츠를 수정합니다.

다음 단계

더 자세히 살펴보기: