mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
a5b36dc379
* 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> * Remove from feature branch * Remove ollama changes --------- Signed-off-by: dependabot[bot] <support@github.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>
1004 lines
44 KiB
C#
1004 lines
44 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
using System.Diagnostics;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using ModelContextProtocol.Client;
|
|
using ModelContextProtocol.Protocol;
|
|
using Xunit.Abstractions;
|
|
|
|
namespace Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests;
|
|
|
|
[Collection("Samples")]
|
|
[Trait("Category", "SampleValidation")]
|
|
public sealed class SamplesValidation(ITestOutputHelper outputHelper) : IAsyncLifetime
|
|
{
|
|
private const string AzureFunctionsPort = "7071";
|
|
private const string AzuritePort = "10000";
|
|
private const string DtsPort = "8080";
|
|
private const string RedisPort = "6379";
|
|
|
|
private static readonly string s_dotnetTargetFramework = GetTargetFramework();
|
|
private static readonly HttpClient s_sharedHttpClient = new();
|
|
private static readonly IConfiguration s_configuration =
|
|
new ConfigurationBuilder()
|
|
.AddUserSecrets(Assembly.GetExecutingAssembly())
|
|
.AddEnvironmentVariables()
|
|
.Build();
|
|
|
|
private static bool s_infrastructureStarted;
|
|
private static readonly TimeSpan s_orchestrationTimeout = TimeSpan.FromMinutes(1);
|
|
private static readonly string s_samplesPath = Path.GetFullPath(
|
|
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "..", "samples", "AzureFunctions"));
|
|
|
|
private readonly ITestOutputHelper _outputHelper = outputHelper;
|
|
|
|
async Task IAsyncLifetime.InitializeAsync()
|
|
{
|
|
if (!s_infrastructureStarted)
|
|
{
|
|
await this.StartSharedInfrastructureAsync();
|
|
s_infrastructureStarted = true;
|
|
}
|
|
}
|
|
|
|
async Task IAsyncLifetime.DisposeAsync()
|
|
{
|
|
// Nothing to clean up
|
|
await Task.CompletedTask;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task SingleAgentSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "01_SingleAgent");
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
Uri startUri = new($"http://localhost:{AzureFunctionsPort}/api/agents/Joker/run");
|
|
this._outputHelper.WriteLine($"Starting single agent orchestration via POST request to {startUri}...");
|
|
|
|
// Test the agent endpoint as described in the README
|
|
const string RequestBody = "Tell me a joke about a pirate.";
|
|
using HttpContent content = new StringContent(RequestBody, Encoding.UTF8, "text/plain");
|
|
|
|
using HttpResponseMessage response = await s_sharedHttpClient.PostAsync(startUri, content);
|
|
|
|
// The response is expected to be a plain text response with the agent's reply (the joke)
|
|
Assert.True(response.IsSuccessStatusCode, $"Agent request failed with status: {response.StatusCode}");
|
|
Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
|
|
string responseText = await response.Content.ReadAsStringAsync();
|
|
Assert.NotEmpty(responseText);
|
|
this._outputHelper.WriteLine($"Agent run response: {responseText}");
|
|
|
|
// The response headers should include the agent thread ID, which can be used to continue the conversation.
|
|
string? threadId = response.Headers.GetValues("x-ms-thread-id")?.FirstOrDefault();
|
|
Assert.NotNull(threadId);
|
|
Assert.NotEmpty(threadId);
|
|
|
|
this._outputHelper.WriteLine($"Agent thread ID: {threadId}");
|
|
|
|
// Wait for up to 30 seconds to see if the agent response is available in the logs
|
|
await this.WaitForConditionAsync(
|
|
condition: () =>
|
|
{
|
|
lock (logs)
|
|
{
|
|
bool exists = logs.Any(
|
|
log => log.Message.Contains("Response:") && log.Message.Contains(threadId));
|
|
return Task.FromResult(exists);
|
|
}
|
|
},
|
|
message: "Agent response is available",
|
|
timeout: TimeSpan.FromSeconds(30));
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task SingleAgentOrchestrationChainingSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "02_AgentOrchestration_Chaining");
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
Uri startUri = new($"http://localhost:{AzureFunctionsPort}/api/singleagent/run");
|
|
this._outputHelper.WriteLine($"Starting single agent orchestration via POST request to {startUri}...");
|
|
|
|
// Start the orchestration
|
|
using HttpResponseMessage startResponse = await s_sharedHttpClient.PostAsync(startUri, content: null);
|
|
|
|
Assert.True(
|
|
startResponse.IsSuccessStatusCode,
|
|
$"Start orchestration failed with status: {startResponse.StatusCode}");
|
|
string startResponseText = await startResponse.Content.ReadAsStringAsync();
|
|
JsonElement startResult = JsonElement.Parse(startResponseText);
|
|
|
|
Assert.True(startResult.TryGetProperty("statusQueryGetUri", out JsonElement statusUriElement));
|
|
Uri statusUri = new(statusUriElement.GetString()!);
|
|
|
|
// Wait for orchestration to complete
|
|
await this.WaitForOrchestrationCompletionAsync(statusUri);
|
|
|
|
// Verify the final result
|
|
using HttpResponseMessage statusResponse = await s_sharedHttpClient.GetAsync(statusUri);
|
|
Assert.True(
|
|
statusResponse.IsSuccessStatusCode,
|
|
$"Status check failed with status: {statusResponse.StatusCode}");
|
|
|
|
string statusText = await statusResponse.Content.ReadAsStringAsync();
|
|
JsonElement statusResult = JsonElement.Parse(statusText);
|
|
|
|
Assert.Equal("Completed", statusResult.GetProperty("runtimeStatus").GetString());
|
|
Assert.True(statusResult.TryGetProperty("output", out JsonElement outputElement));
|
|
string? output = outputElement.GetString();
|
|
|
|
// Can't really validate the output since it's non-deterministic, but we can at least check it's non-empty
|
|
Assert.NotNull(output);
|
|
Assert.True(output.Length > 20, "Output is unexpectedly short");
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task MultiAgentOrchestrationConcurrentSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "03_AgentOrchestration_Concurrency");
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
// Start the multi-agent orchestration
|
|
const string RequestBody = "What is temperature?";
|
|
using HttpContent content = new StringContent(RequestBody, Encoding.UTF8, "text/plain");
|
|
|
|
Uri startUri = new($"http://localhost:{AzureFunctionsPort}/api/multiagent/run");
|
|
this._outputHelper.WriteLine($"Starting multi agent orchestration via POST request to {startUri}...");
|
|
using HttpResponseMessage startResponse = await s_sharedHttpClient.PostAsync(startUri, content);
|
|
|
|
Assert.True(startResponse.IsSuccessStatusCode, $"Start orchestration failed with status: {startResponse.StatusCode}");
|
|
string startResponseText = await startResponse.Content.ReadAsStringAsync();
|
|
JsonElement startResult = JsonElement.Parse(startResponseText);
|
|
|
|
Assert.True(startResult.TryGetProperty("instanceId", out JsonElement instanceIdElement));
|
|
Assert.True(startResult.TryGetProperty("statusQueryGetUri", out JsonElement statusUriElement));
|
|
|
|
Uri statusUri = new(statusUriElement.GetString()!);
|
|
|
|
// Wait for orchestration to complete
|
|
await this.WaitForOrchestrationCompletionAsync(statusUri);
|
|
|
|
// Verify the final result
|
|
using HttpResponseMessage statusResponse = await s_sharedHttpClient.GetAsync(statusUri);
|
|
Assert.True(statusResponse.IsSuccessStatusCode, $"Status check failed with status: {statusResponse.StatusCode}");
|
|
|
|
string statusText = await statusResponse.Content.ReadAsStringAsync();
|
|
JsonElement statusResult = JsonElement.Parse(statusText);
|
|
|
|
Assert.Equal("Completed", statusResult.GetProperty("runtimeStatus").GetString());
|
|
Assert.True(statusResult.TryGetProperty("output", out JsonElement outputElement));
|
|
|
|
// Verify both physicist and chemist responses are present
|
|
Assert.True(outputElement.TryGetProperty("physicist", out JsonElement physicistElement));
|
|
Assert.True(outputElement.TryGetProperty("chemist", out JsonElement chemistElement));
|
|
|
|
string physicistResponse = physicistElement.GetString()!;
|
|
string chemistResponse = chemistElement.GetString()!;
|
|
|
|
Assert.NotEmpty(physicistResponse);
|
|
Assert.NotEmpty(chemistResponse);
|
|
Assert.Contains("temperature", physicistResponse, StringComparison.OrdinalIgnoreCase);
|
|
Assert.Contains("temperature", chemistResponse, StringComparison.OrdinalIgnoreCase);
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task MultiAgentOrchestrationConditionalsSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "04_AgentOrchestration_Conditionals");
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
// Test with legitimate email
|
|
await this.TestSpamDetectionAsync("email-001",
|
|
"Hi John, I hope you're doing well. I wanted to follow up on our meeting yesterday about the quarterly report. Could you please send me the updated figures by Friday? Thanks!",
|
|
expectedSpam: false);
|
|
|
|
// Test with spam email
|
|
await this.TestSpamDetectionAsync("email-002",
|
|
"URGENT! You've won $1,000,000! Click here now to claim your prize! Limited time offer! Don't miss out!",
|
|
expectedSpam: true);
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task SingleAgentOrchestrationHITLSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "05_AgentOrchestration_HITL");
|
|
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
// Start the HITL orchestration with short timeout for testing
|
|
// TODO: Add validation for the approval case
|
|
object requestBody = new
|
|
{
|
|
topic = "The Future of Artificial Intelligence",
|
|
max_review_attempts = 3,
|
|
approval_timeout_hours = 0.001 // Very short timeout for testing
|
|
};
|
|
|
|
string jsonContent = JsonSerializer.Serialize(requestBody);
|
|
using HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
|
|
|
|
Uri startUri = new($"http://localhost:{AzureFunctionsPort}/api/hitl/run");
|
|
this._outputHelper.WriteLine($"Starting HITL orchestration via POST request to {startUri}...");
|
|
using HttpResponseMessage startResponse = await s_sharedHttpClient.PostAsync(startUri, content);
|
|
|
|
Assert.True(
|
|
startResponse.IsSuccessStatusCode,
|
|
$"Start HITL orchestration failed with status: {startResponse.StatusCode}");
|
|
string startResponseText = await startResponse.Content.ReadAsStringAsync();
|
|
JsonElement startResult = JsonElement.Parse(startResponseText);
|
|
|
|
Assert.True(startResult.TryGetProperty("statusQueryGetUri", out JsonElement statusUriElement));
|
|
Uri statusUri = new(statusUriElement.GetString()!);
|
|
|
|
// Wait for orchestration to complete (it should timeout due to short timeout)
|
|
await this.WaitForOrchestrationCompletionAsync(statusUri);
|
|
|
|
// Verify the final result
|
|
using HttpResponseMessage statusResponse = await s_sharedHttpClient.GetAsync(statusUri);
|
|
Assert.True(
|
|
statusResponse.IsSuccessStatusCode,
|
|
$"Status check failed with status: {statusResponse.StatusCode}");
|
|
|
|
string statusText = await statusResponse.Content.ReadAsStringAsync();
|
|
this._outputHelper.WriteLine($"HITL orchestration status text: {statusText}");
|
|
|
|
JsonElement statusResult = JsonElement.Parse(statusText);
|
|
|
|
// The orchestration should complete with a failed status due to timeout
|
|
Assert.Equal("Failed", statusResult.GetProperty("runtimeStatus").GetString());
|
|
Assert.True(statusResult.TryGetProperty("failureDetails", out JsonElement failureDetailsElement));
|
|
Assert.True(failureDetailsElement.TryGetProperty("ErrorType", out JsonElement errorTypeElement));
|
|
Assert.Equal("System.TimeoutException", errorTypeElement.GetString());
|
|
Assert.True(failureDetailsElement.TryGetProperty("ErrorMessage", out JsonElement errorMessageElement));
|
|
Assert.StartsWith("Human approval timed out", errorMessageElement.GetString());
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task LongRunningToolsSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "06_LongRunningTools");
|
|
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
// Test starting an agent that schedules a content generation orchestration
|
|
const string Prompt = "Start a content generation workflow for the topic 'The Future of Artificial Intelligence'";
|
|
using HttpContent messageContent = new StringContent(Prompt, Encoding.UTF8, "text/plain");
|
|
|
|
Uri runAgentUri = new($"http://localhost:{AzureFunctionsPort}/api/agents/publisher/run");
|
|
|
|
this._outputHelper.WriteLine($"Starting agent tool orchestration via POST request to {runAgentUri}...");
|
|
using HttpResponseMessage startResponse = await s_sharedHttpClient.PostAsync(runAgentUri, messageContent);
|
|
|
|
Assert.True(
|
|
startResponse.IsSuccessStatusCode,
|
|
$"Start agent request failed with status: {startResponse.StatusCode}");
|
|
|
|
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
|
|
startResponse.Headers.TryGetValues("x-ms-thread-id", out IEnumerable<string>? agentIdValues);
|
|
string? threadId = agentIdValues?.FirstOrDefault();
|
|
Assert.NotNull(threadId);
|
|
Assert.NotEmpty(threadId);
|
|
|
|
// Wait for the orchestration to report that it's waiting for human approval
|
|
await this.WaitForConditionAsync(
|
|
condition: () =>
|
|
{
|
|
// For now, we have to rely on the logs to check for the "NOTIFICATION" message that gets generated by the activity function.
|
|
// TODO: Synchronously prompt the agent for status
|
|
lock (logs)
|
|
{
|
|
bool exists = logs.Any(log => log.Message.Contains("NOTIFICATION: Please review the following content for approval"));
|
|
return Task.FromResult(exists);
|
|
}
|
|
},
|
|
message: "Orchestration is requesting human feedback",
|
|
timeout: TimeSpan.FromSeconds(60));
|
|
|
|
// Approve the content
|
|
Uri approvalUri = new($"{runAgentUri}?thread_id={threadId}");
|
|
using HttpContent approvalContent = new StringContent("Approve the content", Encoding.UTF8, "text/plain");
|
|
using HttpResponseMessage approvalResponse = await s_sharedHttpClient.PostAsync(approvalUri, approvalContent);
|
|
Assert.True(approvalResponse.IsSuccessStatusCode, $"Approve content request failed with status: {approvalResponse.StatusCode}");
|
|
|
|
// Wait for the publish notification to be logged
|
|
await this.WaitForConditionAsync(
|
|
condition: () =>
|
|
{
|
|
lock (logs)
|
|
{
|
|
// TODO: Synchronously prompt the agent for status
|
|
bool exists = logs.Any(log => log.Message.Contains("PUBLISHING: Content has been published successfully"));
|
|
return Task.FromResult(exists);
|
|
}
|
|
},
|
|
message: "Content published notification is logged",
|
|
timeout: TimeSpan.FromSeconds(60));
|
|
|
|
// Verify the final orchestration status by asking the agent for the status
|
|
Uri statusUri = new($"{runAgentUri}?thread_id={threadId}");
|
|
await this.WaitForConditionAsync(
|
|
condition: async () =>
|
|
{
|
|
this._outputHelper.WriteLine($"Checking status of orchestration at {statusUri}...");
|
|
|
|
using StringContent content = new("Get the status of the workflow", Encoding.UTF8, "text/plain");
|
|
using HttpResponseMessage statusResponse = await s_sharedHttpClient.PostAsync(statusUri, content);
|
|
Assert.True(
|
|
statusResponse.IsSuccessStatusCode,
|
|
$"Status check failed with status: {statusResponse.StatusCode}");
|
|
string statusText = await statusResponse.Content.ReadAsStringAsync();
|
|
this._outputHelper.WriteLine($"Status text: {statusText}");
|
|
|
|
bool isCompleted = statusText.Contains("Completed", StringComparison.OrdinalIgnoreCase);
|
|
bool hasContent = statusText.Contains(
|
|
"The Future of Artificial Intelligence",
|
|
StringComparison.OrdinalIgnoreCase);
|
|
return isCompleted && hasContent;
|
|
},
|
|
message: "Orchestration is completed",
|
|
timeout: TimeSpan.FromSeconds(60));
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AgentAsMcpToolAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "07_AgentAsMcpTool");
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
IClientTransport clientTransport = new HttpClientTransport(new()
|
|
{
|
|
Endpoint = new Uri($"http://localhost:{AzureFunctionsPort}/runtime/webhooks/mcp")
|
|
});
|
|
|
|
await using McpClient mcpClient = await McpClient.CreateAsync(clientTransport!);
|
|
|
|
// Ensure the expected tools are present.
|
|
IList<McpClientTool> tools = await mcpClient.ListToolsAsync();
|
|
|
|
Assert.Single(tools, t => t.Name == "StockAdvisor");
|
|
Assert.Single(tools, t => t.Name == "PlantAdvisor");
|
|
|
|
// Invoke the tools to verify they work as expected.
|
|
string stockPriceResponse = await this.InvokeMcpToolAsync(mcpClient, "StockAdvisor", "MSFT ATH");
|
|
string plantSuggestionResponse = await this.InvokeMcpToolAsync(mcpClient, "PlantAdvisor", "Low light plant");
|
|
Assert.NotEmpty(stockPriceResponse);
|
|
Assert.NotEmpty(plantSuggestionResponse);
|
|
|
|
// Wait for up to 30 seconds to see if the agent responses are available in the logs
|
|
await this.WaitForConditionAsync(
|
|
condition: () =>
|
|
{
|
|
lock (logs)
|
|
{
|
|
bool expectedLogsPresent = logs.Count(log => log.Message.Contains("Response:")) >= 2;
|
|
return Task.FromResult(expectedLogsPresent);
|
|
}
|
|
},
|
|
message: "Agent response is available",
|
|
timeout: TimeSpan.FromSeconds(30));
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ReliableStreamingSampleValidationAsync()
|
|
{
|
|
string samplePath = Path.Combine(s_samplesPath, "08_ReliableStreaming");
|
|
await this.RunSampleTestAsync(samplePath, async (logs) =>
|
|
{
|
|
Uri createUri = new($"http://localhost:{AzureFunctionsPort}/api/agent/create");
|
|
this._outputHelper.WriteLine($"Starting reliable streaming agent via POST request to {createUri}...");
|
|
|
|
// Test the agent endpoint with a simple prompt
|
|
const string RequestBody = "Plan a 3-day trip to Seattle. Include daily activities.";
|
|
using HttpContent content = new StringContent(RequestBody, Encoding.UTF8, "text/plain");
|
|
using HttpRequestMessage request = new(HttpMethod.Post, createUri)
|
|
{
|
|
Content = content
|
|
};
|
|
request.Headers.Add("Accept", "text/plain");
|
|
|
|
using HttpResponseMessage response = await s_sharedHttpClient.SendAsync(
|
|
request,
|
|
HttpCompletionOption.ResponseHeadersRead);
|
|
|
|
// The response should be successful
|
|
Assert.True(response.IsSuccessStatusCode, $"Agent request failed with status: {response.StatusCode}");
|
|
Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
|
|
|
|
// The response headers should include the conversation ID
|
|
string? conversationId = response.Headers.GetValues("x-conversation-id")?.FirstOrDefault();
|
|
Assert.NotNull(conversationId);
|
|
Assert.NotEmpty(conversationId);
|
|
this._outputHelper.WriteLine($"Agent conversation ID: {conversationId}");
|
|
|
|
// Read the streamed response
|
|
using Stream responseStream = await response.Content.ReadAsStreamAsync();
|
|
using StreamReader reader = new(responseStream);
|
|
StringBuilder responseText = new();
|
|
char[] buffer = new char[1024];
|
|
int bytesRead;
|
|
|
|
// Read for a reasonable amount of time to get some content
|
|
using CancellationTokenSource readTimeout = new(TimeSpan.FromSeconds(30));
|
|
try
|
|
{
|
|
while (!readTimeout.Token.IsCancellationRequested)
|
|
{
|
|
bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length);
|
|
if (bytesRead == 0)
|
|
{
|
|
// Check if we've received enough content
|
|
if (responseText.Length > 50)
|
|
{
|
|
break;
|
|
}
|
|
await Task.Delay(100, readTimeout.Token);
|
|
continue;
|
|
}
|
|
|
|
responseText.Append(buffer, 0, bytesRead);
|
|
if (responseText.Length > 200)
|
|
{
|
|
// We've received enough content to validate
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// Timeout is acceptable if we got some content
|
|
}
|
|
|
|
string responseContent = responseText.ToString();
|
|
Assert.True(responseContent.Length > 0, "Expected to receive some streamed content");
|
|
this._outputHelper.WriteLine($"Received {responseContent.Length} characters of streamed content");
|
|
|
|
// Test resumption by calling the stream endpoint
|
|
Uri streamUri = new($"http://localhost:{AzureFunctionsPort}/api/agent/stream/{conversationId}");
|
|
this._outputHelper.WriteLine($"Testing stream resumption via GET request to {streamUri}...");
|
|
|
|
using HttpRequestMessage streamRequest = new(HttpMethod.Get, streamUri);
|
|
streamRequest.Headers.Add("Accept", "text/plain");
|
|
|
|
using HttpResponseMessage streamResponse = await s_sharedHttpClient.SendAsync(
|
|
streamRequest,
|
|
HttpCompletionOption.ResponseHeadersRead);
|
|
Assert.True(streamResponse.IsSuccessStatusCode, $"Stream request failed with status: {streamResponse.StatusCode}");
|
|
Assert.Equal("text/plain", streamResponse.Content.Headers.ContentType?.MediaType);
|
|
|
|
// Verify the conversation ID header is present
|
|
string? resumedConversationId = streamResponse.Headers.GetValues("x-conversation-id")?.FirstOrDefault();
|
|
Assert.Equal(conversationId, resumedConversationId);
|
|
|
|
// Read some content from the resumed stream
|
|
using Stream resumedStream = await streamResponse.Content.ReadAsStreamAsync();
|
|
using StreamReader resumedReader = new(resumedStream);
|
|
StringBuilder resumedText = new();
|
|
|
|
using CancellationTokenSource resumedReadTimeout = new(TimeSpan.FromSeconds(10));
|
|
try
|
|
{
|
|
while (!resumedReadTimeout.Token.IsCancellationRequested)
|
|
{
|
|
bytesRead = await resumedReader.ReadAsync(buffer, 0, buffer.Length);
|
|
if (bytesRead == 0)
|
|
{
|
|
if (resumedText.Length > 50)
|
|
{
|
|
break;
|
|
}
|
|
await Task.Delay(100, resumedReadTimeout.Token);
|
|
continue;
|
|
}
|
|
|
|
resumedText.Append(buffer, 0, bytesRead);
|
|
if (resumedText.Length > 100)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// Timeout is acceptable if we got some content
|
|
}
|
|
|
|
string resumedContent = resumedText.ToString();
|
|
Assert.True(resumedContent.Length > 0, "Expected to receive some content from resumed stream");
|
|
this._outputHelper.WriteLine($"Received {resumedContent.Length} characters from resumed stream");
|
|
});
|
|
}
|
|
|
|
private async Task<string> InvokeMcpToolAsync(McpClient mcpClient, string toolName, string query)
|
|
{
|
|
this._outputHelper.WriteLine($"Invoking MCP tool '{toolName}'...");
|
|
|
|
CallToolResult result = await mcpClient.CallToolAsync(
|
|
toolName,
|
|
arguments: new Dictionary<string, object?> { { "query", query } });
|
|
|
|
string toolCallResult = ((TextContentBlock)result.Content[0]).Text;
|
|
this._outputHelper.WriteLine($"MCP tool '{toolName}' response: {toolCallResult}");
|
|
|
|
return toolCallResult;
|
|
}
|
|
|
|
private async Task TestSpamDetectionAsync(string emailId, string emailContent, bool expectedSpam)
|
|
{
|
|
object requestBody = new
|
|
{
|
|
email_id = emailId,
|
|
email_content = emailContent
|
|
};
|
|
|
|
string jsonContent = JsonSerializer.Serialize(requestBody);
|
|
using HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
|
|
|
|
Uri startUri = new($"http://localhost:{AzureFunctionsPort}/api/spamdetection/run");
|
|
this._outputHelper.WriteLine($"Starting spam detection orchestration via POST request to {startUri}...");
|
|
using HttpResponseMessage startResponse = await s_sharedHttpClient.PostAsync(startUri, content);
|
|
|
|
Assert.True(startResponse.IsSuccessStatusCode, $"Start orchestration failed with status: {startResponse.StatusCode}");
|
|
string startResponseText = await startResponse.Content.ReadAsStringAsync();
|
|
JsonElement startResult = JsonElement.Parse(startResponseText);
|
|
|
|
Assert.True(startResult.TryGetProperty("statusQueryGetUri", out JsonElement statusUriElement));
|
|
Uri statusUri = new(statusUriElement.GetString()!);
|
|
|
|
// Wait for orchestration to complete
|
|
await this.WaitForOrchestrationCompletionAsync(statusUri);
|
|
|
|
// Verify the final result
|
|
using HttpResponseMessage statusResponse = await s_sharedHttpClient.GetAsync(statusUri);
|
|
Assert.True(statusResponse.IsSuccessStatusCode, $"Status check failed with status: {statusResponse.StatusCode}");
|
|
|
|
string statusText = await statusResponse.Content.ReadAsStringAsync();
|
|
JsonElement statusResult = JsonElement.Parse(statusText);
|
|
|
|
Assert.Equal("Completed", statusResult.GetProperty("runtimeStatus").GetString());
|
|
Assert.True(statusResult.TryGetProperty("output", out JsonElement outputElement));
|
|
|
|
string output = outputElement.GetString()!;
|
|
Assert.NotEmpty(output);
|
|
|
|
if (expectedSpam)
|
|
{
|
|
Assert.Contains("spam", output, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
else
|
|
{
|
|
Assert.Contains("sent", output, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
}
|
|
|
|
private async Task StartSharedInfrastructureAsync()
|
|
{
|
|
// Start Azurite if it's not already running
|
|
if (!await this.IsAzuriteRunningAsync())
|
|
{
|
|
await this.StartDockerContainerAsync(
|
|
containerName: "azurite",
|
|
image: "mcr.microsoft.com/azure-storage/azurite",
|
|
ports: ["-p", "10000:10000", "-p", "10001:10001", "-p", "10002:10002"]);
|
|
|
|
// Wait for Azurite
|
|
await this.WaitForConditionAsync(this.IsAzuriteRunningAsync, "Azurite is running", TimeSpan.FromSeconds(30));
|
|
}
|
|
|
|
// Start DTS emulator if it's not already running
|
|
if (!await this.IsDtsEmulatorRunningAsync())
|
|
{
|
|
await this.StartDockerContainerAsync(
|
|
containerName: "dts-emulator",
|
|
image: "mcr.microsoft.com/dts/dts-emulator:latest",
|
|
ports: ["-p", "8080:8080", "-p", "8082:8082"]);
|
|
|
|
// Wait for DTS emulator
|
|
await this.WaitForConditionAsync(
|
|
condition: this.IsDtsEmulatorRunningAsync,
|
|
message: "DTS emulator is running",
|
|
timeout: TimeSpan.FromSeconds(30));
|
|
}
|
|
|
|
// Start Redis if it's not already running
|
|
if (!await this.IsRedisRunningAsync())
|
|
{
|
|
await this.StartDockerContainerAsync(
|
|
containerName: "redis",
|
|
image: "redis:latest",
|
|
ports: ["-p", "6379:6379"]);
|
|
|
|
// Wait for Redis
|
|
await this.WaitForConditionAsync(
|
|
condition: this.IsRedisRunningAsync,
|
|
message: "Redis is running",
|
|
timeout: TimeSpan.FromSeconds(30));
|
|
}
|
|
}
|
|
|
|
private async Task<bool> IsAzuriteRunningAsync()
|
|
{
|
|
this._outputHelper.WriteLine(
|
|
$"Checking if Azurite is running at http://localhost:{AzuritePort}/devstoreaccount1...");
|
|
|
|
try
|
|
{
|
|
using CancellationTokenSource timeoutCts = new(TimeSpan.FromSeconds(30));
|
|
|
|
// Example output when pinging Azurite:
|
|
// $ curl -i http://localhost:10000/devstoreaccount1?comp=list
|
|
// HTTP/1.1 403 Server failed to authenticate the request.
|
|
// Server: Azurite-Blob/3.34.0
|
|
// x-ms-error-code: AuthorizationFailure
|
|
// x-ms-request-id: 6cd21522-bb0f-40f6-962c-fa174f17aa30
|
|
// content-type: application/xml
|
|
// Date: Mon, 20 Oct 2025 23:52:02 GMT
|
|
// Connection: keep-alive
|
|
// Keep-Alive: timeout=5
|
|
// Transfer-Encoding: chunked
|
|
using HttpResponseMessage response = await s_sharedHttpClient.GetAsync(
|
|
requestUri: new Uri($"http://localhost:{AzuritePort}/devstoreaccount1?comp=list"),
|
|
cancellationToken: timeoutCts.Token);
|
|
if (response.Headers.TryGetValues(
|
|
"Server",
|
|
out IEnumerable<string>? serverValues) && serverValues.Any(s => s.StartsWith("Azurite", StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
this._outputHelper.WriteLine($"Azurite is running, server: {string.Join(", ", serverValues)}");
|
|
return true;
|
|
}
|
|
|
|
this._outputHelper.WriteLine($"Azurite is not running. Status code: {response.StatusCode}");
|
|
return false;
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
this._outputHelper.WriteLine($"Azurite is not running: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async Task<bool> IsDtsEmulatorRunningAsync()
|
|
{
|
|
this._outputHelper.WriteLine($"Checking if DTS emulator is running at http://localhost:{DtsPort}/healthz...");
|
|
|
|
// DTS emulator doesn't support HTTP/1.1, so we need to use HTTP/2.0
|
|
using HttpClient http2Client = new()
|
|
{
|
|
DefaultRequestVersion = new Version(2, 0),
|
|
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact
|
|
};
|
|
|
|
try
|
|
{
|
|
using CancellationTokenSource timeoutCts = new(TimeSpan.FromSeconds(30));
|
|
using HttpResponseMessage response = await http2Client.GetAsync(new Uri($"http://localhost:{DtsPort}/healthz"), timeoutCts.Token);
|
|
if (response.Content.Headers.ContentLength > 0)
|
|
{
|
|
string content = await response.Content.ReadAsStringAsync(timeoutCts.Token);
|
|
this._outputHelper.WriteLine($"DTS emulator health check response: {content}");
|
|
}
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
this._outputHelper.WriteLine("DTS emulator is running");
|
|
return true;
|
|
}
|
|
|
|
this._outputHelper.WriteLine($"DTS emulator is not running. Status code: {response.StatusCode}");
|
|
return false;
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
this._outputHelper.WriteLine($"DTS emulator is not running: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async Task<bool> IsRedisRunningAsync()
|
|
{
|
|
this._outputHelper.WriteLine($"Checking if Redis is running at localhost:{RedisPort}...");
|
|
|
|
try
|
|
{
|
|
using CancellationTokenSource timeoutCts = new(TimeSpan.FromSeconds(30));
|
|
ProcessStartInfo startInfo = new()
|
|
{
|
|
FileName = "docker",
|
|
Arguments = "exec redis redis-cli ping",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
CreateNoWindow = true
|
|
};
|
|
|
|
using Process process = new() { StartInfo = startInfo };
|
|
if (!process.Start())
|
|
{
|
|
this._outputHelper.WriteLine("Failed to start docker exec command");
|
|
return false;
|
|
}
|
|
|
|
string output = await process.StandardOutput.ReadToEndAsync(timeoutCts.Token);
|
|
await process.WaitForExitAsync(timeoutCts.Token);
|
|
|
|
if (process.ExitCode == 0 && output.Contains("PONG", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
this._outputHelper.WriteLine("Redis is running");
|
|
return true;
|
|
}
|
|
|
|
this._outputHelper.WriteLine($"Redis is not running. Exit code: {process.ExitCode}, Output: {output}");
|
|
return false;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this._outputHelper.WriteLine($"Redis is not running: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async Task StartDockerContainerAsync(string containerName, string image, string[] ports)
|
|
{
|
|
// Stop existing container if it exists
|
|
await this.RunCommandAsync("docker", ["stop", containerName]);
|
|
await this.RunCommandAsync("docker", ["rm", containerName]);
|
|
|
|
// Start new container
|
|
List<string> args = ["run", "-d", "--name", containerName];
|
|
args.AddRange(ports);
|
|
args.Add(image);
|
|
|
|
this._outputHelper.WriteLine(
|
|
$"Starting new container: {containerName} with image: {image} and ports: {string.Join(", ", ports)}");
|
|
await this.RunCommandAsync("docker", args.ToArray());
|
|
this._outputHelper.WriteLine($"Container started: {containerName}");
|
|
}
|
|
|
|
private async Task WaitForConditionAsync(Func<Task<bool>> condition, string message, TimeSpan timeout)
|
|
{
|
|
this._outputHelper.WriteLine($"Waiting for '{message}'...");
|
|
|
|
using CancellationTokenSource cancellationTokenSource = new(timeout);
|
|
while (true)
|
|
{
|
|
if (await condition())
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(1), cancellationTokenSource.Token);
|
|
}
|
|
catch (OperationCanceledException) when (cancellationTokenSource.IsCancellationRequested)
|
|
{
|
|
throw new TimeoutException($"Timeout waiting for '{message}'");
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task RunSampleTestAsync(string samplePath, Func<IReadOnlyList<OutputLog>, Task> testAction)
|
|
{
|
|
// Start the Azure Functions app
|
|
List<OutputLog> logsContainer = [];
|
|
using Process funcProcess = this.StartFunctionApp(samplePath, logsContainer);
|
|
try
|
|
{
|
|
// Wait for the app to be ready
|
|
await this.WaitForAzureFunctionsAsync();
|
|
|
|
// Run the test
|
|
await testAction(logsContainer);
|
|
}
|
|
finally
|
|
{
|
|
await this.StopProcessAsync(funcProcess);
|
|
}
|
|
}
|
|
|
|
private sealed record OutputLog(DateTime Timestamp, LogLevel Level, string Message);
|
|
|
|
private Process StartFunctionApp(string samplePath, List<OutputLog> logs)
|
|
{
|
|
ProcessStartInfo startInfo = new()
|
|
{
|
|
FileName = "dotnet",
|
|
Arguments = $"run -f {s_dotnetTargetFramework} --port {AzureFunctionsPort}",
|
|
WorkingDirectory = samplePath,
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
};
|
|
|
|
string openAiEndpoint = s_configuration["AZURE_OPENAI_ENDPOINT"] ??
|
|
throw new InvalidOperationException("The required AZURE_OPENAI_ENDPOINT env variable is not set.");
|
|
string openAiDeployment = s_configuration["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"] ??
|
|
throw new InvalidOperationException("The required AZURE_OPENAI_CHAT_DEPLOYMENT_NAME env variable is not set.");
|
|
|
|
// Set required environment variables for the function app (see local.settings.json for required settings)
|
|
startInfo.EnvironmentVariables["AZURE_OPENAI_ENDPOINT"] = openAiEndpoint;
|
|
startInfo.EnvironmentVariables["AZURE_OPENAI_DEPLOYMENT"] = openAiDeployment;
|
|
startInfo.EnvironmentVariables["DURABLE_TASK_SCHEDULER_CONNECTION_STRING"] =
|
|
$"Endpoint=http://localhost:{DtsPort};TaskHub=default;Authentication=None";
|
|
startInfo.EnvironmentVariables["AzureWebJobsStorage"] = "UseDevelopmentStorage=true";
|
|
startInfo.EnvironmentVariables["REDIS_CONNECTION_STRING"] = $"localhost:{RedisPort}";
|
|
|
|
Process process = new() { StartInfo = startInfo };
|
|
|
|
// Capture the output and error streams
|
|
process.ErrorDataReceived += (sender, e) =>
|
|
{
|
|
if (e.Data != null)
|
|
{
|
|
this._outputHelper.WriteLine($"[{startInfo.FileName}(err)]: {e.Data}");
|
|
lock (logs)
|
|
{
|
|
logs.Add(new OutputLog(DateTime.Now, LogLevel.Error, e.Data));
|
|
}
|
|
}
|
|
};
|
|
|
|
process.OutputDataReceived += (sender, e) =>
|
|
{
|
|
if (e.Data != null)
|
|
{
|
|
this._outputHelper.WriteLine($"[{startInfo.FileName}(out)]: {e.Data}");
|
|
lock (logs)
|
|
{
|
|
logs.Add(new OutputLog(DateTime.Now, LogLevel.Information, e.Data));
|
|
}
|
|
}
|
|
};
|
|
|
|
if (!process.Start())
|
|
{
|
|
throw new InvalidOperationException("Failed to start the function app");
|
|
}
|
|
|
|
process.BeginErrorReadLine();
|
|
process.BeginOutputReadLine();
|
|
|
|
return process;
|
|
}
|
|
|
|
private async Task WaitForAzureFunctionsAsync()
|
|
{
|
|
this._outputHelper.WriteLine(
|
|
$"Waiting for Azure Functions Core Tools to be ready at http://localhost:{AzureFunctionsPort}/...");
|
|
await this.WaitForConditionAsync(
|
|
condition: async () =>
|
|
{
|
|
try
|
|
{
|
|
using HttpRequestMessage request = new(HttpMethod.Head, $"http://localhost:{AzureFunctionsPort}/");
|
|
using HttpResponseMessage response = await s_sharedHttpClient.SendAsync(request);
|
|
this._outputHelper.WriteLine($"Azure Functions Core Tools response: {response.StatusCode}");
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
// Expected when the app isn't yet ready
|
|
return false;
|
|
}
|
|
},
|
|
message: "Azure Functions Core Tools is ready",
|
|
timeout: TimeSpan.FromSeconds(60));
|
|
}
|
|
|
|
private async Task WaitForOrchestrationCompletionAsync(Uri statusUri)
|
|
{
|
|
using CancellationTokenSource timeoutCts = new(s_orchestrationTimeout);
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
using HttpResponseMessage response = await s_sharedHttpClient.GetAsync(
|
|
statusUri,
|
|
timeoutCts.Token);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
string responseText = await response.Content.ReadAsStringAsync(timeoutCts.Token);
|
|
JsonElement result = JsonElement.Parse(responseText);
|
|
|
|
if (result.TryGetProperty("runtimeStatus", out JsonElement statusElement) &&
|
|
statusElement.GetString() is "Completed" or "Failed" or "Terminated")
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (!timeoutCts.Token.IsCancellationRequested)
|
|
{
|
|
// Ignore errors and retry
|
|
this._outputHelper.WriteLine($"Error waiting for orchestration completion: {ex}");
|
|
}
|
|
|
|
await Task.Delay(TimeSpan.FromSeconds(1), timeoutCts.Token);
|
|
}
|
|
}
|
|
|
|
private async Task RunCommandAsync(string command, string[] args)
|
|
{
|
|
await this.RunCommandAsync(command, workingDirectory: null, args: args);
|
|
}
|
|
|
|
private async Task RunCommandAsync(string command, string? workingDirectory, string[] args)
|
|
{
|
|
ProcessStartInfo startInfo = new()
|
|
{
|
|
FileName = command,
|
|
Arguments = string.Join(" ", args),
|
|
WorkingDirectory = workingDirectory,
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
CreateNoWindow = true
|
|
};
|
|
|
|
this._outputHelper.WriteLine($"Running command: {command} {string.Join(" ", args)}");
|
|
|
|
using Process process = new() { StartInfo = startInfo };
|
|
process.ErrorDataReceived += (sender, e) => this._outputHelper.WriteLine($"[{command}(err)]: {e.Data}");
|
|
process.OutputDataReceived += (sender, e) => this._outputHelper.WriteLine($"[{command}(out)]: {e.Data}");
|
|
if (!process.Start())
|
|
{
|
|
throw new InvalidOperationException("Failed to start the command");
|
|
}
|
|
process.BeginErrorReadLine();
|
|
process.BeginOutputReadLine();
|
|
|
|
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromMinutes(1));
|
|
await process.WaitForExitAsync(cancellationTokenSource.Token);
|
|
|
|
this._outputHelper.WriteLine($"Command completed with exit code: {process.ExitCode}");
|
|
}
|
|
|
|
private async Task StopProcessAsync(Process process)
|
|
{
|
|
try
|
|
{
|
|
if (!process.HasExited)
|
|
{
|
|
this._outputHelper.WriteLine($"Killing process {process.ProcessName}#{process.Id}");
|
|
process.Kill(entireProcessTree: true);
|
|
|
|
using CancellationTokenSource timeoutCts = new(TimeSpan.FromSeconds(10));
|
|
await process.WaitForExitAsync(timeoutCts.Token);
|
|
this._outputHelper.WriteLine($"Process exited: {process.Id}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this._outputHelper.WriteLine($"Failed to stop process: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private static string GetTargetFramework()
|
|
{
|
|
// Get the target framework by looking at the path of the current file. It should be something like /path/to/project/bin/Debug/net8.0/...
|
|
string filePath = new Uri(typeof(SamplesValidation).Assembly.Location).LocalPath;
|
|
string directory = Path.GetDirectoryName(filePath)!;
|
|
string tfm = Path.GetFileName(directory);
|
|
if (tfm.StartsWith("net", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return tfm;
|
|
}
|
|
|
|
throw new InvalidOperationException($"Unable to find target framework in path: {filePath}");
|
|
}
|
|
}
|