.NET: Adds Valkey to chat message history - issue 5445 (#5542)

* Adds Valkey to chat message history

* Address review: switch to Valkey.Glide, add options class, remove context provider

- Switch from StackExchange.Redis to Valkey.Glide 1.1.0 (official Valkey .NET client)
- Extract optional params into ValkeyChatHistoryProviderOptions
- Add JsonSerializerOptions support, remove [RequiresUnreferencedCode]
- Make MaxMessages/MaxMessagesToRetrieve readonly via options
- Remove ValkeyContextProvider (overlaps with ChatHistoryMemoryProvider + MEVD)
- Remove ValkeyProviderScope (only used by context provider)
- Remove connection string constructors (caller manages IConnectionMultiplexer)
- Update samples to use new API and gpt-5.4-mini

* Use type-safe JsonSerializer overloads, remove suppress attributes

Use JsonSerializerOptions.GetTypeInfo() for Serialize/Deserialize calls
to enable NativeAOT/trimming compatibility without suppress attributes.
Default to AgentAbstractionsJsonUtilities.DefaultOptions when no options provided.

Signed-off-by: Matthias Howell <matthias.howell@improving.com>

* Update READMEs: remove context provider references

Remove ValkeyContextProvider and long-term memory references from sample
READMEs since the context provider was removed from this PR. Simplify
Valkey server requirements (no search module needed for chat history).

Signed-off-by: Matthias Howell <matthias.howell@improving.com>

* Apply suggestion from @westey-m

* Fix formatting (dotnet format)

Signed-off-by: Matthias Howell <matthias.howell@improving.com>

* Update dotnet/src/Microsoft.Agents.AI.Valkey/Microsoft.Agents.AI.Valkey.csproj

Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>

---------

Signed-off-by: Matthias Howell <matthias.howell@improving.com>
Co-authored-by: Matthias Howell <matthias.howell@yoppworks.com>
Co-authored-by: westey <164392973+westey-m@users.noreply.github.com>
Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>
This commit is contained in:
Matthias Howell
2026-06-11 09:18:00 -04:00
committed by GitHub
Unverified
parent 4149f24791
commit 8e1998ddcb
15 changed files with 860 additions and 0 deletions
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0</TargetFrameworks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Valkey\Microsoft.Agents.AI.Valkey.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft. All rights reserved.
// This sample demonstrates using Valkey for persistent chat history with the Agent Framework.
// ValkeyChatHistoryProvider persists conversation history across sessions using Valkey lists.
//
// Prerequisites:
// - A running Valkey server (any version):
// docker run -d --name valkey -p 6379:6379 valkey/valkey:latest
// - Azure OpenAI endpoint and deployment configured via environment variables
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Valkey;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
using Valkey.Glide;
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-5.4-mini";
var valkeyConnection = Environment.GetEnvironmentVariable("VALKEY_CONNECTION") ?? "localhost:6379";
var connection = await ConnectionMultiplexer.ConnectAsync(valkeyConnection);
Console.WriteLine("=== ValkeyChatHistoryProvider — Persistent Chat History ===\n");
var historyProvider = new ValkeyChatHistoryProvider(
connection,
_ => new ValkeyChatHistoryProvider.State($"sample-{Guid.NewGuid():N}"),
new ValkeyChatHistoryProviderOptions
{
KeyPrefix = "sample_chat",
MaxMessages = 20
});
AIAgent historyAgent = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsAIAgent(new ChatClientAgentOptions()
{
ChatOptions = new() { Instructions = "You are a helpful assistant that remembers our conversation." },
ChatHistoryProvider = historyProvider
});
AgentSession session1 = await historyAgent.CreateSessionAsync();
Console.WriteLine(await historyAgent.RunAsync("Hello! My name is Alex and I'm a software engineer.", session1));
Console.WriteLine(await historyAgent.RunAsync("I'm working on a project using Valkey for caching.", session1));
Console.WriteLine(await historyAgent.RunAsync("What do you remember about me?", session1));
var messageCount = await historyProvider.GetMessageCountAsync(session1);
Console.WriteLine($"\n Stored {messageCount} messages in Valkey.\n");
// Clean up
connection.Dispose();
Console.WriteLine("Done!");
@@ -0,0 +1,30 @@
# Agent with Memory Using Valkey
This sample demonstrates using Valkey for persistent chat history with the Agent Framework.
## Components
- **ValkeyChatHistoryProvider** — Persists conversation history across sessions using Valkey lists. Works with any Valkey or Redis OSS server (no search module required).
## Prerequisites
- Azure OpenAI endpoint and deployment
- A running Valkey server (any version):
```bash
docker run -d --name valkey -p 6379:6379 valkey/valkey:latest
```
## Environment Variables
| Variable | Description | Default |
|---|---|---|
| `AZURE_OPENAI_ENDPOINT` | Azure OpenAI endpoint URL | (required) |
| `AZURE_OPENAI_DEPLOYMENT_NAME` | Model deployment name | `gpt-5.4-mini` |
| `VALKEY_CONNECTION` | Valkey connection string | `localhost:6379` |
## Running
```bash
dotnet run
```
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0</TargetFrameworks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.Extensions.Bedrock.MEAI" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" />
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Valkey\Microsoft.Agents.AI.Valkey.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,57 @@
// Copyright (c) Microsoft. All rights reserved.
// This sample demonstrates using Valkey for persistent chat history with the Agent Framework,
// powered by Amazon Bedrock.
//
// Prerequisites:
// - A running Valkey server (any version):
// docker run -d --name valkey -p 6379:6379 valkey/valkey:latest
// - AWS credentials configured (environment variables, AWS profile, or IAM role)
// - Access to an Amazon Bedrock model (e.g., Anthropic Claude)
using Amazon;
using Amazon.BedrockRuntime;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Valkey;
using Microsoft.Extensions.AI;
using Valkey.Glide;
var awsRegion = Environment.GetEnvironmentVariable("AWS_REGION") ?? "us-east-1";
var modelId = Environment.GetEnvironmentVariable("BEDROCK_MODEL_ID") ?? "anthropic.claude-3-5-sonnet-20241022-v2:0";
var valkeyConnection = Environment.GetEnvironmentVariable("VALKEY_CONNECTION") ?? "localhost:6379";
// Create the Bedrock runtime client.
var bedrockRuntime = new AmazonBedrockRuntimeClient(RegionEndpoint.GetBySystemName(awsRegion));
IChatClient chatClient = bedrockRuntime.AsIChatClient(modelId);
var connection = await ConnectionMultiplexer.ConnectAsync(valkeyConnection);
Console.WriteLine("=== ValkeyChatHistoryProvider — Persistent Chat History (Bedrock) ===\n");
var historyProvider = new ValkeyChatHistoryProvider(
connection,
_ => new ValkeyChatHistoryProvider.State($"bedrock-sample-{Guid.NewGuid():N}"),
new ValkeyChatHistoryProviderOptions
{
KeyPrefix = "bedrock_chat",
MaxMessages = 20
});
AIAgent historyAgent = chatClient.AsAIAgent(new ChatClientAgentOptions()
{
ChatOptions = new() { Instructions = "You are a helpful assistant that remembers our conversation." },
ChatHistoryProvider = historyProvider
});
AgentSession session1 = await historyAgent.CreateSessionAsync();
Console.WriteLine(await historyAgent.RunAsync("Hello! My name is Alex and I'm a software engineer.", session1));
Console.WriteLine(await historyAgent.RunAsync("I'm working on a project using Valkey for caching.", session1));
Console.WriteLine(await historyAgent.RunAsync("What do you remember about me?", session1));
var messageCount = await historyProvider.GetMessageCountAsync(session1);
Console.WriteLine($"\n Stored {messageCount} messages in Valkey.\n");
// Clean up
connection.Dispose();
Console.WriteLine("Done!");
@@ -0,0 +1,41 @@
# Agent with Memory Using Valkey + Amazon Bedrock
This sample demonstrates using Valkey for persistent chat history with the Agent Framework, powered by Amazon Bedrock via the `AWSSDK.Extensions.Bedrock.MEAI` adapter.
## Components
- **ValkeyChatHistoryProvider** — Persists conversation history across sessions using Valkey lists. Works with any Valkey or Redis OSS server (no search module required).
- **Amazon Bedrock** — Provides the LLM via `AWSSDK.Extensions.Bedrock.MEAI`, which implements `IChatClient` from `Microsoft.Extensions.AI`.
## Prerequisites
- AWS credentials configured (environment variables, AWS CLI profile, or IAM role)
- Access to an Amazon Bedrock model (e.g., Anthropic Claude 3.5 Sonnet)
- A running Valkey server (any version):
```bash
docker run -d --name valkey -p 6379:6379 valkey/valkey:latest
```
## Environment Variables
| Variable | Description | Default |
|---|---|---|
| `AWS_REGION` | AWS region for Bedrock | `us-east-1` |
| `BEDROCK_MODEL_ID` | Bedrock model identifier | `anthropic.claude-3-5-sonnet-20241022-v2:0` |
| `VALKEY_CONNECTION` | Valkey connection string | `localhost:6379` |
| `AWS_ACCESS_KEY_ID` | AWS access key (if not using profile/role) | — |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key (if not using profile/role) | — |
## Running
```bash
# Using default AWS credential chain (profile, env vars, or IAM role)
dotnet run
# Or with explicit credentials
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_REGION="us-east-1"
dotnet run
```