Redis

Redis では、SDK 間で異なるコンテキスト パターンがサポートされています。 .NETで、Redis でサポートされる検索を RAG の汎用TextSearchProviderに接続します。 Agent Framework Redis パッケージは、Pythonの検索可能なメモリおよび会話履歴プロバイダーを提供します。

Pattern API SDK Behavior
RAG TextSearchProvider Redis 検索アダプターを使用する .NET 呼び出し前またはオンデマンド検索ツールを使用して、関連する Redis コンテンツを取得します。
検索可能なメモリ RedisContextProvider Python 会話の詳細を抽出し、フルテキストまたはハイブリッド ベクター検索を使用して関連するコンテキストを取得します。
会話履歴 RedisHistoryProvider Python セッションのメッセージ記録をそのまま保存し、再読み込みします。

TextSearchProvider を使用して RAG を追加する

.NETには、プロバイダーに依存しないTextSearchProvider パターンを使用します。 アプリケーションによって選択された Redis クライアントまたはベクター ストア コネクタを使用して検索アダプターを実装し、Redis の結果を TextSearchProvider.TextSearchResultにマップし、 AIContextProviders経由でプロバイダーをアタッチします。

この方法では、Redis 固有の Agent Framework コンテキスト プロバイダー パッケージを必要とせずに、Redis でサポートされる RAG がサポートされます。

パッケージをインストールする

pip install agent-framework-redis --pre

検索可能なメモリを追加する

このパターンは、エージェントが前のすべてのメッセージを再生するのではなく、選択した関連情報を取り消す必要がある場合に使用します。

前提条件

  • Redis Stack や互換性のあるマネージド サービスなど、RediSearch がサポートされている Redis デプロイ。
  • サンプル エージェントのMicrosoft Foundry プロジェクトとモデルのデプロイ。
  • ハイブリッド ベクター検索を有効にしたときの埋め込みプロバイダー。

検索可能なメモリを構成する

検索可能なメモリ取得は、セッション間で機能します。 指定されたすべての application_id、 agent_id、および user_id は AND フィルターとして機能しますが、省略されたディメンションはフィルター処理されません。 少なくとも 1 つの識別子を指定する必要があります。 目的の分離境界を表す、安定した信頼できる識別子をすべて指定します。

ハイブリッド取得が必要な場合は、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,
        application_id=APPLICATION_ID,
        agent_id="redis-bot",
    )

    # 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}")

呼び出し元が管理する Redis クライアントを使用する

アプリケーションで接続プールを共有する必要がある場合や、境界付きタイムアウトや正常性チェックなどの接続動作を構成する必要がある場合は、 redis_client を指定します。 クライアントは、 decode_responses=Trueで構成されたスタンドアロンの非同期 Redis クライアントである必要があります。

from agent_framework.redis import RedisHistoryProvider
from redis.asyncio import Redis

redis_client = Redis.from_url(
    "redis://localhost:6379",
    decode_responses=True,
    socket_connect_timeout=3,
    socket_timeout=5,
)

history_provider = RedisHistoryProvider(
    redis_client=redis_client,
    application_id="support-app",
)

redis_clientをredis_urlやcredential_providerと組み合わせないでください。 RedisHistoryProvider はクライアントを借用し、クライアントを閉じないため、アプリケーションはその有効期間に対して引き続き責任を負います。 再試行の動作も呼び出し元によって制御されたままになります。 曖昧な接続切断の後に再試行によって書き込みが再実行された場合、トランスクリプトの追加はべき等ではありません。

スコープ付きキーが既定です。 安定した空でない application_idを設定し、アプリケーションに分離境界がある場合は tenant_id と agent_id を使用します。 また、プロバイダーは、各キーの source_id と空でないセッション ID によってスコープを設定します。

安定したセッション ID を使用し、プロセスの再起動後にクライアントが同じ論理会話を再開する必要がある場合に、シリアル化された AgentSession を信頼されたアプリケーション ストレージに保持します。

以前のリリースでは、履歴は{key_prefix}:{session_id or "default"}配下に保存されていました。 既存のデプロイでは、移行中に key_format="legacy" を一時的に設定できます。 レガシ モードは非推奨となり、スコープ付き識別子は受け入れられません。また、スコープ モードではレガシ キーの読み取り、書き換え、または削除は行われません。 検証済みレコードのみを対応するスコープ キーにコピーし、移行された履歴を検証してから、保持ポリシーに従ってレガシ キーを削除します。

Note

現在、Redis コンテキスト プロバイダーの統合については、Agent Framework Go に関するドキュメントは記載されていません。 最新の状態については、 Agent Framework Go リポジトリ を参照してください。

実稼働に関する考慮事項

  • モデル出力ではなく、認証されたアプリケーション ID からテナント、検索、メモリ、およびセッション スコープを派生させます。
  • TLS、Redis 認証、およびネットワーク分離を使用します。
  • Python会話履歴の場合は、テナント、アプリケーション、エージェント、プロバイダー ソース、およびそれらの境界が存在するセッション スコープを設定します。
  • 必要な耐久性を確保するために、永続化、バックアップ、保持期間、およびエビクションを設定します。
  • 取得したメモリを信頼されていない入力として扱い、間接的なプロンプト挿入を軽減します。
  • メッセージを保持したり、検索可能なコンテンツのインデックスを作成したりする前に、機密性の高いコンテンツを編集します。

次のステップ

より深く進む: