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
@@ -2,8 +2,10 @@
|
||||
|
||||
import importlib.metadata
|
||||
|
||||
from ._chat_client import AzureAIAgentClient
|
||||
from ._agent_provider import AzureAIAgentsProvider
|
||||
from ._chat_client import AzureAIAgentClient, AzureAIAgentOptions
|
||||
from ._client import AzureAIClient
|
||||
from ._project_provider import AzureAIProjectAgentProvider
|
||||
from ._shared import AzureAISettings
|
||||
|
||||
try:
|
||||
@@ -13,7 +15,10 @@ except importlib.metadata.PackageNotFoundError:
|
||||
|
||||
__all__ = [
|
||||
"AzureAIAgentClient",
|
||||
"AzureAIAgentOptions",
|
||||
"AzureAIAgentsProvider",
|
||||
"AzureAIClient",
|
||||
"AzureAIProjectAgentProvider",
|
||||
"AzureAISettings",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import sys
|
||||
from collections.abc import Callable, MutableMapping, Sequence
|
||||
from typing import TYPE_CHECKING, Any, Generic, TypedDict, cast
|
||||
|
||||
from agent_framework import (
|
||||
AGENT_FRAMEWORK_USER_AGENT,
|
||||
AIFunction,
|
||||
ChatAgent,
|
||||
ContextProvider,
|
||||
Middleware,
|
||||
ToolProtocol,
|
||||
normalize_tools,
|
||||
)
|
||||
from agent_framework._mcp import MCPTool
|
||||
from agent_framework.exceptions import ServiceInitializationError
|
||||
from azure.ai.agents.aio import AgentsClient
|
||||
from azure.ai.agents.models import Agent, ResponseFormatJsonSchema, ResponseFormatJsonSchemaType
|
||||
from azure.core.credentials_async import AsyncTokenCredential
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from ._chat_client import AzureAIAgentClient
|
||||
from ._shared import AzureAISettings, from_azure_ai_agent_tools, to_azure_ai_agent_tools
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ._chat_client import AzureAIAgentOptions
|
||||
|
||||
if sys.version_info >= (3, 13):
|
||||
from typing import Self, TypeVar # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import Self, TypeVar # pragma: no cover
|
||||
|
||||
|
||||
# Type variable for options - allows typed ChatAgent[TOptions] returns
|
||||
# Default matches AzureAIAgentClient's default options type
|
||||
TOptions_co = TypeVar(
|
||||
"TOptions_co",
|
||||
bound=TypedDict, # type: ignore[valid-type]
|
||||
default="AzureAIAgentOptions",
|
||||
covariant=True,
|
||||
)
|
||||
|
||||
|
||||
class AzureAIAgentsProvider(Generic[TOptions_co]):
|
||||
"""Provider for Azure AI Agent Service V1 (Persistent Agents API).
|
||||
|
||||
This provider enables creating, retrieving, and wrapping Azure AI agents as ChatAgent
|
||||
instances. It manages the underlying AgentsClient lifecycle and provides a high-level
|
||||
interface for agent operations.
|
||||
|
||||
The provider can be initialized with either:
|
||||
- An existing AgentsClient instance
|
||||
- Azure credentials and endpoint for automatic client creation
|
||||
|
||||
Examples:
|
||||
Using credentials (auto-creates client):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureAIAgentsProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentsProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyAgent",
|
||||
instructions="You are a helpful assistant.",
|
||||
)
|
||||
result = await agent.run("Hello!")
|
||||
|
||||
Using existing AgentsClient:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureAIAgentsProvider
|
||||
from azure.ai.agents.aio import AgentsClient
|
||||
|
||||
async with AgentsClient(endpoint=endpoint, credential=credential) as client:
|
||||
provider = AzureAIAgentsProvider(agents_client=client)
|
||||
agent = await provider.create_agent(name="MyAgent", instructions="...")
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
agents_client: AgentsClient | None = None,
|
||||
*,
|
||||
project_endpoint: str | None = None,
|
||||
credential: AsyncTokenCredential | None = None,
|
||||
env_file_path: str | None = None,
|
||||
env_file_encoding: str | None = None,
|
||||
) -> None:
|
||||
"""Initialize the Azure AI Agents Provider.
|
||||
|
||||
Args:
|
||||
agents_client: An existing AgentsClient to use. If provided, the provider
|
||||
will not manage its lifecycle.
|
||||
|
||||
Keyword Args:
|
||||
project_endpoint: The Azure AI Project endpoint URL.
|
||||
Can also be set via AZURE_AI_PROJECT_ENDPOINT environment variable.
|
||||
credential: Azure async credential for authentication.
|
||||
Required if agents_client is not provided.
|
||||
env_file_path: Path to .env file for loading settings.
|
||||
env_file_encoding: Encoding of the .env file.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If required parameters are missing or invalid.
|
||||
"""
|
||||
try:
|
||||
self._settings = AzureAISettings(
|
||||
project_endpoint=project_endpoint,
|
||||
env_file_path=env_file_path,
|
||||
env_file_encoding=env_file_encoding,
|
||||
)
|
||||
except ValidationError as ex:
|
||||
raise ServiceInitializationError("Failed to create Azure AI settings.", ex) from ex
|
||||
|
||||
self._should_close_client = False
|
||||
|
||||
if agents_client is not None:
|
||||
self._agents_client = agents_client
|
||||
else:
|
||||
if not self._settings.project_endpoint:
|
||||
raise ServiceInitializationError(
|
||||
"Azure AI project endpoint is required. Provide 'project_endpoint' parameter "
|
||||
"or set 'AZURE_AI_PROJECT_ENDPOINT' environment variable."
|
||||
)
|
||||
if not credential:
|
||||
raise ServiceInitializationError("Azure credential is required when agents_client is not provided.")
|
||||
self._agents_client = AgentsClient(
|
||||
endpoint=self._settings.project_endpoint,
|
||||
credential=credential,
|
||||
user_agent=AGENT_FRAMEWORK_USER_AGENT,
|
||||
)
|
||||
self._should_close_client = True
|
||||
|
||||
async def __aenter__(self) -> "Self":
|
||||
"""Async context manager entry."""
|
||||
return self
|
||||
|
||||
async def __aexit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc_val: BaseException | None,
|
||||
exc_tb: Any,
|
||||
) -> None:
|
||||
"""Async context manager exit."""
|
||||
await self.close()
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the provider and release resources.
|
||||
|
||||
Only closes the AgentsClient if it was created by this provider.
|
||||
"""
|
||||
if self._should_close_client:
|
||||
await self._agents_client.close()
|
||||
|
||||
async def create_agent(
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
model: str | None = None,
|
||||
instructions: str | None = None,
|
||||
description: str | None = None,
|
||||
tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Create a new agent on the Azure AI service and return a ChatAgent.
|
||||
|
||||
This method creates a persistent agent on the Azure AI service with the specified
|
||||
configuration and returns a local ChatAgent instance for interaction.
|
||||
|
||||
Args:
|
||||
name: The name for the agent.
|
||||
|
||||
Keyword Args:
|
||||
model: The model deployment name to use. Falls back to
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME environment variable if not provided.
|
||||
instructions: Instructions for the agent's behavior.
|
||||
description: A description of the agent's purpose.
|
||||
tools: Tools to make available to the agent.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
|
||||
Returns:
|
||||
ChatAgent: A ChatAgent instance configured with the created agent.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If model deployment name is not available.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
)
|
||||
"""
|
||||
resolved_model = model or self._settings.model_deployment_name
|
||||
if not resolved_model:
|
||||
raise ServiceInitializationError(
|
||||
"Model deployment name is required. Provide 'model' parameter "
|
||||
"or set 'AZURE_AI_MODEL_DEPLOYMENT_NAME' environment variable."
|
||||
)
|
||||
|
||||
# Extract response_format from default_options if present
|
||||
opts = dict(default_options) if default_options else {}
|
||||
response_format = opts.get("response_format")
|
||||
|
||||
args: dict[str, Any] = {
|
||||
"model": resolved_model,
|
||||
"name": name,
|
||||
}
|
||||
|
||||
if description:
|
||||
args["description"] = description
|
||||
if instructions:
|
||||
args["instructions"] = instructions
|
||||
|
||||
# Handle response format
|
||||
if response_format and isinstance(response_format, type) and issubclass(response_format, BaseModel):
|
||||
args["response_format"] = self._create_response_format_config(response_format)
|
||||
|
||||
# Normalize and convert tools
|
||||
# Local MCP tools (MCPTool) are handled by ChatAgent at runtime, not stored on the Azure agent
|
||||
normalized_tools = normalize_tools(tools)
|
||||
if normalized_tools:
|
||||
# Only convert non-MCP tools to Azure AI format
|
||||
non_mcp_tools = [t for t in normalized_tools if not isinstance(t, MCPTool)]
|
||||
if non_mcp_tools:
|
||||
# Pass run_options to capture tool_resources (e.g., for file search vector stores)
|
||||
run_options: dict[str, Any] = {}
|
||||
args["tools"] = to_azure_ai_agent_tools(non_mcp_tools, run_options)
|
||||
if "tool_resources" in run_options:
|
||||
args["tool_resources"] = run_options["tool_resources"]
|
||||
|
||||
# Create the agent on the service
|
||||
created_agent = await self._agents_client.create_agent(**args)
|
||||
|
||||
# Create ChatAgent wrapper
|
||||
return self._to_chat_agent_from_agent(
|
||||
created_agent,
|
||||
normalized_tools,
|
||||
default_options=default_options,
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
async def get_agent(
|
||||
self,
|
||||
id: str,
|
||||
*,
|
||||
tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Retrieve an existing agent from the service and return a ChatAgent.
|
||||
|
||||
This method fetches an agent by ID from the Azure AI service
|
||||
and returns a local ChatAgent instance for interaction.
|
||||
|
||||
Args:
|
||||
id: The ID of the agent to retrieve from the service.
|
||||
|
||||
Keyword Args:
|
||||
tools: Tools to make available to the agent. Required if the agent
|
||||
has function tools that need implementations.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
|
||||
Returns:
|
||||
ChatAgent: A ChatAgent instance configured with the retrieved agent.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If required function tools are not provided.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
agent = await provider.get_agent("agent-123")
|
||||
|
||||
# With function tools
|
||||
agent = await provider.get_agent("agent-123", tools=my_function)
|
||||
"""
|
||||
agent = await self._agents_client.get_agent(id)
|
||||
|
||||
# Validate function tools
|
||||
normalized_tools = normalize_tools(tools)
|
||||
self._validate_function_tools(agent.tools, normalized_tools)
|
||||
|
||||
return self._to_chat_agent_from_agent(
|
||||
agent,
|
||||
normalized_tools,
|
||||
default_options=default_options,
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
def as_agent(
|
||||
self,
|
||||
agent: Agent,
|
||||
tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Wrap an existing Agent SDK object as a ChatAgent without making HTTP calls.
|
||||
|
||||
Use this method when you already have an Agent object from a previous
|
||||
SDK operation and want to use it with the Agent Framework.
|
||||
|
||||
Args:
|
||||
agent: The Agent object to wrap.
|
||||
tools: Tools to make available to the agent. Required if the agent
|
||||
has function tools that need implementations.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
|
||||
Returns:
|
||||
ChatAgent: A ChatAgent instance configured with the agent.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If required function tools are not provided.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
# Create agent directly with SDK
|
||||
sdk_agent = await agents_client.create_agent(
|
||||
model="gpt-4",
|
||||
name="MyAgent",
|
||||
instructions="...",
|
||||
)
|
||||
|
||||
# Wrap as ChatAgent
|
||||
chat_agent = provider.as_agent(sdk_agent)
|
||||
"""
|
||||
# Validate function tools
|
||||
normalized_tools = normalize_tools(tools)
|
||||
self._validate_function_tools(agent.tools, normalized_tools)
|
||||
|
||||
return self._to_chat_agent_from_agent(
|
||||
agent,
|
||||
normalized_tools,
|
||||
default_options=default_options,
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
def _to_chat_agent_from_agent(
|
||||
self,
|
||||
agent: Agent,
|
||||
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Create a ChatAgent from an Agent SDK object.
|
||||
|
||||
Args:
|
||||
agent: The Agent SDK object.
|
||||
provided_tools: User-provided tools (including function implementations).
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
"""
|
||||
# Create the underlying client
|
||||
client = AzureAIAgentClient(
|
||||
agents_client=self._agents_client,
|
||||
agent_id=agent.id,
|
||||
agent_name=agent.name,
|
||||
agent_description=agent.description,
|
||||
should_cleanup_agent=False, # Provider manages agent lifecycle
|
||||
)
|
||||
|
||||
# Merge tools: convert agent's hosted tools + user-provided function tools
|
||||
merged_tools = self._merge_tools(agent.tools, provided_tools)
|
||||
|
||||
return ChatAgent( # type: ignore[return-value]
|
||||
chat_client=client,
|
||||
id=agent.id,
|
||||
name=agent.name,
|
||||
description=agent.description,
|
||||
instructions=agent.instructions,
|
||||
model_id=agent.model,
|
||||
tools=merged_tools,
|
||||
default_options=default_options, # type: ignore[arg-type]
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
def _merge_tools(
|
||||
self,
|
||||
agent_tools: Sequence[Any] | None,
|
||||
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
|
||||
) -> list[ToolProtocol | dict[str, Any]]:
|
||||
"""Merge hosted tools from agent with user-provided function tools.
|
||||
|
||||
Args:
|
||||
agent_tools: Tools from the agent definition (Azure AI format).
|
||||
provided_tools: User-provided tools (Agent Framework format).
|
||||
|
||||
Returns:
|
||||
Combined list of tools for the ChatAgent.
|
||||
"""
|
||||
merged: list[ToolProtocol | dict[str, Any]] = []
|
||||
|
||||
# Convert hosted tools from agent definition
|
||||
hosted_tools = from_azure_ai_agent_tools(agent_tools)
|
||||
for hosted_tool in hosted_tools:
|
||||
# Skip function tool dicts - they don't have implementations
|
||||
# Skip OpenAPI tool dicts - they're defined on the agent, not needed at runtime
|
||||
if isinstance(hosted_tool, dict):
|
||||
tool_type = hosted_tool.get("type")
|
||||
if tool_type == "function" or tool_type == "openapi":
|
||||
continue
|
||||
merged.append(hosted_tool)
|
||||
|
||||
# Add user-provided function tools and MCP tools
|
||||
if provided_tools:
|
||||
for provided_tool in provided_tools:
|
||||
# AIFunction - has implementation for function calling
|
||||
# MCPTool - ChatAgent handles MCP connection and tool discovery at runtime
|
||||
if isinstance(provided_tool, (AIFunction, MCPTool)):
|
||||
merged.append(provided_tool) # type: ignore[reportUnknownArgumentType]
|
||||
|
||||
return merged
|
||||
|
||||
def _validate_function_tools(
|
||||
self,
|
||||
agent_tools: Sequence[Any] | None,
|
||||
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
|
||||
) -> None:
|
||||
"""Validate that required function tools are provided.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If agent has function tools but user
|
||||
didn't provide implementations.
|
||||
"""
|
||||
if not agent_tools:
|
||||
return
|
||||
|
||||
# Get function tool names from agent definition
|
||||
function_tool_names: set[str] = set()
|
||||
for tool in agent_tools:
|
||||
if isinstance(tool, dict):
|
||||
tool_dict = cast(dict[str, Any], tool)
|
||||
if tool_dict.get("type") == "function":
|
||||
func_def = cast(dict[str, Any], tool_dict.get("function", {}))
|
||||
name = func_def.get("name")
|
||||
if isinstance(name, str):
|
||||
function_tool_names.add(name)
|
||||
elif hasattr(tool, "type") and tool.type == "function":
|
||||
func_attr = getattr(tool, "function", None)
|
||||
if func_attr and hasattr(func_attr, "name"):
|
||||
function_tool_names.add(str(func_attr.name))
|
||||
|
||||
if not function_tool_names:
|
||||
return
|
||||
|
||||
# Get provided function names
|
||||
provided_names: set[str] = set()
|
||||
if provided_tools:
|
||||
for tool in provided_tools:
|
||||
if isinstance(tool, AIFunction):
|
||||
provided_names.add(tool.name)
|
||||
|
||||
# Check for missing implementations
|
||||
missing = function_tool_names - provided_names
|
||||
if missing:
|
||||
raise ServiceInitializationError(
|
||||
f"Agent has function tools that require implementations: {missing}. "
|
||||
"Provide these functions via the 'tools' parameter."
|
||||
)
|
||||
|
||||
def _create_response_format_config(
|
||||
self,
|
||||
response_format: type[BaseModel],
|
||||
) -> ResponseFormatJsonSchemaType:
|
||||
"""Create response format configuration for Azure AI.
|
||||
|
||||
Args:
|
||||
response_format: Pydantic model for structured output.
|
||||
|
||||
Returns:
|
||||
Azure AI response format configuration.
|
||||
"""
|
||||
return ResponseFormatJsonSchemaType(
|
||||
json_schema=ResponseFormatJsonSchema(
|
||||
name=response_format.__name__,
|
||||
schema=response_format.model_json_schema(),
|
||||
)
|
||||
)
|
||||
@@ -2,15 +2,13 @@
|
||||
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import AsyncIterable, MutableMapping, MutableSequence, Sequence
|
||||
from typing import Any, ClassVar, TypeVar
|
||||
from collections.abc import AsyncIterable, Mapping, MutableMapping, MutableSequence, Sequence
|
||||
from typing import Any, ClassVar, Generic, TypedDict
|
||||
|
||||
from agent_framework import (
|
||||
AGENT_FRAMEWORK_USER_AGENT,
|
||||
AIFunction,
|
||||
BaseChatClient,
|
||||
ChatMessage,
|
||||
ChatOptions,
|
||||
@@ -23,16 +21,11 @@ from agent_framework import (
|
||||
FunctionApprovalResponseContent,
|
||||
FunctionCallContent,
|
||||
FunctionResultContent,
|
||||
HostedCodeInterpreterTool,
|
||||
HostedFileContent,
|
||||
HostedFileSearchTool,
|
||||
HostedMCPTool,
|
||||
HostedVectorStoreContent,
|
||||
HostedWebSearchTool,
|
||||
Role,
|
||||
TextContent,
|
||||
TextSpanRegion,
|
||||
ToolMode,
|
||||
ToolProtocol,
|
||||
UriContent,
|
||||
UsageContent,
|
||||
@@ -42,7 +35,7 @@ from agent_framework import (
|
||||
use_chat_middleware,
|
||||
use_function_invocation,
|
||||
)
|
||||
from agent_framework.exceptions import ServiceInitializationError, ServiceResponseException
|
||||
from agent_framework.exceptions import ServiceInitializationError, ServiceInvalidRequestError, ServiceResponseException
|
||||
from agent_framework.observability import use_instrumentation
|
||||
from azure.ai.agents.aio import AgentsClient
|
||||
from azure.ai.agents.models import (
|
||||
@@ -53,14 +46,9 @@ from azure.ai.agents.models import (
|
||||
AgentStreamEvent,
|
||||
AsyncAgentEventHandler,
|
||||
AsyncAgentRunStream,
|
||||
BingCustomSearchTool,
|
||||
BingGroundingTool,
|
||||
CodeInterpreterToolDefinition,
|
||||
FileSearchTool,
|
||||
FunctionName,
|
||||
FunctionToolDefinition,
|
||||
ListSortOrder,
|
||||
McpTool,
|
||||
MessageDeltaChunk,
|
||||
MessageDeltaTextContent,
|
||||
MessageDeltaTextFileCitationAnnotation,
|
||||
@@ -90,10 +78,18 @@ from azure.ai.agents.models import (
|
||||
ToolOutput,
|
||||
)
|
||||
from azure.core.credentials_async import AsyncTokenCredential
|
||||
from pydantic import ValidationError
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from ._shared import AzureAISettings
|
||||
from ._shared import AzureAISettings, to_azure_ai_agent_tools
|
||||
|
||||
if sys.version_info >= (3, 13):
|
||||
from typing import TypeVar # type: ignore # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import TypeVar # type: ignore # pragma: no cover
|
||||
if sys.version_info >= (3, 12):
|
||||
from typing import override # type: ignore # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import override # type: ignore[import] # pragma: no cover
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import Self # pragma: no cover
|
||||
else:
|
||||
@@ -102,14 +98,106 @@ else:
|
||||
|
||||
logger = get_logger("agent_framework.azure")
|
||||
|
||||
__all__ = ["AzureAIAgentClient", "AzureAIAgentOptions"]
|
||||
|
||||
TAzureAIAgentClient = TypeVar("TAzureAIAgentClient", bound="AzureAIAgentClient")
|
||||
|
||||
# region Azure AI Agent Options TypedDict
|
||||
|
||||
|
||||
class AzureAIAgentOptions(ChatOptions, total=False):
|
||||
"""Azure AI Foundry Agent Service-specific options dict.
|
||||
|
||||
Extends base ChatOptions with Azure AI Agent Service parameters.
|
||||
Azure AI Agents provides a managed agent runtime with built-in
|
||||
tools for code interpreter, file search, and web search.
|
||||
|
||||
See: https://learn.microsoft.com/azure/ai-services/agents/
|
||||
|
||||
Keys:
|
||||
# Inherited from ChatOptions:
|
||||
model_id: The model deployment name,
|
||||
translates to ``model`` in Azure AI API.
|
||||
temperature: Sampling temperature between 0 and 2.
|
||||
top_p: Nucleus sampling parameter.
|
||||
max_tokens: Maximum number of tokens to generate,
|
||||
translates to ``max_completion_tokens`` in Azure AI API.
|
||||
tools: List of tools available to the agent.
|
||||
tool_choice: How the model should use tools.
|
||||
allow_multiple_tool_calls: Whether to allow parallel tool calls,
|
||||
translates to ``parallel_tool_calls`` in Azure AI API.
|
||||
response_format: Structured output schema.
|
||||
metadata: Request metadata for tracking.
|
||||
instructions: System instructions for the agent.
|
||||
|
||||
# Options not supported in Azure AI Agent Service:
|
||||
stop: Not supported.
|
||||
seed: Not supported.
|
||||
frequency_penalty: Not supported.
|
||||
presence_penalty: Not supported.
|
||||
user: Not supported.
|
||||
store: Not supported.
|
||||
logit_bias: Not supported.
|
||||
|
||||
# Azure AI Agent-specific options:
|
||||
conversation_id: Thread ID to continue conversation in.
|
||||
tool_resources: Resources for tools (file IDs, vector stores).
|
||||
"""
|
||||
|
||||
# Azure AI Agent-specific options
|
||||
conversation_id: str # type: ignore[misc]
|
||||
"""Thread ID to continue a conversation in an existing thread."""
|
||||
|
||||
tool_resources: dict[str, Any]
|
||||
"""Tool-specific resources for code_interpreter and file_search.
|
||||
For code_interpreter: {"file_ids": ["file-abc123"]}
|
||||
For file_search: {"vector_store_ids": ["vs-abc123"]}
|
||||
"""
|
||||
|
||||
# ChatOptions fields not supported in Azure AI Agent Service
|
||||
stop: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
seed: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
frequency_penalty: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
presence_penalty: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
user: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
store: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
logit_bias: None # type: ignore[misc]
|
||||
"""Not supported in Azure AI Agent Service."""
|
||||
|
||||
|
||||
AZURE_AI_AGENT_OPTION_TRANSLATIONS: dict[str, str] = {
|
||||
"model_id": "model",
|
||||
"max_tokens": "max_completion_tokens",
|
||||
"allow_multiple_tool_calls": "parallel_tool_calls",
|
||||
}
|
||||
"""Maps ChatOptions keys to Azure AI Agents API parameter names."""
|
||||
|
||||
TAzureAIAgentOptions = TypeVar(
|
||||
"TAzureAIAgentOptions",
|
||||
bound=TypedDict, # type: ignore[valid-type]
|
||||
default="AzureAIAgentOptions",
|
||||
covariant=True,
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
@use_function_invocation
|
||||
@use_instrumentation
|
||||
@use_chat_middleware
|
||||
class AzureAIAgentClient(BaseChatClient):
|
||||
class AzureAIAgentClient(BaseChatClient[TAzureAIAgentOptions], Generic[TAzureAIAgentOptions]):
|
||||
"""Azure AI Agent Chat client."""
|
||||
|
||||
OTEL_PROVIDER_NAME: ClassVar[str] = "azure.ai" # type: ignore[reportIncompatibleVariableOverride, misc]
|
||||
@@ -162,19 +250,31 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_AI_PROJECT_ENDPOINT=https://your-project.cognitiveservices.azure.com
|
||||
# Set AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4
|
||||
# Set AZURE_AI_MODEL_DEPLOYMENT_NAME=<model name>
|
||||
credential = DefaultAzureCredential()
|
||||
client = AzureAIAgentClient(credential=credential)
|
||||
|
||||
# Or passing parameters directly
|
||||
client = AzureAIAgentClient(
|
||||
project_endpoint="https://your-project.cognitiveservices.azure.com",
|
||||
model_deployment_name="gpt-4",
|
||||
model_deployment_name="<model name>",
|
||||
credential=credential,
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
client = AzureAIAgentClient(credential=credential, env_file_path="path/to/.env")
|
||||
|
||||
# Using custom ChatOptions with type safety:
|
||||
from typing import TypedDict
|
||||
from agent_framework_azure_ai import AzureAIAgentOptions
|
||||
|
||||
|
||||
class MyOptions(AzureAIAgentOptions, total=False):
|
||||
my_custom_option: str
|
||||
|
||||
|
||||
client: AzureAIAgentClient[MyOptions] = AzureAIAgentClient(credential=credential)
|
||||
response = await client.get_response("Hello", options={"my_custom_option": "value"})
|
||||
"""
|
||||
try:
|
||||
azure_ai_settings = AzureAISettings(
|
||||
@@ -240,46 +340,29 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
await self._cleanup_agent_if_needed()
|
||||
await self._close_client_if_needed()
|
||||
|
||||
@classmethod
|
||||
def from_settings(cls: type[TAzureAIAgentClient], settings: dict[str, Any]) -> TAzureAIAgentClient:
|
||||
"""Initialize a AzureAIAgentClient from a dictionary of settings.
|
||||
|
||||
Args:
|
||||
settings: A dictionary of settings for the service.
|
||||
"""
|
||||
return cls(
|
||||
agents_client=settings.get("agents_client"),
|
||||
agent_id=settings.get("agent_id"),
|
||||
thread_id=settings.get("thread_id"),
|
||||
project_endpoint=settings.get("project_endpoint"),
|
||||
model_deployment_name=settings.get("model_deployment_name"),
|
||||
agent_name=settings.get("agent_name"),
|
||||
credential=settings.get("credential"),
|
||||
env_file_path=settings.get("env_file_path"),
|
||||
should_cleanup_agent=settings.get("should_cleanup_agent", True),
|
||||
)
|
||||
|
||||
@override
|
||||
async def _inner_get_response(
|
||||
self,
|
||||
*,
|
||||
messages: MutableSequence[ChatMessage],
|
||||
chat_options: ChatOptions,
|
||||
options: dict[str, Any],
|
||||
**kwargs: Any,
|
||||
) -> ChatResponse:
|
||||
return await ChatResponse.from_chat_response_generator(
|
||||
updates=self._inner_get_streaming_response(messages=messages, chat_options=chat_options, **kwargs),
|
||||
output_format_type=chat_options.response_format,
|
||||
updates=self._inner_get_streaming_response(messages=messages, options=options, **kwargs),
|
||||
output_format_type=options.get("response_format"),
|
||||
)
|
||||
|
||||
@override
|
||||
async def _inner_get_streaming_response(
|
||||
self,
|
||||
*,
|
||||
messages: MutableSequence[ChatMessage],
|
||||
chat_options: ChatOptions,
|
||||
options: Mapping[str, Any],
|
||||
**kwargs: Any,
|
||||
) -> AsyncIterable[ChatResponseUpdate]:
|
||||
# prepare
|
||||
run_options, required_action_results = await self._prepare_options(messages, chat_options, **kwargs)
|
||||
run_options, required_action_results = await self._prepare_options(messages, options, **kwargs)
|
||||
agent_id = await self._get_agent_id_or_create(run_options)
|
||||
|
||||
# execute and process
|
||||
@@ -783,46 +866,31 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
self._agent_definition = await self.agents_client.get_agent(self.agent_id)
|
||||
return self._agent_definition
|
||||
|
||||
def _prepare_tool_choice(self, chat_options: ChatOptions) -> None:
|
||||
"""Prepare the tools and tool choice for the chat options.
|
||||
|
||||
Args:
|
||||
chat_options: The chat options to prepare.
|
||||
"""
|
||||
chat_tool_mode = chat_options.tool_choice
|
||||
if chat_tool_mode is None or chat_tool_mode == ToolMode.NONE or chat_tool_mode == "none":
|
||||
chat_options.tools = None
|
||||
chat_options.tool_choice = ToolMode.NONE
|
||||
return
|
||||
|
||||
chat_options.tool_choice = chat_tool_mode
|
||||
|
||||
async def _prepare_options(
|
||||
self,
|
||||
messages: MutableSequence[ChatMessage],
|
||||
chat_options: ChatOptions,
|
||||
options: Mapping[str, Any],
|
||||
**kwargs: Any,
|
||||
) -> tuple[dict[str, Any], list[FunctionResultContent | FunctionApprovalResponseContent] | None]:
|
||||
agent_definition = await self._load_agent_definition_if_needed()
|
||||
|
||||
# Use to_dict with exclusions for properties handled separately
|
||||
run_options: dict[str, Any] = chat_options.to_dict(
|
||||
exclude={
|
||||
"type",
|
||||
"instructions", # handled via messages
|
||||
"tools", # handled separately
|
||||
"tool_choice", # handled separately
|
||||
"response_format", # handled separately
|
||||
"additional_properties", # handled separately
|
||||
"frequency_penalty", # not supported
|
||||
"presence_penalty", # not supported
|
||||
"user", # not supported
|
||||
"stop", # not supported
|
||||
"logit_bias", # not supported
|
||||
"seed", # not supported
|
||||
"store", # not supported
|
||||
}
|
||||
)
|
||||
# Build run_options from options dict, excluding specific keys
|
||||
exclude_keys = {
|
||||
"type",
|
||||
"instructions", # handled via messages
|
||||
"tools", # handled separately
|
||||
"tool_choice", # handled separately
|
||||
"response_format", # handled separately
|
||||
"additional_properties", # handled separately
|
||||
"frequency_penalty", # not supported
|
||||
"presence_penalty", # not supported
|
||||
"user", # not supported
|
||||
"stop", # not supported
|
||||
"logit_bias", # not supported
|
||||
"seed", # not supported
|
||||
"store", # not supported
|
||||
}
|
||||
run_options: dict[str, Any] = {k: v for k, v in options.items() if k not in exclude_keys and v is not None}
|
||||
|
||||
# Translation between ChatOptions and Azure AI Agents API
|
||||
translations = {
|
||||
@@ -840,21 +908,31 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
|
||||
# tools and tool_choice
|
||||
if tool_definitions := await self._prepare_tool_definitions_and_resources(
|
||||
chat_options, agent_definition, run_options
|
||||
options, agent_definition, run_options
|
||||
):
|
||||
run_options["tools"] = tool_definitions
|
||||
|
||||
if tool_choice := self._prepare_tool_choice_mode(chat_options):
|
||||
if tool_choice := self._prepare_tool_choice_mode(options):
|
||||
run_options["tool_choice"] = tool_choice
|
||||
|
||||
# response format
|
||||
if chat_options.response_format is not None:
|
||||
run_options["response_format"] = ResponseFormatJsonSchemaType(
|
||||
json_schema=ResponseFormatJsonSchema(
|
||||
name=chat_options.response_format.__name__,
|
||||
schema=chat_options.response_format.model_json_schema(),
|
||||
response_format = options.get("response_format")
|
||||
if response_format is not None:
|
||||
if isinstance(response_format, type) and issubclass(response_format, BaseModel):
|
||||
# Pydantic model - convert to Azure format
|
||||
run_options["response_format"] = ResponseFormatJsonSchemaType(
|
||||
json_schema=ResponseFormatJsonSchema(
|
||||
name=response_format.__name__,
|
||||
schema=response_format.model_json_schema(),
|
||||
)
|
||||
)
|
||||
elif isinstance(response_format, Mapping):
|
||||
# Runtime JSON schema dict - pass through as-is
|
||||
run_options["response_format"] = response_format
|
||||
else:
|
||||
raise ServiceInvalidRequestError(
|
||||
"response_format must be a Pydantic BaseModel class or a dict with runtime JSON schema."
|
||||
)
|
||||
)
|
||||
|
||||
# messages
|
||||
additional_messages, instructions, required_action_results = self._prepare_messages(messages)
|
||||
@@ -873,41 +951,40 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
run_options["instructions"] = "\n".join(instructions)
|
||||
|
||||
# thread_id resolution (conversation_id takes precedence, then kwargs, then instance default)
|
||||
run_options["thread_id"] = chat_options.conversation_id or kwargs.get("conversation_id") or self.thread_id
|
||||
run_options["thread_id"] = options.get("conversation_id") or kwargs.get("conversation_id") or self.thread_id
|
||||
|
||||
return run_options, required_action_results
|
||||
|
||||
def _prepare_tool_choice_mode(
|
||||
self, chat_options: ChatOptions
|
||||
self, options: Mapping[str, Any]
|
||||
) -> AgentsToolChoiceOptionMode | AgentsNamedToolChoice | None:
|
||||
"""Prepare the tool choice mode for Azure AI Agents API."""
|
||||
if chat_options.tool_choice is None:
|
||||
tool_choice = options.get("tool_choice")
|
||||
if tool_choice is None:
|
||||
return None
|
||||
if chat_options.tool_choice == "none":
|
||||
if tool_choice == "none":
|
||||
return AgentsToolChoiceOptionMode.NONE
|
||||
if chat_options.tool_choice == "auto":
|
||||
if tool_choice == "auto":
|
||||
return AgentsToolChoiceOptionMode.AUTO
|
||||
if (
|
||||
isinstance(chat_options.tool_choice, ToolMode)
|
||||
and chat_options.tool_choice == "required"
|
||||
and chat_options.tool_choice.required_function_name is not None
|
||||
):
|
||||
return AgentsNamedToolChoice(
|
||||
type=AgentsNamedToolChoiceType.FUNCTION,
|
||||
function=FunctionName(name=chat_options.tool_choice.required_function_name),
|
||||
)
|
||||
if isinstance(tool_choice, Mapping) and tool_choice.get("mode") == "required":
|
||||
req_fn = tool_choice.get("required_function_name")
|
||||
if req_fn:
|
||||
return AgentsNamedToolChoice(
|
||||
type=AgentsNamedToolChoiceType.FUNCTION,
|
||||
function=FunctionName(name=str(req_fn)),
|
||||
)
|
||||
return None
|
||||
|
||||
async def _prepare_tool_definitions_and_resources(
|
||||
self,
|
||||
chat_options: ChatOptions,
|
||||
options: Mapping[str, Any],
|
||||
agent_definition: Agent | None,
|
||||
run_options: dict[str, Any],
|
||||
) -> list[ToolDefinition | dict[str, Any]]:
|
||||
"""Prepare tool definitions and resources for the run options."""
|
||||
tool_definitions: list[ToolDefinition | dict[str, Any]] = []
|
||||
|
||||
# Add tools from existing agent (exclude function tools - passed via chat_options.tools)
|
||||
# Add tools from existing agent (exclude function tools - passed via options.get("tools"))
|
||||
if agent_definition is not None:
|
||||
agent_tools = [tool for tool in agent_definition.tools if not isinstance(tool, FunctionToolDefinition)]
|
||||
if agent_tools:
|
||||
@@ -916,11 +993,13 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
run_options["tool_resources"] = agent_definition.tool_resources
|
||||
|
||||
# Add run tools if tool_choice allows
|
||||
if chat_options.tool_choice is not None and chat_options.tool_choice != "none" and chat_options.tools:
|
||||
tool_definitions.extend(await self._prepare_tools_for_azure_ai(chat_options.tools, run_options))
|
||||
tool_choice = options.get("tool_choice")
|
||||
tools = options.get("tools")
|
||||
if tool_choice is not None and tool_choice != "none" and tools:
|
||||
tool_definitions.extend(to_azure_ai_agent_tools(tools, run_options))
|
||||
|
||||
# Handle MCP tool resources
|
||||
mcp_resources = self._prepare_mcp_resources(chat_options.tools)
|
||||
mcp_resources = self._prepare_mcp_resources(tools)
|
||||
if mcp_resources:
|
||||
if "tool_resources" not in run_options:
|
||||
run_options["tool_resources"] = {}
|
||||
@@ -1016,82 +1095,6 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
|
||||
return additional_messages, instructions, required_action_results
|
||||
|
||||
async def _prepare_tools_for_azure_ai(
|
||||
self, tools: Sequence["ToolProtocol | MutableMapping[str, Any]"], run_options: dict[str, Any] | None = None
|
||||
) -> list[ToolDefinition | dict[str, Any]]:
|
||||
"""Prepare tool definitions for the Azure AI Agents API."""
|
||||
tool_definitions: list[ToolDefinition | dict[str, Any]] = []
|
||||
for tool in tools:
|
||||
match tool:
|
||||
case AIFunction():
|
||||
tool_definitions.append(tool.to_json_schema_spec()) # type: ignore[reportUnknownArgumentType]
|
||||
case HostedWebSearchTool():
|
||||
additional_props = tool.additional_properties or {}
|
||||
config_args: dict[str, Any] = {}
|
||||
if count := additional_props.get("count"):
|
||||
config_args["count"] = count
|
||||
if freshness := additional_props.get("freshness"):
|
||||
config_args["freshness"] = freshness
|
||||
if market := additional_props.get("market"):
|
||||
config_args["market"] = market
|
||||
if set_lang := additional_props.get("set_lang"):
|
||||
config_args["set_lang"] = set_lang
|
||||
# Bing Grounding
|
||||
connection_id = additional_props.get("connection_id") or os.getenv("BING_CONNECTION_ID")
|
||||
# Custom Bing Search
|
||||
custom_connection_id = additional_props.get("custom_connection_id") or os.getenv(
|
||||
"BING_CUSTOM_CONNECTION_ID"
|
||||
)
|
||||
custom_instance_name = additional_props.get("custom_instance_name") or os.getenv(
|
||||
"BING_CUSTOM_INSTANCE_NAME"
|
||||
)
|
||||
bing_search: BingGroundingTool | BingCustomSearchTool | None = None
|
||||
if (connection_id) and not custom_connection_id and not custom_instance_name:
|
||||
if connection_id:
|
||||
conn_id = connection_id
|
||||
else:
|
||||
raise ServiceInitializationError("Parameter connection_id is not provided.")
|
||||
bing_search = BingGroundingTool(connection_id=conn_id, **config_args)
|
||||
if custom_connection_id and custom_instance_name:
|
||||
bing_search = BingCustomSearchTool(
|
||||
connection_id=custom_connection_id,
|
||||
instance_name=custom_instance_name,
|
||||
**config_args,
|
||||
)
|
||||
if not bing_search:
|
||||
raise ServiceInitializationError(
|
||||
"Bing search tool requires either 'connection_id' for Bing Grounding "
|
||||
"or both 'custom_connection_id' and 'custom_instance_name' for Custom Bing Search. "
|
||||
"These can be provided via additional_properties or environment variables: "
|
||||
"'BING_CONNECTION_ID', 'BING_CUSTOM_CONNECTION_ID', "
|
||||
"'BING_CUSTOM_INSTANCE_NAME'"
|
||||
)
|
||||
tool_definitions.extend(bing_search.definitions)
|
||||
case HostedCodeInterpreterTool():
|
||||
tool_definitions.append(CodeInterpreterToolDefinition())
|
||||
case HostedMCPTool():
|
||||
mcp_tool = McpTool(
|
||||
server_label=tool.name.replace(" ", "_"),
|
||||
server_url=str(tool.url),
|
||||
allowed_tools=list(tool.allowed_tools) if tool.allowed_tools else [],
|
||||
)
|
||||
tool_definitions.extend(mcp_tool.definitions)
|
||||
case HostedFileSearchTool():
|
||||
vector_stores = [inp for inp in tool.inputs or [] if isinstance(inp, HostedVectorStoreContent)]
|
||||
if vector_stores:
|
||||
file_search = FileSearchTool(vector_store_ids=[vs.vector_store_id for vs in vector_stores])
|
||||
tool_definitions.extend(file_search.definitions)
|
||||
# Set tool_resources for file search to work properly with Azure AI
|
||||
if run_options is not None and "tool_resources" not in run_options:
|
||||
run_options["tool_resources"] = file_search.resources
|
||||
case ToolDefinition():
|
||||
tool_definitions.append(tool)
|
||||
case dict():
|
||||
tool_definitions.append(tool)
|
||||
case _:
|
||||
raise ServiceInitializationError(f"Unsupported tool type: {type(tool)}")
|
||||
return tool_definitions
|
||||
|
||||
def _prepare_tool_outputs_for_azure_ai(
|
||||
self,
|
||||
required_action_results: list[FunctionResultContent | FunctionApprovalResponseContent] | None,
|
||||
|
||||
@@ -2,19 +2,18 @@
|
||||
|
||||
import sys
|
||||
from collections.abc import Mapping, MutableSequence
|
||||
from typing import Any, ClassVar, TypeVar, cast
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypedDict, TypeVar, cast
|
||||
|
||||
from agent_framework import (
|
||||
AGENT_FRAMEWORK_USER_AGENT,
|
||||
ChatMessage,
|
||||
ChatOptions,
|
||||
HostedMCPTool,
|
||||
TextContent,
|
||||
get_logger,
|
||||
use_chat_middleware,
|
||||
use_function_invocation,
|
||||
)
|
||||
from agent_framework.exceptions import ServiceInitializationError, ServiceInvalidRequestError
|
||||
from agent_framework.exceptions import ServiceInitializationError
|
||||
from agent_framework.observability import use_instrumentation
|
||||
from agent_framework.openai._responses_client import OpenAIBaseResponsesClient
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
@@ -22,37 +21,44 @@ from azure.ai.projects.models import (
|
||||
MCPTool,
|
||||
PromptAgentDefinition,
|
||||
PromptAgentDefinitionText,
|
||||
ResponseTextFormatConfigurationJsonObject,
|
||||
ResponseTextFormatConfigurationJsonSchema,
|
||||
ResponseTextFormatConfigurationText,
|
||||
)
|
||||
from azure.core.credentials_async import AsyncTokenCredential
|
||||
from azure.core.exceptions import ResourceNotFoundError
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from pydantic import ValidationError
|
||||
|
||||
from ._shared import AzureAISettings
|
||||
from ._shared import AzureAISettings, create_text_format_config
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from agent_framework.openai import OpenAIResponsesOptions
|
||||
|
||||
if sys.version_info >= (3, 13):
|
||||
from typing import TypeVar # type: ignore # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import TypeVar # type: ignore # pragma: no cover
|
||||
if sys.version_info >= (3, 12):
|
||||
from typing import override # type: ignore # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import override # type: ignore[import] # pragma: no cover
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import Self # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import Self # pragma: no cover
|
||||
|
||||
if sys.version_info >= (3, 12):
|
||||
from typing import override # type: ignore # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import override # type: ignore[import] # pragma: no cover
|
||||
|
||||
|
||||
logger = get_logger("agent_framework.azure")
|
||||
|
||||
|
||||
TAzureAIClient = TypeVar("TAzureAIClient", bound="AzureAIClient")
|
||||
TAzureAIClientOptions = TypeVar(
|
||||
"TAzureAIClientOptions",
|
||||
bound=TypedDict, # type: ignore[valid-type]
|
||||
default="OpenAIResponsesOptions",
|
||||
covariant=True,
|
||||
)
|
||||
|
||||
|
||||
@use_function_invocation
|
||||
@use_instrumentation
|
||||
@use_chat_middleware
|
||||
class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
class AzureAIClient(OpenAIBaseResponsesClient[TAzureAIClientOptions], Generic[TAzureAIClientOptions]):
|
||||
"""Azure AI Agent client."""
|
||||
|
||||
OTEL_PROVIDER_NAME: ClassVar[str] = "azure.ai" # type: ignore[reportIncompatibleVariableOverride, misc]
|
||||
@@ -115,6 +121,18 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
|
||||
# Or loading from a .env file
|
||||
client = AzureAIClient(credential=credential, env_file_path="path/to/.env")
|
||||
|
||||
# Using custom ChatOptions with type safety:
|
||||
from typing import TypedDict
|
||||
from agent_framework import ChatOptions
|
||||
|
||||
|
||||
class MyOptions(ChatOptions, total=False):
|
||||
my_custom_option: str
|
||||
|
||||
|
||||
client: AzureAIClient[MyOptions] = AzureAIClient(credential=credential)
|
||||
response = await client.get_response("Hello", options={"my_custom_option": "value"})
|
||||
"""
|
||||
try:
|
||||
azure_ai_settings = AzureAISettings(
|
||||
@@ -265,45 +283,11 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
"""Close the project_client."""
|
||||
await self._close_client_if_needed()
|
||||
|
||||
def _create_text_format_config(
|
||||
self, response_format: Any
|
||||
) -> (
|
||||
ResponseTextFormatConfigurationJsonSchema
|
||||
| ResponseTextFormatConfigurationJsonObject
|
||||
| ResponseTextFormatConfigurationText
|
||||
):
|
||||
"""Convert response_format into Azure text format configuration."""
|
||||
if isinstance(response_format, type) and issubclass(response_format, BaseModel):
|
||||
return ResponseTextFormatConfigurationJsonSchema(
|
||||
name=response_format.__name__,
|
||||
schema=response_format.model_json_schema(),
|
||||
)
|
||||
|
||||
if isinstance(response_format, Mapping):
|
||||
format_config = self._convert_response_format(response_format)
|
||||
format_type = format_config.get("type")
|
||||
if format_type == "json_schema":
|
||||
config_kwargs: dict[str, Any] = {
|
||||
"name": format_config.get("name") or "response",
|
||||
"schema": format_config["schema"],
|
||||
}
|
||||
if "strict" in format_config:
|
||||
config_kwargs["strict"] = format_config["strict"]
|
||||
if "description" in format_config:
|
||||
config_kwargs["description"] = format_config["description"]
|
||||
return ResponseTextFormatConfigurationJsonSchema(**config_kwargs)
|
||||
if format_type == "json_object":
|
||||
return ResponseTextFormatConfigurationJsonObject()
|
||||
if format_type == "text":
|
||||
return ResponseTextFormatConfigurationText()
|
||||
|
||||
raise ServiceInvalidRequestError("response_format must be a Pydantic model or mapping.")
|
||||
|
||||
async def _get_agent_reference_or_create(
|
||||
self,
|
||||
run_options: dict[str, Any],
|
||||
messages_instructions: str | None,
|
||||
chat_options: ChatOptions | None = None,
|
||||
chat_options: Mapping[str, Any] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Determine which agent to use and create if needed.
|
||||
|
||||
@@ -315,11 +299,6 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
Returns:
|
||||
dict[str, str]: The agent reference to use.
|
||||
"""
|
||||
# chat_options is needed separately because the base class excludes response_format
|
||||
# from run_options (transforming it to text/text_format for OpenAI). Azure's agent
|
||||
# creation API requires the original response_format to build its own config format.
|
||||
if chat_options is None:
|
||||
chat_options = ChatOptions()
|
||||
# Agent name must be explicitly provided by the user.
|
||||
if self.agent_name is None:
|
||||
raise ServiceInitializationError(
|
||||
@@ -356,13 +335,8 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
|
||||
# response_format is accessed from chat_options or additional_properties
|
||||
# since the base class excludes it from run_options
|
||||
response_format: Any = (
|
||||
chat_options.response_format
|
||||
if chat_options.response_format is not None
|
||||
else chat_options.additional_properties.get("response_format")
|
||||
)
|
||||
if response_format:
|
||||
args["text"] = PromptAgentDefinitionText(format=self._create_text_format_config(response_format))
|
||||
if chat_options and (response_format := chat_options.get("response_format")):
|
||||
args["text"] = PromptAgentDefinitionText(format=create_text_format_config(response_format))
|
||||
|
||||
# Combine instructions from messages and options
|
||||
combined_instructions = [
|
||||
@@ -392,12 +366,12 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
async def _prepare_options(
|
||||
self,
|
||||
messages: MutableSequence[ChatMessage],
|
||||
chat_options: ChatOptions,
|
||||
options: dict[str, Any],
|
||||
**kwargs: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""Take ChatOptions and create the specific options for Azure AI."""
|
||||
prepared_messages, instructions = self._prepare_messages_for_azure_ai(messages)
|
||||
run_options = await super()._prepare_options(prepared_messages, chat_options, **kwargs)
|
||||
run_options = await super()._prepare_options(prepared_messages, options, **kwargs)
|
||||
|
||||
# WORKAROUND: Azure AI Projects 'create responses' API has schema divergence from OpenAI's
|
||||
# Responses API. Azure requires 'type' at item level and 'annotations' in content items.
|
||||
@@ -409,18 +383,33 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
|
||||
if not self._is_application_endpoint:
|
||||
# Application-scoped response APIs do not support "agent" property.
|
||||
agent_reference = await self._get_agent_reference_or_create(run_options, instructions, chat_options)
|
||||
agent_reference = await self._get_agent_reference_or_create(run_options, instructions, options)
|
||||
run_options["extra_body"] = {"agent": agent_reference}
|
||||
|
||||
# Remove properties that are not supported on request level
|
||||
# but were configured on agent level
|
||||
exclude = ["model", "tools", "response_format", "temperature", "top_p", "text", "text_format"]
|
||||
exclude = [
|
||||
"model",
|
||||
"tools",
|
||||
"response_format",
|
||||
"temperature",
|
||||
"top_p",
|
||||
"text",
|
||||
"text_format",
|
||||
]
|
||||
|
||||
for property in exclude:
|
||||
run_options.pop(property, None)
|
||||
|
||||
return run_options
|
||||
|
||||
@override
|
||||
def _check_model_presence(self, run_options: dict[str, Any]) -> None:
|
||||
if not run_options.get("model"):
|
||||
if not self.model_id:
|
||||
raise ValueError("model_deployment_name must be a non-empty string")
|
||||
run_options["model"] = self.model_id
|
||||
|
||||
def _transform_input_for_azure_ai(self, input_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Transform input items to match Azure AI Projects expected schema.
|
||||
|
||||
@@ -460,9 +449,9 @@ class AzureAIClient(OpenAIBaseResponsesClient):
|
||||
return transformed
|
||||
|
||||
@override
|
||||
def _get_current_conversation_id(self, chat_options: ChatOptions, **kwargs: Any) -> str | None:
|
||||
def _get_current_conversation_id(self, options: dict[str, Any], **kwargs: Any) -> str | None:
|
||||
"""Get the current conversation ID from chat options or kwargs."""
|
||||
return chat_options.conversation_id or kwargs.get("conversation_id") or self.conversation_id
|
||||
return options.get("conversation_id") or kwargs.get("conversation_id") or self.conversation_id
|
||||
|
||||
def _prepare_messages_for_azure_ai(
|
||||
self, messages: MutableSequence[ChatMessage]
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import sys
|
||||
from collections.abc import Callable, MutableMapping, Sequence
|
||||
from typing import TYPE_CHECKING, Any, Generic, TypedDict
|
||||
|
||||
from agent_framework import (
|
||||
AGENT_FRAMEWORK_USER_AGENT,
|
||||
AIFunction,
|
||||
ChatAgent,
|
||||
ContextProvider,
|
||||
Middleware,
|
||||
ToolProtocol,
|
||||
get_logger,
|
||||
normalize_tools,
|
||||
)
|
||||
from agent_framework.exceptions import ServiceInitializationError
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import (
|
||||
AgentReference,
|
||||
AgentVersionDetails,
|
||||
FunctionTool,
|
||||
PromptAgentDefinition,
|
||||
PromptAgentDefinitionText,
|
||||
)
|
||||
from azure.core.credentials_async import AsyncTokenCredential
|
||||
from pydantic import ValidationError
|
||||
|
||||
from ._client import AzureAIClient
|
||||
from ._shared import AzureAISettings, create_text_format_config, from_azure_ai_tools, to_azure_ai_tools
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from agent_framework.openai import OpenAIResponsesOptions
|
||||
|
||||
if sys.version_info >= (3, 13):
|
||||
from typing import Self, TypeVar # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import Self, TypeVar # pragma: no cover
|
||||
|
||||
|
||||
logger = get_logger("agent_framework.azure")
|
||||
|
||||
|
||||
# Type variable for options - allows typed ChatAgent[TOptions] returns
|
||||
# Default matches AzureAIClient's default options type
|
||||
TOptions_co = TypeVar(
|
||||
"TOptions_co",
|
||||
bound=TypedDict, # type: ignore[valid-type]
|
||||
default="OpenAIResponsesOptions",
|
||||
covariant=True,
|
||||
)
|
||||
|
||||
|
||||
class AzureAIProjectAgentProvider(Generic[TOptions_co]):
|
||||
"""Provider for Azure AI Agent Service (Responses API).
|
||||
|
||||
This provider allows you to create, retrieve, and manage Azure AI agents
|
||||
using the AIProjectClient from the Azure AI Projects SDK.
|
||||
|
||||
Examples:
|
||||
Using with explicit AIProjectClient:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import DefaultAzureCredential
|
||||
|
||||
async with AIProjectClient(endpoint, credential) as client:
|
||||
provider = AzureAIProjectAgentProvider(client)
|
||||
agent = await provider.create_agent(
|
||||
name="MyAgent",
|
||||
model="gpt-4",
|
||||
instructions="You are a helpful assistant.",
|
||||
)
|
||||
response = await agent.run("Hello!")
|
||||
|
||||
Using with credential and endpoint (auto-creates client):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import DefaultAzureCredential
|
||||
|
||||
async with AzureAIProjectAgentProvider(credential=credential) as provider:
|
||||
agent = await provider.create_agent(
|
||||
name="MyAgent",
|
||||
model="gpt-4",
|
||||
instructions="You are a helpful assistant.",
|
||||
)
|
||||
response = await agent.run("Hello!")
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
project_client: AIProjectClient | None = None,
|
||||
*,
|
||||
project_endpoint: str | None = None,
|
||||
model: str | None = None,
|
||||
credential: AsyncTokenCredential | None = None,
|
||||
env_file_path: str | None = None,
|
||||
env_file_encoding: str | None = None,
|
||||
) -> None:
|
||||
"""Initialize an Azure AI Project Agent Provider.
|
||||
|
||||
Args:
|
||||
project_client: An existing AIProjectClient to use. If not provided, one will be created.
|
||||
project_endpoint: The Azure AI Project endpoint URL.
|
||||
Can also be set via environment variable AZURE_AI_PROJECT_ENDPOINT.
|
||||
Ignored when a project_client is passed.
|
||||
model: The default model deployment name to use for agent creation.
|
||||
Can also be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
|
||||
credential: Azure async credential to use for authentication.
|
||||
Required when project_client is not provided.
|
||||
env_file_path: Path to environment file for loading settings.
|
||||
env_file_encoding: Encoding of the environment file.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If required parameters are missing or invalid.
|
||||
"""
|
||||
try:
|
||||
self._settings = AzureAISettings(
|
||||
project_endpoint=project_endpoint,
|
||||
model_deployment_name=model,
|
||||
env_file_path=env_file_path,
|
||||
env_file_encoding=env_file_encoding,
|
||||
)
|
||||
except ValidationError as ex:
|
||||
raise ServiceInitializationError("Failed to create Azure AI settings.", ex) from ex
|
||||
|
||||
# Track whether we should close client connection
|
||||
self._should_close_client = False
|
||||
|
||||
if project_client is None:
|
||||
if not self._settings.project_endpoint:
|
||||
raise ServiceInitializationError(
|
||||
"Azure AI project endpoint is required. Set via 'project_endpoint' parameter "
|
||||
"or 'AZURE_AI_PROJECT_ENDPOINT' environment variable."
|
||||
)
|
||||
|
||||
if not credential:
|
||||
raise ServiceInitializationError("Azure credential is required when project_client is not provided.")
|
||||
|
||||
project_client = AIProjectClient(
|
||||
endpoint=self._settings.project_endpoint,
|
||||
credential=credential,
|
||||
user_agent=AGENT_FRAMEWORK_USER_AGENT,
|
||||
)
|
||||
self._should_close_client = True
|
||||
|
||||
self._project_client = project_client
|
||||
|
||||
async def create_agent(
|
||||
self,
|
||||
name: str,
|
||||
model: str | None = None,
|
||||
instructions: str | None = None,
|
||||
description: str | None = None,
|
||||
tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Create a new agent on the Azure AI service and return a local ChatAgent wrapper.
|
||||
|
||||
Args:
|
||||
name: The name of the agent to create.
|
||||
model: The model deployment name to use. Falls back to AZURE_AI_MODEL_DEPLOYMENT_NAME
|
||||
environment variable if not provided.
|
||||
instructions: Instructions for the agent.
|
||||
description: A description of the agent.
|
||||
tools: Tools to make available to the agent.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
|
||||
Returns:
|
||||
ChatAgent: A ChatAgent instance configured with the created agent.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If required parameters are missing.
|
||||
"""
|
||||
# Resolve model from parameter or environment variable
|
||||
resolved_model = model or self._settings.model_deployment_name
|
||||
if not resolved_model:
|
||||
raise ServiceInitializationError(
|
||||
"Model deployment name is required. Provide 'model' parameter "
|
||||
"or set 'AZURE_AI_MODEL_DEPLOYMENT_NAME' environment variable."
|
||||
)
|
||||
|
||||
# Extract response_format from default_options if present
|
||||
opts = dict(default_options) if default_options else {}
|
||||
response_format = opts.get("response_format")
|
||||
|
||||
args: dict[str, Any] = {"model": resolved_model}
|
||||
|
||||
if instructions:
|
||||
args["instructions"] = instructions
|
||||
if response_format and isinstance(response_format, (type, dict)):
|
||||
args["text"] = PromptAgentDefinitionText(
|
||||
format=create_text_format_config(response_format) # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
# Normalize tools once and reuse for both Azure AI API and ChatAgent
|
||||
normalized_tools = normalize_tools(tools)
|
||||
if normalized_tools:
|
||||
args["tools"] = to_azure_ai_tools(normalized_tools)
|
||||
|
||||
created_agent = await self._project_client.agents.create_version(
|
||||
agent_name=name,
|
||||
definition=PromptAgentDefinition(**args),
|
||||
description=description,
|
||||
)
|
||||
|
||||
return self._to_chat_agent_from_details(
|
||||
created_agent,
|
||||
normalized_tools,
|
||||
default_options=default_options,
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
async def get_agent(
|
||||
self,
|
||||
*,
|
||||
name: str | None = None,
|
||||
reference: AgentReference | None = None,
|
||||
tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Retrieve an existing agent from the Azure AI service and return a local ChatAgent wrapper.
|
||||
|
||||
You must provide either name or reference. Use `as_agent()` if you already have
|
||||
AgentVersionDetails and want to avoid an async call.
|
||||
|
||||
Args:
|
||||
name: The name of the agent to retrieve (fetches latest version).
|
||||
reference: Reference containing the agent's name and optionally a specific version.
|
||||
tools: Tools to make available to the agent. Required if the agent has function tools.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
|
||||
Returns:
|
||||
ChatAgent: A ChatAgent instance configured with the retrieved agent.
|
||||
|
||||
Raises:
|
||||
ValueError: If no identifier is provided or required tools are missing.
|
||||
"""
|
||||
existing_agent: AgentVersionDetails
|
||||
|
||||
if reference and reference.version:
|
||||
# Fetch specific version
|
||||
existing_agent = await self._project_client.agents.get_version(
|
||||
agent_name=reference.name, agent_version=reference.version
|
||||
)
|
||||
elif agent_name := (reference.name if reference else name):
|
||||
# Fetch latest version
|
||||
details = await self._project_client.agents.get(agent_name=agent_name)
|
||||
existing_agent = details.versions.latest
|
||||
else:
|
||||
raise ValueError("Either name or reference must be provided to get an agent.")
|
||||
|
||||
if not isinstance(existing_agent.definition, PromptAgentDefinition):
|
||||
raise ValueError("Agent definition must be PromptAgentDefinition to get a ChatAgent.")
|
||||
|
||||
# Validate that required function tools are provided
|
||||
self._validate_function_tools(existing_agent.definition.tools, tools)
|
||||
|
||||
return self._to_chat_agent_from_details(
|
||||
existing_agent,
|
||||
normalize_tools(tools),
|
||||
default_options=default_options,
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
def as_agent(
|
||||
self,
|
||||
details: AgentVersionDetails,
|
||||
tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Wrap an SDK agent version object into a ChatAgent without making HTTP calls.
|
||||
|
||||
Use this when you already have an AgentVersionDetails from a previous API call.
|
||||
|
||||
Args:
|
||||
details: The AgentVersionDetails to wrap.
|
||||
tools: Tools to make available to the agent. Required if the agent has function tools.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
|
||||
Returns:
|
||||
ChatAgent: A ChatAgent instance configured with the agent version.
|
||||
|
||||
Raises:
|
||||
ValueError: If the agent definition is not a PromptAgentDefinition or required tools are missing.
|
||||
"""
|
||||
if not isinstance(details.definition, PromptAgentDefinition):
|
||||
raise ValueError("Agent definition must be PromptAgentDefinition to create a ChatAgent.")
|
||||
|
||||
# Validate that required function tools are provided
|
||||
self._validate_function_tools(details.definition.tools, tools)
|
||||
|
||||
return self._to_chat_agent_from_details(
|
||||
details,
|
||||
normalize_tools(tools),
|
||||
default_options=default_options,
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
def _to_chat_agent_from_details(
|
||||
self,
|
||||
details: AgentVersionDetails,
|
||||
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None = None,
|
||||
default_options: TOptions_co | None = None,
|
||||
middleware: Sequence[Middleware] | None = None,
|
||||
context_provider: ContextProvider | None = None,
|
||||
) -> "ChatAgent[TOptions_co]":
|
||||
"""Create a ChatAgent from an AgentVersionDetails.
|
||||
|
||||
Args:
|
||||
details: The AgentVersionDetails containing the agent definition.
|
||||
provided_tools: User-provided tools (including function implementations).
|
||||
These are merged with hosted tools from the definition.
|
||||
default_options: A TypedDict containing default chat options for the agent.
|
||||
These options are applied to every run unless overridden.
|
||||
middleware: List of middleware to intercept agent and function invocations.
|
||||
context_provider: Context provider to include during agent invocation.
|
||||
"""
|
||||
if not isinstance(details.definition, PromptAgentDefinition):
|
||||
raise ValueError("Agent definition must be PromptAgentDefinition to get a ChatAgent.")
|
||||
|
||||
client = AzureAIClient(
|
||||
project_client=self._project_client,
|
||||
agent_name=details.name,
|
||||
agent_version=details.version,
|
||||
agent_description=details.description,
|
||||
model_deployment_name=details.definition.model,
|
||||
)
|
||||
|
||||
# Merge tools: hosted tools from definition + user-provided function tools
|
||||
# from_azure_ai_tools converts hosted tools (MCP, code interpreter, file search, web search)
|
||||
# but function tools need the actual implementations from provided_tools
|
||||
merged_tools = self._merge_tools(details.definition.tools, provided_tools)
|
||||
|
||||
return ChatAgent( # type: ignore[return-value]
|
||||
chat_client=client,
|
||||
id=details.id,
|
||||
name=details.name,
|
||||
description=details.description,
|
||||
instructions=details.definition.instructions,
|
||||
model_id=details.definition.model,
|
||||
tools=merged_tools,
|
||||
default_options=default_options, # type: ignore[arg-type]
|
||||
middleware=middleware,
|
||||
context_provider=context_provider,
|
||||
)
|
||||
|
||||
def _merge_tools(
|
||||
self,
|
||||
definition_tools: Sequence[Any] | None,
|
||||
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
|
||||
) -> list[ToolProtocol | dict[str, Any]]:
|
||||
"""Merge hosted tools from definition with user-provided function tools.
|
||||
|
||||
Args:
|
||||
definition_tools: Tools from the agent definition (Azure AI format).
|
||||
provided_tools: User-provided tools (Agent Framework format), including function implementations.
|
||||
|
||||
Returns:
|
||||
Combined list of tools for the ChatAgent.
|
||||
"""
|
||||
merged: list[ToolProtocol | dict[str, Any]] = []
|
||||
|
||||
# Convert hosted tools from definition (MCP, code interpreter, file search, web search)
|
||||
# Function tools from the definition are skipped - we use user-provided implementations instead
|
||||
hosted_tools = from_azure_ai_tools(definition_tools)
|
||||
for hosted_tool in hosted_tools:
|
||||
# Skip function tool dicts - they don't have implementations
|
||||
if isinstance(hosted_tool, dict) and hosted_tool.get("type") == "function":
|
||||
continue
|
||||
merged.append(hosted_tool)
|
||||
|
||||
# Add user-provided function tools (these have the actual implementations)
|
||||
if provided_tools:
|
||||
for provided_tool in provided_tools:
|
||||
if isinstance(provided_tool, AIFunction):
|
||||
merged.append(provided_tool) # type: ignore[reportUnknownArgumentType]
|
||||
|
||||
return merged
|
||||
|
||||
def _validate_function_tools(
|
||||
self,
|
||||
agent_tools: Sequence[Any] | None,
|
||||
provided_tools: ToolProtocol
|
||||
| Callable[..., Any]
|
||||
| MutableMapping[str, Any]
|
||||
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
|
||||
| None,
|
||||
) -> None:
|
||||
"""Validate that required function tools are provided."""
|
||||
# Normalize and validate function tools
|
||||
normalized_tools = normalize_tools(provided_tools)
|
||||
tool_names = {tool.name for tool in normalized_tools if isinstance(tool, AIFunction)}
|
||||
|
||||
# If function tools exist in agent definition but were not provided,
|
||||
# we need to raise an error, as it won't be possible to invoke the function.
|
||||
missing_tools = [
|
||||
tool.name for tool in (agent_tools or []) if isinstance(tool, FunctionTool) and tool.name not in tool_names
|
||||
]
|
||||
|
||||
if missing_tools:
|
||||
raise ValueError(
|
||||
f"The following prompt agent definition required tools were not provided: {', '.join(missing_tools)}"
|
||||
)
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
"""Async context manager entry."""
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any) -> None:
|
||||
"""Async context manager exit."""
|
||||
await self.close()
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the provider and release resources.
|
||||
|
||||
Only closes the underlying AIProjectClient if it was created by this provider.
|
||||
"""
|
||||
if self._should_close_client:
|
||||
await self._project_client.close()
|
||||
@@ -1,8 +1,49 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
from typing import ClassVar
|
||||
import os
|
||||
from collections.abc import Mapping, MutableMapping, Sequence
|
||||
from typing import Any, ClassVar, Literal, cast
|
||||
|
||||
from agent_framework import (
|
||||
AIFunction,
|
||||
Contents,
|
||||
HostedCodeInterpreterTool,
|
||||
HostedFileContent,
|
||||
HostedFileSearchTool,
|
||||
HostedMCPTool,
|
||||
HostedVectorStoreContent,
|
||||
HostedWebSearchTool,
|
||||
ToolProtocol,
|
||||
get_logger,
|
||||
)
|
||||
from agent_framework._pydantic import AFBaseSettings
|
||||
from agent_framework.exceptions import ServiceInitializationError, ServiceInvalidRequestError
|
||||
from azure.ai.agents.models import (
|
||||
BingCustomSearchTool,
|
||||
BingGroundingTool,
|
||||
CodeInterpreterToolDefinition,
|
||||
McpTool,
|
||||
ToolDefinition,
|
||||
)
|
||||
from azure.ai.agents.models import FileSearchTool as AgentsFileSearchTool
|
||||
from azure.ai.projects.models import (
|
||||
ApproximateLocation,
|
||||
CodeInterpreterTool,
|
||||
CodeInterpreterToolAuto,
|
||||
FunctionTool,
|
||||
MCPTool,
|
||||
ResponseTextFormatConfigurationJsonObject,
|
||||
ResponseTextFormatConfigurationJsonSchema,
|
||||
ResponseTextFormatConfigurationText,
|
||||
Tool,
|
||||
WebSearchPreviewTool,
|
||||
)
|
||||
from azure.ai.projects.models import (
|
||||
FileSearchTool as ProjectsFileSearchTool,
|
||||
)
|
||||
from pydantic import BaseModel
|
||||
|
||||
logger = get_logger("agent_framework.azure")
|
||||
|
||||
|
||||
class AzureAISettings(AFBaseSettings):
|
||||
@@ -44,3 +85,481 @@ class AzureAISettings(AFBaseSettings):
|
||||
|
||||
project_endpoint: str | None = None
|
||||
model_deployment_name: str | None = None
|
||||
|
||||
|
||||
def to_azure_ai_agent_tools(
|
||||
tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
|
||||
run_options: dict[str, Any] | None = None,
|
||||
) -> list[ToolDefinition | dict[str, Any]]:
|
||||
"""Convert Agent Framework tools to Azure AI V1 SDK tool definitions.
|
||||
|
||||
Args:
|
||||
tools: Sequence of Agent Framework tools to convert.
|
||||
run_options: Optional dict with run options.
|
||||
|
||||
Returns:
|
||||
List of Azure AI V1 SDK tool definitions.
|
||||
|
||||
Raises:
|
||||
ServiceInitializationError: If tool configuration is invalid.
|
||||
"""
|
||||
if not tools:
|
||||
return []
|
||||
|
||||
tool_definitions: list[ToolDefinition | dict[str, Any]] = []
|
||||
for tool in tools:
|
||||
match tool:
|
||||
case AIFunction():
|
||||
tool_definitions.append(tool.to_json_schema_spec()) # type: ignore[reportUnknownArgumentType]
|
||||
case HostedWebSearchTool():
|
||||
additional_props = tool.additional_properties or {}
|
||||
config_args: dict[str, Any] = {}
|
||||
if count := additional_props.get("count"):
|
||||
config_args["count"] = count
|
||||
if freshness := additional_props.get("freshness"):
|
||||
config_args["freshness"] = freshness
|
||||
if market := additional_props.get("market"):
|
||||
config_args["market"] = market
|
||||
if set_lang := additional_props.get("set_lang"):
|
||||
config_args["set_lang"] = set_lang
|
||||
# Bing Grounding
|
||||
connection_id = additional_props.get("connection_id") or os.getenv("BING_CONNECTION_ID")
|
||||
# Custom Bing Search
|
||||
custom_connection_id = additional_props.get("custom_connection_id") or os.getenv(
|
||||
"BING_CUSTOM_CONNECTION_ID"
|
||||
)
|
||||
custom_instance_name = additional_props.get("custom_instance_name") or os.getenv(
|
||||
"BING_CUSTOM_INSTANCE_NAME"
|
||||
)
|
||||
bing_search: BingGroundingTool | BingCustomSearchTool | None = None
|
||||
if connection_id and not custom_connection_id and not custom_instance_name:
|
||||
bing_search = BingGroundingTool(connection_id=connection_id, **config_args)
|
||||
if custom_connection_id and custom_instance_name:
|
||||
bing_search = BingCustomSearchTool(
|
||||
connection_id=custom_connection_id,
|
||||
instance_name=custom_instance_name,
|
||||
**config_args,
|
||||
)
|
||||
if not bing_search:
|
||||
raise ServiceInitializationError(
|
||||
"Bing search tool requires either 'connection_id' for Bing Grounding "
|
||||
"or both 'custom_connection_id' and 'custom_instance_name' for Custom Bing Search. "
|
||||
"These can be provided via additional_properties or environment variables: "
|
||||
"'BING_CONNECTION_ID', 'BING_CUSTOM_CONNECTION_ID', 'BING_CUSTOM_INSTANCE_NAME'"
|
||||
)
|
||||
tool_definitions.extend(bing_search.definitions)
|
||||
case HostedCodeInterpreterTool():
|
||||
tool_definitions.append(CodeInterpreterToolDefinition())
|
||||
case HostedMCPTool():
|
||||
mcp_tool = McpTool(
|
||||
server_label=tool.name.replace(" ", "_"),
|
||||
server_url=str(tool.url),
|
||||
allowed_tools=list(tool.allowed_tools) if tool.allowed_tools else [],
|
||||
)
|
||||
tool_definitions.extend(mcp_tool.definitions)
|
||||
case HostedFileSearchTool():
|
||||
vector_stores = [inp for inp in tool.inputs or [] if isinstance(inp, HostedVectorStoreContent)]
|
||||
if vector_stores:
|
||||
file_search = AgentsFileSearchTool(vector_store_ids=[vs.vector_store_id for vs in vector_stores])
|
||||
tool_definitions.extend(file_search.definitions)
|
||||
# Set tool_resources for file search to work properly with Azure AI
|
||||
if run_options is not None and "tool_resources" not in run_options:
|
||||
run_options["tool_resources"] = file_search.resources
|
||||
case ToolDefinition():
|
||||
tool_definitions.append(tool)
|
||||
case dict():
|
||||
tool_definitions.append(tool)
|
||||
case _:
|
||||
raise ServiceInitializationError(f"Unsupported tool type: {type(tool)}")
|
||||
return tool_definitions
|
||||
|
||||
|
||||
def from_azure_ai_agent_tools(
|
||||
tools: Sequence[ToolDefinition | dict[str, Any]] | None,
|
||||
) -> list[ToolProtocol | dict[str, Any]]:
|
||||
"""Convert Azure AI V1 SDK tool definitions to Agent Framework tools.
|
||||
|
||||
Args:
|
||||
tools: Sequence of Azure AI V1 SDK tool definitions.
|
||||
|
||||
Returns:
|
||||
List of Agent Framework tools.
|
||||
"""
|
||||
if not tools:
|
||||
return []
|
||||
|
||||
result: list[ToolProtocol | dict[str, Any]] = []
|
||||
for tool in tools:
|
||||
# Handle SDK objects
|
||||
if isinstance(tool, CodeInterpreterToolDefinition):
|
||||
result.append(HostedCodeInterpreterTool())
|
||||
elif isinstance(tool, dict):
|
||||
# Handle dict format
|
||||
converted = _convert_dict_tool(tool)
|
||||
if converted is not None:
|
||||
result.append(converted)
|
||||
elif hasattr(tool, "type"):
|
||||
# Handle other SDK objects by type
|
||||
converted = _convert_sdk_tool(tool)
|
||||
if converted is not None:
|
||||
result.append(converted)
|
||||
return result
|
||||
|
||||
|
||||
def _convert_dict_tool(tool: dict[str, Any]) -> ToolProtocol | dict[str, Any] | None:
|
||||
"""Convert a dict-format Azure AI tool to Agent Framework tool."""
|
||||
tool_type = tool.get("type")
|
||||
|
||||
if tool_type == "code_interpreter":
|
||||
return HostedCodeInterpreterTool()
|
||||
|
||||
if tool_type == "file_search":
|
||||
file_search_config = tool.get("file_search", {})
|
||||
vector_store_ids = file_search_config.get("vector_store_ids", [])
|
||||
inputs = [HostedVectorStoreContent(vector_store_id=vs_id) for vs_id in vector_store_ids]
|
||||
return HostedFileSearchTool(inputs=inputs if inputs else None) # type: ignore
|
||||
|
||||
if tool_type == "bing_grounding":
|
||||
bing_config = tool.get("bing_grounding", {})
|
||||
connection_id = bing_config.get("connection_id")
|
||||
return HostedWebSearchTool(additional_properties={"connection_id": connection_id} if connection_id else None)
|
||||
|
||||
if tool_type == "bing_custom_search":
|
||||
bing_config = tool.get("bing_custom_search", {})
|
||||
return HostedWebSearchTool(
|
||||
additional_properties={
|
||||
"custom_connection_id": bing_config.get("connection_id"),
|
||||
"custom_instance_name": bing_config.get("instance_name"),
|
||||
}
|
||||
)
|
||||
|
||||
if tool_type == "mcp":
|
||||
# Hosted MCP tools are defined on the Azure agent, no local handling needed
|
||||
# Azure may not return full server_url, so skip conversion
|
||||
return None
|
||||
|
||||
if tool_type == "function":
|
||||
# Function tools are returned as dicts - users must provide implementations
|
||||
return tool
|
||||
|
||||
# Unknown tool type - pass through
|
||||
return tool
|
||||
|
||||
|
||||
def _convert_sdk_tool(tool: ToolDefinition) -> ToolProtocol | dict[str, Any] | None:
|
||||
"""Convert an SDK-object Azure AI tool to Agent Framework tool."""
|
||||
tool_type = getattr(tool, "type", None)
|
||||
|
||||
if tool_type == "code_interpreter":
|
||||
return HostedCodeInterpreterTool()
|
||||
|
||||
if tool_type == "file_search":
|
||||
file_search_config = getattr(tool, "file_search", None)
|
||||
vector_store_ids = getattr(file_search_config, "vector_store_ids", []) if file_search_config else []
|
||||
inputs = [HostedVectorStoreContent(vector_store_id=vs_id) for vs_id in vector_store_ids]
|
||||
return HostedFileSearchTool(inputs=inputs if inputs else None) # type: ignore
|
||||
|
||||
if tool_type == "bing_grounding":
|
||||
bing_config = getattr(tool, "bing_grounding", None)
|
||||
connection_id = getattr(bing_config, "connection_id", None) if bing_config else None
|
||||
return HostedWebSearchTool(additional_properties={"connection_id": connection_id} if connection_id else None)
|
||||
|
||||
if tool_type == "bing_custom_search":
|
||||
bing_config = getattr(tool, "bing_custom_search", None)
|
||||
return HostedWebSearchTool(
|
||||
additional_properties={
|
||||
"custom_connection_id": getattr(bing_config, "connection_id", None) if bing_config else None,
|
||||
"custom_instance_name": getattr(bing_config, "instance_name", None) if bing_config else None,
|
||||
}
|
||||
)
|
||||
|
||||
if tool_type == "mcp":
|
||||
# Hosted MCP tools are defined on the Azure agent, no local handling needed
|
||||
# Azure may not return full server_url, so skip conversion
|
||||
return None
|
||||
|
||||
if tool_type == "function":
|
||||
# Function tools from SDK don't have implementations - skip
|
||||
return None
|
||||
|
||||
# Unknown tool type - convert to dict if possible
|
||||
if hasattr(tool, "as_dict"):
|
||||
return tool.as_dict() # type: ignore[union-attr]
|
||||
return {"type": tool_type} if tool_type else {}
|
||||
|
||||
|
||||
def from_azure_ai_tools(tools: Sequence[Tool | dict[str, Any]] | None) -> list[ToolProtocol | dict[str, Any]]:
|
||||
"""Parses and converts a sequence of Azure AI tools into Agent Framework compatible tools.
|
||||
|
||||
Args:
|
||||
tools: A sequence of tool objects or dictionaries
|
||||
defining the tools to be parsed. Can be None.
|
||||
|
||||
Returns:
|
||||
list[ToolProtocol | dict[str, Any]]: A list of converted tools compatible with the
|
||||
Agent Framework.
|
||||
"""
|
||||
agent_tools: list[ToolProtocol | dict[str, Any]] = []
|
||||
if not tools:
|
||||
return agent_tools
|
||||
for tool in tools:
|
||||
# Handle raw dictionary tools
|
||||
tool_dict = tool if isinstance(tool, dict) else dict(tool)
|
||||
tool_type = tool_dict.get("type")
|
||||
|
||||
if tool_type == "mcp":
|
||||
mcp_tool = cast(MCPTool, tool_dict)
|
||||
approval_mode: Literal["always_require", "never_require"] | dict[str, set[str]] | None = None
|
||||
if require_approval := mcp_tool.get("require_approval"):
|
||||
if require_approval == "always":
|
||||
approval_mode = "always_require"
|
||||
elif require_approval == "never":
|
||||
approval_mode = "never_require"
|
||||
elif isinstance(require_approval, dict):
|
||||
approval_mode = {}
|
||||
if "always" in require_approval:
|
||||
approval_mode["always_require_approval"] = set(require_approval["always"].get("tool_names", [])) # type: ignore
|
||||
if "never" in require_approval:
|
||||
approval_mode["never_require_approval"] = set(require_approval["never"].get("tool_names", [])) # type: ignore
|
||||
|
||||
agent_tools.append(
|
||||
HostedMCPTool(
|
||||
name=mcp_tool.get("server_label", "").replace("_", " "),
|
||||
url=mcp_tool.get("server_url", ""),
|
||||
description=mcp_tool.get("server_description"),
|
||||
headers=mcp_tool.get("headers"),
|
||||
allowed_tools=mcp_tool.get("allowed_tools"),
|
||||
approval_mode=approval_mode, # type: ignore
|
||||
)
|
||||
)
|
||||
elif tool_type == "code_interpreter":
|
||||
ci_tool = cast(CodeInterpreterTool, tool_dict)
|
||||
container = ci_tool.get("container", {})
|
||||
ci_inputs: list[Contents] = []
|
||||
if "file_ids" in container:
|
||||
for file_id in container["file_ids"]:
|
||||
ci_inputs.append(HostedFileContent(file_id=file_id))
|
||||
|
||||
agent_tools.append(HostedCodeInterpreterTool(inputs=ci_inputs if ci_inputs else None)) # type: ignore
|
||||
elif tool_type == "file_search":
|
||||
fs_tool = cast(ProjectsFileSearchTool, tool_dict)
|
||||
fs_inputs: list[Contents] = []
|
||||
if "vector_store_ids" in fs_tool:
|
||||
for vs_id in fs_tool["vector_store_ids"]:
|
||||
fs_inputs.append(HostedVectorStoreContent(vector_store_id=vs_id))
|
||||
|
||||
agent_tools.append(
|
||||
HostedFileSearchTool(
|
||||
inputs=fs_inputs if fs_inputs else None, # type: ignore
|
||||
max_results=fs_tool.get("max_num_results"),
|
||||
)
|
||||
)
|
||||
elif tool_type == "web_search_preview":
|
||||
ws_tool = cast(WebSearchPreviewTool, tool_dict)
|
||||
additional_properties: dict[str, Any] = {}
|
||||
if user_location := ws_tool.get("user_location"):
|
||||
additional_properties["user_location"] = {
|
||||
"city": user_location.get("city"),
|
||||
"country": user_location.get("country"),
|
||||
"region": user_location.get("region"),
|
||||
"timezone": user_location.get("timezone"),
|
||||
}
|
||||
|
||||
agent_tools.append(HostedWebSearchTool(additional_properties=additional_properties))
|
||||
else:
|
||||
agent_tools.append(tool_dict)
|
||||
return agent_tools
|
||||
|
||||
|
||||
def to_azure_ai_tools(
|
||||
tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
|
||||
) -> list[Tool | dict[str, Any]]:
|
||||
"""Converts Agent Framework tools into Azure AI compatible tools.
|
||||
|
||||
Args:
|
||||
tools: A sequence of Agent Framework tool objects or dictionaries
|
||||
defining the tools to be converted. Can be None.
|
||||
|
||||
Returns:
|
||||
list[Tool | dict[str, Any]]: A list of converted tools compatible with Azure AI.
|
||||
"""
|
||||
azure_tools: list[Tool | dict[str, Any]] = []
|
||||
if not tools:
|
||||
return azure_tools
|
||||
|
||||
for tool in tools:
|
||||
if isinstance(tool, ToolProtocol):
|
||||
match tool:
|
||||
case HostedMCPTool():
|
||||
azure_tools.append(_prepare_mcp_tool_for_azure_ai(tool))
|
||||
case HostedCodeInterpreterTool():
|
||||
file_ids: list[str] = []
|
||||
if tool.inputs:
|
||||
for tool_input in tool.inputs:
|
||||
if isinstance(tool_input, HostedFileContent):
|
||||
file_ids.append(tool_input.file_id)
|
||||
container = CodeInterpreterToolAuto(file_ids=file_ids if file_ids else None)
|
||||
ci_tool: CodeInterpreterTool = CodeInterpreterTool(container=container)
|
||||
azure_tools.append(ci_tool)
|
||||
case AIFunction():
|
||||
params = tool.parameters()
|
||||
params["additionalProperties"] = False
|
||||
azure_tools.append(
|
||||
FunctionTool(
|
||||
name=tool.name,
|
||||
parameters=params,
|
||||
strict=False,
|
||||
description=tool.description,
|
||||
)
|
||||
)
|
||||
case HostedFileSearchTool():
|
||||
if not tool.inputs:
|
||||
raise ValueError("HostedFileSearchTool requires inputs to be specified.")
|
||||
vector_store_ids: list[str] = [
|
||||
inp.vector_store_id for inp in tool.inputs if isinstance(inp, HostedVectorStoreContent)
|
||||
]
|
||||
if not vector_store_ids:
|
||||
raise ValueError(
|
||||
"HostedFileSearchTool requires inputs to be of type `HostedVectorStoreContent`."
|
||||
)
|
||||
fs_tool: ProjectsFileSearchTool = ProjectsFileSearchTool(vector_store_ids=vector_store_ids)
|
||||
if tool.max_results:
|
||||
fs_tool["max_num_results"] = tool.max_results
|
||||
azure_tools.append(fs_tool)
|
||||
case HostedWebSearchTool():
|
||||
ws_tool: WebSearchPreviewTool = WebSearchPreviewTool()
|
||||
if tool.additional_properties:
|
||||
location: dict[str, str] | None = (
|
||||
tool.additional_properties.get("user_location", None)
|
||||
if tool.additional_properties
|
||||
else None
|
||||
)
|
||||
if location:
|
||||
ws_tool.user_location = ApproximateLocation(
|
||||
city=location.get("city"),
|
||||
country=location.get("country"),
|
||||
region=location.get("region"),
|
||||
timezone=location.get("timezone"),
|
||||
)
|
||||
azure_tools.append(ws_tool)
|
||||
case _:
|
||||
logger.debug("Unsupported tool passed (type: %s)", type(tool))
|
||||
else:
|
||||
# Handle raw dictionary tools
|
||||
tool_dict = tool if isinstance(tool, dict) else dict(tool)
|
||||
azure_tools.append(tool_dict)
|
||||
|
||||
return azure_tools
|
||||
|
||||
|
||||
def _prepare_mcp_tool_for_azure_ai(tool: HostedMCPTool) -> MCPTool:
|
||||
"""Convert HostedMCPTool to Azure AI MCPTool format.
|
||||
|
||||
Args:
|
||||
tool: The HostedMCPTool to convert.
|
||||
|
||||
Returns:
|
||||
MCPTool: The converted Azure AI MCPTool.
|
||||
"""
|
||||
mcp: MCPTool = MCPTool(server_label=tool.name.replace(" ", "_"), server_url=str(tool.url))
|
||||
|
||||
if tool.description:
|
||||
mcp["server_description"] = tool.description
|
||||
|
||||
if tool.headers:
|
||||
mcp["headers"] = tool.headers
|
||||
|
||||
if tool.allowed_tools:
|
||||
mcp["allowed_tools"] = list(tool.allowed_tools)
|
||||
|
||||
if tool.approval_mode:
|
||||
match tool.approval_mode:
|
||||
case str():
|
||||
mcp["require_approval"] = "always" if tool.approval_mode == "always_require" else "never"
|
||||
case _:
|
||||
if always_require_approvals := tool.approval_mode.get("always_require_approval"):
|
||||
mcp["require_approval"] = {"always": {"tool_names": list(always_require_approvals)}}
|
||||
if never_require_approvals := tool.approval_mode.get("never_require_approval"):
|
||||
mcp["require_approval"] = {"never": {"tool_names": list(never_require_approvals)}}
|
||||
|
||||
return mcp
|
||||
|
||||
|
||||
def create_text_format_config(
|
||||
response_format: type[BaseModel] | Mapping[str, Any],
|
||||
) -> (
|
||||
ResponseTextFormatConfigurationJsonSchema
|
||||
| ResponseTextFormatConfigurationJsonObject
|
||||
| ResponseTextFormatConfigurationText
|
||||
):
|
||||
"""Convert response_format into Azure text format configuration."""
|
||||
if isinstance(response_format, type) and issubclass(response_format, BaseModel):
|
||||
schema = response_format.model_json_schema()
|
||||
# Ensure additionalProperties is explicitly false to satisfy Azure validation
|
||||
if isinstance(schema, dict):
|
||||
schema.setdefault("additionalProperties", False)
|
||||
return ResponseTextFormatConfigurationJsonSchema(
|
||||
name=response_format.__name__,
|
||||
schema=schema,
|
||||
strict=True,
|
||||
)
|
||||
|
||||
if isinstance(response_format, Mapping):
|
||||
format_config = _convert_response_format(response_format)
|
||||
format_type = format_config.get("type")
|
||||
if format_type == "json_schema":
|
||||
# Ensure schema includes additionalProperties=False to satisfy Azure validation
|
||||
schema = dict(format_config.get("schema", {})) # type: ignore[assignment]
|
||||
schema.setdefault("additionalProperties", False)
|
||||
config_kwargs: dict[str, Any] = {
|
||||
"name": format_config.get("name") or "response",
|
||||
"schema": schema,
|
||||
}
|
||||
if "strict" in format_config:
|
||||
config_kwargs["strict"] = format_config["strict"]
|
||||
if "description" in format_config:
|
||||
config_kwargs["description"] = format_config["description"]
|
||||
return ResponseTextFormatConfigurationJsonSchema(**config_kwargs)
|
||||
if format_type == "json_object":
|
||||
return ResponseTextFormatConfigurationJsonObject()
|
||||
if format_type == "text":
|
||||
return ResponseTextFormatConfigurationText()
|
||||
|
||||
raise ServiceInvalidRequestError("response_format must be a Pydantic model or mapping.")
|
||||
|
||||
|
||||
def _convert_response_format(response_format: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Convert Chat style response_format into Responses text format config."""
|
||||
if "format" in response_format and isinstance(response_format["format"], Mapping):
|
||||
return dict(cast("Mapping[str, Any]", response_format["format"]))
|
||||
|
||||
format_type = response_format.get("type")
|
||||
if format_type == "json_schema":
|
||||
schema_section = response_format.get("json_schema", response_format)
|
||||
if not isinstance(schema_section, Mapping):
|
||||
raise ServiceInvalidRequestError("json_schema response_format must be a mapping.")
|
||||
schema_section_typed = cast("Mapping[str, Any]", schema_section)
|
||||
schema: Any = schema_section_typed.get("schema")
|
||||
if schema is None:
|
||||
raise ServiceInvalidRequestError("json_schema response_format requires a schema.")
|
||||
name: str = str(
|
||||
schema_section_typed.get("name")
|
||||
or schema_section_typed.get("title")
|
||||
or (cast("Mapping[str, Any]", schema).get("title") if isinstance(schema, Mapping) else None)
|
||||
or "response"
|
||||
)
|
||||
format_config: dict[str, Any] = {
|
||||
"type": "json_schema",
|
||||
"name": name,
|
||||
"schema": schema,
|
||||
}
|
||||
if "strict" in schema_section:
|
||||
format_config["strict"] = schema_section["strict"]
|
||||
if "description" in schema_section and schema_section["description"] is not None:
|
||||
format_config["description"] = schema_section["description"]
|
||||
return format_config
|
||||
|
||||
if format_type in {"json_object", "text"}:
|
||||
return {"type": format_type}
|
||||
|
||||
raise ServiceInvalidRequestError("Unsupported response_format provided for Azure AI client.")
|
||||
|
||||
Reference in New Issue
Block a user