mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: Merge main into feature-durabletask-python branch (#3261)
* Python: Add factory pattern to concurrent orchestration builder (#2738) * Add factory pattern to concurrent orchestration builder * Update readme * Address AI comments * Fix unit tests * Fix import * Prevent multiple calls to set participants or factories * Add comments * Mitigate warnings * Fix mypy * Address comments * Address Copilot comments * Fix tests * Python: fix: GroupChat ManagerSelectionResponse JSON Schema for OpenAI Structured Outpu… (#2750) * fix: ManagerSelectionResponse JSON Schema for OpenAI Structured Output Strict Mode * refactor: install pre-commit then commit again * Capture file IDs from code interpreter in streaming responses (#2741) * .NET: [BREAKING] Prevent nulls in AIAgent property (#2719) * prevent nulls in AIAgent property * address feedback * code ql sm04598 (#2723) Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> * .NET: Add Conversation State Sample (Step05) (#2697) * Initial plan * Add Agent_OpenAI_Step05_Conversation sample for conversation state management Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> * Update Program.cs comment to accurately describe the sample Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> * Update the code to use the ConversationClient more in line with the samples in OpenAI * Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Changing sample to use ChatClientAgent and conversationId in GetNewThread --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.7 to 4.0.4.11 (#2777) --- updated-dependencies: - dependency-name: AWSSDK.Extensions.Bedrock.MEAI dependency-version: 4.0.4.11 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump Azure.Identity from 1.17.0 to 1.17.1 (#2780) --- updated-dependencies: - dependency-name: Azure.Identity dependency-version: 1.17.1 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Azure.Identity dependency-version: 1.17.1 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Azure.Identity dependency-version: 1.17.1 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Azure.Identity dependency-version: 1.17.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2778) --- updated-dependencies: - dependency-name: Azure.AI.AgentServer.AgentFramework dependency-version: 1.0.0-beta.5 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Azure.AI.AgentServer.AgentFramework dependency-version: 1.0.0-beta.5 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Azure.AI.AgentServer.AgentFramework dependency-version: 1.0.0-beta.5 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Python: added more complete parsing for mcp tool arguments (#2756) * added more complete parsing for mcp tool arguments * fixed mypy * added nonlocal model counter, and some fixes * fixes in naming logic * extracted json parsing function, added parametrized test and checked coverage * Python: Updated package versions (#2784) * Updated package versions * Small fix * Bump actions/checkout from 5 to 6 (#2404) Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * .NET: adds support for labels in edges, fixes rendering of labels in dot a… (#1507) * adds support for labels in edges, fixes rendering of labels in dot and mermaid, adds rendering of labels in edges * Update dotnet/src/Microsoft.Agents.AI.Workflows/Visualization/WorkflowVisualizer.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * escaping edge labels, adding tests for labels containing strange characters that would break the diagram and enabling the previous signature so the API has backwards compatibility. * Unify label in EdgeData * Edge API adjustments, removed useless "sanitizer" * fixed test --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Jacob Alber <jaalber@microsoft.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * Python: Added custom args and thread object to ai_function kwargs (#2769) * Added an example of using kwargs in ai_function * Added thread object to ai_function kwargs * Updated docs * Small fix * Added thread parameter filtering * Fix WorkflowAgent to include thread convo history. Enable checkpointing. (#2774) * Update OpenAIResponses.yaml to match AgentSchema (#2598) 1. Update `connection` child types -- `kind: ApiKey` to `kind: key` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/apikeyconnection/ 2. Update `outputSchema`'s `PropertySchema` to be `kind` instead of `type` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/propertyschema/ * Python: Remove warnings from workflow builder on not using factories (#2808) * Revert concurrent * Fix comments * Python: Filter framework kwargs from MCP tool invocations (#2870) * Filter framework kwargs from MCP tool invocations * Fixes * Python: Fix WorkflowAgent to emit yield_output as agent response (#2866) * Fix WorkflowAgent to emit yield_output as agent response * use raw_representation * Raw representation handling * Python: Use agent description in HandoffBuilder auto-generated tools (#2713) (#2714) ## Summary Enhanced `HandoffBuilder._apply_auto_tools` to use the target agent's description when creating handoff tools, providing more informative tool descriptions for LLMs. ## Changes - Modified `_apply_auto_tools` to extract `description` from `AgentExecutor._agent` when available - Updated iteration to use `.items()` for more efficient dict traversal - Handoff tools now use agent descriptions instead of generic placeholders ## Example Before: "Handoff to the refund_agent agent." After: "You handle refund requests. Ask for order details and process refunds." ## Testing - All handoff tests pass (20/20) - No breaking changes to existing API Fixes #2713 Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> * Python: [BREAKING] Observability updates (#2782) * fixes Python: Add env_file_path parameter to setup_observability() similar to AzureOpenAIChatClient Fixes #2186 * WIP on updates using configure_azure_monitor * improved setup and clarity * fixed root .env.example * revert changes * updated files * updated sample * updated zero code * test fixes and fixed links * fix devui * removed planning docs * added enable method and updated readme and samples * clarified docstring * add return annotation * updated naming * update capatilized version * updated readme and some fixes * updated decorator name inline with the rest * feedback from comments addressed * Python: Fix middleware terminate flag to exit function calling loop immediately (#2868) * Fix middleware terminate flag to exit function calling loop immediately * Eliminating duck typing * Improve function exec result handling * Fix race condition * Fix mypy issues * Python: Fix context duplication in handoff workflows when restoring from checkpoint (#2867) * Fix context duplication in handoff workflows when restoring from checkpoint * Address Copilot PR review * .NET: Update to latest Azure.AI.*, OpenAI, and M.E.AI* (#2850) * Update to latest Azure.AI.*, OpenAI, and M.E.AI* Absorb breaking changes in Responses surface area * Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs * Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs * Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs * Update dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/Program.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Using patch to remove the model is necessary, updated the response client to actually use the the ForAgent --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com> * Bump actions/download-artifact from 6 to 7 (#2862) Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7. - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/download-artifact dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump actions/cache from 4 to 5 (#2861) Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/cache dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump actions/upload-artifact from 5 to 6 (#2860) Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Python : Ollama Connector for Agent Framework (#1104) * Initial Commit for Olama Connector * Added Olama Sample * Add Sample & Fixed Open Telemetry * Fixed Spelling from Olama to Ollama * remove"opentelemetry-semantic-conventions-ai ~=0.4.13" since its handled in a different pr * Added Tool Calling * Finalizing test cases * Adjust samples to be more reliable * Update python/packages/ollama/agent_framework_ollama/_chat_client.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update python/packages/ollama/pyproject.toml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update python/packages/ollama/tests/test_ollama_chat_client.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update python/packages/ollama/agent_framework_ollama/_chat_client.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Improved Docstrings & Sample * Update python/packages/ollama/agent_framework_ollama/_chat_client.py Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com> * Integrate PR Feedback - Divided Streaming and Non-Streaming into independent Methods - Catch Ollama Validation Error - Add OTEL Provider Name - Checked Ollama Messages - Add Usage Statistics * Revert setting, so it can be none * Validate Message formatting between AF and Ollama * Catch Ollama Error and raise a ServiceResponse Error * Fix mypy error * remove .vscode comma * Add Reasoning support & adjust to new structure * Add Ollama Multimodality and Reasoning * Add test cases for reasoning * Add Tests for Error Handling in Ollama Client * Update python/samples/getting_started/multimodal_input/ollama_chat_multimodal.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Integrated Copilot Feedback * Implement first PR Feedback * Adjust Readme files for examples * Adjust argument passing via additional chat options * Implemented PR Feedback * Removing Ollama Package from Core and moving samples * Fix Link & Adding Samples to Main Sample Readme * Fixing Links in Readme * Moved Multimodal and Chat Example * Fixed Link in ChatClient to Ollama * Fix AgentFramework Links in Ollama Project * Fix observability breaking change --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com> * Skip failing IT (#2904) * .NET: Cosmos DB UT Fast Skip (For Non-Configured Local envs) (#2906) * Cosmos DB UT Fast Skip (Non-Configured Local envs) + Long running UT skip in pipeline when no CosmosDB changes happened * Force a CosmosDB source code change to trigger the pipeline * Address possible string boolean mismatch * Add debug * Enabling emulator always when running IT * .NET: Add TTLs to durable agent sessions (#2679) * .NET: Add TTLs to durable agent sessions * Remove unnecessary async * PR feedback: clarify UTC * PR feedback: limit minimum signal delay to <= 5 minutes * PR feedback: Fix TTL disablement * Linter: use auto-property * Fix build break from OpenAI SDK change * Updated CHANGELOG.md * PR feedback * Reduce default TTL to 14 days to work around DTS bug * Python: Update Mem0Provider to use v2 search API `filters` parameter (#2766) * short fix to move id parameters to filters object * added tests * small fix * mem0 dependency update * Updated package versions (#2913) * .NET: Switch to new "Run" method name. (#2843) * Switch to new "RunAgent" method name. * Try to disable false positive naming warning. * Add comment about disabled warnings. * Rename `RunAgent` to just `Run`. * Update CHANGELOG. * Python: Switch to new "run" method name. (#2890) * Switch to `run` method. * Add support for deprecated `run_agent`. * Fix entity method name. * Fix method name and improve tests. * Update comment. * Update Python CHANGELOG. * [BREAKING] Python: Add factory pattern to handoff orchestration builder (#2844) * WIP: Factory pattern to handoff * Add factory pattern to concurrent orchestration builder; Next: tests and sample verification * Add tests and improve comments * Fix mypy * Simplify handoff_simple.py * Simplify handoff_autonoumous.py and bug fix * Update readme * Address Copilot comments * Python: Flow custom kwargs to agents via Workflow SharedState (#2894) * Flow custom kwargs to agents via SharedState * Address Copilot feedback * Improve sample typing * Fix test * Fix Pydantic error when using Literal type for tool params (#2893) * Updated Ollama package version (#2920) * Python: Azure AI Agent with Bing Grounding Citations Sample (#2892) * bing grounding sample with citations * small fix * fix * .NET: Make DelegatingAIAgent abstract (#2797) * Initial plan * Make DelegatingAIAgent abstract Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Added additional arguments for Azure AI agent (#2922) * Python: Correction of MCP image type conversion in _mcp.py (#2901) * Correction of MCP image type conversion in _mcp.py * Added a new overload to the init function of the DataContent() type of the Agent Framework, edited the test case to correctly test the usage of the data and uri fields while using DataContent() * Fixed tests related to the changes of the DataContent type, added testing for both string and byte representations * Pass kwargs into subworkflows (#2923) * Python: Move ollama samples to samples getting started dir (#2921) * Move ollama samples to samples getting started dir * Address feedback * Python: fix: correct BadRequestError when using Pydantic model in response_fo… (#1843) * fix: correct BadRequestError when using Pydantic model in response_format * Fix lint --------- Co-authored-by: Evan Mattson <evan.mattson@microsoft.com> * .NET: [Breaking] Delete display name property (#2758) * delete the AIAgent.DisplayName property * use agent name as a first value for activity display name * Update dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Python: cleanup and refactoring of chat clients (#2937) * refactoring and unifying naming schemes of internal methods of chat clients * set tool_choice to auto * fix for mypy * added note on naming and fix #2951 * fix responses * fixes in azure ai agents client * Python: Workflow add option to visualize internal executors (#2917) * Workflow add option to visualize internal executors * Address Copilot comments * Python: Fixes Run ID and Thread ID casing to align with AG-UI Typescript SDK (#2948) * added camelCase input to run id and thread id aligning with @ag-ui/core * fixed per copilot suggestions * Python: Add workflow cancellation sample (#2732) * Add workflow cancellation sample Add sample demonstrating how to cancel a running workflow using asyncio tasks. Shows both cancellation mid-execution and normal completion paths. Useful for implementing timeouts, graceful shutdown, or A2A executors. * update docstring * .NET: Update Anthropic package to version 12.0.0 (#2914) * Initial plan * Update Anthropic package to version 12.0.0 Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com> * Python: Add Azure Managed Redis Support with Credential Provider (#2887) * azure redis support * small fixes * azure managed redis sample * fixes * Bump CommunityToolkit.Aspire.OllamaSharp from 13.0.0-beta.440 to 13.0.0 (#2856) --- updated-dependencies: - dependency-name: CommunityToolkit.Aspire.OllamaSharp dependency-version: 13.0.0 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.11 to 4.0.5 (#2853) --- updated-dependencies: - dependency-name: AWSSDK.Extensions.Bedrock.MEAI dependency-version: 4.0.5 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> * Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2854) --- updated-dependencies: - dependency-name: Azure.AI.AgentServer.AgentFramework dependency-version: 1.0.0-beta.5 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Azure.AI.AgentServer.AgentFramework dependency-version: 1.0.0-beta.5 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * Python: Fix WorkflowAgent event handling and kwargs forwarding (#2946) * Fix kwargs propagation through workflow.as_agent() * Fix WorkflowAgent to respect AgentExecutor output_response setting * .NET: Use GrpcEntityRunner instead of TaskEntityDispatcher (#2759) * Use GrpcEntityRunner instead of TaskEntityDispatcher * Pin to Durable worker 1.11.0 * Set the invocation result * Update all Durable packages * Update changelog, rename dispatcher to encondedEntityRequest * Python: Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG (#2968) * Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG * update lock * Fix formatting * Fix ChatKit typing * Python: Introducing Foundry Local Chat Clients (#2915) * redo foundry local chat client * fix mypy and spelling * better docstring, updated sample * fixed tests and added tests * small sample update * Updated package versions (#2978) * Python: Added GitHub MCP sample with PAT (#2967) * added github mcp sample with PAT * addressed copilot fixes * env fix * Python: Preserve reasoning blocks with OpenRouter (#2950) * Preserve reasoning blocks with OpenRouter * Put encrypted reasoning in TextReasoningContent * Remove unneccessary change * Fix docs * Support streaming * Fix handling None in TextReasoningContent.text * Python: Added response.created and response.in_progress event process to OpenAIBaseResponseClient (#2975) * added response.created and response.in_progress to include response.id * better doc string * added tests for the new streaming event types * Python: Introducing support for Bedrock-hosted models (Anthropic, Cohere, etc.) (#2610) * Pushing the bedrock related changes to the new branch after addressing the review comments * 2524 Addressed the second round review comments * 2524 Addressed few more minor comments on the PR * resolving the merge conflict * 2524 resolved the uv.lock conflicts * 2524 addressed more comments * 2524 removed the print statement to fix the checks failure * 2524 resolved the CI failure issues * 2524 fixing the CI breaks * 2524 Addressed the review comment * 2524 resolved conflict --------- Co-authored-by: Sunil Dutta <sunil.dutta@penske.com> Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com> * .NET: [Durable Agents] Reliable streaming sample (#2942) * .NET: [Durable Agents] Reliable streaming sample * Add automated validation for new sample * Address Copilot PR feedback * Fix typo in README.md about agent definitions (#2634) * Fix typo in README.md about agent definitions * Update agent-samples/README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Python: latency improvements (#3014) * latency improvements * fixed mypy, added coding standards and instructions * slight logic improvement * Python: Updated package versions (#3024) * Updated package versions * Updated changelog * Python: add powerfx safe mode (#3028) * add powerfx safe mode * improved docstring and aligned env_file loading * ensured test uses reset * .NET: [Breaking] Introduce RunCoreAsync/RunCoreStreamingAsync delegation pattern in AIAgent (#2749) * Initial plan * Refactor AIAgent: Make RunAsync and RunStreamingAsync non-abstract, add RunCoreAsync and RunCoreStreamingAsync Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Fix infinite recursion in test implementations Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Make RunAsync and RunStreamingAsync non-virtual as requested Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Fix DelegatingAIAgent subclasses to use RunCoreAsync/RunCoreStreamingAsync Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Fix XML documentation references in AnonymousDelegatingAIAgent Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Restore <see cref> tags with proper qualified signatures in AnonymousDelegatingAIAgent Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Rollback unnecessary XML documentation changes in AnonymousDelegatingAIAgent Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Remove pragma and update crefs to RunCoreAsync/RunCoreStreamingAsync Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Fix EntityAgentWrapper to call base.RunCoreAsync/RunCoreStreamingAsync Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * fix compilation issues * fix compilatio issue * fix tests * fix unit tests * fix unit test --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * add issue template and additional labeling (#3006) * fix and extra int test (#3037) * .NET: [BREAKING] Refactor ChatMessageStore methods to be similar to AIContextProvider and add filtering support (#2604) * Refactor ChatMessageStore methods to be similar to AIContextProvider * Fix file encoding * Ensure that AIContextProvider messages area also persisted. * Update formatting and seal context classes * Improve formatting * Remove optional messages from constructor and add unit test * Add ChatMessageStore filtering via a decorator * Update sample and cosmos message store to store AIContextProvider messages in right order. Fix unit tests. * Update Workflowmessage store to use aicontext provider messages. * Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Improve xml docs messaging * Address code review comments. * Also notify message store on failure --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * [BREAKING] Remove unused AgentThreadMetadata (#3067) * Remove unused AgentThreadMetadata * Update DurableTask Changelog * Python: Fix AzureAIClient failure when conversation history contains assistant messages (#3076) * Fix AzureAIClient failure when conversation history contains assistant messages * Address PR review feedback: improve docstring and test assertions * Remove redundant cast * Fix: Update OTLP exporter protocol conditions (#3070) * Python: Fix ExecutorInvokedEvent and ExecutorCompletedEvent observability data (#3090) * Fix ExecutorInvokedEvent.data mutation bug * Fix bug related to not yielding output type * .NET: Seal ChatClientAgentThread (#2842) * Initial plan * Seal ChatClientAgentThread class Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * Fix broken strands urls. (#3102) * Fix broken strands urls. * Fix typos * .NET: Fix message ordering inconsistency when using AIContextProvider (#2659) * Initial plan * Fix message ordering inconsistency when using AIContextProvider Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> * Revert to original message ordering: Input, AIContextProvider, Response Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> * Reorder messages to ChatClient to match MessageStore order: Existing, Input, AIContextProvider Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> * Remove redundant test methods as existing tests already verify the behavior Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * fix: tool_choice parameter not being honored when passed to agent.run() (#3095) * sharepoint sample fix (#3108) * Bump versions to 1.0.0b260106 for a release. Update CHANGELOG.md (#3109) * Bump Bedrock version to latest (#3110) * Python: Fix MCP tool result serialization for list[TextContent] (#2523) * Fix MCP tool result serialization for list[TextContent] When MCP tools return results containing list[TextContent], they were incorrectly serialized to object repr strings like: '[<agent_framework._types.TextContent object at 0x...>]' This fix properly extracts text content from list items by: 1. Checking if items have a 'text' attribute (TextContent) 2. Using model_dump() for items that support it 3. Falling back to str() for other types 4. Joining single items as plain text, multiple items as JSON array Fixes #2509 * Address PR review feedback for MCP tool result serialization - Extract serialize_content_result() to shared _utils.py - Fix logic: use texts[0] instead of join for single item - Add type annotation: texts: list[str] = [] - Return empty string for empty list instead of '[]' - Move import json to file top level - Add comprehensive unit tests for serialization * Address PR review feedback: fix type checking and double serialization - Add isinstance(item.text, str) check to ensure text attribute is a string - Fix double-serialization issue by keeping model_dump results as dicts until final json.dumps (removes escaped JSON strings in arrays) - Improve docstring with detailed return value documentation - Add test for non-string text attribute handling - Add tests for list type tool results in _events.py path * Simplify PR: minimal changes to fix MCP tool result serialization Addresses reviewer feedback about excessive refactoring: - Reset _events.py to original structure - Only add import and use serialize_content_result in one location - All review comments addressed in serialize_content_result(): - Added isinstance(item.text, str) check - Use model_dump(mode="json") to avoid double-serialization - Improved docstring with explicit return value documentation - Empty list returns "" instead of "[]" * Refactor: Move MCP TextContent serialization to core prepare_function_call_results Per reviewer feedback, moved the TextContent serialization logic from ag-ui's serialize_content_result to the core package's prepare_function_call_results function. Changes: - Added handling for objects with 'text' attribute (like MCP TextContent) in _prepare_function_call_results_as_dumpable - Removed serialize_content_result from ag-ui/_utils.py - Updated _events.py and _message_adapters.py to use prepare_function_call_results from core package - Updated tests to match the core function's behavior * Fix failing tests for prepare_function_call_results behavior - test_tool_result_with_none: Update expected value to 'null' (JSON serialization of None) - test_tool_result_with_model_dump_objects: Use Pydantic BaseModel instead of plain class * Fix B903 linter error: Convert MockTextContent to dataclass The ruff linter was reporting B903 (class could be dataclass or namedtuple) for the MockTextContent test helper classes. This commit converts them to dataclasses to satisfy the linter check. * Python: Improve DevUI, add Context Inspector view as new tab under traces (#2742) * Improve DevUI, add Context Inspector view as new tab under traces * fix mypy errors * fix: Handle stale MCP connections in DevUI executor MCP tools can become stale when HTTP streaming responses end - the underlying stdio streams close but `is_connected` remains True. This causes subsequent requests to fail with `ClosedResourceError`. Add `_ensure_mcp_connections()` to detect and reconnect stale MCP tools before agent execution. This is a workaround for an upstream Agent Framework issue where connection state isn't properly tracked. Fixes MCP tools failing on second HTTP request in DevUI. fixes #1476 #1515 #2865 * fix #1572 report import dependency errors more clearly * Ensure there is streaming toggle where users can select streaming vs non streaming mode in devui . Fixes .NET: [Python] DevUI tool call rendering in non-streaming mode? * remove unused dead code * improve ux - workflows with agents show a chat component in execution timelien, also ensure magentic final output shows correctly * update ui build * update devui to use instrumentation instead of tracing, other instrumentation and type/instance check fixes * .NET: Seal factory contexts and add non JSO deserialize overloads (#3066) * Seal factory contexts and add non JSO deserialize overloads * Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Enable blank issues in issue template configuration Need to re-enable creating blank issues * updated templates (#3106) * updated templates * enabled blank and fixed triage * made language optional and moved to the bottom for features * Python: Streaming sample for azurefunctions (#3057) * Streaming sample for azurefunctions * Fixed links and sample name * Addressed feedback * Addressed feedback * Fixed integration tests * Updated test * Python: fix(azure-ai): Fix response_format handling for structured outputs (#3114) * fix(azure-ai): read response_format from chat_options instead of run_options * refactor: use explicit None checks for response_format * Fix mypy error * Mypy fix * Python: Bump python version to 1.0.0b260107 for a release (#3128) * Bump python version to 1.0.0b260107 for a release * Update changelog * Make A2AAgent public, so that it's concrete implementation methods can be used. (#3119) * .NET: Map additional props <-> A2A metadata (#3137) * map additional props from agent run options to a2a request metadata * small touches * add unit tests for new extension methods * Sort using * add unit test * add additiona unit tests * special case json element to avoid unnecessary serialization * Python: Fix Anthropic streaming response bugs (#3141) * test commit identity * fix(anthropic): fix raw_representation and finish_reason in streaming * lint fix * Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.5 to 4.0.5.1 (#2994) --- updated-dependencies: - dependency-name: AWSSDK.Extensions.Bedrock.MEAI dependency-version: 4.0.5.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * Bump Anthropic from 12.0.0 to 12.0.1 (#2993) --- updated-dependencies: - dependency-name: Anthropic dependency-version: 12.0.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * .NET: [Breaking] Prevent loss of input messages & streamed updates when resuming streaming (#2748) * save input messages and stream updates to the continuation token to be able to use them in the last successful stream resumption call. * Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * fix typo * init continuation token from chat response * remove unnecessary types for source generation * remove check for continuation token passed at initial run * remove check for continuation token pass at initial run * centralize continuation token parsing * update xml comments * use readonly collection instead of enumerable --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * .NET: fix: Expose WorkflowErrorEvent as ErrorContent (#2762) * fix: Expose WorkflowErrorEvent as ErrorContent When hosted using .AsAgent(), Workflows were not exposing inner errors coming as Exceptions (through the WorkflowErrorEvent) The fix is to convert their message to an ErrorContent on the way out, rather than rely on the default "empty update" to collect the raw event. * feat: Add a way to show/suppress exception information * Bump Microsoft.Agents.AI.Workflows from 1.0.0-preview.251125.1 to 1.0.0-preview.251219.1 (#2997) --- updated-dependencies: - dependency-name: Microsoft.Agents.AI.Workflows dependency-version: 1.0.0-preview.251219.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> * .NET: Add Run overloads to expose ChatClientAgentRunOptions in IntelliSense (#3115) * Initial plan * Add ChatClientAgentExtensions for improved discoverability of ChatClientAgentRunOptions Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> * Address code review feedback - use collection expression syntax Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> * Apply suggestion from @westey-m * Fix issues with Copilot implementation * Add additional tests for structured output overloads. --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com> * Python: Add tool call/result content types and update connectors and samples (#2971) * Add new AI content types and image tool support Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Add Python content types for tool calls/results and image generation tool support Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Address review feedback for tool content and samples Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Tighten image generation typing and sample tools list Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Align image generation output typing Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Handle MCP naming, image options mapping, and connector tool content Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Allow MCP call in function approval request Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Remove raw image_generation tool remapping Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Restore Anthropic tool_use to function calls unless code execution Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Fix lint issues for hosted file docstring and MCP parsing Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Import ChatResponse types in Anthropic client Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Fix Anthropics citation type imports and MCP typing for handoff/tools Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Skip lightning tests without agentlightning and fix function call import Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * fix lint on lab package * rebuilt anthropic parsing * redid anthropic parsing * typo * updated parsing and added missing docstrings * fix tests * mypy fixes * second mypy fix * add new class to other samples --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu> * Bump Google.GenAI from 0.6.0 to 0.9.0 (#2995) --- updated-dependencies: - dependency-name: Google.GenAI dependency-version: 0.9.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * Bump js-yaml from 4.1.0 to 4.1.1 in /python/packages/devui/frontend (#3123) Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.0 to 4.1.1. - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 4.1.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Updated package versions (#3144) * .NET: Bump Microsoft.Agents.AI.OpenAI and Microsoft.Extensions.AI.OpenAI (#2996) * Bump Microsoft.Agents.AI.OpenAI and Microsoft.Extensions.AI.OpenAI Bumps Microsoft.Agents.AI.OpenAI from 1.0.0-preview.251125.1 to 1.0.0-preview.251219.1 Bumps Microsoft.Extensions.AI.OpenAI from 10.1.0-preview.1.25608.1 to 10.1.1-preview.1.25612.2 --- updated-dependencies: - dependency-name: Microsoft.Agents.AI.OpenAI dependency-version: 1.0.0-preview.251219.1 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Microsoft.Extensions.AI.OpenAI dependency-version: 10.1.1-preview.1.25612.2 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Microsoft.Agents.AI.OpenAI dependency-version: 1.0.0-preview.251219.1 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: Microsoft.Extensions.AI.OpenAI dependency-version: 10.1.1-preview.1.25612.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> * Fixed samples --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com> * Python: fix(ag-ui): Execute tools with approval_mode, fix shared state, code cleanup (#3079) * fix(ag-ui): execute tools after approval in human-in-the-loop flow * Fix shared state bug * Bug fix finalized * Refactoring to clean up code * Code cleanup * More fixes * More code cleanup * Add version detection in __init__.py to ruff ignore list * Track agent name with updates for workflow agent (#3146) * Python: Fix AzureAIClient tool call bug for AG-UI use (#3148) * Fiz AzureAIClient tool call bug * Address copilot feedback * Python: multiple bug fixes (#3150) * fix Python: kwargs are not passed to _prepare_thread_and_messages in ChatAgent.run Fixes #3118 * fix Python: [Bug]: model_id versus model_deployment_name is confusing in Azure AI Agents Fixes #3147 * add types * fixed type and docstring * fix(anthropic): fix duplicate ToolCallStartEvent in streaming tool calls (#3051) When processing `input_json_delta` events, the Anthropic client was passing the tool name from the previous `tool_use` event. This caused ag-ui's `_handle_function_call_content` to emit a `ToolCallStartEvent` for every streaming chunk (since it triggers on `if content.name:`). This fix changes the behavior to pass an empty string for `name` in `input_json_delta` events, matching OpenAI's behavior where streaming argument chunks have `name=""`. The initial `tool_use` event still provides the tool name, so only one `ToolCallStartEvent` is emitted. Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> * .NET: [BREAKING] Change GetNewThread and DeserializeThread to async (#3152) * Change GetNewThread and DeserializeThread plus ChatMessageStore and AIContextProvider Factories to async * Merge fixes * Fix Ollama model env var in documentation (#3156) Signed-off-by: Dina Suehiro Jones <dina.s.jones@intel.com> * Python: Add Pydantic request model and OpenAPI tags support to AG-UI FastAPI endpoint (#2522) * feat(ag-ui): Add Pydantic request model and OpenAPI tags support - Add AGUIRequest Pydantic model in _types.py with field descriptions - Update add_agent_framework_fastapi_endpoint() to accept tags parameter - Use AGUIRequest model for automatic validation and OpenAPI schema generation - Export AGUIRequest and DEFAULT_TAGS in __init__.py - Update test_endpoint.py to expect 422 for invalid requests - Add tests for OpenAPI schema, default tags, custom tags, and validation Benefits: - Better API documentation with complete request schema in Swagger UI - Automatic request validation with Pydantic - Organized endpoints under 'AG-UI' tag instead of 'default' - Improved developer experience and type safety Fixes #<issue-number> * test(ag-ui): Add test for internal error handling to achieve 100% coverage - Add test_endpoint_internal_error_handling() to cover exception handling code - Mock copy.deepcopy to simulate internal error during default_state processing - Add type: ignore for FastAPI tags parameter (known pyright compatibility issue) - Achieves 100% test coverage for _endpoint.py (previously missing lines 103-105) * .NET: Improve resolving `AITool` from DI (#3175) * remove localagenttoolregistry * also give the factory method API * Python: Fix MCPStreamableHTTPTool to use new streamable_http_client API (#3088) * Fix MCPStreamableHTTPTool to use new streamable_http_client API with proper httpx client cleanup Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Update docstring to reflect new streamable_http_client API usage Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Refactor MCPStreamableHTTPTool to accept optional http_client parameter and delegate client creation to streamable_http_client Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Update mcp package minimum version to 1.24.0 for streamable_http_client API support Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Fix critical bugs: apply headers/timeout/sse_read_timeout when creating httpx client, add version constraint <2, and properly manage client lifecycle Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Simplify implementation: remove headers/timeout/sse_read_timeout params, remove kwargs, remove close() override per feedback Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Add back **kwargs parameter for backward compatibility (accepted but not used) Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Remove unused httpx import from test file Note: The uv.lock file needs to be updated with 'uv sync' to reflect the mcp version constraint change (>=1.24.0,<2) Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * cicd fixes * udpated samples with headers examples --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu> * azureai direct a2a endpoint support (#3127) * Python: [BREAKING]: removed display_name, renamed context_providers, middleware and AggregateContextProvider (#3139) * removed display_name, renamed context_providers, middleware and AggregateContextProvider * fixes * fixed test * testfix * removed mistakenly put back test * updated new test * rename middlewares to middleware * middleware fixes * Python: MCP Improvements: improved connection loss behavior, pagination for loading and a param to control representation (#3154) * pagination support (#2848) added a parse_tool_result param and connection loss (#2884) * fix #3153 * improved connection handling * improved logic * Python: Add declarative workflow runtime (#2815) * Further support for declarative python workflows * Add tests. Clean up for typing and formatting * Improvements and cleanup * Typing cleanup. Improve docstrings * Proper code in docstrings * Fix malformed code-block directive in docstring * Remove dead links * PR feedback * Address PR feedback * Address PR feedback * Remove sl * Update devui frontend * More cleanup * Fix uv lock * Skip Py 3.14 tests as powerfx doesn't support it * Fix mypy error * Fix for tool calls * Removed stale docstring * Fix lint * Standardize on .NET namespaces. Revert DevUI changes (bring in later) * Implement remaining items for Python declarative support to match dotnet * point URL to agent, not to agentcard (#3176) * Python: [BREAKING]: Introducing Options as TypedDict and Generic (#3140) * WIP typeddict for options * updated all clients and ChatAgents * updated everything * added ADR * fix mypy * proper typevar imports * fixed import * fixed other imports * slight update in the sample * updated from feedback * fixes * fixed missing covariants and test fixes * fixed typing * updated anthropic thinking config * ruff fixes * fixed int tests * fix tests and mypy * updated integration tests * updated docstring and test fix * improved options handling in obser * mypy fix * updated a host of integration tests * fix tests * bedrock fix * [BREAKING] Python: Refactor orchestrations (#3023) * Group chat refactoring Part 1; Next: HIL and handoff * Add agent approval flow; next samples * WIP: samples * WIP: HIL samples * Group chat HIL working; next: handoff * Fix group chat tool approval sample * WIP: refactor handoff; next handoff handling * Handoff done; next handoff samples and concurrent and sequential * Handoff samples, concurrent, and sequential done; next Magentic * WIP: magentic; next test with samples + HIL * Magentic Working; next fix all samples and tests * Fix handoff samples; next tests * WIP: fixing tests; some orchestration as agent samples are failing * Group chat unit tests done * Handoff unit tests done * Remove old orchestration_request_info and fix related tests * Magentic unit tests done * Fix samples * Fix test * Fix test 2 * mypy * Address comments * Update readme * Address comments * Address comments 2 * Replace display name * Python: ADR for create/get agent API (#2618) * ADR for create/get agent API * Updated ADR with implementation options * Small updates * Updated decision outcome section * Updated broken links * Small updates * Fixed merge conflicts * Small fix * Updated decision outcome section * Small fixes * Updated provider naming based on client SDK * Add ignored parameter for CodeQL in workflow (#3204) * Implement IReadOnlyList on InMemoryChatMessageStore (#3205) * .NET: Make ChatMessageStore and AIContextProvider context props settable (#3196) * Make ChatMessageStore and AIContextProvider context props setable * Add validation to preserve non-null requirement of certain properties. * Fix broken tests. * Python: Add dependencies param to ag-ui FastAPI endpoint (#3191) * Add dependencies param to ag-ui FastAPI endpoint * Address Copilot feedback * renamed all (#3207) * Python: ADR for simplified get response (#3098) * ADR for simplified get response * updated some language, added agent option and code comparison * small update in sample * added workflows and expanded some points * changed decision and number * updated with stream=False default * .NET: [Breaking] Rename`AgentRunResponse` and `AgentRunResponseUpdate` classes (#3197) * rename AgentRunResponse and AgentRunResponseUpdate classes - part1 * rename varialbles, parameters, methods and tests * rollback unnecessary changes * .NET: [Breaking] Rename AgentRunResponseEvent and AgentRunUpdateEvent classes (#3214) * rename AgentRunResponseEvent and AgentRunUpdateEvent classes * rollback unnecessary changes * Python: Create/Get Agent API for Azure V2 (#3059) * Added get_agent method to Azure AI V2 * Small fixes * Small fix * Removed AzureAIAgentProvider * Added create_agent method * Small fixes * Fixed code interpreter tool mapping * Added agent provider for V2 client * Updated response format handling * Added provider example * Fixed errors * Update python/samples/getting_started/agents/azure_ai/README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Small fix * Updates from merge * Resolved comments * Resolved comments --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Python: Add more specific exceptions to Workflow (#3188) * Add more specifc workflow exceptions * Fix tests * AI comments * Misc * Python: Added AzureAI sample for downloading code interpreter generated files (#3189) * added azure ai code interpreter file download sample * copilot fix suggestions * function name fixes + readme update * small fix * update package versions (#3223) Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com> * Python: fix(core): correct FunctionResultContent ordering in WorkflowAgent.merge_updates (#3168) * fix(core): simplify FunctionResultContent ordering in WorkflowAgent.merge_updates * improve comment * Fix name * fix(workflows): rename WorkflowOutputEvent.source_executor_id to executor_id for API consistency (#3166) * Python: fix(ag-ui): add MCP tool support for AG-UI approval flows (#3212) * add MCP tool support for AG-UI approval flows * use attribute in place of property * Python: Properly configure structured outputs based on new options dict (#3213) * Properly configure structured outputs based on new options dict * Fix mypy * .NET: Merge AgentRunOptions.AdditionalProperties into ChatOptions.AdditionalProperties (#3184) * Merge AgentRunOptions.AdditionalProperties into ChatOptions.AdditionalProperties * Fix namespace and typo. * .NET: Update Google.GenAI to 0.11.0 and remove polyfill implementations (#3232) * Initial plan * Update Google.GenAI to 0.11.0 and remove polyfill files Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> * .NET: [BREAKING] Renamed CreateAIAgent/GetAIAgent to AsAIAgent (#3222) * Renamed chat client extension method * Additional renaming * Updated documentation * Fixed tests * Small fix * Small fix * Updated DurableAIAgent and fixed integration tests (#3241) * Python: Create/Get Agent API for Azure V1 (#3192) * Added provider implementation for Azure AI V1 * Small fixes * Fixed OpenAPI example * Fixed local MCP example * Fixed hosted MCP example * Fixed file search sample * Small fixes * Resolved comments * Doc updates * Bump azure-core from 1.37.0 to 1.38.0 in /python (#3209) Bumps [azure-core](https://github.com/Azure/azure-sdk-for-python) from 1.37.0 to 1.38.0. - [Release notes](https://github.com/Azure/azure-sdk-for-python/releases) - [Commits](https://github.com/Azure/azure-sdk-for-python/compare/azure-core_1.37.0...azure-core_1.38.0) --- updated-dependencies: - dependency-name: azure-core dependency-version: 1.38.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Python: Create/Get Agent API for OpenAI Assistants (#3208) * Added provider implementation * Added example with response format * Small improvements * Python: (AG-UI) Support service-managed thread on AG-UI (#3136) * added service thread support * set service_thread_id to only supplied_thread_id * uses raw_representation to extract the conversation_id * removed accidental edit * updated test to use raw_representation * resolves copilot review feedback * revert back StubAgent, since not used * removed relative module import * removed hasattr check per PR feedback * Create/Get Agent API - fixes and example improvements (#3246) * Fix merge conflicts --------- Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: Dina Suehiro Jones <dina.s.jones@intel.com> Co-authored-by: Tao Chen <taochen@microsoft.com> Co-authored-by: Kurt <65111699+q33566@users.noreply.github.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> Co-authored-by: Korolev Dmitry <deagle.gross@gmail.com> Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com> Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> Co-authored-by: Jose Luis Latorre Millas <joslat@gmail.com> Co-authored-by: Jacob Alber <jaalber@microsoft.com> Co-authored-by: Richard Ortega <richardjortega@gmail.com> Co-authored-by: 刘邦学AI <lbbniu@gmail.com> Co-authored-by: Stephen Toub <stoub@microsoft.com> Co-authored-by: Nico Möller <nkm-moeller@mail.de> Co-authored-by: Chris Gillum <cgillum@microsoft.com> Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com> Co-authored-by: Phillip Hoff <phillip.hoff@gmail.com> Co-authored-by: Ege Ozan Özyedek <36128615+egeozanozyedek@users.noreply.github.com> Co-authored-by: samueljohnsiby <66901393+samueljohnsiby@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com> Co-authored-by: Hao Luo <338265+howlowck@users.noreply.github.com> Co-authored-by: Victor Dibia <chuvidi2003@gmail.com> Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com> Co-authored-by: Jacob Viau <javia@microsoft.com> Co-authored-by: SuperKenVery <39673849+SuperKenVery@users.noreply.github.com> Co-authored-by: Sunil Dutta <dutta.2003@gmail.com> Co-authored-by: Sunil Dutta <sunil.dutta@penske.com> Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com> Co-authored-by: Syrine Chelly <62653967+SyChell@users.noreply.github.com> Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com> Co-authored-by: westey <164392973+westey-m@users.noreply.github.com> Co-authored-by: takanori-terai <123897708+takanori-terai@users.noreply.github.com> Co-authored-by: claude89757 <138977524+claude89757@users.noreply.github.com> Co-authored-by: Gavin Aguiar <80794152+gavin-aguiar@users.noreply.github.com> Co-authored-by: Sukeesh <vsukeeshbabu@gmail.com> Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu> Co-authored-by: Ao Chen <chenao3220@gmail.com> Co-authored-by: Dina Suehiro Jones <dina.s.jones@intel.com>
This commit is contained in:
co-authored by
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Tao Chen
Kurt
Evan Mattson
SergeyMenshykh
Korolev Dmitry
Mark Wallace
Copilot
rogerbarreto
Copilot
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Eduard van Valkenburg
Dmytro Struk
Chris
Jose Luis Latorre Millas
Jacob Alber
Richard Ortega
刘邦学AI
Stephen Toub
Nico Möller
Chris Gillum
Giles Odigwe
Phillip Hoff
Ege Ozan Özyedek
samueljohnsiby
Evan Mattson
Hao Luo
Victor Dibia
stephentoub
Jacob Viau
SuperKenVery
Sunil Dutta
Sunil Dutta
budgetboardingai
Syrine Chelly
SergeyMenshykh
westey
takanori-terai
claude89757
Gavin Aguiar
Sukeesh
eavanvalkenburg
eavanvalkenburg
Ao Chen
Dina Suehiro Jones
parent
3df916064c
commit
cd77193742
@@ -22,7 +22,7 @@ public abstract class ChatClientAgentRunStreamingTests<TAgentFixture>(Func<TAgen
|
||||
{
|
||||
// Arrange
|
||||
var agent = await this.Fixture.CreateChatClientAgentAsync(instructions: "Always respond with 'Computer says no', even if there was no user input.");
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var agentCleanup = new AgentCleanup(agent, this.Fixture);
|
||||
await using var threadCleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
@@ -53,7 +53,7 @@ public abstract class ChatClientAgentRunStreamingTests<TAgentFixture>(Func<TAgen
|
||||
AIFunctionFactory.Create(MenuPlugin.GetSpecials),
|
||||
AIFunctionFactory.Create(MenuPlugin.GetItemPrice)
|
||||
]);
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
|
||||
foreach (var questionAndAnswer in questionsAndAnswers)
|
||||
{
|
||||
|
||||
@@ -21,7 +21,7 @@ public abstract class ChatClientAgentRunTests<TAgentFixture>(Func<TAgentFixture>
|
||||
{
|
||||
// Arrange
|
||||
var agent = await this.Fixture.CreateChatClientAgentAsync(instructions: "ALWAYS RESPOND WITH 'Computer says no', even if there was no user input.");
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var agentCleanup = new AgentCleanup(agent, this.Fixture);
|
||||
await using var threadCleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
@@ -53,7 +53,7 @@ public abstract class ChatClientAgentRunTests<TAgentFixture>(Func<TAgentFixture>
|
||||
AIFunctionFactory.Create(MenuPlugin.GetSpecials),
|
||||
AIFunctionFactory.Create(MenuPlugin.GetItemPrice)
|
||||
]);
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
|
||||
foreach (var questionAndAnswer in questionsAndAnswers)
|
||||
{
|
||||
|
||||
@@ -24,7 +24,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -36,7 +36,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -52,7 +52,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -68,7 +68,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -92,7 +92,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
|
||||
const string Q1 = "What is the capital of France.";
|
||||
const string Q2 = "And Austria?";
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
|
||||
@@ -24,7 +24,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -39,7 +39,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -57,7 +57,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -74,7 +74,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
|
||||
{
|
||||
// Arrange
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
@@ -99,7 +99,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
|
||||
const string Q1 = "What is the capital of France.";
|
||||
const string Q2 = "And Austria?";
|
||||
var agent = this.Fixture.Agent;
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await using var cleanup = new ThreadCleanup(thread, this.Fixture);
|
||||
|
||||
// Act
|
||||
|
||||
@@ -148,7 +148,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
new(ChatRole.User, "Test message")
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
await this._agent.RunAsync(inputMessages, thread);
|
||||
@@ -168,7 +168,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
new(ChatRole.User, "Test message")
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
var a2aThread = (A2AAgentThread)thread;
|
||||
a2aThread.ContextId = "existing-context-id";
|
||||
|
||||
@@ -201,7 +201,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
ContextId = "different-context"
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
var a2aThread = (A2AAgentThread)thread;
|
||||
a2aThread.ContextId = "existing-context-id";
|
||||
|
||||
@@ -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<ChatMessage>
|
||||
@@ -227,7 +227,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
};
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in this._agent.RunStreamingAsync(inputMessages))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -272,7 +272,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
ContextId = "new-stream-context"
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
await foreach (var _ in this._agent.RunStreamingAsync(inputMessages, thread))
|
||||
@@ -296,7 +296,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
|
||||
this._handler.StreamingResponseToReturn = new AgentMessage();
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
var a2aThread = (A2AAgentThread)thread;
|
||||
a2aThread.ContextId = "existing-context-id";
|
||||
|
||||
@@ -316,7 +316,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
public async Task RunStreamingAsync_WithThreadHavingDifferentContextId_ThrowsInvalidOperationExceptionAsync()
|
||||
{
|
||||
// Arrange
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
var a2aThread = (A2AAgentThread)thread;
|
||||
a2aThread.ContextId = "existing-context-id";
|
||||
|
||||
@@ -440,7 +440,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
Parts = [new TextPart { Text = "Response to task" }]
|
||||
};
|
||||
|
||||
var thread = (A2AAgentThread)this._agent.GetNewThread();
|
||||
var thread = (A2AAgentThread)await this._agent.GetNewThreadAsync();
|
||||
thread.TaskId = "task-123";
|
||||
|
||||
var inputMessage = new ChatMessage(ChatRole.User, "Please make the background transparent");
|
||||
@@ -466,7 +466,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
Status = new() { State = TaskState.Submitted }
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
await this._agent.RunAsync("Start a task", thread);
|
||||
@@ -492,7 +492,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
}
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
var result = await this._agent.RunAsync("Start a long-running task", thread);
|
||||
@@ -586,7 +586,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
Parts = [new TextPart { Text = "Response to task" }]
|
||||
};
|
||||
|
||||
var thread = (A2AAgentThread)this._agent.GetNewThread();
|
||||
var thread = (A2AAgentThread)await this._agent.GetNewThreadAsync();
|
||||
thread.TaskId = "task-123";
|
||||
|
||||
// Act
|
||||
@@ -613,7 +613,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
Status = new() { State = TaskState.Submitted }
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
await foreach (var _ in this._agent.RunStreamingAsync("Start a task", thread))
|
||||
@@ -646,7 +646,7 @@ public sealed class A2AAgentTests : IDisposable
|
||||
};
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in this._agent.RunStreamingAsync("Test message"))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -686,10 +686,10 @@ public sealed class A2AAgentTests : IDisposable
|
||||
]
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in this._agent.RunStreamingAsync("Start long-running task", thread))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -725,10 +725,10 @@ public sealed class A2AAgentTests : IDisposable
|
||||
Status = new() { State = TaskState.Working }
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in this._agent.RunStreamingAsync("Check task status", thread))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -768,10 +768,10 @@ public sealed class A2AAgentTests : IDisposable
|
||||
}
|
||||
};
|
||||
|
||||
var thread = this._agent.GetNewThread();
|
||||
var thread = await this._agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in this._agent.RunStreamingAsync("Process artifact", thread))
|
||||
{
|
||||
updates.Add(update);
|
||||
|
||||
+2
-2
@@ -34,7 +34,7 @@ public sealed class A2AAgentCardExtensionsTests
|
||||
public void GetAIAgent_ReturnsAIAgent()
|
||||
{
|
||||
// Act
|
||||
var agent = this._agentCard.GetAIAgent();
|
||||
var agent = this._agentCard.AsAIAgent();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -56,7 +56,7 @@ public sealed class A2AAgentCardExtensionsTests
|
||||
Parts = [new TextPart { Text = "Response" }],
|
||||
});
|
||||
|
||||
var agent = this._agentCard.GetAIAgent(httpClient);
|
||||
var agent = this._agentCard.AsAIAgent(httpClient);
|
||||
|
||||
// Act
|
||||
await agent.RunAsync("Test input");
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ public sealed class A2AClientExtensionsTests
|
||||
const string TestDescription = "This is a test agent description";
|
||||
|
||||
// Act
|
||||
var agent = a2aClient.GetAIAgent(TestId, TestName, TestDescription);
|
||||
var agent = a2aClient.AsAIAgent(TestId, TestName, TestDescription);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
|
||||
@@ -30,11 +30,11 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
AgentRunResponse response = await agent.RunAsync(messages);
|
||||
AgentResponse response = await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
@@ -55,11 +55,11 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
AgentRunResponse response = await agent.RunAsync(messages);
|
||||
AgentResponse response = await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(response);
|
||||
@@ -74,7 +74,7 @@ public sealed class AGUIAgentTests
|
||||
// Arrange
|
||||
using HttpClient httpClient = new();
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: "Test agent", name: "agent1");
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: "Test agent", name: "agent1");
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(() => agent.RunAsync(messages: null!));
|
||||
@@ -91,11 +91,11 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: "Test agent", name: "agent1");
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: "Test agent", name: "agent1");
|
||||
List<ChatMessage> 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);
|
||||
@@ -115,12 +115,12 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: "Test agent", name: "agent1");
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: "Test agent", name: "agent1");
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
List<AgentResponseUpdate> updates = [];
|
||||
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
{
|
||||
// Consume the stream
|
||||
updates.Add(update);
|
||||
@@ -139,7 +139,7 @@ public sealed class AGUIAgentTests
|
||||
// Arrange
|
||||
using HttpClient httpClient = new();
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: "Test agent", name: "agent1");
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: "Test agent", name: "agent1");
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
|
||||
@@ -162,12 +162,12 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: "Test agent", name: "agent1");
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: "Test agent", name: "agent1");
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages, thread: null))
|
||||
List<AgentResponseUpdate> updates = [];
|
||||
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, thread: null))
|
||||
{
|
||||
// Consume the stream
|
||||
updates.Add(update);
|
||||
@@ -195,7 +195,7 @@ public sealed class AGUIAgentTests
|
||||
using HttpClient httpClient = new(handler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
@@ -227,12 +227,12 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Hello")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> updates = [];
|
||||
await foreach (var update in agent.RunStreamingAsync(messages, thread))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -244,17 +244,17 @@ public sealed class AGUIAgentTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeserializeThread_WithValidState_ReturnsChatClientAgentThread()
|
||||
public async Task DeserializeThread_WithValidState_ReturnsChatClientAgentThreadAsync()
|
||||
{
|
||||
// Arrange
|
||||
using var httpClient = new HttpClient();
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AgentThread originalThread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: []);
|
||||
AgentThread originalThread = await agent.GetNewThreadAsync();
|
||||
JsonElement serialized = originalThread.Serialize();
|
||||
|
||||
// Act
|
||||
AgentThread deserialized = agent.DeserializeThread(serialized);
|
||||
AgentThread deserialized = await agent.DeserializeThreadAsync(serialized);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(deserialized);
|
||||
@@ -301,12 +301,12 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [testTool]);
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [testTool]);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "What's the weather?")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> allUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
List<AgentResponseUpdate> allUpdates = [];
|
||||
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
{
|
||||
allUpdates.Add(update);
|
||||
}
|
||||
@@ -353,12 +353,12 @@ public sealed class AGUIAgentTests
|
||||
using HttpClient httpClient = new(handler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [tool1]); // Only tool1, not tool2
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [tool1]); // Only tool1, not tool2
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> allUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
List<AgentResponseUpdate> allUpdates = [];
|
||||
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
{
|
||||
allUpdates.Add(update);
|
||||
}
|
||||
@@ -403,12 +403,12 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [faultyTool]);
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [faultyTool]);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> allUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
List<AgentResponseUpdate> allUpdates = [];
|
||||
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages))
|
||||
{
|
||||
allUpdates.Add(update);
|
||||
}
|
||||
@@ -448,7 +448,7 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [tool1, tool2]);
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [tool1, tool2]);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
@@ -486,12 +486,12 @@ public sealed class AGUIAgentTests
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [testTool]);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "agent1", description: "Test agent", tools: [testTool]);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> updates = [];
|
||||
await foreach (var update in agent.RunStreamingAsync(messages, thread))
|
||||
{
|
||||
updates.Add(update);
|
||||
|
||||
@@ -19,8 +19,8 @@ public class AIAgentTests
|
||||
{
|
||||
private readonly Mock<AIAgent> _agentMock;
|
||||
private readonly Mock<AgentThread> _agentThreadMock;
|
||||
private readonly AgentRunResponse _invokeResponse;
|
||||
private readonly List<AgentRunResponseUpdate> _invokeStreamingResponses = [];
|
||||
private readonly AgentResponse _invokeResponse;
|
||||
private readonly List<AgentResponseUpdate> _invokeStreamingResponses = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AIAgentTests"/> class.
|
||||
@@ -29,13 +29,13 @@ public class AIAgentTests
|
||||
{
|
||||
this._agentThreadMock = new Mock<AgentThread>(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<AIAgent> { CallBase = true };
|
||||
this._agentMock
|
||||
.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.Is<AgentThread?>(t => t == this._agentThreadMock.Object),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -43,7 +43,7 @@ public class AIAgentTests
|
||||
.ReturnsAsync(this._invokeResponse);
|
||||
this._agentMock
|
||||
.Protected()
|
||||
.Setup<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.Is<AgentThread?>(t => t == this._agentThreadMock.Object),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -69,7 +69,7 @@ public class AIAgentTests
|
||||
// Verify that the mocked method was called with the expected parameters
|
||||
this._agentMock
|
||||
.Protected()
|
||||
.Verify<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Verify<Task<AgentResponse>>("RunCoreAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(messages => !messages.Any()),
|
||||
ItExpr.Is<AgentThread?>(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<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Verify<Task<AgentResponse>>("RunCoreAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(messages => messages.Count() == 1 && messages.First().Text == Message),
|
||||
ItExpr.Is<AgentThread?>(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<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Verify<Task<AgentResponse>>("RunCoreAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(messages => messages.Count() == 1 && messages.First() == message),
|
||||
ItExpr.Is<AgentThread?>(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<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Verify<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(messages => !messages.Any()),
|
||||
ItExpr.Is<AgentThread?>(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<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Verify<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(messages => messages.Count() == 1 && messages.First().Text == Message),
|
||||
ItExpr.Is<AgentThread?>(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<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Verify<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(messages => messages.Count() == 1 && messages.First() == message),
|
||||
ItExpr.Is<AgentThread?>(t => t == this._agentThreadMock.Object),
|
||||
@@ -378,20 +378,20 @@ public class AIAgentTests
|
||||
|
||||
protected override string? IdCore { get; }
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override async ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override async ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException();
|
||||
|
||||
protected override IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
|
||||
+2
-2
@@ -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);
|
||||
|
||||
+25
-25
@@ -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<ArgumentNullException>("message", () => new AgentRunResponse((ChatMessage)null!));
|
||||
Assert.Throws<ArgumentNullException>("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<AgentRunResponse>(json, AgentAbstractionsJsonUtilities.DefaultOptions);
|
||||
AgentResponse? result = JsonSerializer.Deserialize<AgentResponse>(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<UsageContent>(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<Animal>();
|
||||
@@ -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<Animal>(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<InvalidOperationException>(() => response.Deserialize<Animal>(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<JsonException>(() => response.Deserialize<Animal>(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<JsonException>(() => response.Deserialize<Animal>(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<Animal>(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<Animal>(TestJsonSerializerContext.Default.Options, out _));
|
||||
+33
-33
@@ -9,9 +9,9 @@ using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Microsoft.Agents.AI.Abstractions.UnitTests;
|
||||
|
||||
public class AgentRunResponseUpdateExtensionsTests
|
||||
public class AgentResponseUpdateExtensionsTests
|
||||
{
|
||||
public static IEnumerable<object[]> ToAgentRunResponseCoalescesVariousSequenceAndGapLengthsMemberData()
|
||||
public static IEnumerable<object[]> ToAgentResponseCoalescesVariousSequenceAndGapLengthsMemberData()
|
||||
{
|
||||
foreach (bool useAsync in new[] { false, true })
|
||||
{
|
||||
@@ -32,15 +32,15 @@ public class AgentRunResponseUpdateExtensionsTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToAgentRunResponseWithInvalidArgsThrows() =>
|
||||
Assert.Throws<ArgumentNullException>("updates", () => ((List<AgentRunResponseUpdate>)null!).ToAgentRunResponse());
|
||||
public void ToAgentResponseWithInvalidArgsThrows() =>
|
||||
Assert.Throws<ArgumentNullException>("updates", () => ((List<AgentResponseUpdate>)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<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> updates = [];
|
||||
|
||||
List<string> 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<TextContent>(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<object?[]> ToAgentRunResponse_TimestampFolding_MemberData()
|
||||
public static IEnumerable<object?[]> 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<AgentRunResponseUpdate> YieldAsync(IEnumerable<AgentRunResponseUpdate> updates)
|
||||
private static async IAsyncEnumerable<AgentResponseUpdate> YieldAsync(IEnumerable<AgentResponseUpdate> updates)
|
||||
{
|
||||
foreach (AgentRunResponseUpdate update in updates)
|
||||
foreach (AgentResponseUpdate update in updates)
|
||||
{
|
||||
await Task.Yield();
|
||||
yield return update;
|
||||
+7
-7
@@ -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<AgentRunResponseUpdate>(json, AgentAbstractionsJsonUtilities.DefaultOptions);
|
||||
AgentResponseUpdate? result = JsonSerializer.Deserialize<AgentResponseUpdate>(json, AgentAbstractionsJsonUtilities.DefaultOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(5, result.Contents.Count);
|
||||
@@ -17,8 +17,8 @@ public class DelegatingAIAgentTests
|
||||
{
|
||||
private readonly Mock<AIAgent> _innerAgentMock;
|
||||
private readonly TestDelegatingAIAgent _delegatingAgent;
|
||||
private readonly AgentRunResponse _testResponse;
|
||||
private readonly List<AgentRunResponseUpdate> _testStreamingResponses;
|
||||
private readonly AgentResponse _testResponse;
|
||||
private readonly List<AgentResponseUpdate> _testStreamingResponses;
|
||||
private readonly AgentThread _testThread;
|
||||
|
||||
/// <summary>
|
||||
@@ -27,19 +27,19 @@ public class DelegatingAIAgentTests
|
||||
public DelegatingAIAgentTests()
|
||||
{
|
||||
this._innerAgentMock = new Mock<AIAgent>();
|
||||
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
|
||||
this._innerAgentMock.Protected().SetupGet<string>("IdCore").Returns("test-agent-id");
|
||||
this._innerAgentMock.Setup(x => x.Name).Returns("Test Agent");
|
||||
this._innerAgentMock.Setup(x => x.Description).Returns("Test Description");
|
||||
this._innerAgentMock.Setup(x => x.GetNewThread()).Returns(this._testThread);
|
||||
this._innerAgentMock.Setup(x => x.GetNewThreadAsync()).ReturnsAsync(this._testThread);
|
||||
|
||||
this._innerAgentMock
|
||||
.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -48,7 +48,7 @@ public class DelegatingAIAgentTests
|
||||
|
||||
this._innerAgentMock
|
||||
.Protected()
|
||||
.Setup<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -132,17 +132,17 @@ public class DelegatingAIAgentTests
|
||||
#region Method Delegation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetNewThread delegates to inner agent.
|
||||
/// Verify that GetNewThreadAsync delegates to inner agent.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetNewThread_DelegatesToInnerAgent()
|
||||
public async Task GetNewThreadAsync_DelegatesToInnerAgentAsync()
|
||||
{
|
||||
// Act
|
||||
var thread = this._delegatingAgent.GetNewThread();
|
||||
var thread = await this._delegatingAgent.GetNewThreadAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Same(this._testThread, thread);
|
||||
this._innerAgentMock.Verify(x => x.GetNewThread(), Times.Once);
|
||||
this._innerAgentMock.Verify(x => x.GetNewThreadAsync(), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -156,13 +156,13 @@ public class DelegatingAIAgentTests
|
||||
var expectedThread = new TestAgentThread();
|
||||
var expectedOptions = new AgentRunOptions();
|
||||
var expectedCancellationToken = new CancellationToken();
|
||||
var expectedResult = new TaskCompletionSource<AgentRunResponse>();
|
||||
var expectedResponse = new AgentRunResponse();
|
||||
var expectedResult = new TaskCompletionSource<AgentResponse>();
|
||||
var expectedResponse = new AgentResponse();
|
||||
|
||||
var innerAgentMock = new Mock<AIAgent>();
|
||||
innerAgentMock
|
||||
.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(m => m == expectedMessages),
|
||||
ItExpr.Is<AgentThread?>(t => t == expectedThread),
|
||||
ItExpr.Is<AgentRunOptions?>(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<AIAgent>();
|
||||
innerAgentMock
|
||||
.Protected()
|
||||
.Setup<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(m => m == expectedMessages),
|
||||
ItExpr.Is<AgentThread?>(t => t == expectedThread),
|
||||
ItExpr.Is<AgentRunOptions?>(o => o == expectedOptions),
|
||||
|
||||
+2
-2
@@ -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))]
|
||||
|
||||
+7
-7
@@ -34,7 +34,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
var testChatClient = new TestChatClient(chatClient.Beta.AsIChatClient());
|
||||
|
||||
// Act
|
||||
var agent = chatClient.Beta.CreateAIAgent(
|
||||
var agent = chatClient.Beta.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
@@ -63,7 +63,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
TestChatClient? testChatClient = null;
|
||||
|
||||
// Act
|
||||
var agent = chatClient.Beta.CreateAIAgent(
|
||||
var agent = chatClient.Beta.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
clientFactory: (innerClient) =>
|
||||
@@ -95,7 +95,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = chatClient.Beta.CreateAIAgent(
|
||||
var agent = chatClient.Beta.AsAIAgent(
|
||||
options,
|
||||
clientFactory: (innerClient) => testChatClient);
|
||||
|
||||
@@ -120,7 +120,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
var chatClient = new TestAnthropicChatClient();
|
||||
|
||||
// Act
|
||||
var agent = chatClient.Beta.CreateAIAgent(
|
||||
var agent = chatClient.Beta.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent");
|
||||
@@ -144,7 +144,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
var chatClient = new TestAnthropicChatClient();
|
||||
|
||||
// Act
|
||||
var agent = chatClient.Beta.CreateAIAgent(
|
||||
var agent = chatClient.Beta.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
@@ -167,7 +167,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
{
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
((IBetaService)null!).CreateAIAgent("test-model"));
|
||||
((IBetaService)null!).AsAIAgent("test-model"));
|
||||
|
||||
Assert.Equal("betaService", exception.ParamName);
|
||||
}
|
||||
@@ -183,7 +183,7 @@ public sealed class AnthropicBetaServiceExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
chatClient.Beta.CreateAIAgent((ChatClientAgentOptions)null!));
|
||||
chatClient.Beta.AsAIAgent((ChatClientAgentOptions)null!));
|
||||
|
||||
Assert.Equal("options", exception.ParamName);
|
||||
}
|
||||
|
||||
+7
-7
@@ -101,7 +101,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
var testChatClient = new TestChatClient(chatClient.AsIChatClient());
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
@@ -130,7 +130,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
TestChatClient? testChatClient = null;
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
clientFactory: (innerClient) =>
|
||||
@@ -162,7 +162,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
options,
|
||||
clientFactory: (innerClient) => testChatClient);
|
||||
|
||||
@@ -187,7 +187,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
var chatClient = new TestAnthropicChatClient();
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent");
|
||||
@@ -211,7 +211,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
var chatClient = new TestAnthropicChatClient();
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
model: "test-model",
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
@@ -234,7 +234,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
{
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
((TestAnthropicChatClient)null!).CreateAIAgent("test-model"));
|
||||
((TestAnthropicChatClient)null!).AsAIAgent("test-model"));
|
||||
|
||||
Assert.Equal("client", exception.ParamName);
|
||||
}
|
||||
@@ -250,7 +250,7 @@ public sealed class AnthropicClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
chatClient.CreateAIAgent((ChatClientAgentOptions)null!));
|
||||
chatClient.AsAIAgent((ChatClientAgentOptions)null!));
|
||||
|
||||
Assert.Equal("options", exception.ParamName);
|
||||
}
|
||||
|
||||
+8
-8
@@ -42,7 +42,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
|
||||
// Act & Assert - null agentId
|
||||
var exception1 = Assert.Throws<ArgumentException>(() =>
|
||||
mockClient.Object.GetAIAgent((string)null!));
|
||||
mockClient.Object.GetAIAgent(null!));
|
||||
Assert.Equal("agentId", exception1.ParamName);
|
||||
|
||||
// Act & Assert - empty agentId
|
||||
@@ -314,7 +314,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(response, options);
|
||||
var agent = client.AsAIAgent(response, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -341,7 +341,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(persistentAgent, options);
|
||||
var agent = client.AsAIAgent(persistentAgent, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -363,7 +363,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
var options = new ChatClientAgentOptions(); // Empty options
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(persistentAgent, options);
|
||||
var agent = client.AsAIAgent(persistentAgent, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -443,7 +443,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(
|
||||
var agent = client.AsAIAgent(
|
||||
persistentAgent,
|
||||
options,
|
||||
clientFactory: (innerClient) => testChatClient);
|
||||
@@ -470,7 +470,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
client.GetAIAgent((Response<PersistentAgent>)null!, options));
|
||||
client.AsAIAgent(null!, options));
|
||||
|
||||
Assert.Equal("persistentAgentResponse", exception.ParamName);
|
||||
}
|
||||
@@ -487,7 +487,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
client.GetAIAgent((PersistentAgent)null!, options));
|
||||
client.AsAIAgent((PersistentAgent)null!, options));
|
||||
|
||||
Assert.Equal("persistentAgentMetadata", exception.ParamName);
|
||||
}
|
||||
@@ -504,7 +504,7 @@ public sealed class PersistentAgentsClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
client.GetAIAgent(persistentAgent, (ChatClientAgentOptions)null!));
|
||||
client.AsAIAgent(persistentAgent, (ChatClientAgentOptions)null!));
|
||||
|
||||
Assert.Equal("options", exception.ParamName);
|
||||
}
|
||||
|
||||
+58
-58
@@ -25,13 +25,13 @@ namespace Microsoft.Agents.AI.AzureAI.UnitTests;
|
||||
/// </summary>
|
||||
public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
{
|
||||
#region GetAIAgent(AIProjectClient, AgentRecord) Tests
|
||||
#region AsAIAgent(AIProjectClient, AgentRecord) Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentRecord_WithNullClient_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithAgentRecord_WithNullClient_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient? client = null;
|
||||
@@ -39,39 +39,39 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
client!.GetAIAgent(agentRecord));
|
||||
client!.AsAIAgent(agentRecord));
|
||||
|
||||
Assert.Equal("aiProjectClient", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when agentRecord is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when agentRecord is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentRecord_WithNullAgentRecord_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithAgentRecord_WithNullAgentRecord_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var mockClient = new Mock<AIProjectClient>();
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
mockClient.Object.GetAIAgent((AgentRecord)null!));
|
||||
mockClient.Object.AsAIAgent((AgentRecord)null!));
|
||||
|
||||
Assert.Equal("agentRecord", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with AgentRecord creates a valid agent.
|
||||
/// Verify that AsAIAgent with AgentRecord creates a valid agent.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentRecord_CreatesValidAgent()
|
||||
public void AsAIAgent_WithAgentRecord_CreatesValidAgent()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord);
|
||||
var agent = client.AsAIAgent(agentRecord);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -79,10 +79,10 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with AgentRecord and clientFactory applies the factory.
|
||||
/// Verify that AsAIAgent with AgentRecord and clientFactory applies the factory.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentRecord_WithClientFactory_AppliesFactoryCorrectly()
|
||||
public void AsAIAgent_WithAgentRecord_WithClientFactory_AppliesFactoryCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
@@ -90,7 +90,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
TestChatClient? testChatClient = null;
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(
|
||||
var agent = client.AsAIAgent(
|
||||
agentRecord,
|
||||
clientFactory: (innerClient) => testChatClient = new TestChatClient(innerClient));
|
||||
|
||||
@@ -103,13 +103,13 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetAIAgent(AIProjectClient, AgentVersion) Tests
|
||||
#region AsAIAgent(AIProjectClient, AgentVersion) Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentVersion_WithNullClient_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithAgentVersion_WithNullClient_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient? client = null;
|
||||
@@ -117,39 +117,39 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
client!.GetAIAgent(agentVersion));
|
||||
client!.AsAIAgent(agentVersion));
|
||||
|
||||
Assert.Equal("aiProjectClient", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when agentVersion is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when agentVersion is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentVersion_WithNullAgentVersion_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithAgentVersion_WithNullAgentVersion_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var mockClient = new Mock<AIProjectClient>();
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
mockClient.Object.GetAIAgent((AgentVersion)null!));
|
||||
mockClient.Object.AsAIAgent((AgentVersion)null!));
|
||||
|
||||
Assert.Equal("agentVersion", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with AgentVersion creates a valid agent.
|
||||
/// Verify that AsAIAgent with AgentVersion creates a valid agent.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentVersion_CreatesValidAgent()
|
||||
public void AsAIAgent_WithAgentVersion_CreatesValidAgent()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
AgentVersion agentVersion = this.CreateTestAgentVersion();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentVersion);
|
||||
var agent = client.AsAIAgent(agentVersion);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -157,10 +157,10 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with AgentVersion and clientFactory applies the factory.
|
||||
/// Verify that AsAIAgent with AgentVersion and clientFactory applies the factory.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentVersion_WithClientFactory_AppliesFactoryCorrectly()
|
||||
public void AsAIAgent_WithAgentVersion_WithClientFactory_AppliesFactoryCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
@@ -168,7 +168,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
TestChatClient? testChatClient = null;
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(
|
||||
var agent = client.AsAIAgent(
|
||||
agentVersion,
|
||||
clientFactory: (innerClient) => testChatClient = new TestChatClient(innerClient));
|
||||
|
||||
@@ -183,7 +183,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
/// Verify that GetAIAgent with requireInvocableTools=true enforces invocable tools.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentVersion_WithRequireInvocableToolsTrue_EnforcesInvocableTools()
|
||||
public void AsAIAgent_WithAgentVersion_WithRequireInvocableToolsTrue_EnforcesInvocableTools()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
@@ -194,7 +194,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentVersion, tools: tools);
|
||||
var agent = client.AsAIAgent(agentVersion, tools: tools);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -205,14 +205,14 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
/// Verify that GetAIAgent with requireInvocableTools=false allows declarative functions.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentVersion_WithRequireInvocableToolsFalse_AllowsDeclarativeFunctions()
|
||||
public void AsAIAgent_WithAgentVersion_WithRequireInvocableToolsFalse_AllowsDeclarativeFunctions()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
AgentVersion agentVersion = this.CreateTestAgentVersion();
|
||||
|
||||
// Act - should not throw even without tools when requireInvocableTools is false
|
||||
var agent = client.GetAIAgent(agentVersion);
|
||||
var agent = client.AsAIAgent(agentVersion);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -374,7 +374,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
#region GetAIAgent(AIProjectClient, string) Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_ByName_WithNullClient_ThrowsArgumentNullException()
|
||||
@@ -390,7 +390,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when name is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when name is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_ByName_WithNullName_ThrowsArgumentNullException()
|
||||
@@ -406,7 +406,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentException when name is empty.
|
||||
/// Verify that AsAIAgent throws ArgumentException when name is empty.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_ByName_WithEmptyName_ThrowsArgumentException()
|
||||
@@ -422,7 +422,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws InvalidOperationException when agent is not found.
|
||||
/// Verify that AsAIAgent throws InvalidOperationException when agent is not found.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_ByName_WithNonExistentAgent_ThrowsInvalidOperationException()
|
||||
@@ -505,13 +505,13 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetAIAgent(AIProjectClient, AgentRecord) with tools Tests
|
||||
#region AsAIAgent(AIProjectClient, AgentRecord) with tools Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with additional tools when the definition has no tools does not throw and results in an agent with no tools.
|
||||
/// Verify that AsAIAgent with additional tools when the definition has no tools does not throw and results in an agent with no tools.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentRecordAndAdditionalTools_WhenDefinitionHasNoTools_ShouldNotThrow()
|
||||
public void AsAIAgent_WithAgentRecordAndAdditionalTools_WhenDefinitionHasNoTools_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
@@ -522,7 +522,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord, tools: tools);
|
||||
var agent = client.AsAIAgent(agentRecord, tools: tools);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -536,17 +536,17 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with null tools works correctly.
|
||||
/// Verify that AsAIAgent with null tools works correctly.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentRecordAndNullTools_WorksCorrectly()
|
||||
public void AsAIAgent_WithAgentRecordAndNullTools_WorksCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord, tools: null);
|
||||
var agent = client.AsAIAgent(agentRecord, tools: null);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -1104,7 +1104,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
var shouldBeIgnoredTool = AIFunctionFactory.Create(() => "test", "additional_tool", "An additional test function that should be ignored");
|
||||
|
||||
// Act & Assert
|
||||
var agent = client.GetAIAgent(agentVersion, tools: [invocableInlineAITool, shouldBeIgnoredTool]);
|
||||
var agent = client.AsAIAgent(agentVersion, tools: [invocableInlineAITool, shouldBeIgnoredTool]);
|
||||
Assert.NotNull(agent);
|
||||
var version = agent.GetService<AgentVersion>();
|
||||
Assert.NotNull(version);
|
||||
@@ -1136,7 +1136,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord, tools: tools);
|
||||
var agent = client.AsAIAgent(agentRecord, tools: tools);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -1632,7 +1632,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
#region AgentName Validation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentException when agent name is invalid.
|
||||
/// Verify that AsAIAgent throws ArgumentException when agent name is invalid.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[MemberData(nameof(InvalidAgentNameTestData.GetInvalidAgentNames), MemberType = typeof(InvalidAgentNameTestData))]
|
||||
@@ -1846,7 +1846,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
/// Verify that the underlying chat client created by extension methods can be wrapped with clientFactory.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithClientFactory_WrapsUnderlyingChatClient()
|
||||
public void AsAIAgent_WithClientFactory_WrapsUnderlyingChatClient()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
@@ -1854,7 +1854,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
int factoryCallCount = 0;
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(
|
||||
var agent = client.AsAIAgent(
|
||||
agentRecord,
|
||||
clientFactory: (innerClient) =>
|
||||
{
|
||||
@@ -1903,18 +1903,18 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
/// Verify that multiple clientFactory calls create independent wrapped clients.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_MultipleCallsWithClientFactory_CreatesIndependentClients()
|
||||
public void AsAIAgent_MultipleCallsWithClientFactory_CreatesIndependentClients()
|
||||
{
|
||||
// Arrange
|
||||
AIProjectClient client = this.CreateTestAgentClient();
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord();
|
||||
|
||||
// Act
|
||||
var agent1 = client.GetAIAgent(
|
||||
var agent1 = client.AsAIAgent(
|
||||
agentRecord,
|
||||
clientFactory: (innerClient) => new TestChatClient(innerClient));
|
||||
|
||||
var agent2 = client.GetAIAgent(
|
||||
var agent2 = client.AsAIAgent(
|
||||
agentRecord,
|
||||
clientFactory: (innerClient) => new TestChatClient(innerClient));
|
||||
|
||||
@@ -2165,7 +2165,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
#region GetAIAgent(AIProjectClient, AgentReference) Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when AIProjectClient is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentReference_WithNullClient_ThrowsArgumentNullException()
|
||||
@@ -2182,7 +2182,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when agentReference is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when agentReference is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAgentReference_WithNullAgentReference_ThrowsArgumentNullException()
|
||||
@@ -2297,7 +2297,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord);
|
||||
var agent = client.AsAIAgent(agentRecord);
|
||||
var retrievedRecord = agent.GetService<AgentRecord>();
|
||||
|
||||
// Assert
|
||||
@@ -2338,7 +2338,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentVersion agentVersion = this.CreateTestAgentVersion();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentVersion);
|
||||
var agent = client.AsAIAgent(agentVersion);
|
||||
var retrievedVersion = agent.GetService<AgentVersion>();
|
||||
|
||||
// Assert
|
||||
@@ -2379,7 +2379,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord);
|
||||
var agent = client.AsAIAgent(agentRecord);
|
||||
var metadata = agent.GetService<ChatClientMetadata>();
|
||||
|
||||
// Assert
|
||||
@@ -2402,7 +2402,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord(definition);
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord);
|
||||
var agent = client.AsAIAgent(agentRecord);
|
||||
var metadata = agent.GetService<ChatClientMetadata>();
|
||||
|
||||
// Assert
|
||||
@@ -2423,7 +2423,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentVersion agentVersion = this.CreateTestAgentVersion();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentVersion);
|
||||
var agent = client.AsAIAgent(agentVersion);
|
||||
var metadata = agent.GetService<ChatClientMetadata>();
|
||||
|
||||
// Assert
|
||||
@@ -2467,7 +2467,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentRecord agentRecord = this.CreateTestAgentRecord();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentRecord);
|
||||
var agent = client.AsAIAgent(agentRecord);
|
||||
var retrievedReference = agent.GetService<AgentReference>();
|
||||
|
||||
// Assert
|
||||
@@ -2486,7 +2486,7 @@ public sealed class AzureAIProjectChatClientExtensionsTests
|
||||
AgentVersion agentVersion = this.CreateTestAgentVersion();
|
||||
|
||||
// Act
|
||||
var agent = client.GetAIAgent(agentVersion);
|
||||
var agent = client.AsAIAgent(agentVersion);
|
||||
var retrievedReference = agent.GetService<AgentReference>();
|
||||
|
||||
// Assert
|
||||
|
||||
@@ -53,7 +53,7 @@ public class AzureAIProjectChatClientTests
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await agent.RunAsync("Hello", thread);
|
||||
|
||||
Assert.True(requestTriggered);
|
||||
@@ -102,7 +102,7 @@ public class AzureAIProjectChatClientTests
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await agent.RunAsync("Hello", thread, options: new ChatClientAgentRunOptions() { ChatOptions = new() { ConversationId = "conv_12345" } });
|
||||
|
||||
Assert.True(requestTriggered);
|
||||
@@ -151,7 +151,7 @@ public class AzureAIProjectChatClientTests
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await agent.RunAsync("Hello", thread, options: new ChatClientAgentRunOptions() { ChatOptions = new() { ConversationId = "conv_12345" } });
|
||||
|
||||
Assert.True(requestTriggered);
|
||||
@@ -200,7 +200,7 @@ public class AzureAIProjectChatClientTests
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
await agent.RunAsync("Hello", thread, options: new ChatClientAgentRunOptions() { ChatOptions = new() { ConversationId = "resp_0888a" } });
|
||||
|
||||
Assert.True(requestTriggered);
|
||||
|
||||
+4
-4
@@ -66,22 +66,22 @@ public sealed class AggregatorPromptAgentFactoryTests
|
||||
|
||||
private sealed class TestAgent : AIAgent
|
||||
{
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ public sealed class AgentEntityTests(ITestOutputHelper outputHelper) : IDisposab
|
||||
public async Task EntityNamePrefixAsync()
|
||||
{
|
||||
// Setup
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "TestAgent",
|
||||
instructions: "You are a helpful assistant that always responds with a friendly greeting."
|
||||
);
|
||||
@@ -51,7 +51,7 @@ public sealed class AgentEntityTests(ITestOutputHelper outputHelper) : IDisposab
|
||||
// A proxy agent is needed to call the hosted test agent
|
||||
AIAgent simpleAgentProxy = simpleAgent.AsDurableAgentProxy(testHelper.Services);
|
||||
|
||||
AgentThread thread = simpleAgentProxy.GetNewThread();
|
||||
AgentThread thread = await simpleAgentProxy.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
|
||||
DurableTaskClient client = testHelper.GetClient();
|
||||
|
||||
@@ -88,7 +88,7 @@ public sealed class AgentEntityTests(ITestOutputHelper outputHelper) : IDisposab
|
||||
public async Task RunAgentMethodNamesAllWorkAsync(string runAgentMethodName)
|
||||
{
|
||||
// Setup
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "TestAgent",
|
||||
instructions: "You are a helpful assistant that always responds with a friendly greeting."
|
||||
);
|
||||
@@ -98,7 +98,7 @@ public sealed class AgentEntityTests(ITestOutputHelper outputHelper) : IDisposab
|
||||
// A proxy agent is needed to call the hosted test agent
|
||||
AIAgent simpleAgentProxy = simpleAgent.AsDurableAgentProxy(testHelper.Services);
|
||||
|
||||
AgentThread thread = simpleAgentProxy.GetNewThread();
|
||||
AgentThread thread = await simpleAgentProxy.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
|
||||
DurableTaskClient client = testHelper.GetClient();
|
||||
|
||||
@@ -143,7 +143,7 @@ public sealed class AgentEntityTests(ITestOutputHelper outputHelper) : IDisposab
|
||||
public async Task OrchestrationIdSetDuringOrchestrationAsync()
|
||||
{
|
||||
// Arrange
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "TestAgent",
|
||||
instructions: "You are a helpful assistant that always responds with a friendly greeting."
|
||||
);
|
||||
@@ -184,7 +184,7 @@ public sealed class AgentEntityTests(ITestOutputHelper outputHelper) : IDisposab
|
||||
public override async Task<string> RunAsync(TaskOrchestrationContext context, string input)
|
||||
{
|
||||
DurableAIAgent writer = context.GetAgent("TestAgent");
|
||||
AgentThread writerThread = writer.GetNewThread();
|
||||
AgentThread writerThread = await writer.GetNewThreadAsync();
|
||||
|
||||
await writer.RunAsync(
|
||||
message: context.GetInput<string>()!,
|
||||
|
||||
+13
-13
@@ -41,7 +41,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
public async Task SimplePromptAsync()
|
||||
{
|
||||
// Setup
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
instructions: "You are a helpful assistant that always responds with a friendly greeting.",
|
||||
name: "TestAgent");
|
||||
|
||||
@@ -51,13 +51,13 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
AIAgent simpleAgentProxy = simpleAgent.AsDurableAgentProxy(testHelper.Services);
|
||||
|
||||
// Act: send a prompt to the agent and wait for a response
|
||||
AgentThread thread = simpleAgentProxy.GetNewThread();
|
||||
AgentThread thread = await simpleAgentProxy.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
await simpleAgentProxy.RunAsync(
|
||||
message: "Hello!",
|
||||
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);
|
||||
@@ -94,7 +94,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
return isSunny ? "Pack sunglasses and sunscreen." : "Pack a raincoat and umbrella.";
|
||||
}
|
||||
|
||||
AIAgent tripPlanningAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent tripPlanningAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
instructions: "You are a trip planning assistant. Use the weather tool and packing list tool as needed.",
|
||||
name: "TripPlanningAgent",
|
||||
description: "An agent to help plan your day trips",
|
||||
@@ -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);
|
||||
|
||||
@@ -156,13 +156,13 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
{
|
||||
// 1. Get agent and create a session
|
||||
DurableAIAgent agent = context.GetAgent("SimpleAgent");
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
|
||||
// 2. Call an agent and tell it my name
|
||||
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;
|
||||
}
|
||||
@@ -174,7 +174,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
// This is the agent that will be used to start the workflow
|
||||
agents.AddAIAgentFactory(
|
||||
"WorkflowAgent",
|
||||
sp => TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
sp => TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "WorkflowAgent",
|
||||
instructions: "You can start greeting workflows and check their status.",
|
||||
services: sp,
|
||||
@@ -184,7 +184,7 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
]));
|
||||
|
||||
// This is the agent that will be called by the workflow
|
||||
agents.AddAIAgent(TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
agents.AddAIAgent(TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "SimpleAgent",
|
||||
instructions: "You are a simple assistant."
|
||||
));
|
||||
@@ -194,14 +194,14 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
AIAgent workflowManagerAgentProxy = testHelper.Services.GetDurableAgentProxy("WorkflowAgent");
|
||||
|
||||
// Act: send a prompt to the agent
|
||||
AgentThread thread = workflowManagerAgentProxy.GetNewThread();
|
||||
AgentThread thread = await workflowManagerAgentProxy.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
await workflowManagerAgentProxy.RunAsync(
|
||||
message: "Start a greeting workflow for \"John Doe\".",
|
||||
thread,
|
||||
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);
|
||||
@@ -217,14 +217,14 @@ public sealed class ExternalClientTests(ITestOutputHelper outputHelper) : IDispo
|
||||
public void AsDurableAgentProxy_ThrowsWhenAgentNotRegistered()
|
||||
{
|
||||
// Setup: Register one agent but try to use a different one
|
||||
AIAgent registeredAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent registeredAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
instructions: "You are a helpful assistant.",
|
||||
name: "RegisteredAgent");
|
||||
|
||||
using TestHelper testHelper = TestHelper.Start([registeredAgent], this._outputHelper);
|
||||
|
||||
// Create an agent with a different name that isn't registered
|
||||
AIAgent unregisteredAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent unregisteredAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
instructions: "You are a helpful assistant.",
|
||||
name: "UnregisteredAgent");
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ public sealed class OrchestrationTests(ITestOutputHelper outputHelper) : IDispos
|
||||
// Register a different agent, but not "NonExistentAgent"
|
||||
agents.AddAIAgentFactory(
|
||||
"OtherAgent",
|
||||
sp => TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
sp => TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "OtherAgent",
|
||||
instructions: "You are a test agent."));
|
||||
},
|
||||
|
||||
@@ -40,7 +40,7 @@ public sealed class TimeToLiveTests(ITestOutputHelper outputHelper) : IDisposabl
|
||||
{
|
||||
// Arrange: Create agent with short TTL (10 seconds)
|
||||
TimeSpan ttl = TimeSpan.FromSeconds(10);
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "TTLTestAgent",
|
||||
instructions: "You are a helpful assistant."
|
||||
);
|
||||
@@ -55,7 +55,7 @@ public sealed class TimeToLiveTests(ITestOutputHelper outputHelper) : IDisposabl
|
||||
});
|
||||
|
||||
AIAgent agentProxy = simpleAgent.AsDurableAgentProxy(testHelper.Services);
|
||||
AgentThread thread = agentProxy.GetNewThread();
|
||||
AgentThread thread = await agentProxy.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
DurableTaskClient client = testHelper.GetClient();
|
||||
AgentSessionId sessionId = thread.GetService<AgentSessionId>();
|
||||
|
||||
@@ -105,7 +105,7 @@ public sealed class TimeToLiveTests(ITestOutputHelper outputHelper) : IDisposabl
|
||||
{
|
||||
// Arrange: Create agent with short TTL
|
||||
TimeSpan ttl = TimeSpan.FromSeconds(6);
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).CreateAIAgent(
|
||||
AIAgent simpleAgent = TestHelper.GetAzureOpenAIChatClient(s_configuration).AsAIAgent(
|
||||
name: "TTLResetTestAgent",
|
||||
instructions: "You are a helpful assistant."
|
||||
);
|
||||
@@ -120,7 +120,7 @@ public sealed class TimeToLiveTests(ITestOutputHelper outputHelper) : IDisposabl
|
||||
});
|
||||
|
||||
AIAgent agentProxy = simpleAgent.AsDurableAgentProxy(testHelper.Services);
|
||||
AgentThread thread = agentProxy.GetNewThread();
|
||||
AgentThread thread = await agentProxy.GetNewThreadAsync(this.TestTimeoutToken);
|
||||
DurableTaskClient client = testHelper.GetClient();
|
||||
AgentSessionId sessionId = thread.GetService<AgentSessionId>();
|
||||
|
||||
|
||||
@@ -77,7 +77,9 @@ public sealed class A2AIntegrationTests
|
||||
Assert.NotNull(url);
|
||||
Assert.NotEmpty(url);
|
||||
Assert.StartsWith("http", url, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Equal($"{testServer.BaseAddress.ToString().TrimEnd('/')}/a2a/test-agent/v1/card", url);
|
||||
|
||||
// agentCard's URL matches the agent endpoint
|
||||
Assert.Equal($"{testServer.BaseAddress.ToString().TrimEnd('/')}/a2a/test-agent", url);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -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 = []
|
||||
};
|
||||
@@ -175,29 +175,29 @@ public sealed class AIAgentExtensionsTests
|
||||
{
|
||||
Mock<AIAgent> agentMock = new() { CallBase = true };
|
||||
agentMock.SetupGet(x => x.Name).Returns("TestAgent");
|
||||
agentMock.Setup(x => x.GetNewThread()).Returns(new TestAgentThread());
|
||||
agentMock.Setup(x => x.GetNewThreadAsync()).ReturnsAsync(new TestAgentThread());
|
||||
agentMock
|
||||
.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
ItExpr.IsAny<CancellationToken>())
|
||||
.Callback<IEnumerable<ChatMessage>, 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<AIAgent> CreateAgentMockWithResponse(AgentRunResponse response)
|
||||
private static Mock<AIAgent> CreateAgentMockWithResponse(AgentResponse response)
|
||||
{
|
||||
Mock<AIAgent> agentMock = new() { CallBase = true };
|
||||
agentMock.SetupGet(x => x.Name).Returns("TestAgent");
|
||||
agentMock.Setup(x => x.GetNewThread()).Returns(new TestAgentThread());
|
||||
agentMock.Setup(x => x.GetNewThreadAsync()).ReturnsAsync(new TestAgentThread());
|
||||
agentMock
|
||||
.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
|
||||
+55
-63
@@ -30,14 +30,14 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
// Arrange
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "hello");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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!");
|
||||
@@ -61,14 +61,14 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
// Arrange
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "test");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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<AgentRunResponseUpdate> textUpdates = updates.Where(u => !string.IsNullOrEmpty(u.Text)).ToList();
|
||||
List<AgentResponseUpdate> 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);
|
||||
@@ -105,12 +105,12 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
// Arrange
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
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();
|
||||
@@ -124,13 +124,13 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
// Arrange
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread chatClientThread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread chatClientThread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
ChatMessage firstUserMessage = new(ChatRole.User, "First question");
|
||||
|
||||
// Act - First turn
|
||||
List<AgentRunResponseUpdate> firstTurnUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([firstUserMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None))
|
||||
List<AgentResponseUpdate> 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<AgentRunResponseUpdate> secondTurnUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([secondUserMessage], chatClientThread, new AgentRunOptions(), CancellationToken.None))
|
||||
List<AgentResponseUpdate> 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!");
|
||||
@@ -168,20 +168,20 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
// Arrange
|
||||
await this.SetupTestServerAsync(useMultiMessageAgent: true);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread chatClientThread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread chatClientThread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Tell me a story");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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<AgentRunResponseUpdate> textUpdates = updates.Where(u => !string.IsNullOrEmpty(u.Text)).ToList();
|
||||
List<AgentResponseUpdate> 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));
|
||||
}
|
||||
@@ -200,8 +200,8 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
// Arrange
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread chatClientThread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread chatClientThread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
// Multiple user messages sent in one turn
|
||||
ChatMessage[] userMessages =
|
||||
@@ -211,10 +211,10 @@ public sealed class BasicStreamingTests : IAsyncDisposable
|
||||
new ChatMessage(ChatRole.User, "Third part of question")
|
||||
];
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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!");
|
||||
@@ -280,32 +280,28 @@ internal sealed class FakeChatClientAgent : AIAgent
|
||||
|
||||
public override string? Description => "A fake agent for testing";
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
{
|
||||
return new FakeInMemoryAgentThread();
|
||||
}
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions));
|
||||
|
||||
protected override async Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override async Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
await foreach (AgentRunResponseUpdate update in this.RunStreamingAsync(messages, thread, options, cancellationToken).ConfigureAwait(false))
|
||||
List<AgentResponseUpdate> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
@@ -316,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,
|
||||
@@ -348,32 +344,28 @@ internal sealed class FakeMultiMessageAgent : AIAgent
|
||||
|
||||
public override string? Description => "A fake agent that sends multiple messages for testing";
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
{
|
||||
return new FakeInMemoryAgentThread();
|
||||
}
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions));
|
||||
|
||||
protected override async Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override async Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
await foreach (AgentRunResponseUpdate update in this.RunStreamingAsync(messages, thread, options, cancellationToken).ConfigureAwait(false))
|
||||
List<AgentResponseUpdate> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
@@ -383,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,
|
||||
@@ -397,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,
|
||||
@@ -411,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,
|
||||
|
||||
+8
-9
@@ -303,12 +303,12 @@ internal sealed class FakeForwardedPropsAgent : AIAgent
|
||||
|
||||
public JsonElement ReceivedForwardedProperties { get; private set; }
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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,
|
||||
@@ -334,12 +334,11 @@ internal sealed class FakeForwardedPropsAgent : AIAgent
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread() => new FakeInMemoryAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions));
|
||||
|
||||
private sealed class FakeInMemoryAgentThread : InMemoryAgentThread
|
||||
{
|
||||
|
||||
+43
-44
@@ -33,8 +33,8 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
@@ -42,10 +42,10 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "update state");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
@@ -76,8 +76,8 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
@@ -85,16 +85,16 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "process");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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();
|
||||
@@ -118,8 +118,8 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(complexState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
@@ -127,16 +127,16 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "process complex state");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
@@ -158,8 +158,8 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
@@ -167,16 +167,16 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "increment");
|
||||
|
||||
List<AgentRunResponseUpdate> firstRoundUpdates = [];
|
||||
List<AgentResponseUpdate> 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<DataContent>().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<AgentRunResponseUpdate> secondRoundUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([secondUserMessage, secondStateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
List<AgentResponseUpdate> 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<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
@@ -209,15 +209,15 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
ChatMessage userMessage = new(ChatRole.User, "hello");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -242,8 +242,8 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(emptyState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
@@ -251,10 +251,10 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "hello");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -279,8 +279,8 @@ public sealed class SharedStateTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)await agent.GetNewThreadAsync();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
@@ -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<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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,
|
||||
@@ -417,12 +417,11 @@ internal sealed class FakeStateAgent : AIAgent
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread() => new FakeInMemoryAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions));
|
||||
|
||||
private sealed class FakeInMemoryAgentThread : InMemoryAgentThread
|
||||
{
|
||||
|
||||
+37
-37
@@ -44,14 +44,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(serverTools: [serverTool]);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Call the server function");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -92,14 +92,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(serverTools: [getWeatherTool, getTimeTool]);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "What's the weather and time?");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -133,14 +133,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [clientTool]);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [clientTool]);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Call the client function");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -181,14 +181,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [calculateTool, formatTool]);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [calculateTool, formatTool]);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Calculate 5 + 3 and format 'hello'");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -232,14 +232,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(serverTools: [serverTool]);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [clientTool]);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [clientTool]);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Get both server and client data");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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");
|
||||
@@ -297,14 +297,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(serverTools: [testTool]);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Call the test function");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -341,14 +341,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(serverTools: [func1, func2], triggerParallelCalls: true);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Call both functions in parallel");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -427,14 +427,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync(serverTools: [serverTool], jsonSerializerOptions: ServerJsonContext.Default.Options);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null, ServerJsonContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: []);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Get server forecast for Seattle for 5 days");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -473,14 +473,14 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
|
||||
await this.SetupTestServerAsync();
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null, ClientJsonContext.Default.Options);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [clientTool]);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Test assistant", tools: [clientTool]);
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage userMessage = new(ChatRole.User, "Get client forecast for Portland with hourly data");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
List<AgentResponseUpdate> 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);
|
||||
}
|
||||
@@ -518,7 +518,7 @@ public sealed class ToolCallingTests : IAsyncDisposable
|
||||
this._app = builder.Build();
|
||||
// FakeChatClient will receive options.Tools containing both server and client tools (merged by framework)
|
||||
var fakeChatClient = new FakeToolCallingChatClient(triggerParallelCalls, this._output, jsonSerializerOptions: jsonSerializerOptions);
|
||||
AIAgent baseAgent = fakeChatClient.CreateAIAgent(instructions: null, name: "base-agent", description: "A base agent for tool testing", tools: serverTools ?? []);
|
||||
AIAgent baseAgent = fakeChatClient.AsAIAgent(instructions: null, name: "base-agent", description: "A base agent for tool testing", tools: serverTools ?? []);
|
||||
this._app.MapAGUI("/agent", baseAgent);
|
||||
|
||||
await this._app.StartAsync();
|
||||
|
||||
+16
-14
@@ -425,26 +425,27 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests
|
||||
|
||||
public override string? Description => "Agent that produces multiple text chunks";
|
||||
|
||||
public override AgentThread GetNewThread() => new TestInMemoryAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new TestInMemoryAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions));
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,24 +515,25 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests
|
||||
|
||||
public override string? Description => "Test agent";
|
||||
|
||||
public override AgentThread GetNewThread() => new TestInMemoryAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new TestInMemoryAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions));
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -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<string>? agentIdValues);
|
||||
string? threadId = agentIdValues?.FirstOrDefault();
|
||||
Assert.NotNull(threadId);
|
||||
|
||||
@@ -11,19 +11,19 @@ internal sealed class TestAgent(string name, string description) : AIAgent
|
||||
|
||||
public override string? Description => description;
|
||||
|
||||
public override AgentThread GetNewThread() => new DummyAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) => new(new DummyAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(
|
||||
JsonElement serializedThread,
|
||||
JsonSerializerOptions? jsonSerializerOptions = null) => new DummyAgentThread();
|
||||
JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new DummyAgentThread());
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
|
||||
+149
-14
@@ -2,6 +2,7 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
@@ -17,49 +18,40 @@ public sealed class HostedAgentBuilderToolsExtensionsTests
|
||||
[Fact]
|
||||
public void WithAITool_ThrowsWhenBuilderIsNull()
|
||||
{
|
||||
// Arrange
|
||||
var tool = new DummyAITool();
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => HostedAgentBuilderExtensions.WithAITool(null!, tool));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAITool_ThrowsWhenToolIsNull()
|
||||
{
|
||||
// Arrange
|
||||
var services = new ServiceCollection();
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => builder.WithAITool(null!));
|
||||
Assert.Throws<ArgumentNullException>(() => builder.WithAITool(tool: null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAITools_ThrowsWhenBuilderIsNull()
|
||||
{
|
||||
// Arrange
|
||||
var tools = new[] { new DummyAITool() };
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => HostedAgentBuilderExtensions.WithAITools(null!, tools));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAITools_ThrowsWhenToolsArrayIsNull()
|
||||
{
|
||||
// Arrange
|
||||
var services = new ServiceCollection();
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => builder.WithAITools(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisteredTools_ResolvesAllToolsForAgent()
|
||||
{
|
||||
// Arrange
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IChatClient>(new MockChatClient());
|
||||
|
||||
@@ -73,9 +65,13 @@ public sealed class HostedAgentBuilderToolsExtensionsTests
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
var agent1Tools = ResolveAgentTools(serviceProvider, "test-agent");
|
||||
var agent1Tools = ResolveToolsFromAgent(serviceProvider, "test-agent");
|
||||
Assert.Contains(tool1, agent1Tools);
|
||||
Assert.Contains(tool2, agent1Tools);
|
||||
|
||||
var agent1ToolsDI = ResolveToolsFromDI(serviceProvider, "test-agent");
|
||||
Assert.Contains(tool1, agent1ToolsDI);
|
||||
Assert.Contains(tool2, agent1ToolsDI);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -100,21 +96,160 @@ public sealed class HostedAgentBuilderToolsExtensionsTests
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
var agent1Tools = ResolveAgentTools(serviceProvider, "agent1");
|
||||
var agent2Tools = ResolveAgentTools(serviceProvider, "agent2");
|
||||
var agent1Tools = ResolveToolsFromAgent(serviceProvider, "agent1");
|
||||
var agent2Tools = ResolveToolsFromAgent(serviceProvider, "agent2");
|
||||
|
||||
var agent1ToolsDI = ResolveToolsFromDI(serviceProvider, "agent1");
|
||||
var agent2ToolsDI = ResolveToolsFromDI(serviceProvider, "agent2");
|
||||
|
||||
Assert.Contains(tool1, agent1Tools);
|
||||
Assert.Contains(tool2, agent1Tools);
|
||||
Assert.Contains(tool1, agent1ToolsDI);
|
||||
Assert.Contains(tool2, agent1ToolsDI);
|
||||
|
||||
Assert.Contains(tool3, agent2Tools);
|
||||
Assert.Contains(tool3, agent2ToolsDI);
|
||||
}
|
||||
|
||||
private static IList<AITool> ResolveAgentTools(IServiceProvider serviceProvider, string name)
|
||||
private static IList<AITool> ResolveToolsFromAgent(IServiceProvider serviceProvider, string name)
|
||||
{
|
||||
var agent = serviceProvider.GetRequiredKeyedService<AIAgent>(name) as ChatClientAgent;
|
||||
Assert.NotNull(agent?.ChatOptions?.Tools);
|
||||
return agent.ChatOptions.Tools;
|
||||
}
|
||||
|
||||
private static List<AITool> ResolveToolsFromDI(IServiceProvider serviceProvider, string name)
|
||||
{
|
||||
var tools = serviceProvider.GetKeyedServices<AITool>(name);
|
||||
Assert.NotNull(tools);
|
||||
return tools.ToList();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_ThrowsWhenBuilderIsNull()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() => HostedAgentBuilderExtensions.WithAITool(null!, CreateTool));
|
||||
|
||||
static AITool CreateTool(IServiceProvider _) => new DummyAITool();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_ThrowsWhenFactoryIsNull()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
|
||||
Assert.Throws<ArgumentNullException>(() => builder.WithAITool(factory: null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_RegistersToolFromFactory()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IChatClient>(new MockChatClient());
|
||||
|
||||
DummyAITool? createdTool = null;
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
builder.WithAITool(sp =>
|
||||
{
|
||||
createdTool = new DummyAITool();
|
||||
return createdTool;
|
||||
});
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
var tools = ResolveToolsFromDI(serviceProvider, "test-agent");
|
||||
|
||||
Assert.Single(tools);
|
||||
Assert.Same(createdTool, tools[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_CanAccessServicesFromFactory()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
var mockChatClient = new MockChatClient();
|
||||
services.AddSingleton<IChatClient>(mockChatClient);
|
||||
|
||||
IChatClient? resolvedChatClient = null;
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
builder.WithAITool(sp =>
|
||||
{
|
||||
resolvedChatClient = sp.GetService<IChatClient>();
|
||||
return new DummyAITool();
|
||||
});
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
_ = ResolveToolsFromDI(serviceProvider, "test-agent");
|
||||
|
||||
Assert.Same(mockChatClient, resolvedChatClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_ToolsAreIsolatedPerAgent()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IChatClient>(new MockChatClient());
|
||||
|
||||
var tool1 = new DummyAITool();
|
||||
var tool2 = new DummyAITool();
|
||||
|
||||
var builder1 = services.AddAIAgent("agent1", "Agent 1 instructions");
|
||||
var builder2 = services.AddAIAgent("agent2", "Agent 2 instructions");
|
||||
|
||||
builder1.WithAITool(_ => tool1);
|
||||
builder2.WithAITool(_ => tool2);
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
var agent1Tools = ResolveToolsFromDI(serviceProvider, "agent1");
|
||||
var agent2Tools = ResolveToolsFromDI(serviceProvider, "agent2");
|
||||
|
||||
Assert.Single(agent1Tools);
|
||||
Assert.Contains(tool1, agent1Tools);
|
||||
Assert.DoesNotContain(tool2, agent1Tools);
|
||||
|
||||
Assert.Single(agent2Tools);
|
||||
Assert.Contains(tool2, agent2Tools);
|
||||
Assert.DoesNotContain(tool1, agent2Tools);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_CanCombineWithDirectToolRegistration()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IChatClient>(new MockChatClient());
|
||||
|
||||
var directTool = new DummyAITool();
|
||||
var factoryTool = new DummyAITool();
|
||||
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
builder
|
||||
.WithAITool(directTool)
|
||||
.WithAITool(_ => factoryTool);
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
var tools = ResolveToolsFromDI(serviceProvider, "test-agent");
|
||||
|
||||
Assert.Equal(2, tools.Count);
|
||||
Assert.Contains(directTool, tools);
|
||||
Assert.Contains(factoryTool, tools);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAIToolFactory_ToolsAvailableOnAgent()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IChatClient>(new MockChatClient());
|
||||
|
||||
var factoryTool = new DummyAITool();
|
||||
var builder = services.AddAIAgent("test-agent", "Test instructions");
|
||||
builder.WithAITool(_ => factoryTool);
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
var agentTools = ResolveToolsFromAgent(serviceProvider, "test-agent");
|
||||
|
||||
Assert.Contains(factoryTool, agentTools);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dummy AITool implementation for testing.
|
||||
/// </summary>
|
||||
|
||||
+6
-6
@@ -78,12 +78,12 @@ public sealed class AIAgentWithOpenAIExtensionsTests
|
||||
|
||||
mockAgent
|
||||
.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
ItExpr.IsAny<CancellationToken>())
|
||||
.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<AgentRunResponseUpdate>
|
||||
var responseUpdates = new List<AgentResponseUpdate>
|
||||
{
|
||||
new(ChatRole.Assistant, ResponseText1),
|
||||
new(ChatRole.Assistant, ResponseText2)
|
||||
@@ -168,7 +168,7 @@ public sealed class AIAgentWithOpenAIExtensionsTests
|
||||
|
||||
mockAgent
|
||||
.Protected()
|
||||
.Setup<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -199,9 +199,9 @@ public sealed class AIAgentWithOpenAIExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method to convert a list of AgentRunResponseUpdate to an async enumerable.
|
||||
/// Helper method to convert a list of AgentResponseUpdate to an async enumerable.
|
||||
/// </summary>
|
||||
private static async IAsyncEnumerable<AgentRunResponseUpdate> ToAsyncEnumerableAsync(IEnumerable<AgentRunResponseUpdate> updates)
|
||||
private static async IAsyncEnumerable<AgentResponseUpdate> ToAsyncEnumerableAsync(IEnumerable<AgentResponseUpdate> updates)
|
||||
{
|
||||
foreach (var update in updates)
|
||||
{
|
||||
|
||||
+24
-24
@@ -210,10 +210,10 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with ClientResult and options works correctly.
|
||||
/// Verify that AsAIAgent with ClientResult and options works correctly.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithClientResultAndOptions_WorksCorrectly()
|
||||
public void AsAIAgent_WithClientResultAndOptions_WorksCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -228,7 +228,7 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = assistantClient.GetAIAgent(clientResult, options);
|
||||
var agent = assistantClient.AsAIAgent(clientResult, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -238,10 +238,10 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with Assistant and options works correctly.
|
||||
/// Verify that AsAIAgent with Assistant and options works correctly.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAssistantAndOptions_WorksCorrectly()
|
||||
public void AsAIAgent_WithAssistantAndOptions_WorksCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -255,7 +255,7 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = assistantClient.GetAIAgent(assistant, options);
|
||||
var agent = assistantClient.AsAIAgent(assistant, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -265,10 +265,10 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with Assistant and options falls back to assistant metadata when options are null.
|
||||
/// Verify that AsAIAgent with Assistant and options falls back to assistant metadata when options are null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithAssistantAndOptionsWithNullFields_FallsBackToAssistantMetadata()
|
||||
public void AsAIAgent_WithAssistantAndOptionsWithNullFields_FallsBackToAssistantMetadata()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -277,7 +277,7 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
var options = new ChatClientAgentOptions(); // Empty options
|
||||
|
||||
// Act
|
||||
var agent = assistantClient.GetAIAgent(assistant, options);
|
||||
var agent = assistantClient.AsAIAgent(assistant, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -341,10 +341,10 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with clientFactory parameter correctly applies the factory.
|
||||
/// Verify that AsAIAgent with clientFactory parameter correctly applies the factory.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithClientFactory_AppliesFactoryCorrectly()
|
||||
public void AsAIAgent_WithClientFactory_AppliesFactoryCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -357,7 +357,7 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = assistantClient.GetAIAgent(
|
||||
var agent = assistantClient.AsAIAgent(
|
||||
assistant,
|
||||
options,
|
||||
clientFactory: (innerClient) => testChatClient);
|
||||
@@ -373,10 +373,10 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when assistantClientResult is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when assistantClientResult is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithNullClientResult_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithNullClientResult_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -384,16 +384,16 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
assistantClient.GetAIAgent((ClientResult<Assistant>)null!, options));
|
||||
assistantClient.AsAIAgent(null!, options));
|
||||
|
||||
Assert.Equal("assistantClientResult", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when assistant is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when assistant is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithNullAssistant_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithNullAssistant_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -401,16 +401,16 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
assistantClient.GetAIAgent((Assistant)null!, options));
|
||||
assistantClient.AsAIAgent((Assistant)null!, options));
|
||||
|
||||
Assert.Equal("assistantMetadata", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent throws ArgumentNullException when options is null.
|
||||
/// Verify that AsAIAgent throws ArgumentNullException when options is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithNullOptions_ThrowsArgumentNullException()
|
||||
public void AsAIAgent_WithNullOptions_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -418,7 +418,7 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
assistantClient.GetAIAgent(assistant, (ChatClientAgentOptions)null!));
|
||||
assistantClient.AsAIAgent(assistant, (ChatClientAgentOptions)null!));
|
||||
|
||||
Assert.Equal("options", exception.ParamName);
|
||||
}
|
||||
@@ -518,10 +518,10 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that GetAIAgent with services parameter correctly passes it through to the ChatClientAgent.
|
||||
/// Verify that AsAIAgent with services parameter correctly passes it through to the ChatClientAgent.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void GetAIAgent_WithServices_PassesServicesToAgent()
|
||||
public void AsAIAgent_WithServices_PassesServicesToAgent()
|
||||
{
|
||||
// Arrange
|
||||
var assistantClient = new TestAssistantClient();
|
||||
@@ -529,7 +529,7 @@ public sealed class OpenAIAssistantClientExtensionsTests
|
||||
var assistant = ModelReaderWriter.Read<Assistant>(BinaryData.FromString("""{"id": "asst_abc123", "name": "Test Agent"}"""))!;
|
||||
|
||||
// Act
|
||||
var agent = assistantClient.GetAIAgent(assistant, services: serviceProvider);
|
||||
var agent = assistantClient.AsAIAgent(assistant, services: serviceProvider);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
|
||||
+7
-7
@@ -76,7 +76,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
var testChatClient = new TestChatClient(chatClient.AsIChatClient());
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
description: "Test description",
|
||||
@@ -104,7 +104,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
TestChatClient? testChatClient = null;
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
clientFactory: (innerClient) =>
|
||||
innerClient.AsBuilder().Use((innerClient) => testChatClient = new TestChatClient(innerClient)).Build());
|
||||
@@ -135,7 +135,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
options,
|
||||
clientFactory: (innerClient) => testChatClient);
|
||||
|
||||
@@ -160,7 +160,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
var chatClient = new TestOpenAIChatClient();
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent");
|
||||
|
||||
@@ -183,7 +183,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
var chatClient = new TestOpenAIChatClient();
|
||||
|
||||
// Act
|
||||
var agent = chatClient.CreateAIAgent(
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
clientFactory: null);
|
||||
@@ -205,7 +205,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
{
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
((OpenAIChatClient)null!).CreateAIAgent());
|
||||
((OpenAIChatClient)null!).AsAIAgent());
|
||||
|
||||
Assert.Equal("client", exception.ParamName);
|
||||
}
|
||||
@@ -221,7 +221,7 @@ public sealed class OpenAIChatClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
chatClient.CreateAIAgent((ChatClientAgentOptions)null!));
|
||||
chatClient.AsAIAgent((ChatClientAgentOptions)null!));
|
||||
|
||||
Assert.Equal("options", exception.ParamName);
|
||||
}
|
||||
|
||||
+8
-8
@@ -75,7 +75,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
var testChatClient = new TestChatClient(responseClient.AsIChatClient());
|
||||
|
||||
// Act
|
||||
var agent = responseClient.CreateAIAgent(
|
||||
var agent = responseClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
description: "Test description",
|
||||
@@ -102,7 +102,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
var responseClient = new TestOpenAIResponseClient();
|
||||
|
||||
// Act
|
||||
var agent = responseClient.CreateAIAgent(
|
||||
var agent = responseClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent");
|
||||
|
||||
@@ -125,7 +125,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
var responseClient = new TestOpenAIResponseClient();
|
||||
|
||||
// Act
|
||||
var agent = responseClient.CreateAIAgent(
|
||||
var agent = responseClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
clientFactory: null);
|
||||
@@ -147,7 +147,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
{
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
((ResponsesClient)null!).CreateAIAgent());
|
||||
((ResponsesClient)null!).AsAIAgent());
|
||||
|
||||
Assert.Equal("client", exception.ParamName);
|
||||
}
|
||||
@@ -163,7 +163,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(() =>
|
||||
responseClient.CreateAIAgent((ChatClientAgentOptions)null!));
|
||||
responseClient.AsAIAgent((ChatClientAgentOptions)null!));
|
||||
|
||||
Assert.Equal("options", exception.ParamName);
|
||||
}
|
||||
@@ -179,7 +179,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
var serviceProvider = new TestServiceProvider();
|
||||
|
||||
// Act
|
||||
var agent = responseClient.CreateAIAgent(
|
||||
var agent = responseClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
services: serviceProvider);
|
||||
@@ -211,7 +211,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = responseClient.CreateAIAgent(options, services: serviceProvider);
|
||||
var agent = responseClient.AsAIAgent(options, services: serviceProvider);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -237,7 +237,7 @@ public sealed class OpenAIResponseClientExtensionsTests
|
||||
var testChatClient = new TestChatClient(responseClient.AsIChatClient());
|
||||
|
||||
// Act
|
||||
var agent = responseClient.CreateAIAgent(
|
||||
var agent = responseClient.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "Test Agent",
|
||||
clientFactory: (innerClient) => testChatClient,
|
||||
|
||||
@@ -296,10 +296,10 @@ public sealed class PurviewWrapperTests : IDisposable
|
||||
new(ChatRole.User, "Test message")
|
||||
};
|
||||
var mockAgent = new Mock<AIAgent>();
|
||||
var innerResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Sensitive response"));
|
||||
var innerResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Sensitive response"));
|
||||
|
||||
mockAgent.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread>(),
|
||||
ItExpr.IsAny<AgentRunOptions>(),
|
||||
@@ -335,10 +335,10 @@ public sealed class PurviewWrapperTests : IDisposable
|
||||
new(ChatRole.User, "Test message")
|
||||
};
|
||||
var mockAgent = new Mock<AIAgent>();
|
||||
var innerResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Safe response"));
|
||||
var innerResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Safe response"));
|
||||
|
||||
mockAgent.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread>(),
|
||||
ItExpr.IsAny<AgentRunOptions>(),
|
||||
@@ -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<AIAgent>();
|
||||
mockAgent.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread>(),
|
||||
ItExpr.IsAny<AgentRunOptions>(),
|
||||
@@ -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<AIAgent>();
|
||||
mockAgent.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread>(),
|
||||
ItExpr.IsAny<AgentRunOptions>(),
|
||||
@@ -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<AIAgent>();
|
||||
mockAgent.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread>(),
|
||||
ItExpr.IsAny<AgentRunOptions>(),
|
||||
@@ -527,10 +527,10 @@ public sealed class PurviewWrapperTests : IDisposable
|
||||
new(ChatRole.User, "Test message")
|
||||
};
|
||||
var mockAgent = new Mock<AIAgent>();
|
||||
var innerResponse = new AgentRunResponse(new ChatMessage(ChatRole.Assistant, "Response"));
|
||||
var innerResponse = new AgentResponse(new ChatMessage(ChatRole.Assistant, "Response"));
|
||||
|
||||
mockAgent.Protected()
|
||||
.Setup<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread>(),
|
||||
ItExpr.IsAny<AgentRunOptions>(),
|
||||
|
||||
@@ -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<AnonymousDelegatingAIAgent>(result);
|
||||
@@ -393,7 +393,7 @@ public class AIAgentBuilderTests
|
||||
var builder = new AIAgentBuilder(mockAgent.Object);
|
||||
|
||||
// Act
|
||||
var result = builder.Use(null, (_, _, _, _, _) => AsyncEnumerable.Empty<AgentRunResponseUpdate>()).Build();
|
||||
var result = builder.Use(null, (_, _, _, _, _) => AsyncEnumerable.Empty<AgentResponseUpdate>()).Build();
|
||||
|
||||
// Assert
|
||||
Assert.IsType<AnonymousDelegatingAIAgent>(result);
|
||||
@@ -411,8 +411,8 @@ public class AIAgentBuilderTests
|
||||
|
||||
// Act
|
||||
var result = builder.Use(
|
||||
(_, _, _, _, _) => Task.FromResult(new AgentRunResponse()),
|
||||
(_, _, _, _, _) => AsyncEnumerable.Empty<AgentRunResponseUpdate>()).Build();
|
||||
(_, _, _, _, _) => Task.FromResult(new AgentResponse()),
|
||||
(_, _, _, _, _) => AsyncEnumerable.Empty<AgentResponseUpdate>()).Build();
|
||||
|
||||
// Assert
|
||||
Assert.IsType<AnonymousDelegatingAIAgent>(result);
|
||||
|
||||
@@ -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
|
||||
/// </summary>
|
||||
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;
|
||||
@@ -324,10 +324,10 @@ public class AgentExtensionsTests
|
||||
this._exceptionToThrow = exceptionToThrow;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override string? Name { get; }
|
||||
@@ -337,7 +337,7 @@ public class AgentExtensionsTests
|
||||
public CancellationToken LastCancellationToken { get; private set; }
|
||||
public int RunAsyncCallCount { get; private set; }
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
@@ -355,14 +355,14 @@ public class AgentExtensionsTests
|
||||
return Task.FromResult(this._responseToReturn!);
|
||||
}
|
||||
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -21,8 +21,8 @@ public class AnonymousDelegatingAIAgentTests
|
||||
private readonly List<ChatMessage> _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<AgentThread>().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<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -47,7 +47,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
|
||||
this._innerAgentMock
|
||||
.Protected()
|
||||
.Setup<IAsyncEnumerable<AgentRunResponseUpdate>>("RunCoreStreamingAsync",
|
||||
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -191,7 +191,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
|
||||
this._innerAgentMock
|
||||
.Protected()
|
||||
.Verify<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Verify<Task<AgentResponse>>("RunCoreAsync",
|
||||
Times.Once(),
|
||||
ItExpr.Is<IEnumerable<ChatMessage>>(m => m == this._testMessages),
|
||||
ItExpr.Is<AgentThread?>(t => t == this._testThread),
|
||||
@@ -441,7 +441,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => 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<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -740,7 +740,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
var runExecutionOrder = new List<string>();
|
||||
var streamingExecutionOrder = new List<string>();
|
||||
|
||||
static async IAsyncEnumerable<AgentRunResponseUpdate> FirstStreamingMiddlewareAsync(
|
||||
static async IAsyncEnumerable<AgentResponseUpdate> FirstStreamingMiddlewareAsync(
|
||||
IEnumerable<ChatMessage> messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken,
|
||||
List<string> executionOrder)
|
||||
@@ -753,7 +753,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
executionOrder.Add("First-Streaming-Post");
|
||||
}
|
||||
|
||||
static async IAsyncEnumerable<AgentRunResponseUpdate> SecondStreamingMiddlewareAsync(
|
||||
static async IAsyncEnumerable<AgentResponseUpdate> SecondStreamingMiddlewareAsync(
|
||||
IEnumerable<ChatMessage> messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken,
|
||||
List<string> executionOrder)
|
||||
@@ -891,7 +891,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
{
|
||||
// Arrange
|
||||
var executionOrder = new List<string>();
|
||||
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<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Setup<Task<AgentResponse>>("RunCoreAsync",
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
ItExpr.IsAny<AgentRunOptions?>(),
|
||||
@@ -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<string>();
|
||||
|
||||
var agent = new AIAgentBuilder(this._innerAgentMock.Object)
|
||||
@@ -1007,7 +1007,7 @@ public class AnonymousDelegatingAIAgentTests
|
||||
// Verify inner agent was never called
|
||||
this._innerAgentMock
|
||||
.Protected()
|
||||
.Verify<Task<AgentRunResponse>>("RunCoreAsync",
|
||||
.Verify<Task<AgentResponse>>("RunCoreAsync",
|
||||
Times.Never(),
|
||||
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
|
||||
ItExpr.IsAny<AgentThread?>(),
|
||||
|
||||
+8
-7
@@ -1,6 +1,8 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Moq;
|
||||
|
||||
@@ -115,12 +117,11 @@ public class ChatClientAgentOptionsTests
|
||||
const string Description = "Test description";
|
||||
var tools = new List<AITool> { AIFunctionFactory.Create(() => "test") };
|
||||
|
||||
static ChatMessageStore ChatMessageStoreFactory(
|
||||
ChatClientAgentOptions.ChatMessageStoreFactoryContext ctx) => new Mock<ChatMessageStore>().Object;
|
||||
static ValueTask<ChatMessageStore> ChatMessageStoreFactoryAsync(
|
||||
ChatClientAgentOptions.ChatMessageStoreFactoryContext ctx, CancellationToken ct) => new(new Mock<ChatMessageStore>().Object);
|
||||
|
||||
static AIContextProvider AIContextProviderFactory(
|
||||
ChatClientAgentOptions.AIContextProviderFactoryContext ctx) =>
|
||||
new Mock<AIContextProvider>().Object;
|
||||
static ValueTask<AIContextProvider> AIContextProviderFactoryAsync(
|
||||
ChatClientAgentOptions.AIContextProviderFactoryContext ctx, CancellationToken ct) => new(new Mock<AIContextProvider>().Object);
|
||||
|
||||
var original = new ChatClientAgentOptions()
|
||||
{
|
||||
@@ -128,8 +129,8 @@ public class ChatClientAgentOptionsTests
|
||||
Description = Description,
|
||||
ChatOptions = new() { Tools = tools },
|
||||
Id = "test-id",
|
||||
ChatMessageStoreFactory = ChatMessageStoreFactory,
|
||||
AIContextProviderFactory = AIContextProviderFactory
|
||||
ChatMessageStoreFactory = ChatMessageStoreFactoryAsync,
|
||||
AIContextProviderFactory = AIContextProviderFactoryAsync
|
||||
};
|
||||
|
||||
// Act
|
||||
|
||||
+2
-2
@@ -143,7 +143,7 @@ public class ChatClientAgentRunOptionsTests
|
||||
var options = new ChatClientAgentRunOptions { ChatClientFactory = ClientFactory };
|
||||
|
||||
// Act
|
||||
var responseUpdates = new List<AgentRunResponseUpdate>();
|
||||
var responseUpdates = new List<AgentResponseUpdate>();
|
||||
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<ChatMessage> { new(ChatRole.User, "Test message") };
|
||||
|
||||
// Act - No ChatClientFactory provided
|
||||
var responseUpdates = new List<AgentRunResponseUpdate>();
|
||||
var responseUpdates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in agent.RunStreamingAsync(messages, null, null, CancellationToken.None))
|
||||
{
|
||||
responseUpdates.Add(update);
|
||||
|
||||
@@ -241,8 +241,8 @@ public partial class ChatClientAgentTests
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { ChatOptions = new() { Instructions = "test instructions" } });
|
||||
|
||||
// Create a thread using the agent's GetNewThread method
|
||||
var thread = agent.GetNewThread();
|
||||
// Create a thread using the agent's GetNewThreadAsync method
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
|
||||
// Act
|
||||
await agent.RunAsync([new(ChatRole.User, "new message")], thread: thread);
|
||||
@@ -438,8 +438,8 @@ public partial class ChatClientAgentTests
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(new InMemoryChatMessageStore());
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, CancellationToken, ValueTask<ChatMessageStore>>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(new InMemoryChatMessageStore());
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "test instructions" },
|
||||
@@ -447,7 +447,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
await agent.RunAsync([new(ChatRole.User, "test")], thread);
|
||||
|
||||
// Assert
|
||||
@@ -455,7 +455,7 @@ public partial class ChatClientAgentTests
|
||||
Assert.Equal(2, messageStore.Count);
|
||||
Assert.Equal("test", messageStore[0].Text);
|
||||
Assert.Equal("response", messageStore[1].Text);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>()), Times.Once);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -477,7 +477,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
await agent.RunAsync([new(ChatRole.User, "test")], thread);
|
||||
|
||||
// Assert
|
||||
@@ -509,8 +509,8 @@ public partial class ChatClientAgentTests
|
||||
It.IsAny<ChatMessageStore.InvokedContext>(),
|
||||
It.IsAny<CancellationToken>())).Returns(new ValueTask());
|
||||
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(mockChatMessageStore.Object);
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, CancellationToken, ValueTask<ChatMessageStore>>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockChatMessageStore.Object);
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
@@ -519,7 +519,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
await agent.RunAsync([new(ChatRole.User, "test")], thread);
|
||||
|
||||
// Assert
|
||||
@@ -538,7 +538,7 @@ public partial class ChatClientAgentTests
|
||||
It.Is<ChatMessageStore.InvokedContext>(x => x.RequestMessages.Count() == 1 && x.ChatMessageStoreMessages.Count() == 1 && x.ResponseMessages!.Count() == 1),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>()), Times.Once);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -557,8 +557,8 @@ public partial class ChatClientAgentTests
|
||||
|
||||
Mock<ChatMessageStore> mockChatMessageStore = new();
|
||||
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(mockChatMessageStore.Object);
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, CancellationToken, ValueTask<ChatMessageStore>>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockChatMessageStore.Object);
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
@@ -567,7 +567,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => agent.RunAsync([new(ChatRole.User, "test")], thread));
|
||||
|
||||
// Assert
|
||||
@@ -576,7 +576,7 @@ public partial class ChatClientAgentTests
|
||||
It.Is<ChatMessageStore.InvokedContext>(x => x.RequestMessages.Count() == 1 && x.ResponseMessages == null && x.InvokeException!.Message == "Test Error"),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>()), Times.Once);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -592,8 +592,8 @@ public partial class ChatClientAgentTests
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]) { ConversationId = "ConvId" });
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(new InMemoryChatMessageStore());
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, CancellationToken, ValueTask<ChatMessageStore>>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(new InMemoryChatMessageStore());
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "test instructions" },
|
||||
@@ -601,7 +601,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act & Assert
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => agent.RunAsync([new(ChatRole.User, "test")], thread));
|
||||
Assert.Equal("Only the ConversationId or MessageStore may be set, but not both and switching from one to another is not supported.", exception.Message);
|
||||
}
|
||||
@@ -649,10 +649,10 @@ public partial class ChatClientAgentTests
|
||||
.Setup(p => p.InvokedAsync(It.IsAny<AIContextProvider.InvokedContext>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(new ValueTask());
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { AIContextProviderFactory = _ => mockProvider.Object, ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] } });
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { AIContextProviderFactory = (_, _) => new(mockProvider.Object), ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] } });
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
var thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
await agent.RunAsync(requestMessages, thread);
|
||||
|
||||
// Assert
|
||||
@@ -711,7 +711,7 @@ public partial class ChatClientAgentTests
|
||||
.Setup(p => p.InvokedAsync(It.IsAny<AIContextProvider.InvokedContext>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(new ValueTask());
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { AIContextProviderFactory = _ => mockProvider.Object, ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] } });
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { AIContextProviderFactory = (_, _) => new(mockProvider.Object), ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] } });
|
||||
|
||||
// Act
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => agent.RunAsync(requestMessages));
|
||||
@@ -757,7 +757,7 @@ public partial class ChatClientAgentTests
|
||||
.Setup(p => p.InvokingAsync(It.IsAny<AIContextProvider.InvokingContext>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new AIContext());
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { AIContextProviderFactory = _ => mockProvider.Object, ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] } });
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { AIContextProviderFactory = (_, _) => new(mockProvider.Object), ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] } });
|
||||
|
||||
// Act
|
||||
await agent.RunAsync([new(ChatRole.User, "user message")]);
|
||||
@@ -801,15 +801,15 @@ public partial class ChatClientAgentTests
|
||||
ChatClientAgent agent = new(mockService.Object, options: new());
|
||||
|
||||
// Act
|
||||
AgentRunResponse<Animal> agentRunResponse = await agent.RunAsync<Animal>(messages: [new(ChatRole.User, "Hello")], serializerOptions: JsonContext2.Default.Options);
|
||||
AgentResponse<Animal> agentResponse = await agent.RunAsync<Animal>(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
|
||||
@@ -1120,433 +1120,6 @@ public partial class ChatClientAgentTests
|
||||
|
||||
#endregion
|
||||
|
||||
#region ChatOptions Merging Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging works when agent has ChatOptions but request doesn't.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesAgentOptionsWhenRequestHasNoneAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions { MaxOutputTokens = 100, Temperature = 0.7f, Instructions = "test instructions" };
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equal(100, capturedChatOptions.MaxOutputTokens);
|
||||
Assert.Equal(0.7f, capturedChatOptions.Temperature);
|
||||
Assert.Equal("test instructions", capturedChatOptions.Instructions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesAgentOptionsConstructorWhenRequestHasNoneAsync()
|
||||
{
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { ChatOptions = new() { Instructions = "test instructions" } });
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equal("test instructions", capturedChatOptions.Instructions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging works when request has ChatOptions but agent doesn't.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesRequestOptionsWhenAgentHasNoneAsync()
|
||||
{
|
||||
// Arrange
|
||||
var requestChatOptions = new ChatOptions { MaxOutputTokens = 200, Temperature = 0.3f, Instructions = "test instructions" };
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object);
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equivalent(requestChatOptions, capturedChatOptions); // Should be the same instance since no merging needed
|
||||
Assert.Equal(200, capturedChatOptions.MaxOutputTokens);
|
||||
Assert.Equal(0.3f, capturedChatOptions.Temperature);
|
||||
Assert.Equal("test instructions", capturedChatOptions.Instructions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging prioritizes request options over agent options.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingPrioritizesRequestOptionsOverAgentOptionsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
MaxOutputTokens = 100,
|
||||
Temperature = 0.7f,
|
||||
TopP = 0.9f,
|
||||
ModelId = "agent-model",
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary { ["key"] = "agent-value" }
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
// TopP and ModelId not set, should use agent values
|
||||
MaxOutputTokens = 200,
|
||||
Temperature = 0.3f,
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary { ["key"] = "request-value" },
|
||||
Instructions = "request instructions"
|
||||
};
|
||||
var expectedChatOptionsMerge = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 200, // Request value takes priority
|
||||
Temperature = 0.3f, // Request value takes priority
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary { ["key"] = "request-value" }, // Request value takes priority
|
||||
TopP = 0.9f, // Agent value used when request doesn't specify
|
||||
ModelId = "agent-model", // Agent value used when request doesn't specify
|
||||
Instructions = "test instructions\nrequest instructions" // Request is in addition to agent instructions
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equivalent(expectedChatOptionsMerge, capturedChatOptions); // Should be the same instance (modified in place)
|
||||
Assert.Equal(200, capturedChatOptions.MaxOutputTokens); // Request value takes priority
|
||||
Assert.Equal(0.3f, capturedChatOptions.Temperature); // Request value takes priority
|
||||
Assert.NotNull(capturedChatOptions.AdditionalProperties);
|
||||
Assert.Equal("request-value", capturedChatOptions.AdditionalProperties["key"]); // Request value takes priority
|
||||
Assert.Equal(0.9f, capturedChatOptions.TopP); // Agent value used when request doesn't specify
|
||||
Assert.Equal("agent-model", capturedChatOptions.ModelId); // Agent value used when request doesn't specify
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging returns null when both agent and request have no ChatOptions.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingReturnsNullWhenBothAgentAndRequestHaveNoneAsync()
|
||||
{
|
||||
// Arrange
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object);
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.Null(capturedChatOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging concatenates Tools from agent and request.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingConcatenatesToolsFromAgentAndRequestAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentTool = AIFunctionFactory.Create(() => "agent tool");
|
||||
var requestTool = AIFunctionFactory.Create(() => "request tool");
|
||||
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
Tools = [agentTool]
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
Tools = [requestTool]
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.NotNull(capturedChatOptions.Tools);
|
||||
Assert.Equal(2, capturedChatOptions.Tools.Count);
|
||||
|
||||
// Request tools should come first, then agent tools
|
||||
Assert.Contains(requestTool, capturedChatOptions.Tools);
|
||||
Assert.Contains(agentTool, capturedChatOptions.Tools);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging uses agent Tools when request has no Tools.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesAgentToolsWhenRequestHasNoToolsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentTool = AIFunctionFactory.Create(() => "agent tool");
|
||||
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
Tools = [agentTool]
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
// No Tools specified
|
||||
MaxOutputTokens = 100
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.NotNull(capturedChatOptions.Tools);
|
||||
Assert.Single(capturedChatOptions.Tools);
|
||||
Assert.Contains(agentTool, capturedChatOptions.Tools); // Should contain the agent's tool
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging uses RawRepresentationFactory from request first, with fallback to agent.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("MockAgentSetting", "MockRequestSetting", "MockRequestSetting")]
|
||||
[InlineData("MockAgentSetting", null, "MockAgentSetting")]
|
||||
[InlineData(null, "MockRequestSetting", "MockRequestSetting")]
|
||||
public async Task ChatOptionsMergingUsesRawRepresentationFactoryWithFallbackAsync(string? agentSetting, string? requestSetting, string expectedSetting)
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
RawRepresentationFactory = _ => agentSetting
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
RawRepresentationFactory = _ => requestSetting
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.NotNull(capturedChatOptions.RawRepresentationFactory);
|
||||
Assert.Equal(expectedSetting, capturedChatOptions.RawRepresentationFactory(null!));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging handles all scalar properties correctly.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingHandlesAllScalarPropertiesCorrectlyAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 100,
|
||||
Temperature = 0.7f,
|
||||
TopP = 0.9f,
|
||||
TopK = 50,
|
||||
PresencePenalty = 0.1f,
|
||||
FrequencyPenalty = 0.2f,
|
||||
Instructions = "agent instructions",
|
||||
ModelId = "agent-model",
|
||||
Seed = 12345,
|
||||
ConversationId = "agent-conversation",
|
||||
AllowMultipleToolCalls = true,
|
||||
StopSequences = ["agent-stop"]
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 200,
|
||||
Temperature = 0.3f,
|
||||
Instructions = "request instructions",
|
||||
|
||||
// Other properties not set, should use agent values
|
||||
StopSequences = ["request-stop"]
|
||||
};
|
||||
|
||||
var expectedChatOptionsMerge = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 200,
|
||||
Temperature = 0.3f,
|
||||
|
||||
// Agent value used when request doesn't specify
|
||||
TopP = 0.9f,
|
||||
TopK = 50,
|
||||
PresencePenalty = 0.1f,
|
||||
FrequencyPenalty = 0.2f,
|
||||
Instructions = "agent instructions\nrequest instructions",
|
||||
ModelId = "agent-model",
|
||||
Seed = 12345,
|
||||
ConversationId = "agent-conversation",
|
||||
AllowMultipleToolCalls = true,
|
||||
|
||||
// Merged StopSequences
|
||||
StopSequences = ["request-stop", "agent-stop"]
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equivalent(expectedChatOptionsMerge, capturedChatOptions); // Should be the equivalent instance (modified in place)
|
||||
|
||||
// Request values should take priority
|
||||
Assert.Equal(200, capturedChatOptions.MaxOutputTokens);
|
||||
Assert.Equal(0.3f, capturedChatOptions.Temperature);
|
||||
|
||||
// Merge StopSequences
|
||||
Assert.Equal(["request-stop", "agent-stop"], capturedChatOptions.StopSequences);
|
||||
|
||||
// Agent values should be used when request doesn't specify
|
||||
Assert.Equal(0.9f, capturedChatOptions.TopP);
|
||||
Assert.Equal(50, capturedChatOptions.TopK);
|
||||
Assert.Equal(0.1f, capturedChatOptions.PresencePenalty);
|
||||
Assert.Equal(0.2f, capturedChatOptions.FrequencyPenalty);
|
||||
Assert.Equal("agent-model", capturedChatOptions.ModelId);
|
||||
Assert.Equal(12345, capturedChatOptions.Seed);
|
||||
Assert.Equal("agent-conversation", capturedChatOptions.ConversationId);
|
||||
Assert.Equal(true, capturedChatOptions.AllowMultipleToolCalls);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetService Method Tests
|
||||
|
||||
/// <summary>
|
||||
@@ -1972,7 +1545,7 @@ public partial class ChatClientAgentTests
|
||||
|
||||
// Act
|
||||
var updates = agent.RunStreamingAsync([new ChatMessage(ChatRole.User, "Hello")]);
|
||||
List<AgentRunResponseUpdate> result = [];
|
||||
List<AgentResponseUpdate> result = [];
|
||||
await foreach (var update in updates)
|
||||
{
|
||||
result.Add(update);
|
||||
@@ -2010,8 +1583,8 @@ public partial class ChatClientAgentTests
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>())).Returns(ToAsyncEnumerableAsync(returnUpdates));
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(new InMemoryChatMessageStore());
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, CancellationToken, ValueTask<ChatMessageStore>>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(new InMemoryChatMessageStore());
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "test instructions" },
|
||||
@@ -2019,7 +1592,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
await agent.RunStreamingAsync([new(ChatRole.User, "test")], thread).ToListAsync();
|
||||
|
||||
// Assert
|
||||
@@ -2027,7 +1600,7 @@ public partial class ChatClientAgentTests
|
||||
Assert.Equal(2, messageStore.Count);
|
||||
Assert.Equal("test", messageStore[0].Text);
|
||||
Assert.Equal("what?", messageStore[1].Text);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>()), Times.Once);
|
||||
mockFactory.Verify(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -2048,8 +1621,8 @@ public partial class ChatClientAgentTests
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>())).Returns(ToAsyncEnumerableAsync(returnUpdates));
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, ChatMessageStore>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>())).Returns(new InMemoryChatMessageStore());
|
||||
Mock<Func<ChatClientAgentOptions.ChatMessageStoreFactoryContext, CancellationToken, ValueTask<ChatMessageStore>>> mockFactory = new();
|
||||
mockFactory.Setup(f => f(It.IsAny<ChatClientAgentOptions.ChatMessageStoreFactoryContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(new InMemoryChatMessageStore());
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "test instructions" },
|
||||
@@ -2057,7 +1630,7 @@ public partial class ChatClientAgentTests
|
||||
});
|
||||
|
||||
// Act & Assert
|
||||
ChatClientAgentThread? thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
ChatClientAgentThread? thread = await agent.GetNewThreadAsync() as ChatClientAgentThread;
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await agent.RunStreamingAsync([new(ChatRole.User, "test")], thread).ToListAsync());
|
||||
Assert.Equal("Only the ConversationId or MessageStore may be set, but not both and switching from one to another is not supported.", exception.Message);
|
||||
}
|
||||
@@ -2105,12 +1678,18 @@ public partial class ChatClientAgentTests
|
||||
.Setup(p => p.InvokedAsync(It.IsAny<AIContextProvider.InvokedContext>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(new ValueTask());
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] }, AIContextProviderFactory = _ => mockProvider.Object });
|
||||
ChatClientAgent agent = new(
|
||||
mockService.Object,
|
||||
options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] },
|
||||
AIContextProviderFactory = (_, _) => new(mockProvider.Object)
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread() as ChatClientAgentThread;
|
||||
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
|
||||
@@ -2168,13 +1747,19 @@ public partial class ChatClientAgentTests
|
||||
.Setup(p => p.InvokedAsync(It.IsAny<AIContextProvider.InvokedContext>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(new ValueTask());
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] }, AIContextProviderFactory = _ => mockProvider.Object });
|
||||
ChatClientAgent agent = new(
|
||||
mockService.Object,
|
||||
options: new()
|
||||
{
|
||||
ChatOptions = new() { Instructions = "base instructions", Tools = [AIFunctionFactory.Create(() => { }, "base function")] },
|
||||
AIContextProviderFactory = (_, _) => new(mockProvider.Object)
|
||||
});
|
||||
|
||||
// Act
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(async () =>
|
||||
{
|
||||
var updates = agent.RunStreamingAsync(requestMessages);
|
||||
await updates.ToAgentRunResponseAsync();
|
||||
await updates.ToAgentResponseAsync();
|
||||
});
|
||||
|
||||
// Assert
|
||||
|
||||
@@ -93,7 +93,7 @@ public class ChatClientAgentThreadTests
|
||||
#region Deserialize Tests
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyDeserializeConstructorWithMessagesAsync()
|
||||
public async Task VerifyDeserializeWithMessagesAsync()
|
||||
{
|
||||
// Arrange
|
||||
var json = JsonSerializer.Deserialize("""
|
||||
@@ -103,7 +103,7 @@ public class ChatClientAgentThreadTests
|
||||
""", TestJsonSerializerContext.Default.JsonElement);
|
||||
|
||||
// Act.
|
||||
var thread = new ChatClientAgentThread(json);
|
||||
var thread = await ChatClientAgentThread.DeserializeAsync(json);
|
||||
|
||||
// Assert
|
||||
Assert.Null(thread.ConversationId);
|
||||
@@ -115,7 +115,7 @@ public class ChatClientAgentThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyDeserializeConstructorWithIdAsync()
|
||||
public async Task VerifyDeserializeWithIdAsync()
|
||||
{
|
||||
// Arrange
|
||||
var json = JsonSerializer.Deserialize("""
|
||||
@@ -125,7 +125,7 @@ public class ChatClientAgentThreadTests
|
||||
""", TestJsonSerializerContext.Default.JsonElement);
|
||||
|
||||
// Act
|
||||
var thread = new ChatClientAgentThread(json);
|
||||
var thread = await ChatClientAgentThread.DeserializeAsync(json);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("TestConvId", thread.ConversationId);
|
||||
@@ -133,7 +133,7 @@ public class ChatClientAgentThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyDeserializeConstructorWithAIContextProviderAsync()
|
||||
public async Task VerifyDeserializeWithAIContextProviderAsync()
|
||||
{
|
||||
// Arrange
|
||||
var json = JsonSerializer.Deserialize("""
|
||||
@@ -145,7 +145,7 @@ public class ChatClientAgentThreadTests
|
||||
Mock<AIContextProvider> mockProvider = new();
|
||||
|
||||
// Act
|
||||
var thread = new ChatClientAgentThread(json, aiContextProviderFactory: (_, _) => mockProvider.Object);
|
||||
var thread = await ChatClientAgentThread.DeserializeAsync(json, aiContextProviderFactory: (_, _, _) => new(mockProvider.Object));
|
||||
|
||||
// Assert
|
||||
Assert.Null(thread.MessageStore);
|
||||
@@ -153,14 +153,14 @@ public class ChatClientAgentThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeserializeContructorWithInvalidJsonThrowsAsync()
|
||||
public async Task DeserializeWithInvalidJsonThrowsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var invalidJson = JsonSerializer.Deserialize("[42]", TestJsonSerializerContext.Default.JsonElement);
|
||||
var thread = new ChatClientAgentThread();
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentException>(() => new ChatClientAgentThread(invalidJson));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => ChatClientAgentThread.DeserializeAsync(invalidJson));
|
||||
}
|
||||
|
||||
#endregion Deserialize Tests
|
||||
|
||||
+3
-3
@@ -264,7 +264,7 @@ public class ChatClientAgent_BackgroundResponsesTests
|
||||
ChatClientAgentThread thread = new();
|
||||
|
||||
// Act
|
||||
var actualUpdates = new List<AgentRunResponseUpdate>();
|
||||
var actualUpdates = new List<AgentResponseUpdate>();
|
||||
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<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
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<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in agent.RunStreamingAsync(thread, options: runOptions))
|
||||
{
|
||||
updates.Add(update);
|
||||
|
||||
+442
@@ -0,0 +1,442 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Moq;
|
||||
|
||||
namespace Microsoft.Agents.AI.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="ChatOptions"/> merging in <see cref="ChatClientAgent"/>.
|
||||
/// </summary>
|
||||
public class ChatClientAgent_ChatOptionsMergingTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging works when agent has ChatOptions but request doesn't.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesAgentOptionsWhenRequestHasNoneAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions { MaxOutputTokens = 100, Temperature = 0.7f, Instructions = "test instructions" };
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equal(100, capturedChatOptions.MaxOutputTokens);
|
||||
Assert.Equal(0.7f, capturedChatOptions.Temperature);
|
||||
Assert.Equal("test instructions", capturedChatOptions.Instructions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesAgentOptionsConstructorWhenRequestHasNoneAsync()
|
||||
{
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new() { ChatOptions = new() { Instructions = "test instructions" } });
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equal("test instructions", capturedChatOptions.Instructions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging works when request has ChatOptions but agent doesn't.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesRequestOptionsWhenAgentHasNoneAsync()
|
||||
{
|
||||
// Arrange
|
||||
var requestChatOptions = new ChatOptions { MaxOutputTokens = 200, Temperature = 0.3f, Instructions = "test instructions" };
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object);
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equivalent(requestChatOptions, capturedChatOptions); // Should be the same instance since no merging needed
|
||||
Assert.Equal(200, capturedChatOptions.MaxOutputTokens);
|
||||
Assert.Equal(0.3f, capturedChatOptions.Temperature);
|
||||
Assert.Equal("test instructions", capturedChatOptions.Instructions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that <see cref="ChatOptions"/> merging prioritizes <see cref="AgentRunOptions"/> over request <see cref="ChatOptions"/> and that in turn over agent level <see cref="ChatOptions"/>.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingPrioritizesRequestOptionsOverAgentOptionsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
MaxOutputTokens = 100,
|
||||
Temperature = 0.7f,
|
||||
TopP = 0.9f,
|
||||
ModelId = "agent-model",
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary { ["key1"] = "agent-value", ["key2"] = "agent-value", ["key3"] = "agent-value" }
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
// TopP and ModelId not set, should use agent values
|
||||
MaxOutputTokens = 200,
|
||||
Temperature = 0.3f,
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary { ["key2"] = "request-value", ["key3"] = "request-value" },
|
||||
Instructions = "request instructions"
|
||||
};
|
||||
var agentRunOptionsAdditionalProperties = new AdditionalPropertiesDictionary { ["key3"] = "runoptions-value" };
|
||||
var expectedChatOptionsMerge = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 200, // Request value takes priority
|
||||
Temperature = 0.3f, // Request value takes priority
|
||||
// Check that each level of precedence is respected in AdditionalProperties
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary { ["key1"] = "agent-value", ["key2"] = "request-value", ["key3"] = "runoptions-value" },
|
||||
TopP = 0.9f, // Agent value used when request doesn't specify
|
||||
ModelId = "agent-model", // Agent value used when request doesn't specify
|
||||
Instructions = "test instructions\nrequest instructions" // Request is in addition to agent instructions
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions) { AdditionalProperties = agentRunOptionsAdditionalProperties });
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equivalent(expectedChatOptionsMerge, capturedChatOptions); // Should be the same instance (modified in place)
|
||||
Assert.Equal(200, capturedChatOptions.MaxOutputTokens); // Request value takes priority
|
||||
Assert.Equal(0.3f, capturedChatOptions.Temperature); // Request value takes priority
|
||||
Assert.NotNull(capturedChatOptions.AdditionalProperties);
|
||||
Assert.Equal("agent-value", capturedChatOptions.AdditionalProperties["key1"]); // Agent value used when request doesn't specify
|
||||
Assert.Equal("request-value", capturedChatOptions.AdditionalProperties["key2"]); // Request ChatOptions value takes priority over agent ChatOptions value
|
||||
Assert.Equal("runoptions-value", capturedChatOptions.AdditionalProperties["key3"]); // Run options value takes priority over request and agent ChatOptions values
|
||||
Assert.Equal(0.9f, capturedChatOptions.TopP); // Agent value used when request doesn't specify
|
||||
Assert.Equal("agent-model", capturedChatOptions.ModelId); // Agent value used when request doesn't specify
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging returns null when both agent and request have no ChatOptions.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingReturnsNullWhenBothAgentAndRequestHaveNoneAsync()
|
||||
{
|
||||
// Arrange
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object);
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages);
|
||||
|
||||
// Assert
|
||||
Assert.Null(capturedChatOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging concatenates Tools from agent and request.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingConcatenatesToolsFromAgentAndRequestAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentTool = AIFunctionFactory.Create(() => "agent tool");
|
||||
var requestTool = AIFunctionFactory.Create(() => "request tool");
|
||||
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
Tools = [agentTool]
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
Tools = [requestTool]
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.NotNull(capturedChatOptions.Tools);
|
||||
Assert.Equal(2, capturedChatOptions.Tools.Count);
|
||||
|
||||
// Request tools should come first, then agent tools
|
||||
Assert.Contains(requestTool, capturedChatOptions.Tools);
|
||||
Assert.Contains(agentTool, capturedChatOptions.Tools);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging uses agent Tools when request has no Tools.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingUsesAgentToolsWhenRequestHasNoToolsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentTool = AIFunctionFactory.Create(() => "agent tool");
|
||||
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
Tools = [agentTool]
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
// No Tools specified
|
||||
MaxOutputTokens = 100
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.NotNull(capturedChatOptions.Tools);
|
||||
Assert.Single(capturedChatOptions.Tools);
|
||||
Assert.Contains(agentTool, capturedChatOptions.Tools); // Should contain the agent's tool
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging uses RawRepresentationFactory from request first, with fallback to agent.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("MockAgentSetting", "MockRequestSetting", "MockRequestSetting")]
|
||||
[InlineData("MockAgentSetting", null, "MockAgentSetting")]
|
||||
[InlineData(null, "MockRequestSetting", "MockRequestSetting")]
|
||||
public async Task ChatOptionsMergingUsesRawRepresentationFactoryWithFallbackAsync(string? agentSetting, string? requestSetting, string expectedSetting)
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
Instructions = "test instructions",
|
||||
RawRepresentationFactory = _ => agentSetting
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
RawRepresentationFactory = _ => requestSetting
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.NotNull(capturedChatOptions.RawRepresentationFactory);
|
||||
Assert.Equal(expectedSetting, capturedChatOptions.RawRepresentationFactory(null!));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verify that ChatOptions merging handles all scalar properties correctly.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ChatOptionsMergingHandlesAllScalarPropertiesCorrectlyAsync()
|
||||
{
|
||||
// Arrange
|
||||
var agentChatOptions = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 100,
|
||||
Temperature = 0.7f,
|
||||
TopP = 0.9f,
|
||||
TopK = 50,
|
||||
PresencePenalty = 0.1f,
|
||||
FrequencyPenalty = 0.2f,
|
||||
Instructions = "agent instructions",
|
||||
ModelId = "agent-model",
|
||||
Seed = 12345,
|
||||
ConversationId = "agent-conversation",
|
||||
AllowMultipleToolCalls = true,
|
||||
StopSequences = ["agent-stop"]
|
||||
};
|
||||
var requestChatOptions = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 200,
|
||||
Temperature = 0.3f,
|
||||
Instructions = "request instructions",
|
||||
|
||||
// Other properties not set, should use agent values
|
||||
StopSequences = ["request-stop"]
|
||||
};
|
||||
|
||||
var expectedChatOptionsMerge = new ChatOptions
|
||||
{
|
||||
MaxOutputTokens = 200,
|
||||
Temperature = 0.3f,
|
||||
|
||||
// Agent value used when request doesn't specify
|
||||
TopP = 0.9f,
|
||||
TopK = 50,
|
||||
PresencePenalty = 0.1f,
|
||||
FrequencyPenalty = 0.2f,
|
||||
Instructions = "agent instructions\nrequest instructions",
|
||||
ModelId = "agent-model",
|
||||
Seed = 12345,
|
||||
ConversationId = "agent-conversation",
|
||||
AllowMultipleToolCalls = true,
|
||||
|
||||
// Merged StopSequences
|
||||
StopSequences = ["request-stop", "agent-stop"]
|
||||
};
|
||||
|
||||
Mock<IChatClient> mockService = new();
|
||||
ChatOptions? capturedChatOptions = null;
|
||||
mockService.Setup(
|
||||
s => s.GetResponseAsync(
|
||||
It.IsAny<IEnumerable<ChatMessage>>(),
|
||||
It.IsAny<ChatOptions>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback<IEnumerable<ChatMessage>, ChatOptions, CancellationToken>((msgs, opts, ct) =>
|
||||
capturedChatOptions = opts)
|
||||
.ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockService.Object, options: new()
|
||||
{
|
||||
ChatOptions = agentChatOptions
|
||||
});
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "test") };
|
||||
|
||||
// Act
|
||||
await agent.RunAsync(messages, options: new ChatClientAgentRunOptions(requestChatOptions));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(capturedChatOptions);
|
||||
Assert.Equivalent(expectedChatOptionsMerge, capturedChatOptions); // Should be the equivalent instance (modified in place)
|
||||
|
||||
// Request values should take priority
|
||||
Assert.Equal(200, capturedChatOptions.MaxOutputTokens);
|
||||
Assert.Equal(0.3f, capturedChatOptions.Temperature);
|
||||
|
||||
// Merge StopSequences
|
||||
Assert.Equal(["request-stop", "agent-stop"], capturedChatOptions.StopSequences);
|
||||
|
||||
// Agent values should be used when request doesn't specify
|
||||
Assert.Equal(0.9f, capturedChatOptions.TopP);
|
||||
Assert.Equal(50, capturedChatOptions.TopK);
|
||||
Assert.Equal(0.1f, capturedChatOptions.PresencePenalty);
|
||||
Assert.Equal(0.2f, capturedChatOptions.FrequencyPenalty);
|
||||
Assert.Equal("agent-model", capturedChatOptions.ModelId);
|
||||
Assert.Equal(12345, capturedChatOptions.Seed);
|
||||
Assert.Equal("agent-conversation", capturedChatOptions.ConversationId);
|
||||
Assert.Equal(true, capturedChatOptions.AllowMultipleToolCalls);
|
||||
}
|
||||
}
|
||||
+9
-8
@@ -1,6 +1,7 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Moq;
|
||||
|
||||
@@ -12,7 +13,7 @@ namespace Microsoft.Agents.AI.UnitTests.ChatClient;
|
||||
public class ChatClientAgent_DeserializeThreadTests
|
||||
{
|
||||
[Fact]
|
||||
public void DeserializeThread_UsesAIContextProviderFactory_IfProvided()
|
||||
public async Task DeserializeThread_UsesAIContextProviderFactory_IfProvidedAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
@@ -21,10 +22,10 @@ public class ChatClientAgent_DeserializeThreadTests
|
||||
var agent = new ChatClientAgent(mockChatClient.Object, new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "Test instructions" },
|
||||
AIContextProviderFactory = _ =>
|
||||
AIContextProviderFactory = (_, _) =>
|
||||
{
|
||||
factoryCalled = true;
|
||||
return mockContextProvider.Object;
|
||||
return new ValueTask<AIContextProvider>(mockContextProvider.Object);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -35,7 +36,7 @@ public class ChatClientAgent_DeserializeThreadTests
|
||||
""", TestJsonSerializerContext.Default.JsonElement);
|
||||
|
||||
// Act
|
||||
var thread = agent.DeserializeThread(json);
|
||||
var thread = await agent.DeserializeThreadAsync(json);
|
||||
|
||||
// Assert
|
||||
Assert.True(factoryCalled, "AIContextProviderFactory was not called.");
|
||||
@@ -45,7 +46,7 @@ public class ChatClientAgent_DeserializeThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeserializeThread_UsesChatMessageStoreFactory_IfProvided()
|
||||
public async Task DeserializeThread_UsesChatMessageStoreFactory_IfProvidedAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
@@ -54,10 +55,10 @@ public class ChatClientAgent_DeserializeThreadTests
|
||||
var agent = new ChatClientAgent(mockChatClient.Object, new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "Test instructions" },
|
||||
ChatMessageStoreFactory = _ =>
|
||||
ChatMessageStoreFactory = (_, _) =>
|
||||
{
|
||||
factoryCalled = true;
|
||||
return mockMessageStore.Object;
|
||||
return new ValueTask<ChatMessageStore>(mockMessageStore.Object);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -68,7 +69,7 @@ public class ChatClientAgent_DeserializeThreadTests
|
||||
""", TestJsonSerializerContext.Default.JsonElement);
|
||||
|
||||
// Act
|
||||
var thread = agent.DeserializeThread(json);
|
||||
var thread = await agent.DeserializeThreadAsync(json);
|
||||
|
||||
// Assert
|
||||
Assert.True(factoryCalled, "ChatMessageStoreFactory was not called.");
|
||||
|
||||
+14
-13
@@ -1,17 +1,18 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Moq;
|
||||
|
||||
namespace Microsoft.Agents.AI.UnitTests.ChatClient;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the ChatClientAgent.GetNewThread methods.
|
||||
/// Contains unit tests for the ChatClientAgent.GetNewThreadAsync methods.
|
||||
/// </summary>
|
||||
public class ChatClientAgent_GetNewThreadTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetNewThread_UsesAIContextProviderFactory_IfProvided()
|
||||
public async Task GetNewThread_UsesAIContextProviderFactory_IfProvidedAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
@@ -20,15 +21,15 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
var agent = new ChatClientAgent(mockChatClient.Object, new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "Test instructions" },
|
||||
AIContextProviderFactory = _ =>
|
||||
AIContextProviderFactory = (_, _) =>
|
||||
{
|
||||
factoryCalled = true;
|
||||
return mockContextProvider.Object;
|
||||
return new ValueTask<AIContextProvider>(mockContextProvider.Object);
|
||||
}
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
|
||||
// Assert
|
||||
Assert.True(factoryCalled, "AIContextProviderFactory was not called.");
|
||||
@@ -38,7 +39,7 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_UsesChatMessageStoreFactory_IfProvided()
|
||||
public async Task GetNewThread_UsesChatMessageStoreFactory_IfProvidedAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
@@ -47,15 +48,15 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
var agent = new ChatClientAgent(mockChatClient.Object, new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new() { Instructions = "Test instructions" },
|
||||
ChatMessageStoreFactory = _ =>
|
||||
ChatMessageStoreFactory = (_, _) =>
|
||||
{
|
||||
factoryCalled = true;
|
||||
return mockMessageStore.Object;
|
||||
return new ValueTask<ChatMessageStore>(mockMessageStore.Object);
|
||||
}
|
||||
});
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread();
|
||||
var thread = await agent.GetNewThreadAsync();
|
||||
|
||||
// Assert
|
||||
Assert.True(factoryCalled, "ChatMessageStoreFactory was not called.");
|
||||
@@ -65,7 +66,7 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_UsesChatMessageStore_FromTypedOverload()
|
||||
public async Task GetNewThread_UsesChatMessageStore_FromTypedOverloadAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
@@ -73,7 +74,7 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
var agent = new ChatClientAgent(mockChatClient.Object);
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread(mockMessageStore.Object);
|
||||
var thread = await agent.GetNewThreadAsync(mockMessageStore.Object);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
@@ -82,7 +83,7 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetNewThread_UsesConversationId_FromTypedOverload()
|
||||
public async Task GetNewThread_UsesConversationId_FromTypedOverloadAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
@@ -90,7 +91,7 @@ public class ChatClientAgent_GetNewThreadTests
|
||||
var agent = new ChatClientAgent(mockChatClient.Object);
|
||||
|
||||
// Act
|
||||
var thread = agent.GetNewThread(TestConversationId);
|
||||
var thread = await agent.GetNewThreadAsync(TestConversationId);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ChatClientAgentThread>(thread);
|
||||
|
||||
+37
-37
@@ -30,11 +30,11 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "Response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
AgentRunResponse result = await agent.RunAsync(thread, options);
|
||||
AgentResponse result = await agent.RunAsync(thread, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
@@ -59,11 +59,11 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "Response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
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);
|
||||
@@ -88,12 +88,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "Response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage message = new(ChatRole.User, "Test message");
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
AgentRunResponse result = await agent.RunAsync(message, thread, options);
|
||||
AgentResponse result = await agent.RunAsync(message, thread, options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
@@ -118,12 +118,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, "Response")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
IEnumerable<ChatMessage> messages = [new(ChatRole.User, "Message 1"), new(ChatRole.User, "Message 2")];
|
||||
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);
|
||||
@@ -179,11 +179,11 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).Returns(GetAsyncUpdatesAsync());
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in agent.RunStreamingAsync(thread, options))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -211,11 +211,11 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).Returns(GetAsyncUpdatesAsync());
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in agent.RunStreamingAsync("Test message", thread, options))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -243,12 +243,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).Returns(GetAsyncUpdatesAsync());
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage message = new(ChatRole.User, "Test message");
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in agent.RunStreamingAsync(message, thread, options))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -276,12 +276,12 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).Returns(GetAsyncUpdatesAsync());
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
IEnumerable<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Message 1"), new ChatMessage(ChatRole.User, "Message 2")];
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
var updates = new List<AgentRunResponseUpdate>();
|
||||
var updates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in agent.RunStreamingAsync(messages, thread, options))
|
||||
{
|
||||
updates.Add(update);
|
||||
@@ -324,16 +324,16 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, """{"id":2, "fullName":"Tigger", "species":"Tiger"}""")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
AgentRunResponse<Animal> agentRunResponse = await agent.RunAsync<Animal>(thread, JsonContext_WithCustomRunOptions.Default.Options, options);
|
||||
AgentResponse<Animal> agentResponse = await agent.RunAsync<Animal>(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<IEnumerable<ChatMessage>>(),
|
||||
@@ -354,16 +354,16 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, """{"id":2, "fullName":"Tigger", "species":"Tiger"}""")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
AgentRunResponse<Animal> agentRunResponse = await agent.RunAsync<Animal>("Test message", thread, JsonContext_WithCustomRunOptions.Default.Options, options);
|
||||
AgentResponse<Animal> agentResponse = await agent.RunAsync<Animal>("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<IEnumerable<ChatMessage>>(msgs => msgs.Any(m => m.Text == "Test message")),
|
||||
@@ -384,17 +384,17 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, """{"id":2, "fullName":"Tigger", "species":"Tiger"}""")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
ChatMessage message = new(ChatRole.User, "Test message");
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
AgentRunResponse<Animal> agentRunResponse = await agent.RunAsync<Animal>(message, thread, JsonContext_WithCustomRunOptions.Default.Options, options);
|
||||
AgentResponse<Animal> agentResponse = await agent.RunAsync<Animal>(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<IEnumerable<ChatMessage>>(msgs => msgs.Contains(message)),
|
||||
@@ -415,17 +415,17 @@ public sealed partial class ChatClientAgent_RunWithCustomOptionsTests
|
||||
It.IsAny<CancellationToken>())).ReturnsAsync(new ChatResponse([new(ChatRole.Assistant, """{"id":2, "fullName":"Tigger", "species":"Tiger"}""")]));
|
||||
|
||||
ChatClientAgent agent = new(mockChatClient.Object);
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
IEnumerable<ChatMessage> messages = [new(ChatRole.User, "Message 1"), new(ChatRole.User, "Message 2")];
|
||||
ChatClientAgentRunOptions options = new();
|
||||
|
||||
// Act
|
||||
AgentRunResponse<Animal> agentRunResponse = await agent.RunAsync<Animal>(messages, thread, JsonContext_WithCustomRunOptions.Default.Options, options);
|
||||
AgentResponse<Animal> agentResponse = await agent.RunAsync<Animal>(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<IEnumerable<ChatMessage>>(),
|
||||
|
||||
@@ -19,7 +19,7 @@ public sealed class ChatClientExtensionsTests
|
||||
var chatClientMock = new Mock<IChatClient>();
|
||||
|
||||
// Act
|
||||
var agent = chatClientMock.Object.CreateAIAgent(
|
||||
var agent = chatClientMock.Object.AsAIAgent(
|
||||
instructions: "Test instructions",
|
||||
name: "TestAgent",
|
||||
description: "Test description"
|
||||
@@ -40,7 +40,7 @@ public sealed class ChatClientExtensionsTests
|
||||
var tools = new List<AITool> { new Mock<AITool>().Object };
|
||||
|
||||
// Act
|
||||
var agent = chatClientMock.Object.CreateAIAgent(tools: tools);
|
||||
var agent = chatClientMock.Object.AsAIAgent(tools: tools);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -62,7 +62,7 @@ public sealed class ChatClientExtensionsTests
|
||||
};
|
||||
|
||||
// Act
|
||||
var agent = chatClientMock.Object.CreateAIAgent(options);
|
||||
var agent = chatClientMock.Object.AsAIAgent(options);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(agent);
|
||||
@@ -79,7 +79,7 @@ public sealed class ChatClientExtensionsTests
|
||||
IChatClient chatClient = null!;
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => chatClient.CreateAIAgent(instructions: "instructions"));
|
||||
Assert.Throws<ArgumentNullException>(() => chatClient.AsAIAgent(instructions: "instructions"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -89,6 +89,6 @@ public sealed class ChatClientExtensionsTests
|
||||
IChatClient chatClient = null!;
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => chatClient.CreateAIAgent(options: new() { ChatOptions = new() { Instructions = "instructions" } }));
|
||||
Assert.Throws<ArgumentNullException>(() => chatClient.AsAIAgent(options: new() { ChatOptions = new() { Instructions = "instructions" } }));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -717,7 +717,7 @@ public sealed class FunctionInvocationDelegatingAgentTests
|
||||
var innerAgent = new ChatClientAgent(mockChatClient.Object);
|
||||
var messages = new List<ChatMessage> { new(ChatRole.User, "Test message") };
|
||||
|
||||
async Task<AgentRunResponse> RunningMiddlewareCallbackAsync(IEnumerable<ChatMessage> messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken)
|
||||
async Task<AgentResponse> RunningMiddlewareCallbackAsync(IEnumerable<ChatMessage> 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<AgentRunResponseUpdate>();
|
||||
var responseUpdates = new List<AgentResponseUpdate>();
|
||||
await foreach (var update in middleware.RunStreamingAsync(messages, null, options, CancellationToken.None))
|
||||
{
|
||||
responseUpdates.Add(update);
|
||||
|
||||
@@ -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<AgentRunResponseUpdate> CallbackAsync(
|
||||
static async IAsyncEnumerable<AgentResponseUpdate> CallbackAsync(
|
||||
IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> CallbackAsync(
|
||||
static async IAsyncEnumerable<AgentResponseUpdate> CallbackAsync(
|
||||
IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> CallbackAsync(
|
||||
static async IAsyncEnumerable<AgentResponseUpdate> CallbackAsync(
|
||||
IEnumerable<ChatMessage> messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.Yield();
|
||||
@@ -364,7 +364,7 @@ public class LoggingAgentTests
|
||||
RunStreamingAsyncFunc = CallbackAsync
|
||||
};
|
||||
|
||||
static async IAsyncEnumerable<AgentRunResponseUpdate> CallbackAsync(
|
||||
static async IAsyncEnumerable<AgentResponseUpdate> CallbackAsync(
|
||||
IEnumerable<ChatMessage> messages, AgentThread? thread, AgentRunOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.Yield();
|
||||
|
||||
@@ -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<AgentRunResponseUpdate> CallbackAsync(
|
||||
async static IAsyncEnumerable<AgentResponseUpdate> CallbackAsync(
|
||||
IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> CallbackAsync(
|
||||
async static IAsyncEnumerable<AgentResponseUpdate> CallbackAsync(
|
||||
IEnumerable<ChatMessage> 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()
|
||||
{
|
||||
|
||||
@@ -16,24 +16,24 @@ internal sealed class TestAIAgent : AIAgent
|
||||
|
||||
public Func<JsonElement, JsonSerializerOptions?, AgentThread> DeserializeThreadFunc = delegate { throw new NotSupportedException(); };
|
||||
public Func<AgentThread> GetNewThreadFunc = delegate { throw new NotSupportedException(); };
|
||||
public Func<IEnumerable<ChatMessage>, AgentThread?, AgentRunOptions?, CancellationToken, Task<AgentRunResponse>> RunAsyncFunc = delegate { throw new NotSupportedException(); };
|
||||
public Func<IEnumerable<ChatMessage>, AgentThread?, AgentRunOptions?, CancellationToken, IAsyncEnumerable<AgentRunResponseUpdate>> RunStreamingAsyncFunc = delegate { throw new NotSupportedException(); };
|
||||
public Func<IEnumerable<ChatMessage>, AgentThread?, AgentRunOptions?, CancellationToken, Task<AgentResponse>> RunAsyncFunc = delegate { throw new NotSupportedException(); };
|
||||
public Func<IEnumerable<ChatMessage>, AgentThread?, AgentRunOptions?, CancellationToken, IAsyncEnumerable<AgentResponseUpdate>> RunStreamingAsyncFunc = delegate { throw new NotSupportedException(); };
|
||||
public Func<Type, object?, object?>? GetServiceFunc;
|
||||
|
||||
public override string? Name => this.NameFunc?.Invoke() ?? base.Name;
|
||||
|
||||
public override string? Description => this.DescriptionFunc?.Invoke() ?? base.Description;
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
this.DeserializeThreadFunc(serializedThread, jsonSerializerOptions);
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) =>
|
||||
new(this.DeserializeThreadFunc(serializedThread, jsonSerializerOptions));
|
||||
|
||||
public override AgentThread GetNewThread() =>
|
||||
this.GetNewThreadFunc();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(this.GetNewThreadFunc());
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
this.RunAsyncFunc(messages, thread, options, cancellationToken);
|
||||
|
||||
protected override IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
protected override IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> 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) =>
|
||||
|
||||
+2
-2
@@ -18,7 +18,7 @@ internal sealed class WorkflowEvents
|
||||
this.ExecutorInvokeEvents = workflowEvents.OfType<ExecutorInvokedEvent>().ToList();
|
||||
this.ExecutorCompleteEvents = workflowEvents.OfType<ExecutorCompletedEvent>().ToList();
|
||||
this.InputEvents = workflowEvents.OfType<RequestInfoEvent>().ToList();
|
||||
this.AgentResponseEvents = workflowEvents.OfType<AgentRunResponseEvent>().ToList();
|
||||
this.AgentResponseEvents = workflowEvents.OfType<AgentResponseEvent>().ToList();
|
||||
}
|
||||
|
||||
public IReadOnlyList<WorkflowEvent> Events { get; }
|
||||
@@ -29,5 +29,5 @@ internal sealed class WorkflowEvents
|
||||
public IReadOnlyList<ExecutorInvokedEvent> ExecutorInvokeEvents { get; }
|
||||
public IReadOnlyList<ExecutorCompletedEvent> ExecutorCompleteEvents { get; }
|
||||
public IReadOnlyList<RequestInfoEvent> InputEvents { get; }
|
||||
public IReadOnlyList<AgentRunResponseEvent> AgentResponseEvents { get; }
|
||||
public IReadOnlyList<AgentResponseEvent> AgentResponseEvents { get; }
|
||||
}
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ internal sealed class WorkflowHarness(Workflow workflow, string runId)
|
||||
Console.WriteLine($"ACTION: {actionInvokeEvent.ActionId} [{actionInvokeEvent.ActionType}]");
|
||||
break;
|
||||
|
||||
case AgentRunResponseEvent responseEvent:
|
||||
case AgentResponseEvent responseEvent:
|
||||
if (!string.IsNullOrEmpty(responseEvent.Response.Text))
|
||||
{
|
||||
Console.WriteLine($"AGENT: {responseEvent.Response.AgentId}: {responseEvent.Response.Text}");
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@ public abstract class WorkflowTest(ITestOutputHelper output) : IntegrationTest(o
|
||||
}
|
||||
}
|
||||
|
||||
public static void Responses(IReadOnlyList<AgentRunResponseEvent> responseEvents, Testcase testcase)
|
||||
public static void Responses(IReadOnlyList<AgentResponseEvent> responseEvents, Testcase testcase)
|
||||
{
|
||||
Assert.True(responseEvents.Count >= testcase.Validation.MinResponseCount, $"Response count less than expected: {testcase.Validation.MinResponseCount} (Actual: {responseEvents.Count})");
|
||||
if (testcase.Validation.MaxResponseCount != -1)
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ public sealed class MediaInputTest(ITestOutputHelper output) : IntegrationTest(o
|
||||
WorkflowEvents workflowEvents = await harness.RunWorkflowAsync(inputMessage).ConfigureAwait(false);
|
||||
ConversationUpdateEvent conversationEvent = Assert.Single(workflowEvents.ConversationEvents);
|
||||
this.Output.WriteLine("CONVERSATION: " + conversationEvent.ConversationId);
|
||||
AgentRunResponseEvent agentResponseEvent = Assert.Single(workflowEvents.AgentResponseEvents);
|
||||
AgentResponseEvent agentResponseEvent = Assert.Single(workflowEvents.AgentResponseEvents);
|
||||
this.Output.WriteLine("RESPONSE: " + agentResponseEvent.Response.Text);
|
||||
Assert.NotEmpty(agentResponseEvent.Response.Text);
|
||||
}
|
||||
|
||||
+1
-1
@@ -352,7 +352,7 @@ public sealed class DeclarativeWorkflowTest(ITestOutputHelper output) : Workflow
|
||||
this.Output.WriteLine($"ACTIVITY: {activityEvent.Message}");
|
||||
break;
|
||||
|
||||
case AgentRunResponseEvent messageEvent:
|
||||
case AgentResponseEvent messageEvent:
|
||||
this.Output.WriteLine($"MESSAGE: {messageEvent.Response.Messages[0].Text.Trim()}");
|
||||
break;
|
||||
|
||||
|
||||
+2
-2
@@ -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,
|
||||
[
|
||||
|
||||
+2
-2
@@ -60,8 +60,8 @@ public static class WorkflowProvider
|
||||
NEVER 1!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
+21
-21
@@ -1,4 +1,4 @@
|
||||
// ------------------------------------------------------------------------------
|
||||
// ------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// </auto-generated>
|
||||
@@ -47,7 +47,7 @@ public static class WorkflowProvider
|
||||
await context.QueueStateUpdateAsync("TestValue", UnassignedValue.Instance, "Local").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Assigns an evaluated expression, other variable, or literal value to the "Local.TestValue" variable.
|
||||
/// </summary>
|
||||
@@ -58,11 +58,11 @@ public static class WorkflowProvider
|
||||
{
|
||||
object? evaluatedValue = await context.EvaluateValueAsync<object>("Value(System.LastMessageText)").ConfigureAwait(false);
|
||||
await context.QueueStateUpdateAsync(key: "TestValue", value: evaluatedValue, scopeName: "Local").ConfigureAwait(false);
|
||||
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Conditional branching similar to an if / elseif / elseif / else chain.
|
||||
/// </summary>
|
||||
@@ -76,17 +76,17 @@ public static class WorkflowProvider
|
||||
{
|
||||
return "conditionItem_odd";
|
||||
}
|
||||
|
||||
|
||||
bool condition1 = await context.EvaluateValueAsync<bool>("Mod(Local.TestValue, 2) = 0").ConfigureAwait(false);
|
||||
if (condition1)
|
||||
{
|
||||
return "conditionItem_even";
|
||||
}
|
||||
|
||||
|
||||
return "conditionGroup_testElseActions";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Formats a message template and sends an activity event.
|
||||
/// </summary>
|
||||
@@ -101,13 +101,13 @@ public static class WorkflowProvider
|
||||
ODD
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Formats a message template and sends an activity event.
|
||||
/// </summary>
|
||||
@@ -122,13 +122,13 @@ public static class WorkflowProvider
|
||||
EVEN
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Formats a message template and sends an activity event.
|
||||
/// </summary>
|
||||
@@ -143,16 +143,16 @@ public static class WorkflowProvider
|
||||
All done!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Workflow CreateWorkflow<TInput>(
|
||||
DeclarativeWorkflowOptions options,
|
||||
Func<TInput, ChatMessage>? inputTransform = null)
|
||||
Func<TInput, ChatMessage>? inputTransform = null)
|
||||
where TInput : notnull
|
||||
{
|
||||
// Create root executor to initialize the workflow.
|
||||
@@ -198,4 +198,4 @@ public static class WorkflowProvider
|
||||
// Build the workflow
|
||||
return builder.Build(validateOrphans: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+20
-20
@@ -1,4 +1,4 @@
|
||||
// ------------------------------------------------------------------------------
|
||||
// ------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// </auto-generated>
|
||||
@@ -47,7 +47,7 @@ public static class WorkflowProvider
|
||||
await context.QueueStateUpdateAsync("TestValue", UnassignedValue.Instance, "Local").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Assigns an evaluated expression, other variable, or literal value to the "Local.TestValue" variable.
|
||||
/// </summary>
|
||||
@@ -58,11 +58,11 @@ public static class WorkflowProvider
|
||||
{
|
||||
object? evaluatedValue = await context.EvaluateValueAsync<object>("Value(System.LastMessageText)").ConfigureAwait(false);
|
||||
await context.QueueStateUpdateAsync(key: "TestValue", value: evaluatedValue, scopeName: "Local").ConfigureAwait(false);
|
||||
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Conditional branching similar to an if / elseif / elseif / else chain.
|
||||
/// </summary>
|
||||
@@ -76,11 +76,11 @@ public static class WorkflowProvider
|
||||
{
|
||||
return "conditionItem_odd";
|
||||
}
|
||||
|
||||
|
||||
return "conditionGroup_testElseActions";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Formats a message template and sends an activity event.
|
||||
/// </summary>
|
||||
@@ -95,13 +95,13 @@ public static class WorkflowProvider
|
||||
ODD
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Formats a message template and sends an activity event.
|
||||
/// </summary>
|
||||
@@ -116,13 +116,13 @@ public static class WorkflowProvider
|
||||
EVEN
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Formats a message template and sends an activity event.
|
||||
/// </summary>
|
||||
@@ -137,16 +137,16 @@ public static class WorkflowProvider
|
||||
All done!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Workflow CreateWorkflow<TInput>(
|
||||
DeclarativeWorkflowOptions options,
|
||||
Func<TInput, ChatMessage>? inputTransform = null)
|
||||
Func<TInput, ChatMessage>? inputTransform = null)
|
||||
where TInput : notnull
|
||||
{
|
||||
// Create root executor to initialize the workflow.
|
||||
@@ -190,4 +190,4 @@ public static class WorkflowProvider
|
||||
// Build the workflow
|
||||
return builder.Build(validateOrphans: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -60,8 +60,8 @@ public static class WorkflowProvider
|
||||
NEVER 1!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
// ------------------------------------------------------------------------------
|
||||
// ------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// </auto-generated>
|
||||
@@ -60,8 +60,8 @@ public static class WorkflowProvider
|
||||
NEVER 1!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
@@ -91,4 +91,4 @@ public static class WorkflowProvider
|
||||
// Build the workflow
|
||||
return builder.Build(validateOrphans: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ public static class WorkflowProvider
|
||||
NEVER 1!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
@@ -81,8 +81,8 @@ public static class WorkflowProvider
|
||||
NEVER 2!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
@@ -102,8 +102,8 @@ public static class WorkflowProvider
|
||||
NEVER 3!
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
+2
-2
@@ -70,7 +70,7 @@ public static class WorkflowProvider
|
||||
bool autoSend = true;
|
||||
IList<ChatMessage>? inputMessages = await context.EvaluateListAsync<ChatMessage>("[UserMessage(System.LastMessageText)]").ConfigureAwait(false);
|
||||
|
||||
AgentRunResponse agentResponse =
|
||||
AgentResponse agentResponse =
|
||||
await InvokeAgentAsync(
|
||||
context,
|
||||
agentName,
|
||||
@@ -81,7 +81,7 @@ public static class WorkflowProvider
|
||||
|
||||
if (autoSend)
|
||||
{
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, agentResponse)).ConfigureAwait(false);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, agentResponse)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return default;
|
||||
|
||||
+2
-2
@@ -135,8 +135,8 @@ public static class WorkflowProvider
|
||||
x{Local.Count} - {Local.LoopIndex}:{Local.LoopValue}
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
+2
-2
@@ -135,8 +135,8 @@ public static class WorkflowProvider
|
||||
x{Local.Count} - {Local.LoopIndex}:{Local.LoopValue}
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
+2
-2
@@ -135,8 +135,8 @@ public static class WorkflowProvider
|
||||
x{Local.Count} - {Local.LoopIndex}:{Local.LoopValue}
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
+2
-2
@@ -77,8 +77,8 @@ public static class WorkflowProvider
|
||||
Input: "{Local.TestValue}"
|
||||
"""
|
||||
);
|
||||
AgentRunResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentRunResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
AgentResponse response = new([new ChatMessage(ChatRole.Assistant, activityText)]);
|
||||
await context.AddEventAsync(new AgentResponseEvent(this.Id, response)).ConfigureAwait(false);
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
@@ -135,26 +135,26 @@ public class AgentWorkflowBuilderTests
|
||||
{
|
||||
public override string Name => name;
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
=> new DoubleEchoAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
=> new(new DoubleEchoAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
=> new DoubleEchoAgentThread();
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
=> new(new DoubleEchoAgentThread());
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException();
|
||||
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,7 +393,7 @@ public class AgentWorkflowBuilderTests
|
||||
WorkflowOutputEvent? output = null;
|
||||
await foreach (WorkflowEvent evt in run.WatchStreamAsync().ConfigureAwait(false))
|
||||
{
|
||||
if (evt is AgentRunUpdateEvent executorComplete)
|
||||
if (evt is AgentResponseUpdateEvent executorComplete)
|
||||
{
|
||||
sb.Append(executorComplete.Data);
|
||||
}
|
||||
@@ -409,7 +409,7 @@ public class AgentWorkflowBuilderTests
|
||||
|
||||
private sealed class DoubleEchoAgentWithBarrier(string name, StrongBox<TaskCompletionSource<bool>> barrier, StrongBox<int> remaining) : DoubleEchoAgent(name)
|
||||
{
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Interlocked.Decrement(ref remaining.Value) == 0)
|
||||
|
||||
@@ -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<AgentRunResponseUpdate> ToAgentRunStream(this string message, DateTimeOffset? createdAt = null, string? messageId = null, string? responseId = null, string? agentId = null, string? authorName = null)
|
||||
public static IEnumerable<AgentResponseUpdate> 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<AgentRunResponseUpdate> StreamMessage(this ChatMessage message, string? responseId = null, string? agentId = null)
|
||||
public static IEnumerable<AgentResponseUpdate> 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<AgentRunResponseUpdate> StreamMessages(this List<ChatMessage> messages, string? agentId = null) =>
|
||||
public static IEnumerable<AgentResponseUpdate> StreamMessages(this List<ChatMessage> messages, string? agentId = null) =>
|
||||
messages.SelectMany(message => message.StreamMessage(agentId));
|
||||
|
||||
public static List<ChatMessage> ToChatMessages(this IEnumerable<string> messages, string? authorName = null)
|
||||
|
||||
@@ -39,7 +39,7 @@ public class InProcessExecutionTests
|
||||
run.OutgoingEvents.Should().NotBeEmpty("workflow should produce events during execution");
|
||||
|
||||
// Check that we have an agent execution event
|
||||
var agentEvents = run.OutgoingEvents.OfType<AgentRunUpdateEvent>().ToList();
|
||||
var agentEvents = run.OutgoingEvents.OfType<AgentResponseUpdateEvent>().ToList();
|
||||
agentEvents.Should().NotBeEmpty("agent should have executed and produced update events");
|
||||
|
||||
// Check that we have output events
|
||||
@@ -79,7 +79,7 @@ public class InProcessExecutionTests
|
||||
events.Should().NotBeEmpty("workflow should produce events during execution");
|
||||
|
||||
// Check that we have agent execution events
|
||||
var agentEvents = events.OfType<AgentRunUpdateEvent>().ToList();
|
||||
var agentEvents = events.OfType<AgentResponseUpdateEvent>().ToList();
|
||||
agentEvents.Should().NotBeEmpty("agent should have executed and produced update events");
|
||||
|
||||
// Check that we have output events
|
||||
@@ -125,8 +125,8 @@ public class InProcessExecutionTests
|
||||
nonStreamingEvents.Should().NotBeEmpty("non-streaming version should also produce events");
|
||||
|
||||
// Both should have similar types of events
|
||||
var streamingAgentEvents = streamingEvents.OfType<AgentRunUpdateEvent>().Count();
|
||||
var nonStreamingAgentEvents = nonStreamingEvents.OfType<AgentRunUpdateEvent>().Count();
|
||||
var streamingAgentEvents = streamingEvents.OfType<AgentResponseUpdateEvent>().Count();
|
||||
var nonStreamingAgentEvents = nonStreamingEvents.OfType<AgentResponseUpdateEvent>().Count();
|
||||
|
||||
nonStreamingAgentEvents.Should().Be(streamingAgentEvents,
|
||||
"both versions should produce the same number of agent events");
|
||||
@@ -144,12 +144,12 @@ public class InProcessExecutionTests
|
||||
|
||||
public override string Name { get; }
|
||||
|
||||
public override AgentThread GetNewThread() => new SimpleTestAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) => new(new SimpleTestAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(System.Text.Json.JsonElement serializedThread,
|
||||
System.Text.Json.JsonSerializerOptions? jsonSerializerOptions = null) => new SimpleTestAgentThread();
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(System.Text.Json.JsonElement serializedThread,
|
||||
System.Text.Json.JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) => new(new SimpleTestAgentThread());
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(
|
||||
protected override Task<AgentResponse> RunCoreAsync(
|
||||
IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
|
||||
IEnumerable<ChatMessage> 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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -24,16 +24,16 @@ public class RepresentationTests
|
||||
|
||||
private sealed class TestAgent : AIAgent
|
||||
{
|
||||
public override AgentThread GetNewThread()
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
=> throw new NotImplementedException();
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException();
|
||||
|
||||
protected override IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
protected override IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
|
||||
+10
-10
@@ -39,9 +39,9 @@ internal static class Step6EntryPoint
|
||||
{
|
||||
Debug.WriteLine($"{executorCompleted.ExecutorId}: {executorCompleted.Data}");
|
||||
}
|
||||
else if (evt is AgentRunUpdateEvent update)
|
||||
else if (evt is AgentResponseUpdateEvent update)
|
||||
{
|
||||
AgentRunResponse response = update.AsResponse();
|
||||
AgentResponse response = update.AsResponse();
|
||||
|
||||
foreach (ChatMessage message in response.Messages)
|
||||
{
|
||||
@@ -60,23 +60,23 @@ internal sealed class HelloAgent(string id = nameof(HelloAgent)) : AIAgent
|
||||
protected override string? IdCore => id;
|
||||
public override string? Name => id;
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
=> new HelloAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
=> new(new HelloAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
=> new HelloAgentThread();
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
=> new(new HelloAgentThread());
|
||||
|
||||
protected override async Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override async Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
IEnumerable<AgentRunResponseUpdate> update = [
|
||||
IEnumerable<AgentResponseUpdate> update = [
|
||||
await this.RunCoreStreamingAsync(messages, thread, options, cancellationToken)
|
||||
.SingleAsync(cancellationToken)
|
||||
.ConfigureAwait(false)];
|
||||
|
||||
return update.ToAgentRunResponse();
|
||||
return update.ToAgentResponse();
|
||||
}
|
||||
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
yield return new(ChatRole.Assistant, "Hello World!")
|
||||
{
|
||||
|
||||
+2
-2
@@ -19,8 +19,8 @@ internal static class Step7EntryPoint
|
||||
|
||||
for (int i = 0; i < numIterations; i++)
|
||||
{
|
||||
AgentThread thread = agent.GetNewThread();
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(thread).ConfigureAwait(false))
|
||||
AgentThread thread = await agent.GetNewThreadAsync();
|
||||
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(thread).ConfigureAwait(false))
|
||||
{
|
||||
if (update.RawRepresentation is WorkflowEvent)
|
||||
{
|
||||
|
||||
+2
-2
@@ -21,10 +21,10 @@ internal static class Step10EntryPoint
|
||||
{
|
||||
AIAgent hostAgent = WorkflowInstance.AsAgent("echo-workflow", "EchoW", executionEnvironment: executionEnvironment);
|
||||
|
||||
AgentThread thread = hostAgent.GetNewThread();
|
||||
AgentThread thread = await hostAgent.GetNewThreadAsync();
|
||||
foreach (string input in inputs)
|
||||
{
|
||||
AgentRunResponse response;
|
||||
AgentResponse response;
|
||||
ResponseContinuationToken? continuationToken = null;
|
||||
do
|
||||
{
|
||||
|
||||
+2
-2
@@ -33,10 +33,10 @@ internal static class Step11EntryPoint
|
||||
{
|
||||
AIAgent hostAgent = WorkflowInstance.AsAgent("echo-workflow", "EchoW", executionEnvironment: executionEnvironment);
|
||||
|
||||
AgentThread thread = hostAgent.GetNewThread();
|
||||
AgentThread thread = await hostAgent.GetNewThreadAsync();
|
||||
foreach (string input in inputs)
|
||||
{
|
||||
AgentRunResponse response;
|
||||
AgentResponse response;
|
||||
ResponseContinuationToken? continuationToken = null;
|
||||
do
|
||||
{
|
||||
|
||||
+2
-2
@@ -69,10 +69,10 @@ internal static class Step12EntryPoint
|
||||
{
|
||||
AIAgent hostAgent = WorkflowInstance.AsAgent("echo-workflow", "EchoW", executionEnvironment: executionEnvironment);
|
||||
|
||||
AgentThread thread = hostAgent.GetNewThread();
|
||||
AgentThread thread = await hostAgent.GetNewThreadAsync();
|
||||
foreach (string input in inputs)
|
||||
{
|
||||
AgentRunResponse response;
|
||||
AgentResponse response;
|
||||
ResponseContinuationToken? continuationToken = null;
|
||||
do
|
||||
{
|
||||
|
||||
+8
-8
@@ -51,32 +51,32 @@ public class SpecializedExecutorSmokeTests
|
||||
return result;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
=> new TestAgentThread();
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
=> new(new TestAgentThread());
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
=> new TestAgentThread();
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
=> new(new TestAgentThread());
|
||||
|
||||
public static TestAIAgent FromStrings(params string[] messages) =>
|
||||
new(ToChatMessages(messages));
|
||||
|
||||
public List<ChatMessage> Messages { get; } = Validate(messages) ?? [];
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(new AgentRunResponse(this.Messages)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> 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,
|
||||
|
||||
@@ -16,15 +16,13 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre
|
||||
protected override string? IdCore => id;
|
||||
public override string? Name => name ?? base.Name;
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override async ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return serializedThread.Deserialize<EchoAgentThread>(jsonSerializerOptions) ?? this.GetNewThread();
|
||||
return serializedThread.Deserialize<EchoAgentThread>(jsonSerializerOptions) ?? await this.GetNewThreadAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
{
|
||||
return new EchoAgentThread();
|
||||
}
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default) =>
|
||||
new(new EchoAgentThread());
|
||||
|
||||
private static ChatMessage UpdateThread(ChatMessage message, InMemoryAgentThread? thread = null)
|
||||
{
|
||||
@@ -60,9 +58,9 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre
|
||||
return [];
|
||||
}
|
||||
|
||||
protected override Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
AgentRunResponse result =
|
||||
AgentResponse result =
|
||||
new(this.EchoMessages(messages, thread, options).ToList())
|
||||
{
|
||||
AgentId = this.Id,
|
||||
@@ -73,7 +71,7 @@ internal class TestEchoAgent(string? id = null, string? name = null, string? pre
|
||||
return Task.FromResult(result);
|
||||
}
|
||||
|
||||
protected override async IAsyncEnumerable<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
string responseId = Guid.NewGuid().ToString("N");
|
||||
|
||||
|
||||
@@ -41,23 +41,23 @@ public class WorkflowHostSmokeTests
|
||||
{ }
|
||||
}
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
public override ValueTask<AgentThread> DeserializeThreadAsync(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return new Thread(serializedThread, jsonSerializerOptions);
|
||||
return new(new Thread(serializedThread, jsonSerializerOptions));
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread()
|
||||
public override ValueTask<AgentThread> GetNewThreadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return new Thread();
|
||||
return new(new Thread());
|
||||
}
|
||||
|
||||
protected override async Task<AgentRunResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
protected override async Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> 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<AgentRunResponseUpdate> updates = await workflow.AsAgent("WorkflowAgent", includeExceptionDetails: includeExceptionDetails)
|
||||
List<AgentResponseUpdate> 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())
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user