Compare commits

..
Author SHA1 Message Date
Chris Rickman 7fa6a304d8 Sample format 2026-03-06 11:33:37 -08:00
ChrisandGitHub 83de93f377 Merge branch 'main' into crickman/feature-compaction 2026-03-05 11:00:52 -08:00
Chris Rickman e296bb5078 Sample readme 2026-03-05 08:35:49 -08:00
ChrisandGitHub 2563dbae71 Merge branch 'main' into crickman/feature-compaction 2026-03-05 08:10:51 -08:00
Chris Rickman c1b1c18bc2 Namespace 2026-03-05 02:29:36 -08:00
ChrisandGitHub 0e664029d1 Merge branch 'main' into crickman/feature-compaction 2026-03-05 02:27:18 -08:00
Chris Rickman 475c065680 Sample 2026-03-05 01:53:53 -08:00
Chris Rickman d6c4dbea96 Checkpoint 2026-03-02 22:00:21 -08:00
Chris Rickman 42d424587d Sample 2026-03-02 13:46:28 -08:00
Chris Rickman e061d095e7 Checkpoint 2026-03-02 13:27:25 -08:00
304 changed files with 5296 additions and 24186 deletions
-18
View File
@@ -8,10 +8,6 @@ inputs:
os:
description: The operating system to set up
required: true
exclude-packages:
description: Space-separated list of packages to exclude from uv sync
required: false
default: ''
runs:
using: "composite"
@@ -23,20 +19,6 @@ runs:
enable-cache: true
cache-suffix: ${{ inputs.os }}-${{ inputs.python-version }}
cache-dependency-glob: "**/uv.lock"
- name: Exclude incompatible workspace packages
if: ${{ inputs.exclude-packages != '' }}
shell: bash
run: |
for pkg in ${{ inputs.exclude-packages }}; do
for f in python/packages/*/pyproject.toml; do
if grep -q "name = \"$pkg\"" "$f"; then
pkg_dir=$(dirname "$f" | sed 's|python/||')
echo "Excluding workspace package: $pkg ($pkg_dir)"
sed -i.bak '/\[tool\.uv\.workspace\]/a\exclude = ["'"$pkg_dir"'"]' python/pyproject.toml
sed -i.bak '/'"$pkg"' = { workspace = true }/d' python/pyproject.toml
fi
done
done
- name: Install the project
shell: bash
run: |
+2 -1
View File
@@ -86,10 +86,11 @@ jobs:
run: docker pull mcr.microsoft.com/dotnet/sdk:${{ matrix.dotnet }}
# This step will run dotnet format on each of the unique csproj files and fail if any changes are made
# exclude-diagnostics should be removed after fixes for IL2026 and IL3050 are out: https://github.com/dotnet/sdk/issues/51136
- name: Run dotnet format
if: steps.find-csproj.outputs.csproj_files != ''
run: |
for csproj in ${{ steps.find-csproj.outputs.csproj_files }}; do
echo "Running dotnet format on $csproj"
docker run --rm -v $(pwd):/app -w /app mcr.microsoft.com/dotnet/sdk:${{ matrix.dotnet }} /bin/sh -c "dotnet format $csproj --verify-no-changes --verbosity diagnostic"
docker run --rm -v $(pwd):/app -w /app mcr.microsoft.com/dotnet/sdk:${{ matrix.dotnet }} /bin/sh -c "dotnet format $csproj --verify-no-changes --verbosity diagnostic --exclude-diagnostics IL2026 IL3050"
done
+4 -4
View File
@@ -18,7 +18,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.11"]
python-version: ["3.10"]
runs-on: ubuntu-latest
continue-on-error: true
defaults:
@@ -55,7 +55,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.11"]
python-version: ["3.10"]
runs-on: ubuntu-latest
continue-on-error: true
defaults:
@@ -84,7 +84,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.11"]
python-version: ["3.10"]
runs-on: ubuntu-latest
continue-on-error: true
defaults:
@@ -117,7 +117,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.11"]
python-version: ["3.10"]
runs-on: ubuntu-latest
continue-on-error: true
defaults:
@@ -170,7 +170,7 @@ jobs:
environment: integration
timeout-minutes: 60
env:
UV_PYTHON: "3.11"
UV_PYTHON: "3.10"
OPENAI_CHAT_MODEL_ID: ${{ vars.OPENAI__CHATMODELID }}
OPENAI_RESPONSES_MODEL_ID: ${{ vars.OPENAI__RESPONSESMODELID }}
OPENAI_API_KEY: ${{ secrets.OPENAI__APIKEY }}
-1
View File
@@ -67,7 +67,6 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
os: ${{ runner.os }}
exclude-packages: ${{ matrix.python-version == '3.10' && 'agent-framework-github-copilot' || '' }}
env:
# Configure a constant location for the uv cache
UV_CACHE_DIR: /tmp/.uv-cache
+1 -1
View File
@@ -288,7 +288,7 @@ jobs:
runs-on: ubuntu-latest
environment: integration
env:
UV_PYTHON: "3.11"
UV_PYTHON: "3.10"
OPENAI_CHAT_MODEL_ID: ${{ vars.OPENAI__CHATMODELID }}
OPENAI_RESPONSES_MODEL_ID: ${{ vars.OPENAI__RESPONSESMODELID }}
OPENAI_API_KEY: ${{ secrets.OPENAI__APIKEY }}
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
run:
working-directory: python
env:
UV_PYTHON: "3.11"
UV_PYTHON: "3.10"
steps:
- uses: actions/checkout@v6
# Save the PR number to a file since the workflow_run event
+1 -2
View File
@@ -34,13 +34,12 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
os: ${{ runner.os }}
exclude-packages: ${{ matrix.python-version == '3.10' && 'agent-framework-github-copilot' || '' }}
env:
# Configure a constant location for the uv cache
UV_CACHE_DIR: /tmp/.uv-cache
# Unit tests
- name: Run all tests
run: uv run poe all-tests ${{ matrix.python-version == '3.10' && '--ignore-glob=packages/github_copilot/**' || '' }}
run: uv run poe all-tests
working-directory: ./python
# Surface failing tests
+3 -3
View File
@@ -64,7 +64,7 @@ Approaches observed from the compared SDKs:
| AutoGen | **Approach 1** Separates messages into Agent-Agent (maps to Primary) and Internal (maps to Secondary) and these are returned as separate properties on the agent response object. See [types of messages](https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/messages.html#types-of-messages) and [Response](https://microsoft.github.io/autogen/stable/reference/python/autogen_agentchat.base.html#autogen_agentchat.base.Response) | **Approach 2** Returns a stream of internal events and the last item is a Response object. See [ChatAgent.on_messages_stream](https://microsoft.github.io/autogen/stable/reference/python/autogen_agentchat.base.html#autogen_agentchat.base.ChatAgent.on_messages_stream) |
| OpenAI Agent SDK | **Approach 1** Separates new_items (Primary+Secondary) from final output (Primary) as separate properties on the [RunResult](https://github.com/openai/openai-agents-python/blob/main/src/agents/result.py#L39) | **Approach 1** Similar to non-streaming, has a way of streaming updates via a method on the response object which includes all data, and then a separate final output property on the response object which is populated only when the run is complete. See [RunResultStreaming](https://github.com/openai/openai-agents-python/blob/main/src/agents/result.py#L136) |
| Google ADK | **Approach 2** [Emits events](https://google.github.io/adk-docs/runtime/#step-by-step-breakdown) with [FinalResponse](https://github.com/google/adk-java/blob/main/core/src/main/java/com/google/adk/events/Event.java#L232) true (Primary) / false (Secondary) and callers have to filter out those with false to get just the final response message | **Approach 2** Similar to non-streaming except [events](https://google.github.io/adk-docs/runtime/#streaming-vs-non-streaming-output-partialtrue) are emitted with [Partial](https://github.com/google/adk-java/blob/main/core/src/main/java/com/google/adk/events/Event.java#L133) true to indicate that they are streaming messages. A final non partial event is also emitted. |
| AWS (Strands) | **Approach 3** Returns an [AgentResult](https://strandsagents.com/docs/api/python/strands.agent.agent_result/#agentresult) (Primary) with messages and a reason for the run's completion. | **Approach 2** [Streams events](https://strandsagents.com/docs/user-guide/concepts/streaming/) (Primary+Secondary) including, response text, current_tool_use, even data from "callbacks" (strands plugins) |
| AWS (Strands) | **Approach 3** Returns an [AgentResult](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent_result/) (Primary) with messages and a reason for the run's completion. | **Approach 2** [Streams events](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent/#strands.agent.agent.Agent.stream_async) (Primary+Secondary) including, response text, current_tool_use, even data from "callbacks" (strands plugins) |
| LangGraph | **Approach 2** A mixed list of all [messages](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) | **Approach 2** A mixed list of all [messages](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) |
| Agno | **Combination of various approaches** Returns a [RunResponse](https://docs.agno.com/reference/agents/run-response) object with text content, messages (essentially chat history including inputs and instructions), reasoning and thinking text properties. Secondary events could potentially be extracted from messages. | **Approach 2** Returns [RunResponseEvent](https://docs.agno.com/reference/agents/run-response#runresponseevent-types-and-attributes) objects including tool call, memory update, etc, information, where the [RunResponseCompletedEvent](https://docs.agno.com/reference/agents/run-response#runresponsecompletedevent) has similar properties to RunResponse|
| A2A | **Approach 3** Returns a [Task or Message](https://a2aproject.github.io/A2A/latest/specification/#71-messagesend) where the message is the final result (Primary) and task is a reference to a long running process. | **Approach 2** Returns a [stream](https://a2aproject.github.io/A2A/latest/specification/#72-messagestream) that contains task updates (Secondary) and a final message (Primary) |
@@ -496,7 +496,7 @@ We need to decide what AIContent types, each agent response type will be mapped
|-|-|
| AutoGen | **Approach 1** Supports [configuring an agent](https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/agents.html#structured-output) at agent creation. |
| Google ADK | **Approach 1** Both [input and output schemas can be specified for LLM Agents](https://google.github.io/adk-docs/agents/llm-agents/#structuring-data-input_schema-output_schema-output_key) at construction time. This option is specific to this agent type and other agent types do not necessarily support |
| AWS (Strands) | **Approach 2** Supports a special invocation method called [structured_output](https://strandsagents.com/docs/user-guide/concepts/agents/structured-output/) |
| AWS (Strands) | **Approach 2** Supports a special invocation method called [structured_output](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent/#strands.agent.agent.Agent.structured_output) |
| LangGraph | **Approach 1** Supports [configuring an agent](https://langchain-ai.github.io/langgraph/agents/agents/?h=structured#6-configure-structured-output) at agent construction time, and a [structured response](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) can be retrieved as a special property on the agent response |
| Agno | **Approach 1** Supports [configuring an agent](https://docs.agno.com/input-output/structured-output/agent) at agent construction time |
| A2A | **Informal Approach 2** Doesn't formally support schema negotiation, but [hints can be provided via metadata](https://a2a-protocol.org/latest/specification/#97-structured-data-exchange-requesting-and-providing-json) at invocation time |
@@ -508,7 +508,7 @@ We need to decide what AIContent types, each agent response type will be mapped
|-|-|
| AutoGen | Supports a [stop reason](https://microsoft.github.io/autogen/stable/reference/python/autogen_agentchat.base.html#autogen_agentchat.base.TaskResult.stop_reason) which is a freeform text string |
| Google ADK | [No equivalent present](https://github.com/google/adk-python/blob/main/src/google/adk/events/event.py) |
| AWS (Strands) | Exposes a `stop_reason` property on the [AgentResult](https://strandsagents.com/docs/api/python/strands.agent.agent_result/#agentresult) class with options that are tied closely to LLM operations. |
| AWS (Strands) | Exposes a [stop_reason](https://strandsagents.com/latest/documentation/docs/api-reference/python/types/event_loop/#strands.types.event_loop.StopReason) property on the [AgentResult](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent_result/) class with options that are tied closely to LLM operations. |
| LangGraph | No equivalent present, output contains only [messages](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) |
| Agno | [No equivalent present](https://docs.agno.com/reference/agents/run-response) |
| A2A | No equivalent present, response only contains a [message](https://a2a-protocol.org/latest/specification/#64-message-object) or [task](https://a2a-protocol.org/latest/specification/#61-task-object). |
@@ -1240,10 +1240,3 @@ class AttributionAwareStrategy(CompactionStrategy):
- [ADR-0016: Unifying Context Management with ContextPlugin](0016-python-context-middleware.md) — Parent ADR that established `ContextProvider`, `HistoryProvider`, and `AgentSession` architecture.
- [Context Compaction Limitations Analysis](https://gist.github.com/victordibia/ec3f3baf97345f7e47da025cf55b999f) — Detailed analysis of why current architecture cannot support in-run compaction, with attempted solutions and their failure modes. Option 4 in this ADR corresponds to "Option A: Middleware Access to Mutable Message Source" from that analysis; Options 1-3 correspond to "Option B: Tool Loop Hook", adapted here to a `BaseChatClient` hook instead of `FunctionInvocationConfiguration`.
### Implementation Rollout Note
Implementation is split into two phases:
1. **Phase 1 (PR 1):** runtime compaction foundation in `agent_framework/_compaction.py`, in-run integration, and extensive core tests, plus in-run compaction samples (`basics`, `advanced`, `custom`).
2. **Phase 2 (PR 2):** history/storage compaction (`upsert`-based full replacement), provider support, storage tests, and storage-focused sample (`storage`).
+2 -3
View File
@@ -11,8 +11,8 @@
</PropertyGroup>
<ItemGroup>
<!-- Aspire.* -->
<PackageVersion Include="Anthropic" Version="12.8.0" />
<PackageVersion Include="Anthropic.Foundry" Version="0.4.2" />
<PackageVersion Include="Anthropic" Version="12.3.0" />
<PackageVersion Include="Anthropic.Foundry" Version="0.4.1" />
<PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="13.0.0-preview.1.25560.3" />
<PackageVersion Include="Aspire.Hosting.AppHost" Version="$(AspireAppHostSdkVersion)" />
<PackageVersion Include="Aspire.Hosting.Azure.CognitiveServices" Version="$(AspireAppHostSdkVersion)" />
@@ -108,7 +108,6 @@
<!-- Inference SDKs -->
<PackageVersion Include="AWSSDK.Extensions.Bedrock.MEAI" Version="4.0.5.1" />
<PackageVersion Include="Microsoft.ML.OnnxRuntimeGenAI" Version="0.10.0" />
<PackageVersion Include="Microsoft.ML.Tokenizers" Version="2.0.0" />
<PackageVersion Include="OllamaSharp" Version="5.4.8" />
<PackageVersion Include="OpenAI" Version="2.8.0" />
<!-- Identity -->
-4
View File
@@ -104,7 +104,6 @@
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step01_ChatHistoryMemory/AgentWithMemory_Step01_ChatHistoryMemory.csproj" />
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step02_MemoryUsingMem0/AgentWithMemory_Step02_MemoryUsingMem0.csproj" />
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step04_MemoryUsingFoundry/AgentWithMemory_Step04_MemoryUsingFoundry.csproj" />
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step05_BoundedChatHistory/AgentWithMemory_Step05_BoundedChatHistory.csproj" />
</Folder>
<Folder Name="/Samples/02-agents/AgentWithOpenAI/">
<File Path="samples/02-agents/AgentWithOpenAI/README.md" />
@@ -286,11 +285,8 @@
</Folder>
<Folder Name="/Samples/05-end-to-end/HostedAgents/">
<Project Path="samples/05-end-to-end/HostedAgents/AgentsInWorkflows/AgentsInWorkflows.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/AgentThreadAndHITL/AgentThreadAndHITL.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/AgentWithHostedMCP/AgentWithHostedMCP.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/AgentWithLocalTools/AgentWithLocalTools.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/AgentWithTextSearchRag/AgentWithTextSearchRag.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/AgentWithTools/AgentWithTools.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/FoundryMultiAgent/FoundryMultiAgent.csproj" />
<Project Path="samples/05-end-to-end/HostedAgents/FoundrySingleAgent/FoundrySingleAgent.csproj" />
</Folder>
-1
View File
@@ -14,7 +14,6 @@
"src\\Microsoft.Agents.AI.Declarative\\Microsoft.Agents.AI.Declarative.csproj",
"src\\Microsoft.Agents.AI.DevUI\\Microsoft.Agents.AI.DevUI.csproj",
"src\\Microsoft.Agents.AI.DurableTask\\Microsoft.Agents.AI.DurableTask.csproj",
"src\\Microsoft.Agents.AI.FoundryMemory\\Microsoft.Agents.AI.FoundryMemory.csproj",
"src\\Microsoft.Agents.AI.Hosting.A2A.AspNetCore\\Microsoft.Agents.AI.Hosting.A2A.AspNetCore.csproj",
"src\\Microsoft.Agents.AI.Hosting.A2A\\Microsoft.Agents.AI.Hosting.A2A.csproj",
"src\\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore\\Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.csproj",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.200",
"version": "10.0.100",
"rollForward": "minor",
"allowPrerelease": false
},
+4 -4
View File
@@ -2,11 +2,11 @@
<PropertyGroup>
<!-- Central version prefix - applies to all nuget packages. -->
<VersionPrefix>1.0.0</VersionPrefix>
<RCNumber>4</RCNumber>
<RCNumber>3</RCNumber>
<PackageVersion Condition="'$(IsReleaseCandidate)' == 'true'">$(VersionPrefix)-rc$(RCNumber)</PackageVersion>
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' != ''">$(VersionPrefix)-$(VersionSuffix).260311.1</PackageVersion>
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' == ''">$(VersionPrefix)-preview.260311.1</PackageVersion>
<GitTag>1.0.0-rc4</GitTag>
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' != ''">$(VersionPrefix)-$(VersionSuffix).260304.1</PackageVersion>
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' == ''">$(VersionPrefix)-preview.260304.1</PackageVersion>
<GitTag>1.0.0-rc3</GitTag>
<Configurations>Debug;Release;Publish</Configurations>
<IsPackable>true</IsPackable>
@@ -4,6 +4,7 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
@@ -26,7 +27,7 @@ ChatClient chatClient = new AzureOpenAIClient(
new DefaultAzureCredential())
.GetChatClient(deploymentName);
AIAgent agent = chatClient.AsAIAgent(
AIAgent agent = chatClient.AsIChatClient().AsAIAgent(
name: "AGUIAssistant",
instructions: "You are a helpful assistant.");
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
@@ -82,7 +82,7 @@ ChatClient chatClient = new AzureOpenAIClient(
new DefaultAzureCredential())
.GetChatClient(deploymentName);
ChatClientAgent agent = chatClient.AsAIAgent(
ChatClientAgent agent = chatClient.AsIChatClient().AsAIAgent(
name: "AGUIAssistant",
instructions: "You are a helpful assistant with access to restaurant information.",
tools: tools);
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
@@ -4,6 +4,7 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
@@ -26,7 +27,7 @@ ChatClient chatClient = new AzureOpenAIClient(
new DefaultAzureCredential())
.GetChatClient(deploymentName);
AIAgent agent = chatClient.AsAIAgent(
AIAgent agent = chatClient.AsIChatClient().AsAIAgent(
name: "AGUIAssistant",
instructions: "You are a helpful assistant.");
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
@@ -60,7 +60,7 @@ ChatClient openAIChatClient = new AzureOpenAIClient(
new DefaultAzureCredential())
.GetChatClient(deploymentName);
ChatClientAgent baseAgent = openAIChatClient.AsAIAgent(
ChatClientAgent baseAgent = openAIChatClient.AsIChatClient().AsAIAgent(
name: "AGUIAssistant",
instructions: "You are a helpful assistant in charge of approving expenses",
tools: tools);
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
@@ -4,6 +4,7 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
using OpenAI.Chat;
using RecipeAssistant;
@@ -36,7 +37,7 @@ ChatClient chatClient = new AzureOpenAIClient(
new DefaultAzureCredential())
.GetChatClient(deploymentName);
AIAgent baseAgent = chatClient.AsAIAgent(
AIAgent baseAgent = chatClient.AsIChatClient().AsAIAgent(
name: "RecipeAgent",
instructions: """
You are a helpful recipe assistant. When users ask you to create or suggest a recipe,
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" />
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
@@ -1,22 +0,0 @@
<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" />
<PackageReference Include="Microsoft.SemanticKernel.Connectors.InMemory" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
</ItemGroup>
</Project>
@@ -1,133 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
namespace SampleApp;
/// <summary>
/// A <see cref="ChatHistoryProvider"/> that keeps a bounded window of recent messages in session state
/// (via <see cref="InMemoryChatHistoryProvider"/>) and overflows older messages to a vector store
/// (via <see cref="ChatHistoryMemoryProvider"/>). When providing chat history, it searches the vector
/// store for relevant older messages and prepends them as a memory context message.
/// </summary>
/// <remarks>
/// Only non-system messages are counted towards the session state limit and overflow mechanism. System messages are always retained in session state and are not included in the vector store.
/// Function calls and function results are also dropped when truncation happens, both from in-memory state, and they are also not persisted to the vector store.
/// </remarks>
internal sealed class BoundedChatHistoryProvider : ChatHistoryProvider, IDisposable
{
private readonly InMemoryChatHistoryProvider _chatHistoryProvider;
private readonly ChatHistoryMemoryProvider _memoryProvider;
private readonly TruncatingChatReducer _reducer;
private readonly string _contextPrompt;
private IReadOnlyList<string>? _stateKeys;
/// <summary>
/// Initializes a new instance of the <see cref="BoundedChatHistoryProvider"/> class.
/// </summary>
/// <param name="maxSessionMessages">The maximum number of non-system messages to keep in session state before overflowing to the vector store.</param>
/// <param name="vectorStore">The vector store to use for storing and retrieving overflow chat history.</param>
/// <param name="collectionName">The name of the collection for storing overflow chat history in the vector store.</param>
/// <param name="vectorDimensions">The number of dimensions to use for the chat history vector store embeddings.</param>
/// <param name="stateInitializer">A delegate that initializes the memory provider state, providing the storage and search scopes.</param>
/// <param name="contextPrompt">Optional prompt to prefix memory search results. Defaults to a standard memory context prompt.</param>
public BoundedChatHistoryProvider(
int maxSessionMessages,
VectorStore vectorStore,
string collectionName,
int vectorDimensions,
Func<AgentSession?, ChatHistoryMemoryProvider.State> stateInitializer,
string? contextPrompt = null)
{
if (maxSessionMessages < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxSessionMessages), "maxSessionMessages must be non-negative.");
}
this._reducer = new TruncatingChatReducer(maxSessionMessages);
this._chatHistoryProvider = new InMemoryChatHistoryProvider(new InMemoryChatHistoryProviderOptions
{
ChatReducer = this._reducer,
ReducerTriggerEvent = InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.AfterMessageAdded,
StorageInputRequestMessageFilter = msgs => msgs,
});
this._memoryProvider = new ChatHistoryMemoryProvider(
vectorStore,
collectionName,
vectorDimensions,
stateInitializer,
options: new ChatHistoryMemoryProviderOptions
{
SearchInputMessageFilter = msgs => msgs,
StorageInputRequestMessageFilter = msgs => msgs,
});
this._contextPrompt = contextPrompt
?? "The following are memories from earlier in this conversation. Use them to inform your responses:";
}
/// <inheritdoc />
public override IReadOnlyList<string> StateKeys => this._stateKeys ??= this._chatHistoryProvider.StateKeys.Concat(this._memoryProvider.StateKeys).ToArray();
/// <inheritdoc />
protected override async ValueTask<IEnumerable<ChatMessage>> ProvideChatHistoryAsync(
InvokingContext context,
CancellationToken cancellationToken = default)
{
// Delegate to the inner provider's full lifecycle (retrieve, filter, stamp, merge with request messages).
var chatHistoryProviderInputContext = new InvokingContext(context.Agent, context.Session, []);
var allMessages = await this._chatHistoryProvider.InvokingAsync(chatHistoryProviderInputContext, cancellationToken).ConfigureAwait(false);
// Search the vector store for relevant older messages.
var aiContext = new AIContext { Messages = context.RequestMessages.ToList() };
var invokingContext = new AIContextProvider.InvokingContext(
context.Agent, context.Session, aiContext);
var result = await this._memoryProvider.InvokingAsync(invokingContext, cancellationToken).ConfigureAwait(false);
// Extract only the messages added by the memory provider (stamped with AIContextProvider source type).
var memoryMessages = result.Messages?
.Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.AIContextProvider)
.ToList();
if (memoryMessages is { Count: > 0 })
{
var memoryText = string.Join("\n", memoryMessages.Select(m => m.Text).Where(t => !string.IsNullOrWhiteSpace(t)));
if (!string.IsNullOrWhiteSpace(memoryText))
{
var contextMessage = new ChatMessage(ChatRole.User, $"{this._contextPrompt}\n{memoryText}");
return new[] { contextMessage }.Concat(allMessages);
}
}
return allMessages;
}
/// <inheritdoc />
protected override async ValueTask StoreChatHistoryAsync(
InvokedContext context,
CancellationToken cancellationToken = default)
{
// Delegate storage to the in-memory provider. Its TruncatingChatReducer (AfterMessageAdded trigger)
// will automatically truncate to the configured maximum and expose any removed messages.
var innerContext = new InvokedContext(
context.Agent, context.Session, context.RequestMessages, context.ResponseMessages!);
await this._chatHistoryProvider.InvokedAsync(innerContext, cancellationToken).ConfigureAwait(false);
// Archive any messages that the reducer removed to the vector store.
if (this._reducer.RemovedMessages is { Count: > 0 })
{
var overflowContext = new AIContextProvider.InvokedContext(
context.Agent, context.Session, this._reducer.RemovedMessages, []);
await this._memoryProvider.InvokedAsync(overflowContext, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc/>
public void Dispose()
{
this._memoryProvider.Dispose();
}
}
@@ -1,79 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
// This sample shows how to create a bounded chat history provider that keeps a configurable number of
// recent messages in session state and automatically overflows older messages to a vector store.
// When the agent is invoked, it searches the vector store for relevant older messages and
// prepends them as a "memory" context message before the recent session history.
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
using Microsoft.SemanticKernel.Connectors.InMemory;
using OpenAI.Chat;
using SampleApp;
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-4o-mini";
var embeddingDeploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME") ?? "text-embedding-3-large";
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
var credential = new DefaultAzureCredential();
// Create a vector store to store overflow chat messages.
// For demonstration purposes, we are using an in-memory vector store.
// Replace this with a persistent vector store implementation for production scenarios.
VectorStore vectorStore = new InMemoryVectorStore(new InMemoryVectorStoreOptions()
{
EmbeddingGenerator = new AzureOpenAIClient(new Uri(endpoint), credential)
.GetEmbeddingClient(embeddingDeploymentName)
.AsIEmbeddingGenerator()
});
var sessionId = Guid.NewGuid().ToString();
// Create the BoundedChatHistoryProvider with a maximum of 4 non-system messages in session state.
// It internally creates an InMemoryChatHistoryProvider with a TruncatingChatReducer and a
// ChatHistoryMemoryProvider with the correct configuration to ensure overflow messages are
// automatically archived to the vector store and recalled via semantic search.
var boundedProvider = new BoundedChatHistoryProvider(
maxSessionMessages: 4,
vectorStore,
collectionName: "chathistory-overflow",
vectorDimensions: 3072,
session => new ChatHistoryMemoryProvider.State(
storageScope: new() { UserId = "UID1", SessionId = sessionId },
searchScope: new() { UserId = "UID1" }));
// Create the agent with the bounded chat history provider.
AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), credential)
.GetChatClient(deploymentName)
.AsAIAgent(new ChatClientAgentOptions
{
ChatOptions = new() { Instructions = "You are a helpful assistant. Answer questions concisely." },
Name = "Assistant",
ChatHistoryProvider = boundedProvider,
});
// Start a conversation. The first several exchanges will fill up the session state window.
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine("--- Filling the session window (4 messages max) ---\n");
Console.WriteLine(await agent.RunAsync("My favorite color is blue.", session));
Console.WriteLine(await agent.RunAsync("I have a dog named Max.", session));
// At this point the session state holds 4 messages (2 user + 2 assistant).
// The next exchange will push the oldest messages into the vector store.
Console.WriteLine("\n--- Next exchange will trigger overflow to vector store ---\n");
Console.WriteLine(await agent.RunAsync("What is the capital of France?", session));
// The oldest messages about favorite color have now been archived to the vector store.
// Ask the agent something that requires recalling the overflowed information.
Console.WriteLine("\n--- Asking about overflowed information (should recall from vector store) ---\n");
Console.WriteLine(await agent.RunAsync("What is my favorite color?", session));
@@ -1,40 +0,0 @@
# Bounded Chat History with Vector Store Overflow
This sample demonstrates how to create a custom `ChatHistoryProvider` that keeps a bounded window of recent messages in session state and automatically overflows older messages to a vector store. When the agent is invoked, it searches the vector store for relevant older messages and prepends them as memory context.
## Concepts
- **`TruncatingChatReducer`**: A custom `IChatReducer` that keeps the most recent N messages and exposes removed messages via a `RemovedMessages` property.
- **`BoundedChatHistoryProvider`**: A custom `ChatHistoryProvider` that composes:
- `InMemoryChatHistoryProvider` for fast session-state storage (bounded by the reducer)
- `ChatHistoryMemoryProvider` for vector-store overflow and semantic search of older messages
## Prerequisites
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)
- An Azure OpenAI resource with:
- A chat deployment (e.g., `gpt-4o-mini`)
- An embedding deployment (e.g., `text-embedding-3-large`)
## Configuration
Set the following environment variables:
| Variable | Description | Default |
|---|---|---|
| `AZURE_OPENAI_ENDPOINT` | Your Azure OpenAI endpoint URL | *(required)* |
| `AZURE_OPENAI_DEPLOYMENT_NAME` | Chat model deployment name | `gpt-4o-mini` |
| `AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME` | Embedding model deployment name | `text-embedding-3-large` |
## Running the Sample
```bash
dotnet run
```
## How it Works
1. The agent starts a conversation with a bounded session window of 4 non-system, non-function messages (i.e., user/assistant turns). System messages are always preserved, and function call/result messages are truncated and not preserved.
2. As messages accumulate beyond the limit, the `TruncatingChatReducer` removes the oldest messages.
3. The `BoundedChatHistoryProvider` detects the removed messages and stores them in a vector store via `ChatHistoryMemoryProvider`.
4. On subsequent invocations, the provider searches the vector store for relevant older messages and prepends them as memory context, allowing the agent to recall information from earlier in the conversation.
@@ -1,65 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Extensions.AI;
namespace SampleApp;
/// <summary>
/// A truncating chat reducer that keeps the most recent messages up to a configured maximum,
/// preserving any leading system message. Removed messages are exposed via <see cref="RemovedMessages"/>
/// so that a caller can archive them (e.g. to a vector store).
/// </summary>
internal sealed class TruncatingChatReducer : IChatReducer
{
private readonly int _maxMessages;
/// <summary>
/// Initializes a new instance of the <see cref="TruncatingChatReducer"/> class.
/// </summary>
/// <param name="maxMessages">The maximum number of non-system messages to retain.</param>
public TruncatingChatReducer(int maxMessages)
{
this._maxMessages = maxMessages > 0 ? maxMessages : throw new ArgumentOutOfRangeException(nameof(maxMessages));
}
/// <summary>
/// Gets the messages that were removed during the most recent call to <see cref="ReduceAsync"/>.
/// </summary>
public IReadOnlyList<ChatMessage> RemovedMessages { get; private set; } = [];
/// <inheritdoc />
public Task<IEnumerable<ChatMessage>> ReduceAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken)
{
_ = messages ?? throw new ArgumentNullException(nameof(messages));
ChatMessage? systemMessage = null;
Queue<ChatMessage> retained = new(capacity: this._maxMessages);
List<ChatMessage> removed = [];
foreach (var message in messages)
{
if (message.Role == ChatRole.System)
{
// Preserve the first system message outside the counting window.
systemMessage ??= message;
}
else if (!message.Contents.Any(c => c is FunctionCallContent or FunctionResultContent))
{
if (retained.Count >= this._maxMessages)
{
removed.Add(retained.Dequeue());
}
retained.Enqueue(message);
}
}
this.RemovedMessages = removed;
IEnumerable<ChatMessage> result = systemMessage is not null
? new[] { systemMessage }.Concat(retained)
: retained;
return Task.FromResult(result);
}
}
@@ -8,6 +8,5 @@ These samples show how to create an agent with the Agent Framework that uses Mem
|[Memory with MemoryStore](./AgentWithMemory_Step02_MemoryUsingMem0/)|This sample demonstrates how to create and run an agent that uses the Mem0 service to extract and retrieve individual memories.|
|[Custom Memory Implementation](../../01-get-started/04_memory/)|This sample demonstrates how to create a custom memory component and attach it to an agent.|
|[Memory with Azure AI Foundry](./AgentWithMemory_Step04_MemoryUsingFoundry/)|This sample demonstrates how to create and run an agent that uses Azure AI Foundry's managed memory service to extract and retrieve individual memories.|
|[Bounded Chat History with Overflow](./AgentWithMemory_Step05_BoundedChatHistory/)|This sample demonstrates how to create a bounded chat history provider that overflows older messages to a vector store and recalls them as memories.|
> **See also**: [Memory Search with Foundry Agents](../FoundryAgents/FoundryAgents_Step22_MemorySearch/) - demonstrates using the built-in Memory Search tool with Azure Foundry Agents.
@@ -1,8 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
// This sample demonstrates how to use a CompactionProvider with a compaction pipeline
// as an AIContextProvider for an agent's in-run context management. The pipeline chains multiple
// compaction strategies from gentle to aggressive:
// This sample demonstrates how to use a ChatHistoryCompactionPipeline as the ChatReducer for an agent's
// in-memory chat history. The pipeline chains multiple compaction strategies from gentle to aggressive:
// 1. ToolResultCompactionStrategy - Collapses old tool-call groups into concise summaries
// 2. SummarizationCompactionStrategy - LLM-compresses older conversation spans
// 3. SlidingWindowCompactionStrategy - Keeps only the most recent N user turns
@@ -40,45 +39,47 @@ static string LookupPrice([Description("The product name to look up.")] string p
};
// Configure the compaction pipeline with one of each strategy, ordered least to most aggressive.
PipelineCompactionStrategy compactionPipeline =
new(// 1. Gentle: collapse old tool-call groups into short summaries
new ToolResultCompactionStrategy(CompactionTriggers.MessagesExceed(7)),
const int MaxTokens = 512;
const int MaxTurns = 4;
ChatHistoryCompactionPipeline compactionPipeline =
new(// 1. Gentle: collapse old tool-call groups into short summaries like "[Tool calls: LookupPrice]"
new ToolResultCompactionStrategy(MaxTokens, preserveRecentGroups: 2),
// 2. Moderate: use an LLM to summarize older conversation spans into a concise message
new SummarizationCompactionStrategy(summarizerChatClient, CompactionTriggers.TokensExceed(0x500)),
new SummarizationCompactionStrategy(summarizerChatClient, MaxTokens, preserveRecentGroups: 2),
// 3. Aggressive: keep only the last N user turns and their responses
new SlidingWindowCompactionStrategy(CompactionTriggers.TurnsExceed(4)),
new SlidingWindowCompactionStrategy(MaxTurns),
// 4. Emergency: drop oldest groups until under the token budget
new TruncationCompactionStrategy(CompactionTriggers.TokensExceed(0x8000)));
new TruncationCompactionStrategy(MaxTokens, preserveRecentGroups: 1));
// Create the agent with a CompactionProvider that uses the compaction pipeline.
// TODO: PRECONFIGURED PIPELINE
////Create(
//// Approach.Balanced,
//// Size.Compact,
//// summarizerChatClient);
// Create the agent with an in-memory chat history provider whose reducer is the compaction pipeline.
AIAgent agent =
agentChatClient
.AsBuilder()
// Note: Adding the CompactionProvider at the builder level means it will be applied to all agents
// built from this builder and will manage context for both agent messages and tool calls.
.UseAIContextProviders(new CompactionProvider(compactionPipeline))
.BuildAIAgent(
new ChatClientAgentOptions
agentChatClient.AsAIAgent(
new ChatClientAgentOptions
{
Name = "ShoppingAssistant",
ChatOptions = new()
{
Name = "ShoppingAssistant",
ChatOptions = new()
{
Instructions =
"""
You are a helpful, but long winded, shopping assistant.
Help the user look up prices and compare products.
When responding, Be sure to be extra descriptive and use as
many words as possible without sounding ridiculous.
""",
Tools = [AIFunctionFactory.Create(LookupPrice)]
},
// Note: AIContextProviders may be specified here instead of ChatClientBuilder.UseAIContextProviders.
// Specifying compaction at the agent level skips compaction in the function calling loop.
//AIContextProviders = [new CompactionProvider(compactionPipeline)]
});
Instructions =
"""
You are a helpful, but long winded, shopping assistant.
Help the user look up prices and compare products.
When responding, Be sure to be extra descriptive and use as
many words as possible without sounding ridiculous.
""",
Tools = [AIFunctionFactory.Create(LookupPrice)],
},
ChatHistoryProvider = new InMemoryChatHistoryProvider(new() { ChatReducer = compactionPipeline }),
});
AgentSession session = await agent.CreateSessionAsync();
@@ -88,7 +89,7 @@ void PrintChatHistory()
if (session.TryGetInMemoryChatHistory(out var history))
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"\n[Messages: #{history.Count}]\n");
Console.WriteLine($"\n[Messages: x{history.Count}]\n");
Console.ResetColor();
}
}
@@ -115,6 +116,5 @@ foreach (string prompt in prompts)
Console.Write("\n[Agent] ");
Console.ResetColor();
Console.WriteLine(await agent.RunAsync(prompt, session));
PrintChatHistory();
}
@@ -1,132 +0,0 @@
# Compaction Pipeline
This sample demonstrates how to use a `CompactionProvider` with a `PipelineCompactionStrategy` to manage long conversation histories in a token-efficient way. The pipeline chains four compaction strategies, ordered from gentle to aggressive, so that the least disruptive strategy runs first and more aggressive strategies only activate when necessary.
## What This Sample Shows
- **`CompactionProvider`** — an `AIContextProvider` that applies a compaction strategy before each agent invocation, keeping only the most relevant messages within the model's context window
- **`PipelineCompactionStrategy`** — chains multiple compaction strategies into an ordered pipeline; each strategy evaluates its own trigger independently and operates on the output of the previous one
- **`ToolResultCompactionStrategy`** — collapses older tool-call groups into concise inline summaries, activated by a message-count trigger
- **`SummarizationCompactionStrategy`** — uses an LLM to compress older conversation spans into a single summary message, activated by a token-count trigger
- **`SlidingWindowCompactionStrategy`** — retains only the most recent N user turns and their responses, activated by a turn-count trigger
- **`TruncationCompactionStrategy`** — emergency backstop that drops the oldest groups until the conversation fits within a hard token budget
- **`CompactionTriggers`** — factory methods (`MessagesExceed`, `TokensExceed`, `TurnsExceed`, `GroupsExceed`, `HasToolCalls`, `All`, `Any`) that control when each strategy activates
## Concepts
### Message groups
The compaction engine organizes messages into atomic *groups* that are treated as indivisible units during compaction. A group is either:
| Group kind | Contents |
|---|---|
| `System` | System prompt message(s) |
| `User` | A single user message |
| `ToolCall` | One assistant message with tool calls + the matching tool result messages |
| `AssistantText` | A single assistant text-only message |
| `Summary` | One or more messages summarizing earlier conversation spans, produced by compaction strategies |
`Summary` groups (`CompactionGroupKind.Summary`) are created by compaction strategies (for example, `SummarizationCompactionStrategy`) and do not originate directly from user or assistant messages.
Strategies exclude entire groups rather than individual messages, preserving the tool-call/result pairing required by most model APIs.
### Compaction triggers
A `CompactionTrigger` is a predicate evaluated against the current `MessageIndex`. When the trigger fires, the strategy performs compaction; when it does not fire, the strategy is skipped. Available triggers are:
| Trigger | Activates when… |
|---|---|
| `CompactionTriggers.Always` | Always (unconditional) |
| `CompactionTriggers.Never` | Never (disabled) |
| `CompactionTriggers.MessagesExceed(n)` | Included message count > n |
| `CompactionTriggers.TokensExceed(n)` | Included token count > n |
| `CompactionTriggers.TurnsExceed(n)` | Included user-turn count > n |
| `CompactionTriggers.GroupsExceed(n)` | Included group count > n |
| `CompactionTriggers.HasToolCalls()` | At least one included tool-call group exists |
| `CompactionTriggers.All(...)` | All supplied triggers fire (logical AND) |
| `CompactionTriggers.Any(...)` | Any supplied trigger fires (logical OR) |
### Pipeline ordering
Order strategies from **least aggressive** to **most aggressive**. The pipeline runs every strategy whose trigger is met. Earlier strategies reduce the conversation gently so that later, more destructive strategies may not need to activate at all.
```
1. ToolResultCompactionStrategy gentle: replaces verbose tool results with a short label
2. SummarizationCompactionStrategy moderate: LLM-summarizes older turns
3. SlidingWindowCompactionStrategy aggressive: drops turns beyond the window
4. TruncationCompactionStrategy emergency: hard token-budget enforcement
```
## Prerequisites
- .NET 10 SDK or later
- Azure OpenAI service endpoint and model deployment
- Azure CLI installed and authenticated
**Note**: This sample uses `DefaultAzureCredential`. Sign in with `az login` before running. For production, prefer a specific credential such as `ManagedIdentityCredential`. For more information, see the [Azure CLI authentication documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively).
## Environment Variables
```powershell
$env:AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" # Required
$env:AZURE_OPENAI_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini
```
## Running the Sample
```powershell
cd dotnet/samples/02-agents/Agents/Agent_Step18_CompactionPipeline
dotnet run
```
## Expected Behavior
The sample runs a seven-turn shopping-assistant conversation with tool calls. After each turn it prints the full message count so you can observe the pipeline compaction doesn't alter the source conversation.
Each of the four compaction strategies has a deliberately low threshold so that it activates during the short demonstration conversation. In a production scenario you would raise the thresholds to match your model's context window and cost requirements.
## Customizing the Pipeline
### Using a single strategy
If you only need one compaction strategy, pass it directly to `CompactionProvider` without wrapping it in a pipeline:
```csharp
CompactionProvider provider =
new(new SlidingWindowCompactionStrategy(CompactionTriggers.TurnsExceed(20)));
```
### Ad-hoc compaction outside the provider pipeline
`CompactionProvider.CompactAsync` applies a strategy to an arbitrary list of messages without an active agent session:
```csharp
IEnumerable<ChatMessage> compacted = await CompactionProvider.CompactAsync(
new TruncationCompactionStrategy(CompactionTriggers.TokensExceed(8000)),
existingMessages);
```
### Using a different model for summarization
The `SummarizationCompactionStrategy` accepts any `IChatClient`. Use a smaller, cheaper model to reduce summarization cost:
```csharp
IChatClient summarizerChatClient = openAIClient.GetChatClient("gpt-4o-mini").AsIChatClient();
new SummarizationCompactionStrategy(summarizerChatClient, CompactionTriggers.TokensExceed(4000))
```
### Registering through `ChatClientAgentOptions`
`CompactionProvider` can also be specified directly on `ChatClientAgentOptions` instead of calling `UseAIContextProviders` on the `ChatClientBuilder`:
```csharp
AIAgent agent = agentChatClient
.AsBuilder()
.BuildAIAgent(new ChatClientAgentOptions
{
AIContextProviders = [new CompactionProvider(compactionPipeline)]
});
```
This places the compaction provider at the agent level instead of the chat client level, which allows you to use different compaction strategies for different agents that share the same chat client.
> Note: In this mode the `CompactionProvider` is not engaged during the tool calling loop. Agent-level `AIContextProviders` run before chat history is stored, so any synthetic summary messages produced by `CompactionProvider` can become part of the persisted history when using `ChatHistoryProvider`. If you want to compact only the request context while preserving the original stored history, register `CompactionProvider` on the `ChatClientBuilder` via `UseAIContextProviders(...)` instead of on `ChatClientAgentOptions`.
@@ -12,8 +12,11 @@ using OpenAI.Responses;
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
string embeddingModelName = Environment.GetEnvironmentVariable("AZURE_AI_EMBEDDING_DEPLOYMENT_NAME") ?? "text-embedding-ada-002";
string memoryStoreName = Environment.GetEnvironmentVariable("AZURE_AI_MEMORY_STORE_ID") ?? $"foundry-memory-sample-{Guid.NewGuid():N}";
// Memory store configuration
// NOTE: Memory stores must be created beforehand via Azure Portal or Python SDK.
// The .NET SDK currently only supports using existing memory stores with agents.
string memoryStoreName = Environment.GetEnvironmentVariable("AZURE_AI_MEMORY_STORE_ID") ?? throw new InvalidOperationException("AZURE_AI_MEMORY_STORE_ID is not set.");
const string AgentInstructions = """
You are a helpful assistant that remembers past conversations.
@@ -29,57 +32,71 @@ const string AgentNameNative = "MemorySearchAgent-NATIVE";
string userScope = $"user_{Environment.MachineName}";
// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents.
DefaultAzureCredential credential = new();
AIProjectClient aiProjectClient = new(new Uri(endpoint), credential);
// Ensure the memory store exists and has memories to retrieve.
await EnsureMemoryStoreAsync();
AIProjectClient aiProjectClient = new(new Uri(endpoint), new AzureCliCredential());
// Create the Memory Search tool configuration
MemorySearchPreviewTool memorySearchTool = new(memoryStoreName, userScope) { UpdateDelay = 0 };
MemorySearchPreviewTool memorySearchTool = new(memoryStoreName, userScope)
{
// Optional: Configure how quickly new memories are indexed (in seconds)
UpdateDelay = 1,
// Optional: Configure search behavior
SearchOptions = new MemorySearchToolOptions
{
// Additional search options can be configured here if needed
}
};
// Create agent using Option 1 (MEAI) or Option 2 (Native SDK)
AIAgent agent = await CreateAgentWithMEAI();
// AIAgent agent = await CreateAgentWithNativeSDK();
try
Console.WriteLine("Agent created with Memory Search tool. Starting conversation...\n");
// Conversation 1: Share some personal information
Console.WriteLine("User: My name is Alice and I love programming in C#.");
AgentResponse response1 = await agent.RunAsync("My name is Alice and I love programming in C#.");
Console.WriteLine($"Agent: {response1.Messages.LastOrDefault()?.Text}\n");
// Allow time for memory to be indexed
await Task.Delay(2000);
// Conversation 2: Test if the agent remembers
Console.WriteLine("User: What's my name and what programming language do I prefer?");
AgentResponse response2 = await agent.RunAsync("What's my name and what programming language do I prefer?");
Console.WriteLine($"Agent: {response2.Messages.LastOrDefault()?.Text}\n");
// Inspect memory search results if available in raw response items
// Note: Memory search tool call results appear as AgentResponseItem types
foreach (var message in response2.Messages)
{
Console.WriteLine("Agent created with Memory Search tool. Starting conversation...\n");
// The agent uses the memory search tool to recall stored information.
Console.WriteLine("User: What's my name and what programming language do I prefer?");
AgentResponse response = await agent.RunAsync("What's my name and what programming language do I prefer?");
Console.WriteLine($"Agent: {response.Messages.LastOrDefault()?.Text}\n");
// Inspect memory search results if available in raw response items.
foreach (var message in response.Messages)
if (message.RawRepresentation is AgentResponseItem agentResponseItem &&
agentResponseItem is MemorySearchToolCallResponseItem memorySearchResult)
{
if (message.RawRepresentation is MemorySearchToolCallResponseItem memorySearchResult)
{
Console.WriteLine($"Memory Search Status: {memorySearchResult.Status}");
Console.WriteLine($"Memory Search Results Count: {memorySearchResult.Results.Count}");
Console.WriteLine($"Memory Search Status: {memorySearchResult.Status}");
Console.WriteLine($"Memory Search Results Count: {memorySearchResult.Results.Count}");
foreach (var result in memorySearchResult.Results)
{
var memoryItem = result.MemoryItem;
Console.WriteLine($" - Memory ID: {memoryItem.MemoryId}");
Console.WriteLine($" Scope: {memoryItem.Scope}");
Console.WriteLine($" Content: {memoryItem.Content}");
Console.WriteLine($" Updated: {memoryItem.UpdatedAt}");
}
foreach (var result in memorySearchResult.Results)
{
var memoryItem = result.MemoryItem;
Console.WriteLine($" - Memory ID: {memoryItem.MemoryId}");
Console.WriteLine($" Scope: {memoryItem.Scope}");
Console.WriteLine($" Content: {memoryItem.Content}");
Console.WriteLine($" Updated: {memoryItem.UpdatedAt}");
}
}
}
finally
{
// Cleanup: Delete the agent and memory store.
Console.WriteLine("\nCleaning up...");
await aiProjectClient.Agents.DeleteAgentAsync(agent.Name);
Console.WriteLine("Agent deleted.");
await aiProjectClient.MemoryStores.DeleteMemoryStoreAsync(memoryStoreName);
Console.WriteLine("Memory store deleted.");
}
// Cleanup: Delete the agent (memory store persists and should be cleaned up separately if needed)
Console.WriteLine("\nCleaning up agent...");
await aiProjectClient.Agents.DeleteAgentAsync(agent.Name);
Console.WriteLine("Agent deleted successfully.");
// NOTE: Memory stores are long-lived resources and are NOT deleted with the agent.
// To delete a memory store, use the Azure Portal or Python SDK:
// await project_client.memory_stores.delete(memory_store.name)
// --- Agent Creation Options ---
#pragma warning disable CS8321 // Local function is declared but never used
// Option 1 - Using MemorySearchTool wrapped as MEAI AITool
@@ -105,36 +122,3 @@ async Task<AIAgent> CreateAgentWithNativeSDK()
})
);
}
// Helpers — kept at the bottom so the main agent flow above stays clean.
async Task EnsureMemoryStoreAsync()
{
Console.WriteLine($"Creating memory store '{memoryStoreName}'...");
try
{
await aiProjectClient.MemoryStores.GetMemoryStoreAsync(memoryStoreName);
Console.WriteLine("Memory store already exists.");
}
catch (System.ClientModel.ClientResultException ex) when (ex.Status == 404)
{
MemoryStoreDefaultDefinition definition = new(deploymentName, embeddingModelName);
await aiProjectClient.MemoryStores.CreateMemoryStoreAsync(memoryStoreName, definition, "Sample memory store for Memory Search demo");
Console.WriteLine("Memory store created.");
}
Console.WriteLine("Storing memories from a prior conversation...");
MemoryUpdateOptions memoryOptions = new(userScope) { UpdateDelay = 0 };
memoryOptions.Items.Add(ResponseItem.CreateUserMessageItem("My name is Alice and I love programming in C#."));
MemoryUpdateResult updateResult = await aiProjectClient.MemoryStores.WaitForMemoriesUpdateAsync(
memoryStoreName: memoryStoreName,
options: memoryOptions,
pollingInterval: 500);
if (updateResult.Status == MemoryStoreUpdateStatus.Failed)
{
throw new InvalidOperationException($"Memory update failed: {updateResult.ErrorDetails}");
}
Console.WriteLine($"Memory update completed (status: {updateResult.Status}).\n");
}
@@ -10,7 +10,7 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
using ChatClient = OpenAI.Chat.ChatClient;
namespace AGUIDojoServer;
@@ -36,7 +36,7 @@ internal static class ChatClientAgentFactory
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
return chatClient.AsAIAgent(
return chatClient.AsIChatClient().AsAIAgent(
name: "AgenticChat",
description: "A simple chat agent using Azure OpenAI");
}
@@ -45,7 +45,7 @@ internal static class ChatClientAgentFactory
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
return chatClient.AsAIAgent(
return chatClient.AsIChatClient().AsAIAgent(
name: "BackendToolRenderer",
description: "An agent that can render backend tools using Azure OpenAI",
tools: [AIFunctionFactory.Create(
@@ -59,7 +59,7 @@ internal static class ChatClientAgentFactory
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
return chatClient.AsAIAgent(
return chatClient.AsIChatClient().AsAIAgent(
name: "HumanInTheLoopAgent",
description: "An agent that involves human feedback in its decision-making process using Azure OpenAI");
}
@@ -68,7 +68,7 @@ internal static class ChatClientAgentFactory
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
return chatClient.AsAIAgent(
return chatClient.AsIChatClient().AsAIAgent(
name: "ToolBasedGenerativeUIAgent",
description: "An agent that uses tools to generate user interfaces using Azure OpenAI");
}
@@ -76,7 +76,7 @@ internal static class ChatClientAgentFactory
public static AIAgent CreateAgenticUI(JsonSerializerOptions options)
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
var baseAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
var baseAgent = chatClient.AsIChatClient().AsAIAgent(new ChatClientAgentOptions
{
Name = "AgenticUIAgent",
Description = "An agent that generates agentic user interfaces using Azure OpenAI",
@@ -119,7 +119,7 @@ internal static class ChatClientAgentFactory
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
var baseAgent = chatClient.AsAIAgent(
var baseAgent = chatClient.AsIChatClient().AsAIAgent(
name: "SharedStateAgent",
description: "An agent that demonstrates shared state patterns using Azure OpenAI");
@@ -130,7 +130,7 @@ internal static class ChatClientAgentFactory
{
ChatClient chatClient = s_azureOpenAIClient!.GetChatClient(s_deploymentName!);
var baseAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
var baseAgent = chatClient.AsIChatClient().AsAIAgent(new ChatClientAgentOptions
{
Name = "PredictiveStateUpdatesAgent",
Description = "An agent that demonstrates predictive state updates using Azure OpenAI",
@@ -74,7 +74,7 @@ AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(
ChatClient chatClient = azureOpenAIClient.GetChatClient(deploymentName);
// Create AI agent
ChatClientAgent agent = chatClient.AsAIAgent(
ChatClientAgent agent = chatClient.AsIChatClient().AsAIAgent(
name: "ChatAssistant",
instructions: "You are a helpful assistant.");
@@ -162,7 +162,7 @@ dotnet run
Edit the instructions in `Server/Program.cs`:
```csharp
ChatClientAgent agent = chatClient.AsAIAgent(
ChatClientAgent agent = chatClient.AsIChatClient().AsAIAgent(
name: "ChatAssistant",
instructions: "You are a helpful coding assistant specializing in C# and .NET.");
```
@@ -6,6 +6,7 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
@@ -27,7 +28,7 @@ AzureOpenAIClient azureOpenAIClient = new(
ChatClient chatClient = azureOpenAIClient.GetChatClient(deploymentName);
ChatClientAgent agent = chatClient.AsAIAgent(
ChatClientAgent agent = chatClient.AsIChatClient().AsAIAgent(
name: "ChatAssistant",
instructions: "You are a helpful assistant.");
@@ -12,7 +12,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Chat;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
@@ -90,6 +89,7 @@ builder.Services.AddSingleton<AIAgent>(sp =>
return new OpenAIClient(apiKey)
.GetChatClient(model)
.AsIChatClient()
.AsAIAgent(
name: "ExpenseApprovalAgent",
instructions: "You are an expense approval assistant. You can list pending expenses "
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
</ItemGroup>
<ItemGroup>
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -36,10 +36,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.9" />
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.8" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.8.0-beta.1" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-preview.251219.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.1.1-preview.1.25612.2" />
</ItemGroup>
<!-- Add analyzers with compatible versions -->
@@ -11,10 +11,9 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
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-4o-mini";
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
@@ -23,19 +22,17 @@ static string GetWeather([Description("The location to get the weather for.")] s
// Create the chat client and agent.
// Note: ApprovalRequiredAIFunction wraps the tool to require user approval before invocation.
// User should reply with 'approve' or 'reject' when prompted.
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
#pragma warning disable MEAI001 // Type is for evaluation purposes only
AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
new AzureCliCredential())
.GetChatClient(deploymentName)
.AsAIAgent(
.AsIChatClient()
.CreateAIAgent(
instructions: "You are a helpful assistant",
tools: [new ApprovalRequiredAIFunction(AIFunctionFactory.Create(GetWeather))]
);
#pragma warning restore MEAI001
InMemoryAgentThreadRepository threadRepository = new(agent);
var threadRepository = new InMemoryAgentThreadRepository(agent);
await agent.RunAIAgentAsync(telemetrySourceName: "Agents", threadRepository: threadRepository);
@@ -35,10 +35,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.9" />
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.6" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.8.0-beta.1" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.3.0" />
</ItemGroup>
<!-- Add analyzers with compatible versions -->
@@ -9,10 +9,9 @@ using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI.Responses;
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
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-4o-mini";
// Create an MCP tool that can be called without approval.
AITool mcpTool = new HostedMcpServerTool(serverName: "microsoft_learn", serverAddress: "https://learn.microsoft.com/api/mcp")
@@ -29,7 +28,8 @@ AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetResponsesClient(deploymentName)
.AsAIAgent(
.AsIChatClient()
.CreateAIAgent(
instructions: "You answer questions by searching the Microsoft Learn content only.",
name: "MicrosoftLearnAgent",
tools: [mcpTool]);
@@ -18,7 +18,7 @@ Before running this sample, ensure you have:
2. A deployment of a chat model (e.g., gpt-4o-mini)
3. Azure CLI installed and authenticated
**Note**: This sample uses `DefaultAzureCredential` for authentication, which probes multiple sources automatically. For local development, make sure you're logged in with `az login` and have access to the Azure OpenAI resource.
**Note**: This sample uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure OpenAI resource.
## Environment Variables
@@ -36,11 +36,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.9" />
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.8" />
<PackageReference Include="Azure.AI.Projects" Version="1.2.0-beta.5" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.8.0-beta.1" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.3.0" />
</ItemGroup>
<!-- Add analyzers with compatible versions -->
@@ -15,21 +15,21 @@ using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
var endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
var deploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
Console.WriteLine($"Project Endpoint: {endpoint}");
Console.WriteLine($"Model Deployment: {deploymentName}");
Hotel[] seattleHotels =
[
var seattleHotels = new[]
{
new Hotel("Contoso Suites", 189, 4.5, "Downtown"),
new Hotel("Fabrikam Residences", 159, 4.2, "Pike Place Market"),
new Hotel("Alpine Ski House", 249, 4.7, "Seattle Center"),
new Hotel("Margie's Travel Lodge", 219, 4.4, "Waterfront"),
new Hotel("Northwind Inn", 139, 4.0, "Capitol Hill"),
new Hotel("Relecloud Hotel", 99, 3.8, "University District"),
];
};
[Description("Get available hotels in Seattle for the specified dates. This simulates a call to a hotel availability API.")]
string GetAvailableHotels(
@@ -54,21 +54,21 @@ string GetAvailableHotels(
return "Error: Check-out date must be after check-in date.";
}
int nights = (checkOut - checkIn).Days;
List<Hotel> availableHotels = seattleHotels.Where(h => h.PricePerNight <= maxPrice).ToList();
var nights = (checkOut - checkIn).Days;
var availableHotels = seattleHotels.Where(h => h.PricePerNight <= maxPrice).ToList();
if (availableHotels.Count == 0)
{
return $"No hotels found in Seattle within your budget of ${maxPrice}/night.";
}
StringBuilder result = new();
var result = new StringBuilder();
result.AppendLine($"Available hotels in Seattle from {checkInDate} to {checkOutDate} ({nights} nights):");
result.AppendLine();
foreach (Hotel hotel in availableHotels)
foreach (var hotel in availableHotels)
{
int totalCost = hotel.PricePerNight * nights;
var totalCost = hotel.PricePerNight * nights;
result.AppendLine($"**{hotel.Name}**");
result.AppendLine($" Location: {hotel.Location}");
result.AppendLine($" Rating: {hotel.Rating}/5");
@@ -84,10 +84,7 @@ string GetAvailableHotels(
}
}
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
DefaultAzureCredential credential = new();
var credential = new AzureCliCredential();
AIProjectClient projectClient = new(new Uri(endpoint), credential);
ClientConnection connection = projectClient.GetConnection(typeof(AzureOpenAIClient).FullName!);
@@ -99,14 +96,14 @@ if (!connection.TryGetLocatorAsUri(out Uri? openAiEndpoint) || openAiEndpoint is
openAiEndpoint = new Uri($"https://{openAiEndpoint.Host}");
Console.WriteLine($"OpenAI Endpoint: {openAiEndpoint}");
IChatClient chatClient = new AzureOpenAIClient(openAiEndpoint, credential)
var chatClient = new AzureOpenAIClient(openAiEndpoint, credential)
.GetChatClient(deploymentName)
.AsIChatClient()
.AsBuilder()
.UseOpenTelemetry(sourceName: "Agents", configure: cfg => cfg.EnableSensitiveData = false)
.Build();
AIAgent agent = chatClient.AsAIAgent(
var agent = new ChatClientAgent(chatClient,
name: "SeattleHotelAgent",
instructions: """
You are a helpful travel assistant specializing in finding hotels in Seattle, Washington.
@@ -35,10 +35,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.9" />
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.5" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.7.0-beta.2" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-preview.251219.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.1.1-preview.1.25612.2" />
</ItemGroup>
<!-- Add analyzers with compatible versions -->
@@ -11,8 +11,8 @@ using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
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-4o-mini";
TextSearchProviderOptions textSearchOptions = new()
{
@@ -28,13 +28,13 @@ AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsAIAgent(new ChatClientAgentOptions
.CreateAIAgent(new ChatClientAgentOptions
{
ChatOptions = new ChatOptions
{
Instructions = "You are a helpful support specialist for Contoso Outdoors. Answer questions using the provided context and cite the source document when available.",
},
AIContextProviders = [new TextSearchProvider(MockSearchAsync, textSearchOptions)]
AIContextProviderFactory = ctx => new TextSearchProvider(MockSearchAsync, ctx.SerializedState, ctx.JsonSerializerOptions, textSearchOptions)
});
await agent.RunAIAgentAsync();
@@ -35,10 +35,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.9" />
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.8" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.8.0-beta.1" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-preview.251219.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.3.0" />
</ItemGroup>
<!-- Add analyzers with compatible versions -->
@@ -9,16 +9,13 @@ using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
string toolConnectionId = Environment.GetEnvironmentVariable("MCP_TOOL_CONNECTION_ID") ?? throw new InvalidOperationException("MCP_TOOL_CONNECTION_ID is not set.");
var openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
var toolConnectionId = Environment.GetEnvironmentVariable("MCP_TOOL_CONNECTION_ID") ?? throw new InvalidOperationException("MCP_TOOL_CONNECTION_ID is not set.");
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
DefaultAzureCredential credential = new();
var credential = new AzureCliCredential();
IChatClient chatClient = new AzureOpenAIClient(new Uri(openAiEndpoint), credential)
var chatClient = new AzureOpenAIClient(new Uri(openAiEndpoint), credential)
.GetChatClient(deploymentName)
.AsIChatClient()
.AsBuilder()
@@ -26,7 +23,7 @@ IChatClient chatClient = new AzureOpenAIClient(new Uri(openAiEndpoint), credenti
.UseOpenTelemetry(sourceName: "Agents", configure: (cfg) => cfg.EnableSensitiveData = true)
.Build();
AIAgent agent = chatClient.AsAIAgent(
var agent = new ChatClientAgent(chatClient,
name: "AgentWithTools",
instructions: @"You are a helpful assistant with access to tools for fetching Microsoft documentation.
@@ -6,7 +6,7 @@ Key features:
- Configuring Foundry tools using `UseFoundryTools` with MCP and code interpreter
- Connecting to an external MCP tool via a Foundry project connection
- Using `DefaultAzureCredential` for Azure authentication
- Using `AzureCliCredential` for Azure authentication
- OpenTelemetry instrumentation for both the chat client and agent
> For common prerequisites and setup instructions, see the [Hosted Agent Samples README](../README.md).
@@ -36,7 +36,7 @@ $env:MCP_TOOL_CONNECTION_ID="SampleMCPTool"
## How It Works
1. An `AzureOpenAIClient` is created with `DefaultAzureCredential` and used to get a chat client
1. An `AzureOpenAIClient` is created with `AzureCliCredential` and used to get a chat client
2. The chat client is wrapped with `UseFoundryTools` which registers two Foundry tool types:
- **MCP connection**: Connects to an external MCP server (Microsoft Learn) via the project connection name, providing documentation fetch and search capabilities
- **Code interpreter**: Allows the agent to execute code snippets when needed
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -35,10 +35,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.9" />
<PackageReference Include="Azure.AI.AgentServer.AgentFramework" Version="1.0.0-beta.5" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.7.0-beta.2" />
<PackageReference Include="Azure.Identity" Version="1.17.1" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.0.0-preview.251219.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.1.0-preview.1.25608.1" />
</ItemGroup>
<!-- Add analyzers with compatible versions -->
@@ -12,8 +12,8 @@ using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
// Set up the Azure OpenAI client
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
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-4o-mini";
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
@@ -32,9 +32,9 @@ AIAgent agent = new WorkflowBuilder(frenchAgent)
.AddEdge(frenchAgent, spanishAgent)
.AddEdge(spanishAgent, englishAgent)
.Build()
.AsAIAgent();
.AsAgent();
await agent.RunAIAgentAsync();
static AIAgent GetTranslationAgent(string targetLanguage, IChatClient chatClient) =>
chatClient.AsAIAgent($"You are a translation assistant that translates the provided text to {targetLanguage}.");
static ChatClientAgent GetTranslationAgent(string targetLanguage, IChatClient chatClient) =>
new(chatClient, $"You are a translation assistant that translates the provided text to {targetLanguage}.");
@@ -19,7 +19,7 @@ Before you begin, ensure you have the following prerequisites:
- Azure OpenAI service endpoint and deployment configured
- Azure CLI installed and authenticated (for Azure credential authentication)
**Note**: This demo uses `DefaultAzureCredential` for authentication, which probes multiple sources automatically. For local development, make sure you're logged in with `az login` and have access to the Azure OpenAI resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively).
**Note**: This demo uses Azure CLI credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure OpenAI resource. For more information, see the [Azure CLI documentation](https://learn.microsoft.com/cli/azure/authenticate-azure-cli-interactively).
Set the following environment variables:
@@ -25,7 +25,7 @@ Before running any sample, ensure you have:
### Authenticate with Azure CLI
All samples use `DefaultAzureCredential` for authentication, which automatically probes multiple credential sources (environment variables, managed identity, Azure CLI, etc.). For local development, the simplest approach is to authenticate via Azure CLI:
All samples use `AzureCliCredential` for authentication. Make sure you're logged in:
```powershell
az login
@@ -127,7 +127,6 @@ public sealed class A2AAgent : AIAgent
{
AgentId = this.Id,
ResponseId = message.MessageId,
FinishReason = ChatFinishReason.Stop,
RawRepresentation = message,
Messages = [message.ToChatMessage()],
AdditionalProperties = message.Metadata?.ToAdditionalProperties(),
@@ -142,7 +141,6 @@ public sealed class A2AAgent : AIAgent
{
AgentId = this.Id,
ResponseId = agentTask.Id,
FinishReason = MapTaskStateToFinishReason(agentTask.Status.State),
RawRepresentation = agentTask,
Messages = agentTask.ToChatMessages() ?? [],
ContinuationToken = CreateContinuationToken(agentTask.Id, agentTask.Status.State),
@@ -330,7 +328,6 @@ public sealed class A2AAgent : AIAgent
{
AgentId = this.Id,
ResponseId = message.MessageId,
FinishReason = ChatFinishReason.Stop,
RawRepresentation = message,
Role = ChatRole.Assistant,
MessageId = message.MessageId,
@@ -345,7 +342,6 @@ public sealed class A2AAgent : AIAgent
{
AgentId = this.Id,
ResponseId = task.Id,
FinishReason = MapTaskStateToFinishReason(task.Status.State),
RawRepresentation = task,
Role = ChatRole.Assistant,
Contents = task.ToAIContents(),
@@ -369,16 +365,7 @@ public sealed class A2AAgent : AIAgent
responseUpdate.Contents = artifactUpdateEvent.Artifact.ToAIContents();
responseUpdate.RawRepresentation = artifactUpdateEvent;
}
else if (taskUpdateEvent is TaskStatusUpdateEvent statusUpdateEvent)
{
responseUpdate.FinishReason = MapTaskStateToFinishReason(statusUpdateEvent.Status.State);
}
return responseUpdate;
}
private static ChatFinishReason? MapTaskStateToFinishReason(TaskState state)
{
return state == TaskState.Completed ? ChatFinishReason.Stop : null;
}
}
@@ -20,19 +20,6 @@ namespace Microsoft.Agents.AI;
/// <see cref="AIAgent"/> serves as the foundational class for implementing AI agents that can participate in conversations
/// and process user requests. An agent instance may participate in multiple concurrent conversations, and each conversation
/// may involve multiple agents working together.
/// <para>
/// <strong>Security considerations:</strong> An <see cref="AIAgent"/> orchestrates data flow across trust boundaries —
/// messages are sent to external AI services, context providers, chat history stores, and function tools. Agent Framework
/// passes messages through as-is without validation or sanitization. Developers must be aware that:
/// <list type="bullet">
/// <item><description>User-supplied messages may contain prompt injection attempts designed to manipulate LLM behavior.</description></item>
/// <item><description>LLM responses should be treated as untrusted output — they may contain hallucinations, malicious payloads (e.g., scripts, SQL),
/// or content influenced by indirect prompt injection. Always validate and sanitize LLM output before rendering in HTML, executing as code,
/// or using in database queries.</description></item>
/// <item><description>Messages with different roles carry different trust levels: <c>system</c> messages have the highest trust and must be developer-controlled;
/// <c>user</c>, <c>assistant</c>, and <c>tool</c> messages should be treated as untrusted.</description></item>
/// </list>
/// </para>
/// </remarks>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public abstract partial class AIAgent
@@ -178,11 +165,6 @@ public abstract partial class AIAgent
/// This method enables saving conversation sessions to persistent storage,
/// allowing conversations to resume across application restarts or be migrated between
/// different agent instances. Use <see cref="DeserializeSessionAsync"/> to restore the session.
/// <para>
/// <strong>Security consideration:</strong> Serialized sessions may contain conversation content, session identifiers,
/// and other potentially sensitive data including PII. Ensure that serialized session data is stored securely with
/// appropriate access controls and encryption at rest.
/// </para>
/// </remarks>
public ValueTask<JsonElement> SerializeSessionAsync(AgentSession session, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
=> this.SerializeSessionCoreAsync(session, jsonSerializerOptions, cancellationToken);
@@ -212,12 +194,6 @@ public abstract partial class AIAgent
/// This method enables restoration of conversation sessions from previously saved state,
/// allowing conversations to resume across application restarts or be migrated between
/// different agent instances.
/// <para>
/// <strong>Security consideration:</strong> Restoring a session from an untrusted source is equivalent to accepting untrusted input.
/// Serialized sessions may contain conversation content, session identifiers, and potentially sensitive data. A compromised
/// storage backend could alter message roles to escalate trust, or inject adversarial content that influences LLM behavior.
/// Treat serialized session data as sensitive and ensure it is stored and transmitted securely.
/// </para>
/// </remarks>
public ValueTask<AgentSession> DeserializeSessionAsync(JsonElement serializedState, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
=> this.DeserializeSessionCoreAsync(serializedState, jsonSerializerOptions, cancellationToken);
@@ -325,11 +301,6 @@ public abstract partial class AIAgent
/// The messages are processed in the order provided and become part of the conversation history.
/// The agent's response will also be added to <paramref name="session"/> if one is provided.
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Agent Framework does not validate or sanitize message content — it is passed through
/// to the underlying AI service as-is. If input messages include untrusted user content, developers should be aware of prompt injection risks.
/// System-role messages must be developer-controlled and should never contain end-user input.
/// </para>
/// </remarks>
public Task<AgentResponse> RunAsync(
IEnumerable<ChatMessage> messages,
@@ -455,11 +426,6 @@ public abstract partial class AIAgent
/// Each <see cref="AgentResponseUpdate"/> represents a portion of the complete response, allowing consumers
/// to display partial results, implement progressive loading, or provide immediate feedback to users.
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Agent Framework does not validate or sanitize message content — it is passed through
/// to the underlying AI service as-is. If input messages include untrusted user content, developers should be aware of prompt injection risks.
/// System-role messages must be developer-controlled and should never contain end-user input.
/// </para>
/// </remarks>
public async IAsyncEnumerable<AgentResponseUpdate> RunStreamingAsync(
IEnumerable<ChatMessage> messages,
@@ -28,14 +28,6 @@ namespace Microsoft.Agents.AI;
/// <see cref="InvokingAsync"/> to provide context, and optionally called at the end of invocation via
/// <see cref="InvokedAsync"/> to process results.
/// </para>
/// <para>
/// <strong>Security considerations:</strong> Context providers may inject messages with any role, including <c>system</c>, which
/// has the highest trust level and directly shapes LLM behavior. Developers must ensure that all providers attached to an agent
/// are trusted. Agent Framework does not validate or filter the data returned by providers — it is accepted as-is and merged into
/// the request context. If a provider retrieves data from an external source (e.g., a vector database or memory service), be aware
/// that a compromised data source could introduce adversarial content designed to manipulate LLM behavior via indirect prompt injection.
/// Implementers should validate and sanitize data retrieved from external sources before returning it.
/// </para>
/// </remarks>
public abstract class AIContextProvider
{
@@ -104,11 +96,6 @@ public abstract class AIContextProvider
/// <item><description>Injecting contextual messages from conversation history</description></item>
/// </list>
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Data retrieved from external sources (e.g., vector databases, memory services, or
/// knowledge bases) may contain adversarial content designed to influence LLM behavior via indirect prompt injection.
/// Implementers should validate data integrity and consider the trustworthiness of the data source.
/// </para>
/// </remarks>
public ValueTask<AIContext> InvokingAsync(InvokingContext context, CancellationToken cancellationToken = default)
=> this.InvokingCoreAsync(Throw.IfNull(context), cancellationToken);
@@ -208,11 +195,6 @@ public abstract class AIContextProvider
/// In contrast with <see cref="InvokingCoreAsync"/>, this method only returns additional context to be merged with the input,
/// while <see cref="InvokingCoreAsync"/> is responsible for returning the full merged <see cref="AIContext"/> for the invocation.
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Any messages, tools, or instructions returned by this method will be merged into the
/// AI request context. If data is retrieved from external or untrusted sources, implementers should validate and sanitize it
/// to prevent indirect prompt injection attacks.
/// </para>
/// </remarks>
/// <param name="context">Contains the request context including the caller provided messages that will be used by the agent for this invocation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
@@ -317,10 +299,6 @@ public abstract class AIContextProvider
/// <para>
/// The default implementation of <see cref="InvokedCoreAsync"/> only calls this method if the invocation succeeded.
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Messages being processed/stored may contain PII and sensitive conversation content.
/// Implementers should ensure appropriate encryption at rest and access controls for the storage backend.
/// </para>
/// </remarks>
protected virtual ValueTask StoreAIContextAsync(InvokedContext context, CancellationToken cancellationToken = default) =>
default;
@@ -61,7 +61,6 @@ public class AgentResponse
this.AdditionalProperties = response.AdditionalProperties;
this.CreatedAt = response.CreatedAt;
this.FinishReason = response.FinishReason;
this.Messages = response.Messages;
this.RawRepresentation = response;
this.ResponseId = response.ResponseId;
@@ -85,7 +84,6 @@ public class AgentResponse
this.AdditionalProperties = response.AdditionalProperties;
this.CreatedAt = response.CreatedAt;
this.FinishReason = response.FinishReason;
this.Messages = response.Messages;
this.RawRepresentation = response;
this.ResponseId = response.ResponseId;
@@ -192,21 +190,6 @@ public class AgentResponse
/// </remarks>
public DateTimeOffset? CreatedAt { get; set; }
/// <summary>
/// Gets or sets the reason for the agent response finishing.
/// </summary>
/// <value>
/// A <see cref="ChatFinishReason"/> value indicating why the response finished (e.g., stop, length, content filter, tool calls),
/// or <see langword="null"/> if the finish reason is not available.
/// </value>
/// <remarks>
/// <para>
/// This property is particularly useful for detecting non-normal completions, such as content filtering
/// or token limit truncation, which may require special handling by the caller.
/// </para>
/// </remarks>
public ChatFinishReason? FinishReason { get; set; }
/// <summary>
/// Gets or sets the resource usage information for generating this response.
/// </summary>
@@ -293,7 +276,6 @@ public class AgentResponse
RawRepresentation = message.RawRepresentation,
Role = message.Role,
FinishReason = this.FinishReason,
AgentId = this.AgentId,
ResponseId = this.ResponseId,
MessageId = message.MessageId,
@@ -38,7 +38,6 @@ public static class AgentResponseExtensions
{
AdditionalProperties = response.AdditionalProperties,
CreatedAt = response.CreatedAt,
FinishReason = response.FinishReason,
Messages = response.Messages,
RawRepresentation = response,
ResponseId = response.ResponseId,
@@ -72,7 +71,6 @@ public static class AgentResponseExtensions
AuthorName = responseUpdate.AuthorName,
Contents = responseUpdate.Contents,
CreatedAt = responseUpdate.CreatedAt,
FinishReason = responseUpdate.FinishReason,
MessageId = responseUpdate.MessageId,
RawRepresentation = responseUpdate,
ResponseId = responseUpdate.ResponseId,
@@ -70,7 +70,6 @@ public class AgentResponseUpdate
this.AuthorName = chatResponseUpdate.AuthorName;
this.Contents = chatResponseUpdate.Contents;
this.CreatedAt = chatResponseUpdate.CreatedAt;
this.FinishReason = chatResponseUpdate.FinishReason;
this.MessageId = chatResponseUpdate.MessageId;
this.RawRepresentation = chatResponseUpdate;
this.ResponseId = chatResponseUpdate.ResponseId;
@@ -154,15 +153,6 @@ public class AgentResponseUpdate
/// </remarks>
public ResponseContinuationToken? ContinuationToken { get; set; }
/// <summary>
/// Gets or sets the reason for the agent response finishing.
/// </summary>
/// <value>
/// A <see cref="ChatFinishReason"/> value indicating why the response finished (e.g., stop, length, content filter, tool calls),
/// or <see langword="null"/> if the finish reason is not available or not yet determined (mid-stream).
/// </value>
public ChatFinishReason? FinishReason { get; set; }
/// <inheritdoc/>
public override string ToString() => this.Text;
@@ -42,15 +42,6 @@ namespace Microsoft.Agents.AI;
/// <see cref="JsonElement"/> and the <see cref="AIAgent.DeserializeSessionAsync(JsonElement, JsonSerializerOptions?, System.Threading.CancellationToken)"/> method
/// can be used to deserialize the session.
/// </para>
/// <para>
/// <strong>Security considerations:</strong> Serialized sessions may contain conversation content, session identifiers,
/// and other potentially sensitive data including PII. Developers should:
/// <list type="bullet">
/// <item><description>Treat serialized session data as sensitive and store it securely with appropriate access controls and encryption at rest.</description></item>
/// <item><description>Treat restoring a session from an untrusted source as equivalent to accepting untrusted input. A compromised storage backend
/// could alter message roles to escalate trust, or inject adversarial content that influences LLM behavior.</description></item>
/// </list>
/// </para>
/// </remarks>
/// <seealso cref="AIAgent"/>
/// <seealso cref="AIAgent.CreateSessionAsync(System.Threading.CancellationToken)"/>
@@ -76,11 +67,6 @@ public abstract class AgentSession
/// <summary>
/// Gets any arbitrary state associated with this session.
/// </summary>
/// <remarks>
/// Data stored in the <see cref="StateBag"/> will be included when the session is serialized.
/// Avoid storing secrets, credentials, or highly sensitive data in the state bag without appropriate encryption,
/// as this data may be persisted to external storage.
/// </remarks>
[JsonPropertyName("stateBag")]
public AgentSessionStateBag StateBag { get; protected set; } = new();
@@ -37,14 +37,6 @@ namespace Microsoft.Agents.AI;
/// A <see cref="ChatHistoryProvider"/> is only relevant for scenarios where the underlying AI service that the agent is using
/// does not use in-service chat history storage.
/// </para>
/// <para>
/// <strong>Security considerations:</strong> Agent Framework does not validate or filter the messages returned by the provider
/// during load — they are accepted as-is and treated identically to user-supplied messages. Implementers must ensure that only
/// trusted data is returned. If the underlying storage is compromised, adversarial content could influence LLM behavior via
/// indirect prompt injection — for example, injected messages could alter the conversation context or impersonate different roles.
/// Messages stored in chat history may contain PII and sensitive conversation content; implementers should consider encryption
/// at rest and appropriate access controls for the storage backend.
/// </para>
/// </remarks>
public abstract class ChatHistoryProvider
{
@@ -167,11 +159,6 @@ public abstract class ChatHistoryProvider
/// Messages are returned in chronological order to maintain proper conversation flow and context for the agent.
/// The oldest messages appear first in the collection, followed by more recent messages.
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Messages loaded from storage should be treated with the same caution as user-supplied
/// messages. A compromised storage backend could alter message roles to escalate trust (e.g., changing <c>user</c> messages to
/// <c>system</c> messages) or inject adversarial content that influences LLM behavior.
/// </para>
/// </remarks>
/// <param name="context">Contains the request context including the caller provided messages that will be used by the agent for this invocation.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
@@ -286,10 +273,6 @@ public abstract class ChatHistoryProvider
/// <para>
/// The default implementation of <see cref="InvokedCoreAsync"/> only calls this method if the invocation succeeded.
/// </para>
/// <para>
/// <strong>Security consideration:</strong> Messages being stored may contain PII and sensitive conversation content.
/// Implementers should ensure appropriate encryption at rest and access controls for the storage backend.
/// </para>
/// </remarks>
protected virtual ValueTask StoreChatHistoryAsync(InvokedContext context, CancellationToken cancellationToken = default) =>
default;
@@ -0,0 +1,102 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
public partial class ChatHistoryCompactionPipeline
{
/// <summary>
/// %%% COMMENT
/// </summary>
public enum Size
{
/// <summary>
/// %%% COMMENT
/// </summary>
Compact,
/// <summary>
/// %%% COMMENT
/// </summary>
Adequate,
/// <summary>
/// %%% COMMENT
/// </summary>
Accomodating,
}
/// <summary>
/// %%% COMMENT
/// </summary>
public enum Approach
{
/// <summary>
/// %%% COMMENT
/// </summary>
Aggressive,
/// <summary>
/// %%% COMMENT
/// </summary>
Balanced,
/// <summary>
/// %%% COMMENT
/// </summary>
Gentle,
}
/// <summary>
/// %%% COMMENT
/// </summary>
/// <param name="approach"></param>
/// <param name="size"></param>
/// <param name="chatClient"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public static ChatHistoryCompactionPipeline Create(Approach approach, Size size, IChatClient chatClient) =>
approach switch
{
Approach.Aggressive => CreateAgressive(size, chatClient),
Approach.Balanced => CreateBalanced(size),
Approach.Gentle => CreateGentle(size),
_ => throw new NotImplementedException(), // %%% EXCEPTION
};
private static ChatHistoryCompactionPipeline CreateAgressive(Size size, IChatClient chatClient) =>
new(// 1. Gentle: collapse old tool-call groups into short summaries like "[Tool calls: LookupPrice]"
new ToolResultCompactionStrategy(MaxTokens(size), preserveRecentGroups: 2),
// 2. Moderate: use an LLM to summarize older conversation spans into a concise message
new SummarizationCompactionStrategy(chatClient, MaxTokens(size), preserveRecentGroups: 2),
// 3. Aggressive: keep only the last N user turns and their responses
new SlidingWindowCompactionStrategy(MaxTurns(size)),
// 4. Emergency: drop oldest groups until under the token budget
new TruncationCompactionStrategy(MaxTokens(size), preserveRecentGroups: 1));
private static ChatHistoryCompactionPipeline CreateBalanced(Size size) =>
new(// 1. Gentle: collapse old tool-call groups into short summaries like "[Tool calls: LookupPrice]"
new ToolResultCompactionStrategy(MaxTokens(size), preserveRecentGroups: 2),
// 2. Aggressive: keep only the last N user turns and their responses
new SlidingWindowCompactionStrategy(MaxTurns(size)));
private static ChatHistoryCompactionPipeline CreateGentle(Size size) =>
new(// 1. Gentle: collapse old tool-call groups into short summaries like "[Tool calls: LookupPrice]"
new ToolResultCompactionStrategy(MaxTokens(size), preserveRecentGroups: 2));
private static int MaxTokens(Size size) =>
size switch
{
Size.Compact => 500,
Size.Adequate => 1000,
Size.Accomodating => 2000,
_ => throw new NotImplementedException(), // %%% EXCEPTION
};
private static int MaxTurns(Size size) =>
size switch
{
Size.Compact => 10,
Size.Adequate => 50,
Size.Accomodating => 100,
_ => throw new NotImplementedException(), // %%% EXCEPTION
};
}
@@ -0,0 +1,114 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Executes a chain of <see cref="ChatHistoryCompactionStrategy"/> instances in order
/// against a mutable message list.
/// </summary>
/// <remarks>
/// <para>
/// Each strategy's trigger is evaluated against the metrics <em>as they stand after prior strategies</em>,
/// so earlier strategies can bring the conversation within thresholds that cause later strategies to skip.
/// </para>
/// <para>
/// The pipeline is fully standalone — it can be used without any agent, session, or context provider.
/// It also implements <see cref="IChatReducer"/> so it can be used directly anywhere a reducer is
/// accepted (e.g., <see cref="InMemoryChatHistoryProviderOptions.ChatReducer"/>).
/// </para>
/// </remarks>
public partial class ChatHistoryCompactionPipeline : IChatReducer
{
private readonly ChatHistoryCompactionStrategy[] _strategies;
private readonly IChatHistoryMetricsCalculator _metricsCalculator;
/// <summary>
/// Initializes a new instance of the <see cref="ChatHistoryCompactionPipeline"/> class.
/// </summary>
/// <param name="strategies">The ordered list of compaction strategies to execute.</param>
/// <remarks>
/// By default, <see cref="DefaultChatHistoryMetricsCalculator"/> is used.
/// </remarks>
public ChatHistoryCompactionPipeline(
params IEnumerable<ChatHistoryCompactionStrategy> strategies)
: this(metricsCalculator: null, strategies) { }
/// <summary>
/// Initializes a new instance of the <see cref="ChatHistoryCompactionPipeline"/> class.
/// </summary>
/// <param name="metricsCalculator">
/// An optional metrics calculator. When <see langword="null"/>, a
/// <see cref="DefaultChatHistoryMetricsCalculator"/> is used.
/// </param>
/// <param name="strategies">The ordered list of compaction strategies to execute.</param>
public ChatHistoryCompactionPipeline(
IChatHistoryMetricsCalculator? metricsCalculator,
params IEnumerable<ChatHistoryCompactionStrategy> strategies)
{
this._strategies = [.. Throw.IfNull(strategies)];
this._metricsCalculator = metricsCalculator ?? DefaultChatHistoryMetricsCalculator.Instance;
}
/// <summary>
/// Reduces the given messages by running all strategies in sequence.
/// </summary>
/// <param name="messages">The messages to reduce.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
/// <returns>The reduced set of messages.</returns>
public virtual async Task<IEnumerable<ChatMessage>> ReduceAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
List<ChatMessage> messageBuffer = messages is List<ChatMessage> messageList ? messageList : [.. messages];
await this.CompactAsync(messageBuffer, cancellationToken).ConfigureAwait(false);
return messageBuffer;
}
/// <summary>
/// Run all strategies in sequence against the given messages.
/// </summary>
/// <param name="messages">The mutable message list to compact.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
/// <returns>A <see cref="CompactionPipelineResult"/> with aggregate and per-strategy metrics.</returns>
public async ValueTask<CompactionPipelineResult> CompactAsync(
List<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
Throw.IfNull(messages);
ChatHistoryMetric overallBefore = this._metricsCalculator.Calculate(messages);
Debug.WriteLine($"COMPACTION: BEGIN x{overallBefore.MessageCount}/#{overallBefore.UserTurnCount} ({overallBefore.TokenCount} tokens)");
List<CompactionResult> compactionResults = new(this._strategies.Length);
Stopwatch timer = new();
TimeSpan startTime = TimeSpan.Zero;
ChatHistoryMetric overallAfter = overallBefore;
ChatHistoryMetric currentBefore = overallBefore;
foreach (ChatHistoryCompactionStrategy strategy in this._strategies)
{
// %%% VERBOSE - Debug.WriteLine($"COMPACTION: {strategy.Name} START");
timer.Start();
ChatHistoryCompactionStrategy.s_currentMetrics.Value = currentBefore;
CompactionResult strategyResult = await strategy.CompactAsync(messages, this._metricsCalculator, cancellationToken).ConfigureAwait(false);
timer.Stop();
TimeSpan elapsedTime = timer.Elapsed - startTime;
// %%% VERBOSE - Debug.WriteLine($"COMPACTION: {strategy.Name} FINISH [{elapsedTime}]");
compactionResults.Add(strategyResult);
overallAfter = currentBefore = strategyResult.After;
}
Debug.WriteLineIf(overallBefore.TokenCount != overallAfter.TokenCount, $"COMPACTION: TOTAL [{timer.Elapsed}] {overallBefore.TokenCount} => {overallAfter.TokenCount} tokens");
return new(overallBefore, overallAfter, compactionResults);
}
}
@@ -0,0 +1,120 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// A named compaction strategy with an optional conditional trigger that delegates
/// actual message reduction to an <see cref="IChatReducer"/>.
/// </summary>
/// <remarks>
/// <para>
/// Each strategy wraps an <see cref="IChatReducer"/> that performs the actual compaction,
/// while the strategy adds:
/// <list type="bullet">
/// <item><description>A conditional trigger via <see cref="ShouldCompact"/> that decides whether compaction runs.</description></item>
/// <item><description>Before/after <see cref="ChatHistoryMetric"/> reporting via <see cref="CompactionResult"/>.</description></item>
/// </list>
/// </para>
/// <para>
/// For simple cases, construct a <see cref="ChatHistoryCompactionStrategy"/> directly with any
/// <see cref="IChatReducer"/>. For custom trigger logic, subclass and override <see cref="ShouldCompact"/>.
/// </para>
/// <para>
/// Reducers <b>must</b> preserve atomic message groups: an assistant message containing
/// tool calls and its corresponding tool result messages must be kept or removed together.
/// Use <see cref="DefaultChatHistoryMetricsCalculator"/> to identify these groups when authoring custom reducers.
/// </para>
/// </remarks>
public abstract class ChatHistoryCompactionStrategy
{
internal static readonly AsyncLocal<ChatHistoryMetric> s_currentMetrics = new();
/// <summary>
/// Initializes a new instance of the <see cref="ChatHistoryCompactionStrategy"/> class.
/// </summary>
/// <param name="reducer">The <see cref="IChatReducer"/> that performs the actual message compaction.</param>
protected ChatHistoryCompactionStrategy(IChatReducer reducer)
{
this.Reducer = Throw.IfNull(reducer);
}
/// <summary>
/// Exposes the current <see cref="ChatHistoryMetric"/> for the executing strategy, allowing <see cref="Reducer"/> to make informed decisions.
/// </summary>
protected static ChatHistoryMetric CurrentMetrics => s_currentMetrics.Value ?? throw new InvalidOperationException($"No active {nameof(ChatHistoryCompactionStrategy)}.");
/// <summary>
/// Gets the <see cref="IChatReducer"/> that performs the actual message compaction.
/// </summary>
public IChatReducer Reducer { get; }
/// <summary>
/// Gets the display name of this strategy, used for logging and diagnostics.
/// </summary>
/// <remarks>
/// The default implementation returns the type name of the underlying <see cref="IChatReducer"/>.
/// </remarks>
public virtual string Name => this.Reducer.GetType().Name;
/// <summary>
/// Evaluates whether this strategy should execute given the current conversation metrics.
/// </summary>
/// <param name="metrics">The current conversation metrics.</param>
/// <returns>
/// <see langword="true"/> to proceed with compaction; <see langword="false"/> to skip.
/// </returns>
protected abstract bool ShouldCompact(ChatHistoryMetric metrics);
/// <summary>
/// Execute this strategy: check the trigger, delegate to the <see cref="IChatReducer"/>, and report metrics.
/// </summary>
/// <param name="history">The mutable message list to compact.</param>
/// <param name="metricsCalculator">The calculator to use for metric snapshots.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
/// <returns>A <see cref="CompactionResult"/> reporting the outcome.</returns>
internal async ValueTask<CompactionResult> CompactAsync(
List<ChatMessage> history,
IChatHistoryMetricsCalculator metricsCalculator,
CancellationToken cancellationToken = default)
{
Throw.IfNull(metricsCalculator);
Throw.IfNull(history);
ChatHistoryMetric beforeMetrics = CurrentMetrics;
if (!this.ShouldCompact(beforeMetrics))
{
// %%% VERBOSE - Debug.WriteLine($"COMPACTION: {this.Name} - Skipped");
return CompactionResult.Skipped(this.Name, beforeMetrics);
}
Debug.WriteLine($"COMPACTION: {this.Name} - Reducing");
IEnumerable<ChatMessage> reducerResult = await this.Reducer.ReduceAsync(history, cancellationToken).ConfigureAwait(false);
// Ensure we have a concrete collection to avoid multiple enumerations of the reducer result, which could be costly if it's an iterator.
ChatMessage[] reducedCopy = [.. reducerResult];
bool modified = reducedCopy.Length != history.Count;
if (modified)
{
history.Clear();
history.AddRange(reducedCopy);
}
ChatHistoryMetric afterMetrics = modified
? metricsCalculator.Calculate(reducedCopy)
: beforeMetrics;
Debug.WriteLine($"COMPACTION: {this.Name} - Tokens {beforeMetrics.TokenCount} => {afterMetrics.TokenCount}");
return new(this.Name, applied: modified, beforeMetrics, afterMetrics);
}
}
@@ -0,0 +1,45 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Immutable snapshot of conversation metrics used for compaction trigger evaluation and reporting.
/// </summary>
public sealed class ChatHistoryMetric
{
/// <summary>
/// Gets the estimated token count across all messages.
/// </summary>
public int TokenCount { get; init; }
/// <summary>
/// Gets the total serialized byte count of all messages.
/// </summary>
public long ByteCount { get; init; }
#pragma warning disable IDE0001 // Simplify Names
/// <summary>
/// Gets the total number of <see cref="Microsoft.Extensions.AI.ChatMessage"/> objects.
/// </summary>
#pragma warning restore IDE0001 // Simplify Names
public int MessageCount { get; init; }
/// <summary>
/// Gets the number of tool/function call content items across all messages.
/// </summary>
public int ToolCallCount { get; init; }
/// <summary>
/// Gets the number of user turns. A user turn is a user message together with the full
/// set of agent responses (including tool calls and results) before the next user input.
/// </summary>
public int UserTurnCount { get; init; }
/// <summary>
/// Gets the atomic message group index for the analyzed messages.
/// Each group represents a contiguous range of messages that must be kept or removed together.
/// </summary>
public IReadOnlyList<ChatMessageGroup> Groups { get; init; } = [];
}
@@ -0,0 +1,64 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Represents a contiguous range of messages in a conversation that form an atomic group.
/// Atomic groups must be kept or removed together to maintain API correctness.
/// </summary>
/// <remarks>
/// For example, an assistant message containing tool calls and the subsequent tool result messages
/// form an atomic group — removing one without the other causes API errors.
/// </remarks>
public readonly struct ChatMessageGroup : IEquatable<ChatMessageGroup>
{
/// <summary>
/// Initializes a new instance of the <see cref="ChatMessageGroup"/> struct.
/// </summary>
/// <param name="startIndex">The zero-based index of the first message in this group.</param>
/// <param name="count">The number of messages in this group.</param>
/// <param name="kind">The kind of this message group.</param>
public ChatMessageGroup(int startIndex, int count, ChatMessageGroupKind kind)
{
this.StartIndex = startIndex;
this.Count = count;
this.Kind = kind;
}
/// <summary>
/// Gets the zero-based index of the first message in this group within the original message list.
/// </summary>
public int StartIndex { get; }
/// <summary>
/// Gets the number of messages in this group.
/// </summary>
public int Count { get; }
/// <summary>
/// Gets the kind of this message group.
/// </summary>
public ChatMessageGroupKind Kind { get; }
/// <inheritdoc/>
public bool Equals(ChatMessageGroup other) =>
this.StartIndex == other.StartIndex &&
this.Count == other.Count &&
this.Kind == other.Kind;
/// <inheritdoc/>
public override bool Equals(object? obj) =>
obj is ChatMessageGroup other &&
this.Equals(other);
/// <inheritdoc/>
public override int GetHashCode() => HashCode.Combine(this.StartIndex, this.Count, (int)this.Kind);
/// <summary>Determines whether two <see cref="ChatMessageGroup"/> instances are equal.</summary>
public static bool operator ==(ChatMessageGroup left, ChatMessageGroup right) => left.Equals(right);
/// <summary>Determines whether two <see cref="ChatMessageGroup"/> instances are not equal.</summary>
public static bool operator !=(ChatMessageGroup left, ChatMessageGroup right) => !left.Equals(right);
}
@@ -0,0 +1,27 @@
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Identifies the kind of an atomic message group in a conversation.
/// </summary>
public enum ChatMessageGroupKind
{
/// <summary>A system message.</summary>
System,
/// <summary>A user message (start of a user turn).</summary>
UserTurn,
/// <summary>An assistant message with tool calls and their corresponding tool result messages.</summary>
AssistantToolGroup,
/// <summary>An assistant message without tool calls.</summary>
AssistantPlain,
/// <summary>A tool result message that is not part of a recognized group.</summary>
ToolResult,
/// <summary>A message with an unrecognized role.</summary>
Other
}
@@ -0,0 +1,35 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using Microsoft.Extensions.AI;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Represents a chat history compaction strategy that uses a condition function to determine when compaction should
/// occur.
/// </summary>
/// <remarks>
/// This strategy evaluates a user-provided condition against compaction metrics to decide whether to
/// compact the chat history. It is useful for scenarios where compaction should be triggered based on custom thresholds
/// or criteria. Inherits from ChatHistoryCompactionStrategy.
/// </remarks>
public class ChatReducerCompactionStrategy : ChatHistoryCompactionStrategy
{
private readonly Func<ChatHistoryMetric, bool> _condition;
/// <summary>
/// Initializes a new instance of the <see cref="ChatReducerCompactionStrategy"/> class.
/// </summary>
public ChatReducerCompactionStrategy(
IChatReducer reducer,
Func<ChatHistoryMetric, bool> condition)
: base(reducer)
{
this._condition = Throw.IfNull(condition);
}
/// <inheritdoc/>
protected override bool ShouldCompact(ChatHistoryMetric metrics) => this._condition(metrics);
}
@@ -0,0 +1,49 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Reports the aggregate outcome of a <see cref="ChatHistoryCompactionPipeline"/> execution.
/// </summary>
public sealed class CompactionPipelineResult
{
/// <summary>
/// Initializes a new instance of the <see cref="CompactionPipelineResult"/> class.
/// </summary>
/// <param name="before">Metrics of the conversation before any strategy ran.</param>
/// <param name="after">Metrics of the conversation after all strategies ran.</param>
/// <param name="strategyResults">Per-strategy results in execution order.</param>
internal CompactionPipelineResult(
ChatHistoryMetric before,
ChatHistoryMetric after,
IReadOnlyList<CompactionResult> strategyResults)
{
this.Before = Throw.IfNull(before);
this.After = Throw.IfNull(after);
this.StrategyResults = Throw.IfNull(strategyResults);
}
/// <summary>
/// Gets the conversation metrics before any compaction strategy ran.
/// </summary>
public ChatHistoryMetric Before { get; }
/// <summary>
/// Gets the conversation metrics after all compaction strategies ran.
/// </summary>
public ChatHistoryMetric After { get; }
/// <summary>
/// Gets the per-strategy results in execution order.
/// </summary>
public IReadOnlyList<CompactionResult> StrategyResults { get; }
/// <summary>
/// Gets a value indicating whether any strategy modified the message list.
/// </summary>
public bool AnyApplied => this.StrategyResults.Any(r => r.Applied);
}
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Reports the outcome of a single <see cref="ChatHistoryCompactionStrategy"/> execution.
/// </summary>
public sealed class CompactionResult
{
/// <summary>
/// Initializes a new instance of the <see cref="CompactionResult"/> class.
/// </summary>
/// <param name="strategyName">The name of the strategy that produced this result.</param>
/// <param name="applied">Whether the strategy modified the message list.</param>
/// <param name="before">Metrics before the strategy ran.</param>
/// <param name="after">Metrics after the strategy ran.</param>
public CompactionResult(string strategyName, bool applied, ChatHistoryMetric before, ChatHistoryMetric after)
{
this.StrategyName = Throw.IfNullOrWhitespace(strategyName);
this.Applied = applied;
this.Before = Throw.IfNull(before);
this.After = Throw.IfNull(after);
}
/// <summary>
/// Gets the name of the strategy that produced this result.
/// </summary>
public string StrategyName { get; }
/// <summary>
/// Gets a value indicating whether the strategy modified the message list.
/// </summary>
public bool Applied { get; }
/// <summary>
/// Gets the conversation metrics before the strategy executed.
/// </summary>
public ChatHistoryMetric Before { get; }
/// <summary>
/// Gets the conversation metrics after the strategy executed.
/// </summary>
public ChatHistoryMetric After { get; }
/// <summary>
/// Creates a <see cref="CompactionResult"/> representing a skipped strategy.
/// </summary>
/// <param name="strategyName">The name of the skipped strategy.</param>
/// <param name="metrics">The current conversation metrics.</param>
/// <returns>A result indicating no compaction was applied.</returns>
internal static CompactionResult Skipped(string strategyName, ChatHistoryMetric metrics)
=> new(strategyName, applied: false, metrics, metrics);
}
@@ -0,0 +1,161 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Default implementation of <see cref="IChatHistoryMetricsCalculator"/> that uses
/// JSON serialization length heuristics for token and byte estimation.
/// </summary>
/// <remarks>
/// <para>
/// Token estimation uses a configurable characters-per-token ratio (default ~4) since
/// precise tokenization requires a model-specific tokenizer. For production workloads
/// requiring accurate token counts, implement <see cref="IChatHistoryMetricsCalculator"/>
/// with a model-appropriate tokenizer.
/// </para>
/// </remarks>
public sealed class DefaultChatHistoryMetricsCalculator : IChatHistoryMetricsCalculator
{
/// <summary>
/// Gets the singleton instance of the chat history metrics calculator.
/// </summary>
/// <remarks>
/// <see cref="DefaultChatHistoryMetricsCalculator"/> can be safety accessed by
/// concurrent threads.
/// </remarks>
public static readonly DefaultChatHistoryMetricsCalculator Instance = new();
private const int DefaultCharsPerToken = 4;
private const int PerMessageOverheadTokens = 4;
private readonly int _charsPerToken;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultChatHistoryMetricsCalculator"/> class.
/// </summary>
/// <param name="charsPerToken">
/// The approximate number of characters per token used for estimation. Default is 4.
/// </param>
public DefaultChatHistoryMetricsCalculator(int charsPerToken = DefaultCharsPerToken)
{
this._charsPerToken = charsPerToken > 0 ? charsPerToken : DefaultCharsPerToken;
}
/// <inheritdoc/>
public ChatHistoryMetric Calculate(IReadOnlyList<ChatMessage> messages)
{
if (messages is null || messages.Count == 0)
{
return new();
}
int totalTokens = 0;
long totalBytes = 0;
int toolCallCount = 0;
int userTurnCount = 0;
bool inUserTurn = false;
List<ChatMessageGroup> groups = [];
int index = 0;
while (index < messages.Count)
{
ChatMessage message = messages[index];
// Accumulate per-message metrics
this.AccumulateMessageMetrics(message, ref totalTokens, ref totalBytes, ref toolCallCount);
if (message.Role == ChatRole.User)
{
if (!inUserTurn)
{
userTurnCount++;
inUserTurn = true;
}
}
else
{
inUserTurn = false;
}
// Identify the group starting at this message
if (message.Role == ChatRole.System)
{
groups.Add(new(index, 1, ChatMessageGroupKind.System));
index++;
}
else if (message.Role == ChatRole.User)
{
groups.Add(new(index, 1, ChatMessageGroupKind.UserTurn));
index++;
}
else if (message.Role == ChatRole.Assistant)
{
bool hasToolCalls = message.Contents!.Any(c => c is FunctionCallContent);
if (hasToolCalls)
{
int groupStart = index;
index++;
while (index < messages.Count && messages[index].Role == ChatRole.Tool)
{
this.AccumulateMessageMetrics(messages[index], ref totalTokens, ref totalBytes, ref toolCallCount);
inUserTurn = false;
index++;
}
groups.Add(new(groupStart, index - groupStart, ChatMessageGroupKind.AssistantToolGroup));
}
else
{
groups.Add(new(index, 1, ChatMessageGroupKind.AssistantPlain));
index++;
}
}
else if (message.Role == ChatRole.Tool)
{
groups.Add(new(index, 1, ChatMessageGroupKind.ToolResult));
index++;
}
else
{
groups.Add(new(index, 1, ChatMessageGroupKind.Other));
index++;
}
}
return new()
{
TokenCount = totalTokens,
ByteCount = totalBytes,
MessageCount = messages.Count,
ToolCallCount = toolCallCount,
UserTurnCount = userTurnCount,
Groups = groups
};
}
private void AccumulateMessageMetrics(ChatMessage message, ref int totalTokens, ref long totalBytes, ref int toolCallCount)
{
string serialized = message.Text;
int charCount = serialized.Length;
totalBytes += System.Text.Encoding.UTF8.GetByteCount(serialized);
totalTokens += (charCount / this._charsPerToken) + PerMessageOverheadTokens;
if (message.Contents is not null)
{
foreach (AIContent content in message.Contents)
{
if (content is FunctionCallContent)
{
toolCallCount++;
}
}
}
}
}
@@ -0,0 +1,26 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
// %%% TODO: Is this interface needed? Consider whether the default implementation is sufficient
// and whether custom metrics calculators are a realistic extension point.
/// <summary>
/// Computes <see cref="ChatHistoryMetric"/> for a list of messages.
/// </summary>
/// <remarks>
/// Token counting is model-specific. Implementations can provide precise tokenization
/// (e.g., using tiktoken or a model-specific tokenizer) or use estimation heuristics.
/// </remarks>
public interface IChatHistoryMetricsCalculator
{
/// <summary>
/// Compute metrics for the given messages.
/// </summary>
/// <param name="messages">The messages to analyze.</param>
/// <returns>A <see cref="ChatHistoryMetric"/> snapshot.</returns>
ChatHistoryMetric Calculate(IReadOnlyList<ChatMessage> messages);
}
@@ -0,0 +1,91 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// A compaction strategy that keeps only the most recent user turns and their
/// associated response groups, removing older turns to bound conversation length.
/// </summary>
/// <remarks>
/// <para>
/// This strategy always preserves system messages. It identifies user turns in the
/// conversation and keeps the last <c>maxTurns</c> turns along with all response groups
/// (assistant replies, tool call groups) that follow each kept turn.
/// </para>
/// <para>
/// The trigger condition fires only when the number of user turns exceeds <c>maxTurns</c>.
/// </para>
/// <para>
/// This strategy is more predictable than token-based truncation for bounding conversation
/// length, since it operates on logical turn boundaries rather than estimated token counts.
/// </para>
/// </remarks>
public class SlidingWindowCompactionStrategy : ChatHistoryCompactionStrategy
{
private readonly int _maxTurns;
/// <summary>
/// Initializes a new instance of the <see cref="SlidingWindowCompactionStrategy"/> class.
/// </summary>
/// <param name="maxTurns">
/// The maximum number of user turns to keep. Older turns and their associated responses are removed.
/// </param>
public SlidingWindowCompactionStrategy(int maxTurns)
: base(new SlidingWindowReducer(maxTurns))
{
this._maxTurns = maxTurns;
}
/// <inheritdoc/>
protected override bool ShouldCompact(ChatHistoryMetric metrics) =>
metrics.UserTurnCount > this._maxTurns;
/// <summary>
/// An <see cref="IChatReducer"/> that keeps system messages and the last N user turns
/// with all their associated response groups.
/// </summary>
private sealed class SlidingWindowReducer(int maxTurns) : IChatReducer
{
public Task<IEnumerable<ChatMessage>> ReduceAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
IReadOnlyList<ChatMessage> messageList = [.. messages]; // %%% PERFORMANCE
IReadOnlyList<ChatMessageGroup> groups = CurrentMetrics.Groups;
// Find the group-list indices where each user turn starts
int[] turnGroupIndices =
[.. CurrentMetrics.Groups
.Select((group, index) => (group, index))
.Where(t => t.group.Kind == ChatMessageGroupKind.UserTurn)
.Select(t => t.index)];
// Keep the last maxTurns user turns and everything after the first kept turn
int firstKeptTurnIndex = turnGroupIndices.Length - maxTurns;
int firstKeptGroupIndex = turnGroupIndices[firstKeptTurnIndex];
List<ChatMessage> result = new(messageList.Count); // %%% PERFORMANCE
for (int gi = 0; gi < groups.Count; gi++)
{
ChatMessageGroup group = groups[gi];
// Always keep system messages; keep groups at or after the window start
if (group.Kind == ChatMessageGroupKind.System || gi >= firstKeptGroupIndex)
{
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
result.Add(messageList[j]);
}
}
}
return Task.FromResult<IEnumerable<ChatMessage>>(result);
}
}
}
@@ -0,0 +1,166 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// A compaction strategy that uses an LLM to summarize older portions of the conversation,
/// replacing them with a concise summary message that preserves key facts and context.
/// </summary>
/// <remarks>
/// <para>
/// This strategy sits between tool-result clearing (gentle) and truncation (aggressive) in the
/// compaction ladder. Unlike truncation which discards messages entirely, summarization preserves
/// the essential information in compressed form, allowing the agent to maintain awareness of
/// earlier context.
/// </para>
/// <para>
/// The strategy protects system messages and the most recent <c>preserveRecentGroups</c>
/// non-system groups. All older groups are collected and sent to the <see cref="IChatClient"/>
/// for summarization. The resulting summary replaces those messages as a single assistant message.
/// </para>
/// </remarks>
public class SummarizationCompactionStrategy : ChatHistoryCompactionStrategy
{
private readonly int _maxTokens;
/// <summary>
/// The default summarization prompt used when none is provided.
/// </summary>
public const string DefaultSummarizationPrompt =
"""
You are a conversation summarizer. Produce a concise summary of the conversation that preserves:
- Key facts, decisions, and user preferences
- Important context needed for future turns
- Tool call outcomes and their significance
Omit pleasantries and redundant exchanges. Be factual and brief.
""";
/// <summary>
/// Initializes a new instance of the <see cref="SummarizationCompactionStrategy"/> class.
/// </summary>
/// <param name="chatClient">The <see cref="IChatClient"/> to use for generating summaries. A smaller, faster model is recommended.</param>
/// <param name="maxTokens">The maximum token budget. Summarization is triggered when the token count exceeds this value.</param>
/// <param name="preserveRecentGroups">
/// The number of most-recent non-system message groups to protect from summarization.
/// Defaults to 4, preserving the current and recent exchanges.
/// </param>
/// <param name="summarizationPrompt">
/// An optional custom system prompt for the summarization LLM call. When <see langword="null"/>,
/// a default prompt that emphasizes fact-preservation is used.
/// </param>
public SummarizationCompactionStrategy(
IChatClient chatClient,
int maxTokens,
int preserveRecentGroups = 4,
string? summarizationPrompt = null)
: base(new SummarizationReducer(chatClient, preserveRecentGroups, summarizationPrompt ?? DefaultSummarizationPrompt))
{
this._maxTokens = maxTokens;
}
/// <inheritdoc/>
protected override bool ShouldCompact(ChatHistoryMetric metrics) =>
metrics.TokenCount > this._maxTokens;
/// <summary>
/// An <see cref="IChatReducer"/> that sends older message groups to an LLM for summarization,
/// then replaces them with a single summary message.
/// </summary>
private sealed class SummarizationReducer : IChatReducer
{
private readonly IChatClient _chatClient;
private readonly int _preserveRecentGroups;
private readonly string _summarizationPrompt;
public SummarizationReducer(IChatClient chatClient, int preserveRecentGroups, string summarizationPrompt)
{
this._chatClient = Throw.IfNull(chatClient);
this._preserveRecentGroups = preserveRecentGroups;
this._summarizationPrompt = Throw.IfNullOrEmpty(summarizationPrompt);
}
public async Task<IEnumerable<ChatMessage>> ReduceAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
IReadOnlyList<ChatMessage> messageList = [.. messages];
IReadOnlyList<ChatMessageGroup> groups = CurrentMetrics.Groups;
List<ChatMessageGroup> nonSystemGroups = [.. groups.Where(g => g.Kind != ChatMessageGroupKind.System)];
int protectedFromIndex = Math.Max(0, nonSystemGroups.Count - this._preserveRecentGroups);
if (protectedFromIndex == 0)
{
// Nothing to summarize — all groups are protected
return messageList;
}
// Collect messages from groups that will be summarized
List<ChatMessage> toSummarize = [];
for (int i = 0; i < protectedFromIndex; i++)
{
ChatMessageGroup group = nonSystemGroups[i];
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
toSummarize.Add(messageList[j]);
}
}
if (toSummarize.Count == 0)
{
return messageList;
}
// Build the summarization request
List<ChatMessage> summarizationRequest =
[
new(ChatRole.System, this._summarizationPrompt),
.. toSummarize,
new(ChatRole.User, "Summarize the conversation above concisely."),
];
ChatResponse response = await this._chatClient.GetResponseAsync(summarizationRequest, cancellationToken: cancellationToken).ConfigureAwait(false);
string summaryText = string.IsNullOrWhiteSpace(response.Text) ? "[Summary unavailable]" : response.Text;
// Build result: system groups + summary + protected groups
List<ChatMessage> result = [];
// Keep system messages
foreach (ChatMessageGroup group in groups)
{
if (group.Kind == ChatMessageGroupKind.System)
{
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
result.Add(messageList[j]);
}
}
}
// Insert summary
result.Add(new ChatMessage(ChatRole.Assistant, $"[Summary]\n{summaryText}"));
// Keep protected groups
for (int i = protectedFromIndex; i < nonSystemGroups.Count; i++)
{
ChatMessageGroup group = nonSystemGroups[i];
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
result.Add(messageList[j]);
}
}
return result;
}
}
}
@@ -0,0 +1,118 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// A compaction strategy that collapses old assistant-tool-call groups into single
/// concise assistant messages, removing the detailed tool results while preserving
/// a record of which tools were called.
/// </summary>
/// <remarks>
/// <para>
/// This is the gentlest compaction strategy — it does not remove any user messages or
/// plain assistant responses. It only targets <see cref="ChatMessageGroupKind.AssistantToolGroup"/>
/// entries outside the protected recent window, replacing each multi-message group
/// (assistant call + tool results) with a single assistant message like
/// <c>[Tool calls: get_weather, search_docs]</c>.
/// </para>
/// <para>
/// The trigger condition fires only when token count exceeds <c>maxTokens</c> and
/// there is at least one tool call in the conversation.
/// </para>
/// </remarks>
public class ToolResultCompactionStrategy : ChatHistoryCompactionStrategy
{
/// <summary>
/// The default value for `preserveRecentGroups` used when constructing <see cref="ToolResultCompactionStrategy"/>.
/// </summary>
public const int DefaultPreserveRecentGroups = 2;
private readonly int _maxTokens;
/// <summary>
/// Initializes a new instance of the <see cref="ToolResultCompactionStrategy"/> class.
/// </summary>
/// <param name="maxTokens">The maximum token budget. Tool groups are collapsed when the token count exceeds this value.</param>
/// <param name="preserveRecentGroups">
/// The number of most-recent non-system message groups to protect from collapsing.
/// Defaults to 2, ensuring the current turn's tool interactions remain visible.
/// </param>
public ToolResultCompactionStrategy(int maxTokens, int preserveRecentGroups = DefaultPreserveRecentGroups)
: base(new ToolResultClearingReducer(preserveRecentGroups))
{
this._maxTokens = maxTokens;
}
/// <inheritdoc/>
protected override bool ShouldCompact(ChatHistoryMetric metrics) =>
metrics.TokenCount > this._maxTokens && metrics.ToolCallCount > 0;
/// <summary>
/// An <see cref="IChatReducer"/> that collapses <see cref="ChatMessageGroupKind.AssistantToolGroup"/>
/// entries into single summary messages, preserving the most recent groups.
/// </summary>
private sealed class ToolResultClearingReducer(int preserveRecentGroups) : IChatReducer
{
public Task<IEnumerable<ChatMessage>> ReduceAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
IReadOnlyList<ChatMessage> messageList = [.. messages];
IReadOnlyList<ChatMessageGroup> groups = CurrentMetrics.Groups;
List<ChatMessageGroup> nonSystemGroups = [.. groups.Where(g => g.Kind != ChatMessageGroupKind.System)];
int protectedFromIndex = Math.Max(0, nonSystemGroups.Count - preserveRecentGroups);
HashSet<int> protectedGroupStarts = [];
for (int i = protectedFromIndex; i < nonSystemGroups.Count; i++)
{
protectedGroupStarts.Add(nonSystemGroups[i].StartIndex);
}
List<ChatMessage> result = new(messageList.Count);
bool anyCollapsed = false;
foreach (ChatMessageGroup group in groups)
{
if (group.Kind == ChatMessageGroupKind.AssistantToolGroup && !protectedGroupStarts.Contains(group.StartIndex))
{
// Collapse this tool group into a single summary message
List<string> toolNames = [];
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
if (messageList[j].Contents is not null)
{
foreach (AIContent content in messageList[j].Contents)
{
if (content is FunctionCallContent fcc)
{
toolNames.Add(fcc.Name);
}
}
}
}
string summary = $"[Tool calls: {string.Join(", ", toolNames)}]";
result.Add(new ChatMessage(ChatRole.Assistant, summary));
anyCollapsed = true;
}
else
{
// Keep this group as-is
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
result.Add(messageList[j]);
}
}
}
return Task.FromResult<IEnumerable<ChatMessage>>(anyCollapsed ? result : messageList);
}
}
}
@@ -0,0 +1,97 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// A compaction strategy that removes the oldest message groups until the estimated
/// token count is within a specified budget.
/// </summary>
/// <remarks>
/// <para>
/// This strategy preserves system messages and removes the oldest non-system message groups first.
/// It respects atomic group boundaries — an assistant message with tool calls and its
/// corresponding tool result messages are always removed together.
/// </para>
/// <para>
/// The trigger condition fires only when the current token count exceeds <c>maxTokens</c>.
/// </para>
/// </remarks>
public class TruncationCompactionStrategy : ChatHistoryCompactionStrategy
{
private readonly int _maxTokens;
/// <summary>
/// Initializes a new instance of the <see cref="TruncationCompactionStrategy"/> class.
/// </summary>
/// <param name="maxTokens">The maximum token budget. Groups are removed until the token count is at or below this value.</param>
/// <param name="preserveRecentGroups">
/// The minimum number of most-recent non-system message groups to keep.
/// Defaults to 1 so that at least the latest exchange is always preserved.
/// </param>
public TruncationCompactionStrategy(int maxTokens, int preserveRecentGroups = 1)
: base(new TruncationReducer(preserveRecentGroups))
{
this._maxTokens = maxTokens;
}
/// <inheritdoc/>
protected override bool ShouldCompact(ChatHistoryMetric metrics) =>
metrics.TokenCount > this._maxTokens;
/// <summary>
/// An <see cref="IChatReducer"/> that removes the oldest non-system message groups,
/// keeping at least the most recent group.
/// </summary>
private sealed class TruncationReducer(int preserveRecentGroups) : IChatReducer
{
public Task<IEnumerable<ChatMessage>> ReduceAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
IReadOnlyList<ChatMessage> messageList = [.. messages];
ChatMessageGroup[] removableGroups = [.. CurrentMetrics.Groups.Where(g => g.Kind != ChatMessageGroupKind.System)];
if (removableGroups.Length == 0)
{
return Task.FromResult<IEnumerable<ChatMessage>>(messageList);
}
// Remove oldest non-system groups, keeping at least preserveRecentGroups.
int maxRemovable = removableGroups.Length - preserveRecentGroups;
if (maxRemovable <= 0)
{
return Task.FromResult<IEnumerable<ChatMessage>>(messageList);
}
HashSet<int> removedGroupStarts = [];
for (int ri = 0; ri < maxRemovable; ri++)
{
removedGroupStarts.Add(removableGroups[ri].StartIndex);
}
List<ChatMessage> messagesToKeep = new(messageList.Count);
foreach (ChatMessageGroup group in CurrentMetrics.Groups)
{
if (removedGroupStarts.Contains(group.StartIndex))
{
continue;
}
for (int j = group.StartIndex; j < group.StartIndex + group.Count; j++)
{
messagesToKeep.Add(messageList[j]);
}
}
return Task.FromResult<IEnumerable<ChatMessage>>(messagesToKeep);
}
}
}
@@ -79,21 +79,20 @@ public sealed class InMemoryChatHistoryProvider : ChatHistoryProvider
/// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception>
public void SetMessages(AgentSession? session, List<ChatMessage> messages)
{
Throw.IfNull(messages);
_ = Throw.IfNull(messages);
State state = this._sessionState.GetOrInitializeState(session);
var state = this._sessionState.GetOrInitializeState(session);
state.Messages = messages;
}
/// <inheritdoc />
protected override async ValueTask<IEnumerable<ChatMessage>> ProvideChatHistoryAsync(InvokingContext context, CancellationToken cancellationToken = default)
{
State state = this._sessionState.GetOrInitializeState(context.Session);
var state = this._sessionState.GetOrInitializeState(context.Session);
if (this.ReducerTriggerEvent is InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.BeforeMessagesRetrieval && this.ChatReducer is not null)
{
// Apply pre-retrieval reduction if configured
await ReduceMessagesAsync(this.ChatReducer, state, cancellationToken).ConfigureAwait(false);
state.Messages = (await this.ChatReducer.ReduceAsync(state.Messages, cancellationToken).ConfigureAwait(false)).ToList();
}
return state.Messages;
@@ -102,7 +101,7 @@ public sealed class InMemoryChatHistoryProvider : ChatHistoryProvider
/// <inheritdoc />
protected override async ValueTask StoreChatHistoryAsync(InvokedContext context, CancellationToken cancellationToken = default)
{
State state = this._sessionState.GetOrInitializeState(context.Session);
var state = this._sessionState.GetOrInitializeState(context.Session);
// Add request and response messages to the provider
var allNewMessages = context.RequestMessages.Concat(context.ResponseMessages ?? []);
@@ -110,16 +109,10 @@ public sealed class InMemoryChatHistoryProvider : ChatHistoryProvider
if (this.ReducerTriggerEvent is InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.AfterMessageAdded && this.ChatReducer is not null)
{
// Apply pre-write reduction strategy if configured
await ReduceMessagesAsync(this.ChatReducer, state, cancellationToken).ConfigureAwait(false);
state.Messages = (await this.ChatReducer.ReduceAsync(state.Messages, cancellationToken).ConfigureAwait(false)).ToList();
}
}
private static async Task ReduceMessagesAsync(IChatReducer reducer, State state, CancellationToken cancellationToken = default)
{
state.Messages = [.. await reducer.ReduceAsync(state.Messages, cancellationToken).ConfigureAwait(false)];
}
/// <summary>
/// Represents the state of a <see cref="InMemoryChatHistoryProvider"/> stored in the <see cref="AgentSession.StateBag"/>.
/// </summary>
@@ -31,6 +31,10 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
<PackageReference Include="Microsoft.Bcl.HashCode" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.Agents.AI.Abstractions.UnitTests" />
</ItemGroup>
@@ -17,24 +17,6 @@ namespace Microsoft.Agents.AI;
/// <summary>
/// Provides a Cosmos DB implementation of the <see cref="ChatHistoryProvider"/> abstract class.
/// </summary>
/// <remarks>
/// <para>
/// <strong>Security considerations:</strong>
/// <list type="bullet">
/// <item><description><strong>PII and sensitive data:</strong> Chat history stored in Cosmos DB may contain PII, sensitive conversation
/// content, and system instructions. Ensure the Cosmos DB account is configured with appropriate access controls, encryption at rest,
/// and network security (e.g., private endpoints, virtual network rules). The <see cref="MessageTtlSeconds"/> property can be used to
/// automatically expire messages and limit data retention.</description></item>
/// <item><description><strong>Compromised store risks:</strong> Agent Framework does not validate or filter messages loaded from the
/// store — they are accepted as-is. If the Cosmos DB store is compromised, adversarial content could be injected into the conversation
/// context, potentially influencing LLM behavior via indirect prompt injection. Altered message roles (e.g., changing <c>user</c> to
/// <c>system</c>) could escalate trust levels.</description></item>
/// <item><description><strong>Authentication:</strong> Agent Framework does not manage authentication or encryption for the Cosmos DB
/// connection — these are the responsibility of the <see cref="CosmosClient"/> configuration. Use managed identity
/// or token-based authentication where possible, and avoid embedding connection strings with keys in source code.</description></item>
/// </list>
/// </para>
/// </remarks>
[RequiresUnreferencedCode("The CosmosChatHistoryProvider uses JSON serialization which is incompatible with trimming.")]
[RequiresDynamicCode("The CosmosChatHistoryProvider uses JSON serialization which is incompatible with NativeAOT.")]
public sealed class CosmosChatHistoryProvider : ChatHistoryProvider, IDisposable
@@ -13,6 +13,10 @@
</PropertyGroup>
<Import Project="$(RepoRoot)/dotnet/nuget/nuget-package.props" />
<PropertyGroup>
<!-- Disable packing until we are ready to release this as a nuget -->
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.Agents.AI.Abstractions\Microsoft.Agents.AI.Abstractions.csproj" />
@@ -72,7 +72,9 @@ internal static class AIAgentChatCompletionsProcessor
await foreach (var agentResponseUpdate in agent.RunStreamingAsync(chatMessages, options: options, cancellationToken: cancellationToken).WithCancellation(cancellationToken))
{
var finishReason = agentResponseUpdate.FinishReason?.ToString() ?? "stop";
var finishReason = (agentResponseUpdate.RawRepresentation is ChatResponseUpdate { FinishReason: not null } chatResponseUpdate)
? chatResponseUpdate.FinishReason.ToString()
: "stop";
var choiceChunks = new List<ChatCompletionChoiceChunk>();
CompletionUsage? usageDetails = null;
@@ -34,7 +34,9 @@ internal static class AgentResponseExtensions
var chatCompletionChoices = new List<ChatCompletionChoice>();
var index = 0;
var finishReason = agentResponse.FinishReason?.ToString() ?? ChatFinishReason.Stop.Value; // "stop" is a natural stop point; returning this by-default
var finishReason = (agentResponse.RawRepresentation is ChatResponse { FinishReason: not null } chatResponse)
? chatResponse.FinishReason.ToString()
: "stop"; // "stop" is a natural stop point; returning this by-default
foreach (var message in agentResponse.Messages)
{
@@ -19,10 +19,9 @@ public static class AgentHostingServiceCollectionExtensions
/// <param name="services">The service collection to configure.</param>
/// <param name="name">The name of the agent.</param>
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The same <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="services"/> or <paramref name="name"/> is <see langword="null"/>.</exception>
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions)
{
Throw.IfNull(services);
Throw.IfNullOrEmpty(name);
@@ -31,7 +30,7 @@ public static class AgentHostingServiceCollectionExtensions
var chatClient = sp.GetRequiredService<IChatClient>();
var tools = sp.GetKeyedServices<AITool>(name).ToList();
return new ChatClientAgent(chatClient, instructions, key, tools: tools);
}, lifetime);
});
}
/// <summary>
@@ -41,10 +40,9 @@ public static class AgentHostingServiceCollectionExtensions
/// <param name="name">The name of the agent.</param>
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="chatClient">The chat client which the agent will use for inference.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The same <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="services"/> or <paramref name="name"/> is <see langword="null"/>.</exception>
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, IChatClient chatClient, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, IChatClient chatClient)
{
Throw.IfNull(services);
Throw.IfNullOrEmpty(name);
@@ -52,7 +50,7 @@ public static class AgentHostingServiceCollectionExtensions
{
var tools = sp.GetKeyedServices<AITool>(name).ToList();
return new ChatClientAgent(chatClient, instructions, key, tools: tools);
}, lifetime);
});
}
/// <summary>
@@ -62,10 +60,9 @@ public static class AgentHostingServiceCollectionExtensions
/// <param name="name">The name of the agent.</param>
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="chatClientServiceKey">The key to use when resolving the chat client from the service provider. If <see langword="null"/>, a non-keyed service will be resolved.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The same <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="services"/> or <paramref name="name"/> is <see langword="null"/>.</exception>
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, object? chatClientServiceKey, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, object? chatClientServiceKey)
{
Throw.IfNull(services);
Throw.IfNullOrEmpty(name);
@@ -74,7 +71,7 @@ public static class AgentHostingServiceCollectionExtensions
var chatClient = chatClientServiceKey is null ? sp.GetRequiredService<IChatClient>() : sp.GetRequiredKeyedService<IChatClient>(chatClientServiceKey);
var tools = sp.GetKeyedServices<AITool>(name).ToList();
return new ChatClientAgent(chatClient, instructions, key, tools: tools);
}, lifetime);
});
}
/// <summary>
@@ -85,10 +82,9 @@ public static class AgentHostingServiceCollectionExtensions
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="description">A description of the agent.</param>
/// <param name="chatClientServiceKey">The key to use when resolving the chat client from the service provider. If <see langword="null"/>, a non-keyed service will be resolved.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The same <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="services"/> or <paramref name="name"/> is <see langword="null"/>.</exception>
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, string? description, object? chatClientServiceKey, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, string? instructions, string? description, object? chatClientServiceKey)
{
Throw.IfNull(services);
Throw.IfNullOrEmpty(name);
@@ -97,7 +93,7 @@ public static class AgentHostingServiceCollectionExtensions
var chatClient = chatClientServiceKey is null ? sp.GetRequiredService<IChatClient>() : sp.GetRequiredKeyedService<IChatClient>(chatClientServiceKey);
var tools = sp.GetKeyedServices<AITool>(name).ToList();
return new ChatClientAgent(chatClient, instructions: instructions, name: key, description: description, tools: tools);
}, lifetime);
});
}
/// <summary>
@@ -106,16 +102,15 @@ public static class AgentHostingServiceCollectionExtensions
/// <param name="services">The service collection to configure.</param>
/// <param name="name">The name of the agent.</param>
/// <param name="createAgentDelegate">A factory delegate that creates the AI agent instance. The delegate receives the service provider and agent key as parameters.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The same <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="services"/>, <paramref name="name"/>, or <paramref name="createAgentDelegate"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">Thrown when the agent factory delegate returns <see langword="null"/> or an agent whose <see cref="AIAgent.Name"/> does not match <paramref name="name"/>.</exception>
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, Func<IServiceProvider, string, AIAgent> createAgentDelegate, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IServiceCollection services, string name, Func<IServiceProvider, string, AIAgent> createAgentDelegate)
{
Throw.IfNull(services);
Throw.IfNull(name);
Throw.IfNull(createAgentDelegate);
services.AddKeyedService(name, (sp, key) =>
services.AddKeyedSingleton(name, (sp, key) =>
{
Throw.IfNull(key);
var keyString = key as string;
@@ -127,18 +122,8 @@ public static class AgentHostingServiceCollectionExtensions
}
return agent;
}, lifetime);
});
return new HostedAgentBuilder(name, services, lifetime);
}
/// <summary>
/// Registers a keyed service with the specified lifetime.
/// </summary>
internal static void AddKeyedService<T>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, T> factory, ServiceLifetime lifetime)
where T : class
{
var descriptor = new ServiceDescriptor(typeof(T), serviceKey, (sp, key) => factory(sp, key), lifetime);
services.Add(descriptor);
return new HostedAgentBuilder(name, services);
}
}
@@ -2,7 +2,6 @@
using System;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Shared.Diagnostics;
@@ -19,13 +18,12 @@ public static class HostApplicationBuilderAgentExtensions
/// <param name="builder">The host application builder to configure.</param>
/// <param name="name">The name of the agent.</param>
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The configured host application builder.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="name"/>, or <paramref name="instructions"/> is null.</exception>
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions)
{
Throw.IfNull(builder);
return builder.Services.AddAIAgent(name, instructions, lifetime);
return builder.Services.AddAIAgent(name, instructions);
}
/// <summary>
@@ -35,14 +33,13 @@ public static class HostApplicationBuilderAgentExtensions
/// <param name="name">The name of the agent.</param>
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="chatClient">The chat client which the agent will use for inference.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The configured host application builder.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="name"/>, or <paramref name="instructions"/> is null.</exception>
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, IChatClient chatClient, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, IChatClient chatClient)
{
Throw.IfNull(builder);
Throw.IfNullOrEmpty(name);
return builder.Services.AddAIAgent(name, instructions, chatClient, lifetime);
return builder.Services.AddAIAgent(name, instructions, chatClient);
}
/// <summary>
@@ -53,14 +50,13 @@ public static class HostApplicationBuilderAgentExtensions
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="description">A description of the agent.</param>
/// <param name="chatClientServiceKey">The key to use when resolving the chat client from the service provider. If null, a non-keyed service will be resolved.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The configured host application builder.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="name"/>, or <paramref name="instructions"/> is null.</exception>
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, string? description, object? chatClientServiceKey, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, string? description, object? chatClientServiceKey)
{
Throw.IfNull(builder);
Throw.IfNullOrEmpty(name);
return builder.Services.AddAIAgent(name, instructions, description, chatClientServiceKey, lifetime);
return builder.Services.AddAIAgent(name, instructions, description, chatClientServiceKey);
}
/// <summary>
@@ -70,13 +66,12 @@ public static class HostApplicationBuilderAgentExtensions
/// <param name="name">The name of the agent.</param>
/// <param name="instructions">The instructions for the agent.</param>
/// <param name="chatClientServiceKey">The key to use when resolving the chat client from the service provider. If null, a non-keyed service will be resolved.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The configured host application builder.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="name"/>, or <paramref name="instructions"/> is null.</exception>
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, object? chatClientServiceKey, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string? instructions, object? chatClientServiceKey)
{
Throw.IfNull(builder);
return builder.Services.AddAIAgent(name, instructions, chatClientServiceKey, lifetime);
return builder.Services.AddAIAgent(name, instructions, chatClientServiceKey);
}
/// <summary>
@@ -85,13 +80,12 @@ public static class HostApplicationBuilderAgentExtensions
/// <param name="builder">The host application builder to configure.</param>
/// <param name="name">The name of the agent.</param>
/// <param name="createAgentDelegate">A factory delegate that creates the AI agent instance. The delegate receives the service provider and agent key as parameters.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>The configured host application builder.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="name"/>, or <paramref name="createAgentDelegate"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown when the agent factory delegate returns null or an invalid AI agent instance.</exception>
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, Func<IServiceProvider, string, AIAgent> createAgentDelegate, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, Func<IServiceProvider, string, AIAgent> createAgentDelegate)
{
Throw.IfNull(builder);
return builder.Services.AddAIAgent(name, createAgentDelegate, lifetime);
return builder.Services.AddAIAgent(name, createAgentDelegate);
}
}
@@ -19,20 +19,19 @@ public static class HostApplicationBuilderWorkflowExtensions
/// <param name="builder">The <see cref="IHostApplicationBuilder"/> to configure.</param>
/// <param name="name">The unique name for the workflow.</param>
/// <param name="createWorkflowDelegate">A factory function that creates the <see cref="Workflow"/> instance. The function receives the service provider and workflow name as parameters.</param>
/// <param name="lifetime">The DI service lifetime for the workflow registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>An <see cref="IHostedWorkflowBuilder"/> that can be used to further configure the workflow.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="name"/>, or <paramref name="createWorkflowDelegate"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="name"/> is empty.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the factory delegate returns null or a workflow with a name that doesn't match the expected name.
/// </exception>
public static IHostedWorkflowBuilder AddWorkflow(this IHostApplicationBuilder builder, string name, Func<IServiceProvider, string, Workflow> createWorkflowDelegate, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedWorkflowBuilder AddWorkflow(this IHostApplicationBuilder builder, string name, Func<IServiceProvider, string, Workflow> createWorkflowDelegate)
{
Throw.IfNull(builder);
Throw.IfNull(name);
Throw.IfNull(createWorkflowDelegate);
builder.Services.AddKeyedService(name, (sp, key) =>
builder.Services.AddKeyedSingleton(name, (sp, key) =>
{
Throw.IfNull(key);
var keyString = key as string;
@@ -44,7 +43,7 @@ public static class HostApplicationBuilderWorkflowExtensions
}
return workflow;
}, lifetime);
});
return new HostedWorkflowBuilder(name, builder);
}
@@ -9,17 +9,15 @@ internal sealed class HostedAgentBuilder : IHostedAgentBuilder
{
public string Name { get; }
public IServiceCollection ServiceCollection { get; }
public ServiceLifetime Lifetime { get; }
public HostedAgentBuilder(string name, IHostApplicationBuilder builder, ServiceLifetime lifetime = ServiceLifetime.Singleton)
: this(name, builder.Services, lifetime)
public HostedAgentBuilder(string name, IHostApplicationBuilder builder)
: this(name, builder.Services)
{
}
public HostedAgentBuilder(string name, IServiceCollection serviceCollection, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public HostedAgentBuilder(string name, IServiceCollection serviceCollection)
{
this.Name = name;
this.ServiceCollection = serviceCollection;
this.Lifetime = lifetime;
}
}
@@ -42,19 +42,17 @@ public static class HostedAgentBuilderExtensions
/// <param name="builder">The host agent builder to configure.</param>
/// <param name="createAgentSessionStore">A factory function that creates an agent session store instance using the provided service provider and agent
/// name.</param>
/// <param name="lifetime">The DI service lifetime for the session store registration. Defaults to <see cref="ServiceLifetime.Singleton"/>
/// because session stores persist conversation state across requests and are consumed independently of the agent's lifetime.</param>
/// <returns>The same host agent builder instance, enabling further configuration.</returns>
public static IHostedAgentBuilder WithSessionStore(this IHostedAgentBuilder builder, Func<IServiceProvider, string, AgentSessionStore> createAgentSessionStore, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder WithSessionStore(this IHostedAgentBuilder builder, Func<IServiceProvider, string, AgentSessionStore> createAgentSessionStore)
{
builder.ServiceCollection.AddKeyedService(builder.Name, (sp, key) =>
builder.ServiceCollection.AddKeyedSingleton(builder.Name, (sp, key) =>
{
Throw.IfNull(key);
var keyString = key as string;
Throw.IfNullOrEmpty(keyString);
return createAgentSessionStore(sp, keyString) ??
throw new InvalidOperationException($"The agent session store factory did not return a valid {nameof(AgentSessionStore)} instance for key '{keyString}'.");
}, lifetime);
});
return builder;
}
@@ -100,39 +98,13 @@ public static class HostedAgentBuilderExtensions
/// </summary>
/// <param name="builder">The hosted agent builder.</param>
/// <param name="factory">A factory function that creates a AI tool using the provided service provider.</param>
/// <param name="lifetime">The DI service lifetime for the tool registration. If <see langword="null"/>, the agent's lifetime is used.</param>
/// <returns>The same <see cref="IHostedAgentBuilder"/> instance so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="factory"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the effective tool lifetime is shorter than the agent's lifetime, which would cause a captive dependency.
/// For example, a singleton agent cannot use scoped or transient tools.
/// </exception>
public static IHostedAgentBuilder WithAITool(this IHostedAgentBuilder builder, Func<IServiceProvider, AITool> factory, ServiceLifetime? lifetime = null)
public static IHostedAgentBuilder WithAITool(this IHostedAgentBuilder builder, Func<IServiceProvider, AITool> factory)
{
Throw.IfNull(builder);
Throw.IfNull(factory);
var effectiveLifetime = lifetime ?? builder.Lifetime;
ValidateToolLifetime(builder.Lifetime, effectiveLifetime);
builder.ServiceCollection.AddKeyedService(builder.Name, (sp, name) => factory(sp), effectiveLifetime);
builder.ServiceCollection.AddKeyedSingleton(builder.Name, (sp, name) => factory(sp));
return builder;
}
/// <summary>
/// Validates that the tool lifetime is compatible with the agent lifetime.
/// A tool's lifetime must be at least as long as the agent's lifetime to prevent captive dependency issues.
/// </summary>
internal static void ValidateToolLifetime(ServiceLifetime agentLifetime, ServiceLifetime toolLifetime)
{
// ServiceLifetime enum: Singleton=0, Scoped=1, Transient=2
// A higher value means a shorter lifetime.
if (toolLifetime > agentLifetime)
{
throw new InvalidOperationException(
$"A tool with lifetime '{toolLifetime}' cannot be registered for an agent with lifetime '{agentLifetime}'. " +
"The tool's lifetime must be at least as long as the agent's lifetime to avoid captive dependency issues.");
}
}
}
@@ -14,24 +14,22 @@ public static class HostedWorkflowBuilderExtensions
/// Registers the workflow as an AI agent in the dependency injection container.
/// </summary>
/// <param name="builder">The <see cref="IHostedWorkflowBuilder"/> instance to extend.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>An <see cref="IHostedAgentBuilder"/> that can be used to further configure the agent.</returns>
public static IHostedAgentBuilder AddAsAIAgent(this IHostedWorkflowBuilder builder, ServiceLifetime lifetime = ServiceLifetime.Singleton)
=> builder.AddAsAIAgent(name: null, lifetime: lifetime);
public static IHostedAgentBuilder AddAsAIAgent(this IHostedWorkflowBuilder builder)
=> builder.AddAsAIAgent(name: null);
/// <summary>
/// Registers the workflow as an AI agent in the dependency injection container.
/// </summary>
/// <param name="builder">The <see cref="IHostedWorkflowBuilder"/> instance to extend.</param>
/// <param name="name">The optional name for the AI agent. If not specified, the workflow name is used.</param>
/// <param name="lifetime">The DI service lifetime for the agent registration. Defaults to <see cref="ServiceLifetime.Singleton"/>.</param>
/// <returns>An <see cref="IHostedAgentBuilder"/> that can be used to further configure the agent.</returns>
public static IHostedAgentBuilder AddAsAIAgent(this IHostedWorkflowBuilder builder, string? name, ServiceLifetime lifetime = ServiceLifetime.Singleton)
public static IHostedAgentBuilder AddAsAIAgent(this IHostedWorkflowBuilder builder, string? name)
{
var workflowName = builder.Name;
var agentName = name ?? workflowName;
return builder.HostApplicationBuilder.AddAIAgent(agentName, (sp, key) =>
sp.GetRequiredKeyedService<Workflow>(workflowName).AsAIAgent(name: key), lifetime);
sp.GetRequiredKeyedService<Workflow>(workflowName).AsAIAgent(name: key));
}
}
@@ -18,9 +18,4 @@ public interface IHostedAgentBuilder
/// Gets the service collection for configuration.
/// </summary>
IServiceCollection ServiceCollection { get; }
/// <summary>
/// Gets the DI service lifetime used for the agent registration.
/// </summary>
ServiceLifetime Lifetime { get; }
}
@@ -13,38 +13,16 @@ using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Mem0;
#pragma warning disable IDE0001 // Simplify Names - Microsoft.Extensions.Logging.LogLevel.Trace doesn't get found in net472 when removing the namespace.
/// <summary>
/// Provides a Mem0 backed <see cref="MessageAIContextProvider"/> that persists conversation messages as memories
/// and retrieves related memories to augment the agent invocation context.
/// </summary>
/// <remarks>
/// <para>
/// The provider stores user, assistant and system messages as Mem0 memories and retrieves relevant memories
/// for new invocations using a semantic search endpoint. Retrieved memories are injected as user messages
/// to the model, prefixed by a configurable context prompt.
/// </para>
/// <para>
/// <strong>Security considerations:</strong>
/// <list type="bullet">
/// <item><description><strong>External service trust:</strong> This provider communicates with an external Mem0 service over HTTP.
/// Agent Framework does not manage authentication, encryption, or connection details for this service — these are the responsibility
/// of the <see cref="HttpClient"/> configuration. Ensure the HTTP client is configured with appropriate authentication
/// and uses HTTPS to protect data in transit.</description></item>
/// <item><description><strong>PII and sensitive data:</strong> Conversation messages (including user inputs, LLM responses, and system
/// instructions) are sent to the external Mem0 service for storage. These messages may contain PII or sensitive information.
/// Ensure the Mem0 service is configured with appropriate data retention policies and access controls.</description></item>
/// <item><description><strong>Indirect prompt injection:</strong> Memories retrieved from the Mem0 service are injected into the LLM
/// context as user messages. If the memory store is compromised, adversarial content could influence LLM behavior. The data
/// returned from the service is accepted as-is without validation or sanitization.</description></item>
/// <item><description><strong>Trace logging:</strong> When <see cref="Microsoft.Extensions.Logging.LogLevel.Trace"/> is enabled,
/// full memory content (including search queries and results) may be logged. This data may contain PII and should not be enabled
/// in production environments.</description></item>
/// </list>
/// </para>
/// </remarks>
public sealed class Mem0Provider : MessageAIContextProvider
#pragma warning restore IDE0001 // Simplify Names
{
private const string DefaultContextPrompt = "## Memories\nConsider the following memories when answering user questions:";
@@ -3,7 +3,6 @@
#pragma warning disable CS0618 // Type or member is obsolete - Internal use of obsolete types for backward compatibility
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
@@ -134,25 +133,7 @@ internal sealed class ExecutorProtocol(MessageRouter router, ISet<Type> sendType
public bool CanHandle(Type type) => router.CanHandle(type);
private readonly ConcurrentDictionary<Type, bool> _canOutputCache = new();
public bool CanOutput(Type type)
{
return this._canOutputCache.GetOrAdd(type, this.CanOutputCore);
}
private bool CanOutputCore(Type type)
{
foreach (TypeId yieldType in this._yieldTypes)
{
if (yieldType.IsMatchPolymorphic(type))
{
return true;
}
}
return false;
}
public bool CanOutput(Type type) => this._yieldTypes.Contains(new(type));
public ProtocolDescriptor Describe() => new(this.Router.IncomingTypes, yieldTypes, sendTypes, this.Router.HasCatchAll);
}
@@ -124,7 +124,6 @@ internal sealed class MessageMerger
List<ChatMessage> messages = [];
Dictionary<string, AgentResponse> responses = [];
HashSet<string> agentIds = [];
HashSet<ChatFinishReason> finishReasons = [];
foreach (string responseId in this._mergeStates.Keys)
{
@@ -157,11 +156,6 @@ internal sealed class MessageMerger
createdTimes.Add(response.CreatedAt.Value);
}
if (response.FinishReason.HasValue)
{
finishReasons.Add(response.FinishReason.Value);
}
usage = MergeUsage(usage, response.Usage);
additionalProperties = MergeProperties(additionalProperties, response.AdditionalProperties);
}
@@ -188,7 +182,6 @@ internal sealed class MessageMerger
AgentId = primaryAgentId
?? primaryAgentName
?? (agentIds.Count == 1 ? agentIds.First() : null),
FinishReason = finishReasons.Count == 1 ? finishReasons.First() : null,
CreatedAt = DateTimeOffset.UtcNow,
Usage = usage,
AdditionalProperties = additionalProperties
@@ -214,7 +207,6 @@ internal sealed class MessageMerger
AgentId = incoming.AgentId ?? current.AgentId,
AdditionalProperties = MergeProperties(current.AdditionalProperties, incoming.AdditionalProperties),
CreatedAt = incoming.CreatedAt ?? current.CreatedAt,
FinishReason = incoming.FinishReason ?? current.FinishReason,
Messages = current.Messages.Concat(incoming.Messages).ToList(),
ResponseId = current.ResponseId,
RawRepresentation = rawRepresentation,
@@ -17,25 +17,6 @@ namespace Microsoft.Agents.AI;
/// <summary>
/// Provides an <see cref="AIAgent"/> that delegates to an <see cref="IChatClient"/> implementation.
/// </summary>
/// <remarks>
/// <para>
/// <strong>Security considerations:</strong> The <see cref="ChatClientAgent"/> orchestrates data flow across trust boundaries.
/// The underlying AI service is an external endpoint and LLM responses should be treated as untrusted output. Developers should be aware of:
/// <list type="bullet">
/// <item><description><strong>Hallucination:</strong> LLMs may generate plausible-sounding but factually incorrect information.
/// Do not treat LLM output as authoritative without verification.</description></item>
/// <item><description><strong>Indirect prompt injection:</strong> Data retrieved by tools, AI context providers, or chat history providers may
/// contain adversarial content designed to influence LLM behavior or exfiltrate data through tool calls.</description></item>
/// <item><description><strong>Malicious payloads:</strong> LLM output may contain content that is harmful if rendered or executed without
/// sanitization — for example, HTML/JavaScript for cross-site scripting, SQL for injection, or shell commands.</description></item>
/// <item><description><strong>Tool invocation:</strong> By default, all tools provided to the agent are invoked without user approval.
/// The AI selects which functions to call and with what arguments. Function arguments should be treated as untrusted input.
/// Developers should require explicit approval for tools with side effects, data sensitivity, or irreversibility.</description></item>
/// </list>
/// Developers should validate and sanitize LLM output before rendering it in HTML, executing it as code, using it in database queries,
/// or passing it to any security-sensitive context. Apply defense-in-depth by combining tool approval requirements with output validation.
/// </para>
/// </remarks>
public sealed partial class ChatClientAgent : AIAgent
{
private readonly ChatClientAgentOptions? _agentOptions;
@@ -63,9 +44,6 @@ public sealed partial class ChatClientAgent : AIAgent
/// Optional collection of tools that the agent can invoke during conversations.
/// These tools augment any tools that may be provided to the agent via <see cref="ChatOptions.Tools"/> when
/// the agent is run.
/// By default, all provided tools are invoked without user approval. The AI selects which functions to call and chooses
/// the arguments — these arguments should be treated as untrusted input. Developers should require explicit approval
/// for tools that have side effects, access sensitive data, or perform irreversible operations.
/// </param>
/// <param name="loggerFactory">
/// Optional logger factory for creating loggers used by the agent and its components.
@@ -55,7 +55,7 @@ public static class ChatClientExtensions
if (chatClient.GetService<FunctionInvokingChatClient>() is null)
{
chatBuilder.Use((innerClient, services) =>
_ = chatBuilder.Use((innerClient, services) =>
{
var loggerFactory = services.GetService<ILoggerFactory>();
@@ -1,159 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Content-based equality comparison for <see cref="ChatMessage"/> instances.
/// </summary>
internal static class ChatMessageContentEquality
{
/// <summary>
/// Determines whether two <see cref="ChatMessage"/> instances represent the same message by content.
/// </summary>
/// <remarks>
/// When both messages define a <see cref="ChatMessage.MessageId"/>, identity is determined solely
/// by that identifier. Otherwise, the comparison falls through to <see cref="ChatMessage.Role"/>,
/// <see cref="ChatMessage.AuthorName"/>, and each item in <see cref="ChatMessage.Contents"/>.
/// </remarks>
internal static bool ContentEquals(this ChatMessage? message, ChatMessage? other)
{
if (ReferenceEquals(message, other))
{
return true;
}
if (message is null || other is null)
{
return false;
}
// A matching MessageId is sufficient.
if (message.MessageId is not null && other.MessageId is not null)
{
return string.Equals(message.MessageId, other.MessageId, StringComparison.Ordinal);
}
if (message.Role != other.Role)
{
return false;
}
if (!string.Equals(message.AuthorName, other.AuthorName, StringComparison.Ordinal))
{
return false;
}
return ContentsEqual(message.Contents, other.Contents);
}
private static bool ContentsEqual(IList<AIContent> left, IList<AIContent> right)
{
if (left.Count != right.Count)
{
return false;
}
for (int i = 0; i < left.Count; i++)
{
if (!ContentItemEquals(left[i], right[i]))
{
return false;
}
}
return true;
}
private static bool ContentItemEquals(AIContent left, AIContent right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if (left.GetType() != right.GetType())
{
return false;
}
return (left, right) switch
{
(TextContent a, TextContent b) => TextContentEquals(a, b),
(TextReasoningContent a, TextReasoningContent b) => TextReasoningContentEquals(a, b),
(DataContent a, DataContent b) => DataContentEquals(a, b),
(UriContent a, UriContent b) => UriContentEquals(a, b),
(ErrorContent a, ErrorContent b) => ErrorContentEquals(a, b),
(FunctionCallContent a, FunctionCallContent b) => FunctionCallContentEquals(a, b),
(FunctionResultContent a, FunctionResultContent b) => FunctionResultContentEquals(a, b),
(HostedFileContent a, HostedFileContent b) => HostedFileContentEquals(a, b),
(AIContent a, AIContent b) => a.GetType() == b.GetType(),
};
}
private static bool TextContentEquals(TextContent a, TextContent b) =>
string.Equals(a.Text, b.Text, StringComparison.Ordinal);
private static bool TextReasoningContentEquals(TextReasoningContent a, TextReasoningContent b) =>
string.Equals(a.Text, b.Text, StringComparison.Ordinal) &&
string.Equals(a.ProtectedData, b.ProtectedData, StringComparison.Ordinal);
private static bool DataContentEquals(DataContent a, DataContent b) =>
string.Equals(a.MediaType, b.MediaType, StringComparison.Ordinal) &&
string.Equals(a.Name, b.Name, StringComparison.Ordinal) &&
a.Data.Span.SequenceEqual(b.Data.Span);
private static bool UriContentEquals(UriContent a, UriContent b) =>
Equals(a.Uri, b.Uri) &&
string.Equals(a.MediaType, b.MediaType, StringComparison.Ordinal);
private static bool ErrorContentEquals(ErrorContent a, ErrorContent b) =>
string.Equals(a.Message, b.Message, StringComparison.Ordinal) &&
string.Equals(a.ErrorCode, b.ErrorCode, StringComparison.Ordinal) &&
Equals(a.Details, b.Details);
private static bool FunctionCallContentEquals(FunctionCallContent a, FunctionCallContent b) =>
string.Equals(a.CallId, b.CallId, StringComparison.Ordinal) &&
string.Equals(a.Name, b.Name, StringComparison.Ordinal) &&
ArgumentsEqual(a.Arguments, b.Arguments);
private static bool FunctionResultContentEquals(FunctionResultContent a, FunctionResultContent b) =>
string.Equals(a.CallId, b.CallId, StringComparison.Ordinal) &&
Equals(a.Result, b.Result);
private static bool ArgumentsEqual(IDictionary<string, object?>? left, IDictionary<string, object?>? right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if (left is null || right is null)
{
return false;
}
if (left.Count != right.Count)
{
return false;
}
foreach (KeyValuePair<string, object?> entry in left)
{
if (!right.TryGetValue(entry.Key, out object? value) || !Equals(entry.Value, value))
{
return false;
}
}
return true;
}
private static bool HostedFileContentEquals(HostedFileContent a, HostedFileContent b) =>
string.Equals(a.FileId, b.FileId, StringComparison.Ordinal) &&
string.Equals(a.MediaType, b.MediaType, StringComparison.Ordinal) &&
string.Equals(a.Name, b.Name, StringComparison.Ordinal);
}
@@ -1,82 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Shared.DiagnosticIds;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// A compaction strategy that delegates to an <see cref="IChatReducer"/> to reduce the conversation's
/// included messages.
/// </summary>
/// <remarks>
/// <para>
/// This strategy bridges the <see cref="IChatReducer"/> abstraction from <c>Microsoft.Extensions.AI</c>
/// into the compaction pipeline. It collects the currently included messages from the
/// <see cref="CompactionMessageIndex"/>, passes them to the reducer, and rebuilds the index from the
/// reduced message list when the reducer produces fewer messages.
/// </para>
/// <para>
/// The <see cref="CompactionTrigger"/> controls when reduction is attempted.
/// Use <see cref="CompactionTriggers"/> for common trigger conditions such as token or message thresholds.
/// </para>
/// <para>
/// Use this strategy when you have an existing <see cref="IChatReducer"/> implementation
/// (such as <c>MessageCountingChatReducer</c>) and want to apply it as part of a
/// <see cref="CompactionStrategy"/> pipeline or as an in-run compaction strategy.
/// </para>
/// </remarks>
[Experimental(DiagnosticIds.Experiments.AgentsAIExperiments)]
public sealed class ChatReducerCompactionStrategy : CompactionStrategy
{
/// <summary>
/// Initializes a new instance of the <see cref="ChatReducerCompactionStrategy"/> class.
/// </summary>
/// <param name="chatReducer">
/// The <see cref="IChatReducer"/> that performs the message reduction.
/// </param>
/// <param name="trigger">
/// The <see cref="CompactionTrigger"/> that controls when compaction proceeds.
/// </param>
public ChatReducerCompactionStrategy(IChatReducer chatReducer, CompactionTrigger trigger)
: base(trigger)
{
this.ChatReducer = Throw.IfNull(chatReducer);
}
/// <summary>
/// Gets the chat reducer used to reduce messages.
/// </summary>
public IChatReducer ChatReducer { get; }
/// <inheritdoc/>
protected override async ValueTask<bool> CompactCoreAsync(CompactionMessageIndex index, ILogger logger, CancellationToken cancellationToken)
{
// No need to short-circuit on empty conversations, this is handled by <see cref="CompactionStrategy.CompactAsync"/>.
List<ChatMessage> includedMessages = [.. index.GetIncludedMessages()];
IEnumerable<ChatMessage> reduced = await this.ChatReducer.ReduceAsync(includedMessages, cancellationToken).ConfigureAwait(false);
IList<ChatMessage> reducedMessages = reduced as IList<ChatMessage> ?? [.. reduced];
if (reducedMessages.Count >= includedMessages.Count)
{
return false;
}
// Rebuild the index from the reduced messages
CompactionMessageIndex rebuilt = CompactionMessageIndex.Create(reducedMessages, index.Tokenizer);
index.Groups.Clear();
foreach (CompactionMessageGroup group in rebuilt.Groups)
{
index.Groups.Add(group);
}
return true;
}
}
@@ -1,55 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Diagnostics.CodeAnalysis;
using Microsoft.Shared.DiagnosticIds;
namespace Microsoft.Agents.AI.Compaction;
/// <summary>
/// Identifies the kind of a <see cref="CompactionMessageGroup"/>.
/// </summary>
/// <remarks>
/// Message groups are used to classify logically related messages that must be kept together
/// during compaction operations. For example, an assistant message containing tool calls
/// and its corresponding tool result messages form an atomic <see cref="ToolCall"/> group.
/// </remarks>
[Experimental(DiagnosticIds.Experiments.AgentsAIExperiments)]
public enum CompactionGroupKind
{
/// <summary>
/// A system message group containing one or more system messages.
/// </summary>
System,
/// <summary>
/// A user message group containing a single user message.
/// </summary>
User,
/// <summary>
/// An assistant message group containing a single assistant text response (no tool calls).
/// </summary>
AssistantText,
/// <summary>
/// An atomic tool call group containing an assistant message with tool calls
/// followed by the corresponding tool result messages.
/// </summary>
/// <remarks>
/// This group must be treated as an atomic unit during compaction. Removing the assistant
/// message without its tool results (or vice versa) will cause LLM API errors.
/// </remarks>
ToolCall,
#pragma warning disable IDE0001 // Simplify Names
/// <summary>
/// A summary message group produced by a compaction strategy (e.g., <c>SummarizationCompactionStrategy</c>).
/// </summary>
/// <remarks>
/// Summary groups replace previously compacted messages with a condensed representation.
/// They are identified by the <see cref="CompactionMessageGroup.SummaryPropertyKey"/> metadata entry
/// on the underlying <see cref="Microsoft.Extensions.AI.ChatMessage"/>.
/// </remarks>
#pragma warning restore IDE0001 // Simplify Names
Summary,
}
@@ -1,112 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Logging;
namespace Microsoft.Agents.AI.Compaction;
#pragma warning disable SYSLIB1006 // Multiple logging methods cannot use the same event id within a class
/// <summary>
/// Extensions for logging compaction diagnostics.
/// </summary>
/// <remarks>
/// This extension uses the <see cref="LoggerMessageAttribute"/> to
/// generate logging code at compile time to achieve optimized code.
/// </remarks>
[ExcludeFromCodeCoverage]
internal static partial class CompactionLogMessages
{
/// <summary>
/// Logs when compaction is skipped because the trigger condition was not met.
/// </summary>
[LoggerMessage(
Level = LogLevel.Trace,
Message = "Compaction skipped for {StrategyName}: trigger condition not met or insufficient groups.")]
public static partial void LogCompactionSkipped(
this ILogger logger,
string strategyName);
/// <summary>
/// Logs compaction completion with before/after metrics.
/// </summary>
[LoggerMessage(
Level = LogLevel.Debug,
Message = "Compaction completed: {StrategyName} in {DurationMs}ms — Messages {BeforeMessages}→{AfterMessages}, Groups {BeforeGroups}→{AfterGroups}, Tokens {BeforeTokens}→{AfterTokens}")]
public static partial void LogCompactionCompleted(
this ILogger logger,
string strategyName,
long durationMs,
int beforeMessages,
int afterMessages,
int beforeGroups,
int afterGroups,
int beforeTokens,
int afterTokens);
/// <summary>
/// Logs when the compaction provider skips compaction.
/// </summary>
[LoggerMessage(
Level = LogLevel.Trace,
Message = "CompactionProvider skipped: {Reason}.")]
public static partial void LogCompactionProviderSkipped(
this ILogger logger,
string reason);
/// <summary>
/// Logs when the compaction provider begins applying a compaction strategy.
/// </summary>
[LoggerMessage(
Level = LogLevel.Debug,
Message = "CompactionProvider applying compaction to {MessageCount} messages using {StrategyName}.")]
public static partial void LogCompactionProviderApplying(
this ILogger logger,
int messageCount,
string strategyName);
/// <summary>
/// Logs when the compaction provider has applied compaction with result metrics.
/// </summary>
[LoggerMessage(
Level = LogLevel.Debug,
Message = "CompactionProvider compaction applied: messages {BeforeMessages}→{AfterMessages}.")]
public static partial void LogCompactionProviderApplied(
this ILogger logger,
int beforeMessages,
int afterMessages);
/// <summary>
/// Logs when a summarization LLM call is starting.
/// </summary>
[LoggerMessage(
Level = LogLevel.Debug,
Message = "Summarization starting for {GroupCount} groups ({MessageCount} messages) using {ChatClientType}.")]
public static partial void LogSummarizationStarting(
this ILogger logger,
int groupCount,
int messageCount,
string chatClientType);
/// <summary>
/// Logs when a summarization LLM call has completed.
/// </summary>
[LoggerMessage(
Level = LogLevel.Debug,
Message = "Summarization completed: summary length {SummaryLength} characters, inserted at index {InsertIndex}.")]
public static partial void LogSummarizationCompleted(
this ILogger logger,
int summaryLength,
int insertIndex);
/// <summary>
/// Logs when a summarization LLM call fails and groups are restored.
/// </summary>
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Summarization failed for {GroupCount} groups; restoring excluded groups and continuing without compaction. Error: {ErrorMessage}")]
public static partial void LogSummarizationFailed(
this ILogger logger,
int groupCount,
string errorMessage);
}

Some files were not shown because too many files have changed in this diff Show More