mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f958bf06ba | ||
|
|
443ed50f58 | ||
|
|
88b98aacd1 | ||
|
|
291547ad02 | ||
|
|
9498c8425e | ||
|
|
93825265cf | ||
|
|
9d86adfcb2 | ||
|
|
570bed9ff6 | ||
|
|
eff5aee5aa |
+2
-2
@@ -28,10 +28,10 @@ namespace SampleApp
|
||||
{
|
||||
public override string? Name => "UpperCaseParrotAgent";
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new CustomAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new CustomAgentThread(serializedThread, jsonSerializerOptions);
|
||||
|
||||
protected override async Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
|
||||
+199
-45
@@ -22,53 +22,200 @@ var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT
|
||||
// Replace this with a vector store implementation of your choice if you want to persist the chat history to disk.
|
||||
VectorStore vectorStore = new InMemoryVectorStore();
|
||||
|
||||
// Create the agent
|
||||
AIAgent agent = new AzureOpenAIClient(
|
||||
new Uri(endpoint),
|
||||
new AzureCliCredential())
|
||||
.GetChatClient(deploymentName)
|
||||
.CreateAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "You are good at telling jokes." },
|
||||
Name = "Joker",
|
||||
ChatMessageStoreFactory = ctx =>
|
||||
// Execute various samples showing how to use a custom ChatMessageStore with an agent.
|
||||
await CustomChatMessageStore_UsingFactory_Async();
|
||||
await CustomChatMessageStore_UsingFactoryAndExistingExternalId_Async();
|
||||
await CustomChatMessageStore_PerThread_Async();
|
||||
await CustomChatMessageStore_PerRun_Async();
|
||||
|
||||
// Here we can see how to create a custom ChatMessageStore using a factory method
|
||||
// provided to the agent via the ChatMessageStoreFactory option.
|
||||
// This allows us to use a custom chat message store, where the consumer of the agent
|
||||
// doesn't need to know anything about the storage mechanism used.
|
||||
async Task CustomChatMessageStore_UsingFactory_Async()
|
||||
{
|
||||
Console.WriteLine("\n--- With Factory ---\n");
|
||||
|
||||
// Create the agent
|
||||
AIAgent agent = new AzureOpenAIClient(
|
||||
new Uri(endpoint),
|
||||
new AzureCliCredential())
|
||||
// Use a service that doesn't require storage of chat history in the service itself.
|
||||
.GetChatClient(deploymentName)
|
||||
.CreateAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
// Create a new chat message store for this agent that stores the messages in a vector store.
|
||||
// Each thread must get its own copy of the VectorChatMessageStore, since the store
|
||||
// also contains the id that the thread is stored under.
|
||||
return new VectorChatMessageStore(vectorStore, ctx.SerializedState, ctx.JsonSerializerOptions);
|
||||
}
|
||||
});
|
||||
ChatOptions = new() { Instructions = "You are good at telling jokes." },
|
||||
Name = "Joker",
|
||||
ChatMessageStoreFactory = ctx =>
|
||||
{
|
||||
// Create a new chat message store for this agent that stores the messages in a vector store.
|
||||
// Each thread must get its own copy of the VectorChatMessageStore, since the store
|
||||
// also contains the id that the thread is stored under.
|
||||
return new VectorChatMessageStore(vectorStore, ctx.SerializedState, ctx.JsonSerializerOptions, ctx.Features);
|
||||
}
|
||||
});
|
||||
|
||||
// Start a new thread for the agent conversation.
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
// Start a new thread for the agent conversation.
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
|
||||
// Run the agent with the thread that stores conversation history in the vector store.
|
||||
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread));
|
||||
// Run the agent with the thread that stores conversation history in the vector store.
|
||||
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread));
|
||||
|
||||
// Serialize the thread state, so it can be stored for later use.
|
||||
// Since the chat history is stored in the vector store, the serialized thread
|
||||
// only contains the guid that the messages are stored under in the vector store.
|
||||
JsonElement serializedThread = thread.Serialize();
|
||||
// Serialize the thread state, so it can be stored for later use.
|
||||
// Since the chat history is stored in the vector store, the serialized thread
|
||||
// only contains the guid that the messages are stored under in the vector store.
|
||||
JsonElement serializedThread = thread.Serialize();
|
||||
|
||||
Console.WriteLine("\n--- Serialized thread ---\n");
|
||||
Console.WriteLine(JsonSerializer.Serialize(serializedThread, new JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine("\n--- Serialized thread ---\n");
|
||||
Console.WriteLine(JsonSerializer.Serialize(serializedThread, new JsonSerializerOptions { WriteIndented = true }));
|
||||
|
||||
// The serialized thread can now be saved to a database, file, or any other storage mechanism
|
||||
// and loaded again later.
|
||||
// The serialized thread can now be saved to a database, file, or any other storage mechanism
|
||||
// and loaded again later.
|
||||
|
||||
// Deserialize the thread state after loading from storage.
|
||||
AgentThread resumedThread = agent.DeserializeThread(serializedThread);
|
||||
// Deserialize the thread state after loading from storage.
|
||||
AgentThread resumedThread = agent.DeserializeThread(serializedThread);
|
||||
|
||||
// Run the agent with the thread that stores conversation history in the vector store a second time.
|
||||
Console.WriteLine(await agent.RunAsync("Now tell the same joke in the voice of a pirate, and add some emojis to the joke.", resumedThread));
|
||||
// Run the agent with the thread that stores conversation history in the vector store a second time.
|
||||
Console.WriteLine(await agent.RunAsync("Now tell the same joke in the voice of a pirate, and add some emojis to the joke.", resumedThread));
|
||||
}
|
||||
|
||||
// We can access the VectorChatMessageStore via the thread's GetService method if we need to read the key under which threads are stored.
|
||||
var messageStore = resumedThread.GetService<VectorChatMessageStore>()!;
|
||||
Console.WriteLine($"\nThread is stored in vector store under key: {messageStore.ThreadDbKey}");
|
||||
// Here we can see how to create a custom ChatMessageStore using a factory method
|
||||
// provided to the agent via the ChatMessageStoreFactory option.
|
||||
// It also shows how we can pass a custom storage id at runtime to the message store using
|
||||
// the VectorChatMessageStoreThreadDbKeyFeature.
|
||||
// Note that not all agents or chat message stores may support this feature.
|
||||
async Task CustomChatMessageStore_UsingFactoryAndExistingExternalId_Async()
|
||||
{
|
||||
Console.WriteLine("\n--- With Factory and Existing External ID ---\n");
|
||||
|
||||
// Create the agent
|
||||
AIAgent agent = new AzureOpenAIClient(
|
||||
new Uri(endpoint),
|
||||
new AzureCliCredential())
|
||||
// Use a service that doesn't require storage of chat history in the service itself.
|
||||
.GetChatClient(deploymentName)
|
||||
.CreateAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "You are good at telling jokes." },
|
||||
Name = "Joker",
|
||||
ChatMessageStoreFactory = ctx =>
|
||||
{
|
||||
// Create a new chat message store for this agent that stores the messages in a vector store.
|
||||
// Each thread must get its own copy of the VectorChatMessageStore, since the store
|
||||
// also contains the id that the thread is stored under.
|
||||
return new VectorChatMessageStore(vectorStore, ctx.SerializedState, ctx.JsonSerializerOptions, ctx.Features);
|
||||
}
|
||||
});
|
||||
|
||||
// Start a new thread for the agent conversation.
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
|
||||
// Run the agent with the thread that stores conversation history in the vector store.
|
||||
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread));
|
||||
|
||||
// We can access the VectorChatMessageStore via the thread's GetService method if we need to read the key under which threads are stored.
|
||||
var messageStoreFromFactory = thread.GetService<VectorChatMessageStore>()!;
|
||||
Console.WriteLine($"\nThread is stored in vector store under key: {messageStoreFromFactory.ThreadDbKey}");
|
||||
|
||||
// It's possible to create a new thread that uses the same chat message store id by providing
|
||||
// the VectorChatMessageStoreThreadDbKeyFeature in the feature collection when creating the new thread.
|
||||
AgentThread resumedThread = agent.GetNewThread(
|
||||
new AgentFeatureCollection().WithFeature(new VectorChatMessageStoreThreadDbKeyFeature(messageStoreFromFactory.ThreadDbKey!)));
|
||||
|
||||
// Run the agent with the thread that stores conversation history in the vector store.
|
||||
Console.WriteLine(await agent.RunAsync("Now tell the same joke in the voice of a pirate, and add some emojis to the joke.", resumedThread));
|
||||
}
|
||||
|
||||
// Here we can see how to create a custom ChatMessageStore and pass it to the thread
|
||||
// when creating a new thread.
|
||||
async Task CustomChatMessageStore_PerThread_Async()
|
||||
{
|
||||
Console.WriteLine("\n--- Per Thread ---\n");
|
||||
|
||||
// We can also create an agent without a factory that provides a ChatMessageStore.
|
||||
AIAgent agent = new AzureOpenAIClient(
|
||||
new Uri(endpoint),
|
||||
new AzureCliCredential())
|
||||
// Use a service that doesn't require storage of chat history in the service itself.
|
||||
.GetChatClient(deploymentName)
|
||||
.CreateAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "You are good at telling jokes." },
|
||||
Name = "Joker"
|
||||
});
|
||||
|
||||
// Instead of using a factory on the agent to create the ChatMessageStore, we can
|
||||
// create a VectorChatMessageStore ourselves and register it in a feature collection.
|
||||
// We can then pass the feature collection when creating a new thread.
|
||||
// We also have the opportunity here to pass any id that we want for storing the chat history in the vector store.
|
||||
VectorChatMessageStore perThreadMessageStore = new(vectorStore, "chat-history-1");
|
||||
AgentThread thread = agent.GetNewThread(new AgentFeatureCollection().WithFeature<ChatMessageStore>(perThreadMessageStore));
|
||||
|
||||
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread));
|
||||
|
||||
// When serializing this thread, we'll see that it has the id from the message store stored in its state.
|
||||
JsonElement serializedThread = thread.Serialize();
|
||||
|
||||
Console.WriteLine("\n--- Serialized thread ---\n");
|
||||
Console.WriteLine(JsonSerializer.Serialize(serializedThread, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
|
||||
// Here we can see how to create a custom ChatMessageStore for a single run using the Features option
|
||||
// passed when we run the agent.
|
||||
// Note that if the agent doesn't support a chat message store, it would be ignored.
|
||||
async Task CustomChatMessageStore_PerRun_Async()
|
||||
{
|
||||
Console.WriteLine("\n--- Per Run ---\n");
|
||||
|
||||
// We can also create an agent without a factory that provides a ChatMessageStore.
|
||||
AIAgent agent = new AzureOpenAIClient(
|
||||
new Uri(endpoint),
|
||||
new AzureCliCredential())
|
||||
// Use a service that doesn't require storage of chat history in the service itself.
|
||||
.GetChatClient(deploymentName)
|
||||
.CreateAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "You are good at telling jokes." },
|
||||
Name = "Joker"
|
||||
});
|
||||
|
||||
// Start a new thread for the agent conversation.
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
|
||||
// Instead of using a factory on the agent to create the ChatMessageStore, we can
|
||||
// create a VectorChatMessageStore ourselves and register it in a feature collection.
|
||||
// We can then pass the feature collection to the agent when running it by using the Features option.
|
||||
// The message store would only be used for the run that it's passed to.
|
||||
// If the agent doesn't support a message store, it would be ignored.
|
||||
// We also have the opportunity here to pass any id that we want for storing the chat history in the vector store.
|
||||
VectorChatMessageStore perRunMessageStore = new(vectorStore, "chat-history-1");
|
||||
Console.WriteLine(await agent.RunAsync(
|
||||
"Tell me a joke about a pirate.",
|
||||
thread,
|
||||
options: new AgentRunOptions()
|
||||
{
|
||||
Features = new AgentFeatureCollection().WithFeature<ChatMessageStore>(perRunMessageStore)
|
||||
}));
|
||||
|
||||
// When serializing this thread, we'll see that it has no messagestore state, since the messagestore was not attached to the thread,
|
||||
// but just provided for the single run. Note that, depending on the circumstances, the thread may still contain other state, e.g. Memories,
|
||||
// if an AIContextProvider is attached which adds memory to an agent.
|
||||
JsonElement serializedThread = thread.Serialize();
|
||||
|
||||
Console.WriteLine("\n--- Serialized thread ---\n");
|
||||
Console.WriteLine(JsonSerializer.Serialize(serializedThread, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
|
||||
namespace SampleApp
|
||||
{
|
||||
/// <summary>
|
||||
/// A feature that allows providing the thread database key for the <see cref="VectorChatMessageStore"/>.
|
||||
/// </summary>
|
||||
internal sealed class VectorChatMessageStoreThreadDbKeyFeature(string threadDbKey)
|
||||
{
|
||||
public string ThreadDbKey { get; } = threadDbKey;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sample implementation of <see cref="ChatMessageStore"/> that stores chat messages in a vector store.
|
||||
/// </summary>
|
||||
@@ -76,29 +223,36 @@ namespace SampleApp
|
||||
{
|
||||
private readonly VectorStore _vectorStore;
|
||||
|
||||
public VectorChatMessageStore(VectorStore vectorStore, JsonElement serializedStoreState, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public VectorChatMessageStore(VectorStore vectorStore, string threadDbKey)
|
||||
{
|
||||
this._vectorStore = vectorStore ?? throw new ArgumentNullException(nameof(vectorStore));
|
||||
this.ThreadDbKey = threadDbKey ?? throw new ArgumentNullException(nameof(threadDbKey));
|
||||
}
|
||||
|
||||
public VectorChatMessageStore(VectorStore vectorStore, JsonElement serializedStoreState, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? features = null)
|
||||
{
|
||||
this._vectorStore = vectorStore ?? throw new ArgumentNullException(nameof(vectorStore));
|
||||
|
||||
if (serializedStoreState.ValueKind is JsonValueKind.String)
|
||||
{
|
||||
// Here we can deserialize the thread id so that we can access the same messages as before the suspension.
|
||||
this.ThreadDbKey = serializedStoreState.Deserialize<string>();
|
||||
}
|
||||
// Here we can deserialize the thread id so that we can access the same messages as before the suspension, or if
|
||||
// a user provided a ConversationIdAgentFeature in the features collection, we can use that
|
||||
// or finally we can generate one ourselves.
|
||||
this.ThreadDbKey = serializedStoreState.ValueKind is JsonValueKind.String
|
||||
? serializedStoreState.Deserialize<string>()
|
||||
: features?.TryGet<VectorChatMessageStoreThreadDbKeyFeature>(out var threadDbKeyFeature) is true
|
||||
? threadDbKeyFeature.ThreadDbKey
|
||||
: Guid.NewGuid().ToString("N");
|
||||
}
|
||||
|
||||
public string? ThreadDbKey { get; private set; }
|
||||
public string? ThreadDbKey { get; }
|
||||
|
||||
public override async Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken = default)
|
||||
{
|
||||
this.ThreadDbKey ??= Guid.NewGuid().ToString("N");
|
||||
|
||||
var collection = this._vectorStore.GetCollection<string, ChatHistoryItem>("ChatHistory");
|
||||
await collection.EnsureCollectionExistsAsync(cancellationToken);
|
||||
|
||||
await collection.UpsertAsync(messages.Select(x => new ChatHistoryItem()
|
||||
{
|
||||
Key = this.ThreadDbKey + x.MessageId,
|
||||
Key = this.ThreadDbKey + (string.IsNullOrWhiteSpace(x.MessageId) ? Guid.NewGuid().ToString("N") : x.MessageId),
|
||||
Timestamp = DateTimeOffset.UtcNow,
|
||||
ThreadId = this.ThreadDbKey,
|
||||
SerializedMessage = JsonSerializer.Serialize(x),
|
||||
|
||||
@@ -52,8 +52,13 @@ internal sealed class A2AAgent : AIAgent
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed override AgentThread GetNewThread()
|
||||
=> new A2AAgentThread();
|
||||
public sealed override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new A2AAgentThread()
|
||||
{
|
||||
ContextId = featureCollection?.TryGet<ConversationIdAgentFeature>(out var conversationIdFeature) is true
|
||||
? conversationIdFeature.ConversationId
|
||||
: null
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Get a new <see cref="AgentThread"/> instance using an existing context id, to continue that conversation.
|
||||
@@ -64,7 +69,7 @@ internal sealed class A2AAgent : AIAgent
|
||||
=> new A2AAgentThread() { ContextId = contextId };
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new A2AAgentThread(serializedThread, jsonSerializerOptions);
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
||||
@@ -105,6 +105,7 @@ public abstract class AIAgent
|
||||
/// <summary>
|
||||
/// Creates a new conversation thread that is compatible with this agent.
|
||||
/// </summary>
|
||||
/// <param name="featureCollection">An optional feature collection to override or provide additional context or capabilities to the thread where the thread supports these features.</param>
|
||||
/// <returns>A new <see cref="AgentThread"/> instance ready for use with this agent.</returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -118,13 +119,14 @@ public abstract class AIAgent
|
||||
/// may be deferred until first use to optimize performance.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public abstract AgentThread GetNewThread();
|
||||
public abstract AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null);
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes an agent thread from its JSON serialized representation.
|
||||
/// </summary>
|
||||
/// <param name="serializedThread">A <see cref="JsonElement"/> containing the serialized thread state.</param>
|
||||
/// <param name="jsonSerializerOptions">Optional settings to customize the deserialization process.</param>
|
||||
/// <param name="featureCollection">An optional feature collection to override or provide additional context or capabilities to the thread where the thread supports these features.</param>
|
||||
/// <returns>A restored <see cref="AgentThread"/> instance with the state from <paramref name="serializedThread"/>.</returns>
|
||||
/// <exception cref="ArgumentException">The <paramref name="serializedThread"/> is not in the expected format.</exception>
|
||||
/// <exception cref="JsonException">The serialized data is invalid or cannot be deserialized.</exception>
|
||||
@@ -133,7 +135,7 @@ public abstract class AIAgent
|
||||
/// allowing conversations to resume across application restarts or be migrated between
|
||||
/// different agent instances.
|
||||
/// </remarks>
|
||||
public abstract AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null);
|
||||
public abstract AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null);
|
||||
|
||||
/// <summary>
|
||||
/// Run the agent with no message assuming that all required instructions are already provided to the agent or on the thread.
|
||||
|
||||
@@ -34,6 +34,7 @@ public class AgentRunOptions
|
||||
this.ContinuationToken = options.ContinuationToken;
|
||||
this.AllowBackgroundResponses = options.AllowBackgroundResponses;
|
||||
this.AdditionalProperties = options.AdditionalProperties?.Clone();
|
||||
this.Features = options.Features;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -90,4 +91,9 @@ public class AgentRunOptions
|
||||
/// preserving implementation-specific details or extending the options with custom data.
|
||||
/// </remarks>
|
||||
public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of features provided by the caller and middleware for this run.
|
||||
/// </summary>
|
||||
public IAgentFeatureCollection? Features { get; set; }
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ namespace Microsoft.Agents.AI;
|
||||
/// <item><description>Chat history reduction, e.g. where messages needs to be summarized or truncated to reduce the size.</description></item>
|
||||
/// </list>
|
||||
/// An <see cref="AgentThread"/> is always constructed by an <see cref="AIAgent"/> so that the <see cref="AIAgent"/>
|
||||
/// can attach any necessary behaviors to the <see cref="AgentThread"/>. See the <see cref="AIAgent.GetNewThread()"/>
|
||||
/// and <see cref="AIAgent.DeserializeThread(JsonElement, JsonSerializerOptions?)"/> methods for more information.
|
||||
/// can attach any necessary behaviors to the <see cref="AgentThread"/>. See the <see cref="AIAgent.GetNewThread(Microsoft.Agents.AI.IAgentFeatureCollection?)"/>
|
||||
/// and <see cref="AIAgent.DeserializeThread(JsonElement, JsonSerializerOptions?, Microsoft.Agents.AI.IAgentFeatureCollection?)"/> methods for more information.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Because of these behaviors, an <see cref="AgentThread"/> may not be reusable across different agents, since each agent
|
||||
@@ -37,13 +37,13 @@ namespace Microsoft.Agents.AI;
|
||||
/// To support conversations that may need to survive application restarts or separate service requests, an <see cref="AgentThread"/> can be serialized
|
||||
/// and deserialized, so that it can be saved in a persistent store.
|
||||
/// The <see cref="AgentThread"/> provides the <see cref="Serialize(JsonSerializerOptions?)"/> method to serialize the thread to a
|
||||
/// <see cref="JsonElement"/> and the <see cref="AIAgent.DeserializeThread(JsonElement, JsonSerializerOptions?)"/> method
|
||||
/// <see cref="JsonElement"/> and the <see cref="AIAgent.DeserializeThread(JsonElement, JsonSerializerOptions?, Microsoft.Agents.AI.IAgentFeatureCollection?)"/> method
|
||||
/// can be used to deserialize the thread.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <seealso cref="AIAgent"/>
|
||||
/// <seealso cref="AIAgent.GetNewThread()"/>
|
||||
/// <seealso cref="AIAgent.DeserializeThread(JsonElement, JsonSerializerOptions?)"/>
|
||||
/// <seealso cref="AIAgent.GetNewThread(Microsoft.Agents.AI.IAgentFeatureCollection?)"/>
|
||||
/// <seealso cref="AIAgent.DeserializeThread(JsonElement, JsonSerializerOptions?, Microsoft.Agents.AI.IAgentFeatureCollection?)"/>
|
||||
public abstract class AgentThread
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -74,11 +74,11 @@ public abstract class DelegatingAIAgent : AIAgent
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override AgentThread GetNewThread() => this.InnerAgent.GetNewThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => this.InnerAgent.GetNewThread(featureCollection);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
=> this.InnerAgent.DeserializeThread(serializedThread, jsonSerializerOptions);
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> this.InnerAgent.DeserializeThread(serializedThread, jsonSerializerOptions, featureCollection);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
|
||||
namespace Microsoft.Agents.AI;
|
||||
|
||||
#pragma warning disable CA1043 // Use Integral Or String Argument For Indexers
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation for <see cref="IAgentFeatureCollection"/>.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Count = {GetCount()}")]
|
||||
[DebuggerTypeProxy(typeof(FeatureCollectionDebugView))]
|
||||
public class AgentFeatureCollection : IAgentFeatureCollection
|
||||
{
|
||||
private readonly IAgentFeatureCollection? _innerCollection;
|
||||
private Dictionary<Type, object>? _features;
|
||||
private volatile int _containerRevision;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="AgentFeatureCollection"/>.
|
||||
/// </summary>
|
||||
public AgentFeatureCollection()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="AgentFeatureCollection"/> with the specified initial capacity.
|
||||
/// </summary>
|
||||
/// <param name="initialCapacity">The initial number of elements that the collection can contain.</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException"><paramref name="initialCapacity"/> is less than 0</exception>
|
||||
public AgentFeatureCollection(int initialCapacity)
|
||||
{
|
||||
Throw.IfLessThan(initialCapacity, 0);
|
||||
this._features = new(initialCapacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="AgentFeatureCollection"/> with the specified inner collection.
|
||||
/// </summary>
|
||||
/// <param name="innerCollection">The inner collection.</param>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// When providing an inner collection, and if a feature is not found in this collection,
|
||||
/// an attempt will be made to retrieve it from the inner collection as a fallback.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The <see cref="Remove{TFeature}"/> method will only remove features from this collection
|
||||
/// and not from the inner collection. When removing a feature from this collection, and
|
||||
/// it exists in the inner collection, it will still be retrievable from the inner collection.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public AgentFeatureCollection(IAgentFeatureCollection innerCollection)
|
||||
{
|
||||
this._innerCollection = Throw.IfNull(innerCollection);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Revision
|
||||
{
|
||||
get { return this._containerRevision + (this._innerCollection?.Revision ?? 0); }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsReadOnly { get { return false; } }
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return this.GetEnumerator();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerator<KeyValuePair<Type, object>> GetEnumerator()
|
||||
{
|
||||
if (this._features is not { Count: > 0 })
|
||||
{
|
||||
IEnumerable<KeyValuePair<Type, object>> e = ((IEnumerable<KeyValuePair<Type, object>>?)this._innerCollection) ?? [];
|
||||
return e.GetEnumerator();
|
||||
}
|
||||
|
||||
if (this._innerCollection is null)
|
||||
{
|
||||
return this._features.GetEnumerator();
|
||||
}
|
||||
|
||||
if (this._innerCollection is AgentFeatureCollection innerCollection && innerCollection._features is not { Count: > 0 })
|
||||
{
|
||||
return this._features.GetEnumerator();
|
||||
}
|
||||
|
||||
return YieldAll();
|
||||
|
||||
IEnumerator<KeyValuePair<Type, object>> YieldAll()
|
||||
{
|
||||
HashSet<Type> set = [];
|
||||
|
||||
foreach (var entry in this._features)
|
||||
{
|
||||
set.Add(entry.Key);
|
||||
yield return entry;
|
||||
}
|
||||
|
||||
foreach (var entry in this._innerCollection.Where(x => !set.Contains(x.Key)))
|
||||
{
|
||||
yield return entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryGet<TFeature>([MaybeNullWhen(false)] out TFeature feature)
|
||||
where TFeature : notnull
|
||||
{
|
||||
if (this.TryGet(typeof(TFeature), out var obj))
|
||||
{
|
||||
feature = (TFeature)obj;
|
||||
return true;
|
||||
}
|
||||
|
||||
feature = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryGet(Type type, [MaybeNullWhen(false)] out object feature)
|
||||
{
|
||||
if (this._features?.TryGetValue(type, out var obj) is true)
|
||||
{
|
||||
feature = obj;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this._innerCollection?.TryGet(type, out var defaultFeature) is true)
|
||||
{
|
||||
feature = defaultFeature;
|
||||
return true;
|
||||
}
|
||||
|
||||
feature = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Set<TFeature>(TFeature instance)
|
||||
where TFeature : notnull
|
||||
{
|
||||
Throw.IfNull(instance);
|
||||
|
||||
this._features ??= new();
|
||||
this._features[typeof(TFeature)] = instance;
|
||||
this._containerRevision++;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Remove<TFeature>()
|
||||
where TFeature : notnull
|
||||
=> this.Remove(typeof(TFeature));
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Remove(Type type)
|
||||
{
|
||||
if (this._features?.Remove(type) is true)
|
||||
{
|
||||
this._containerRevision++;
|
||||
}
|
||||
}
|
||||
|
||||
// Used by the debugger. Count over enumerable is required to get the correct value.
|
||||
private int GetCount() => this.Count();
|
||||
|
||||
private sealed class FeatureCollectionDebugView(AgentFeatureCollection features)
|
||||
{
|
||||
private readonly AgentFeatureCollection _features = features;
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
|
||||
public DictionaryItemDebugView<Type, object>[] Items => this._features.Select(pair => new DictionaryItemDebugView<Type, object>(pair)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a key/value pair for displaying an item of a dictionary by a debugger.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Value}", Name = "[{Key}]")]
|
||||
internal readonly struct DictionaryItemDebugView<TKey, TValue>
|
||||
{
|
||||
public DictionaryItemDebugView(TKey key, TValue value)
|
||||
{
|
||||
this.Key = key;
|
||||
this.Value = value;
|
||||
}
|
||||
|
||||
public DictionaryItemDebugView(KeyValuePair<TKey, TValue> keyValue)
|
||||
{
|
||||
this.Key = keyValue.Key;
|
||||
this.Value = keyValue.Value;
|
||||
}
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
|
||||
public TKey Key { get; }
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
|
||||
public TValue Value { get; }
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Microsoft.Agents.AI;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for <see cref="IAgentFeatureCollection"/>.
|
||||
/// </summary>
|
||||
public static class AgentFeatureCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the specified feature to the collection and returns the collection.
|
||||
/// </summary>
|
||||
/// <typeparam name="TFeature">The feature key.</typeparam>
|
||||
/// <param name="features">The feature collection to add the new feature to.</param>
|
||||
/// <param name="feature">The feature to add to the collection.</param>
|
||||
/// <returns>The updated collection.</returns>
|
||||
public static IAgentFeatureCollection WithFeature<TFeature>(this IAgentFeatureCollection features, TFeature feature)
|
||||
where TFeature : notnull
|
||||
{
|
||||
features.Set(feature);
|
||||
return features;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
|
||||
namespace Microsoft.Agents.AI;
|
||||
|
||||
/// <summary>
|
||||
/// An agent feature that allows providing a conversation identifier.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This feature allows a user to provide a specific identifier for chat history when stored in the underlying AI service.
|
||||
/// </remarks>
|
||||
public class ConversationIdAgentFeature
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConversationIdAgentFeature"/> class with the specified thread
|
||||
/// identifier.
|
||||
/// </summary>
|
||||
/// <param name="conversationId">The unique identifier of the thread required by the underlying AI service. Cannot be <see langword="null"/> or empty.</param>
|
||||
public ConversationIdAgentFeature(string conversationId)
|
||||
{
|
||||
this.ConversationId = Throw.IfNullOrWhitespace(conversationId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the conversation identifier.
|
||||
/// </summary>
|
||||
public string ConversationId { get; }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Microsoft.Agents.AI;
|
||||
|
||||
#pragma warning disable CA1043 // Use Integral Or String Argument For Indexers
|
||||
#pragma warning disable CA1716 // Identifiers should not match keywords
|
||||
|
||||
/// <summary>
|
||||
/// Represents a collection of Agent features.
|
||||
/// </summary>
|
||||
public interface IAgentFeatureCollection : IEnumerable<KeyValuePair<Type, object>>
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates if the collection can be modified.
|
||||
/// </summary>
|
||||
bool IsReadOnly { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Incremented for each modification and can be used to verify cached results.
|
||||
/// </summary>
|
||||
int Revision { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to retrieve a feature of the specified type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TFeature">The type of the feature to retrieve.</typeparam>
|
||||
/// <param name="feature">When this method returns, contains the feature of type <typeparamref name="TFeature"/> if found; otherwise, the
|
||||
/// default value for the type.</param>
|
||||
/// <returns>
|
||||
/// <see langword="true"/> if the feature of type <typeparamref name="TFeature"/> was successfully retrieved;
|
||||
/// otherwise, <see langword="false"/>.
|
||||
/// </returns>
|
||||
bool TryGet<TFeature>([MaybeNullWhen(false)] out TFeature feature)
|
||||
where TFeature : notnull;
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to retrieve a feature of the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type of the feature to get.</param>
|
||||
/// <param name="feature">When this method returns, contains the feature of type <paramref name="type"/> if found; otherwise, the
|
||||
/// default value for the type.</param>
|
||||
/// <returns>
|
||||
/// <see langword="true"/> if the feature of type <paramref name="type"/> was successfully retrieved;
|
||||
/// otherwise, <see langword="false"/>.
|
||||
/// </returns>
|
||||
bool TryGet(Type type, [MaybeNullWhen(false)] out object feature);
|
||||
|
||||
/// <summary>
|
||||
/// Remove a feature from the collection.
|
||||
/// </summary>
|
||||
/// <typeparam name="TFeature">The feature key.</typeparam>
|
||||
void Remove<TFeature>()
|
||||
where TFeature : notnull;
|
||||
|
||||
/// <summary>
|
||||
/// Remove a feature from the collection.
|
||||
/// </summary>
|
||||
/// <param name="type">The type of the feature to remove.</param>
|
||||
void Remove(Type type);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the given feature in the collection.
|
||||
/// </summary>
|
||||
/// <typeparam name="TFeature">The feature key.</typeparam>
|
||||
/// <param name="instance">The feature value.</param>
|
||||
void Set<TFeature>(TFeature instance)
|
||||
where TFeature : notnull;
|
||||
}
|
||||
@@ -42,8 +42,13 @@ public class CopilotStudioAgent : AIAgent
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed override AgentThread GetNewThread()
|
||||
=> new CopilotStudioAgentThread();
|
||||
public sealed override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new CopilotStudioAgentThread()
|
||||
{
|
||||
ConversationId = featureCollection?.TryGet<ConversationIdAgentFeature>(out var conversationIdFeature) is true
|
||||
? conversationIdFeature.ConversationId
|
||||
: null
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Get a new <see cref="AgentThread"/> instance using an existing conversation id, to continue that conversation.
|
||||
@@ -54,7 +59,7 @@ public class CopilotStudioAgent : AIAgent
|
||||
=> new CopilotStudioAgentThread() { ConversationId = conversationId };
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new CopilotStudioAgentThread(serializedThread, jsonSerializerOptions);
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
||||
@@ -33,21 +33,17 @@ public sealed class DurableAIAgent : AIAgent
|
||||
/// Creates a new agent thread for this agent using a random session ID.
|
||||
/// </summary>
|
||||
/// <returns>A new agent thread.</returns>
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
AgentSessionId sessionId = this._context.NewAgentSessionId(this._agentName);
|
||||
return new DurableAgentThread(sessionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes an agent thread from JSON.
|
||||
/// </summary>
|
||||
/// <param name="serializedThread">The serialized thread data.</param>
|
||||
/// <param name="jsonSerializerOptions">Optional JSON serializer options.</param>
|
||||
/// <returns>The deserialized agent thread.</returns>
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread DeserializeThread(
|
||||
JsonElement serializedThread,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
JsonSerializerOptions? jsonSerializerOptions = null,
|
||||
IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return DurableAgentThread.Deserialize(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
|
||||
@@ -13,12 +13,13 @@ internal class DurableAIAgentProxy(string name, IDurableAgentClient agentClient)
|
||||
|
||||
public override AgentThread DeserializeThread(
|
||||
JsonElement serializedThread,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
JsonSerializerOptions? jsonSerializerOptions = null,
|
||||
IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return DurableAgentThread.Deserialize(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new DurableAgentThread(AgentSessionId.WithRandomKey(this.Name!));
|
||||
}
|
||||
|
||||
@@ -30,15 +30,15 @@ internal class PurviewAgent : AIAgent, IDisposable
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return this._innerAgent.DeserializeThread(serializedThread, jsonSerializerOptions);
|
||||
return this._innerAgent.DeserializeThread(serializedThread, jsonSerializerOptions, featureCollection);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return this._innerAgent.GetNewThread();
|
||||
return this._innerAgent.GetNewThread(featureCollection);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
||||
@@ -61,9 +61,9 @@ internal sealed class WorkflowHostAgent : AIAgent
|
||||
protocol.ThrowIfNotChatProtocol();
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread() => new WorkflowThread(this._workflow, this.GenerateNewId(), this._executionEnvironment, this._checkpointManager);
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new WorkflowThread(this._workflow, this.GenerateNewId(), this._executionEnvironment, this._checkpointManager);
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new WorkflowThread(this._workflow, serializedThread, this._executionEnvironment, this._checkpointManager, jsonSerializerOptions);
|
||||
|
||||
private async ValueTask<WorkflowThread> UpdateThreadAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, CancellationToken cancellationToken = default)
|
||||
|
||||
@@ -272,7 +272,7 @@ public sealed partial class ChatClientAgent : AIAgent
|
||||
this.UpdateThreadWithTypeAndConversationId(safeThread, chatResponse.ConversationId);
|
||||
|
||||
// To avoid inconsistent state we only notify the thread of the input messages if no error occurs after the initial request.
|
||||
await NotifyMessageStoreOfNewMessagesAsync(safeThread, inputMessages.Concat(aiContextProviderMessages ?? []).Concat(chatResponse.Messages), cancellationToken).ConfigureAwait(false);
|
||||
await NotifyMessageStoreOfNewMessagesAsync(safeThread, inputMessages.Concat(aiContextProviderMessages ?? []).Concat(chatResponse.Messages), options, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Notify the AIContextProvider of all new messages.
|
||||
await NotifyAIContextProviderOfSuccessAsync(safeThread, inputMessages, aiContextProviderMessages, chatResponse.Messages, cancellationToken).ConfigureAwait(false);
|
||||
@@ -288,11 +288,20 @@ public sealed partial class ChatClientAgent : AIAgent
|
||||
: this.ChatClient.GetService(serviceType, serviceKey));
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new ChatClientAgentThread
|
||||
{
|
||||
MessageStore = this._agentOptions?.ChatMessageStoreFactory?.Invoke(new() { SerializedState = default, JsonSerializerOptions = null }),
|
||||
AIContextProvider = this._agentOptions?.AIContextProviderFactory?.Invoke(new() { SerializedState = default, JsonSerializerOptions = null })
|
||||
ConversationId = featureCollection?.TryGet<ConversationIdAgentFeature>(out var conversationIdAgentFeature) is true
|
||||
? conversationIdAgentFeature.ConversationId
|
||||
: null,
|
||||
MessageStore =
|
||||
featureCollection?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true
|
||||
? chatMessageStoreFeature
|
||||
: this._agentOptions?.ChatMessageStoreFactory?.Invoke(new() { SerializedState = default, Features = featureCollection, JsonSerializerOptions = null }),
|
||||
AIContextProvider =
|
||||
featureCollection?.TryGet<AIContextProvider>(out var aIContextProviderFeature) is true
|
||||
? aIContextProviderFeature
|
||||
: this._agentOptions?.AIContextProviderFactory?.Invoke(new() { SerializedState = default, Features = featureCollection, JsonSerializerOptions = null })
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -348,15 +357,21 @@ public sealed partial class ChatClientAgent : AIAgent
|
||||
};
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
Func<JsonElement, JsonSerializerOptions?, ChatMessageStore>? chatMessageStoreFactory = this._agentOptions?.ChatMessageStoreFactory is null ?
|
||||
null :
|
||||
(jse, jso) => this._agentOptions.ChatMessageStoreFactory.Invoke(new() { SerializedState = jse, JsonSerializerOptions = jso });
|
||||
Func<JsonElement, JsonSerializerOptions?, ChatMessageStore>? chatMessageStoreFactory =
|
||||
featureCollection?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true
|
||||
? (jse, jso) => chatMessageStoreFeature
|
||||
: this._agentOptions?.ChatMessageStoreFactory is not null
|
||||
? (jse, jso) => this._agentOptions.ChatMessageStoreFactory.Invoke(new() { SerializedState = jse, Features = featureCollection, JsonSerializerOptions = jso })
|
||||
: null;
|
||||
|
||||
Func<JsonElement, JsonSerializerOptions?, AIContextProvider>? aiContextProviderFactory = this._agentOptions?.AIContextProviderFactory is null ?
|
||||
null :
|
||||
(jse, jso) => this._agentOptions.AIContextProviderFactory.Invoke(new() { SerializedState = jse, JsonSerializerOptions = jso });
|
||||
Func<JsonElement, JsonSerializerOptions?, AIContextProvider>? aiContextProviderFactory =
|
||||
featureCollection?.TryGet<AIContextProvider>(out var aiContextProviderFeature) is true
|
||||
? (jse, jso) => aiContextProviderFeature
|
||||
: this._agentOptions?.AIContextProviderFactory is not null
|
||||
? (jse, jso) => this._agentOptions.AIContextProviderFactory.Invoke(new() { SerializedState = jse, Features = featureCollection, JsonSerializerOptions = jso })
|
||||
: null;
|
||||
|
||||
return new ChatClientAgentThread(
|
||||
serializedThread,
|
||||
@@ -415,7 +430,7 @@ public sealed partial class ChatClientAgent : AIAgent
|
||||
}
|
||||
|
||||
// Only notify the thread of new messages if the chatResponse was successful to avoid inconsistent message state in the thread.
|
||||
await NotifyMessageStoreOfNewMessagesAsync(safeThread, inputMessages.Concat(aiContextProviderMessages ?? []).Concat(chatResponse.Messages), cancellationToken).ConfigureAwait(false);
|
||||
await NotifyMessageStoreOfNewMessagesAsync(safeThread, inputMessages.Concat(aiContextProviderMessages ?? []).Concat(chatResponse.Messages), options, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Notify the AIContextProvider of all new messages.
|
||||
await NotifyAIContextProviderOfSuccessAsync(safeThread, inputMessages, aiContextProviderMessages, chatResponse.Messages, cancellationToken).ConfigureAwait(false);
|
||||
@@ -641,10 +656,19 @@ public sealed partial class ChatClientAgent : AIAgent
|
||||
// Populate the thread messages only if we are not continuing an existing response as it's not allowed
|
||||
if (chatOptions?.ContinuationToken is null)
|
||||
{
|
||||
// Add any existing messages from the thread to the messages to be sent to the chat client.
|
||||
if (typedThread.MessageStore is not null)
|
||||
var messageStore = typedThread.MessageStore;
|
||||
|
||||
// If the caller provided an override message store via run options, we should use that instead of the message store
|
||||
// on the thread.
|
||||
if (runOptions?.Features?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true)
|
||||
{
|
||||
inputMessagesForChatClient.AddRange(await typedThread.MessageStore.GetMessagesAsync(cancellationToken).ConfigureAwait(false));
|
||||
messageStore = chatMessageStoreFeature;
|
||||
}
|
||||
|
||||
// Add any existing messages from the thread to the messages to be sent to the chat client.
|
||||
if (messageStore is not null)
|
||||
{
|
||||
inputMessagesForChatClient.AddRange(await messageStore.GetMessagesAsync(cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
// If we have an AIContextProvider, we should get context from it, and update our
|
||||
@@ -725,10 +749,17 @@ public sealed partial class ChatClientAgent : AIAgent
|
||||
}
|
||||
}
|
||||
|
||||
private static Task NotifyMessageStoreOfNewMessagesAsync(ChatClientAgentThread thread, IEnumerable<ChatMessage> newMessages, CancellationToken cancellationToken)
|
||||
private static Task NotifyMessageStoreOfNewMessagesAsync(ChatClientAgentThread thread, IEnumerable<ChatMessage> newMessages, AgentRunOptions? runOptions, CancellationToken cancellationToken)
|
||||
{
|
||||
var messageStore = thread.MessageStore;
|
||||
|
||||
// If the caller provided an override message store via run options, we should use that instead of the message store
|
||||
// on the thread.
|
||||
if (runOptions?.Features?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true)
|
||||
{
|
||||
messageStore = chatMessageStoreFeature;
|
||||
}
|
||||
|
||||
// Only notify the message store if we have one.
|
||||
// If we don't have one, it means that the chat history is service managed and the underlying service is responsible for storing messages.
|
||||
if (messageStore is not null)
|
||||
|
||||
@@ -92,6 +92,11 @@ public sealed class ChatClientAgentOptions
|
||||
/// Gets or sets the JSON serialization options to use when deserializing the <see cref="SerializedState"/>.
|
||||
/// </summary>
|
||||
public JsonSerializerOptions? JsonSerializerOptions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of features provided by the caller and middleware.
|
||||
/// </summary>
|
||||
public IAgentFeatureCollection? Features { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -109,5 +114,10 @@ public sealed class ChatClientAgentOptions
|
||||
/// Gets or sets the JSON serialization options to use when deserializing the <see cref="SerializedState"/>.
|
||||
/// </summary>
|
||||
public JsonSerializerOptions? JsonSerializerOptions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of features provided by the caller and middleware.
|
||||
/// </summary>
|
||||
public IAgentFeatureCollection? Features { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,24 @@ public sealed class A2AAgentTests : IDisposable
|
||||
Assert.Null(agent.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_WithStringFeature_UsesItForContextId()
|
||||
{
|
||||
// Arrange
|
||||
var contextIdFeature = new ConversationIdAgentFeature("feature-context-id");
|
||||
var agentWithFeature = new A2AAgent(this._a2aClient);
|
||||
|
||||
// Act
|
||||
var features = new AgentFeatureCollection();
|
||||
features.Set(contextIdFeature);
|
||||
var thread = agentWithFeature.GetNewThread(features);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<A2AAgentThread>(thread);
|
||||
var a2aThread = (A2AAgentThread)thread;
|
||||
Assert.Equal(contextIdFeature.ConversationId, a2aThread.ContextId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_AllowsNonUserRoleMessagesAsync()
|
||||
{
|
||||
|
||||
@@ -378,10 +378,10 @@ public class AIAgentTests
|
||||
|
||||
protected override string? IdCore { get; }
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
namespace Microsoft.Agents.AI.Abstractions.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AgentFeatureCollection"/> class.
|
||||
/// </summary>
|
||||
public class AgentFeatureCollectionTests
|
||||
{
|
||||
[Fact]
|
||||
public void Feature_RoundTrips()
|
||||
{
|
||||
// Arrange.
|
||||
var interfaces = new AgentFeatureCollection();
|
||||
var thing = new Thing();
|
||||
|
||||
// Act.
|
||||
interfaces.Set<IThing>(thing);
|
||||
Assert.True(interfaces.TryGet<IThing>(out var actualThing));
|
||||
|
||||
// Assert.
|
||||
Assert.Same(actualThing, thing);
|
||||
Assert.Equal(1, interfaces.Revision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveOfT_Removes()
|
||||
{
|
||||
// Arrange.
|
||||
var interfaces = new AgentFeatureCollection();
|
||||
var thing = new Thing();
|
||||
|
||||
interfaces.Set<IThing>(thing);
|
||||
Assert.True(interfaces.TryGet<IThing>(out _));
|
||||
|
||||
// Act.
|
||||
interfaces.Remove<IThing>();
|
||||
|
||||
// Assert.
|
||||
Assert.False(interfaces.TryGet<IThing>(out _));
|
||||
Assert.Equal(2, interfaces.Revision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_Removes()
|
||||
{
|
||||
// Arrange.
|
||||
var interfaces = new AgentFeatureCollection();
|
||||
var thing = new Thing();
|
||||
|
||||
interfaces.Set<IThing>(thing);
|
||||
Assert.True(interfaces.TryGet<IThing>(out _));
|
||||
|
||||
// Act.
|
||||
interfaces.Remove(typeof(IThing));
|
||||
|
||||
// Assert.
|
||||
Assert.False(interfaces.TryGet<IThing>(out _));
|
||||
Assert.Equal(2, interfaces.Revision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGetMissingFeature_ReturnsFalse()
|
||||
{
|
||||
// Arrange.
|
||||
var interfaces = new AgentFeatureCollection();
|
||||
|
||||
// Act & Assert.
|
||||
Assert.False(interfaces.TryGet<Thing>(out var actualThing));
|
||||
Assert.Null(actualThing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_Null_Throws()
|
||||
{
|
||||
// Arrange.
|
||||
var interfaces = new AgentFeatureCollection();
|
||||
|
||||
// Act & Assert.
|
||||
Assert.Throws<ArgumentNullException>(() => interfaces.Set<IThing>(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsReadOnly_DefaultsToFalse()
|
||||
{
|
||||
// Arrange.
|
||||
var interfaces = new AgentFeatureCollection();
|
||||
|
||||
// Act & Assert.
|
||||
Assert.False(interfaces.IsReadOnly);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGetOfT_FallsBackToInnerCollection()
|
||||
{
|
||||
// Arrange.
|
||||
var inner = new AgentFeatureCollection();
|
||||
var thing = new Thing();
|
||||
inner.Set<IThing>(thing);
|
||||
var outer = new AgentFeatureCollection(inner);
|
||||
|
||||
// Act & Assert.
|
||||
Assert.True(outer.TryGet<IThing>(out var actualThing));
|
||||
Assert.Same(actualThing, thing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGetOfT_OverridesInnerWithOuterCollection()
|
||||
{
|
||||
// Arrange.
|
||||
var inner = new AgentFeatureCollection();
|
||||
var innerThing = new Thing();
|
||||
inner.Set<IThing>(innerThing);
|
||||
|
||||
var outer = new AgentFeatureCollection(inner);
|
||||
var outerThing = new Thing();
|
||||
outer.Set<IThing>(outerThing);
|
||||
|
||||
// Act & Assert.
|
||||
Assert.True(outer.TryGet<IThing>(out var actualThing));
|
||||
Assert.Same(outerThing, actualThing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGet_FallsBackToInnerCollection()
|
||||
{
|
||||
// Arrange.
|
||||
var inner = new AgentFeatureCollection();
|
||||
var thing = new Thing();
|
||||
inner.Set<IThing>(thing);
|
||||
var outer = new AgentFeatureCollection(inner);
|
||||
|
||||
// Act & Assert.
|
||||
Assert.True(outer.TryGet(typeof(IThing), out var actualThing));
|
||||
Assert.Same(actualThing, thing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGet_OverridesInnerWithOuterCollection()
|
||||
{
|
||||
// Arrange.
|
||||
var inner = new AgentFeatureCollection();
|
||||
var innerThing = new Thing();
|
||||
inner.Set<IThing>(innerThing);
|
||||
|
||||
var outer = new AgentFeatureCollection(inner);
|
||||
var outerThing = new Thing();
|
||||
outer.Set<IThing>(outerThing);
|
||||
|
||||
// Act & Assert.
|
||||
Assert.True(outer.TryGet(typeof(IThing), out var actualThing));
|
||||
Assert.Same(outerThing, actualThing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Enumerate_OverridesInnerWithOuterCollection()
|
||||
{
|
||||
// Arrange.
|
||||
var inner = new AgentFeatureCollection();
|
||||
var innerThing = new Thing();
|
||||
inner.Set<IThing>(innerThing);
|
||||
|
||||
var outer = new AgentFeatureCollection(inner);
|
||||
var outerThing = new Thing();
|
||||
outer.Set<IThing>(outerThing);
|
||||
|
||||
// Act.
|
||||
var items = outer.ToList();
|
||||
|
||||
// Assert.
|
||||
Assert.Single(items);
|
||||
Assert.Same(outerThing, items.First().Value as IThing);
|
||||
}
|
||||
|
||||
private interface IThing
|
||||
{
|
||||
string Hello();
|
||||
}
|
||||
|
||||
private sealed class Thing : IThing
|
||||
{
|
||||
public string Hello()
|
||||
{
|
||||
return "World";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,8 @@ public class AgentRunOptionsTests
|
||||
{
|
||||
["key1"] = "value1",
|
||||
["key2"] = 42
|
||||
}
|
||||
},
|
||||
Features = new AgentFeatureCollection()
|
||||
};
|
||||
|
||||
// Act
|
||||
@@ -37,6 +38,7 @@ public class AgentRunOptionsTests
|
||||
Assert.NotSame(options.AdditionalProperties, clone.AdditionalProperties);
|
||||
Assert.Equal("value1", clone.AdditionalProperties["key1"]);
|
||||
Assert.Equal(42, clone.AdditionalProperties["key2"]);
|
||||
Assert.Same(options.Features, clone.Features);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
@@ -35,7 +36,12 @@ public class DelegatingAIAgentTests
|
||||
this._innerAgentMock.Protected().SetupGet<string>("IdCore").Returns("test-agent-id");
|
||||
this._innerAgentMock.Setup(x => x.Name).Returns("Test Agent");
|
||||
this._innerAgentMock.Setup(x => x.Description).Returns("Test Description");
|
||||
this._innerAgentMock.Setup(x => x.GetNewThread()).Returns(this._testThread);
|
||||
this._innerAgentMock.Setup(x => x.GetNewThread(It.IsAny<IAgentFeatureCollection?>())).Returns(this._testThread);
|
||||
this._innerAgentMock.Setup(x => x.DeserializeThread(
|
||||
It.IsAny<JsonElement>(),
|
||||
It.IsAny<JsonSerializerOptions?>(),
|
||||
It.IsAny<IAgentFeatureCollection?>()))
|
||||
.Returns(this._testThread);
|
||||
|
||||
this._innerAgentMock
|
||||
.Protected()
|
||||
@@ -138,11 +144,29 @@ public class DelegatingAIAgentTests
|
||||
public void GetNewThread_DelegatesToInnerAgent()
|
||||
{
|
||||
// Act
|
||||
var thread = this._delegatingAgent.GetNewThread();
|
||||
var featureCollection = new AgentFeatureCollection();
|
||||
var thread = this._delegatingAgent.GetNewThread(featureCollection);
|
||||
|
||||
// Assert
|
||||
Assert.Same(this._testThread, thread);
|
||||
this._innerAgentMock.Verify(x => x.GetNewThread(), Times.Once);
|
||||
this._innerAgentMock.Verify(x => x.GetNewThread(featureCollection), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that DeserializeThread delegates to inner agent.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void DeserializeThread_DelegatesToInnerAgent()
|
||||
{
|
||||
// Act
|
||||
var featureCollection = new AgentFeatureCollection();
|
||||
var jsonElement = new JsonElement();
|
||||
var jso = new JsonSerializerOptions();
|
||||
var thread = this._delegatingAgent.DeserializeThread(jsonElement, jso, featureCollection);
|
||||
|
||||
// Assert
|
||||
Assert.Same(this._testThread, thread);
|
||||
this._innerAgentMock.Verify(x => x.DeserializeThread(jsonElement, jso, featureCollection), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+2
-2
@@ -66,12 +66,12 @@ public sealed class AggregatorPromptAgentFactoryTests
|
||||
|
||||
private sealed class TestAgent : AIAgent
|
||||
{
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
+4
-4
@@ -280,12 +280,12 @@ internal sealed class FakeChatClientAgent : AIAgent
|
||||
|
||||
public override string? Description => "A fake agent for testing";
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread();
|
||||
}
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
@@ -348,12 +348,12 @@ internal sealed class FakeMultiMessageAgent : AIAgent
|
||||
|
||||
public override string? Description => "A fake agent that sends multiple messages for testing";
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread();
|
||||
}
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
|
||||
+2
-2
@@ -334,9 +334,9 @@ internal sealed class FakeForwardedPropsAgent : AIAgent
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread() => new FakeInMemoryAgentThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new FakeInMemoryAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
|
||||
+2
-2
@@ -417,9 +417,9 @@ internal sealed class FakeStateAgent : AIAgent
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread() => new FakeInMemoryAgentThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new FakeInMemoryAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
|
||||
+4
-4
@@ -425,9 +425,9 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests
|
||||
|
||||
public override string? Description => "Agent that produces multiple text chunks";
|
||||
|
||||
public override AgentThread GetNewThread() => new TestInMemoryAgentThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new TestInMemoryAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null) =>
|
||||
new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
@@ -514,9 +514,9 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests
|
||||
|
||||
public override string? Description => "Test agent";
|
||||
|
||||
public override AgentThread GetNewThread() => new TestInMemoryAgentThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new TestInMemoryAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null) =>
|
||||
new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
|
||||
@@ -11,11 +11,12 @@ internal sealed class TestAgent(string name, string description) : AIAgent
|
||||
|
||||
public override string? Description => description;
|
||||
|
||||
public override AgentThread GetNewThread() => new DummyAgentThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new DummyAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(
|
||||
JsonElement serializedThread,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null) => new DummyAgentThread();
|
||||
JsonSerializerOptions? jsonSerializerOptions = null,
|
||||
IAgentFeatureCollection? featureCollection = null) => new DummyAgentThread();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
|
||||
@@ -324,10 +324,10 @@ public class AgentExtensionsTests
|
||||
this._exceptionToThrow = exceptionToThrow;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override string? Name { get; }
|
||||
|
||||
@@ -425,39 +425,6 @@ public partial class ChatClientAgentTests
|
||||
Assert.Equal("ConvId", thread.ConversationId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that RunAsync uses the ChatMessageStore factory when the chat client returns no conversation id.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task RunAsyncUsesChatMessageStoreWhenNoConversationIdReturnedByChatClientAsync()
|
||||
{
|
||||
// Arrange
|
||||
Mock<IChatClient> mockService = new();
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(new InMemoryChatMessageStore());
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "test instructions" },
|
||||
ChatMessageStoreFactory = mockFactory.Object
|
||||
});
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
await agent.RunAsync([new(ChatRole.User, "test")], thread);
|
||||
|
||||
// Assert
|
||||
var messageStore = Assert.IsType<InMemoryChatMessageStore>(thread!.MessageStore);
|
||||
Assert.Equal(2, messageStore.Count);
|
||||
Assert.Equal("test", messageStore[0].Text);
|
||||
Assert.Equal("response", messageStore[1].Text);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that RunAsync uses the default InMemoryChatMessageStore when the chat client returns no conversation id.
|
||||
/// </summary>
|
||||
@@ -522,6 +489,40 @@ public partial class ChatClientAgentTests
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that RunAsync uses the ChatMessageStore provided via run params when the chat client returns no conversation id.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task RunAsyncUsesChatMessageStoreWhenProvidedViaFeaturesAndNoConversationIdReturnedByChatClientAsync()
|
||||
{
|
||||
// Arrange
|
||||
Mock<IChatClient> mockService = new();
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
Mock<ChatMessageStore> mockChatMessageStore = new();
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "test instructions" },
|
||||
});
|
||||
|
||||
AgentFeatureCollection features = new();
|
||||
features.Set(mockChatMessageStore.Object);
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
await agent.RunAsync([new(ChatRole.User, "test")], thread, options: new AgentRunOptions() { Features = features });
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatMessageStore>(thread!.MessageStore, exactMatch: false);
|
||||
mockChatMessageStore.Verify(s => s.GetMessagesAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
mockChatMessageStore.Verify(s => s.AddMessagesAsync(It.Is<IEnumerable<ChatMessage>>(x => x.Count() == 2), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that RunAsync throws when a ChatMessageStore Factory is provided and the chat client returns a conversation id.
|
||||
/// </summary>
|
||||
|
||||
+64
@@ -76,4 +76,68 @@ public class ChatClientAgent_DeserializeThreadTests
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Same(mockMessageStore.Object, typedThread.MessageStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeserializeThread_UsesChatMessageStore_FromFeatureOverload()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var mockMessageStore = new Mock<ChatMessageStore>();
|
||||
var agent = new ChatClientAgent(mockChatClient.Object, new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new ChatOptions { Instructions = "Test instructions" },
|
||||
ChatMessageStoreFactory = _ =>
|
||||
{
|
||||
Assert.Fail("ChatMessageStoreFactory should not have been called.");
|
||||
return null!;
|
||||
}
|
||||
});
|
||||
|
||||
var json = JsonSerializer.Deserialize("""
|
||||
{
|
||||
}
|
||||
""", TestJsonSerializerContext.Default.JsonElement);
|
||||
|
||||
// Act
|
||||
var agentFeatures = new AgentFeatureCollection();
|
||||
agentFeatures.Set(mockMessageStore.Object);
|
||||
var thread = agent.DeserializeThread(json, null, agentFeatures);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Same(mockMessageStore.Object, typedThread.MessageStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeserializeThread_UsesAIContextProvider_FromFeatureOverload()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var mockContextProvider = new Mock<AIContextProvider>();
|
||||
var agent = new ChatClientAgent(mockChatClient.Object, new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new ChatOptions { Instructions = "Test instructions" },
|
||||
AIContextProviderFactory = _ =>
|
||||
{
|
||||
Assert.Fail("AIContextProviderFactory should not have been called.");
|
||||
return null!;
|
||||
}
|
||||
});
|
||||
|
||||
var json = JsonSerializer.Deserialize("""
|
||||
{
|
||||
}
|
||||
""", TestJsonSerializerContext.Default.JsonElement);
|
||||
|
||||
// Act
|
||||
var agentFeatures = new AgentFeatureCollection();
|
||||
agentFeatures.Set(mockContextProvider.Object);
|
||||
var thread = agent.DeserializeThread(json, null, agentFeatures);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Same(mockContextProvider.Object, typedThread.AIContextProvider);
|
||||
}
|
||||
}
|
||||
|
||||
+76
@@ -1,5 +1,6 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Moq;
|
||||
|
||||
@@ -97,4 +98,79 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Equal(TestConversationId, typedThread.ConversationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_UsesConversationId_FromFeatureOverload()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var testConversationId = new ConversationIdAgentFeature("test_conversation_id");
|
||||
var agent = new ChatClientAgent(mockChatClient.Object);
|
||||
|
||||
// Act
|
||||
var agentFeatures = new AgentFeatureCollection();
|
||||
agentFeatures.Set(testConversationId);
|
||||
var thread = agent.GetNewThread(agentFeatures);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Equal(testConversationId.ConversationId, typedThread.ConversationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_UsesChatMessageStore_FromFeatureOverload()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var mockMessageStore = new Mock<ChatMessageStore>();
|
||||
var agent = new ChatClientAgent(mockChatClient.Object);
|
||||
|
||||
// Act
|
||||
var agentFeatures = new AgentFeatureCollection();
|
||||
agentFeatures.Set(mockMessageStore.Object);
|
||||
var thread = agent.GetNewThread(agentFeatures);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Same(mockMessageStore.Object, typedThread.MessageStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_UsesAIContextProvider_FromFeatureOverload()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var mockContextProvider = new Mock<AIContextProvider>();
|
||||
var agent = new ChatClientAgent(mockChatClient.Object);
|
||||
|
||||
// Act
|
||||
var agentFeatures = new AgentFeatureCollection();
|
||||
agentFeatures.Set(mockContextProvider.Object);
|
||||
var thread = agent.GetNewThread(agentFeatures);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
var typedThread = (ChatClientAgentThread)thread;
|
||||
Assert.Same(mockContextProvider.Object, typedThread.AIContextProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_Throws_IfBothConversationIdAndMessageStoreAreSet()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var mockMessageStore = new Mock<ChatMessageStore>();
|
||||
var testConversationId = new ConversationIdAgentFeature("test_conversation_id");
|
||||
var agent = new ChatClientAgent(mockChatClient.Object);
|
||||
|
||||
// Act & Assert
|
||||
var agentFeatures = new AgentFeatureCollection();
|
||||
agentFeatures.Set(mockMessageStore.Object);
|
||||
agentFeatures.Set(testConversationId);
|
||||
|
||||
var exception = Assert.Throws<InvalidOperationException>(() => agent.GetNewThread(agentFeatures));
|
||||
Assert.Equal("Only the ConversationId or MessageStore may be set, but not both and switching from one to another is not supported.", exception.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,10 +24,10 @@ internal sealed class TestAIAgent : AIAgent
|
||||
|
||||
public override string? Description => this.DescriptionFunc?.Invoke() ?? base.Description;
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null) =>
|
||||
this.DeserializeThreadFunc(serializedThread, jsonSerializerOptions);
|
||||
|
||||
public override AgentThread GetNewThread() =>
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) =>
|
||||
this.GetNewThreadFunc();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
|
||||
@@ -135,10 +135,10 @@ public class AgentWorkflowBuilderTests
|
||||
{
|
||||
public override string Name => name;
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new DoubleEchoAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new DoubleEchoAgentThread();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
|
||||
@@ -144,10 +144,12 @@ public class InProcessExecutionTests
|
||||
|
||||
public override string Name { get; }
|
||||
|
||||
public override AgentThread GetNewThread() => new SimpleTestAgentThread();
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null) => new SimpleTestAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(System.Text.Json.JsonElement serializedThread,
|
||||
System.Text.Json.JsonSerializerOptions? jsonSerializerOptions = null) => new SimpleTestAgentThread();
|
||||
public override AgentThread DeserializeThread(
|
||||
System.Text.Json.JsonElement serializedThread,
|
||||
System.Text.Json.JsonSerializerOptions? jsonSerializerOptions = null,
|
||||
IAgentFeatureCollection? featureCollection = null) => new SimpleTestAgentThread();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
|
||||
@@ -24,10 +24,10 @@ public class RepresentationTests
|
||||
|
||||
private sealed class TestAgent : AIAgent
|
||||
{
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
|
||||
+2
-2
@@ -60,10 +60,10 @@ internal sealed class HelloAgent(string id = nameof(HelloAgent)) : AIAgent
|
||||
protected override string? IdCore => id;
|
||||
public override string? Name => id;
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new HelloAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new HelloAgentThread();
|
||||
|
||||
protected override async Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
|
||||
+2
-2
@@ -51,10 +51,10 @@ public class SpecializedExecutorSmokeTests
|
||||
return result;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
=> new TestAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
=> new TestAgentThread();
|
||||
|
||||
public static TestAIAgent FromStrings(params string[] messages) =>
|
||||
|
||||
@@ -16,12 +16,12 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre
|
||||
protected override string? IdCore => id;
|
||||
public override string? Name => name ?? base.Name;
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return serializedThread.Deserialize<EchoAgentThread>(jsonSerializerOptions) ?? this.GetNewThread();
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
|
||||
{
|
||||
return new EchoAgentThread();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user