diff --git a/.github/upgrades/prompts/SemanticKernelToAgentFramework.md b/.github/upgrades/prompts/SemanticKernelToAgentFramework.md index 44985bba98..6ff0984609 100644 --- a/.github/upgrades/prompts/SemanticKernelToAgentFramework.md +++ b/.github/upgrades/prompts/SemanticKernelToAgentFramework.md @@ -105,7 +105,7 @@ After completing migration, verify these specific items: 1. **Compilation**: Execute `dotnet build` on all modified projects - zero errors required 2. **Namespace Updates**: Confirm all `using Microsoft.SemanticKernel.Agents` statements are replaced 3. **Method Calls**: Verify all `InvokeAsync` calls are changed to `RunAsync` -4. **Return Types**: Confirm handling of `AgentRunResponse` instead of `IAsyncEnumerable>` +4. **Return Types**: Confirm handling of `AgentResponse` instead of `IAsyncEnumerable>` 5. **Thread Creation**: Validate all thread creation uses `agent.GetNewThread()` pattern 6. **Tool Registration**: Ensure `[KernelFunction]` attributes are removed and `AIFunctionFactory.Create()` is used 7. **Options Configuration**: Verify `AgentRunOptions` or `ChatClientAgentRunOptions` replaces `AgentInvokeOptions` @@ -119,7 +119,7 @@ Agent Framework provides functionality for creating and managing AI agents throu Key API differences: - Agent creation: Remove Kernel dependency, use direct client-based creation - Method names: `InvokeAsync` → `RunAsync`, `InvokeStreamingAsync` → `RunStreamingAsync` -- Return types: `IAsyncEnumerable>` → `AgentRunResponse` +- Return types: `IAsyncEnumerable>` → `AgentResponse` - Thread creation: Provider-specific constructors → `agent.GetNewThread()` - Tool registration: `KernelPlugin` system → Direct `AIFunction` registration - Options: `AgentInvokeOptions` → Provider-specific run options (e.g., `ChatClientAgentRunOptions`) @@ -166,8 +166,8 @@ Replace these method calls: | `thread.DeleteAsync()` | Provider-specific cleanup | Use provider client directly | Return type changes: -- `IAsyncEnumerable>` → `AgentRunResponse` -- `IAsyncEnumerable` → `IAsyncEnumerable` +- `IAsyncEnumerable>` → `AgentResponse` +- `IAsyncEnumerable` → `IAsyncEnumerable` @@ -191,8 +191,8 @@ Agent Framework changes these behaviors compared to Semantic Kernel Agents: 1. **Thread Management**: Agent Framework automatically manages thread state. Semantic Kernel required manual thread updates in some scenarios (e.g., OpenAI Responses). 2. **Return Types**: - - Non-streaming: Returns single `AgentRunResponse` instead of `IAsyncEnumerable>` - - Streaming: Returns `IAsyncEnumerable` instead of `IAsyncEnumerable` + - Non-streaming: Returns single `AgentResponse` instead of `IAsyncEnumerable>` + - Streaming: Returns `IAsyncEnumerable` instead of `IAsyncEnumerable` 3. **Tool Registration**: Agent Framework uses direct function registration without requiring `[KernelFunction]` attributes. @@ -397,7 +397,7 @@ await foreach (AgentResponseItem item in agent.InvokeAsync(u **With this Agent Framework non-streaming pattern:** ```csharp -AgentRunResponse result = await agent.RunAsync(userInput, thread, options); +AgentResponse result = await agent.RunAsync(userInput, thread, options); Console.WriteLine(result); ``` @@ -411,7 +411,7 @@ await foreach (StreamingChatMessageContent update in agent.InvokeStreamingAsync( **With this Agent Framework streaming pattern:** ```csharp -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(userInput, thread, options)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(userInput, thread, options)) { Console.Write(update); } @@ -420,8 +420,8 @@ await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(userInpu **Required changes:** 1. Replace `agent.InvokeAsync()` with `agent.RunAsync()` 2. Replace `agent.InvokeStreamingAsync()` with `agent.RunStreamingAsync()` -3. Change return type handling from `IAsyncEnumerable>` to `AgentRunResponse` -4. Change streaming type from `StreamingChatMessageContent` to `AgentRunResponseUpdate` +3. Change return type handling from `IAsyncEnumerable>` to `AgentResponse` +4. Change streaming type from `StreamingChatMessageContent` to `AgentResponseUpdate` 5. Remove `await foreach` for non-streaming calls 6. Access message content directly from result object instead of iterating @@ -661,7 +661,7 @@ await foreach (var result in agent.InvokeAsync(input, thread, options)) ```csharp ChatClientAgentRunOptions options = new(new ChatOptions { MaxOutputTokens = 1000 }); -AgentRunResponse result = await agent.RunAsync(input, thread, options); +AgentResponse result = await agent.RunAsync(input, thread, options); Console.WriteLine(result); // Access underlying content when needed: @@ -689,7 +689,7 @@ await foreach (var result in agent.InvokeAsync(input, thread, options)) **With this Agent Framework non-streaming usage pattern:** ```csharp -AgentRunResponse result = await agent.RunAsync(input, thread, options); +AgentResponse result = await agent.RunAsync(input, thread, options); Console.WriteLine($"Tokens: {result.Usage.TotalTokenCount}"); ``` @@ -709,7 +709,7 @@ await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsyn **With this Agent Framework streaming usage pattern:** ```csharp -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(input, thread, options)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, thread, options)) { if (update.Contents.OfType().FirstOrDefault() is { } usageContent) { diff --git a/docs/decisions/0001-agent-run-response.md b/docs/decisions/0001-agent-run-response.md index 9f13af787c..6f3385e1a1 100644 --- a/docs/decisions/0001-agent-run-response.md +++ b/docs/decisions/0001-agent-run-response.md @@ -163,8 +163,8 @@ foreach (var update in response.Messages) ### Option 2 Run: Container with Primary and Secondary Properties, RunStreaming: Stream of Primary + Secondary Run returns a new response type that has separate properties for the Primary Content and the Secondary Updates leading up to it. -The Primary content is available in the `AgentRunResponse.Messages` property while Secondary updates are in a new `AgentRunResponse.Updates` property. -`AgentRunResponse.Text` returns the Primary content text. +The Primary content is available in the `AgentResponse.Messages` property while Secondary updates are in a new `AgentResponse.Updates` property. +`AgentResponse.Text` returns the Primary content text. Since streaming would still need to return an `IAsyncEnumerable` of updates, the design would differ from non-streaming. With non-streaming Primary and Secondary content is split into separate lists, while with streaming it's combined in one stream. @@ -232,24 +232,24 @@ await foreach (var update in responses) ```csharp class Agent { - public abstract Task RunAsync( + public abstract Task RunAsync( IReadOnlyCollection messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default); - public abstract IAsyncEnumerable RunStreamingAsync( + public abstract IAsyncEnumerable RunStreamingAsync( IReadOnlyCollection messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default); } -class AgentRunResponse : ChatResponse +class AgentResponse : ChatResponse { } -public class AgentRunResponseUpdate : ChatResponseUpdate +public class AgentResponseUpdate : ChatResponseUpdate { } ``` @@ -265,20 +265,20 @@ The new types could also exclude properties that make less sense for agents, lik ```csharp class Agent { - public abstract Task RunAsync( + public abstract Task RunAsync( IReadOnlyCollection messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default); - public abstract IAsyncEnumerable RunStreamingAsync( + public abstract IAsyncEnumerable RunStreamingAsync( IReadOnlyCollection messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default); } -class AgentRunResponse // Compare with ChatResponse +class AgentResponse // Compare with ChatResponse { public string Text { get; } // Aggregation of TextContent from messages. @@ -294,12 +294,12 @@ class AgentRunResponse // Compare with ChatResponse public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } } -// Not Included in AgentRunResponse compared to ChatResponse +// Not Included in AgentResponse compared to ChatResponse public ChatFinishReason? FinishReason { get; set; } public string? ConversationId { get; set; } public string? ModelId { get; set; } -public class AgentRunResponseUpdate // Compare with ChatResponseUpdate +public class AgentResponseUpdate // Compare with ChatResponseUpdate { public string Text { get; } // Aggregation of TextContent from Contents. @@ -317,7 +317,7 @@ public class AgentRunResponseUpdate // Compare with ChatResponseUpdate public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } } -// Not Included in AgentRunResponseUpdate compared to ChatResponseUpdate +// Not Included in AgentResponseUpdate compared to ChatResponseUpdate public ChatFinishReason? FinishReason { get; set; } public string? ConversationId { get; set; } public string? ModelId { get; set; } @@ -360,7 +360,7 @@ public class ChatFinishReason ### Option 2: Add another property on responses for AgentRun ```csharp -class AgentRunResponse +class AgentResponse { ... public AgentRun RunReference { get; set; } // Reference to long running process @@ -368,7 +368,7 @@ class AgentRunResponse } -public class AgentRunResponseUpdate +public class AgentResponseUpdate { ... public AgentRun RunReference { get; set; } // Reference to long running process @@ -424,7 +424,7 @@ Note that where an agent doesn't support structured output, it may also be possi See [Structured Outputs Support](#structured-outputs-support) for a comparison on what other agent frameworks and protocols support. To support a good user experience for structured outputs, I'm proposing that we follow the pattern used by MEAI. -We would add a generic version of `AgentRunResponse`, that allows us to get the agent result already deserialized into our preferred type. +We would add a generic version of `AgentResponse`, that allows us to get the agent result already deserialized into our preferred type. This would be coupled with generic overload extension methods for Run that automatically builds a schema from the supplied type and updates the run options. @@ -438,14 +438,14 @@ class Movie public int ReleaseYear { get; set; } } -AgentRunResponse response = agent.RunAsync("What are the top 3 children's movies of the 80s."); +AgentResponse response = agent.RunAsync("What are the top 3 children's movies of the 80s."); Movie[] movies = response.Result ``` If we only support requesting a schema at agent creation time or where an agent has a built in schema, the following would be the preferred approach: ```csharp -AgentRunResponse response = agent.RunAsync("What are the top 3 children's movies of the 80s."); +AgentResponse response = agent.RunAsync("What are the top 3 children's movies of the 80s."); Movie[] movies = response.TryParseStructuredOutput(); ``` @@ -463,7 +463,7 @@ Option 2 chosen so that we can vary Agent responses independently of Chat Client ### StructuredOutputs Decision We will not support structured output per run request, but individual agents are free to allow this on the concrete implementation or at construction time. -We will however add support for easily extracting a structured output type from the `AgentRunResponse`. +We will however add support for easily extracting a structured output type from the `AgentResponse`. ## Addendum 1: AIContext Derived Types for different response types / Gap Analysis (Work in progress) diff --git a/docs/decisions/0005-python-naming-conventions.md b/docs/decisions/0005-python-naming-conventions.md index d82cad16ab..3a79b98f91 100644 --- a/docs/decisions/0005-python-naming-conventions.md +++ b/docs/decisions/0005-python-naming-conventions.md @@ -54,7 +54,7 @@ The table below represents the majority of the naming changes discussed in issue | *Mcp* & *Http* | *MCP* & *HTTP* | accepted | Acronyms should be uppercased in class names, according to PEP 8. | None | | `agent.run_streaming` | `agent.run_stream` | accepted | Shorter and more closely aligns with AutoGen and Semantic Kernel names for the same methods. | None | | `workflow.run_streaming` | `workflow.run_stream` | accepted | In sync with `agent.run_stream` and shorter and more closely aligns with AutoGen and Semantic Kernel names for the same methods. | None | -| AgentRunResponse & AgentRunResponseUpdate | AgentResponse & AgentResponseUpdate | rejected | Rejected, because it is the response to a run invocation and AgentResponse is too generic. | None | +| AgentResponse & AgentResponseUpdate | AgentResponse & AgentResponseUpdate | rejected | Rejected, because it is the response to a run invocation and AgentResponse is too generic. | None | | *Content | * | rejected | Rejected other content type renames (removing `Content` suffix) because it would reduce clarity and discoverability. | Item was also considered, but rejected as it is very similar to Content, but would be inconsistent with dotnet. | | ChatResponse & ChatResponseUpdate | Response & ResponseUpdate | rejected | Rejected, because Response is too generic. | None | diff --git a/docs/decisions/0006-userapproval.md b/docs/decisions/0006-userapproval.md index 63ca8bc0fb..7823ab4de4 100644 --- a/docs/decisions/0006-userapproval.md +++ b/docs/decisions/0006-userapproval.md @@ -161,11 +161,11 @@ while (response.ApprovalRequests.Count > 0) response = await agent.RunAsync(messages, thread); } -class AgentRunResponse +class AgentResponse { ... - // A new property on AgentRunResponse to aggregate the ApprovalRequestContent items from + // A new property on AgentResponse to aggregate the ApprovalRequestContent items from // the response messages (Similar to the Text property). public IEnumerable ApprovalRequests { get; set; } @@ -251,11 +251,11 @@ while (response.UserInputRequests.Any()) response = await agent.RunAsync(messages, thread); } -class AgentRunResponse +class AgentResponse { ... - // A new property on AgentRunResponse to aggregate the UserInputRequestContent items from + // A new property on AgentResponse to aggregate the UserInputRequestContent items from // the response messages (Similar to the Text property). public IReadOnlyList UserInputRequests { get; set; } @@ -366,11 +366,11 @@ while (response.UserInputRequests.Any()) response = await agent.RunAsync(messages, thread); } -class AgentRunResponse +class AgentResponse { ... - // A new property on AgentRunResponse to aggregate the UserInputRequestContent items from + // A new property on AgentResponse to aggregate the UserInputRequestContent items from // the response messages (Similar to the Text property). public IEnumerable UserInputRequests { get; set; } diff --git a/docs/decisions/0007-agent-filtering-middleware.md b/docs/decisions/0007-agent-filtering-middleware.md index 3855e8a9c8..dbdd6d37d1 100644 --- a/docs/decisions/0007-agent-filtering-middleware.md +++ b/docs/decisions/0007-agent-filtering-middleware.md @@ -115,7 +115,7 @@ public class AIAgent } } - public async Task RunAsync( + public async Task RunAsync( IReadOnlyCollection messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -135,7 +135,7 @@ public class AIAgent return context.Response ?? throw new InvalidOperationException("Agent execution did not produce a response"); } - protected abstract Task ExecuteCoreLogicAsync( + protected abstract Task ExecuteCoreLogicAsync( IReadOnlyCollection messages, AgentThread? thread, AgentRunOptions? options, @@ -190,7 +190,7 @@ internal sealed class GuardrailCallbackAgent : DelegatingAIAgent public GuardrailCallbackAgent(AIAgent innerAgent) : base(innerAgent) { } - public override async Task RunAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + public override async Task RunAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { var filteredMessages = this.FilterMessages(messages); Console.WriteLine($"Guardrail Middleware - Filtered messages: {new ChatResponse(filteredMessages).Text}"); @@ -202,14 +202,14 @@ internal sealed class GuardrailCallbackAgent : DelegatingAIAgent return response; } - public override async IAsyncEnumerable RunStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public override async IAsyncEnumerable RunStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { var filteredMessages = this.FilterMessages(messages); await foreach (var update in this.InnerAgent.RunStreamingAsync(filteredMessages, thread, options, cancellationToken)) { if (update.Text != null) { - yield return new AgentRunResponseUpdate(update.Role, this.FilterContent(update.Text)); + yield return new AgentResponseUpdate(update.Role, this.FilterContent(update.Text)); } else { @@ -252,7 +252,7 @@ internal sealed class RunningCallbackHandlerAgent : DelegatingAIAgent this._func = func; } - public override async Task RunAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + public override async Task RunAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { var context = new AgentInvokeCallbackContext(this, messages, thread, options, isStreaming: false, cancellationToken); @@ -469,7 +469,7 @@ public sealed class CallbackEnabledAgent : DelegatingAIAgent this._callbacksProcessor = callbackMiddlewareProcessor ?? new(); } - public override async Task RunAsync( + public override async Task RunAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -541,7 +541,7 @@ public abstract class AgentContext public class AgentRunContext : AgentContext { public IList Messages { get; set; } - public AgentRunResponse? Response { get; set; } + public AgentResponse? Response { get; set; } public AgentThread? Thread { get; } public AgentRunContext(AIAgent agent, IList messages, AgentThread? thread, AgentRunOptions? options) diff --git a/docs/decisions/0009-support-long-running-operations.md b/docs/decisions/0009-support-long-running-operations.md index 7227840c8f..a62a038553 100644 --- a/docs/decisions/0009-support-long-running-operations.md +++ b/docs/decisions/0009-support-long-running-operations.md @@ -687,7 +687,7 @@ This section considers different options for exposing the `RunId`, `Status`, and #### 4.1. As AIContent The `AsyncRunContent` class will represent a long-running operation initiated and managed by an agent/LLM. -Items of this content type will be returned in a chat message as part of the `AgentRunResponse` or `ChatResponse` +Items of this content type will be returned in a chat message as part of the `AgentResponse` or `ChatResponse` response to represent the long-running operation. The `AsyncRunContent` class has two properties: `RunId` and `Status`. The `RunId` identifies the @@ -1162,29 +1162,29 @@ For cancellation and deletion of long-running operations, new methods will be ad public abstract class AIAgent { // Existing methods... - public Task RunAsync(string message, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { ... } - public IAsyncEnumerable RunStreamingAsync(string message, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { ... } + public Task RunAsync(string message, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { ... } + public IAsyncEnumerable RunStreamingAsync(string message, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { ... } // New methods for uncommon operations - public virtual Task CancelRunAsync(string id, AgentCancelRunOptions? options = null, CancellationToken cancellationToken = default) + public virtual Task CancelRunAsync(string id, AgentCancelRunOptions? options = null, CancellationToken cancellationToken = default) { - return Task.FromResult(null); + return Task.FromResult(null); } - public virtual Task DeleteRunAsync(string id, AgentDeleteRunOptions? options = null, CancellationToken cancellationToken = default) + public virtual Task DeleteRunAsync(string id, AgentDeleteRunOptions? options = null, CancellationToken cancellationToken = default) { - return Task.FromResult(null); + return Task.FromResult(null); } } // Agent that supports update and cancellation public class CustomAgent : AIAgent { - public override async Task CancelRunAsync(string id, AgentCancelRunOptions? options = null, CancellationToken cancellationToken = default) + public override async Task CancelRunAsync(string id, AgentCancelRunOptions? options = null, CancellationToken cancellationToken = default) { var response = await this._client.CancelRunAsync(id, options?.Thread?.ConversationId); - return ConvertToAgentRunResponse(response); + return ConvertToAgentResponse(response); } // No overload for DeleteRunAsync as it's not supported by the underlying API @@ -1195,7 +1195,7 @@ AIAgent agent = new CustomAgent(); AgentThread thread = agent.GetNewThread(); -AgentRunResponse response = await agent.RunAsync("What is the capital of France?"); +AgentResponse response = await agent.RunAsync("What is the capital of France?"); response = await agent.CancelRunAsync(response.ResponseId, new AgentCancelRunOptions { Thread = thread }); ``` @@ -1251,10 +1251,10 @@ public class AgentRunOptions AIAgent agent = ...; // Get an instance of an AIAgent // Start a long-running execution for the prompt if supported by the underlying API -AgentRunResponse response = await agent.RunAsync("", new AgentRunOptions { AllowLongRunningResponses = true }); +AgentResponse response = await agent.RunAsync("", new AgentRunOptions { AllowLongRunningResponses = true }); // Start a quick prompt -AgentRunResponse response = await agent.RunAsync(""); +AgentResponse response = await agent.RunAsync(""); ``` **Pros:** @@ -1279,7 +1279,7 @@ Below are the details of the option selected for chat clients that is also selec #### 3.1 Continuation Token of a Custom Type This option suggests using `ContinuationToken` to encapsulate all properties representing a long-running operation. The continuation token will be returned by agents in the -`ContinuationToken` property of the `AgentRunResponse` and `AgentRunResponseUpdate` responses to indicate that the response is part of a long-running operation. A null value +`ContinuationToken` property of the `AgentResponse` and `AgentResponseUpdate` responses to indicate that the response is part of a long-running operation. A null value of the property will indicate that the response is not part of a long-running operation or the long-running operation has been completed. Callers will set the token in the `ContinuationToken` property of the `AgentRunOptions` class in follow-up calls to the `Run{Streaming}Async` methods to indicate that they want to "continue" the long-running operation identified by the token. @@ -1313,18 +1313,18 @@ public class AgentRunOptions public ResponseContinuationToken? ContinuationToken { get; set; } } -public class AgentRunResponse +public class AgentResponse { public ResponseContinuationToken? ContinuationToken { get; } } -public class AgentRunResponseUpdate +public class AgentResponseUpdate { public ResponseContinuationToken? ContinuationToken { get; } } // Usage example -AgentRunResponse response = await agent.RunAsync("What is the capital of France?"); +AgentResponse response = await agent.RunAsync("What is the capital of France?"); AgentRunOptions options = new() { ContinuationToken = response.ContinuationToken }; diff --git a/docs/decisions/0010-ag-ui-support.md b/docs/decisions/0010-ag-ui-support.md index 8d9475bb5a..e1d46e9eff 100644 --- a/docs/decisions/0010-ag-ui-support.md +++ b/docs/decisions/0010-ag-ui-support.md @@ -36,7 +36,7 @@ Chosen option: "Current approach with internal event types and framework-native - Protects consumers from protocol changes by keeping AG-UI events internal - Maintains framework abstractions through conversion at boundaries -- Uses existing framework types (AgentRunResponseUpdate, ChatMessage) for public API +- Uses existing framework types (AgentResponseUpdate, ChatMessage) for public API - Focuses on core text streaming functionality - Leverages existing properties (ConversationId, ResponseId, ErrorContent) instead of custom types - Provides bidirectional client and server support @@ -69,7 +69,7 @@ Chosen option: "Current approach with internal event types and framework-native 3. **Agent Factory Pattern** - `MapAGUIAgent` uses factory function `(messages) => AIAgent` to allow request-specific agent configuration supporting multi-tenancy -4. **Bidirectional Conversion Architecture** - Symmetric conversion logic in shared namespace compiled into both packages for server (`AgentRunResponseUpdate` → AG-UI events) and client (AG-UI events → `AgentRunResponseUpdate`) +4. **Bidirectional Conversion Architecture** - Symmetric conversion logic in shared namespace compiled into both packages for server (`AgentResponseUpdate` → AG-UI events) and client (AG-UI events → `AgentResponseUpdate`) 5. **Thread Management** - `AGUIAgentThread` stores only `ThreadId` with thread ID communicated via `ConversationId`; applications manage persistence for parity with other implementations and to be compliant with the protocol. Future extensions will support having the server manage the conversation. diff --git a/docs/specs/001-foundry-sdk-alignment.md b/docs/specs/001-foundry-sdk-alignment.md index 1bbe879be8..b7b780c35f 100644 --- a/docs/specs/001-foundry-sdk-alignment.md +++ b/docs/specs/001-foundry-sdk-alignment.md @@ -125,7 +125,7 @@ The proposed solution is to add helper methods which allow developers to either - [Foundry SDK] Create a `PersistentAgentsClient` - [Foundry SDK] Create a `PersistentAgent` using the `PersistentAgentsClient` - [Foundry SDK] Retrieve an `AIAgent` using the `PersistentAgentsClient` -- [Agent Framework SDK] Invoke the `AIAgent` instance and access response from the `AgentRunResponse` +- [Agent Framework SDK] Invoke the `AIAgent` instance and access response from the `AgentResponse` - [Foundry SDK] Clean up the agent @@ -156,7 +156,7 @@ await persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id); - [Foundry SDK] Create a `PersistentAgentsClient` - [Foundry SDK] Create a `AIAgent` using the `PersistentAgentsClient` -- [Agent Framework SDK] Invoke the `AIAgent` instance and access response from the `AgentRunResponse` +- [Agent Framework SDK] Invoke the `AIAgent` instance and access response from the `AgentResponse` - [Foundry SDK] Clean up the agent ```csharp @@ -184,7 +184,7 @@ await persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id); - [Foundry SDK] Create a `PersistentAgentsClient` - [Foundry SDK] Create a `AIAgent` using the `PersistentAgentsClient` - [Agent Framework SDK] Optionally create an `AgentThread` for the agent run -- [Agent Framework SDK] Invoke the `AIAgent` instance and access response from the `AgentRunResponse` +- [Agent Framework SDK] Invoke the `AIAgent` instance and access response from the `AgentResponse` - [Foundry SDK] Clean up the agent and the agent thread ```csharp @@ -227,7 +227,7 @@ await persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id); - [Foundry SDK] Create a `PersistentAgentsClient` - [Foundry SDK] Create multiple `AIAgent` instances using the `PersistentAgentsClient` - [Agent Framework SDK] Create a `SequentialOrchestration` and add all of the agents to it -- [Agent Framework SDK] Invoke the `SequentialOrchestration` instance and access response from the `AgentRunResponse` +- [Agent Framework SDK] Invoke the `SequentialOrchestration` instance and access response from the `AgentResponse` - [Foundry SDK] Clean up the agents ```csharp @@ -281,7 +281,7 @@ SequentialOrchestration orchestration = // Run the orchestration string input = "An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours"; Console.WriteLine($"\n# INPUT: {input}\n"); -AgentRunResponse result = await orchestration.RunAsync(input); +AgentResponse result = await orchestration.RunAsync(input); Console.WriteLine($"\n# RESULT: {result}"); // Cleanup diff --git a/dotnet/samples/AGUIClientServer/AGUIClient/Program.cs b/dotnet/samples/AGUIClientServer/AGUIClient/Program.cs index 0d461f92af..a4bec13009 100644 --- a/dotnet/samples/AGUIClientServer/AGUIClient/Program.cs +++ b/dotnet/samples/AGUIClientServer/AGUIClient/Program.cs @@ -114,7 +114,7 @@ public static class Program bool isFirstUpdate = true; string? threadId = null; var updates = new List(); - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread, cancellationToken: cancellationToken)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread, cancellationToken: cancellationToken)) { // Use AsChatResponseUpdate to access ChatResponseUpdate properties ChatResponseUpdate chatUpdate = update.AsChatResponseUpdate(); diff --git a/dotnet/samples/AGUIClientServer/AGUIDojoServer/AgenticUI/AgenticUIAgent.cs b/dotnet/samples/AGUIClientServer/AGUIDojoServer/AgenticUI/AgenticUIAgent.cs index d79787d260..da082483db 100644 --- a/dotnet/samples/AGUIClientServer/AGUIDojoServer/AgenticUI/AgenticUIAgent.cs +++ b/dotnet/samples/AGUIClientServer/AGUIDojoServer/AgenticUI/AgenticUIAgent.cs @@ -19,12 +19,12 @@ internal sealed class AgenticUIAgent : DelegatingAIAgent this._jsonSerializerOptions = jsonSerializerOptions; } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentRunResponseAsync(cancellationToken); + return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -69,7 +69,7 @@ internal sealed class AgenticUIAgent : DelegatingAIAgent yield return update; - yield return new AgentRunResponseUpdate( + yield return new AgentResponseUpdate( new ChatResponseUpdate(role: ChatRole.System, stateEventsToEmit) { MessageId = "delta_" + Guid.NewGuid().ToString("N"), diff --git a/dotnet/samples/AGUIClientServer/AGUIDojoServer/PredictiveStateUpdates/PredictiveStateUpdatesAgent.cs b/dotnet/samples/AGUIClientServer/AGUIDojoServer/PredictiveStateUpdates/PredictiveStateUpdatesAgent.cs index ab9ca2fca3..2e994d8e29 100644 --- a/dotnet/samples/AGUIClientServer/AGUIDojoServer/PredictiveStateUpdates/PredictiveStateUpdatesAgent.cs +++ b/dotnet/samples/AGUIClientServer/AGUIDojoServer/PredictiveStateUpdates/PredictiveStateUpdatesAgent.cs @@ -20,12 +20,12 @@ internal sealed class PredictiveStateUpdatesAgent : DelegatingAIAgent this._jsonSerializerOptions = jsonSerializerOptions; } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentRunResponseAsync(cancellationToken); + return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -79,7 +79,7 @@ internal sealed class PredictiveStateUpdatesAgent : DelegatingAIAgent stateUpdate, this._jsonSerializerOptions.GetTypeInfo(typeof(DocumentState))); - yield return new AgentRunResponseUpdate( + yield return new AgentResponseUpdate( new ChatResponseUpdate(role: ChatRole.Assistant, [new DataContent(stateBytes, "application/json")]) { MessageId = "snapshot" + Guid.NewGuid().ToString("N"), diff --git a/dotnet/samples/AGUIClientServer/AGUIDojoServer/SharedState/SharedStateAgent.cs b/dotnet/samples/AGUIClientServer/AGUIDojoServer/SharedState/SharedStateAgent.cs index 1a1e58860a..36a629dd56 100644 --- a/dotnet/samples/AGUIClientServer/AGUIDojoServer/SharedState/SharedStateAgent.cs +++ b/dotnet/samples/AGUIClientServer/AGUIDojoServer/SharedState/SharedStateAgent.cs @@ -19,12 +19,12 @@ internal sealed class SharedStateAgent : DelegatingAIAgent this._jsonSerializerOptions = jsonSerializerOptions; } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentRunResponseAsync(cancellationToken); + return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -63,7 +63,7 @@ internal sealed class SharedStateAgent : DelegatingAIAgent var firstRunMessages = messages.Append(stateUpdateMessage); - var allUpdates = new List(); + var allUpdates = new List(); await foreach (var update in this.InnerAgent.RunStreamingAsync(firstRunMessages, thread, firstRunOptions, cancellationToken).ConfigureAwait(false)) { allUpdates.Add(update); @@ -76,14 +76,14 @@ internal sealed class SharedStateAgent : DelegatingAIAgent } } - var response = allUpdates.ToAgentRunResponse(); + var response = allUpdates.ToAgentResponse(); if (response.TryDeserialize(this._jsonSerializerOptions, out JsonElement stateSnapshot)) { byte[] stateBytes = JsonSerializer.SerializeToUtf8Bytes( stateSnapshot, this._jsonSerializerOptions.GetTypeInfo(typeof(JsonElement))); - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { Contents = [new DataContent(stateBytes, "application/json")] }; diff --git a/dotnet/samples/AGUIClientServer/README.md b/dotnet/samples/AGUIClientServer/README.md index b0ad2265d0..d624c6f4b6 100644 --- a/dotnet/samples/AGUIClientServer/README.md +++ b/dotnet/samples/AGUIClientServer/README.md @@ -151,9 +151,9 @@ AIAgent agent = chatClient.CreateAIAgent( tools: []); bool isFirstUpdate = true; -AgentRunResponseUpdate? currentUpdate = null; +AgentResponseUpdate? currentUpdate = null; -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread)) { // First update indicates run started if (isFirstUpdate) @@ -190,19 +190,19 @@ if (currentUpdate != null) The `RunStreamingAsync` method: 1. Sends messages to the server via HTTP POST 2. Receives server-sent events (SSE) stream -3. Parses events into `AgentRunResponseUpdate` objects +3. Parses events into `AgentResponseUpdate` objects 4. Yields updates as they arrive for real-time display ## Key Concepts - **Thread**: Represents a conversation context that persists across multiple runs (accessed via `ConversationId` property) - **Run**: A single execution of the agent for a given set of messages (identified by `ResponseId` property) -- **AgentRunResponseUpdate**: Contains the response data with: +- **AgentResponseUpdate**: Contains the response data with: - `ResponseId`: The unique run identifier - `ConversationId`: The thread/conversation identifier - `Contents`: Collection of content items (TextContent, ErrorContent, etc.) - **Run Lifecycle**: - - The **first** `AgentRunResponseUpdate` in a run indicates the run has started + - The **first** `AgentResponseUpdate` in a run indicates the run has started - Subsequent updates contain streaming content as the agent processes - - The **last** `AgentRunResponseUpdate` in a run indicates the run has finished + - The **last** `AgentResponseUpdate` in a run indicates the run has finished - If an error occurs, the update will contain `ErrorContent` \ No newline at end of file diff --git a/dotnet/samples/AgentWebChat/AgentWebChat.Web/A2AAgentClient.cs b/dotnet/samples/AgentWebChat/AgentWebChat.Web/A2AAgentClient.cs index 08dafea129..1f87597122 100644 --- a/dotnet/samples/AgentWebChat/AgentWebChat.Web/A2AAgentClient.cs +++ b/dotnet/samples/AgentWebChat/AgentWebChat.Web/A2AAgentClient.cs @@ -25,7 +25,7 @@ internal sealed class A2AAgentClient : AgentClientBase this._uri = baseUri; } - public override async IAsyncEnumerable RunStreamingAsync( + public override async IAsyncEnumerable RunStreamingAsync( string agentName, IList messages, string? threadId = null, @@ -37,7 +37,7 @@ internal sealed class A2AAgentClient : AgentClientBase var contextId = threadId ?? Guid.NewGuid().ToString("N"); // Convert and send messages via A2A without try-catch in yield method - var results = new List(); + var results = new List(); try { @@ -60,7 +60,7 @@ internal sealed class A2AAgentClient : AgentClientBase var responseMessage = message.ToChatMessage(); if (responseMessage is { Contents.Count: > 0 }) { - results.Add(new AgentRunResponseUpdate(responseMessage.Role, responseMessage.Contents) + results.Add(new AgentResponseUpdate(responseMessage.Role, responseMessage.Contents) { MessageId = message.MessageId, CreatedAt = DateTimeOffset.UtcNow @@ -90,7 +90,7 @@ internal sealed class A2AAgentClient : AgentClientBase RawRepresentation = artifact, }; - results.Add(new AgentRunResponseUpdate(chatMessage.Role, chatMessage.Contents) + results.Add(new AgentResponseUpdate(chatMessage.Role, chatMessage.Contents) { MessageId = agentTask.Id, CreatedAt = DateTimeOffset.UtcNow @@ -108,7 +108,7 @@ internal sealed class A2AAgentClient : AgentClientBase { this._logger.LogError(ex, "Error running agent {AgentName} via A2A", agentName); - results.Add(new AgentRunResponseUpdate(ChatRole.Assistant, $"Error: {ex.Message}") + results.Add(new AgentResponseUpdate(ChatRole.Assistant, $"Error: {ex.Message}") { MessageId = Guid.NewGuid().ToString("N"), CreatedAt = DateTimeOffset.UtcNow diff --git a/dotnet/samples/AgentWebChat/AgentWebChat.Web/IAgentClient.cs b/dotnet/samples/AgentWebChat/AgentWebChat.Web/IAgentClient.cs index 2d08ef5e45..2d22413f0d 100644 --- a/dotnet/samples/AgentWebChat/AgentWebChat.Web/IAgentClient.cs +++ b/dotnet/samples/AgentWebChat/AgentWebChat.Web/IAgentClient.cs @@ -19,7 +19,7 @@ internal abstract class AgentClientBase /// Optional thread identifier for conversation continuity. /// Cancellation token. /// An asynchronous enumerable of agent response updates. - public abstract IAsyncEnumerable RunStreamingAsync( + public abstract IAsyncEnumerable RunStreamingAsync( string agentName, IList messages, string? threadId = null, diff --git a/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIChatCompletionsAgentClient.cs b/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIChatCompletionsAgentClient.cs index 95e3d16fd4..a5b522a892 100644 --- a/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIChatCompletionsAgentClient.cs +++ b/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIChatCompletionsAgentClient.cs @@ -16,7 +16,7 @@ namespace AgentWebChat.Web; /// internal sealed class OpenAIChatCompletionsAgentClient(HttpClient httpClient) : AgentClientBase { - public override async IAsyncEnumerable RunStreamingAsync( + public override async IAsyncEnumerable RunStreamingAsync( string agentName, IList messages, string? threadId = null, @@ -31,7 +31,7 @@ internal sealed class OpenAIChatCompletionsAgentClient(HttpClient httpClient) : var openAiClient = new ChatClient(model: "myModel!", credential: new ApiKeyCredential("dummy-key"), options: options).AsIChatClient(); await foreach (var update in openAiClient.GetStreamingResponseAsync(messages, cancellationToken: cancellationToken)) { - yield return new AgentRunResponseUpdate(update); + yield return new AgentResponseUpdate(update); } } } diff --git a/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIResponsesAgentClient.cs b/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIResponsesAgentClient.cs index d0121a6165..7594468398 100644 --- a/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIResponsesAgentClient.cs +++ b/dotnet/samples/AgentWebChat/AgentWebChat.Web/OpenAIResponsesAgentClient.cs @@ -15,7 +15,7 @@ namespace AgentWebChat.Web; /// internal sealed class OpenAIResponsesAgentClient(HttpClient httpClient) : AgentClientBase { - public override async IAsyncEnumerable RunStreamingAsync( + public override async IAsyncEnumerable RunStreamingAsync( string agentName, IList messages, string? threadId = null, @@ -35,7 +35,7 @@ internal sealed class OpenAIResponsesAgentClient(HttpClient httpClient) : AgentC await foreach (var update in openAiClient.GetStreamingResponseAsync(messages, chatOptions, cancellationToken: cancellationToken)) { - yield return new AgentRunResponseUpdate(update); + yield return new AgentResponseUpdate(update); } } } diff --git a/dotnet/samples/AzureFunctions/02_AgentOrchestration_Chaining/FunctionTriggers.cs b/dotnet/samples/AzureFunctions/02_AgentOrchestration_Chaining/FunctionTriggers.cs index f2a714f5af..8ac9ea8d51 100644 --- a/dotnet/samples/AzureFunctions/02_AgentOrchestration_Chaining/FunctionTriggers.cs +++ b/dotnet/samples/AzureFunctions/02_AgentOrchestration_Chaining/FunctionTriggers.cs @@ -21,11 +21,11 @@ public static class FunctionTriggers DurableAIAgent writer = context.GetAgent("WriterAgent"); AgentThread writerThread = await writer.GetNewThreadAsync(); - AgentRunResponse initial = await writer.RunAsync( + AgentResponse initial = await writer.RunAsync( message: "Write a concise inspirational sentence about learning.", thread: writerThread); - AgentRunResponse refined = await writer.RunAsync( + AgentResponse refined = await writer.RunAsync( message: $"Improve this further while keeping it under 25 words: {initial.Result.Text}", thread: writerThread); diff --git a/dotnet/samples/AzureFunctions/03_AgentOrchestration_Concurrency/FunctionTriggers.cs b/dotnet/samples/AzureFunctions/03_AgentOrchestration_Concurrency/FunctionTriggers.cs index 2d15dd585c..241faf6df7 100644 --- a/dotnet/samples/AzureFunctions/03_AgentOrchestration_Concurrency/FunctionTriggers.cs +++ b/dotnet/samples/AzureFunctions/03_AgentOrchestration_Concurrency/FunctionTriggers.cs @@ -26,9 +26,9 @@ public static class FunctionsTriggers DurableAIAgent chemist = context.GetAgent("ChemistAgent"); // Start both agent runs concurrently - Task> physicistTask = physicist.RunAsync(prompt); + Task> physicistTask = physicist.RunAsync(prompt); - Task> chemistTask = chemist.RunAsync(prompt); + Task> chemistTask = chemist.RunAsync(prompt); // Wait for both tasks to complete using Task.WhenAll await Task.WhenAll(physicistTask, chemistTask); diff --git a/dotnet/samples/AzureFunctions/04_AgentOrchestration_Conditionals/FunctionTriggers.cs b/dotnet/samples/AzureFunctions/04_AgentOrchestration_Conditionals/FunctionTriggers.cs index 059cb12db1..f09579978f 100644 --- a/dotnet/samples/AzureFunctions/04_AgentOrchestration_Conditionals/FunctionTriggers.cs +++ b/dotnet/samples/AzureFunctions/04_AgentOrchestration_Conditionals/FunctionTriggers.cs @@ -24,7 +24,7 @@ public static class FunctionTriggers AgentThread spamThread = await spamDetectionAgent.GetNewThreadAsync(); // Step 1: Check if the email is spam - AgentRunResponse spamDetectionResponse = await spamDetectionAgent.RunAsync( + AgentResponse spamDetectionResponse = await spamDetectionAgent.RunAsync( message: $""" Analyze this email for spam content and return a JSON response with 'is_spam' (boolean) and 'reason' (string) fields: @@ -45,7 +45,7 @@ public static class FunctionTriggers DurableAIAgent emailAssistantAgent = context.GetAgent("EmailAssistantAgent"); AgentThread emailThread = await emailAssistantAgent.GetNewThreadAsync(); - AgentRunResponse emailAssistantResponse = await emailAssistantAgent.RunAsync( + AgentResponse emailAssistantResponse = await emailAssistantAgent.RunAsync( message: $""" Draft a professional response to this email. Return a JSON response with a 'response' field containing the reply: diff --git a/dotnet/samples/AzureFunctions/05_AgentOrchestration_HITL/FunctionTriggers.cs b/dotnet/samples/AzureFunctions/05_AgentOrchestration_HITL/FunctionTriggers.cs index 056e827487..6dcbb50c01 100644 --- a/dotnet/samples/AzureFunctions/05_AgentOrchestration_HITL/FunctionTriggers.cs +++ b/dotnet/samples/AzureFunctions/05_AgentOrchestration_HITL/FunctionTriggers.cs @@ -30,7 +30,7 @@ public static class FunctionTriggers context.SetCustomStatus($"Starting content generation for topic: {input.Topic}"); // Step 1: Generate initial content - AgentRunResponse writerResponse = await writerAgent.RunAsync( + AgentResponse writerResponse = await writerAgent.RunAsync( message: $"Write a short article about '{input.Topic}'.", thread: writerThread); GeneratedContent content = writerResponse.Result; diff --git a/dotnet/samples/AzureFunctions/06_LongRunningTools/FunctionTriggers.cs b/dotnet/samples/AzureFunctions/06_LongRunningTools/FunctionTriggers.cs index 95987203a1..9f73cff18e 100644 --- a/dotnet/samples/AzureFunctions/06_LongRunningTools/FunctionTriggers.cs +++ b/dotnet/samples/AzureFunctions/06_LongRunningTools/FunctionTriggers.cs @@ -26,7 +26,7 @@ public static class FunctionTriggers context.SetCustomStatus($"Starting content generation for topic: {input.Topic}"); // Step 1: Generate initial content - AgentRunResponse writerResponse = await writerAgent.RunAsync( + AgentResponse writerResponse = await writerAgent.RunAsync( message: $"Write a short article about '{input.Topic}'.", thread: writerThread); GeneratedContent content = writerResponse.Result; diff --git a/dotnet/samples/AzureFunctions/08_ReliableStreaming/README.md b/dotnet/samples/AzureFunctions/08_ReliableStreaming/README.md index f1c68c2339..fd13f23ecd 100644 --- a/dotnet/samples/AzureFunctions/08_ReliableStreaming/README.md +++ b/dotnet/samples/AzureFunctions/08_ReliableStreaming/README.md @@ -196,7 +196,7 @@ The `id` field is the Redis stream entry ID - use it as the `cursor` parameter t 2. **Agent invoked**: The durable entity (`AgentEntity`) is signaled to run the travel planner agent. This is fire-and-forget from the HTTP request's perspective. -3. **Responses captured**: As the agent generates responses, `RedisStreamResponseHandler` (implementing `IAgentResponseHandler`) extracts the text from each `AgentRunResponseUpdate` and publishes it to a Redis Stream keyed by session ID. +3. **Responses captured**: As the agent generates responses, `RedisStreamResponseHandler` (implementing `IAgentResponseHandler`) extracts the text from each `AgentResponseUpdate` and publishes it to a Redis Stream keyed by session ID. 4. **Client polls Redis**: The HTTP response streams events by polling the Redis Stream. For SSE format, each event includes the Redis entry ID as the `id` field. diff --git a/dotnet/samples/AzureFunctions/08_ReliableStreaming/RedisStreamResponseHandler.cs b/dotnet/samples/AzureFunctions/08_ReliableStreaming/RedisStreamResponseHandler.cs index 21f944338a..e13c685a08 100644 --- a/dotnet/samples/AzureFunctions/08_ReliableStreaming/RedisStreamResponseHandler.cs +++ b/dotnet/samples/AzureFunctions/08_ReliableStreaming/RedisStreamResponseHandler.cs @@ -29,7 +29,7 @@ public readonly record struct StreamChunk(string EntryId, string? Text, bool IsD /// /// /// Each agent session gets its own Redis Stream, keyed by session ID. The stream entries -/// contain text chunks extracted from objects. +/// contain text chunks extracted from objects. /// /// public sealed class RedisStreamResponseHandler : IAgentResponseHandler @@ -53,7 +53,7 @@ public sealed class RedisStreamResponseHandler : IAgentResponseHandler /// public async ValueTask OnStreamingResponseUpdateAsync( - IAsyncEnumerable messageStream, + IAsyncEnumerable messageStream, CancellationToken cancellationToken) { // Get the current session ID from the DurableAgentContext @@ -73,7 +73,7 @@ public sealed class RedisStreamResponseHandler : IAgentResponseHandler IDatabase db = this._redis.GetDatabase(); int sequenceNumber = 0; - await foreach (AgentRunResponseUpdate update in messageStream.WithCancellation(cancellationToken)) + await foreach (AgentResponseUpdate update in messageStream.WithCancellation(cancellationToken)) { // Extract just the text content - this avoids serialization round-trip issues string text = update.Text; @@ -112,7 +112,7 @@ public sealed class RedisStreamResponseHandler : IAgentResponseHandler } /// - public ValueTask OnAgentResponseAsync(AgentRunResponse message, CancellationToken cancellationToken) + public ValueTask OnAgentResponseAsync(AgentResponse message, CancellationToken cancellationToken) { // This handler is optimized for streaming responses. // For non-streaming responses, we don't need to store in Redis since diff --git a/dotnet/samples/GettingStarted/A2A/A2AAgent_PollingForTaskCompletion/Program.cs b/dotnet/samples/GettingStarted/A2A/A2AAgent_PollingForTaskCompletion/Program.cs index f54f290e82..1062cc4b6f 100644 --- a/dotnet/samples/GettingStarted/A2A/A2AAgent_PollingForTaskCompletion/Program.cs +++ b/dotnet/samples/GettingStarted/A2A/A2AAgent_PollingForTaskCompletion/Program.cs @@ -19,7 +19,7 @@ AIAgent agent = agentCard.GetAIAgent(); AgentThread thread = await agent.GetNewThreadAsync(); // Start the initial run with a long-running task. -AgentRunResponse response = await agent.RunAsync("Conduct a comprehensive analysis of quantum computing applications in cryptography, including recent breakthroughs, implementation challenges, and future roadmap. Please include diagrams and visual representations to illustrate complex concepts.", thread); +AgentResponse response = await agent.RunAsync("Conduct a comprehensive analysis of quantum computing applications in cryptography, including recent breakthroughs, implementation challenges, and future roadmap. Please include diagrams and visual representations to illustrate complex concepts.", thread); // Poll until the response is complete. while (response.ContinuationToken is { } token) diff --git a/dotnet/samples/GettingStarted/AGUI/README.md b/dotnet/samples/GettingStarted/AGUI/README.md index a624fe81f3..f55e317e36 100644 --- a/dotnet/samples/GettingStarted/AGUI/README.md +++ b/dotnet/samples/GettingStarted/AGUI/README.md @@ -212,7 +212,7 @@ dotnet run 1. `AGUIAgent` sends HTTP POST request to server 2. Server responds with SSE stream -3. Client parses events into `AgentRunResponseUpdate` objects +3. Client parses events into `AgentResponseUpdate` objects 4. Updates are displayed based on content type 5. `ConversationId` maintains conversation context diff --git a/dotnet/samples/GettingStarted/AGUI/Step01_GettingStarted/Client/Program.cs b/dotnet/samples/GettingStarted/AGUI/Step01_GettingStarted/Client/Program.cs index 691ed40495..78bacc949c 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step01_GettingStarted/Client/Program.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step01_GettingStarted/Client/Program.cs @@ -51,7 +51,7 @@ try bool isFirstUpdate = true; string? threadId = null; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread)) { ChatResponseUpdate chatUpdate = update.AsChatResponseUpdate(); diff --git a/dotnet/samples/GettingStarted/AGUI/Step02_BackendTools/Client/Program.cs b/dotnet/samples/GettingStarted/AGUI/Step02_BackendTools/Client/Program.cs index 4306171979..6c22071a61 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step02_BackendTools/Client/Program.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step02_BackendTools/Client/Program.cs @@ -51,7 +51,7 @@ try bool isFirstUpdate = true; string? threadId = null; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread)) { ChatResponseUpdate chatUpdate = update.AsChatResponseUpdate(); diff --git a/dotnet/samples/GettingStarted/AGUI/Step03_FrontendTools/Client/Program.cs b/dotnet/samples/GettingStarted/AGUI/Step03_FrontendTools/Client/Program.cs index ec0fa2c74e..e675d5cca5 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step03_FrontendTools/Client/Program.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step03_FrontendTools/Client/Program.cs @@ -64,7 +64,7 @@ try bool isFirstUpdate = true; string? threadId = null; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread)) { ChatResponseUpdate chatUpdate = update.AsChatResponseUpdate(); diff --git a/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/Program.cs b/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/Program.cs index 656989458d..e93446ecb1 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/Program.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/Program.cs @@ -51,8 +51,8 @@ while ((input = Console.ReadLine()) != null && !input.Equals("exit", StringCompa { approvalResponses.Clear(); - List chatResponseUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread, cancellationToken: default)) + List chatResponseUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread, cancellationToken: default)) { chatResponseUpdates.Add(update); foreach (AIContent content in update.Contents) @@ -111,7 +111,7 @@ while ((input = Console.ReadLine()) != null && !input.Equals("exit", StringCompa } } - AgentRunResponse response = chatResponseUpdates.ToAgentRunResponse(); + AgentResponse response = chatResponseUpdates.ToAgentResponse(); messages.AddRange(response.Messages); foreach (AIContent approvalResponse in approvalResponses) { diff --git a/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/ServerFunctionApprovalClientAgent.cs b/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/ServerFunctionApprovalClientAgent.cs index 9f7812cc50..ef84b85281 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/ServerFunctionApprovalClientAgent.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Client/ServerFunctionApprovalClientAgent.cs @@ -22,17 +22,17 @@ internal sealed class ServerFunctionApprovalClientAgent : DelegatingAIAgent this._jsonSerializerOptions = jsonSerializerOptions; } - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken) - .ToAgentRunResponseAsync(cancellationToken); + .ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -166,8 +166,8 @@ internal sealed class ServerFunctionApprovalClientAgent : DelegatingAIAgent return result ?? messages; } - private static AgentRunResponseUpdate ProcessIncomingServerApprovalRequests( - AgentRunResponseUpdate update, + private static AgentResponseUpdate ProcessIncomingServerApprovalRequests( + AgentResponseUpdate update, JsonSerializerOptions jsonSerializerOptions) { IList? updatedContents = null; @@ -215,7 +215,7 @@ internal sealed class ServerFunctionApprovalClientAgent : DelegatingAIAgent if (updatedContents is not null) { var chatUpdate = update.AsChatResponseUpdate(); - return new AgentRunResponseUpdate(new ChatResponseUpdate() + return new AgentResponseUpdate(new ChatResponseUpdate() { Role = chatUpdate.Role, Contents = updatedContents, diff --git a/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Server/ServerFunctionApprovalServerAgent.cs b/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Server/ServerFunctionApprovalServerAgent.cs index 69e3db58c7..01649084ac 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Server/ServerFunctionApprovalServerAgent.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step04_HumanInLoop/Server/ServerFunctionApprovalServerAgent.cs @@ -22,17 +22,17 @@ internal sealed class ServerFunctionApprovalAgent : DelegatingAIAgent this._jsonSerializerOptions = jsonSerializerOptions; } - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken) - .ToAgentRunResponseAsync(cancellationToken); + .ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -172,8 +172,8 @@ internal sealed class ServerFunctionApprovalAgent : DelegatingAIAgent return result ?? messages; } - private static AgentRunResponseUpdate ProcessOutgoingApprovalRequests( - AgentRunResponseUpdate update, + private static AgentResponseUpdate ProcessOutgoingApprovalRequests( + AgentResponseUpdate update, JsonSerializerOptions jsonSerializerOptions) { IList? updatedContents = null; @@ -207,7 +207,7 @@ internal sealed class ServerFunctionApprovalAgent : DelegatingAIAgent { var chatUpdate = update.AsChatResponseUpdate(); // Yield a tool call update that represents the approval request - return new AgentRunResponseUpdate(new ChatResponseUpdate() + return new AgentResponseUpdate(new ChatResponseUpdate() { Role = chatUpdate.Role, Contents = updatedContents, diff --git a/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/Program.cs b/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/Program.cs index 87286fbe4c..1946bfc051 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/Program.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/Program.cs @@ -70,7 +70,7 @@ try Console.WriteLine(); - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread)) { ChatResponseUpdate chatUpdate = update.AsChatResponseUpdate(); diff --git a/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/StatefulAgent.cs b/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/StatefulAgent.cs index d5fd9f187b..8eca890e60 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/StatefulAgent.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Client/StatefulAgent.cs @@ -35,18 +35,18 @@ internal sealed class StatefulAgent : DelegatingAIAgent } /// - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken) - .ToAgentRunResponseAsync(cancellationToken); + .ToAgentResponseAsync(cancellationToken); } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -64,7 +64,7 @@ internal sealed class StatefulAgent : DelegatingAIAgent messagesWithState.Add(stateMessage); // Stream the response and update state when received - await foreach (AgentRunResponseUpdate update in this.InnerAgent.RunStreamingAsync(messagesWithState, thread, options, cancellationToken)) + await foreach (AgentResponseUpdate update in this.InnerAgent.RunStreamingAsync(messagesWithState, thread, options, cancellationToken)) { // Check if this update contains a state snapshot foreach (AIContent content in update.Contents) diff --git a/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Server/SharedStateAgent.cs b/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Server/SharedStateAgent.cs index 603698b579..1ac21adfce 100644 --- a/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Server/SharedStateAgent.cs +++ b/dotnet/samples/GettingStarted/AGUI/Step05_StateManagement/Server/SharedStateAgent.cs @@ -17,17 +17,17 @@ internal sealed class SharedStateAgent : DelegatingAIAgent this._jsonSerializerOptions = jsonSerializerOptions; } - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken) - .ToAgentRunResponseAsync(cancellationToken); + .ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -91,7 +91,7 @@ internal sealed class SharedStateAgent : DelegatingAIAgent var firstRunMessages = messages.Append(stateUpdateMessage); // Collect all updates from first run - var allUpdates = new List(); + var allUpdates = new List(); await foreach (var update in this.InnerAgent.RunStreamingAsync(firstRunMessages, thread, firstRunOptions, cancellationToken).ConfigureAwait(false)) { allUpdates.Add(update); @@ -104,7 +104,7 @@ internal sealed class SharedStateAgent : DelegatingAIAgent } } - var response = allUpdates.ToAgentRunResponse(); + var response = allUpdates.ToAgentResponse(); // Try to deserialize the structured state response if (response.TryDeserialize(this._jsonSerializerOptions, out JsonElement stateSnapshot)) @@ -113,7 +113,7 @@ internal sealed class SharedStateAgent : DelegatingAIAgent byte[] stateBytes = JsonSerializer.SerializeToUtf8Bytes( stateSnapshot, this._jsonSerializerOptions.GetTypeInfo(typeof(JsonElement))); - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { Contents = [new DataContent(stateBytes, "application/json")] }; diff --git a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/Program.cs b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/Program.cs index 46ac8a55fa..3d72a82c11 100644 --- a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/Program.cs +++ b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/Program.cs @@ -14,5 +14,5 @@ A2ACardResolver agentCardResolver = new(new Uri(a2aAgentHost)); AIAgent agent = await agentCardResolver.GetAIAgentAsync(); // Invoke the agent and output the text result. -AgentRunResponse response = await agent.RunAsync("Tell me a joke about a pirate."); +AgentResponse response = await agent.RunAsync("Tell me a joke about a pirate."); Console.WriteLine(response); diff --git a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/README.md b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/README.md index 536514306e..534eacfdb5 100644 --- a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/README.md +++ b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_A2A/README.md @@ -29,6 +29,6 @@ A2AClient a2aClient = new(new Uri("https://your-a2a-agent-host/echo")); AIAgent agent = a2aClient.GetAIAgent(); // Run the agent -AgentRunResponse response = await agent.RunAsync("Tell me a joke about a pirate."); +AgentResponse response = await agent.RunAsync("Tell me a joke about a pirate."); Console.WriteLine(response); ``` \ No newline at end of file diff --git a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_CustomImplementation/Program.cs b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_CustomImplementation/Program.cs index 51913d3d7d..3e52a5f01a 100644 --- a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_CustomImplementation/Program.cs +++ b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_CustomImplementation/Program.cs @@ -34,7 +34,7 @@ namespace SampleApp public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new CustomAgentThread(serializedThread, jsonSerializerOptions)); - protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { // Create a thread if the user didn't supply one. thread ??= await this.GetNewThreadAsync(cancellationToken); @@ -58,7 +58,7 @@ namespace SampleApp }; await typedThread.MessageStore.InvokedAsync(invokedContext, cancellationToken); - return new AgentRunResponse + return new AgentResponse { AgentId = this.Id, ResponseId = Guid.NewGuid().ToString("N"), @@ -66,7 +66,7 @@ namespace SampleApp }; } - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { // Create a thread if the user didn't supply one. thread ??= await this.GetNewThreadAsync(cancellationToken); @@ -92,7 +92,7 @@ namespace SampleApp foreach (var message in responseMessages) { - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { AgentId = this.Id, AuthorName = message.AuthorName, diff --git a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_GoogleGemini/Program.cs b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_GoogleGemini/Program.cs index 89c86d5c56..79980c14db 100644 --- a/dotnet/samples/GettingStarted/AgentProviders/Agent_With_GoogleGemini/Program.cs +++ b/dotnet/samples/GettingStarted/AgentProviders/Agent_With_GoogleGemini/Program.cs @@ -22,7 +22,7 @@ ChatClientAgent agentGenAI = new( name: JokerName, instructions: JokerInstructions); -AgentRunResponse response = await agentGenAI.RunAsync("Tell me a joke about a pirate."); +AgentResponse response = await agentGenAI.RunAsync("Tell me a joke about a pirate."); Console.WriteLine($"Google GenAI client based agent response:\n{response}"); // Using a community driven Mscc.GenerativeAI.Microsoft package diff --git a/dotnet/samples/GettingStarted/AgentWithAnthropic/Agent_Anthropic_Step03_UsingFunctionTools/Program.cs b/dotnet/samples/GettingStarted/AgentWithAnthropic/Agent_Anthropic_Step03_UsingFunctionTools/Program.cs index ad117fca3d..fae850ca0e 100644 --- a/dotnet/samples/GettingStarted/AgentWithAnthropic/Agent_Anthropic_Step03_UsingFunctionTools/Program.cs +++ b/dotnet/samples/GettingStarted/AgentWithAnthropic/Agent_Anthropic_Step03_UsingFunctionTools/Program.cs @@ -31,7 +31,7 @@ Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?", // Streaming agent interaction with function tools. thread = await agent.GetNewThreadAsync(); -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync("What is the weather like in Amsterdam?", thread)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("What is the weather like in Amsterdam?", thread)) { Console.WriteLine(update); } diff --git a/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step03_CreateFromChatClient/OpenAIChatClientAgent.cs b/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step03_CreateFromChatClient/OpenAIChatClientAgent.cs index a0b59d1053..3694f70b11 100644 --- a/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step03_CreateFromChatClient/OpenAIChatClientAgent.cs +++ b/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step03_CreateFromChatClient/OpenAIChatClientAgent.cs @@ -87,10 +87,10 @@ public class OpenAIChatClientAgent : DelegatingAIAgent } /// - protected sealed override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected sealed override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => base.RunCoreAsync(messages, thread, options, cancellationToken); /// - protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => base.RunCoreStreamingAsync(messages, thread, options, cancellationToken); } diff --git a/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/OpenAIResponseClientAgent.cs b/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/OpenAIResponseClientAgent.cs index f894a5434c..e0c4f36356 100644 --- a/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/OpenAIResponseClientAgent.cs +++ b/dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/OpenAIResponseClientAgent.cs @@ -105,10 +105,10 @@ public class OpenAIResponseClientAgent : DelegatingAIAgent } /// - protected sealed override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected sealed override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => base.RunCoreAsync(messages, thread, options, cancellationToken); /// - protected sealed override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected sealed override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => base.RunCoreStreamingAsync(messages, thread, options, cancellationToken); } diff --git a/dotnet/samples/GettingStarted/Agents/Agent_Step04_UsingFunctionToolsWithApprovals/Program.cs b/dotnet/samples/GettingStarted/Agents/Agent_Step04_UsingFunctionToolsWithApprovals/Program.cs index 61ad65a164..169cabcb47 100644 --- a/dotnet/samples/GettingStarted/Agents/Agent_Step04_UsingFunctionToolsWithApprovals/Program.cs +++ b/dotnet/samples/GettingStarted/Agents/Agent_Step04_UsingFunctionToolsWithApprovals/Program.cs @@ -64,4 +64,4 @@ while (userInputRequests.Count > 0) Console.WriteLine($"\nAgent: {response}"); // For streaming use: -// Console.WriteLine($"\nAgent: {updates.ToAgentRunResponse()}"); +// Console.WriteLine($"\nAgent: {updates.ToAgentResponse()}"); diff --git a/dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOutput/Program.cs b/dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOutput/Program.cs index 3b923069f4..e7fc4088df 100644 --- a/dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOutput/Program.cs +++ b/dotnet/samples/GettingStarted/Agents/Agent_Step05_StructuredOutput/Program.cs @@ -24,7 +24,7 @@ ChatClient chatClient = new AzureOpenAIClient( ChatClientAgent agent = chatClient.CreateAIAgent(name: "HelpfulAssistant", instructions: "You are a helpful assistant."); // Set PersonInfo as the type parameter of RunAsync method to specify the expected structured output from the agent and invoke the agent with some unstructured input. -AgentRunResponse response = await agent.RunAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); +AgentResponse response = await agent.RunAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); // Access the structured output via the Result property of the agent response. Console.WriteLine("Assistant Output:"); @@ -44,7 +44,7 @@ var updates = agentWithPersonInfo.RunStreamingAsync("Please provide information // Assemble all the parts of the streamed output, since we can only deserialize once we have the full json, // then deserialize the response into the PersonInfo class. -PersonInfo personInfo = (await updates.ToAgentRunResponseAsync()).Deserialize(JsonSerializerOptions.Web); +PersonInfo personInfo = (await updates.ToAgentResponseAsync()).Deserialize(JsonSerializerOptions.Web); Console.WriteLine("Assistant Output:"); Console.WriteLine($"Name: {personInfo.Name}"); diff --git a/dotnet/samples/GettingStarted/Agents/Agent_Step13_BackgroundResponsesWithToolsAndPersistence/Program.cs b/dotnet/samples/GettingStarted/Agents/Agent_Step13_BackgroundResponsesWithToolsAndPersistence/Program.cs index 124ffa2a63..98f85a7593 100644 --- a/dotnet/samples/GettingStarted/Agents/Agent_Step13_BackgroundResponsesWithToolsAndPersistence/Program.cs +++ b/dotnet/samples/GettingStarted/Agents/Agent_Step13_BackgroundResponsesWithToolsAndPersistence/Program.cs @@ -35,7 +35,7 @@ AgentRunOptions options = new() { AllowBackgroundResponses = true }; AgentThread thread = await agent.GetNewThreadAsync(); // Start the initial run. -AgentRunResponse response = await agent.RunAsync("Write a very long novel about a team of astronauts exploring an uncharted galaxy.", thread, options); +AgentResponse response = await agent.RunAsync("Write a very long novel about a team of astronauts exploring an uncharted galaxy.", thread, options); // Poll for background responses until complete. while (response.ContinuationToken is not null) diff --git a/dotnet/samples/GettingStarted/Agents/Agent_Step14_Middleware/Program.cs b/dotnet/samples/GettingStarted/Agents/Agent_Step14_Middleware/Program.cs index 00217024ec..7e8f9de058 100644 --- a/dotnet/samples/GettingStarted/Agents/Agent_Step14_Middleware/Program.cs +++ b/dotnet/samples/GettingStarted/Agents/Agent_Step14_Middleware/Program.cs @@ -131,7 +131,7 @@ async ValueTask PerRequestFunctionCallingMiddleware(AIAgent agent, Func } // This middleware redacts PII information from input and output messages. -async Task PIIMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +async Task PIIMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { // Redact PII information from input messages var filteredMessages = FilterMessages(messages); @@ -171,7 +171,7 @@ async Task PIIMiddleware(IEnumerable messages, Ag } // This middleware enforces guardrails by redacting certain keywords from input and output messages. -async Task GuardrailMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +async Task GuardrailMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { // Redact keywords from input messages var filteredMessages = FilterMessages(messages); @@ -208,7 +208,7 @@ async Task GuardrailMiddleware(IEnumerable messag } // This middleware handles Human in the loop console interaction for any user approval required during function calling. -async Task ConsolePromptingApprovalMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +async Task ConsolePromptingApprovalMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { var response = await innerAgent.RunAsync(messages, thread, options, cancellationToken); diff --git a/dotnet/samples/GettingStarted/Agents/Agent_Step17_BackgroundResponses/Program.cs b/dotnet/samples/GettingStarted/Agents/Agent_Step17_BackgroundResponses/Program.cs index 2ac72ef06e..d35b42a780 100644 --- a/dotnet/samples/GettingStarted/Agents/Agent_Step17_BackgroundResponses/Program.cs +++ b/dotnet/samples/GettingStarted/Agents/Agent_Step17_BackgroundResponses/Program.cs @@ -22,7 +22,7 @@ AgentRunOptions options = new() { AllowBackgroundResponses = true }; AgentThread thread = await agent.GetNewThreadAsync(); // Start the initial run. -AgentRunResponse response = await agent.RunAsync("Write a very long novel about otters in space.", thread, options); +AgentResponse response = await agent.RunAsync("Write a very long novel about otters in space.", thread, options); // Poll until the response is complete. while (response.ContinuationToken is { } token) @@ -43,9 +43,9 @@ Console.WriteLine(response.Text); options = new() { AllowBackgroundResponses = true }; thread = await agent.GetNewThreadAsync(); -AgentRunResponseUpdate? lastReceivedUpdate = null; +AgentResponseUpdate? lastReceivedUpdate = null; // Start streaming. -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync("Write a very long novel about otters in space.", thread, options)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Write a very long novel about otters in space.", thread, options)) { // Output each update. Console.Write(update.Text); @@ -63,7 +63,7 @@ await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync("Write a // Resume from interruption point. options.ContinuationToken = lastReceivedUpdate?.ContinuationToken; -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(thread, options)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(thread, options)) { // Output each update. Console.Write(update.Text); diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs index 4d840d54ff..8ebceaea26 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step01.2_Running/Program.cs @@ -27,7 +27,7 @@ AgentVersion agentVersion = aiProjectClient.Agents.CreateAgentVersion(agentName: AIAgent jokerAgent = aiProjectClient.GetAIAgent(agentVersion); // Invoke the agent with streaming support. -await foreach (AgentRunResponseUpdate update in jokerAgent.RunStreamingAsync("Tell me a joke about a pirate.")) +await foreach (AgentResponseUpdate update in jokerAgent.RunStreamingAsync("Tell me a joke about a pirate.")) { Console.WriteLine(update); } diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs index 4b9e2caa73..4ad3d86255 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step02_MultiturnConversation/Program.cs @@ -32,11 +32,11 @@ Console.WriteLine(await jokerAgent.RunAsync("Now add some emojis to the joke and // Invoke the agent with a multi-turn conversation and streaming, where the context is preserved in the thread object. thread = await jokerAgent.GetNewThreadAsync(); -await foreach (AgentRunResponseUpdate update in jokerAgent.RunStreamingAsync("Tell me a joke about a pirate.", thread)) +await foreach (AgentResponseUpdate update in jokerAgent.RunStreamingAsync("Tell me a joke about a pirate.", thread)) { Console.WriteLine(update); } -await foreach (AgentRunResponseUpdate update in jokerAgent.RunStreamingAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", thread)) +await foreach (AgentResponseUpdate update in jokerAgent.RunStreamingAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", thread)) { Console.WriteLine(update); } diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs index fbf7d9b5d9..0f51bb8364 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step03_UsingFunctionTools/Program.cs @@ -42,7 +42,7 @@ Console.WriteLine(await existingAgent.RunAsync("What is the weather like in Amst // Streaming agent interaction with function tools. thread = await existingAgent.GetNewThreadAsync(); -await foreach (AgentRunResponseUpdate update in existingAgent.RunStreamingAsync("What is the weather like in Amsterdam?", thread)) +await foreach (AgentResponseUpdate update in existingAgent.RunStreamingAsync("What is the weather like in Amsterdam?", thread)) { Console.WriteLine(update); } diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs index 9de52a54f1..1eb140cedc 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step04_UsingFunctionToolsWithApprovals/Program.cs @@ -33,7 +33,7 @@ AIAgent agent = await aiProjectClient.CreateAIAgentAsync(name: AssistantName, mo // Call the agent with approval-required function tools. // The agent will request approval before invoking the function. AgentThread thread = await agent.GetNewThreadAsync(); -AgentRunResponse response = await agent.RunAsync("What is the weather like in Amsterdam?", thread); +AgentResponse response = await agent.RunAsync("What is the weather like in Amsterdam?", thread); // Check if there are any user input requests (approvals needed). List userInputRequests = response.UserInputRequests.ToList(); diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs index ac05565836..aaeb90fafa 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step05_StructuredOutput/Program.cs @@ -35,7 +35,7 @@ ChatClientAgent agent = await aiProjectClient.CreateAIAgentAsync( }); // Set PersonInfo as the type parameter of RunAsync method to specify the expected structured output from the agent and invoke the agent with some unstructured input. -AgentRunResponse response = await agent.RunAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); +AgentResponse response = await agent.RunAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); // Access the structured output via the Result property of the agent response. Console.WriteLine("Assistant Output:"); @@ -57,11 +57,11 @@ ChatClientAgent agentWithPersonInfo = aiProjectClient.CreateAIAgent( }); // Invoke the agent with some unstructured input while streaming, to extract the structured information from. -IAsyncEnumerable updates = agentWithPersonInfo.RunStreamingAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); +IAsyncEnumerable updates = agentWithPersonInfo.RunStreamingAsync("Please provide information about John Smith, who is a 35-year-old software engineer."); // Assemble all the parts of the streamed output, since we can only deserialize once we have the full json, // then deserialize the response into the PersonInfo class. -PersonInfo personInfo = (await updates.ToAgentRunResponseAsync()).Deserialize(JsonSerializerOptions.Web); +PersonInfo personInfo = (await updates.ToAgentResponseAsync()).Deserialize(JsonSerializerOptions.Web); Console.WriteLine("Assistant Output:"); Console.WriteLine($"Name: {personInfo.Name}"); diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs index 002d547a14..4ba3ee4d34 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step07_Observability/Program.cs @@ -43,7 +43,7 @@ Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread) // Invoke the agent with streaming support. thread = await agent.GetNewThreadAsync(); -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync("Tell me a joke about a pirate.", thread)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a joke about a pirate.", thread)) { Console.WriteLine(update); } diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step08_DependencyInjection/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step08_DependencyInjection/Program.cs index de972b213a..d6d1dd8d9f 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step08_DependencyInjection/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step08_DependencyInjection/Program.cs @@ -65,7 +65,7 @@ internal sealed class SampleService(AIProjectClient client, AIAgent agent, IHost } // Stream the output to the console as it is generated. - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(input, this._thread, cancellationToken: cancellationToken)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, this._thread, cancellationToken: cancellationToken)) { Console.Write(update); } diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs index 6f915c69ba..fa841ca913 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step10_UsingImages/Program.cs @@ -26,7 +26,7 @@ ChatMessage message = new(ChatRole.User, [ AgentThread thread = await agent.GetNewThreadAsync(); -await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(message, thread)) +await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(message, thread)) { Console.WriteLine(update); } diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs index cd1e9e9ef4..0c6b76612c 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step12_Middleware/Program.cs @@ -52,18 +52,18 @@ AIAgent middlewareEnabledAgent = originalAgent AgentThread thread = await middlewareEnabledAgent.GetNewThreadAsync(); Console.WriteLine("\n\n=== Example 1: Wording Guardrail ==="); -AgentRunResponse guardRailedResponse = await middlewareEnabledAgent.RunAsync("Tell me something harmful."); +AgentResponse guardRailedResponse = await middlewareEnabledAgent.RunAsync("Tell me something harmful."); Console.WriteLine($"Guard railed response: {guardRailedResponse}"); Console.WriteLine("\n\n=== Example 2: PII detection ==="); -AgentRunResponse piiResponse = await middlewareEnabledAgent.RunAsync("My name is John Doe, call me at 123-456-7890 or email me at john@something.com"); +AgentResponse piiResponse = await middlewareEnabledAgent.RunAsync("My name is John Doe, call me at 123-456-7890 or email me at john@something.com"); Console.WriteLine($"Pii filtered response: {piiResponse}"); Console.WriteLine("\n\n=== Example 3: Agent function middleware ==="); // Agent function middleware support is limited to agents that wraps a upstream ChatClientAgent or derived from it. -AgentRunResponse functionCallResponse = await middlewareEnabledAgent.RunAsync("What's the current time and the weather in Seattle?", thread); +AgentResponse functionCallResponse = await middlewareEnabledAgent.RunAsync("What's the current time and the weather in Seattle?", thread); Console.WriteLine($"Function calling response: {functionCallResponse}"); // Special per-request middleware agent. @@ -78,7 +78,7 @@ AIAgent humanInTheLoopAgent = aiProjectClient.CreateAIAgent( tools: [new ApprovalRequiredAIFunction(AIFunctionFactory.Create(GetWeather, name: nameof(GetWeather)))]); // Using the ConsolePromptingApprovalMiddleware for a specific request to handle user approval during function calls. -AgentRunResponse response = await humanInTheLoopAgent +AgentResponse response = await humanInTheLoopAgent .AsBuilder() .Use(ConsolePromptingApprovalMiddleware, null) .Build() @@ -113,7 +113,7 @@ async ValueTask FunctionCallOverrideWeather(AIAgent agent, FunctionInvo } // This middleware redacts PII information from input and output messages. -async Task PIIMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +async Task PIIMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { // Redact PII information from input messages var filteredMessages = FilterMessages(messages); @@ -152,7 +152,7 @@ async Task PIIMiddleware(IEnumerable messages, Ag } // This middleware enforces guardrails by redacting certain keywords from input and output messages. -async Task GuardrailMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +async Task GuardrailMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { // Redact keywords from input messages var filteredMessages = FilterMessages(messages); @@ -189,9 +189,9 @@ async Task GuardrailMiddleware(IEnumerable messag } // This middleware handles Human in the loop console interaction for any user approval required during function calling. -async Task ConsolePromptingApprovalMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) +async Task ConsolePromptingApprovalMiddleware(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { - AgentRunResponse response = await innerAgent.RunAsync(messages, thread, options, cancellationToken); + AgentResponse response = await innerAgent.RunAsync(messages, thread, options, cancellationToken); List userInputRequests = response.UserInputRequests.ToList(); diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs index 0f6f6ef2d9..858c678528 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step14_CodeInterpreter/Program.cs @@ -49,10 +49,10 @@ AIAgent agentOption2 = await aiProjectClient.CreateAIAgentAsync( // Either invoke option1 or option2 agent, should have same result // Option 1 -AgentRunResponse response = await agentOption1.RunAsync("I need to solve the equation sin(x) + x^2 = 42"); +AgentResponse response = await agentOption1.RunAsync("I need to solve the equation sin(x) + x^2 = 42"); // Option 2 -// AgentRunResponse response = await agentOption2.RunAsync("I need to solve the equation sin(x) + x^2 = 42"); +// AgentResponse response = await agentOption2.RunAsync("I need to solve the equation sin(x) + x^2 = 42"); // Get the CodeInterpreterToolCallContent CodeInterpreterToolCallContent? toolCallContent = response.Messages.SelectMany(m => m.Contents).OfType().FirstOrDefault(); diff --git a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs index 9f4002deae..9d8cab17a0 100644 --- a/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs +++ b/dotnet/samples/GettingStarted/FoundryAgents/FoundryAgents_Step15_ComputerUse/Program.cs @@ -93,7 +93,7 @@ internal sealed class Program // Initial request with screenshot - start with Bing search page Console.WriteLine("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); - AgentRunResponse runResponse = await agent.RunAsync(message, thread: thread, options: runOptions); + AgentResponse response = await agent.RunAsync(message, thread: thread, options: runOptions); // Main interaction loop const int MaxIterations = 10; @@ -105,7 +105,7 @@ internal sealed class Program while (true) { // Poll until the response is complete. - while (runResponse.ContinuationToken is { } token) + while (response.ContinuationToken is { } token) { // Wait before polling again. await Task.Delay(TimeSpan.FromSeconds(2)); @@ -113,10 +113,10 @@ internal sealed class Program // Continue with the token. runOptions.ContinuationToken = token; - runResponse = await agent.RunAsync(thread, runOptions); + response = await agent.RunAsync(thread, runOptions); } - Console.WriteLine($"Agent response received (ID: {runResponse.ResponseId})"); + Console.WriteLine($"Agent response received (ID: {response.ResponseId})"); if (iteration >= MaxIterations) { @@ -128,7 +128,7 @@ internal sealed class Program Console.WriteLine($"\n--- Iteration {iteration} ---"); // Check for computer calls in the response - IEnumerable computerCallResponseItems = runResponse.Messages + IEnumerable computerCallResponseItems = response.Messages .SelectMany(x => x.Contents) .Where(c => c.RawRepresentation is ComputerCallResponseItem and not null) .Select(c => (ComputerCallResponseItem)c.RawRepresentation!); @@ -137,7 +137,7 @@ internal sealed class Program if (firstComputerCall is null) { Console.WriteLine("No computer call actions found. Ending interaction."); - Console.WriteLine($"Final Response: {runResponse}"); + Console.WriteLine($"Final Response: {response}"); break; } @@ -168,7 +168,7 @@ internal sealed class Program // Follow-up message with action result and new screenshot message = new(ChatRole.User, [content]); - runResponse = await agent.RunAsync(message, thread: thread, options: runOptions); + response = await agent.RunAsync(message, thread: thread, options: runOptions); } } } diff --git a/dotnet/samples/GettingStarted/Workflows/Agents/WorkflowAsAnAgent/Program.cs b/dotnet/samples/GettingStarted/Workflows/Agents/WorkflowAsAnAgent/Program.cs index 18b19c5885..4ba04bd87f 100644 --- a/dotnet/samples/GettingStarted/Workflows/Agents/WorkflowAsAnAgent/Program.cs +++ b/dotnet/samples/GettingStarted/Workflows/Agents/WorkflowAsAnAgent/Program.cs @@ -58,8 +58,8 @@ public static class Program // re-render all messages on each update. static async Task ProcessInputAsync(AIAgent agent, AgentThread thread, string input) { - Dictionary> buffer = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(input, thread)) + Dictionary> buffer = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, thread)) { if (update.MessageId is null || string.IsNullOrEmpty(update.Text)) { @@ -68,7 +68,7 @@ public static class Program } Console.Clear(); - if (!buffer.TryGetValue(update.MessageId, out List? value)) + if (!buffer.TryGetValue(update.MessageId, out List? value)) { value = []; buffer[update.MessageId] = value; diff --git a/dotnet/samples/GettingStarted/Workflows/Declarative/ExecuteCode/Generated.cs b/dotnet/samples/GettingStarted/Workflows/Declarative/ExecuteCode/Generated.cs index 6fc508064e..6b46ca1027 100644 --- a/dotnet/samples/GettingStarted/Workflows/Declarative/ExecuteCode/Generated.cs +++ b/dotnet/samples/GettingStarted/Workflows/Declarative/ExecuteCode/Generated.cs @@ -65,7 +65,7 @@ public static class SampleWorkflowProvider bool autoSend = true; IList? inputMessages = null; - AgentRunResponse agentResponse = + AgentResponse agentResponse = await InvokeAgentAsync( context, agentName, @@ -102,7 +102,7 @@ public static class SampleWorkflowProvider bool autoSend = false; IList? inputMessages = null; - AgentRunResponse agentResponse = + AgentResponse agentResponse = await InvokeAgentAsync( context, agentName, @@ -175,7 +175,7 @@ public static class SampleWorkflowProvider GOLD STAR! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -196,7 +196,7 @@ public static class SampleWorkflowProvider Let's try again later... """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/samples/GettingStarted/Workflows/Declarative/HostedWorkflow/Program.cs b/dotnet/samples/GettingStarted/Workflows/Declarative/HostedWorkflow/Program.cs index c3cd0219d3..ee5c229f3d 100644 --- a/dotnet/samples/GettingStarted/Workflows/Declarative/HostedWorkflow/Program.cs +++ b/dotnet/samples/GettingStarted/Workflows/Declarative/HostedWorkflow/Program.cs @@ -65,10 +65,10 @@ internal sealed class Program }; ChatClientAgentRunOptions runOptions = new(chatOptions); - IAsyncEnumerable agentResponseUpdates = agent.RunStreamingAsync(workflowInput, thread, runOptions); + IAsyncEnumerable agentResponseUpdates = agent.RunStreamingAsync(workflowInput, thread, runOptions); string? lastMessageId = null; - await foreach (AgentRunResponseUpdate responseUpdate in agentResponseUpdates) + await foreach (AgentResponseUpdate responseUpdate in agentResponseUpdates) { if (responseUpdate.MessageId != lastMessageId) { diff --git a/dotnet/samples/GettingStarted/Workflows/Observability/WorkflowAsAnAgent/Program.cs b/dotnet/samples/GettingStarted/Workflows/Observability/WorkflowAsAnAgent/Program.cs index e2790d5196..bf9f17ac80 100644 --- a/dotnet/samples/GettingStarted/Workflows/Observability/WorkflowAsAnAgent/Program.cs +++ b/dotnet/samples/GettingStarted/Workflows/Observability/WorkflowAsAnAgent/Program.cs @@ -111,8 +111,8 @@ public static class Program // re-render all messages on each update. static async Task ProcessInputAsync(AIAgent agent, AgentThread thread, string input) { - Dictionary> buffer = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(input, thread)) + Dictionary> buffer = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, thread)) { if (update.MessageId is null || string.IsNullOrEmpty(update.Text)) { @@ -121,7 +121,7 @@ public static class Program } Console.Clear(); - if (!buffer.TryGetValue(update.MessageId, out List? value)) + if (!buffer.TryGetValue(update.MessageId, out List? value)) { value = []; buffer[update.MessageId] = value; diff --git a/dotnet/samples/GettingStarted/Workflows/_Foundational/08_WriterCriticWorkflow/Program.cs b/dotnet/samples/GettingStarted/Workflows/_Foundational/08_WriterCriticWorkflow/Program.cs index 265a87b5f6..fbf85cf0d0 100644 --- a/dotnet/samples/GettingStarted/Workflows/_Foundational/08_WriterCriticWorkflow/Program.cs +++ b/dotnet/samples/GettingStarted/Workflows/_Foundational/08_WriterCriticWorkflow/Program.cs @@ -254,7 +254,7 @@ internal sealed class WriterExecutor : Executor Console.WriteLine($"\n=== Writer (Iteration {state.Iteration}) ===\n"); StringBuilder sb = new(); - await foreach (AgentRunResponseUpdate update in this._agent.RunStreamingAsync(message, cancellationToken: cancellationToken)) + await foreach (AgentResponseUpdate update in this._agent.RunStreamingAsync(message, cancellationToken: cancellationToken)) { if (!string.IsNullOrEmpty(update.Text)) { @@ -313,10 +313,10 @@ internal sealed class CriticExecutor : Executor Console.WriteLine($"=== Critic (Iteration {state.Iteration}) ===\n"); // Use RunStreamingAsync to get streaming updates, then deserialize at the end - IAsyncEnumerable updates = this._agent.RunStreamingAsync(message, cancellationToken: cancellationToken); + IAsyncEnumerable updates = this._agent.RunStreamingAsync(message, cancellationToken: cancellationToken); // Stream the output in real-time (for any rationale/explanation) - await foreach (AgentRunResponseUpdate update in updates) + await foreach (AgentResponseUpdate update in updates) { if (!string.IsNullOrEmpty(update.Text)) { @@ -326,7 +326,7 @@ internal sealed class CriticExecutor : Executor Console.WriteLine("\n"); // Convert the stream to a response and deserialize the structured output - AgentRunResponse response = await updates.ToAgentRunResponseAsync(cancellationToken); + AgentResponse response = await updates.ToAgentResponseAsync(cancellationToken); CriticDecision decision = response.Deserialize(JsonSerializerOptions.Web); Console.WriteLine($"Decision: {(decision.Approved ? "✅ APPROVED" : "❌ NEEDS REVISION")}"); @@ -394,7 +394,7 @@ internal sealed class SummaryExecutor : Executor string prompt = $"Present this approved content:\n\n{message.Content}"; StringBuilder sb = new(); - await foreach (AgentRunResponseUpdate update in this._agent.RunStreamingAsync(new ChatMessage(ChatRole.User, prompt), cancellationToken: cancellationToken)) + await foreach (AgentResponseUpdate update in this._agent.RunStreamingAsync(new ChatMessage(ChatRole.User, prompt), cancellationToken: cancellationToken)) { if (!string.IsNullOrEmpty(update.Text)) { diff --git a/dotnet/samples/M365Agent/AFAgentApplication.cs b/dotnet/samples/M365Agent/AFAgentApplication.cs index 8afff15167..0962c1d6d2 100644 --- a/dotnet/samples/M365Agent/AFAgentApplication.cs +++ b/dotnet/samples/M365Agent/AFAgentApplication.cs @@ -49,16 +49,16 @@ internal sealed class AFAgentApplication : AgentApplication ChatMessage chatMessage = HandleUserInput(turnContext); // Invoke the WeatherForecastAgent to process the message - AgentRunResponse agentRunResponse = await this._agent.RunAsync(chatMessage, agentThread, cancellationToken: cancellationToken); + AgentResponse agentResponse = await this._agent.RunAsync(chatMessage, agentThread, cancellationToken: cancellationToken); // Check for any user input requests in the response // and turn them into adaptive cards in the streaming response. List? attachments = null; - HandleUserInputRequests(agentRunResponse, ref attachments); + HandleUserInputRequests(agentResponse, ref attachments); // Check for Adaptive Card content in the response messages // and return them appropriately in the response. - var adaptiveCards = agentRunResponse.Messages.SelectMany(x => x.Contents).OfType().ToList(); + var adaptiveCards = agentResponse.Messages.SelectMany(x => x.Contents).OfType().ToList(); if (adaptiveCards.Count > 0) { attachments ??= []; @@ -70,7 +70,7 @@ internal sealed class AFAgentApplication : AgentApplication } else { - turnContext.StreamingResponse.QueueTextChunk(agentRunResponse.Text); + turnContext.StreamingResponse.QueueTextChunk(agentResponse.Text); } // If created any adaptive cards, add them to the final message. @@ -134,9 +134,9 @@ internal sealed class AFAgentApplication : AgentApplication /// When the agent returns any user input requests, this method converts them into adaptive cards that /// asks the user to approve or deny the requests. /// - /// The that may contain the user input requests. + /// The that may contain the user input requests. /// The list of to which the adaptive cards will be added. - private static void HandleUserInputRequests(AgentRunResponse response, ref List? attachments) + private static void HandleUserInputRequests(AgentResponse response, ref List? attachments) { var userInputRequests = response.UserInputRequests.ToList(); if (userInputRequests.Count > 0) diff --git a/dotnet/samples/M365Agent/Agents/WeatherForecastAgent.cs b/dotnet/samples/M365Agent/Agents/WeatherForecastAgent.cs index ff7af20ba9..a4023a2c58 100644 --- a/dotnet/samples/M365Agent/Agents/WeatherForecastAgent.cs +++ b/dotnet/samples/M365Agent/Agents/WeatherForecastAgent.cs @@ -48,7 +48,7 @@ public class WeatherForecastAgent : DelegatingAIAgent { } - protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { var response = await base.RunCoreAsync(messages, thread, options, cancellationToken); diff --git a/dotnet/src/Microsoft.Agents.AI.A2A/A2AAgent.cs b/dotnet/src/Microsoft.Agents.AI.A2A/A2AAgent.cs index a31c3110dc..01e7c8f146 100644 --- a/dotnet/src/Microsoft.Agents.AI.A2A/A2AAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.A2A/A2AAgent.cs @@ -68,7 +68,7 @@ public sealed class A2AAgent : AIAgent => new(new A2AAgentThread(serializedThread, jsonSerializerOptions)); /// - protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { _ = Throw.IfNull(messages); @@ -99,7 +99,7 @@ public sealed class A2AAgent : AIAgent { UpdateThread(typedThread, message.ContextId); - return new AgentRunResponse + return new AgentResponse { AgentId = this.Id, ResponseId = message.MessageId, @@ -113,7 +113,7 @@ public sealed class A2AAgent : AIAgent { UpdateThread(typedThread, agentTask.ContextId, agentTask.Id); - var response = new AgentRunResponse + var response = new AgentResponse { AgentId = this.Id, ResponseId = agentTask.Id, @@ -135,7 +135,7 @@ public sealed class A2AAgent : AIAgent } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { _ = Throw.IfNull(messages); @@ -291,9 +291,9 @@ public sealed class A2AAgent : AIAgent return null; } - private AgentRunResponseUpdate ConvertToAgentResponseUpdate(AgentMessage message) + private AgentResponseUpdate ConvertToAgentResponseUpdate(AgentMessage message) { - return new AgentRunResponseUpdate + return new AgentResponseUpdate { AgentId = this.Id, ResponseId = message.MessageId, @@ -305,9 +305,9 @@ public sealed class A2AAgent : AIAgent }; } - private AgentRunResponseUpdate ConvertToAgentResponseUpdate(AgentTask task) + private AgentResponseUpdate ConvertToAgentResponseUpdate(AgentTask task) { - return new AgentRunResponseUpdate + return new AgentResponseUpdate { AgentId = this.Id, ResponseId = task.Id, @@ -318,9 +318,9 @@ public sealed class A2AAgent : AIAgent }; } - private AgentRunResponseUpdate ConvertToAgentResponseUpdate(TaskUpdateEvent taskUpdateEvent) + private AgentResponseUpdate ConvertToAgentResponseUpdate(TaskUpdateEvent taskUpdateEvent) { - AgentRunResponseUpdate responseUpdate = new() + AgentResponseUpdate responseUpdate = new() { AgentId = this.Id, ResponseId = taskUpdateEvent.TaskId, diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs index 71135ad6e6..10284dc25a 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AIAgent.cs @@ -146,12 +146,12 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// /// This overload is useful when the agent has sufficient context from previous messages in the thread /// or from its initial configuration to generate a meaningful response without additional input. /// - public Task RunAsync( + public Task RunAsync( AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => @@ -167,13 +167,13 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// is , empty, or contains only whitespace. /// /// The provided text will be wrapped in a with the role /// before being sent to the agent. This is a convenience method for simple text-based interactions. /// - public Task RunAsync( + public Task RunAsync( string message, AgentThread? thread = null, AgentRunOptions? options = null, @@ -194,9 +194,9 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// is . - public Task RunAsync( + public Task RunAsync( ChatMessage message, AgentThread? thread = null, AgentRunOptions? options = null, @@ -217,7 +217,7 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// /// /// This method delegates to to perform the actual agent invocation. It handles collections of messages, @@ -229,7 +229,7 @@ public abstract class AIAgent /// The agent's response will also be added to if one is provided. /// /// - public Task RunAsync( + public Task RunAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -246,7 +246,7 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// /// /// This is the primary invocation method that implementations must override. It handles collections of messages, @@ -258,7 +258,7 @@ public abstract class AIAgent /// The agent's response will also be added to if one is provided. /// /// - protected abstract Task RunCoreAsync( + protected abstract Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -273,8 +273,8 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. - public IAsyncEnumerable RunStreamingAsync( + /// An asynchronous enumerable of instances representing the streaming response. + public IAsyncEnumerable RunStreamingAsync( AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => @@ -290,13 +290,13 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. + /// An asynchronous enumerable of instances representing the streaming response. /// is , empty, or contains only whitespace. /// /// The provided text will be wrapped in a with the role. /// Streaming invocation provides real-time updates as the agent generates its response. /// - public IAsyncEnumerable RunStreamingAsync( + public IAsyncEnumerable RunStreamingAsync( string message, AgentThread? thread = null, AgentRunOptions? options = null, @@ -317,9 +317,9 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. + /// An asynchronous enumerable of instances representing the streaming response. /// is . - public IAsyncEnumerable RunStreamingAsync( + public IAsyncEnumerable RunStreamingAsync( ChatMessage message, AgentThread? thread = null, AgentRunOptions? options = null, @@ -340,18 +340,18 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. + /// An asynchronous enumerable of instances representing the streaming response. /// /// /// This method delegates to to perform the actual streaming invocation. It provides real-time /// updates as the agent processes the input and generates its response, enabling more responsive user experiences. /// /// - /// Each represents a portion of the complete response, allowing consumers + /// Each represents a portion of the complete response, allowing consumers /// to display partial results, implement progressive loading, or provide immediate feedback to users. /// /// - public IAsyncEnumerable RunStreamingAsync( + public IAsyncEnumerable RunStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -368,18 +368,18 @@ public abstract class AIAgent /// /// Optional configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. + /// An asynchronous enumerable of instances representing the streaming response. /// /// /// This is the primary streaming invocation method that implementations must override. It provides real-time /// updates as the agent processes the input and generates its response, enabling more responsive user experiences. /// /// - /// Each represents a portion of the complete response, allowing consumers + /// Each represents a portion of the complete response, allowing consumers /// to display partial results, implement progressive loading, or provide immediate feedback to users. /// /// - protected abstract IAsyncEnumerable RunCoreStreamingAsync( + protected abstract IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentAbstractionsJsonUtilities.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentAbstractionsJsonUtilities.cs index d5003cace0..937d871c56 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentAbstractionsJsonUtilities.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentAbstractionsJsonUtilities.cs @@ -76,10 +76,10 @@ public static partial class AgentAbstractionsJsonUtilities // Agent abstraction types [JsonSerializable(typeof(AgentRunOptions))] - [JsonSerializable(typeof(AgentRunResponse))] - [JsonSerializable(typeof(AgentRunResponse[]))] - [JsonSerializable(typeof(AgentRunResponseUpdate))] - [JsonSerializable(typeof(AgentRunResponseUpdate[]))] + [JsonSerializable(typeof(AgentResponse))] + [JsonSerializable(typeof(AgentResponse[]))] + [JsonSerializable(typeof(AgentResponseUpdate))] + [JsonSerializable(typeof(AgentResponseUpdate[]))] [JsonSerializable(typeof(ServiceIdAgentThread.ServiceIdAgentThreadState))] [JsonSerializable(typeof(InMemoryAgentThread.InMemoryAgentThreadState))] [JsonSerializable(typeof(InMemoryChatMessageStore.StoreState))] diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponse.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse.cs similarity index 92% rename from dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponse.cs rename to dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse.cs index 7828b5c62d..dbded1ef88 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponse.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse.cs @@ -24,30 +24,30 @@ namespace Microsoft.Agents.AI; /// /// /// -/// provides one or more response messages and metadata about the response. +/// provides one or more response messages and metadata about the response. /// A typical response will contain a single message, however a response may contain multiple messages /// in a variety of scenarios. For example, if the agent internally invokes functions or tools, performs /// RAG retrievals or has other complex logic, a single run by the agent may produce many messages showing /// the intermediate progress that the agent made towards producing the agent result. /// /// -/// To get the text result of the response, use the property or simply call on the . +/// To get the text result of the response, use the property or simply call on the . /// /// -public class AgentRunResponse +public class AgentResponse { /// The response messages. private IList? _messages; - /// Initializes a new instance of the class. - public AgentRunResponse() + /// Initializes a new instance of the class. + public AgentResponse() { } - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// The response message to include in this response. /// is . - public AgentRunResponse(ChatMessage message) + public AgentResponse(ChatMessage message) { _ = Throw.IfNull(message); @@ -55,16 +55,16 @@ public class AgentRunResponse } /// - /// Initializes a new instance of the class from an existing . + /// Initializes a new instance of the class from an existing . /// - /// The from which to populate this . + /// The from which to populate this . /// is . /// /// This constructor creates an agent response that wraps an existing , preserving all /// metadata and storing the original response in for access to /// the underlying implementation details. /// - public AgentRunResponse(ChatResponse response) + public AgentResponse(ChatResponse response) { _ = Throw.IfNull(response); @@ -78,10 +78,10 @@ public class AgentRunResponse } /// - /// Initializes a new instance of the class with the specified collection of messages. + /// Initializes a new instance of the class with the specified collection of messages. /// /// The collection of response messages, or to create an empty response. - public AgentRunResponse(IList? messages) + public AgentResponse(IList? messages) { this._messages = messages; } @@ -201,7 +201,7 @@ public class AgentRunResponse /// Gets or sets the raw representation of the run response from an underlying implementation. /// - /// If a is created to represent some underlying object from another object + /// If a is created to represent some underlying object from another object /// model, this property can be used to store that original object. This can be useful for debugging or /// for enabling a consumer to access the underlying object model if needed. /// @@ -226,11 +226,11 @@ public class AgentRunResponse public override string ToString() => this.Text; /// - /// Converts this into a collection of instances + /// Converts this into a collection of instances /// suitable for streaming scenarios. /// /// - /// An array of instances that collectively represent + /// An array of instances that collectively represent /// the same information as this response. /// /// @@ -245,12 +245,12 @@ public class AgentRunResponse /// original message sequence. /// /// - public AgentRunResponseUpdate[] ToAgentRunResponseUpdates() + public AgentResponseUpdate[] ToAgentResponseUpdates() { - AgentRunResponseUpdate? extra = null; + AgentResponseUpdate? extra = null; if (this.AdditionalProperties is not null || this.Usage is not null) { - extra = new AgentRunResponseUpdate + extra = new AgentResponseUpdate { AdditionalProperties = this.AdditionalProperties, }; @@ -262,13 +262,13 @@ public class AgentRunResponse } int messageCount = this._messages?.Count ?? 0; - var updates = new AgentRunResponseUpdate[messageCount + (extra is not null ? 1 : 0)]; + var updates = new AgentResponseUpdate[messageCount + (extra is not null ? 1 : 0)]; int i; for (i = 0; i < messageCount; i++) { ChatMessage message = this._messages![i]; - updates[i] = new AgentRunResponseUpdate + updates[i] = new AgentResponseUpdate { AdditionalProperties = message.AdditionalProperties, AuthorName = message.AuthorName, diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponseExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseExtensions.cs similarity index 71% rename from dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponseExtensions.cs rename to dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseExtensions.cs index cb3ad7ec74..75ff6fb359 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponseExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseExtensions.cs @@ -11,24 +11,24 @@ using Microsoft.Shared.Diagnostics; namespace Microsoft.Agents.AI; /// -/// Provides extension methods for working with and instances. +/// Provides extension methods for working with and instances. /// -public static class AgentRunResponseExtensions +public static class AgentResponseExtensions { /// - /// Creates a from an instance. + /// Creates a from an instance. /// - /// The to convert. + /// The to convert. /// A built from the specified . /// is . /// - /// If the 's is already a + /// If the 's is already a /// instance, that instance is returned directly. /// Otherwise, a new is created and populated with the data from the . - /// The resulting instance is a shallow copy; any reference-type members (e.g. ) + /// The resulting instance is a shallow copy; any reference-type members (e.g. ) /// will be shared between the two instances. /// - public static ChatResponse AsChatResponse(this AgentRunResponse response) + public static ChatResponse AsChatResponse(this AgentResponse response) { Throw.IfNull(response); @@ -47,19 +47,19 @@ public static class AgentRunResponseExtensions } /// - /// Creates a from an instance. + /// Creates a from an instance. /// - /// The to convert. + /// The to convert. /// A built from the specified . /// is . /// - /// If the 's is already a + /// If the 's is already a /// instance, that instance is returned directly. /// Otherwise, a new is created and populated with the data from the . - /// The resulting instance is a shallow copy; any reference-type members (e.g. ) + /// The resulting instance is a shallow copy; any reference-type members (e.g. ) /// will be shared between the two instances. /// - public static ChatResponseUpdate AsChatResponseUpdate(this AgentRunResponseUpdate responseUpdate) + public static ChatResponseUpdate AsChatResponseUpdate(this AgentResponseUpdate responseUpdate) { Throw.IfNull(responseUpdate); @@ -81,17 +81,17 @@ public static class AgentRunResponseExtensions /// /// Creates an asynchronous enumerable of instances from an asynchronous - /// enumerable of instances. + /// enumerable of instances. /// - /// The sequence of instances to convert. + /// The sequence of instances to convert. /// An asynchronous enumerable of instances built from . /// is . /// - /// Each is converted to a using + /// Each is converted to a using /// . /// public static async IAsyncEnumerable AsChatResponseUpdatesAsync( - this IAsyncEnumerable responseUpdates) + this IAsyncEnumerable responseUpdates) { Throw.IfNull(responseUpdates); @@ -102,71 +102,71 @@ public static class AgentRunResponseExtensions } /// - /// Combines a sequence of instances into a single . + /// Combines a sequence of instances into a single . /// /// The sequence of updates to be combined into a single response. - /// A single that represents the combined state of all the updates. + /// A single that represents the combined state of all the updates. /// is . /// - /// As part of combining into a single , the method will attempt to reconstruct - /// instances. This includes using to determine + /// As part of combining into a single , the method will attempt to reconstruct + /// instances. This includes using to determine /// message boundaries, as well as coalescing contiguous items where applicable, e.g. multiple /// instances in a row may be combined into a single . /// - public static AgentRunResponse ToAgentRunResponse( - this IEnumerable updates) + public static AgentResponse ToAgentResponse( + this IEnumerable updates) { _ = Throw.IfNull(updates); - AgentRunResponseDetails additionalDetails = new(); + AgentResponseDetails additionalDetails = new(); ChatResponse chatResponse = AsChatResponseUpdatesWithAdditionalDetails(updates, additionalDetails) .ToChatResponse(); - return new AgentRunResponse(chatResponse) + return new AgentResponse(chatResponse) { AgentId = additionalDetails.AgentId, }; } /// - /// Asynchronously combines a sequence of instances into a single . + /// Asynchronously combines a sequence of instances into a single . /// /// The asynchronous sequence of updates to be combined into a single response. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains a single that represents the combined state of all the updates. + /// A task that represents the asynchronous operation. The task result contains a single that represents the combined state of all the updates. /// is . /// /// - /// This is the asynchronous version of . + /// This is the asynchronous version of . /// It performs the same combining logic but operates on an asynchronous enumerable of updates. /// /// - /// As part of combining into a single , the method will attempt to reconstruct - /// instances. This includes using to determine + /// As part of combining into a single , the method will attempt to reconstruct + /// instances. This includes using to determine /// message boundaries, as well as coalescing contiguous items where applicable, e.g. multiple /// instances in a row may be combined into a single . /// /// - public static Task ToAgentRunResponseAsync( - this IAsyncEnumerable updates, + public static Task ToAgentResponseAsync( + this IAsyncEnumerable updates, CancellationToken cancellationToken = default) { _ = Throw.IfNull(updates); - return ToAgentRunResponseAsync(updates, cancellationToken); + return ToAgentResponseAsync(updates, cancellationToken); - static async Task ToAgentRunResponseAsync( - IAsyncEnumerable updates, + static async Task ToAgentResponseAsync( + IAsyncEnumerable updates, CancellationToken cancellationToken) { - AgentRunResponseDetails additionalDetails = new(); + AgentResponseDetails additionalDetails = new(); ChatResponse chatResponse = await AsChatResponseUpdatesWithAdditionalDetailsAsync(updates, additionalDetails, cancellationToken) .ToChatResponseAsync(cancellationToken) .ConfigureAwait(false); - return new AgentRunResponse(chatResponse) + return new AgentResponse(chatResponse) { AgentId = additionalDetails.AgentId, }; @@ -174,8 +174,8 @@ public static class AgentRunResponseExtensions } private static IEnumerable AsChatResponseUpdatesWithAdditionalDetails( - IEnumerable updates, - AgentRunResponseDetails additionalDetails) + IEnumerable updates, + AgentResponseDetails additionalDetails) { foreach (var update in updates) { @@ -185,8 +185,8 @@ public static class AgentRunResponseExtensions } private static async IAsyncEnumerable AsChatResponseUpdatesWithAdditionalDetailsAsync( - IAsyncEnumerable updates, - AgentRunResponseDetails additionalDetails, + IAsyncEnumerable updates, + AgentResponseDetails additionalDetails, [EnumeratorCancellation] CancellationToken cancellationToken) { await foreach (var update in updates.WithCancellation(cancellationToken).ConfigureAwait(false)) @@ -196,7 +196,7 @@ public static class AgentRunResponseExtensions } } - private static void UpdateAdditionalDetails(AgentRunResponseUpdate update, AgentRunResponseDetails details) + private static void UpdateAdditionalDetails(AgentResponseUpdate update, AgentResponseDetails details) { if (update.AgentId is { Length: > 0 }) { @@ -204,7 +204,7 @@ public static class AgentRunResponseExtensions } } - private sealed class AgentRunResponseDetails + private sealed class AgentResponseDetails { public string? AgentId { get; set; } } diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponseUpdate.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseUpdate.cs similarity index 82% rename from dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponseUpdate.cs rename to dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseUpdate.cs index ccf3deae54..041af06593 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponseUpdate.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponseUpdate.cs @@ -16,54 +16,54 @@ namespace Microsoft.Agents.AI; /// /// /// -/// is so named because it represents updates +/// is so named because it represents updates /// that layer on each other to form a single agent response. Conceptually, this combines the roles of -/// and in streaming output. +/// and in streaming output. /// /// -/// To get the text result of this response chunk, use the property or simply call on the . +/// To get the text result of this response chunk, use the property or simply call on the . /// /// -/// The relationship between and is -/// codified in the and -/// , which enable bidirectional conversions +/// The relationship between and is +/// codified in the and +/// , which enable bidirectional conversions /// between the two. Note, however, that the provided conversions may be lossy, for example if multiple /// updates all have different objects whereas there's only one slot for -/// such an object available in . +/// such an object available in . /// /// [DebuggerDisplay("[{Role}] {ContentForDebuggerDisplay}{EllipsesForDebuggerDisplay,nq}")] -public class AgentRunResponseUpdate +public class AgentResponseUpdate { /// The response update content items. private IList? _contents; - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. [JsonConstructor] - public AgentRunResponseUpdate() + public AgentResponseUpdate() { } - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// The role of the author of the update. /// The text content of the update. - public AgentRunResponseUpdate(ChatRole? role, string? content) + public AgentResponseUpdate(ChatRole? role, string? content) : this(role, content is null ? null : [new TextContent(content)]) { } - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// The role of the author of the update. /// The contents of the update. - public AgentRunResponseUpdate(ChatRole? role, IList? contents) + public AgentResponseUpdate(ChatRole? role, IList? contents) { this.Role = role; this._contents = contents; } - /// Initializes a new instance of the class. - /// The from which to seed this . - public AgentRunResponseUpdate(ChatResponseUpdate chatResponseUpdate) + /// Initializes a new instance of the class. + /// The from which to seed this . + public AgentResponseUpdate(ChatResponseUpdate chatResponseUpdate) { _ = Throw.IfNull(chatResponseUpdate); @@ -112,7 +112,7 @@ public class AgentRunResponseUpdate /// Gets or sets the raw representation of the response update from an underlying implementation. /// - /// If a is created to represent some underlying object from another object + /// If a is created to represent some underlying object from another object /// model, this property can be used to store that original object. This can be useful for debugging or /// for enabling a consumer to access the underlying object model if needed. /// @@ -136,8 +136,8 @@ public class AgentRunResponseUpdate /// Some providers may consider streaming responses to be a single message, and in that case /// the value of this property may be the same as the response ID. /// - /// This value is used when - /// groups instances into instances. + /// This value is used when + /// groups instances into instances. /// The value must be unique to each call to the underlying provider, and must be shared by /// all updates that are part of the same logical message within a streaming response. /// diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponse{T}.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse{T}.cs similarity index 63% rename from dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponse{T}.cs rename to dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse{T}.cs index 9bac7df6fe..2a18aadb37 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunResponse{T}.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentResponse{T}.cs @@ -8,18 +8,18 @@ namespace Microsoft.Agents.AI; /// Represents the response of the specified type to an run request. /// /// The type of value expected from the agent. -public abstract class AgentRunResponse : AgentRunResponse +public abstract class AgentResponse : AgentResponse { - /// Initializes a new instance of the class. - protected AgentRunResponse() + /// Initializes a new instance of the class. + protected AgentResponse() { } /// - /// Initializes a new instance of the class from an existing . + /// Initializes a new instance of the class from an existing . /// - /// The from which to populate this . - protected AgentRunResponse(ChatResponse response) : base(response) + /// The from which to populate this . + protected AgentResponse(ChatResponse response) : base(response) { } diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunOptions.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunOptions.cs index 9cd6d51680..5fea157b75 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunOptions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/AgentRunOptions.cs @@ -43,10 +43,10 @@ public class AgentRunOptions /// This property is used for background responses that can be activated via the /// property if the implementation supports them. /// Streamed background responses, such as those returned by default by - /// can be resumed if interrupted. This means that a continuation token obtained from the + /// can be resumed if interrupted. This means that a continuation token obtained from the /// of an update just before the interruption occurred can be passed to this property to resume the stream from the point of interruption. /// Non-streamed background responses, such as those returned by , - /// can be polled for completion by obtaining the token from the property + /// can be polled for completion by obtaining the token from the property /// and passing it via this property on subsequent calls to . /// public ResponseContinuationToken? ContinuationToken { get; set; } diff --git a/dotnet/src/Microsoft.Agents.AI.Abstractions/DelegatingAIAgent.cs b/dotnet/src/Microsoft.Agents.AI.Abstractions/DelegatingAIAgent.cs index 8f6a36a670..e9a3d5bc7a 100644 --- a/dotnet/src/Microsoft.Agents.AI.Abstractions/DelegatingAIAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.Abstractions/DelegatingAIAgent.cs @@ -81,7 +81,7 @@ public abstract class DelegatingAIAgent : AIAgent => this.InnerAgent.DeserializeThreadAsync(serializedThread, jsonSerializerOptions, cancellationToken); /// - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -89,7 +89,7 @@ public abstract class DelegatingAIAgent : AIAgent => this.InnerAgent.RunAsync(messages, thread, options, cancellationToken); /// - protected override IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, diff --git a/dotnet/src/Microsoft.Agents.AI.CopilotStudio/CopilotStudioAgent.cs b/dotnet/src/Microsoft.Agents.AI.CopilotStudio/CopilotStudioAgent.cs index 391af7849e..6b69975f50 100644 --- a/dotnet/src/Microsoft.Agents.AI.CopilotStudio/CopilotStudioAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.CopilotStudio/CopilotStudioAgent.cs @@ -58,7 +58,7 @@ public class CopilotStudioAgent : AIAgent => new(new CopilotStudioAgentThread(serializedThread, jsonSerializerOptions)); /// - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -88,7 +88,7 @@ public class CopilotStudioAgent : AIAgent // TODO: Review list of ChatResponse properties to ensure we set all availble values. // Setting ResponseId and MessageId end up being particularly important for streaming consumers // so that they can tell things like response boundaries. - return new AgentRunResponse(responseMessagesList) + return new AgentResponse(responseMessagesList) { AgentId = this.Id, ResponseId = responseMessagesList.LastOrDefault()?.MessageId, @@ -96,7 +96,7 @@ public class CopilotStudioAgent : AIAgent } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -125,7 +125,7 @@ public class CopilotStudioAgent : AIAgent // TODO: Review list of ChatResponse properties to ensure we set all availble values. // Setting ResponseId and MessageId end up being particularly important for streaming consumers // so that they can tell things like response boundaries. - yield return new AgentRunResponseUpdate(message.Role, message.Contents) + yield return new AgentResponseUpdate(message.Role, message.Contents) { AgentId = this.Id, AdditionalProperties = message.AdditionalProperties, diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentEntity.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentEntity.cs index 3c23e46fd3..15432804f3 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentEntity.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentEntity.cs @@ -21,7 +21,7 @@ internal class AgentEntity(IServiceProvider services, CancellationToken cancella ? cancellationToken : services.GetService()?.ApplicationStopping ?? CancellationToken.None; - public Task RunAgentAsync(RunRequest request) + public Task RunAgentAsync(RunRequest request) { return this.Run(request); } @@ -29,7 +29,7 @@ internal class AgentEntity(IServiceProvider services, CancellationToken cancella // IDE1006 and VSTHRD200 disabled to allow method name to match the common cross-platform entity operation name. #pragma warning disable IDE1006 #pragma warning disable VSTHRD200 - public async Task Run(RunRequest request) + public async Task Run(RunRequest request) #pragma warning restore VSTHRD200 #pragma warning restore IDE1006 { @@ -43,7 +43,7 @@ internal class AgentEntity(IServiceProvider services, CancellationToken cancella if (request.Messages.Count == 0) { logger.LogInformation("Ignoring empty request"); - return new AgentRunResponse(); + return new AgentResponse(); } this.State.Data.ConversationHistory.Add(DurableAgentStateRequest.FromRunRequest(request)); @@ -65,29 +65,29 @@ internal class AgentEntity(IServiceProvider services, CancellationToken cancella try { // Start the agent response stream - IAsyncEnumerable responseStream = agentWrapper.RunStreamingAsync( + IAsyncEnumerable responseStream = agentWrapper.RunStreamingAsync( this.State.Data.ConversationHistory.SelectMany(e => e.Messages).Select(m => m.ToChatMessage()), await agentWrapper.GetNewThreadAsync(cancellationToken).ConfigureAwait(false), options: null, this._cancellationToken); - AgentRunResponse response; + AgentResponse response; if (this._messageHandler is null) { // If no message handler is provided, we can just get the full response at once. // This is expected to be the common case for non-interactive agents. - response = await responseStream.ToAgentRunResponseAsync(this._cancellationToken); + response = await responseStream.ToAgentResponseAsync(this._cancellationToken); } else { - List responseUpdates = []; + List responseUpdates = []; // To support interactive chat agents, we need to stream the responses to an IAgentMessageHandler. // The user-provided message handler can be implemented to send the responses to the user. // We assume that only non-empty text updates are useful for the user. - async IAsyncEnumerable StreamResultsAsync() + async IAsyncEnumerable StreamResultsAsync() { - await foreach (AgentRunResponseUpdate update in responseStream) + await foreach (AgentResponseUpdate update in responseStream) { // We need the full response further down, so we piece it together as we go. responseUpdates.Add(update); @@ -98,12 +98,12 @@ internal class AgentEntity(IServiceProvider services, CancellationToken cancella } await this._messageHandler.OnStreamingResponseUpdateAsync(StreamResultsAsync(), this._cancellationToken); - response = responseUpdates.ToAgentRunResponse(); + response = responseUpdates.ToAgentResponse(); } // Persist the agent response to the entity state for client polling this.State.Data.ConversationHistory.Add( - DurableAgentStateResponse.FromRunResponse(request.CorrelationId, response)); + DurableAgentStateResponse.FromResponse(request.CorrelationId, response)); string responseText = response.Text; diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentRunHandle.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentRunHandle.cs index e4fe08dbf2..0ff329153f 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentRunHandle.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentRunHandle.cs @@ -44,7 +44,7 @@ internal sealed class AgentRunHandle /// The cancellation token. /// The agent response corresponding to this request. /// Thrown when the response is not found after polling. - public async Task ReadAgentResponseAsync(CancellationToken cancellationToken = default) + public async Task ReadAgentResponseAsync(CancellationToken cancellationToken = default) { TimeSpan pollInterval = TimeSpan.FromMilliseconds(50); // Start with 50ms TimeSpan maxPollInterval = TimeSpan.FromSeconds(3); // Maximum 3 seconds @@ -69,7 +69,7 @@ internal sealed class AgentRunHandle if (response is not null) { this._logger.LogDonePollingForResponse(this.SessionId, this.CorrelationId); - return response.ToRunResponse(); + return response.ToResponse(); } } diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgent.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgent.cs index 5cc8ce451d..dd598e2618 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgent.cs @@ -65,7 +65,7 @@ public sealed class DurableAIAgent : AIAgent /// Thrown when the agent has not been registered. /// Thrown when the provided thread is not valid for a durable agent. /// Thrown when cancellation is requested (cancellation is not supported for durable agents). - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -107,7 +107,7 @@ public sealed class DurableAIAgent : AIAgent try { - return await this._context.Entities.CallEntityAsync( + return await this._context.Entities.CallEntityAsync( durableThread.SessionId, nameof(AgentEntity.Run), request); @@ -130,7 +130,7 @@ public sealed class DurableAIAgent : AIAgent /// Optional run options. /// The cancellation token. /// A streaming response enumerable. - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -138,8 +138,8 @@ public sealed class DurableAIAgent : AIAgent { // Streaming is not supported for durable agents, so we just return the full response // as a single update. - AgentRunResponse response = await this.RunAsync(messages, thread, options, cancellationToken); - foreach (AgentRunResponseUpdate update in response.ToAgentRunResponseUpdates()) + AgentResponse response = await this.RunAsync(messages, thread, options, cancellationToken); + foreach (AgentResponseUpdate update in response.ToAgentResponseUpdates()) { yield return update; } @@ -162,7 +162,7 @@ public sealed class DurableAIAgent : AIAgent /// Thrown when the agent response is empty or cannot be deserialized. /// /// The output from the agent. - public async Task> RunAsync( + public async Task> RunAsync( string message, AgentThread? thread = null, JsonSerializerOptions? serializerOptions = null, @@ -196,7 +196,7 @@ public sealed class DurableAIAgent : AIAgent /// The output from the agent. [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Fallback to reflection-based deserialization is intentional for library flexibility with user-defined types.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL3050", Justification = "Fallback to reflection-based deserialization is intentional for library flexibility with user-defined types.")] - public async Task> RunAsync( + public async Task> RunAsync( IEnumerable messages, AgentThread? thread = null, JsonSerializerOptions? serializerOptions = null, @@ -223,7 +223,7 @@ public sealed class DurableAIAgent : AIAgent // Create the JSON schema for the response type durableOptions.ResponseFormat = ChatResponseFormat.ForJsonSchema(); - AgentRunResponse response = await this.RunAsync(messages, thread, durableOptions, cancellationToken); + AgentResponse response = await this.RunAsync(messages, thread, durableOptions, cancellationToken); // Deserialize the response text to the requested type if (string.IsNullOrEmpty(response.Text)) @@ -242,11 +242,11 @@ public sealed class DurableAIAgent : AIAgent : JsonSerializer.Deserialize(response.Text, serializerOptions)) ?? throw new InvalidOperationException($"Failed to deserialize agent response to type {typeof(T).Name}."); - return new DurableAIAgentRunResponse(response, result); + return new DurableAIAgentResponse(response, result); } - private sealed class DurableAIAgentRunResponse(AgentRunResponse response, T result) - : AgentRunResponse(response.AsChatResponse()) + private sealed class DurableAIAgentResponse(AgentResponse response, T result) + : AgentResponse(response.AsChatResponse()) { public override T Result { get; } = result; } diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgentProxy.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgentProxy.cs index ca631a32c8..2461302e6e 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgentProxy.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgentProxy.cs @@ -23,7 +23,7 @@ internal class DurableAIAgentProxy(string name, IDurableAgentClient agentClient) return ValueTask.FromResult(new DurableAgentThread(AgentSessionId.WithRandomKey(this.Name!))); } - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -64,13 +64,13 @@ internal class DurableAIAgentProxy(string name, IDurableAgentClient agentClient) if (isFireAndForget) { // If the request is fire and forget, return an empty response. - return new AgentRunResponse(); + return new AgentResponse(); } return await agentRunHandle.ReadAgentResponseAsync(cancellationToken); } - protected override IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAgentJsonUtilities.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAgentJsonUtilities.cs index e3864e9ad4..966218058c 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAgentJsonUtilities.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAgentJsonUtilities.cs @@ -20,7 +20,7 @@ namespace Microsoft.Agents.AI.DurableTask; /// baseline defaults. /// for default null-value suppression. /// to tolerate numbers encoded as strings. -/// Chained type info resolvers from shared agent abstractions to cover cross-package types (e.g. , ). +/// Chained type info resolvers from shared agent abstractions to cover cross-package types (e.g. , ). /// /// /// Keep the list of [JsonSerializable] types in sync with the Durable Agent data model anytime new state or request/response diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/EntityAgentWrapper.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/EntityAgentWrapper.cs index 4a6074fcb6..e58db5e9b4 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/EntityAgentWrapper.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/EntityAgentWrapper.cs @@ -21,13 +21,13 @@ internal sealed class EntityAgentWrapper( // The ID of the agent is always the entity ID. protected override string? IdCore => this._entityContext.Id.ToString(); - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - AgentRunResponse response = await base.RunCoreAsync( + AgentResponse response = await base.RunCoreAsync( messages, thread, this.GetAgentEntityRunOptions(options), @@ -37,13 +37,13 @@ internal sealed class EntityAgentWrapper( return response; } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - await foreach (AgentRunResponseUpdate update in base.RunCoreStreamingAsync( + await foreach (AgentResponseUpdate update in base.RunCoreStreamingAsync( messages, thread, this.GetAgentEntityRunOptions(options), diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/IAgentResponseHandler.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/IAgentResponseHandler.cs index 45a4e9f258..c12a765e00 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/IAgentResponseHandler.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/IAgentResponseHandler.cs @@ -17,7 +17,7 @@ public interface IAgentResponseHandler /// Signals that the operation should be cancelled. /// ValueTask OnStreamingResponseUpdateAsync( - IAsyncEnumerable messageStream, + IAsyncEnumerable messageStream, CancellationToken cancellationToken); /// @@ -30,6 +30,6 @@ public interface IAgentResponseHandler /// Signals that the operation should be cancelled. /// ValueTask OnAgentResponseAsync( - AgentRunResponse message, + AgentResponse message, CancellationToken cancellationToken); } diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/Microsoft.Agents.AI.DurableTask.csproj b/dotnet/src/Microsoft.Agents.AI.DurableTask/Microsoft.Agents.AI.DurableTask.csproj index 41284e1085..43ebe9c61f 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/Microsoft.Agents.AI.DurableTask.csproj +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/Microsoft.Agents.AI.DurableTask.csproj @@ -4,7 +4,7 @@ $(TargetFrameworksCore) enable - + $(NoWarn);CA2007;MEAI001 diff --git a/dotnet/src/Microsoft.Agents.AI.DurableTask/State/DurableAgentStateResponse.cs b/dotnet/src/Microsoft.Agents.AI.DurableTask/State/DurableAgentStateResponse.cs index 216bb6e05c..612ff4b48f 100644 --- a/dotnet/src/Microsoft.Agents.AI.DurableTask/State/DurableAgentStateResponse.cs +++ b/dotnet/src/Microsoft.Agents.AI.DurableTask/State/DurableAgentStateResponse.cs @@ -17,12 +17,12 @@ internal sealed class DurableAgentStateResponse : DurableAgentStateEntry public DurableAgentStateUsage? Usage { get; init; } /// - /// Creates a from an . + /// Creates a from an . /// /// The correlation ID linking this response to its request. - /// The to convert. + /// The to convert. /// A representing the original response. - public static DurableAgentStateResponse FromRunResponse(string correlationId, AgentRunResponse response) + public static DurableAgentStateResponse FromResponse(string correlationId, AgentResponse response) { return new DurableAgentStateResponse() { @@ -34,12 +34,12 @@ internal sealed class DurableAgentStateResponse : DurableAgentStateEntry } /// - /// Converts this back to an . + /// Converts this back to an . /// - /// A representing this response. - public AgentRunResponse ToRunResponse() + /// A representing this response. + public AgentResponse ToResponse() { - return new AgentRunResponse() + return new AgentResponse() { CreatedAt = this.CreatedAt, Messages = this.Messages.Select(m => m.ToChatMessage()).ToList(), diff --git a/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/BuiltInFunctions.cs b/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/BuiltInFunctions.cs index 3d824994e9..edde523271 100644 --- a/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/BuiltInFunctions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/BuiltInFunctions.cs @@ -119,7 +119,7 @@ internal static class BuiltInFunctions if (waitForResponse) { - AgentRunResponse agentResponse = await agentProxy.RunAsync( + AgentResponse agentResponse = await agentProxy.RunAsync( message: new ChatMessage(ChatRole.User, message), thread: new DurableAgentThread(sessionId), options: options, @@ -170,7 +170,7 @@ internal static class BuiltInFunctions AIAgent agentProxy = client.AsDurableAgentProxy(functionContext, agentName); - AgentRunResponse agentResponse = await agentProxy.RunAsync( + AgentResponse agentResponse = await agentProxy.RunAsync( message: new ChatMessage(ChatRole.User, query), thread: new DurableAgentThread(sessionId), options: null); @@ -224,7 +224,7 @@ internal static class BuiltInFunctions FunctionContext context, HttpStatusCode statusCode, string threadId, - AgentRunResponse agentResponse) + AgentResponse agentResponse) { HttpResponseData response = req.CreateResponse(statusCode); response.Headers.Add("x-ms-thread-id", threadId); @@ -321,7 +321,7 @@ internal static class BuiltInFunctions private sealed record AgentRunSuccessResponse( [property: JsonPropertyName("status")] int Status, [property: JsonPropertyName("thread_id")] string ThreadId, - [property: JsonPropertyName("response")] AgentRunResponse Response); + [property: JsonPropertyName("response")] AgentResponse Response); /// /// Represents an accepted (fire-and-forget) agent run response. diff --git a/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md b/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md index ff0913ff2c..ee50c78ff5 100644 --- a/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md +++ b/dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/README.md @@ -77,7 +77,7 @@ public static async Task SpamDetectionOrchestration( AgentThread spamThread = await spamDetectionAgent.GetNewThreadAsync(); // Step 1: Check if the email is spam - AgentRunResponse spamDetectionResponse = await spamDetectionAgent.RunAsync( + AgentResponse spamDetectionResponse = await spamDetectionAgent.RunAsync( message: $""" Analyze this email for spam content and return a JSON response with 'is_spam' (boolean) and 'reason' (string) fields: @@ -99,7 +99,7 @@ public static async Task SpamDetectionOrchestration( DurableAIAgent emailAssistantAgent = context.GetAgent("EmailAssistantAgent"); AgentThread emailThread = await emailAssistantAgent.GetNewThreadAsync(); - AgentRunResponse emailAssistantResponse = await emailAssistantAgent.RunAsync( + AgentResponse emailAssistantResponse = await emailAssistantAgent.RunAsync( message: $""" Draft a professional response to this email. Return a JSON response with a 'response' field containing the reply: diff --git a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AIAgentChatCompletionsProcessor.cs b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AIAgentChatCompletionsProcessor.cs index d9e51b6aa2..42443dc2ca 100644 --- a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AIAgentChatCompletionsProcessor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AIAgentChatCompletionsProcessor.cs @@ -70,18 +70,18 @@ internal static class AIAgentChatCompletionsProcessor DateTimeOffset? createdAt = null; var chunkId = IdGenerator.NewId(prefix: "chatcmpl", delimiter: "-", stringLength: 13); - await foreach (var agentRunResponseUpdate in agent.RunStreamingAsync(chatMessages, options: options, cancellationToken: cancellationToken).WithCancellation(cancellationToken)) + await foreach (var agentResponseUpdate in agent.RunStreamingAsync(chatMessages, options: options, cancellationToken: cancellationToken).WithCancellation(cancellationToken)) { - var finishReason = (agentRunResponseUpdate.RawRepresentation is ChatResponseUpdate { FinishReason: not null } chatResponseUpdate) + var finishReason = (agentResponseUpdate.RawRepresentation is ChatResponseUpdate { FinishReason: not null } chatResponseUpdate) ? chatResponseUpdate.FinishReason.ToString() : "stop"; var choiceChunks = new List(); CompletionUsage? usageDetails = null; - createdAt ??= agentRunResponseUpdate.CreatedAt; + createdAt ??= agentResponseUpdate.CreatedAt; - foreach (var content in agentRunResponseUpdate.Contents) + foreach (var content in agentResponseUpdate.Contents) { // usage content is handled separately if (content is UsageContent usageContent && usageContent.Details != null) @@ -124,7 +124,7 @@ internal static class AIAgentChatCompletionsProcessor continue; } - delta.Role = agentRunResponseUpdate.Role?.Value ?? "user"; + delta.Role = agentResponseUpdate.Role?.Value ?? "user"; var choiceChunk = new ChatCompletionChoiceChunk { diff --git a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AgentRunResponseExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AgentResponseExtensions.cs similarity index 92% rename from dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AgentRunResponseExtensions.cs rename to dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AgentResponseExtensions.cs index f50aa44d4d..95d7df0231 100644 --- a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AgentRunResponseExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/ChatCompletions/AgentResponseExtensions.cs @@ -12,33 +12,33 @@ namespace Microsoft.Agents.AI.Hosting.OpenAI.ChatCompletions; /// /// Extension methods for converting agent responses to ChatCompletion models. /// -internal static class AgentRunResponseExtensions +internal static class AgentResponseExtensions { - public static ChatCompletion ToChatCompletion(this AgentRunResponse agentRunResponse, CreateChatCompletion request) + public static ChatCompletion ToChatCompletion(this AgentResponse agentResponse, CreateChatCompletion request) { - IList choices = agentRunResponse.ToChoices(); + IList choices = agentResponse.ToChoices(); return new ChatCompletion { Id = IdGenerator.NewId(prefix: "chatcmpl", delimiter: "-", stringLength: 13), Choices = choices, - Created = (agentRunResponse.CreatedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(), + Created = (agentResponse.CreatedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(), Model = request.Model, - Usage = agentRunResponse.Usage.ToCompletionUsage(), + Usage = agentResponse.Usage.ToCompletionUsage(), ServiceTier = request.ServiceTier ?? "default" }; } - public static List ToChoices(this AgentRunResponse agentRunResponse) + public static List ToChoices(this AgentResponse agentResponse) { var chatCompletionChoices = new List(); var index = 0; - var finishReason = (agentRunResponse.RawRepresentation is ChatResponse { FinishReason: not null } chatResponse) + 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 agentRunResponse.Messages) + foreach (var message in agentResponse.Messages) { foreach (var content in message.Contents) { diff --git a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentRunResponseExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentResponseExtensions.cs similarity index 96% rename from dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentRunResponseExtensions.cs rename to dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentResponseExtensions.cs index 97dcf9740f..2734fad427 100644 --- a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentRunResponseExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentResponseExtensions.cs @@ -13,19 +13,19 @@ namespace Microsoft.Agents.AI.Hosting.OpenAI.Responses; /// /// Extension methods for converting agent responses to Response models. /// -internal static class AgentRunResponseExtensions +internal static class AgentResponseExtensions { private static ChatRole s_DeveloperRole => new("developer"); /// - /// Converts an AgentRunResponse to a Response model. + /// Converts an AgentResponse to a Response model. /// - /// The agent run response to convert. + /// The agent response to convert. /// The original create response request. /// The agent invocation context. /// A Response model. public static Response ToResponse( - this AgentRunResponse agentRunResponse, + this AgentResponse agentResponse, CreateResponse request, AgentInvocationContext context) { @@ -41,7 +41,7 @@ internal static class AgentRunResponseExtensions }); } - output.AddRange(agentRunResponse.Messages + output.AddRange(agentResponse.Messages .SelectMany(msg => msg.ToItemResource(context.IdGenerator, context.JsonSerializerOptions))); return new Response @@ -49,7 +49,7 @@ internal static class AgentRunResponseExtensions Agent = request.Agent?.ToAgentId(), Background = request.Background, Conversation = request.Conversation ?? (context.ConversationId != null ? new ConversationReference { Id = context.ConversationId } : null), - CreatedAt = (agentRunResponse.CreatedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(), + CreatedAt = (agentResponse.CreatedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(), Error = null, Id = context.ResponseId, Instructions = request.Instructions, @@ -74,7 +74,7 @@ internal static class AgentRunResponseExtensions TopLogprobs = request.TopLogprobs, TopP = request.TopP ?? 1.0, Truncation = request.Truncation, - Usage = agentRunResponse.Usage.ToResponseUsage(), + Usage = agentResponse.Usage.ToResponseUsage(), #pragma warning disable CS0618 // Type or member is obsolete User = request.User, #pragma warning restore CS0618 // Type or member is obsolete diff --git a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentRunResponseUpdateExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentResponseUpdateExtensions.cs similarity index 97% rename from dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentRunResponseUpdateExtensions.cs rename to dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentResponseUpdateExtensions.cs index 628b80b340..f4c1e3c7a0 100644 --- a/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentRunResponseUpdateExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Hosting.OpenAI/Responses/AgentResponseUpdateExtensions.cs @@ -16,12 +16,12 @@ using Microsoft.Extensions.AI; namespace Microsoft.Agents.AI.Hosting.OpenAI.Responses; /// -/// Extension methods for . +/// Extension methods for . /// -internal static class AgentRunResponseUpdateExtensions +internal static class AgentResponseUpdateExtensions { /// - /// Converts a stream of to stream of . + /// Converts a stream of to stream of . /// /// The agent run response updates. /// The create response request. @@ -29,7 +29,7 @@ internal static class AgentRunResponseUpdateExtensions /// The cancellation token. /// A stream of response events. public static async IAsyncEnumerable ToStreamingResponseAsync( - this IAsyncEnumerable updates, + this IAsyncEnumerable updates, CreateResponse request, AgentInvocationContext context, [EnumeratorCancellation] CancellationToken cancellationToken = default) @@ -48,7 +48,7 @@ internal static class AgentRunResponseUpdateExtensions // Track active item IDs by executor ID to pair invoked/completed/failed events Dictionary executorItemIds = []; - AgentRunResponseUpdate? previousUpdate = null; + AgentResponseUpdate? previousUpdate = null; StreamingEventGenerator? generator = null; while (await updateEnumerator.MoveNextAsync().ConfigureAwait(false)) { @@ -279,7 +279,7 @@ internal static class AgentRunResponseUpdateExtensions } } - private static bool IsSameMessage(AgentRunResponseUpdate? first, AgentRunResponseUpdate? second) + private static bool IsSameMessage(AgentResponseUpdate? first, AgentResponseUpdate? second) { return IsSameValue(first?.MessageId, second?.MessageId) && IsSameValue(first?.AuthorName, second?.AuthorName) diff --git a/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingChatCompletionUpdateCollectionResult.cs b/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingChatCompletionUpdateCollectionResult.cs index 17c9c2d95a..db0c7a8673 100644 --- a/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingChatCompletionUpdateCollectionResult.cs +++ b/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingChatCompletionUpdateCollectionResult.cs @@ -7,9 +7,9 @@ namespace Microsoft.Agents.AI.OpenAI; internal sealed class AsyncStreamingChatCompletionUpdateCollectionResult : AsyncCollectionResult { - private readonly IAsyncEnumerable _updates; + private readonly IAsyncEnumerable _updates; - internal AsyncStreamingChatCompletionUpdateCollectionResult(IAsyncEnumerable updates) + internal AsyncStreamingChatCompletionUpdateCollectionResult(IAsyncEnumerable updates) { this._updates = updates; } @@ -23,7 +23,7 @@ internal sealed class AsyncStreamingChatCompletionUpdateCollectionResult : Async protected override IAsyncEnumerable GetValuesFromPageAsync(ClientResult page) { - var updates = ((ClientResult>)page).Value; + var updates = ((ClientResult>)page).Value; return updates.AsChatResponseUpdatesAsync().AsOpenAIStreamingChatCompletionUpdatesAsync(); } diff --git a/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingResponseUpdateCollectionResult.cs b/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingResponseUpdateCollectionResult.cs index c67f4d1462..77400b3377 100644 --- a/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingResponseUpdateCollectionResult.cs +++ b/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/AsyncStreamingResponseUpdateCollectionResult.cs @@ -7,9 +7,9 @@ namespace Microsoft.Agents.AI.OpenAI; internal sealed class AsyncStreamingResponseUpdateCollectionResult : AsyncCollectionResult { - private readonly IAsyncEnumerable _updates; + private readonly IAsyncEnumerable _updates; - internal AsyncStreamingResponseUpdateCollectionResult(IAsyncEnumerable updates) + internal AsyncStreamingResponseUpdateCollectionResult(IAsyncEnumerable updates) { this._updates = updates; } @@ -23,7 +23,7 @@ internal sealed class AsyncStreamingResponseUpdateCollectionResult : AsyncCollec protected async override IAsyncEnumerable GetValuesFromPageAsync(ClientResult page) { - var updates = ((ClientResult>)page).Value; + var updates = ((ClientResult>)page).Value; await foreach (var update in updates.ConfigureAwait(false)) { diff --git a/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/StreamingUpdatePipelineResponse.cs b/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/StreamingUpdatePipelineResponse.cs index e999ad04e7..3114464675 100644 --- a/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/StreamingUpdatePipelineResponse.cs +++ b/dotnet/src/Microsoft.Agents.AI.OpenAI/ChatClient/StreamingUpdatePipelineResponse.cs @@ -55,7 +55,7 @@ internal sealed class StreamingUpdatePipelineResponse : PipelineResponse // No resources to dispose. } - internal StreamingUpdatePipelineResponse(IAsyncEnumerable updates) + internal StreamingUpdatePipelineResponse(IAsyncEnumerable updates) { } diff --git a/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AIAgentWithOpenAIExtensions.cs b/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AIAgentWithOpenAIExtensions.cs index d487ba00e1..defc934b30 100644 --- a/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AIAgentWithOpenAIExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AIAgentWithOpenAIExtensions.cs @@ -16,7 +16,7 @@ namespace Microsoft.Agents.AI; /// These extensions bridge the gap between the Microsoft Extensions AI framework and the OpenAI SDK, /// allowing developers to work with native OpenAI types while leveraging the AI Agent framework. /// The methods handle the conversion between OpenAI chat message types and Microsoft Extensions AI types, -/// and return OpenAI objects directly from the agent's . +/// and return OpenAI objects directly from the agent's . /// public static class AIAgentWithOpenAIExtensions { @@ -34,7 +34,7 @@ public static class AIAgentWithOpenAIExtensions /// Thrown when any message in has a type that is not supported by the message conversion method. /// /// This method converts the OpenAI chat messages to the Microsoft Extensions AI format using the appropriate conversion method, - /// runs the agent with the converted message collection, and then extracts the native OpenAI from the response using . + /// runs the agent with the converted message collection, and then extracts the native OpenAI from the response using . /// public static async Task RunAsync(this AIAgent agent, IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { @@ -60,14 +60,14 @@ public static class AIAgentWithOpenAIExtensions /// Thrown when the type is not supported by the message conversion method. /// /// This method converts the OpenAI chat messages to the Microsoft Extensions AI format using the appropriate conversion method, - /// runs the agent, and then extracts the native OpenAI from the response using . + /// runs the agent, and then extracts the native OpenAI from the response using . /// public static AsyncCollectionResult RunStreamingAsync(this AIAgent agent, IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { Throw.IfNull(agent); Throw.IfNull(messages); - IAsyncEnumerable response = agent.RunStreamingAsync([.. messages.AsChatMessages()], thread, options, cancellationToken); + IAsyncEnumerable response = agent.RunStreamingAsync([.. messages.AsChatMessages()], thread, options, cancellationToken); return new AsyncStreamingChatCompletionUpdateCollectionResult(response); } @@ -86,7 +86,7 @@ public static class AIAgentWithOpenAIExtensions /// Thrown when any message in has a type that is not supported by the message conversion method. /// /// This method converts the OpenAI response items to the Microsoft Extensions AI format using the appropriate conversion method, - /// runs the agent with the converted message collection, and then extracts the native OpenAI from the response using . + /// runs the agent with the converted message collection, and then extracts the native OpenAI from the response using . /// public static async Task RunAsync(this AIAgent agent, IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { @@ -121,7 +121,7 @@ public static class AIAgentWithOpenAIExtensions Throw.IfNull(agent); Throw.IfNull(messages); - IAsyncEnumerable response = agent.RunStreamingAsync([.. messages.AsChatMessages()], thread, options, cancellationToken); + IAsyncEnumerable response = agent.RunStreamingAsync([.. messages.AsChatMessages()], thread, options, cancellationToken); return new AsyncStreamingResponseUpdateCollectionResult(response); } diff --git a/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AgentRunResponseExtensions.cs b/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AgentResponseExtensions.cs similarity index 79% rename from dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AgentRunResponseExtensions.cs rename to dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AgentResponseExtensions.cs index 44844e64f5..e855aaef56 100644 --- a/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AgentRunResponseExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.OpenAI/Extensions/AgentResponseExtensions.cs @@ -8,18 +8,18 @@ using OpenAI.Responses; namespace Microsoft.Agents.AI; /// -/// Provides extension methods for and instances to +/// Provides extension methods for and instances to /// create or extract native OpenAI response objects from the Microsoft Agent Framework responses. /// -public static class AgentRunResponseExtensions +public static class AgentResponseExtensions { /// - /// Creates or extracts a native OpenAI object from an . + /// Creates or extracts a native OpenAI object from an . /// /// The agent response. /// The OpenAI object. /// is . - public static ChatCompletion AsOpenAIChatCompletion(this AgentRunResponse response) + public static ChatCompletion AsOpenAIChatCompletion(this AgentResponse response) { Throw.IfNull(response); @@ -29,12 +29,12 @@ public static class AgentRunResponseExtensions } /// - /// Creates or extracts a native OpenAI object from an . + /// Creates or extracts a native OpenAI object from an . /// /// The agent response. /// The OpenAI object. /// is . - public static ResponseResult AsOpenAIResponse(this AgentRunResponse response) + public static ResponseResult AsOpenAIResponse(this AgentResponse response) { Throw.IfNull(response); diff --git a/dotnet/src/Microsoft.Agents.AI.Purview/PurviewAgent.cs b/dotnet/src/Microsoft.Agents.AI.Purview/PurviewAgent.cs index bd6c42c564..c30c089198 100644 --- a/dotnet/src/Microsoft.Agents.AI.Purview/PurviewAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.Purview/PurviewAgent.cs @@ -42,16 +42,16 @@ internal class PurviewAgent : AIAgent, IDisposable } /// - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { return this._purviewWrapper.ProcessAgentContentAsync(messages, thread, options, this._innerAgent, cancellationToken); } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { var response = await this._purviewWrapper.ProcessAgentContentAsync(messages, thread, options, this._innerAgent, cancellationToken).ConfigureAwait(false); - foreach (var update in response.ToAgentRunResponseUpdates()) + foreach (var update in response.ToAgentResponseUpdates()) { yield return update; } diff --git a/dotnet/src/Microsoft.Agents.AI.Purview/PurviewWrapper.cs b/dotnet/src/Microsoft.Agents.AI.Purview/PurviewWrapper.cs index a818fb264f..835b0146a8 100644 --- a/dotnet/src/Microsoft.Agents.AI.Purview/PurviewWrapper.cs +++ b/dotnet/src/Microsoft.Agents.AI.Purview/PurviewWrapper.cs @@ -134,7 +134,7 @@ internal sealed class PurviewWrapper : IDisposable /// The wrapped agent. /// The cancellation token used to interrupt async operations. /// The agent's response. This could be the response from the agent or a message indicating that Purview has blocked the prompt or response. - public async Task ProcessAgentContentAsync(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) + public async Task ProcessAgentContentAsync(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { string threadId = GetThreadIdFromAgentThread(thread, messages); @@ -151,7 +151,7 @@ internal sealed class PurviewWrapper : IDisposable this._logger.LogInformation("Prompt blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedPromptMessage); } - return new AgentRunResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedPromptMessage)); + return new AgentResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedPromptMessage)); } } catch (Exception ex) @@ -167,7 +167,7 @@ internal sealed class PurviewWrapper : IDisposable } } - AgentRunResponse response = await innerAgent.RunAsync(messages, thread, options, cancellationToken).ConfigureAwait(false); + AgentResponse response = await innerAgent.RunAsync(messages, thread, options, cancellationToken).ConfigureAwait(false); try { @@ -180,7 +180,7 @@ internal sealed class PurviewWrapper : IDisposable this._logger.LogInformation("Response blocked by policy. Sending message: {Message}", this._purviewSettings.BlockedResponseMessage); } - return new AgentRunResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedResponseMessage)); + return new AgentResponse(new ChatMessage(ChatRole.System, this._purviewSettings.BlockedResponseMessage)); } } catch (Exception ex) diff --git a/dotnet/src/Microsoft.Agents.AI.Purview/README.md b/dotnet/src/Microsoft.Agents.AI.Purview/README.md index 1ee2a25826..6df5ec4c3d 100644 --- a/dotnet/src/Microsoft.Agents.AI.Purview/README.md +++ b/dotnet/src/Microsoft.Agents.AI.Purview/README.md @@ -211,7 +211,7 @@ The policy logic is identical; the only difference is the hook point in the pipe ## Middleware Lifecycle 1. Before sending the prompt to the agent, the middleware checks the app and user metadata against Purview's protection scopes and evaluates all the `ChatMessage`s in the prompt. -2. If the content was blocked, the middleware returns a `ChatResponse` or `AgentRunResponse` containing the `BlockedPromptMessage` text. The blocked content does not get passed to the agent. +2. If the content was blocked, the middleware returns a `ChatResponse` or `AgentResponse` containing the `BlockedPromptMessage` text. The blocked content does not get passed to the agent. 3. If the evaluation did not block the content, the middleware passes the prompt data to the agent and waits for a response. 4. After receiving a response from the agent, the middleware calls Purview again to evaluate the response content. 5. If the content was blocked, the middleware returns a response containing the `BlockedResponseMessage`. diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative.AzureAI/AzureAgentProvider.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative.AzureAI/AzureAgentProvider.cs index d4010a43c2..322ab7606a 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative.AzureAI/AzureAgentProvider.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative.AzureAI/AzureAgentProvider.cs @@ -90,7 +90,7 @@ public sealed class AzureAgentProvider(Uri projectEndpoint, TokenCredential proj } /// - public override async IAsyncEnumerable InvokeAgentAsync( + public override async IAsyncEnumerable InvokeAgentAsync( string agentId, string? agentVersion, string? conversationId, @@ -120,12 +120,12 @@ public sealed class AzureAgentProvider(Uri projectEndpoint, TokenCredential proj ChatClientAgentRunOptions runOptions = new(chatOptions); - IAsyncEnumerable agentResponse = + IAsyncEnumerable agentResponse = messages is not null ? agent.RunStreamingAsync([.. messages], null, runOptions, cancellationToken) : agent.RunStreamingAsync([new ChatMessage(ChatRole.User, string.Empty)], null, runOptions, cancellationToken); - await foreach (AgentRunResponseUpdate update in agentResponse.ConfigureAwait(false)) + await foreach (AgentResponseUpdate update in agentResponse.ConfigureAwait(false)) { update.AuthorName = agentVersionResult.Name; yield return update; diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.cs index 3704d38b21..30530573fa 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.cs @@ -64,7 +64,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.CodeGen EvaluateListExpression(this.Model.Input?.Messages, "inputMessages"); this.Write(@" - AgentRunResponse agentResponse = + AgentResponse agentResponse = await InvokeAgentAsync( context, agentName, diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.tt b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.tt index 48c4acb859..310c48e308 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.tt +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/InvokeAzureAgentTemplate.tt @@ -21,7 +21,7 @@ internal sealed class <#= this.Name #>Executor(FormulaSession session, WorkflowA EvaluateBoolExpression(this.Model.Output?.AutoSend, "autoSend", defaultValue: true); EvaluateListExpression(this.Model.Input?.Messages, "inputMessages");#> - AgentRunResponse agentResponse = + AgentResponse agentResponse = await InvokeAgentAsync( context, agentName, diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.cs index 1d85f885b8..6cc1cdb435 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.cs @@ -71,7 +71,7 @@ if (this.Model.Activity is MessageActivityTemplate messageActivity) } - this.Write("\n );\n AgentRunResponse response = new([new ChatMessage(ChatRole" + + this.Write("\n );\n AgentResponse response = new([new ChatMessage(ChatRole" + ".Assistant, activityText)]);\n await context.AddEventAsync(new AgentRunRes" + "ponseEvent(this.Id, response)).ConfigureAwait(false);"); diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.tt b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.tt index a1f0e3191f..7d247faf44 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.tt +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/CodeGen/SendActivityTemplate.tt @@ -25,7 +25,7 @@ if (this.Model.Activity is MessageActivityTemplate messageActivity) } #> ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);<# } #> diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Events/ExternalInputRequest.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Events/ExternalInputRequest.cs index 8caf374b70..6cee3d308e 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Events/ExternalInputRequest.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Events/ExternalInputRequest.cs @@ -13,21 +13,21 @@ public sealed class ExternalInputRequest /// /// The source message that triggered the request for external input. /// - public AgentRunResponse AgentResponse { get; } + public AgentResponse AgentResponse { get; } [JsonConstructor] - internal ExternalInputRequest(AgentRunResponse agentResponse) + internal ExternalInputRequest(AgentResponse agentResponse) { this.AgentResponse = agentResponse; } internal ExternalInputRequest(ChatMessage message) { - this.AgentResponse = new AgentRunResponse(message); + this.AgentResponse = new AgentResponse(message); } internal ExternalInputRequest(string text) { - this.AgentResponse = new AgentRunResponse(new ChatMessage(ChatRole.User, text)); + this.AgentResponse = new AgentResponse(new ChatMessage(ChatRole.User, text)); } } diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Extensions/AgentProviderExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Extensions/AgentProviderExtensions.cs index 037665e8b8..d82febb2a8 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Extensions/AgentProviderExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Extensions/AgentProviderExtensions.cs @@ -9,7 +9,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.Extensions; internal static class AgentProviderExtensions { - public static async ValueTask InvokeAgentAsync( + public static async ValueTask InvokeAgentAsync( this WorkflowAgentProvider agentProvider, string executorId, IWorkflowContext context, @@ -20,15 +20,15 @@ internal static class AgentProviderExtensions IDictionary? inputArguments = null, CancellationToken cancellationToken = default) { - IAsyncEnumerable agentUpdates = agentProvider.InvokeAgentAsync(agentName, null, conversationId, inputMessages, inputArguments, cancellationToken); + IAsyncEnumerable agentUpdates = agentProvider.InvokeAgentAsync(agentName, null, conversationId, inputMessages, inputArguments, cancellationToken); // Enable "autoSend" behavior if this is the workflow conversation. bool isWorkflowConversation = context.IsWorkflowConversation(conversationId, out string? workflowConversationId); autoSend |= isWorkflowConversation; // Process the agent response updates. - List updates = []; - await foreach (AgentRunResponseUpdate update in agentUpdates.ConfigureAwait(false)) + List updates = []; + await foreach (AgentResponseUpdate update in agentUpdates.ConfigureAwait(false)) { await AssignConversationIdAsync(((ChatResponseUpdate?)update.RawRepresentation)?.ConversationId).ConfigureAwait(false); @@ -40,7 +40,7 @@ internal static class AgentProviderExtensions } } - AgentRunResponse response = updates.ToAgentRunResponse(); + AgentResponse response = updates.ToAgentResponse(); if (autoSend) { diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Kit/AgentExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Kit/AgentExecutor.cs index 45a5b47bd8..9545b9d1ff 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Kit/AgentExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Kit/AgentExecutor.cs @@ -26,7 +26,7 @@ public abstract class AgentExecutor(string id, FormulaSession session, WorkflowA /// Optional messages to add to the conversation prior to invocation. /// A token that can be used to observe cancellation. /// - protected ValueTask InvokeAgentAsync( + protected ValueTask InvokeAgentAsync( IWorkflowContext context, string agentName, string? conversationId, diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/AddConversationMessageExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/AddConversationMessageExecutor.cs index 632f462758..fa7d304454 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/AddConversationMessageExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/AddConversationMessageExecutor.cs @@ -30,7 +30,7 @@ internal sealed class AddConversationMessageExecutor(AddConversationMessage mode if (isWorkflowConversation) { - await context.AddEventAsync(new AgentRunResponseEvent(this.Id, new AgentRunResponse(newMessage)), cancellationToken).ConfigureAwait(false); + await context.AddEventAsync(new AgentRunResponseEvent(this.Id, new AgentResponse(newMessage)), cancellationToken).ConfigureAwait(false); } return default; diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/CopyConversationMessagesExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/CopyConversationMessagesExecutor.cs index 01b1bab496..b43d388da8 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/CopyConversationMessagesExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/CopyConversationMessagesExecutor.cs @@ -33,7 +33,7 @@ internal sealed class CopyConversationMessagesExecutor(CopyConversationMessages if (isWorkflowConversation) { - await context.AddEventAsync(new AgentRunResponseEvent(this.Id, new AgentRunResponse([.. inputMessages])), cancellationToken).ConfigureAwait(false); + await context.AddEventAsync(new AgentRunResponseEvent(this.Id, new AgentResponse([.. inputMessages])), cancellationToken).ConfigureAwait(false); } } diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/InvokeAzureAgentExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/InvokeAzureAgentExecutor.cs index ed069a9b78..0cd6fee77b 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/InvokeAzureAgentExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/InvokeAzureAgentExecutor.cs @@ -61,12 +61,12 @@ internal sealed class InvokeAzureAgentExecutor(InvokeAzureAgent model, WorkflowA string agentName = this.GetAgentName(); bool autoSend = this.GetAutoSendValue(); Dictionary? inputParameters = this.GetStructuredInputs(); - AgentRunResponse agentResponse = await agentProvider.InvokeAgentAsync(this.Id, context, agentName, conversationId, autoSend, messages, inputParameters, cancellationToken).ConfigureAwait(false); + AgentResponse agentResponse = await agentProvider.InvokeAgentAsync(this.Id, context, agentName, conversationId, autoSend, messages, inputParameters, cancellationToken).ConfigureAwait(false); ChatMessage[] actionableMessages = FilterActionableContent(agentResponse).ToArray(); if (actionableMessages.Length > 0) { - AgentRunResponse filteredResponse = + AgentResponse filteredResponse = new(actionableMessages) { AdditionalProperties = agentResponse.AdditionalProperties, @@ -137,7 +137,7 @@ internal sealed class InvokeAzureAgentExecutor(InvokeAzureAgent model, WorkflowA return userInput?.ToChatMessages(); } - private static IEnumerable FilterActionableContent(AgentRunResponse agentResponse) + private static IEnumerable FilterActionableContent(AgentResponse agentResponse) { HashSet functionResultIds = [.. agentResponse.Messages diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/RequestExternalInputExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/RequestExternalInputExecutor.cs index 2c35dc18e9..1b7a348ede 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/RequestExternalInputExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/RequestExternalInputExecutor.cs @@ -26,7 +26,7 @@ internal sealed class RequestExternalInputExecutor(RequestExternalInput model, W protected override async ValueTask ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default) { - ExternalInputRequest inputRequest = new(new AgentRunResponse()); + ExternalInputRequest inputRequest = new(new AgentResponse()); await context.SendMessageAsync(inputRequest, cancellationToken).ConfigureAwait(false); diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/WorkflowAgentProvider.cs b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/WorkflowAgentProvider.cs index e0967ab376..cfd75d1ca4 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/WorkflowAgentProvider.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/WorkflowAgentProvider.cs @@ -91,8 +91,8 @@ public abstract class WorkflowAgentProvider /// The messages to include in the invocation. /// Optional input arguments for agents that provide support. /// A token that propagates notification when operation should be canceled. - /// Asynchronous set of . - public abstract IAsyncEnumerable InvokeAgentAsync( + /// Asynchronous set of . + public abstract IAsyncEnumerable InvokeAgentAsync( string agentId, string? agentVersion, string? conversationId, diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/AIAgentsAbstractionsExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/AIAgentsAbstractionsExtensions.cs index 9f9906270e..54653f306a 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/AIAgentsAbstractionsExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/AIAgentsAbstractionsExtensions.cs @@ -8,7 +8,7 @@ namespace Microsoft.Agents.AI.Workflows; internal static class AIAgentsAbstractionsExtensions { - public static ChatMessage ToChatMessage(this AgentRunResponseUpdate update) => + public static ChatMessage ToChatMessage(this AgentResponseUpdate update) => new() { AuthorName = update.AuthorName, diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunResponseEvent.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunResponseEvent.cs index 3f0013a88c..f3bc6834c2 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunResponseEvent.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunResponseEvent.cs @@ -14,7 +14,7 @@ public class AgentRunResponseEvent : ExecutorEvent /// /// The identifier of the executor that generated this event. /// The agent run response. - public AgentRunResponseEvent(string executorId, AgentRunResponse response) : base(executorId, data: response) + public AgentRunResponseEvent(string executorId, AgentResponse response) : base(executorId, data: response) { this.Response = Throw.IfNull(response); } @@ -22,5 +22,5 @@ public class AgentRunResponseEvent : ExecutorEvent /// /// Gets the agent run response. /// - public AgentRunResponse Response { get; } + public AgentResponse Response { get; } } diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunUpdateEvent.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunUpdateEvent.cs index 9fbf16b602..34a8d52ab8 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunUpdateEvent.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/AgentRunUpdateEvent.cs @@ -15,7 +15,7 @@ public class AgentRunUpdateEvent : ExecutorEvent /// /// The identifier of the executor that generated this event. /// The agent run response update. - public AgentRunUpdateEvent(string executorId, AgentRunResponseUpdate update) : base(executorId, data: update) + public AgentRunUpdateEvent(string executorId, AgentResponseUpdate update) : base(executorId, data: update) { this.Update = Throw.IfNull(update); } @@ -23,15 +23,15 @@ public class AgentRunUpdateEvent : ExecutorEvent /// /// Gets the agent run response update. /// - public AgentRunResponseUpdate Update { get; } + public AgentResponseUpdate Update { get; } /// - /// Converts this event to an containing just this update. + /// Converts this event to an containing just this update. /// /// - public AgentRunResponse AsResponse() + public AgentResponse AsResponse() { - IEnumerable updates = [this.Update]; - return updates.ToAgentRunResponse(); + IEnumerable updates = [this.Update]; + return updates.ToAgentResponse(); } } diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/MessageMerger.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/MessageMerger.cs index 4560074dd2..de4a8b89f7 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/MessageMerger.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/MessageMerger.cs @@ -14,10 +14,10 @@ internal sealed class MessageMerger { public string? ResponseId { get; } = responseId; - public Dictionary> UpdatesByMessageId { get; } = []; - public List DanglingUpdates { get; } = []; + public Dictionary> UpdatesByMessageId { get; } = []; + public List DanglingUpdates { get; } = []; - public void AddUpdate(AgentRunResponseUpdate update) + public void AddUpdate(AgentResponseUpdate update) { if (update.MessageId is null) { @@ -25,7 +25,7 @@ internal sealed class MessageMerger } else { - if (!this.UpdatesByMessageId.TryGetValue(update.MessageId, out List? updates)) + if (!this.UpdatesByMessageId.TryGetValue(update.MessageId, out List? updates)) { this.UpdatesByMessageId[update.MessageId] = updates = []; } @@ -34,24 +34,24 @@ internal sealed class MessageMerger } } - public AgentRunResponse ComputeMerged(string messageId) + public AgentResponse ComputeMerged(string messageId) { - if (this.UpdatesByMessageId.TryGetValue(Throw.IfNull(messageId), out List? updates)) + if (this.UpdatesByMessageId.TryGetValue(Throw.IfNull(messageId), out List? updates)) { - return updates.ToAgentRunResponse(); + return updates.ToAgentResponse(); } throw new KeyNotFoundException($"No updates found for message ID '{messageId}' in response '{this.ResponseId}'."); } - public AgentRunResponse ComputeDangling() + public AgentResponse ComputeDangling() { if (this.DanglingUpdates.Count == 0) { throw new InvalidOperationException("No dangling updates to compute a response from."); } - return this.DanglingUpdates.ToAgentRunResponse(); + return this.DanglingUpdates.ToAgentResponse(); } public List ComputeFlattened() @@ -66,7 +66,7 @@ internal sealed class MessageMerger IList AggregateUpdatesToMessage(string messageId) { - List updates = this.UpdatesByMessageId[messageId]; + List updates = this.UpdatesByMessageId[messageId]; if (updates.Count == 0) { throw new InvalidOperationException($"No updates found for message ID '{messageId}' in response '{this.ResponseId}'."); @@ -80,7 +80,7 @@ internal sealed class MessageMerger private readonly Dictionary _mergeStates = []; private readonly ResponseMergeState _danglingState = new(null); - public void AddUpdate(AgentRunResponseUpdate update) + public void AddUpdate(AgentResponseUpdate update) { if (update.ResponseId is null) { @@ -97,7 +97,7 @@ internal sealed class MessageMerger } } - private int CompareByDateTimeOffset(AgentRunResponse left, AgentRunResponse right) + private int CompareByDateTimeOffset(AgentResponse left, AgentResponse right) { const int LESS = -1, EQ = 0, GREATER = 1; @@ -119,17 +119,17 @@ internal sealed class MessageMerger return left.CreatedAt.Value.CompareTo(right.CreatedAt.Value); } - public AgentRunResponse ComputeMerged(string primaryResponseId, string? primaryAgentId = null, string? primaryAgentName = null) + public AgentResponse ComputeMerged(string primaryResponseId, string? primaryAgentId = null, string? primaryAgentName = null) { List messages = []; - Dictionary responses = []; + Dictionary responses = []; HashSet agentIds = []; foreach (string responseId in this._mergeStates.Keys) { ResponseMergeState mergeState = this._mergeStates[responseId]; - List responseList = mergeState.UpdatesByMessageId.Keys.Select(mergeState.ComputeMerged).ToList(); + List responseList = mergeState.UpdatesByMessageId.Keys.Select(mergeState.ComputeMerged).ToList(); if (mergeState.DanglingUpdates.Count > 0) { responseList.Add(mergeState.ComputeDangling()); @@ -144,7 +144,7 @@ internal sealed class MessageMerger AdditionalPropertiesDictionary? additionalProperties = null; HashSet createdTimes = []; - foreach (AgentRunResponse response in responses.Values) + foreach (AgentResponse response in responses.Values) { if (response.AgentId is not null) { @@ -176,7 +176,7 @@ internal sealed class MessageMerger } messages.RemoveAll(m => m.Contents.Count == 0); - return new AgentRunResponse(messages) + return new AgentResponse(messages) { ResponseId = primaryResponseId, AgentId = primaryAgentId @@ -187,7 +187,7 @@ internal sealed class MessageMerger AdditionalProperties = additionalProperties }; - static AgentRunResponse MergeResponses(AgentRunResponse? current, AgentRunResponse incoming) + static AgentResponse MergeResponses(AgentResponse? current, AgentResponse incoming) { if (current is null) { @@ -214,7 +214,7 @@ internal sealed class MessageMerger }; } - static IEnumerable GetMessagesWithCreatedAt(AgentRunResponse response) + static IEnumerable GetMessagesWithCreatedAt(AgentResponse response) { if (response.Messages.Count == 0) { diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AIAgentHostExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AIAgentHostExecutor.cs index 87474b9c08..3a344933f9 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AIAgentHostExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AIAgentHostExecutor.cs @@ -54,14 +54,14 @@ internal sealed class AIAgentHostExecutor : ChatProtocolExecutor if (emitEvents ?? this._emitEvents) { // Run the agent in streaming mode only when agent run update events are to be emitted. - IAsyncEnumerable agentStream = this._agent.RunStreamingAsync( + IAsyncEnumerable agentStream = this._agent.RunStreamingAsync( messages, await this.EnsureThreadAsync(context, cancellationToken).ConfigureAwait(false), cancellationToken: cancellationToken); - List updates = []; + List updates = []; - await foreach (AgentRunResponseUpdate update in agentStream.ConfigureAwait(false)) + await foreach (AgentResponseUpdate update in agentStream.ConfigureAwait(false)) { await context.AddEventAsync(new AgentRunUpdateEvent(this.Id, update), cancellationToken).ConfigureAwait(false); @@ -72,12 +72,12 @@ internal sealed class AIAgentHostExecutor : ChatProtocolExecutor updates.Add(update); } - await context.SendMessageAsync(updates.ToAgentRunResponse().Messages, cancellationToken: cancellationToken).ConfigureAwait(false); + await context.SendMessageAsync(updates.ToAgentResponse().Messages, cancellationToken: cancellationToken).ConfigureAwait(false); } else { // Otherwise, run the agent in non-streaming mode. - AgentRunResponse response = await this._agent.RunAsync( + AgentResponse response = await this._agent.RunAsync( messages, await this.EnsureThreadAsync(context, cancellationToken).ConfigureAwait(false), cancellationToken: cancellationToken).ConfigureAwait(false); diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AgentRunStreamingExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AgentRunStreamingExecutor.cs index ae3a932feb..03a3432ee0 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AgentRunStreamingExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/AgentRunStreamingExecutor.cs @@ -22,7 +22,7 @@ internal sealed class AgentRunStreamingExecutor(AIAgent agent, bool includeInput { List? roleChanged = messages.ChangeAssistantToUserForOtherParticipants(agent.Name ?? agent.Id); - List updates = []; + List updates = []; await foreach (var update in agent.RunStreamingAsync(messages, cancellationToken: cancellationToken).ConfigureAwait(false)) { updates.Add(update); @@ -35,7 +35,7 @@ internal sealed class AgentRunStreamingExecutor(AIAgent agent, bool includeInput roleChanged.ResetUserToAssistantForChangedRoles(); List result = includeInputInOutput ? [.. messages] : []; - result.AddRange(updates.ToAgentRunResponse().Messages); + result.AddRange(updates.ToAgentResponse().Messages); await context.SendMessageAsync(result, cancellationToken: cancellationToken).ConfigureAwait(false); } diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs index 24e0eea3cb..e703275972 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs @@ -64,7 +64,7 @@ internal sealed class HandoffAgentExecutor( routeBuilder.AddHandler(async (handoffState, context, cancellationToken) => { string? requestedHandoff = null; - List updates = []; + List updates = []; List allMessages = handoffState.Messages; List? roleChanges = allMessages.ChangeAssistantToUserForOtherParticipants(this._agent.Name ?? this._agent.Id); @@ -82,7 +82,7 @@ internal sealed class HandoffAgentExecutor( { requestedHandoff = fcc.Name; await AddUpdateAsync( - new AgentRunResponseUpdate + new AgentResponseUpdate { AgentId = this._agent.Id, AuthorName = this._agent.Name ?? this._agent.Id, @@ -98,13 +98,13 @@ internal sealed class HandoffAgentExecutor( } } - allMessages.AddRange(updates.ToAgentRunResponse().Messages); + allMessages.AddRange(updates.ToAgentResponse().Messages); roleChanges.ResetUserToAssistantForChangedRoles(); await context.SendMessageAsync(new HandoffState(handoffState.TurnToken, requestedHandoff, allMessages), cancellationToken: cancellationToken).ConfigureAwait(false); - async Task AddUpdateAsync(AgentRunResponseUpdate update, CancellationToken cancellationToken) + async Task AddUpdateAsync(AgentResponseUpdate update, CancellationToken cancellationToken) { updates.Add(update); if (handoffState.TurnToken.EmitEvents is true) diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowHostAgent.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowHostAgent.cs index 37867cfd51..f20660bc51 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowHostAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowHostAgent.cs @@ -85,7 +85,7 @@ internal sealed class WorkflowHostAgent : AIAgent } protected override async - Task RunCoreAsync( + Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -96,7 +96,7 @@ internal sealed class WorkflowHostAgent : AIAgent WorkflowThread workflowThread = await this.UpdateThreadAsync(messages, thread, cancellationToken).ConfigureAwait(false); MessageMerger merger = new(); - await foreach (AgentRunResponseUpdate update in workflowThread.InvokeStageAsync(cancellationToken) + await foreach (AgentResponseUpdate update in workflowThread.InvokeStageAsync(cancellationToken) .ConfigureAwait(false) .WithCancellation(cancellationToken)) { @@ -107,7 +107,7 @@ internal sealed class WorkflowHostAgent : AIAgent } protected override async - IAsyncEnumerable RunCoreStreamingAsync( + IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -116,7 +116,7 @@ internal sealed class WorkflowHostAgent : AIAgent await this.ValidateWorkflowAsync().ConfigureAwait(false); WorkflowThread workflowThread = await this.UpdateThreadAsync(messages, thread, cancellationToken).ConfigureAwait(false); - await foreach (AgentRunResponseUpdate update in workflowThread.InvokeStageAsync(cancellationToken) + await foreach (AgentResponseUpdate update in workflowThread.InvokeStageAsync(cancellationToken) .ConfigureAwait(false) .WithCancellation(cancellationToken)) { diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowThread.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowThread.cs index 94144831e0..6bd41ecadb 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowThread.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowThread.cs @@ -83,11 +83,11 @@ internal sealed class WorkflowThread : AgentThread return marshaller.Marshal(info); } - public AgentRunResponseUpdate CreateUpdate(string responseId, object raw, params AIContent[] parts) + public AgentResponseUpdate CreateUpdate(string responseId, object raw, params AIContent[] parts) { Throw.IfNullOrEmpty(parts); - AgentRunResponseUpdate update = new(ChatRole.Assistant, parts) + AgentResponseUpdate update = new(ChatRole.Assistant, parts) { CreatedAt = DateTimeOffset.UtcNow, MessageId = Guid.NewGuid().ToString("N"), @@ -130,7 +130,7 @@ internal sealed class WorkflowThread : AgentThread } internal async - IAsyncEnumerable InvokeStageAsync( + IAsyncEnumerable InvokeStageAsync( [EnumeratorCancellation] CancellationToken cancellationToken = default) { try @@ -157,7 +157,7 @@ internal sealed class WorkflowThread : AgentThread case RequestInfoEvent requestInfo: FunctionCallContent fcContent = requestInfo.Request.ToFunctionCall(); - AgentRunResponseUpdate update = this.CreateUpdate(this.LastResponseId, evt, fcContent); + AgentResponseUpdate update = this.CreateUpdate(this.LastResponseId, evt, fcContent); yield return update; break; @@ -186,7 +186,7 @@ internal sealed class WorkflowThread : AgentThread default: // Emit all other workflow events for observability (DevUI, logging, etc.) - yield return new AgentRunResponseUpdate(ChatRole.Assistant, []) + yield return new AgentResponseUpdate(ChatRole.Assistant, []) { CreatedAt = DateTimeOffset.UtcNow, MessageId = Guid.NewGuid().ToString("N"), diff --git a/dotnet/src/Microsoft.Agents.AI/AIAgentBuilder.cs b/dotnet/src/Microsoft.Agents.AI/AIAgentBuilder.cs index a74da3ed20..7d629c42b1 100644 --- a/dotnet/src/Microsoft.Agents.AI/AIAgentBuilder.cs +++ b/dotnet/src/Microsoft.Agents.AI/AIAgentBuilder.cs @@ -143,8 +143,8 @@ public sealed class AIAgentBuilder /// /// Both and are . public AIAgentBuilder Use( - Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, Task>? runFunc, - Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, IAsyncEnumerable>? runStreamingFunc) + Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, Task>? runFunc, + Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, IAsyncEnumerable>? runStreamingFunc) { AnonymousDelegatingAIAgent.ThrowIfBothDelegatesNull(runFunc, runStreamingFunc); diff --git a/dotnet/src/Microsoft.Agents.AI/AnonymousDelegatingAIAgent.cs b/dotnet/src/Microsoft.Agents.AI/AnonymousDelegatingAIAgent.cs index 542bafdbf4..48de303bc1 100644 --- a/dotnet/src/Microsoft.Agents.AI/AnonymousDelegatingAIAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI/AnonymousDelegatingAIAgent.cs @@ -18,7 +18,7 @@ namespace Microsoft.Agents.AI; internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent { /// The delegate to use as the implementation of . - private readonly Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, Task>? _runFunc; + private readonly Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, Task>? _runFunc; /// The delegate to use as the implementation of . /// @@ -26,7 +26,7 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent /// will be invoked with the same arguments as the method itself. /// When , will delegate directly to the inner agent. /// - private readonly Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, IAsyncEnumerable>? _runStreamingFunc; + private readonly Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, IAsyncEnumerable>? _runStreamingFunc; /// The delegate to use as the implementation of both and . private readonly Func, AgentThread?, AgentRunOptions?, Func, AgentThread?, AgentRunOptions?, CancellationToken, Task>, CancellationToken, Task>? _sharedFunc; @@ -74,8 +74,8 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent /// Both and are . public AnonymousDelegatingAIAgent( AIAgent innerAgent, - Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, Task>? runFunc, - Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, IAsyncEnumerable>? runStreamingFunc) + Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, Task>? runFunc, + Func, AgentThread?, AgentRunOptions?, AIAgent, CancellationToken, IAsyncEnumerable>? runStreamingFunc) : base(innerAgent) { ThrowIfBothDelegatesNull(runFunc, runStreamingFunc); @@ -85,7 +85,7 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent } /// - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -97,10 +97,10 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent { return GetRunViaSharedAsync(messages, thread, options, cancellationToken); - async Task GetRunViaSharedAsync( + async Task GetRunViaSharedAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, CancellationToken cancellationToken) { - AgentRunResponse? response = null; + AgentResponse? response = null; await this._sharedFunc( messages, @@ -113,7 +113,7 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent if (response is null) { - Throw.InvalidOperationException("The shared delegate completed successfully without producing an AgentRunResponse."); + Throw.InvalidOperationException("The shared delegate completed successfully without producing an AgentResponse."); } return response; @@ -127,12 +127,12 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent { Debug.Assert(this._runStreamingFunc is not null, "Expected non-null streaming delegate."); return this._runStreamingFunc!(messages, thread, options, this.InnerAgent, cancellationToken) - .ToAgentRunResponseAsync(cancellationToken); + .ToAgentResponseAsync(cancellationToken); } } /// - protected override IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -142,7 +142,7 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent if (this._sharedFunc is not null) { - var updates = Channel.CreateBounded(1); + var updates = Channel.CreateBounded(1); _ = ProcessAsync(); async Task ProcessAsync() @@ -180,10 +180,10 @@ internal sealed class AnonymousDelegatingAIAgent : DelegatingAIAgent Debug.Assert(this._runFunc is not null, "Expected non-null non-streaming delegate."); return GetStreamingRunAsyncViaRunAsync(this._runFunc!(messages, thread, options, this.InnerAgent, cancellationToken)); - static async IAsyncEnumerable GetStreamingRunAsyncViaRunAsync(Task task) + static async IAsyncEnumerable GetStreamingRunAsyncViaRunAsync(Task task) { - AgentRunResponse response = await task.ConfigureAwait(false); - foreach (var update in response.ToAgentRunResponseUpdates()) + AgentResponse response = await task.ConfigureAwait(false); + foreach (var update in response.ToAgentResponseUpdates()) { yield return update; } diff --git a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs index 8f6d6a5160..206f97cf54 100644 --- a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs @@ -149,7 +149,7 @@ public sealed partial class ChatClientAgent : AIAgent internal ChatOptions? ChatOptions => this._agentOptions?.ChatOptions; /// - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -160,9 +160,9 @@ public sealed partial class ChatClientAgent : AIAgent return chatClient.GetResponseAsync(threadMessages, chatOptions, ct); } - static AgentRunResponse CreateResponse(ChatResponse chatResponse) + static AgentResponse CreateResponse(ChatResponse chatResponse) { - return new AgentRunResponse(chatResponse) + return new AgentResponse(chatResponse) { ContinuationToken = WrapContinuationToken(chatResponse.ContinuationToken) }; @@ -196,7 +196,7 @@ public sealed partial class ChatClientAgent : AIAgent } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -406,14 +406,14 @@ public sealed partial class ChatClientAgent : AIAgent #region Private - private async Task RunCoreAsync( + private async Task RunCoreAsync( Func, ChatOptions?, CancellationToken, Task> chatClientRunFunc, - Func agentResponseFactoryFunc, + Func agentResponseFactoryFunc, IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) - where TAgentRunResponse : AgentRunResponse + where TAgentResponse : AgentResponse where TChatClientResponse : ChatResponse { var inputMessages = Throw.IfNull(messages) as IReadOnlyCollection ?? messages.ToList(); diff --git a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentCustomOptions.cs b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentCustomOptions.cs index b0cbd3d793..c5502ad916 100644 --- a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentCustomOptions.cs +++ b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentCustomOptions.cs @@ -22,8 +22,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task RunAsync( AgentThread? thread, ChatClientAgentRunOptions? options, CancellationToken cancellationToken = default) => @@ -39,8 +39,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task RunAsync( string message, AgentThread? thread, ChatClientAgentRunOptions? options, @@ -57,8 +57,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task RunAsync( ChatMessage message, AgentThread? thread, ChatClientAgentRunOptions? options, @@ -75,8 +75,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task RunAsync( IEnumerable messages, AgentThread? thread, ChatClientAgentRunOptions? options, @@ -92,8 +92,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. - public IAsyncEnumerable RunStreamingAsync( + /// An asynchronous enumerable of instances representing the streaming response. + public IAsyncEnumerable RunStreamingAsync( AgentThread? thread, ChatClientAgentRunOptions? options, CancellationToken cancellationToken = default) => @@ -109,8 +109,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. - public IAsyncEnumerable RunStreamingAsync( + /// An asynchronous enumerable of instances representing the streaming response. + public IAsyncEnumerable RunStreamingAsync( string message, AgentThread? thread, ChatClientAgentRunOptions? options, @@ -127,8 +127,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. - public IAsyncEnumerable RunStreamingAsync( + /// An asynchronous enumerable of instances representing the streaming response. + public IAsyncEnumerable RunStreamingAsync( ChatMessage message, AgentThread? thread, ChatClientAgentRunOptions? options, @@ -145,8 +145,8 @@ public partial class ChatClientAgent /// /// Configuration parameters for controlling the agent's invocation behavior. /// The to monitor for cancellation requests. The default is . - /// An asynchronous enumerable of instances representing the streaming response. - public IAsyncEnumerable RunStreamingAsync( + /// An asynchronous enumerable of instances representing the streaming response. + public IAsyncEnumerable RunStreamingAsync( IEnumerable messages, AgentThread? thread, ChatClientAgentRunOptions? options, @@ -167,8 +167,8 @@ public partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task> RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task> RunAsync( AgentThread? thread, JsonSerializerOptions? serializerOptions, ChatClientAgentRunOptions? options, @@ -191,8 +191,8 @@ public partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task> RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task> RunAsync( string message, AgentThread? thread, JsonSerializerOptions? serializerOptions, @@ -216,8 +216,8 @@ public partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task> RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task> RunAsync( ChatMessage message, AgentThread? thread, JsonSerializerOptions? serializerOptions, @@ -241,8 +241,8 @@ public partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. - public Task> RunAsync( + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + public Task> RunAsync( IEnumerable messages, AgentThread? thread, JsonSerializerOptions? serializerOptions, diff --git a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentRunResponse{T}.cs b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentRunResponse{T}.cs index 352be764eb..a4fadff0c7 100644 --- a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentRunResponse{T}.cs +++ b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentRunResponse{T}.cs @@ -12,23 +12,23 @@ namespace Microsoft.Agents.AI; /// The type of value expected from the chat response. /// /// Language models are not guaranteed to honor the requested schema. If the model's output is not -/// parsable as the expected type, you can access the underlying JSON response on the property. +/// parsable as the expected type, you can access the underlying JSON response on the property. /// -public sealed class ChatClientAgentRunResponse : AgentRunResponse +public sealed class ChatClientAgentResponse : AgentResponse { private readonly ChatResponse _response; /// - /// Initializes a new instance of the class from an existing . + /// Initializes a new instance of the class from an existing . /// - /// The from which to populate this . + /// The from which to populate this . /// is . /// /// This constructor creates an agent response that wraps an existing , preserving all /// metadata and storing the original response in for access to /// the underlying implementation details. /// - public ChatClientAgentRunResponse(ChatResponse response) : base(response) + public ChatClientAgentResponse(ChatResponse response) : base(response) { _ = Throw.IfNull(response); diff --git a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentStructuredOutput.cs b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentStructuredOutput.cs index 9a535cd645..6bd62e85a2 100644 --- a/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentStructuredOutput.cs +++ b/dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentStructuredOutput.cs @@ -29,12 +29,12 @@ public sealed partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// /// This overload is useful when the agent has sufficient context from previous messages in the thread /// or from its initial configuration to generate a meaningful response without additional input. /// - public Task> RunAsync( + public Task> RunAsync( AgentThread? thread = null, JsonSerializerOptions? serializerOptions = null, AgentRunOptions? options = null, @@ -57,13 +57,13 @@ public sealed partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// is , empty, or contains only whitespace. /// /// The provided text will be wrapped in a with the role /// before being sent to the agent. This is a convenience method for simple text-based interactions. /// - public Task> RunAsync( + public Task> RunAsync( string message, AgentThread? thread = null, JsonSerializerOptions? serializerOptions = null, @@ -91,9 +91,9 @@ public sealed partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// is . - public Task> RunAsync( + public Task> RunAsync( ChatMessage message, AgentThread? thread = null, JsonSerializerOptions? serializerOptions = null, @@ -121,7 +121,7 @@ public sealed partial class ChatClientAgent /// Using a JSON schema improves reliability if the underlying model supports native structured output with a schema, but might cause an error if the model does not support it. /// /// The to monitor for cancellation requests. The default is . - /// A task that represents the asynchronous operation. The task result contains an with the agent's output. + /// A task that represents the asynchronous operation. The task result contains an with the agent's output. /// The type of structured output to request. /// /// @@ -134,7 +134,7 @@ public sealed partial class ChatClientAgent /// The agent's response will also be added to if one is provided. /// /// - public Task> RunAsync( + public Task> RunAsync( IEnumerable messages, AgentThread? thread = null, JsonSerializerOptions? serializerOptions = null, @@ -152,9 +152,9 @@ public sealed partial class ChatClientAgent ct).ConfigureAwait(false); } - static ChatClientAgentRunResponse CreateResponse(ChatResponse chatResponse) + static ChatClientAgentResponse CreateResponse(ChatResponse chatResponse) { - return new ChatClientAgentRunResponse(chatResponse) + return new ChatClientAgentResponse(chatResponse) { ContinuationToken = WrapContinuationToken(chatResponse.ContinuationToken) }; diff --git a/dotnet/src/Microsoft.Agents.AI/FunctionInvocationDelegatingAgent.cs b/dotnet/src/Microsoft.Agents.AI/FunctionInvocationDelegatingAgent.cs index 2463b266c7..0604ef17d8 100644 --- a/dotnet/src/Microsoft.Agents.AI/FunctionInvocationDelegatingAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI/FunctionInvocationDelegatingAgent.cs @@ -21,10 +21,10 @@ internal sealed class FunctionInvocationDelegatingAgent : DelegatingAIAgent this._delegateFunc = delegateFunc; } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => this.InnerAgent.RunAsync(messages, thread, this.AgentRunOptionsWithFunctionMiddleware(options), cancellationToken); - protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => this.InnerAgent.RunStreamingAsync(messages, thread, this.AgentRunOptionsWithFunctionMiddleware(options), cancellationToken); // Decorate options to add the middleware function diff --git a/dotnet/src/Microsoft.Agents.AI/LoggingAgent.cs b/dotnet/src/Microsoft.Agents.AI/LoggingAgent.cs index 03b85d1ef5..258ea55ed7 100644 --- a/dotnet/src/Microsoft.Agents.AI/LoggingAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI/LoggingAgent.cs @@ -55,7 +55,7 @@ public sealed partial class LoggingAgent : DelegatingAIAgent } /// - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { if (this._logger.IsEnabled(LogLevel.Debug)) @@ -72,7 +72,7 @@ public sealed partial class LoggingAgent : DelegatingAIAgent try { - AgentRunResponse response = await base.RunCoreAsync(messages, thread, options, cancellationToken).ConfigureAwait(false); + AgentResponse response = await base.RunCoreAsync(messages, thread, options, cancellationToken).ConfigureAwait(false); if (this._logger.IsEnabled(LogLevel.Debug)) { @@ -101,7 +101,7 @@ public sealed partial class LoggingAgent : DelegatingAIAgent } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { if (this._logger.IsEnabled(LogLevel.Debug)) @@ -116,7 +116,7 @@ public sealed partial class LoggingAgent : DelegatingAIAgent } } - IAsyncEnumerator e; + IAsyncEnumerator e; try { e = base.RunCoreStreamingAsync(messages, thread, options, cancellationToken).GetAsyncEnumerator(cancellationToken); @@ -134,7 +134,7 @@ public sealed partial class LoggingAgent : DelegatingAIAgent try { - AgentRunResponseUpdate? update = null; + AgentResponseUpdate? update = null; while (true) { try diff --git a/dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs b/dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs index 35d31371c3..07dadf4e0b 100644 --- a/dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs +++ b/dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs @@ -78,25 +78,25 @@ public sealed class OpenTelemetryAgent : DelegatingAIAgent, IDisposable } /// - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { ChatOptions co = new ForwardedOptions(options, thread, Activity.Current); var response = await this._otelClient.GetResponseAsync(messages, co, cancellationToken).ConfigureAwait(false); - return response.RawRepresentation as AgentRunResponse ?? new AgentRunResponse(response); + return response.RawRepresentation as AgentResponse ?? new AgentResponse(response); } /// - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { ChatOptions co = new ForwardedOptions(options, thread, Activity.Current); await foreach (var update in this._otelClient.GetStreamingResponseAsync(messages, co, cancellationToken).ConfigureAwait(false)) { - yield return update.RawRepresentation as AgentRunResponseUpdate ?? new AgentRunResponseUpdate(update); + yield return update.RawRepresentation as AgentResponseUpdate ?? new AgentResponseUpdate(update); } } diff --git a/dotnet/src/Shared/Samples/BaseSample.cs b/dotnet/src/Shared/Samples/BaseSample.cs index 36c18f2db4..90c2d991a8 100644 --- a/dotnet/src/Shared/Samples/BaseSample.cs +++ b/dotnet/src/Shared/Samples/BaseSample.cs @@ -86,12 +86,12 @@ public abstract class BaseSample : TextWriter /// Processes and writes the latest agent chat response to the console, including metadata and content details. /// /// This method formats and outputs the most recent message from the provided object. It includes the message role, author name (if available), text content, and + /// cref="AgentResponse"/> object. It includes the message role, author name (if available), text content, and /// additional content such as images, function calls, and function results. Usage statistics, including token /// counts, are also displayed. - /// The object containing the chat messages and usage data. + /// The object containing the chat messages and usage data. /// The flag to indicate whether to print usage information. Defaults to . - protected void WriteResponseOutput(AgentRunResponse response, bool? printUsage = true) + protected void WriteResponseOutput(AgentResponse response, bool? printUsage = true) { if (response.Messages.Count == 0) { @@ -150,11 +150,11 @@ public abstract class BaseSample : TextWriter /// Writes the streaming agent response updates to the console. /// /// This method formats and outputs the most recent message from the provided object. It includes the message role, author name (if available), text content, and + /// cref="AgentResponseUpdate"/> object. It includes the message role, author name (if available), text content, and /// additional content such as images, function calls, and function results. Usage statistics, including token /// counts, are also displayed. - /// The object containing the chat messages and usage data. - protected void WriteAgentOutput(AgentRunResponseUpdate update) + /// The object containing the chat messages and usage data. + protected void WriteAgentOutput(AgentResponseUpdate update) { if (update.Contents.Count == 0) { diff --git a/dotnet/src/Shared/Samples/OrchestrationSample.cs b/dotnet/src/Shared/Samples/OrchestrationSample.cs index 55f372de47..6eb8b5f886 100644 --- a/dotnet/src/Shared/Samples/OrchestrationSample.cs +++ b/dotnet/src/Shared/Samples/OrchestrationSample.cs @@ -75,13 +75,13 @@ public abstract class OrchestrationSample : BaseSample /// /// Writes the streamed agent run response updates to the console or test output, including role and author information. /// - /// An enumerable of objects representing streamed responses. - protected static void WriteStreamedResponse(IEnumerable streamedResponses) + /// An enumerable of objects representing streamed responses. + protected static void WriteStreamedResponse(IEnumerable streamedResponses) { string? authorName = null; ChatRole? authorRole = null; StringBuilder builder = new(); - foreach (AgentRunResponseUpdate response in streamedResponses) + foreach (AgentResponseUpdate response in streamedResponses) { authorName ??= response.AuthorName; authorRole ??= response.Role; @@ -106,7 +106,7 @@ public abstract class OrchestrationSample : BaseSample /// /// Gets the list of streamed response updates received so far. /// - public List StreamedResponses { get; } = []; + public List StreamedResponses { get; } = []; /// /// Gets the list of chat messages representing the conversation history. @@ -131,9 +131,9 @@ public abstract class OrchestrationSample : BaseSample /// /// Callback to handle a streamed agent run response update, adding it to the list and writing output if final. /// - /// The to process. + /// The to process. /// A representing the asynchronous operation. - public ValueTask StreamingResultCallbackAsync(AgentRunResponseUpdate streamedResponse) + public ValueTask StreamingResultCallbackAsync(AgentResponseUpdate streamedResponse) { this.StreamedResponses.Add(streamedResponse); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.A2A.UnitTests/A2AAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.A2A.UnitTests/A2AAgentTests.cs index 6364e87012..b6002de9ef 100644 --- a/dotnet/tests/Microsoft.Agents.AI.A2A.UnitTests/A2AAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.A2A.UnitTests/A2AAgentTests.cs @@ -210,7 +210,7 @@ public sealed class A2AAgentTests : IDisposable } [Fact] - public async Task RunStreamingAsync_WithValidUserMessage_YieldsAgentRunResponseUpdatesAsync() + public async Task RunStreamingAsync_WithValidUserMessage_YieldsAgentResponseUpdatesAsync() { // Arrange var inputMessages = new List @@ -227,7 +227,7 @@ public sealed class A2AAgentTests : IDisposable }; // Act - var updates = new List(); + var updates = new List(); await foreach (var update in this._agent.RunStreamingAsync(inputMessages)) { updates.Add(update); @@ -646,7 +646,7 @@ public sealed class A2AAgentTests : IDisposable }; // Act - var updates = new List(); + var updates = new List(); await foreach (var update in this._agent.RunStreamingAsync("Test message")) { updates.Add(update); @@ -689,7 +689,7 @@ public sealed class A2AAgentTests : IDisposable var thread = await this._agent.GetNewThreadAsync(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in this._agent.RunStreamingAsync("Start long-running task", thread)) { updates.Add(update); @@ -728,7 +728,7 @@ public sealed class A2AAgentTests : IDisposable var thread = await this._agent.GetNewThreadAsync(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in this._agent.RunStreamingAsync("Check task status", thread)) { updates.Add(update); @@ -771,7 +771,7 @@ public sealed class A2AAgentTests : IDisposable var thread = await this._agent.GetNewThreadAsync(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in this._agent.RunStreamingAsync("Process artifact", thread)) { updates.Add(update); diff --git a/dotnet/tests/Microsoft.Agents.AI.AGUI.UnitTests/AGUIChatClientTests.cs b/dotnet/tests/Microsoft.Agents.AI.AGUI.UnitTests/AGUIChatClientTests.cs index cc000ca73a..009b109891 100644 --- a/dotnet/tests/Microsoft.Agents.AI.AGUI.UnitTests/AGUIChatClientTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.AGUI.UnitTests/AGUIChatClientTests.cs @@ -34,7 +34,7 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - AgentRunResponse response = await agent.RunAsync(messages); + AgentResponse response = await agent.RunAsync(messages); // Assert Assert.NotNull(response); @@ -59,7 +59,7 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - AgentRunResponse response = await agent.RunAsync(messages); + AgentResponse response = await agent.RunAsync(messages); // Assert Assert.NotNull(response); @@ -95,7 +95,7 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - AgentRunResponse response = await agent.RunAsync(messages, thread: null); + AgentResponse response = await agent.RunAsync(messages, thread: null); // Assert Assert.NotNull(response); @@ -119,8 +119,8 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - List updates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages)) + List updates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages)) { // Consume the stream updates.Add(update); @@ -166,8 +166,8 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - List updates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread: null)) + List updates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread: null)) { // Consume the stream updates.Add(update); @@ -232,7 +232,7 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Hello")]; // Act - List updates = []; + List updates = []; await foreach (var update in agent.RunStreamingAsync(messages, thread)) { updates.Add(update); @@ -305,8 +305,8 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "What's the weather?")]; // Act - List allUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages)) + List allUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages)) { allUpdates.Add(update); } @@ -357,8 +357,8 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - List allUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages)) + List allUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages)) { allUpdates.Add(update); } @@ -407,8 +407,8 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - List allUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages)) + List allUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages)) { allUpdates.Add(update); } @@ -491,7 +491,7 @@ public sealed class AGUIAgentTests List messages = [new ChatMessage(ChatRole.User, "Test")]; // Act - List updates = []; + List updates = []; await foreach (var update in agent.RunStreamingAsync(messages, thread)) { updates.Add(update); diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AIAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AIAgentTests.cs index 514de74dab..8d5f1b0b87 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AIAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AIAgentTests.cs @@ -19,8 +19,8 @@ public class AIAgentTests { private readonly Mock _agentMock; private readonly Mock _agentThreadMock; - private readonly AgentRunResponse _invokeResponse; - private readonly List _invokeStreamingResponses = []; + private readonly AgentResponse _invokeResponse; + private readonly List _invokeStreamingResponses = []; /// /// Initializes a new instance of the class. @@ -29,13 +29,13 @@ public class AIAgentTests { this._agentThreadMock = new Mock(MockBehavior.Strict); - this._invokeResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Hi")); - this._invokeStreamingResponses.Add(new AgentRunResponseUpdate(ChatRole.Assistant, "Hi")); + this._invokeResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Hi")); + this._invokeStreamingResponses.Add(new AgentResponseUpdate(ChatRole.Assistant, "Hi")); this._agentMock = new Mock { CallBase = true }; this._agentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.Is(t => t == this._agentThreadMock.Object), ItExpr.IsAny(), @@ -43,7 +43,7 @@ public class AIAgentTests .ReturnsAsync(this._invokeResponse); this._agentMock .Protected() - .Setup>("RunCoreStreamingAsync", + .Setup>("RunCoreStreamingAsync", ItExpr.IsAny>(), ItExpr.Is(t => t == this._agentThreadMock.Object), ItExpr.IsAny(), @@ -69,7 +69,7 @@ public class AIAgentTests // Verify that the mocked method was called with the expected parameters this._agentMock .Protected() - .Verify>("RunCoreAsync", + .Verify>("RunCoreAsync", Times.Once(), ItExpr.Is>(messages => !messages.Any()), ItExpr.Is(t => t == this._agentThreadMock.Object), @@ -96,7 +96,7 @@ public class AIAgentTests // Verify that the mocked method was called with the expected parameters this._agentMock .Protected() - .Verify>("RunCoreAsync", + .Verify>("RunCoreAsync", Times.Once(), ItExpr.Is>(messages => messages.Count() == 1 && messages.First().Text == Message), ItExpr.Is(t => t == this._agentThreadMock.Object), @@ -123,7 +123,7 @@ public class AIAgentTests // Verify that the mocked method was called with the expected parameters this._agentMock .Protected() - .Verify>("RunCoreAsync", + .Verify>("RunCoreAsync", Times.Once(), ItExpr.Is>(messages => messages.Count() == 1 && messages.First() == message), ItExpr.Is(t => t == this._agentThreadMock.Object), @@ -152,7 +152,7 @@ public class AIAgentTests // Verify that the mocked method was called with the expected parameters this._agentMock .Protected() - .Verify>("RunCoreStreamingAsync", + .Verify>("RunCoreStreamingAsync", Times.Once(), ItExpr.Is>(messages => !messages.Any()), ItExpr.Is(t => t == this._agentThreadMock.Object), @@ -182,7 +182,7 @@ public class AIAgentTests // Verify that the mocked method was called with the expected parameters this._agentMock .Protected() - .Verify>("RunCoreStreamingAsync", + .Verify>("RunCoreStreamingAsync", Times.Once(), ItExpr.Is>(messages => messages.Count() == 1 && messages.First().Text == Message), ItExpr.Is(t => t == this._agentThreadMock.Object), @@ -212,7 +212,7 @@ public class AIAgentTests // Verify that the mocked method was called with the expected parameters this._agentMock .Protected() - .Verify>("RunCoreStreamingAsync", + .Verify>("RunCoreStreamingAsync", Times.Once(), ItExpr.Is>(messages => messages.Count() == 1 && messages.First() == message), ItExpr.Is(t => t == this._agentThreadMock.Object), @@ -384,14 +384,14 @@ public class AIAgentTests public override async ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - protected override IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentAbstractionsJsonUtilitiesTests.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentAbstractionsJsonUtilitiesTests.cs index e286796243..5958bba3b3 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentAbstractionsJsonUtilitiesTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentAbstractionsJsonUtilitiesTests.cs @@ -79,9 +79,9 @@ public class AgentAbstractionsJsonUtilitiesTests #endif [Fact] - public void DefaultOptions_UsesCamelCasePropertyNames_ForAgentRunResponse() + public void DefaultOptions_UsesCamelCasePropertyNames_ForAgentResponse() { - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Hello")); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Hello")); string json = JsonSerializer.Serialize(response, AgentAbstractionsJsonUtilities.DefaultOptions); Assert.Contains("\"messages\"", json); Assert.DoesNotContain("\"Messages\"", json); diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseTests.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseTests.cs similarity index 83% rename from dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseTests.cs rename to dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseTests.cs index 8e39b4c4fa..75bc90ca8e 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseTests.cs @@ -9,12 +9,12 @@ using Microsoft.Extensions.AI; namespace Microsoft.Agents.AI.Abstractions.UnitTests; -public class AgentRunResponseTests +public class AgentResponseTests { [Fact] public void ConstructorWithNullEmptyArgsIsValid() { - AgentRunResponse response; + AgentResponse response; response = new(); Assert.Empty(response.Messages); @@ -26,13 +26,13 @@ public class AgentRunResponseTests Assert.Empty(response.Text); Assert.Null(response.ContinuationToken); - Assert.Throws("message", () => new AgentRunResponse((ChatMessage)null!)); + Assert.Throws("message", () => new AgentResponse((ChatMessage)null!)); } [Fact] public void ConstructorWithMessagesRoundtrips() { - AgentRunResponse response = new(); + AgentResponse response = new(); Assert.NotNull(response.Messages); Assert.Same(response.Messages, response.Messages); @@ -60,7 +60,7 @@ public class AgentRunResponseTests ContinuationToken = ResponseContinuationToken.FromBytes(new byte[] { 1, 2, 3 }) }; - AgentRunResponse response = new(chatResponse); + AgentResponse response = new(chatResponse); Assert.Same(chatResponse.AdditionalProperties, response.AdditionalProperties); Assert.Equal(chatResponse.CreatedAt, response.CreatedAt); Assert.Same(chatResponse.Messages, response.Messages); @@ -73,7 +73,7 @@ public class AgentRunResponseTests [Fact] public void PropertiesRoundtrip() { - AgentRunResponse response = new(); + AgentResponse response = new(); Assert.Null(response.AgentId); response.AgentId = "agentId"; @@ -110,7 +110,7 @@ public class AgentRunResponseTests [Fact] public void JsonSerializationRoundtrips() { - AgentRunResponse original = new(new ChatMessage(ChatRole.Assistant, "the message")) + AgentResponse original = new(new ChatMessage(ChatRole.Assistant, "the message")) { AgentId = "agentId", ResponseId = "id", @@ -123,7 +123,7 @@ public class AgentRunResponseTests string json = JsonSerializer.Serialize(original, AgentAbstractionsJsonUtilities.DefaultOptions); - AgentRunResponse? result = JsonSerializer.Deserialize(json, AgentAbstractionsJsonUtilities.DefaultOptions); + AgentResponse? result = JsonSerializer.Deserialize(json, AgentAbstractionsJsonUtilities.DefaultOptions); Assert.NotNull(result); Assert.Equal(ChatRole.Assistant, result.Messages.Single().Role); @@ -145,7 +145,7 @@ public class AgentRunResponseTests [Fact] public void ToStringOutputsText() { - AgentRunResponse response = new(new ChatMessage(ChatRole.Assistant, $"This is a test.{Environment.NewLine}It's multiple lines.")); + AgentResponse response = new(new ChatMessage(ChatRole.Assistant, $"This is a test.{Environment.NewLine}It's multiple lines.")); Assert.Equal(response.Text, response.ToString()); } @@ -153,7 +153,7 @@ public class AgentRunResponseTests [Fact] public void TextGetConcatenatesAllTextContent() { - AgentRunResponse response = new( + AgentResponse response = new( [ new ChatMessage( ChatRole.Assistant, @@ -174,15 +174,15 @@ public class AgentRunResponseTests [Fact] public void TextGetReturnsEmptyStringWithNoMessages() { - AgentRunResponse response = new(); + AgentResponse response = new(); Assert.Equal(string.Empty, response.Text); } [Fact] - public void ToAgentRunResponseUpdatesProducesUpdates() + public void ToAgentResponseUpdatesProducesUpdates() { - AgentRunResponse response = new(new ChatMessage(new ChatRole("customRole"), "Text") { MessageId = "someMessage" }) + AgentResponse response = new(new ChatMessage(new ChatRole("customRole"), "Text") { MessageId = "someMessage" }) { AgentId = "agentId", ResponseId = "12345", @@ -194,11 +194,11 @@ public class AgentRunResponseTests }, }; - AgentRunResponseUpdate[] updates = response.ToAgentRunResponseUpdates(); + AgentResponseUpdate[] updates = response.ToAgentResponseUpdates(); Assert.NotNull(updates); Assert.Equal(2, updates.Length); - AgentRunResponseUpdate update0 = updates[0]; + AgentResponseUpdate update0 = updates[0]; Assert.Equal("agentId", update0.AgentId); Assert.Equal("12345", update0.ResponseId); Assert.Equal("someMessage", update0.MessageId); @@ -206,7 +206,7 @@ public class AgentRunResponseTests Assert.Equal("customRole", update0.Role?.Value); Assert.Equal("Text", update0.Text); - AgentRunResponseUpdate update1 = updates[1]; + AgentResponseUpdate update1 = updates[1]; Assert.Equal("value1", update1.AdditionalProperties?["key1"]); Assert.Equal(42, update1.AdditionalProperties?["key2"]); Assert.IsType(update1.Contents[0]); @@ -225,7 +225,7 @@ public class AgentRunResponseTests { // Arrange. var expectedResult = new Animal { Id = 1, FullName = "Tigger", Species = Species.Tiger }; - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); // Act. var animal = response.Deserialize(); @@ -243,7 +243,7 @@ public class AgentRunResponseTests { // Arrange. var expectedResult = new Animal { Id = 1, FullName = "Tigger", Species = Species.Tiger }; - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); // Act. var animal = response.Deserialize(TestJsonSerializerContext.Default.Options); @@ -259,7 +259,7 @@ public class AgentRunResponseTests public void ParseAsStructuredOutputFailsWithEmptyString() { // Arrange. - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, string.Empty)); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, string.Empty)); // Act & Assert. var exception = Assert.Throws(() => response.Deserialize(TestJsonSerializerContext.Default.Options)); @@ -270,7 +270,7 @@ public class AgentRunResponseTests public void ParseAsStructuredOutputFailsWithInvalidJson() { // Arrange. - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "invalid json")); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, "invalid json")); // Act & Assert. Assert.Throws(() => response.Deserialize(TestJsonSerializerContext.Default.Options)); @@ -280,7 +280,7 @@ public class AgentRunResponseTests public void ParseAsStructuredOutputFailsWithIncorrectTypedJson() { // Arrange. - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "[]")); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, "[]")); // Act & Assert. Assert.Throws(() => response.Deserialize(TestJsonSerializerContext.Default.Options)); @@ -297,7 +297,7 @@ public class AgentRunResponseTests { // Arrange. var expectedResult = new Animal { Id = 1, FullName = "Tigger", Species = Species.Tiger }; - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); // Act. response.TryDeserialize(out Animal? animal); @@ -315,7 +315,7 @@ public class AgentRunResponseTests { // Arrange. var expectedResult = new Animal { Id = 1, FullName = "Tigger", Species = Species.Tiger }; - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, JsonSerializer.Serialize(expectedResult, TestJsonSerializerContext.Default.Animal))); // Act. response.TryDeserialize(TestJsonSerializerContext.Default.Options, out Animal? animal); @@ -331,7 +331,7 @@ public class AgentRunResponseTests public void TryParseAsStructuredOutputFailsWithEmptyText() { // Arrange. - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, string.Empty)); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, string.Empty)); // Act & Assert. Assert.False(response.TryDeserialize(TestJsonSerializerContext.Default.Options, out _)); @@ -341,7 +341,7 @@ public class AgentRunResponseTests public void TryParseAsStructuredOutputFailsWithIncorrectTypedJson() { // Arrange. - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "[]")); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, "[]")); // Act & Assert. Assert.False(response.TryDeserialize(TestJsonSerializerContext.Default.Options, out _)); diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseUpdateExtensionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseUpdateExtensionsTests.cs similarity index 80% rename from dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseUpdateExtensionsTests.cs rename to dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseUpdateExtensionsTests.cs index a653cf80f5..2f136066e4 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseUpdateExtensionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseUpdateExtensionsTests.cs @@ -9,9 +9,9 @@ using Microsoft.Extensions.AI; namespace Microsoft.Agents.AI.Abstractions.UnitTests; -public class AgentRunResponseUpdateExtensionsTests +public class AgentResponseUpdateExtensionsTests { - public static IEnumerable ToAgentRunResponseCoalescesVariousSequenceAndGapLengthsMemberData() + public static IEnumerable ToAgentResponseCoalescesVariousSequenceAndGapLengthsMemberData() { foreach (bool useAsync in new[] { false, true }) { @@ -32,15 +32,15 @@ public class AgentRunResponseUpdateExtensionsTests } [Fact] - public void ToAgentRunResponseWithInvalidArgsThrows() => - Assert.Throws("updates", () => ((List)null!).ToAgentRunResponse()); + public void ToAgentResponseWithInvalidArgsThrows() => + Assert.Throws("updates", () => ((List)null!).ToAgentResponse()); [Theory] [InlineData(false)] [InlineData(true)] - public async Task ToAgentRunResponseSuccessfullyCreatesResponseAsync(bool useAsync) + public async Task ToAgentResponseSuccessfullyCreatesResponseAsync(bool useAsync) { - AgentRunResponseUpdate[] updates = + AgentResponseUpdate[] updates = [ new(ChatRole.Assistant, "Hello") { ResponseId = "someResponse", MessageId = "12345", CreatedAt = new DateTimeOffset(1, 2, 3, 4, 5, 6, TimeSpan.Zero), AgentId = "agentId" }, new(new("human"), ", ") { AuthorName = "Someone", AdditionalProperties = new() { ["a"] = "b" } }, @@ -50,9 +50,9 @@ public class AgentRunResponseUpdateExtensionsTests new() { Contents = [new UsageContent(new() { InputTokenCount = 4, OutputTokenCount = 5 })] }, ]; - AgentRunResponse response = useAsync ? - updates.ToAgentRunResponse() : - await YieldAsync(updates).ToAgentRunResponseAsync(); + AgentResponse response = useAsync ? + updates.ToAgentResponse() : + await YieldAsync(updates).ToAgentResponseAsync(); Assert.NotNull(response); Assert.Equal("agentId", response.AgentId); @@ -90,10 +90,10 @@ public class AgentRunResponseUpdateExtensionsTests } [Theory] - [MemberData(nameof(ToAgentRunResponseCoalescesVariousSequenceAndGapLengthsMemberData))] - public async Task ToAgentRunResponseCoalescesVariousSequenceAndGapLengthsAsync(bool useAsync, int numSequences, int sequenceLength, int gapLength, bool gapBeginningEnd) + [MemberData(nameof(ToAgentResponseCoalescesVariousSequenceAndGapLengthsMemberData))] + public async Task ToAgentResponseCoalescesVariousSequenceAndGapLengthsAsync(bool useAsync, int numSequences, int sequenceLength, int gapLength, bool gapBeginningEnd) { - List updates = []; + List updates = []; List expected = []; @@ -133,7 +133,7 @@ public class AgentRunResponseUpdateExtensionsTests } } - AgentRunResponse response = useAsync ? await YieldAsync(updates).ToAgentRunResponseAsync() : updates.ToAgentRunResponse(); + AgentResponse response = useAsync ? await YieldAsync(updates).ToAgentResponseAsync() : updates.ToAgentResponse(); Assert.NotNull(response); ChatMessage message = response.Messages.Single(); @@ -152,9 +152,9 @@ public class AgentRunResponseUpdateExtensionsTests [Theory] [InlineData(false)] [InlineData(true)] - public async Task ToAgentRunResponseCoalescesTextContentAndTextReasoningContentSeparatelyAsync(bool useAsync) + public async Task ToAgentResponseCoalescesTextContentAndTextReasoningContentSeparatelyAsync(bool useAsync) { - AgentRunResponseUpdate[] updates = + AgentResponseUpdate[] updates = [ new(null, "A"), new(null, "B"), @@ -174,7 +174,7 @@ public class AgentRunResponseUpdateExtensionsTests new() { Contents = [new TextReasoningContent("P")] }, ]; - AgentRunResponse response = useAsync ? await YieldAsync(updates).ToAgentRunResponseAsync() : updates.ToAgentRunResponse(); + AgentResponse response = useAsync ? await YieldAsync(updates).ToAgentResponseAsync() : updates.ToAgentResponse(); ChatMessage message = Assert.Single(response.Messages); Assert.Equal(8, message.Contents.Count); Assert.Equal("ABC", Assert.IsType(message.Contents[0]).Text); @@ -188,16 +188,16 @@ public class AgentRunResponseUpdateExtensionsTests } [Fact] - public async Task ToAgentRunResponseUsesContentExtractedFromContentsAsync() + public async Task ToAgentResponseUsesContentExtractedFromContentsAsync() { - AgentRunResponseUpdate[] updates = + AgentResponseUpdate[] updates = [ new(null, "Hello, "), new(null, "world!"), new() { Contents = [new UsageContent(new() { TotalTokenCount = 42 })] }, ]; - AgentRunResponse response = await YieldAsync(updates).ToAgentRunResponseAsync(); + AgentResponse response = await YieldAsync(updates).ToAgentResponseAsync(); Assert.NotNull(response); @@ -210,14 +210,14 @@ public class AgentRunResponseUpdateExtensionsTests [Theory] [InlineData(false)] [InlineData(true)] - public async Task ToAgentRunResponse_AlternativeTimestampsAsync(bool useAsync) + public async Task ToAgentResponse_AlternativeTimestampsAsync(bool useAsync) { DateTimeOffset early = new(2024, 1, 1, 10, 0, 0, TimeSpan.Zero); DateTimeOffset middle = new(2024, 1, 1, 11, 0, 0, TimeSpan.Zero); DateTimeOffset late = new(2024, 1, 1, 12, 0, 0, TimeSpan.Zero); DateTimeOffset unixEpoch = new(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); - AgentRunResponseUpdate[] updates = + AgentResponseUpdate[] updates = [ // Start with an early timestamp @@ -242,9 +242,9 @@ public class AgentRunResponseUpdateExtensionsTests new(null, "g") { CreatedAt = null }, ]; - AgentRunResponse response = useAsync ? - updates.ToAgentRunResponse() : - await YieldAsync(updates).ToAgentRunResponseAsync(); + AgentResponse response = useAsync ? + updates.ToAgentResponse() : + await YieldAsync(updates).ToAgentResponseAsync(); Assert.Single(response.Messages); Assert.Equal("abcdefg", response.Messages[0].Text); @@ -253,7 +253,7 @@ public class AgentRunResponseUpdateExtensionsTests Assert.Equal(late, response.CreatedAt); } - public static IEnumerable ToAgentRunResponse_TimestampFolding_MemberData() + public static IEnumerable ToAgentResponse_TimestampFolding_MemberData() { // Base test cases var testCases = new (string? timestamp1, string? timestamp2, string? expectedTimestamp)[] @@ -276,22 +276,22 @@ public class AgentRunResponseUpdateExtensionsTests } [Theory] - [MemberData(nameof(ToAgentRunResponse_TimestampFolding_MemberData))] - public async Task ToAgentRunResponse_TimestampFoldingAsync(bool useAsync, string? timestamp1, string? timestamp2, string? expectedTimestamp) + [MemberData(nameof(ToAgentResponse_TimestampFolding_MemberData))] + public async Task ToAgentResponse_TimestampFoldingAsync(bool useAsync, string? timestamp1, string? timestamp2, string? expectedTimestamp) { DateTimeOffset? first = timestamp1 is not null ? DateTimeOffset.Parse(timestamp1) : null; DateTimeOffset? second = timestamp2 is not null ? DateTimeOffset.Parse(timestamp2) : null; DateTimeOffset? expected = expectedTimestamp is not null ? DateTimeOffset.Parse(expectedTimestamp) : null; - AgentRunResponseUpdate[] updates = + AgentResponseUpdate[] updates = [ new(ChatRole.Assistant, "a") { CreatedAt = first }, new(null, "b") { CreatedAt = second }, ]; - AgentRunResponse response = useAsync ? - updates.ToAgentRunResponse() : - await YieldAsync(updates).ToAgentRunResponseAsync(); + AgentResponse response = useAsync ? + updates.ToAgentResponse() : + await YieldAsync(updates).ToAgentResponseAsync(); Assert.Single(response.Messages); Assert.Equal("ab", response.Messages[0].Text); @@ -299,9 +299,9 @@ public class AgentRunResponseUpdateExtensionsTests Assert.Equal(expected, response.CreatedAt); } - private static async IAsyncEnumerable YieldAsync(IEnumerable updates) + private static async IAsyncEnumerable YieldAsync(IEnumerable updates) { - foreach (AgentRunResponseUpdate update in updates) + foreach (AgentResponseUpdate update in updates) { await Task.Yield(); yield return update; diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseUpdateTests.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseUpdateTests.cs similarity index 94% rename from dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseUpdateTests.cs rename to dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseUpdateTests.cs index 32b7acd673..7fda5f680b 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentRunResponseUpdateTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/AgentResponseUpdateTests.cs @@ -7,12 +7,12 @@ using Microsoft.Extensions.AI; namespace Microsoft.Agents.AI.Abstractions.UnitTests; -public class AgentRunResponseUpdateTests +public class AgentResponseUpdateTests { [Fact] public void ConstructorPropsDefaulted() { - AgentRunResponseUpdate update = new(); + AgentResponseUpdate update = new(); Assert.Null(update.AuthorName); Assert.Null(update.Role); Assert.Empty(update.Text); @@ -45,7 +45,7 @@ public class AgentRunResponseUpdateTests ContinuationToken = ResponseContinuationToken.FromBytes(new byte[] { 1, 2, 3 }), }; - AgentRunResponseUpdate response = new(chatResponseUpdate); + AgentResponseUpdate response = new(chatResponseUpdate); Assert.Same(chatResponseUpdate.AdditionalProperties, response.AdditionalProperties); Assert.Equal(chatResponseUpdate.AuthorName, response.AuthorName); Assert.Same(chatResponseUpdate.Contents, response.Contents); @@ -60,7 +60,7 @@ public class AgentRunResponseUpdateTests [Fact] public void PropertiesRoundtrip() { - AgentRunResponseUpdate update = new(); + AgentResponseUpdate update = new(); Assert.Null(update.AuthorName); update.AuthorName = "author"; @@ -114,7 +114,7 @@ public class AgentRunResponseUpdateTests [Fact] public void TextGetUsesAllTextContent() { - AgentRunResponseUpdate update = new() + AgentResponseUpdate update = new() { Role = ChatRole.User, Contents = @@ -142,7 +142,7 @@ public class AgentRunResponseUpdateTests [Fact] public void JsonSerializationRoundtrips() { - AgentRunResponseUpdate original = new() + AgentResponseUpdate original = new() { AuthorName = "author", Role = ChatRole.Assistant, @@ -164,7 +164,7 @@ public class AgentRunResponseUpdateTests string json = JsonSerializer.Serialize(original, AgentAbstractionsJsonUtilities.DefaultOptions); - AgentRunResponseUpdate? result = JsonSerializer.Deserialize(json, AgentAbstractionsJsonUtilities.DefaultOptions); + AgentResponseUpdate? result = JsonSerializer.Deserialize(json, AgentAbstractionsJsonUtilities.DefaultOptions); Assert.NotNull(result); Assert.Equal(5, result.Contents.Count); diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/DelegatingAIAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/DelegatingAIAgentTests.cs index be9522fc0b..8055a95f3a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/DelegatingAIAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/DelegatingAIAgentTests.cs @@ -17,8 +17,8 @@ public class DelegatingAIAgentTests { private readonly Mock _innerAgentMock; private readonly TestDelegatingAIAgent _delegatingAgent; - private readonly AgentRunResponse _testResponse; - private readonly List _testStreamingResponses; + private readonly AgentResponse _testResponse; + private readonly List _testStreamingResponses; private readonly AgentThread _testThread; /// @@ -27,8 +27,8 @@ public class DelegatingAIAgentTests public DelegatingAIAgentTests() { this._innerAgentMock = new Mock(); - this._testResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Test response")); - this._testStreamingResponses = [new AgentRunResponseUpdate(ChatRole.Assistant, "Test streaming response")]; + this._testResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Test response")); + this._testStreamingResponses = [new AgentResponseUpdate(ChatRole.Assistant, "Test streaming response")]; this._testThread = new TestAgentThread(); // Setup inner agent mock @@ -39,7 +39,7 @@ public class DelegatingAIAgentTests this._innerAgentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -48,7 +48,7 @@ public class DelegatingAIAgentTests this._innerAgentMock .Protected() - .Setup>("RunCoreStreamingAsync", + .Setup>("RunCoreStreamingAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -156,13 +156,13 @@ public class DelegatingAIAgentTests var expectedThread = new TestAgentThread(); var expectedOptions = new AgentRunOptions(); var expectedCancellationToken = new CancellationToken(); - var expectedResult = new TaskCompletionSource(); - var expectedResponse = new AgentRunResponse(); + var expectedResult = new TaskCompletionSource(); + var expectedResponse = new AgentResponse(); var innerAgentMock = new Mock(); innerAgentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.Is>(m => m == expectedMessages), ItExpr.Is(t => t == expectedThread), ItExpr.Is(o => o == expectedOptions), @@ -192,7 +192,7 @@ public class DelegatingAIAgentTests var expectedThread = new TestAgentThread(); var expectedOptions = new AgentRunOptions(); var expectedCancellationToken = new CancellationToken(); - AgentRunResponseUpdate[] expectedResults = + AgentResponseUpdate[] expectedResults = [ new(ChatRole.Assistant, "Message 1"), new(ChatRole.Assistant, "Message 2") @@ -201,7 +201,7 @@ public class DelegatingAIAgentTests var innerAgentMock = new Mock(); innerAgentMock .Protected() - .Setup>("RunCoreStreamingAsync", + .Setup>("RunCoreStreamingAsync", ItExpr.Is>(m => m == expectedMessages), ItExpr.Is(t => t == expectedThread), ItExpr.Is(o => o == expectedOptions), diff --git a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/TestJsonSerializerContext.cs b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/TestJsonSerializerContext.cs index ec343504ab..1f6f9bb578 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/TestJsonSerializerContext.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Abstractions.UnitTests/TestJsonSerializerContext.cs @@ -11,8 +11,8 @@ namespace Microsoft.Agents.AI.Abstractions.UnitTests; PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, UseStringEnumConverter = true)] -[JsonSerializable(typeof(AgentRunResponse))] -[JsonSerializable(typeof(AgentRunResponseUpdate))] +[JsonSerializable(typeof(AgentResponse))] +[JsonSerializable(typeof(AgentResponseUpdate))] [JsonSerializable(typeof(AgentRunOptions))] [JsonSerializable(typeof(Animal))] [JsonSerializable(typeof(JsonElement))] diff --git a/dotnet/tests/Microsoft.Agents.AI.Declarative.UnitTests/AggregatorPromptAgentFactoryTests.cs b/dotnet/tests/Microsoft.Agents.AI.Declarative.UnitTests/AggregatorPromptAgentFactoryTests.cs index 2e10935686..54bc8ebfed 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Declarative.UnitTests/AggregatorPromptAgentFactoryTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Declarative.UnitTests/AggregatorPromptAgentFactoryTests.cs @@ -76,12 +76,12 @@ public sealed class AggregatorPromptAgentFactoryTests throw new NotImplementedException(); } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } - protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } diff --git a/dotnet/tests/Microsoft.Agents.AI.DurableTask.IntegrationTests/ExternalClientTests.cs b/dotnet/tests/Microsoft.Agents.AI.DurableTask.IntegrationTests/ExternalClientTests.cs index 9076b6f6e7..6131d56367 100644 --- a/dotnet/tests/Microsoft.Agents.AI.DurableTask.IntegrationTests/ExternalClientTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.DurableTask.IntegrationTests/ExternalClientTests.cs @@ -57,7 +57,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo thread, cancellationToken: this.TestTimeoutToken); - AgentRunResponse response = await simpleAgentProxy.RunAsync( + AgentResponse response = await simpleAgentProxy.RunAsync( message: "Repeat what you just said but say it like a pirate", thread, cancellationToken: this.TestTimeoutToken); @@ -105,7 +105,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo AIAgent tripPlanningAgentProxy = tripPlanningAgent.AsDurableAgentProxy(testHelper.Services); // Act: send a prompt to the agent - AgentRunResponse response = await tripPlanningAgentProxy.RunAsync( + AgentResponse response = await tripPlanningAgentProxy.RunAsync( message: "Help me figure out what to pack for my Seattle trip next Sunday", cancellationToken: this.TestTimeoutToken); @@ -162,7 +162,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo await agent.RunAsync($"My name is {name}.", thread); // 3. Call the agent again with the same thread (ask it to tell me my name) - AgentRunResponse response = await agent.RunAsync("What is my name?", thread); + AgentResponse response = await agent.RunAsync("What is my name?", thread); return response.Text; } @@ -201,7 +201,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo cancellationToken: this.TestTimeoutToken); // Act: prompt it again to wait for the workflow to complete - AgentRunResponse response = await workflowManagerAgentProxy.RunAsync( + AgentResponse response = await workflowManagerAgentProxy.RunAsync( message: "Wait for the workflow to complete and tell me the result.", thread, cancellationToken: this.TestTimeoutToken); diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.A2A.UnitTests/AIAgentExtensionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.A2A.UnitTests/AIAgentExtensionsTests.cs index 10e9bea395..271e80b966 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.A2A.UnitTests/AIAgentExtensionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.A2A.UnitTests/AIAgentExtensionsTests.cs @@ -101,7 +101,7 @@ public sealed class AIAgentExtensionsTests ["responseKey1"] = "responseValue1", ["responseKey2"] = 123 }; - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, "Test response")]) + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, "Test response")]) { AdditionalProperties = additionalProps }; @@ -130,7 +130,7 @@ public sealed class AIAgentExtensionsTests public async Task MapA2A_WhenResponseHasNullAdditionalProperties_ReturnsAgentMessageWithNullMetadataAsync() { // Arrange - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, "Test response")]) + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, "Test response")]) { AdditionalProperties = null }; @@ -154,7 +154,7 @@ public sealed class AIAgentExtensionsTests public async Task MapA2A_WhenResponseHasEmptyAdditionalProperties_ReturnsAgentMessageWithNullMetadataAsync() { // Arrange - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, "Test response")]) + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, "Test response")]) { AdditionalProperties = [] }; @@ -178,26 +178,26 @@ public sealed class AIAgentExtensionsTests agentMock.Setup(x => x.GetNewThreadAsync()).ReturnsAsync(new TestAgentThread()); agentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), ItExpr.IsAny()) .Callback, AgentThread?, AgentRunOptions?, CancellationToken>( (_, _, options, _) => optionsCallback(options)) - .ReturnsAsync(new AgentRunResponse([new ChatMessage(ChatRole.Assistant, "Test response")])); + .ReturnsAsync(new AgentResponse([new ChatMessage(ChatRole.Assistant, "Test response")])); return agentMock; } - private static Mock CreateAgentMockWithResponse(AgentRunResponse response) + private static Mock CreateAgentMockWithResponse(AgentResponse response) { Mock agentMock = new() { CallBase = true }; agentMock.SetupGet(x => x.Name).Returns("TestAgent"); agentMock.Setup(x => x.GetNewThreadAsync()).ReturnsAsync(new TestAgentThread()); agentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/BasicStreamingTests.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/BasicStreamingTests.cs index 26b578d305..950861ce42 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/BasicStreamingTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/BasicStreamingTests.cs @@ -34,10 +34,10 @@ public sealed class BasicStreamingTests : IAsyncDisposable ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "hello"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -49,7 +49,7 @@ public sealed class BasicStreamingTests : IAsyncDisposable updates.Should().AllSatisfy(u => u.Role.Should().Be(ChatRole.Assistant)); // Verify assistant response message - AgentRunResponse response = updates.ToAgentRunResponse(); + AgentResponse response = updates.ToAgentResponse(); response.Messages.Should().HaveCount(1); response.Messages[0].Role.Should().Be(ChatRole.Assistant); response.Messages[0].Text.Should().Be("Hello from fake agent!"); @@ -65,10 +65,10 @@ public sealed class BasicStreamingTests : IAsyncDisposable ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "test"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -86,14 +86,14 @@ public sealed class BasicStreamingTests : IAsyncDisposable updates.Should().Contain(u => !string.IsNullOrEmpty(u.Text)); // All text content updates should have the same message ID - List textUpdates = updates.Where(u => !string.IsNullOrEmpty(u.Text)).ToList(); + List textUpdates = updates.Where(u => !string.IsNullOrEmpty(u.Text)).ToList(); textUpdates.Should().NotBeEmpty(); string? firstMessageId = textUpdates.FirstOrDefault()?.MessageId; firstMessageId.Should().NotBeNullOrEmpty(); textUpdates.Should().AllSatisfy(u => u.MessageId.Should().Be(firstMessageId)); // RunFinished should be the last update - AgentRunResponseUpdate lastUpdate = updates[^1]; + AgentResponseUpdate lastUpdate = updates[^1]; lastUpdate.ResponseId.Should().Be(runId); ChatResponseUpdate lastChatUpdate = lastUpdate.AsChatResponseUpdate(); lastChatUpdate.ConversationId.Should().Be(threadId); @@ -110,7 +110,7 @@ public sealed class BasicStreamingTests : IAsyncDisposable ChatMessage userMessage = new(ChatRole.User, "hello"); // Act - AgentRunResponse response = await agent.RunAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None); + AgentResponse response = await agent.RunAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None); // Assert response.Messages.Should().NotBeEmpty(); @@ -129,8 +129,8 @@ public sealed class BasicStreamingTests : IAsyncDisposable ChatMessage firstUserMessage = new(ChatRole.User, "First question"); // Act - First turn - List firstTurnUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([firstUserMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None)) + List firstTurnUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([firstUserMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None)) { firstTurnUpdates.Add(update); } @@ -140,8 +140,8 @@ public sealed class BasicStreamingTests : IAsyncDisposable // Act - Second turn with another message ChatMessage secondUserMessage = new(ChatRole.User, "Second question"); - List secondTurnUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([secondUserMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None)) + List secondTurnUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([secondUserMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None)) { secondTurnUpdates.Add(update); } @@ -150,13 +150,13 @@ public sealed class BasicStreamingTests : IAsyncDisposable secondTurnUpdates.Should().Contain(u => !string.IsNullOrEmpty(u.Text)); // Verify first turn assistant response - AgentRunResponse firstResponse = firstTurnUpdates.ToAgentRunResponse(); + AgentResponse firstResponse = firstTurnUpdates.ToAgentResponse(); firstResponse.Messages.Should().HaveCount(1); firstResponse.Messages[0].Role.Should().Be(ChatRole.Assistant); firstResponse.Messages[0].Text.Should().Be("Hello from fake agent!"); // Verify second turn assistant response - AgentRunResponse secondResponse = secondTurnUpdates.ToAgentRunResponse(); + AgentResponse secondResponse = secondTurnUpdates.ToAgentResponse(); secondResponse.Messages.Should().HaveCount(1); secondResponse.Messages[0].Role.Should().Be(ChatRole.Assistant); secondResponse.Messages[0].Text.Should().Be("Hello from fake agent!"); @@ -172,16 +172,16 @@ public sealed class BasicStreamingTests : IAsyncDisposable ChatClientAgentThread chatClientThread = (ChatClientAgentThread)await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Tell me a story"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } // Assert - Should have received text updates with different message IDs - List textUpdates = updates.Where(u => !string.IsNullOrEmpty(u.Text)).ToList(); + List textUpdates = updates.Where(u => !string.IsNullOrEmpty(u.Text)).ToList(); textUpdates.Should().NotBeEmpty(); // Extract unique message IDs @@ -189,7 +189,7 @@ public sealed class BasicStreamingTests : IAsyncDisposable messageIds.Should().HaveCountGreaterThan(1, "agent should send multiple messages"); // Verify assistant messages from updates - AgentRunResponse response = updates.ToAgentRunResponse(); + AgentResponse response = updates.ToAgentResponse(); response.Messages.Should().HaveCountGreaterThan(1); response.Messages.Should().AllSatisfy(m => m.Role.Should().Be(ChatRole.Assistant)); } @@ -211,10 +211,10 @@ public sealed class BasicStreamingTests : IAsyncDisposable new ChatMessage(ChatRole.User, "Third part of question") ]; - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(userMessages, chatClientThread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(userMessages, chatClientThread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -224,7 +224,7 @@ public sealed class BasicStreamingTests : IAsyncDisposable updates.Should().Contain(u => u.Role == ChatRole.Assistant); // Verify assistant response message - AgentRunResponse response = updates.ToAgentRunResponse(); + AgentResponse response = updates.ToAgentResponse(); response.Messages.Should().HaveCount(1); response.Messages[0].Role.Should().Be(ChatRole.Assistant); response.Messages[0].Text.Should().Be("Hello from fake agent!"); @@ -286,22 +286,22 @@ internal sealed class FakeChatClientAgent : AIAgent public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions)); - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - List updates = []; - await foreach (AgentRunResponseUpdate update in this.RunStreamingAsync(messages, thread, options, cancellationToken).ConfigureAwait(false)) + List updates = []; + await foreach (AgentResponseUpdate update in this.RunStreamingAsync(messages, thread, options, cancellationToken).ConfigureAwait(false)) { updates.Add(update); } - return updates.ToAgentRunResponse(); + return updates.ToAgentResponse(); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -312,7 +312,7 @@ internal sealed class FakeChatClientAgent : AIAgent // Simulate streaming a deterministic response foreach (string chunk in new[] { "Hello", " ", "from", " ", "fake", " ", "agent", "!" }) { - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = messageId, Role = ChatRole.Assistant, @@ -350,22 +350,22 @@ internal sealed class FakeMultiMessageAgent : AIAgent public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions)); - protected override async Task RunCoreAsync( + protected override async Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - List updates = []; - await foreach (AgentRunResponseUpdate update in this.RunStreamingAsync(messages, thread, options, cancellationToken).ConfigureAwait(false)) + List updates = []; + await foreach (AgentResponseUpdate update in this.RunStreamingAsync(messages, thread, options, cancellationToken).ConfigureAwait(false)) { updates.Add(update); } - return updates.ToAgentRunResponse(); + return updates.ToAgentResponse(); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -375,7 +375,7 @@ internal sealed class FakeMultiMessageAgent : AIAgent string messageId1 = Guid.NewGuid().ToString("N"); foreach (string chunk in new[] { "First", " ", "message" }) { - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = messageId1, Role = ChatRole.Assistant, @@ -389,7 +389,7 @@ internal sealed class FakeMultiMessageAgent : AIAgent string messageId2 = Guid.NewGuid().ToString("N"); foreach (string chunk in new[] { "Second", " ", "message" }) { - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = messageId2, Role = ChatRole.Assistant, @@ -403,7 +403,7 @@ internal sealed class FakeMultiMessageAgent : AIAgent string messageId3 = Guid.NewGuid().ToString("N"); foreach (string chunk in new[] { "Third", " ", "message" }) { - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = messageId3, Role = ChatRole.Assistant, diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ForwardedPropertiesTests.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ForwardedPropertiesTests.cs index 5bd6c8b2c5..2009fdb91b 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ForwardedPropertiesTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ForwardedPropertiesTests.cs @@ -303,12 +303,12 @@ internal sealed class FakeForwardedPropsAgent : AIAgent public JsonElement ReceivedForwardedProperties { get; private set; } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentRunResponseAsync(cancellationToken); + return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -324,7 +324,7 @@ internal sealed class FakeForwardedPropsAgent : AIAgent // Always return a text response string messageId = Guid.NewGuid().ToString("N"); - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = messageId, Role = ChatRole.Assistant, diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/SharedStateTests.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/SharedStateTests.cs index 2bcc264d74..1e8e613b31 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/SharedStateTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/SharedStateTests.cs @@ -42,10 +42,10 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage stateMessage = new(ChatRole.System, [stateContent]); ChatMessage userMessage = new(ChatRole.User, "update state"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -54,7 +54,7 @@ public sealed class SharedStateTests : IAsyncDisposable updates.Should().NotBeEmpty(); // Should receive state snapshot as DataContent with application/json media type - AgentRunResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); + AgentResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); stateUpdate.Should().NotBeNull("should receive state snapshot update"); DataContent? dataContent = stateUpdate!.Contents.OfType().FirstOrDefault(dc => dc.MediaType == "application/json"); @@ -85,16 +85,16 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage stateMessage = new(ChatRole.System, [stateContent]); ChatMessage userMessage = new(ChatRole.User, "process"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } // Assert - AgentRunResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); + AgentResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); stateUpdate.Should().NotBeNull(); ChatResponseUpdate chatUpdate = stateUpdate!.AsChatResponseUpdate(); @@ -127,16 +127,16 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage stateMessage = new(ChatRole.System, [stateContent]); ChatMessage userMessage = new(ChatRole.User, "process complex state"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } // Assert - AgentRunResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); + AgentResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); stateUpdate.Should().NotBeNull(); DataContent? dataContent = stateUpdate!.Contents.OfType().FirstOrDefault(dc => dc.MediaType == "application/json"); @@ -167,16 +167,16 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage stateMessage = new(ChatRole.System, [stateContent]); ChatMessage userMessage = new(ChatRole.User, "increment"); - List firstRoundUpdates = []; + List firstRoundUpdates = []; // Act - First round - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) { firstRoundUpdates.Add(update); } // Extract state snapshot from first round - AgentRunResponseUpdate? firstStateUpdate = firstRoundUpdates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); + AgentResponseUpdate? firstStateUpdate = firstRoundUpdates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); firstStateUpdate.Should().NotBeNull(); DataContent? firstStateContent = firstStateUpdate!.Contents.OfType().FirstOrDefault(dc => dc.MediaType == "application/json"); @@ -184,14 +184,14 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage secondStateMessage = new(ChatRole.System, [firstStateContent!]); ChatMessage secondUserMessage = new(ChatRole.User, "increment again"); - List secondRoundUpdates = []; - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([secondUserMessage, secondStateMessage], thread, new AgentRunOptions(), CancellationToken.None)) + List secondRoundUpdates = []; + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([secondUserMessage, secondStateMessage], thread, new AgentRunOptions(), CancellationToken.None)) { secondRoundUpdates.Add(update); } // Assert - Second round should have incremented counter again - AgentRunResponseUpdate? secondStateUpdate = secondRoundUpdates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); + AgentResponseUpdate? secondStateUpdate = secondRoundUpdates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json")); secondStateUpdate.Should().NotBeNull(); DataContent? secondStateContent = secondStateUpdate!.Contents.OfType().FirstOrDefault(dc => dc.MediaType == "application/json"); @@ -214,10 +214,10 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage userMessage = new(ChatRole.User, "hello"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -251,10 +251,10 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage stateMessage = new(ChatRole.System, [stateContent]); ChatMessage userMessage = new(ChatRole.User, "hello"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -289,7 +289,7 @@ public sealed class SharedStateTests : IAsyncDisposable ChatMessage userMessage = new(ChatRole.User, "process"); // Act - AgentRunResponse response = await agent.RunAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None); + AgentResponse response = await agent.RunAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None); // Assert response.Should().NotBeNull(); @@ -342,12 +342,12 @@ internal sealed class FakeStateAgent : AIAgent { public override string? Description => "Agent for state testing"; - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentRunResponseAsync(cancellationToken); + return this.RunCoreStreamingAsync(messages, thread, options, cancellationToken).ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -396,7 +396,7 @@ internal sealed class FakeStateAgent : AIAgent byte[] modifiedStateBytes = System.Text.Encoding.UTF8.GetBytes(modifiedStateJson); DataContent modifiedStateContent = new(modifiedStateBytes, "application/json"); - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = Guid.NewGuid().ToString("N"), Role = ChatRole.Assistant, @@ -407,7 +407,7 @@ internal sealed class FakeStateAgent : AIAgent // Always return a text response string messageId = Guid.NewGuid().ToString("N"); - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { MessageId = messageId, Role = ChatRole.Assistant, diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ToolCallingTests.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ToolCallingTests.cs index 4e51fadf94..e744e52d34 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ToolCallingTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/ToolCallingTests.cs @@ -48,10 +48,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Call the server function"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -96,10 +96,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "What's the weather and time?"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -137,10 +137,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Call the client function"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -185,10 +185,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Calculate 5 + 3 and format 'hello'"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -236,10 +236,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Get both server and client data"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); this._output.WriteLine($"Update: {update.Contents.Count} contents"); @@ -301,10 +301,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Call the test function"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -345,10 +345,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Call both functions in parallel"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -431,10 +431,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Get server forecast for Seattle for 5 days"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } @@ -477,10 +477,10 @@ public sealed class ToolCallingTests : IAsyncDisposable AgentThread thread = await agent.GetNewThreadAsync(); ChatMessage userMessage = new(ChatRole.User, "Get client forecast for Portland with hourly data"); - List updates = []; + List updates = []; // Act - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None)) { updates.Add(update); } diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.UnitTests/AGUIEndpointRouteBuilderExtensionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.UnitTests/AGUIEndpointRouteBuilderExtensionsTests.cs index e84876e719..a98d76d065 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.UnitTests/AGUIEndpointRouteBuilderExtensionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.UnitTests/AGUIEndpointRouteBuilderExtensionsTests.cs @@ -431,21 +431,21 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions)); - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) { await Task.CompletedTask; - yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, "First")); - yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, " part")); - yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, " of response")); + yield return new AgentResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, "First")); + yield return new AgentResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, " part")); + yield return new AgentResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, " of response")); } } @@ -521,19 +521,19 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions)); - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) { await Task.CompletedTask; - yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, "Test response")); + yield return new AgentResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, "Test response")); } } } diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests/SamplesValidation.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests/SamplesValidation.cs index c80cd73941..0dccceaa1a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests/SamplesValidation.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests/SamplesValidation.cs @@ -286,7 +286,7 @@ public sealed class SamplesValidation(ITestOutputHelper outputHelper) : IAsyncLi string startResponseText = await startResponse.Content.ReadAsStringAsync(); this._outputHelper.WriteLine($"Agent response: {startResponseText}"); - // The response should be deserializable as an AgentRunResponse object and have a valid thread ID + // The response should be deserializable as an AgentResponse object and have a valid thread ID startResponse.Headers.TryGetValues("x-ms-thread-id", out IEnumerable? agentIdValues); string? threadId = agentIdValues?.FirstOrDefault(); Assert.NotNull(threadId); diff --git a/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.UnitTests/TestAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.UnitTests/TestAgent.cs index ed6f4aa132..2f8faa320a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.UnitTests/TestAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.UnitTests/TestAgent.cs @@ -17,13 +17,13 @@ internal sealed class TestAgent(string name, string description) : AIAgent JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new DummyAgentThread()); - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, - CancellationToken cancellationToken = default) => Task.FromResult(new AgentRunResponse([.. messages])); + CancellationToken cancellationToken = default) => Task.FromResult(new AgentResponse([.. messages])); - protected override IAsyncEnumerable RunCoreStreamingAsync( + protected override IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, diff --git a/dotnet/tests/Microsoft.Agents.AI.OpenAI.UnitTests/Extensions/AIAgentWithOpenAIExtensionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.OpenAI.UnitTests/Extensions/AIAgentWithOpenAIExtensionsTests.cs index 60c37c9b82..d29535eddb 100644 --- a/dotnet/tests/Microsoft.Agents.AI.OpenAI.UnitTests/Extensions/AIAgentWithOpenAIExtensionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.OpenAI.UnitTests/Extensions/AIAgentWithOpenAIExtensionsTests.cs @@ -78,12 +78,12 @@ public sealed class AIAgentWithOpenAIExtensionsTests mockAgent .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), ItExpr.IsAny()) - .ReturnsAsync(new AgentRunResponse([responseMessage])); + .ReturnsAsync(new AgentResponse([responseMessage])); // Act var result = await mockAgent.Object.RunAsync(openAiMessages, mockThread.Object, options, cancellationToken); @@ -160,7 +160,7 @@ public sealed class AIAgentWithOpenAIExtensionsTests OpenAIChatMessage.CreateUserMessage(TestMessageText) }; - var responseUpdates = new List + var responseUpdates = new List { new(ChatRole.Assistant, ResponseText1), new(ChatRole.Assistant, ResponseText2) @@ -168,7 +168,7 @@ public sealed class AIAgentWithOpenAIExtensionsTests mockAgent .Protected() - .Setup>("RunCoreStreamingAsync", + .Setup>("RunCoreStreamingAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -199,9 +199,9 @@ public sealed class AIAgentWithOpenAIExtensionsTests } /// - /// Helper method to convert a list of AgentRunResponseUpdate to an async enumerable. + /// Helper method to convert a list of AgentResponseUpdate to an async enumerable. /// - private static async IAsyncEnumerable ToAsyncEnumerableAsync(IEnumerable updates) + private static async IAsyncEnumerable ToAsyncEnumerableAsync(IEnumerable updates) { foreach (var update in updates) { diff --git a/dotnet/tests/Microsoft.Agents.AI.Purview.UnitTests/PurviewWrapperTests.cs b/dotnet/tests/Microsoft.Agents.AI.Purview.UnitTests/PurviewWrapperTests.cs index eafc67f7fc..ed012669d6 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Purview.UnitTests/PurviewWrapperTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Purview.UnitTests/PurviewWrapperTests.cs @@ -296,10 +296,10 @@ public sealed class PurviewWrapperTests : IDisposable new(ChatRole.User, "Test message") }; var mockAgent = new Mock(); - var innerResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Sensitive response")); + var innerResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Sensitive response")); mockAgent.Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -335,10 +335,10 @@ public sealed class PurviewWrapperTests : IDisposable new(ChatRole.User, "Test message") }; var mockAgent = new Mock(); - var innerResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Safe response")); + var innerResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Safe response")); mockAgent.Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -378,10 +378,10 @@ public sealed class PurviewWrapperTests : IDisposable new(ChatRole.User, "Test message") }; - var expectedResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Response from inner agent")); + var expectedResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Response from inner agent")); var mockAgent = new Mock(); mockAgent.Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -445,10 +445,10 @@ public sealed class PurviewWrapperTests : IDisposable } }; - var expectedResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Response")); + var expectedResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Response")); var mockAgent = new Mock(); mockAgent.Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -487,10 +487,10 @@ public sealed class PurviewWrapperTests : IDisposable new(ChatRole.User, "Test message") }; - var expectedResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Response")); + var expectedResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Response")); var mockAgent = new Mock(); mockAgent.Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -527,10 +527,10 @@ public sealed class PurviewWrapperTests : IDisposable new(ChatRole.User, "Test message") }; var mockAgent = new Mock(); - var innerResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Response")); + var innerResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Response")); mockAgent.Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AIAgentBuilderTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AIAgentBuilderTests.cs index 7f455327dc..48b2475a2b 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AIAgentBuilderTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AIAgentBuilderTests.cs @@ -376,7 +376,7 @@ public class AIAgentBuilderTests var builder = new AIAgentBuilder(mockAgent.Object); // Act - var result = builder.Use((_, _, _, _, _) => Task.FromResult(new AgentRunResponse()), null).Build(); + var result = builder.Use((_, _, _, _, _) => Task.FromResult(new AgentResponse()), null).Build(); // Assert Assert.IsType(result); @@ -393,7 +393,7 @@ public class AIAgentBuilderTests var builder = new AIAgentBuilder(mockAgent.Object); // Act - var result = builder.Use(null, (_, _, _, _, _) => AsyncEnumerable.Empty()).Build(); + var result = builder.Use(null, (_, _, _, _, _) => AsyncEnumerable.Empty()).Build(); // Assert Assert.IsType(result); @@ -411,8 +411,8 @@ public class AIAgentBuilderTests // Act var result = builder.Use( - (_, _, _, _, _) => Task.FromResult(new AgentRunResponse()), - (_, _, _, _, _) => AsyncEnumerable.Empty()).Build(); + (_, _, _, _, _) => Task.FromResult(new AgentResponse()), + (_, _, _, _, _) => AsyncEnumerable.Empty()).Build(); // Assert Assert.IsType(result); diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentExtensionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentExtensionsTests.cs index 33d08351b9..43039a7b76 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentExtensionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentExtensionsTests.cs @@ -121,7 +121,7 @@ public class AgentExtensionsTests public async Task CreateFromAgent_WhenFunctionInvokedAsync_CallsAgentRunAsync() { // Arrange - var expectedResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Test response")); + var expectedResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Test response")); var testAgent = new TestAgent("TestAgent", "Test description", expectedResponse); var aiFunction = testAgent.AsAIFunction(); @@ -139,7 +139,7 @@ public class AgentExtensionsTests public async Task CreateFromAgent_WhenFunctionInvokedWithCancellationTokenAsync_PassesCancellationTokenAsync() { // Arrange - var expectedResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Test response")); + var expectedResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Test response")); var testAgent = new TestAgent("TestAgent", "Test description", expectedResponse); using var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; @@ -257,7 +257,7 @@ public class AgentExtensionsTests public async Task CreateFromAgent_InvokeWithComplexResponseFromAgentAsync_ReturnsCorrectResponseAsync() { // Arrange - var expectedResponse = new AgentRunResponse + var expectedResponse = new AgentResponse { AgentId = "agent-123", ResponseId = "response-456", @@ -307,10 +307,10 @@ public class AgentExtensionsTests /// private sealed class TestAgent : AIAgent { - private readonly AgentRunResponse? _responseToReturn; + private readonly AgentResponse? _responseToReturn; private readonly Exception? _exceptionToThrow; - public TestAgent(string? name, string? description, AgentRunResponse responseToReturn) + public TestAgent(string? name, string? description, AgentResponse responseToReturn) { this.Name = name; this.Description = description; @@ -337,7 +337,7 @@ public class AgentExtensionsTests public CancellationToken LastCancellationToken { get; private set; } public int RunAsyncCallCount { get; private set; } - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -355,14 +355,14 @@ public class AgentExtensionsTests return Task.FromResult(this._responseToReturn!); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { var response = await this.RunAsync(messages, thread, options, cancellationToken); - foreach (var update in response.ToAgentRunResponseUpdates()) + foreach (var update in response.ToAgentResponseUpdates()) { yield return update; } diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentJsonUtilitiesTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentJsonUtilitiesTests.cs index 65815607d9..c9cd1e827e 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentJsonUtilitiesTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AgentJsonUtilitiesTests.cs @@ -79,9 +79,9 @@ public class AgentJsonUtilitiesTests #endif [Fact] - public void DefaultOptions_UsesCamelCasePropertyNames_ForAgentRunResponse() + public void DefaultOptions_UsesCamelCasePropertyNames_ForAgentResponse() { - var response = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Hello")); + var response = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Hello")); string json = JsonSerializer.Serialize(response, AgentJsonUtilities.DefaultOptions); Assert.Contains("\"messages\"", json); Assert.DoesNotContain("\"Messages\"", json); diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AnonymousDelegatingAIAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AnonymousDelegatingAIAgentTests.cs index 4e91fc1430..43937a1148 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/AnonymousDelegatingAIAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/AnonymousDelegatingAIAgentTests.cs @@ -21,8 +21,8 @@ public class AnonymousDelegatingAIAgentTests private readonly List _testMessages; private readonly AgentThread _testThread; private readonly AgentRunOptions _testOptions; - private readonly AgentRunResponse _testResponse; - private readonly AgentRunResponseUpdate[] _testStreamingResponses; + private readonly AgentResponse _testResponse; + private readonly AgentResponseUpdate[] _testStreamingResponses; public AnonymousDelegatingAIAgentTests() { @@ -30,15 +30,15 @@ public class AnonymousDelegatingAIAgentTests this._testMessages = [new ChatMessage(ChatRole.User, "Test message")]; this._testThread = new Mock().Object; this._testOptions = new AgentRunOptions(); - this._testResponse = new AgentRunResponse([new ChatMessage(ChatRole.Assistant, "Test response")]); + this._testResponse = new AgentResponse([new ChatMessage(ChatRole.Assistant, "Test response")]); this._testStreamingResponses = [ - new AgentRunResponseUpdate(ChatRole.Assistant, "Response 1"), - new AgentRunResponseUpdate(ChatRole.Assistant, "Response 2") + new AgentResponseUpdate(ChatRole.Assistant, "Response 1"), + new AgentResponseUpdate(ChatRole.Assistant, "Response 2") ]; this._innerAgentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -47,7 +47,7 @@ public class AnonymousDelegatingAIAgentTests this._innerAgentMock .Protected() - .Setup>("RunCoreStreamingAsync", + .Setup>("RunCoreStreamingAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -191,7 +191,7 @@ public class AnonymousDelegatingAIAgentTests this._innerAgentMock .Protected() - .Verify>("RunCoreAsync", + .Verify>("RunCoreAsync", Times.Once(), ItExpr.Is>(m => m == this._testMessages), ItExpr.Is(t => t == this._testThread), @@ -441,7 +441,7 @@ public class AnonymousDelegatingAIAgentTests var exception = await Assert.ThrowsAsync( () => agent.RunAsync(this._testMessages, this._testThread, this._testOptions)); - Assert.Contains("without producing an AgentRunResponse", exception.Message); + Assert.Contains("without producing an AgentResponse", exception.Message); } #endregion @@ -468,7 +468,7 @@ public class AnonymousDelegatingAIAgentTests this._innerAgentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -740,7 +740,7 @@ public class AnonymousDelegatingAIAgentTests var runExecutionOrder = new List(); var streamingExecutionOrder = new List(); - static async IAsyncEnumerable FirstStreamingMiddlewareAsync( + static async IAsyncEnumerable FirstStreamingMiddlewareAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, [EnumeratorCancellation] CancellationToken cancellationToken, List executionOrder) @@ -753,7 +753,7 @@ public class AnonymousDelegatingAIAgentTests executionOrder.Add("First-Streaming-Post"); } - static async IAsyncEnumerable SecondStreamingMiddlewareAsync( + static async IAsyncEnumerable SecondStreamingMiddlewareAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, [EnumeratorCancellation] CancellationToken cancellationToken, List executionOrder) @@ -891,7 +891,7 @@ public class AnonymousDelegatingAIAgentTests { // Arrange var executionOrder = new List(); - var fallbackResponse = new AgentRunResponse([new ChatMessage(ChatRole.Assistant, "Fallback response")]); + var fallbackResponse = new AgentResponse([new ChatMessage(ChatRole.Assistant, "Fallback response")]); var agent = new AIAgentBuilder(this._innerAgentMock.Object) .Use( @@ -938,7 +938,7 @@ public class AnonymousDelegatingAIAgentTests // Setup mock to throw OperationCanceledException when cancelled token is used this._innerAgentMock .Protected() - .Setup>("RunCoreAsync", + .Setup>("RunCoreAsync", ItExpr.IsAny>(), ItExpr.IsAny(), ItExpr.IsAny(), @@ -973,7 +973,7 @@ public class AnonymousDelegatingAIAgentTests public async Task AIAgentBuilder_Use_MiddlewareShortCircuits_InnerAgentNotCalledAsync() { // Arrange - var shortCircuitResponse = new AgentRunResponse([new ChatMessage(ChatRole.Assistant, "Short-circuited")]); + var shortCircuitResponse = new AgentResponse([new ChatMessage(ChatRole.Assistant, "Short-circuited")]); var executionOrder = new List(); var agent = new AIAgentBuilder(this._innerAgentMock.Object) @@ -1007,7 +1007,7 @@ public class AnonymousDelegatingAIAgentTests // Verify inner agent was never called this._innerAgentMock .Protected() - .Verify>("RunCoreAsync", + .Verify>("RunCoreAsync", Times.Never(), ItExpr.IsAny>(), ItExpr.IsAny(), diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentRunOptionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentRunOptionsTests.cs index 9dd1fce4fb..1aa49dc328 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentRunOptionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentRunOptionsTests.cs @@ -143,7 +143,7 @@ public class ChatClientAgentRunOptionsTests var options = new ChatClientAgentRunOptions { ChatClientFactory = ClientFactory }; // Act - var responseUpdates = new List(); + var responseUpdates = new List(); await foreach (var update in agent.RunStreamingAsync(messages, null, options, CancellationToken.None)) { responseUpdates.Add(update); @@ -215,7 +215,7 @@ public class ChatClientAgentRunOptionsTests var messages = new List { new(ChatRole.User, "Test message") }; // Act - No ChatClientFactory provided - var responseUpdates = new List(); + var responseUpdates = new List(); await foreach (var update in agent.RunStreamingAsync(messages, null, null, CancellationToken.None)) { responseUpdates.Add(update); diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentTests.cs index 18d20e3e76..ba4e836b07 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgentTests.cs @@ -801,15 +801,15 @@ public partial class ChatClientAgentTests ChatClientAgent agent = new(mockService.Object, options: new()); // Act - AgentRunResponse agentRunResponse = await agent.RunAsync(messages: [new(ChatRole.User, "Hello")], serializerOptions: JsonContext2.Default.Options); + AgentResponse agentResponse = await agent.RunAsync(messages: [new(ChatRole.User, "Hello")], serializerOptions: JsonContext2.Default.Options); // Assert - Assert.Single(agentRunResponse.Messages); + Assert.Single(agentResponse.Messages); - Assert.NotNull(agentRunResponse.Result); - Assert.Equal(expectedSO.Id, agentRunResponse.Result.Id); - Assert.Equal(expectedSO.FullName, agentRunResponse.Result.FullName); - Assert.Equal(expectedSO.Species, agentRunResponse.Result.Species); + Assert.NotNull(agentResponse.Result); + Assert.Equal(expectedSO.Id, agentResponse.Result.Id); + Assert.Equal(expectedSO.FullName, agentResponse.Result.FullName); + Assert.Equal(expectedSO.Species, agentResponse.Result.Species); } #endregion @@ -1972,7 +1972,7 @@ public partial class ChatClientAgentTests // Act var updates = agent.RunStreamingAsync([new ChatMessage(ChatRole.User, "Hello")]); - List result = []; + List result = []; await foreach (var update in updates) { result.Add(update); @@ -2116,7 +2116,7 @@ public partial class ChatClientAgentTests // Act var thread = await agent.GetNewThreadAsync() as ChatClientAgentThread; var updates = agent.RunStreamingAsync(requestMessages, thread); - _ = await updates.ToAgentRunResponseAsync(); + _ = await updates.ToAgentResponseAsync(); // Assert // Should contain: base instructions, user message, context message, base function, context function @@ -2186,7 +2186,7 @@ public partial class ChatClientAgentTests await Assert.ThrowsAsync(async () => { var updates = agent.RunStreamingAsync(requestMessages); - await updates.ToAgentRunResponseAsync(); + await updates.ToAgentResponseAsync(); }); // Assert diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs index cfccb7267a..79af3add1d 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs @@ -264,7 +264,7 @@ public class ChatClientAgent_BackgroundResponsesTests ChatClientAgentThread thread = new(); // Act - var actualUpdates = new List(); + var actualUpdates = new List(); await foreach (var u in agent.RunStreamingAsync([new(ChatRole.User, "hi")], thread, options: new ChatClientAgentRunOptions(new ChatOptions { AllowBackgroundResponses = true }))) { actualUpdates.Add(u); @@ -543,7 +543,7 @@ public class ChatClientAgent_BackgroundResponsesTests }; // Act - var updates = new List(); + var updates = new List(); await foreach (var update in agent.RunStreamingAsync(thread, options: runOptions)) { updates.Add(update); @@ -591,7 +591,7 @@ public class ChatClientAgent_BackgroundResponsesTests }; // Act - var updates = new List(); + var updates = new List(); await foreach (var update in agent.RunStreamingAsync(thread, options: runOptions)) { updates.Add(update); diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_RunWithCustomOptionsTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_RunWithCustomOptionsTests.cs index ee84928ba5..4c85bcbb51 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_RunWithCustomOptionsTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_RunWithCustomOptionsTests.cs @@ -34,7 +34,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse result = await agent.RunAsync(thread, options); + AgentResponse result = await agent.RunAsync(thread, options); // Assert Assert.NotNull(result); @@ -63,7 +63,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse result = await agent.RunAsync("Test message", thread, options); + AgentResponse result = await agent.RunAsync("Test message", thread, options); // Assert Assert.NotNull(result); @@ -93,7 +93,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse result = await agent.RunAsync(message, thread, options); + AgentResponse result = await agent.RunAsync(message, thread, options); // Assert Assert.NotNull(result); @@ -123,7 +123,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse result = await agent.RunAsync(messages, thread, options); + AgentResponse result = await agent.RunAsync(messages, thread, options); // Assert Assert.NotNull(result); @@ -151,7 +151,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(new ChatOptions { Temperature = 0.5f }); // Act - AgentRunResponse result = await agent.RunAsync("Test", null, options); + AgentResponse result = await agent.RunAsync("Test", null, options); // Assert Assert.NotNull(result); @@ -183,7 +183,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in agent.RunStreamingAsync(thread, options)) { updates.Add(update); @@ -215,7 +215,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in agent.RunStreamingAsync("Test message", thread, options)) { updates.Add(update); @@ -248,7 +248,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in agent.RunStreamingAsync(message, thread, options)) { updates.Add(update); @@ -281,7 +281,7 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - var updates = new List(); + var updates = new List(); await foreach (var update in agent.RunStreamingAsync(messages, thread, options)) { updates.Add(update); @@ -328,12 +328,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse agentRunResponse = await agent.RunAsync(thread, JsonContext_WithCustomRunOptions.Default.Options, options); + AgentResponse agentResponse = await agent.RunAsync(thread, JsonContext_WithCustomRunOptions.Default.Options, options); // Assert - Assert.NotNull(agentRunResponse); - Assert.Single(agentRunResponse.Messages); - Assert.Equal("Tigger", agentRunResponse.Result.FullName); + Assert.NotNull(agentResponse); + Assert.Single(agentResponse.Messages); + Assert.Equal("Tigger", agentResponse.Result.FullName); mockChatClient.Verify( x => x.GetResponseAsync( It.IsAny>(), @@ -358,12 +358,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse agentRunResponse = await agent.RunAsync("Test message", thread, JsonContext_WithCustomRunOptions.Default.Options, options); + AgentResponse agentResponse = await agent.RunAsync("Test message", thread, JsonContext_WithCustomRunOptions.Default.Options, options); // Assert - Assert.NotNull(agentRunResponse); - Assert.Single(agentRunResponse.Messages); - Assert.Equal("Tigger", agentRunResponse.Result.FullName); + Assert.NotNull(agentResponse); + Assert.Single(agentResponse.Messages); + Assert.Equal("Tigger", agentResponse.Result.FullName); mockChatClient.Verify( x => x.GetResponseAsync( It.Is>(msgs => msgs.Any(m => m.Text == "Test message")), @@ -389,12 +389,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse agentRunResponse = await agent.RunAsync(message, thread, JsonContext_WithCustomRunOptions.Default.Options, options); + AgentResponse agentResponse = await agent.RunAsync(message, thread, JsonContext_WithCustomRunOptions.Default.Options, options); // Assert - Assert.NotNull(agentRunResponse); - Assert.Single(agentRunResponse.Messages); - Assert.Equal("Tigger", agentRunResponse.Result.FullName); + Assert.NotNull(agentResponse); + Assert.Single(agentResponse.Messages); + Assert.Equal("Tigger", agentResponse.Result.FullName); mockChatClient.Verify( x => x.GetResponseAsync( It.Is>(msgs => msgs.Contains(message)), @@ -420,12 +420,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests ChatClientAgentRunOptions options = new(); // Act - AgentRunResponse agentRunResponse = await agent.RunAsync(messages, thread, JsonContext_WithCustomRunOptions.Default.Options, options); + AgentResponse agentResponse = await agent.RunAsync(messages, thread, JsonContext_WithCustomRunOptions.Default.Options, options); // Assert - Assert.NotNull(agentRunResponse); - Assert.Single(agentRunResponse.Messages); - Assert.Equal("Tigger", agentRunResponse.Result.FullName); + Assert.NotNull(agentResponse); + Assert.Single(agentResponse.Messages); + Assert.Equal("Tigger", agentResponse.Result.FullName); mockChatClient.Verify( x => x.GetResponseAsync( It.IsAny>(), diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/FunctionInvocationDelegatingAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/FunctionInvocationDelegatingAgentTests.cs index 5866e610b6..50955234e5 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/FunctionInvocationDelegatingAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/FunctionInvocationDelegatingAgentTests.cs @@ -717,7 +717,7 @@ public sealed class FunctionInvocationDelegatingAgentTests var innerAgent = new ChatClientAgent(mockChatClient.Object); var messages = new List { new(ChatRole.User, "Test message") }; - async Task RunningMiddlewareCallbackAsync(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) + async Task RunningMiddlewareCallbackAsync(IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { executionOrder.Add("Running-Pre"); var result = await innerAgent.RunAsync(messages, thread, options, cancellationToken); @@ -800,7 +800,7 @@ public sealed class FunctionInvocationDelegatingAgentTests // Act var options = new ChatClientAgentRunOptions(new ChatOptions { Tools = [testFunction] }); - var responseUpdates = new List(); + var responseUpdates = new List(); await foreach (var update in middleware.RunStreamingAsync(messages, null, options, CancellationToken.None)) { responseUpdates.Add(update); diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/LoggingAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/LoggingAgentTests.cs index 58e9536491..b5e701cb38 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/LoggingAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/LoggingAgentTests.cs @@ -83,7 +83,7 @@ public class LoggingAgentTests RunAsyncFunc = async (messages, thread, options, cancellationToken) => { await Task.Yield(); - return new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Test response")); + return new AgentResponse(new ChatMessage(ChatRole.Assistant, "Test response")); } }; @@ -126,7 +126,7 @@ public class LoggingAgentTests RunAsyncFunc = async (messages, thread, options, cancellationToken) => { await Task.Yield(); - return new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Test response")); + return new AgentResponse(new ChatMessage(ChatRole.Assistant, "Test response")); } }; @@ -228,11 +228,11 @@ public class LoggingAgentTests RunStreamingAsyncFunc = CallbackAsync }; - static async IAsyncEnumerable CallbackAsync( + static async IAsyncEnumerable CallbackAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Yield(); - yield return new AgentRunResponseUpdate(ChatRole.Assistant, "Test"); + yield return new AgentResponseUpdate(ChatRole.Assistant, "Test"); } var agent = new LoggingAgent(innerAgent, mockLogger.Object); @@ -277,12 +277,12 @@ public class LoggingAgentTests RunStreamingAsyncFunc = CallbackAsync }; - static async IAsyncEnumerable CallbackAsync( + static async IAsyncEnumerable CallbackAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Yield(); - yield return new AgentRunResponseUpdate(ChatRole.Assistant, "Update 1"); - yield return new AgentRunResponseUpdate(ChatRole.Assistant, "Update 2"); + yield return new AgentResponseUpdate(ChatRole.Assistant, "Update 1"); + yield return new AgentResponseUpdate(ChatRole.Assistant, "Update 2"); } var agent = new LoggingAgent(innerAgent, mockLogger.Object); @@ -317,7 +317,7 @@ public class LoggingAgentTests RunStreamingAsyncFunc = CallbackAsync }; - static async IAsyncEnumerable CallbackAsync( + static async IAsyncEnumerable CallbackAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Yield(); @@ -364,7 +364,7 @@ public class LoggingAgentTests RunStreamingAsyncFunc = CallbackAsync }; - static async IAsyncEnumerable CallbackAsync( + static async IAsyncEnumerable CallbackAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Yield(); diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/OpenTelemetryAgentTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/OpenTelemetryAgentTests.cs index 405832763c..84dc1d7a20 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/OpenTelemetryAgentTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/OpenTelemetryAgentTests.cs @@ -82,7 +82,7 @@ public class OpenTelemetryAgentTests RunAsyncFunc = async (messages, thread, options, cancellationToken) => { await Task.Yield(); - return new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "The blue whale, I think.")) + return new AgentResponse(new ChatMessage(ChatRole.Assistant, "The blue whale, I think.")) { ResponseId = "id123", Usage = new UsageDetails @@ -107,7 +107,7 @@ public class OpenTelemetryAgentTests null, }; - async static IAsyncEnumerable CallbackAsync( + async static IAsyncEnumerable CallbackAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Yield(); @@ -115,13 +115,13 @@ public class OpenTelemetryAgentTests foreach (string text in new[] { "The ", "blue ", "whale,", " ", "", "I", " think." }) { await Task.Yield(); - yield return new AgentRunResponseUpdate(ChatRole.Assistant, text) + yield return new AgentResponseUpdate(ChatRole.Assistant, text) { ResponseId = "id123", }; } - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { Contents = [new UsageContent(new() { @@ -307,7 +307,7 @@ public class OpenTelemetryAgentTests RunAsyncFunc = async (messages, thread, options, cancellationToken) => { await Task.Yield(); - return new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "The blue whale, I think.")) + return new AgentResponse(new ChatMessage(ChatRole.Assistant, "The blue whale, I think.")) { ResponseId = "id123", Usage = new UsageDetails @@ -332,7 +332,7 @@ public class OpenTelemetryAgentTests null, }; - async static IAsyncEnumerable CallbackAsync( + async static IAsyncEnumerable CallbackAsync( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { await Task.Yield(); @@ -340,13 +340,13 @@ public class OpenTelemetryAgentTests foreach (string text in new[] { "The ", "blue ", "whale,", " ", "", "I", " think." }) { await Task.Yield(); - yield return new AgentRunResponseUpdate(ChatRole.Assistant, text) + yield return new AgentResponseUpdate(ChatRole.Assistant, text) { ResponseId = "id123", }; } - yield return new AgentRunResponseUpdate + yield return new AgentResponseUpdate { Contents = [new UsageContent(new() { diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/TestAIAgent.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/TestAIAgent.cs index afeb81baa5..473c01bb6b 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/TestAIAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/TestAIAgent.cs @@ -16,8 +16,8 @@ internal sealed class TestAIAgent : AIAgent public Func DeserializeThreadFunc = delegate { throw new NotSupportedException(); }; public Func GetNewThreadFunc = delegate { throw new NotSupportedException(); }; - public Func, AgentThread?, AgentRunOptions?, CancellationToken, Task> RunAsyncFunc = delegate { throw new NotSupportedException(); }; - public Func, AgentThread?, AgentRunOptions?, CancellationToken, IAsyncEnumerable> RunStreamingAsyncFunc = delegate { throw new NotSupportedException(); }; + public Func, AgentThread?, AgentRunOptions?, CancellationToken, Task> RunAsyncFunc = delegate { throw new NotSupportedException(); }; + public Func, AgentThread?, AgentRunOptions?, CancellationToken, IAsyncEnumerable> RunStreamingAsyncFunc = delegate { throw new NotSupportedException(); }; public Func? GetServiceFunc; public override string? Name => this.NameFunc?.Invoke() ?? base.Name; @@ -30,10 +30,10 @@ internal sealed class TestAIAgent : AIAgent public override ValueTask GetNewThreadAsync(CancellationToken cancellationToken = default) => new(this.GetNewThreadFunc()); - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => this.RunAsyncFunc(messages, thread, options, cancellationToken); - protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => this.RunStreamingAsyncFunc(messages, thread, options, cancellationToken); public override object? GetService(Type serviceType, object? serviceKey = null) => diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Events/ExternalInputRequestTest.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Events/ExternalInputRequestTest.cs index 49d06337fe..d1165d84d4 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Events/ExternalInputRequestTest.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Events/ExternalInputRequestTest.cs @@ -15,7 +15,7 @@ public sealed class ExternalInputRequestTest(ITestOutputHelper output) : EventTe public void VerifySerializationWithText() { // Arrange - ExternalInputRequest source = new(new AgentRunResponse(new ChatMessage(ChatRole.User, "Wassup?"))); + ExternalInputRequest source = new(new AgentResponse(new ChatMessage(ChatRole.User, "Wassup?"))); // Act ExternalInputRequest copy = VerifyEventSerialization(source); @@ -30,7 +30,7 @@ public sealed class ExternalInputRequestTest(ITestOutputHelper output) : EventTe { // Arrange ExternalInputRequest source = - new(new AgentRunResponse( + new(new AgentResponse( new ChatMessage( ChatRole.Assistant, [ diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/CancelWorkflow.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/CancelWorkflow.cs index 9cf72036fd..0bf1ce343a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/CancelWorkflow.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/CancelWorkflow.cs @@ -60,7 +60,7 @@ public static class WorkflowProvider NEVER 1! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Condition.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Condition.cs index 68deb1f19e..709dccc81e 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Condition.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Condition.cs @@ -101,7 +101,7 @@ public static class WorkflowProvider ODD """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -122,7 +122,7 @@ public static class WorkflowProvider EVEN """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -143,7 +143,7 @@ public static class WorkflowProvider All done! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/ConditionElse.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/ConditionElse.cs index 47e278bc59..0abc378e5b 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/ConditionElse.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/ConditionElse.cs @@ -95,7 +95,7 @@ public static class WorkflowProvider ODD """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -116,7 +116,7 @@ public static class WorkflowProvider EVEN """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -137,7 +137,7 @@ public static class WorkflowProvider All done! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndConversation.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndConversation.cs index 9cf72036fd..0bf1ce343a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndConversation.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndConversation.cs @@ -60,7 +60,7 @@ public static class WorkflowProvider NEVER 1! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndWorkflow.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndWorkflow.cs index d17ddeb3a6..d4d89ccfa2 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndWorkflow.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/EndWorkflow.cs @@ -60,7 +60,7 @@ public static class WorkflowProvider NEVER 1! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Goto.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Goto.cs index d684232acf..14e2145a43 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Goto.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/Goto.cs @@ -60,7 +60,7 @@ public static class WorkflowProvider NEVER 1! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -81,7 +81,7 @@ public static class WorkflowProvider NEVER 2! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; @@ -102,7 +102,7 @@ public static class WorkflowProvider NEVER 3! """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/InvokeAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/InvokeAgent.cs index 08d324cbcd..5305c0643a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/InvokeAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/InvokeAgent.cs @@ -70,7 +70,7 @@ public static class WorkflowProvider bool autoSend = true; IList? inputMessages = await context.EvaluateListAsync("[UserMessage(System.LastMessageText)]").ConfigureAwait(false); - AgentRunResponse agentResponse = + AgentResponse agentResponse = await InvokeAgentAsync( context, agentName, diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopBreak.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopBreak.cs index f9bd0b6bd8..101d448746 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopBreak.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopBreak.cs @@ -135,7 +135,7 @@ public static class WorkflowProvider x{Local.Count} - {Local.LoopIndex}:{Local.LoopValue} """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopContinue.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopContinue.cs index 507f99995c..1cc056e647 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopContinue.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopContinue.cs @@ -135,7 +135,7 @@ public static class WorkflowProvider x{Local.Count} - {Local.LoopIndex}:{Local.LoopValue} """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopEach.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopEach.cs index 6d141cfe21..fba77afff5 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopEach.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/LoopEach.cs @@ -135,7 +135,7 @@ public static class WorkflowProvider x{Local.Count} - {Local.LoopIndex}:{Local.LoopValue} """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/SendActivity.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/SendActivity.cs index 69a99467ca..d065bcb3c8 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/SendActivity.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Workflows/SendActivity.cs @@ -77,7 +77,7 @@ public static class WorkflowProvider Input: "{Local.TestValue}" """ ); - AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); + AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]); await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false); return default; diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/AgentWorkflowBuilderTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/AgentWorkflowBuilderTests.cs index 938d1da927..da62a7a97c 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/AgentWorkflowBuilderTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/AgentWorkflowBuilderTests.cs @@ -141,20 +141,20 @@ public class AgentWorkflowBuilderTests public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new DoubleEchoAgentThread()); - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { await Task.Yield(); var contents = messages.SelectMany(m => m.Contents).ToList(); string id = Guid.NewGuid().ToString("N"); - yield return new AgentRunResponseUpdate(ChatRole.Assistant, this.Name) { AuthorName = this.Name, MessageId = id }; - yield return new AgentRunResponseUpdate(ChatRole.Assistant, contents) { AuthorName = this.Name, MessageId = id }; - yield return new AgentRunResponseUpdate(ChatRole.Assistant, contents) { AuthorName = this.Name, MessageId = id }; + yield return new AgentResponseUpdate(ChatRole.Assistant, this.Name) { AuthorName = this.Name, MessageId = id }; + yield return new AgentResponseUpdate(ChatRole.Assistant, contents) { AuthorName = this.Name, MessageId = id }; + yield return new AgentResponseUpdate(ChatRole.Assistant, contents) { AuthorName = this.Name, MessageId = id }; } } @@ -409,7 +409,7 @@ public class AgentWorkflowBuilderTests private sealed class DoubleEchoAgentWithBarrier(string name, StrongBox> barrier, StrongBox remaining) : DoubleEchoAgent(name) { - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { if (Interlocked.Decrement(ref remaining.Value) == 0) diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/ChatMessageBuilder.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/ChatMessageBuilder.cs index 659babe7e1..f3f7990c6c 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/ChatMessageBuilder.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/ChatMessageBuilder.cs @@ -25,7 +25,7 @@ internal static class TextMessageStreamingExtensions return splits.Select(text => (AIContent)new TextContent(text) { RawRepresentation = text }); } - public static AgentRunResponseUpdate ToResponseUpdate(this AIContent content, string? messageId = null, DateTimeOffset? createdAt = null, string? responseId = null, string? agentId = null, string? authorName = null) => + public static AgentResponseUpdate ToResponseUpdate(this AIContent content, string? messageId = null, DateTimeOffset? createdAt = null, string? responseId = null, string? agentId = null, string? authorName = null) => new() { Role = ChatRole.Assistant, @@ -37,7 +37,7 @@ internal static class TextMessageStreamingExtensions Contents = [content], }; - public static IEnumerable ToAgentRunStream(this string message, DateTimeOffset? createdAt = null, string? messageId = null, string? responseId = null, string? agentId = null, string? authorName = null) + public static IEnumerable ToAgentRunStream(this string message, DateTimeOffset? createdAt = null, string? messageId = null, string? responseId = null, string? agentId = null, string? authorName = null) { messageId ??= Guid.NewGuid().ToString("N"); @@ -54,7 +54,7 @@ internal static class TextMessageStreamingExtensions RawRepresentation = rawRepresentation, }; - public static IEnumerable StreamMessage(this ChatMessage message, string? responseId = null, string? agentId = null) + public static IEnumerable StreamMessage(this ChatMessage message, string? responseId = null, string? agentId = null) { responseId ??= Guid.NewGuid().ToString("N"); string messageId = message.MessageId ?? Guid.NewGuid().ToString("N"); @@ -62,7 +62,7 @@ internal static class TextMessageStreamingExtensions return message.Contents.Select(content => content.ToResponseUpdate(messageId, message.CreatedAt, responseId: responseId, agentId: agentId, authorName: message.AuthorName)); } - public static IEnumerable StreamMessages(this List messages, string? agentId = null) => + public static IEnumerable StreamMessages(this List messages, string? agentId = null) => messages.SelectMany(message => message.StreamMessage(agentId)); public static List ToChatMessages(this IEnumerable messages, string? authorName = null) diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/InProcessExecutionTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/InProcessExecutionTests.cs index 188622de51..d7f4ef7f23 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/InProcessExecutionTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/InProcessExecutionTests.cs @@ -149,7 +149,7 @@ public class InProcessExecutionTests public override ValueTask DeserializeThreadAsync(System.Text.Json.JsonElement serializedThread, System.Text.Json.JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new SimpleTestAgentThread()); - protected override Task RunCoreAsync( + protected override Task RunCoreAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -157,10 +157,10 @@ public class InProcessExecutionTests { var lastMessage = messages.LastOrDefault(); var responseMessage = new ChatMessage(ChatRole.Assistant, $"Echo: {lastMessage?.Text ?? "no message"}"); - return Task.FromResult(new AgentRunResponse(responseMessage)); + return Task.FromResult(new AgentResponse(responseMessage)); } - protected override async IAsyncEnumerable RunCoreStreamingAsync( + protected override async IAsyncEnumerable RunCoreStreamingAsync( IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, @@ -174,14 +174,14 @@ public class InProcessExecutionTests string messageId = Guid.NewGuid().ToString("N"); // Yield role first - yield return new AgentRunResponseUpdate(ChatRole.Assistant, this.Name) + yield return new AgentResponseUpdate(ChatRole.Assistant, this.Name) { AuthorName = this.Name, MessageId = messageId }; // Then yield content - yield return new AgentRunResponseUpdate(ChatRole.Assistant, responseText) + yield return new AgentResponseUpdate(ChatRole.Assistant, responseText) { AuthorName = this.Name, MessageId = messageId diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/MessageMergerTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/MessageMergerTests.cs index 793d01673e..93448aa327 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/MessageMergerTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/MessageMergerTests.cs @@ -23,12 +23,12 @@ public class MessageMergerTests MessageMerger merger = new(); - foreach (AgentRunResponseUpdate update in "Hello Agent Framework Workflows!".ToAgentRunStream(authorName: TestAuthorName1, agentId: TestAgentId1, messageId: messageId, createdAt: creationTime, responseId: responseId)) + foreach (AgentResponseUpdate update in "Hello Agent Framework Workflows!".ToAgentRunStream(authorName: TestAuthorName1, agentId: TestAgentId1, messageId: messageId, createdAt: creationTime, responseId: responseId)) { merger.AddUpdate(update); } - AgentRunResponse response = merger.ComputeMerged(responseId); + AgentResponse response = merger.ComputeMerged(responseId); response.Messages.Should().HaveCount(1); response.Messages[0].Role.Should().Be(ChatRole.Assistant); diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/RepresentationTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/RepresentationTests.cs index 299c6af903..fab0c2bc3d 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/RepresentationTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/RepresentationTests.cs @@ -30,10 +30,10 @@ public class RepresentationTests public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + protected override IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); } diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/06_GroupChat_Workflow.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/06_GroupChat_Workflow.cs index 342113e658..611e61d5b8 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/06_GroupChat_Workflow.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/06_GroupChat_Workflow.cs @@ -41,7 +41,7 @@ internal static class Step6EntryPoint } else if (evt is AgentRunUpdateEvent update) { - AgentRunResponse response = update.AsResponse(); + AgentResponse response = update.AsResponse(); foreach (ChatMessage message in response.Messages) { @@ -66,17 +66,17 @@ internal sealed class HelloAgent(string id = nameof(HelloAgent)) : AIAgent public override ValueTask DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new HelloAgentThread()); - protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - IEnumerable update = [ + IEnumerable update = [ await this.RunCoreStreamingAsync(messages, thread, options, cancellationToken) .SingleAsync(cancellationToken) .ConfigureAwait(false)]; - return update.ToAgentRunResponse(); + return update.ToAgentResponse(); } - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { yield return new(ChatRole.Assistant, "Hello World!") { diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/07_GroupChat_Workflow_HostAsAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/07_GroupChat_Workflow_HostAsAgent.cs index 17c37772dd..71844aff69 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/07_GroupChat_Workflow_HostAsAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/07_GroupChat_Workflow_HostAsAgent.cs @@ -20,7 +20,7 @@ internal static class Step7EntryPoint for (int i = 0; i < numIterations; i++) { AgentThread thread = await agent.GetNewThreadAsync(); - await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(thread).ConfigureAwait(false)) + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(thread).ConfigureAwait(false)) { if (update.RawRepresentation is WorkflowEvent) { diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/10_Sequential_HostAsAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/10_Sequential_HostAsAgent.cs index acd392a4d4..6b87aabd97 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/10_Sequential_HostAsAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/10_Sequential_HostAsAgent.cs @@ -24,7 +24,7 @@ internal static class Step10EntryPoint AgentThread thread = await hostAgent.GetNewThreadAsync(); foreach (string input in inputs) { - AgentRunResponse response; + AgentResponse response; ResponseContinuationToken? continuationToken = null; do { diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/11_Concurrent_HostAsAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/11_Concurrent_HostAsAgent.cs index 09f07267b6..dc939fda8b 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/11_Concurrent_HostAsAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/11_Concurrent_HostAsAgent.cs @@ -36,7 +36,7 @@ internal static class Step11EntryPoint AgentThread thread = await hostAgent.GetNewThreadAsync(); foreach (string input in inputs) { - AgentRunResponse response; + AgentResponse response; ResponseContinuationToken? continuationToken = null; do { diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/12_HandOff_HostAsAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/12_HandOff_HostAsAgent.cs index 28e3d7c48c..5cf4e07120 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/12_HandOff_HostAsAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/Sample/12_HandOff_HostAsAgent.cs @@ -72,7 +72,7 @@ internal static class Step12EntryPoint AgentThread thread = await hostAgent.GetNewThreadAsync(); foreach (string input in inputs) { - AgentRunResponse response; + AgentResponse response; ResponseContinuationToken? continuationToken = null; do { diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/SpecializedExecutorSmokeTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/SpecializedExecutorSmokeTests.cs index 2bf8ac52d1..ddd2b1fcdd 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/SpecializedExecutorSmokeTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/SpecializedExecutorSmokeTests.cs @@ -62,21 +62,21 @@ public class SpecializedExecutorSmokeTests public List Messages { get; } = Validate(messages) ?? []; - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => - Task.FromResult(new AgentRunResponse(this.Messages) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) => + Task.FromResult(new AgentResponse(this.Messages) { AgentId = this.Id, ResponseId = Guid.NewGuid().ToString("N") }); - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { string responseId = Guid.NewGuid().ToString("N"); foreach (ChatMessage message in this.Messages) { foreach (AIContent content in message.Contents) { - yield return new AgentRunResponseUpdate() + yield return new AgentResponseUpdate() { AgentId = this.Id, MessageId = message.MessageId, diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/TestEchoAgent.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/TestEchoAgent.cs index 73a14568e5..b971736b74 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/TestEchoAgent.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/TestEchoAgent.cs @@ -58,9 +58,9 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre return []; } - protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { - AgentRunResponse result = + AgentResponse result = new(this.EchoMessages(messages, thread, options).ToList()) { AgentId = this.Id, @@ -71,7 +71,7 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre return Task.FromResult(result); } - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { string responseId = Guid.NewGuid().ToString("N"); diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowHostSmokeTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowHostSmokeTests.cs index 32308d8b56..eed0d72dac 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowHostSmokeTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowHostSmokeTests.cs @@ -51,13 +51,13 @@ public class WorkflowHostSmokeTests return new(new Thread()); } - protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) + protected override async Task RunCoreAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) { return await this.RunStreamingAsync(messages, thread, options, cancellationToken) - .ToAgentRunResponseAsync(cancellationToken); + .ToAgentResponseAsync(cancellationToken); } - protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + protected override async IAsyncEnumerable RunCoreStreamingAsync(IEnumerable messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { const string ErrorMessage = "Simulated agent failure."; if (failByThrowing) @@ -65,7 +65,7 @@ public class WorkflowHostSmokeTests throw new ExpectedException(ErrorMessage); } - yield return new AgentRunResponseUpdate(ChatRole.Assistant, [new ErrorContent(ErrorMessage)]); + yield return new AgentResponseUpdate(ChatRole.Assistant, [new ErrorContent(ErrorMessage)]); } } @@ -91,13 +91,13 @@ public class WorkflowHostSmokeTests Workflow workflow = CreateWorkflow(failByThrowing); // Act - List updates = await workflow.AsAgent("WorkflowAgent", includeExceptionDetails: includeExceptionDetails) + List updates = await workflow.AsAgent("WorkflowAgent", includeExceptionDetails: includeExceptionDetails) .RunStreamingAsync(new ChatMessage(ChatRole.User, "Hello")) .ToListAsync(); // Assert bool hadErrorContent = false; - foreach (AgentRunResponseUpdate update in updates) + foreach (AgentResponseUpdate update in updates) { if (update.Contents.Any()) {