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:
committed by
GitHub
Unverified
parent
3df916064c
commit
cd77193742
@@ -6,8 +6,9 @@ This folder contains examples demonstrating different ways to create and use age
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIClient`. Demonstrates both streaming and non-streaming responses with function tools. Shows automatic agent creation and basic weather functionality. |
|
||||
| [`azure_ai_use_latest_version.py`](azure_ai_use_latest_version.py) | Demonstrates how to reuse the latest version of an existing agent instead of creating a new agent version on each instantiation using the `use_latest_version=True` parameter. |
|
||||
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIProjectAgentProvider`. Demonstrates both streaming and non-streaming responses with function tools. Shows automatic agent creation and basic weather functionality. |
|
||||
| [`azure_ai_provider_methods.py`](azure_ai_provider_methods.py) | Comprehensive guide to `AzureAIProjectAgentProvider` methods: `create_agent()` for creating new agents, `get_agent()` for retrieving existing agents (by name, reference, or details), and `as_agent()` for wrapping SDK objects without HTTP calls. |
|
||||
| [`azure_ai_use_latest_version.py`](azure_ai_use_latest_version.py) | Demonstrates how to reuse the latest version of an existing agent instead of creating a new agent version on each instantiation by using `provider.get_agent()` to retrieve the latest version. |
|
||||
| [`azure_ai_with_agent_to_agent.py`](azure_ai_with_agent_to_agent.py) | Shows how to use Agent-to-Agent (A2A) capabilities with Azure AI agents to enable communication with other agents using the A2A protocol. Requires an A2A connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_azure_ai_search.py`](azure_ai_with_azure_ai_search.py) | Shows how to use Azure AI Search with Azure AI agents to search through indexed data and answer user questions with proper citations. Requires an Azure AI Search connection and index configured in your Azure AI project. |
|
||||
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to search the web for current information and provide grounded responses with citations. Requires a Bing connection configured in your Azure AI project. |
|
||||
@@ -15,6 +16,7 @@ This folder contains examples demonstrating different ways to create and use age
|
||||
| [`azure_ai_with_browser_automation.py`](azure_ai_with_browser_automation.py) | Shows how to use Browser Automation with Azure AI agents to perform automated web browsing tasks and provide responses based on web interactions. Requires a Browser Automation connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use the `HostedCodeInterpreterTool` with Azure AI agents to write and execute Python code for mathematical problem solving and data analysis. |
|
||||
| [`azure_ai_with_code_interpreter_file_generation.py`](azure_ai_with_code_interpreter_file_generation.py) | Shows how to retrieve file IDs from code interpreter generated files using both streaming and non-streaming approaches. |
|
||||
| [`azure_ai_with_code_interpreter_file_download.py`](azure_ai_with_code_interpreter_file_download.py) | Shows how to download files generated by code interpreter using the OpenAI containers API. |
|
||||
| [`azure_ai_with_existing_agent.py`](azure_ai_with_existing_agent.py) | Shows how to work with a pre-existing agent by providing the agent name and version to the Azure AI client. Demonstrates agent reuse patterns for production scenarios. |
|
||||
| [`azure_ai_with_existing_conversation.py`](azure_ai_with_existing_conversation.py) | Demonstrates how to use an existing conversation created on the service side with Azure AI agents. Shows two approaches: specifying conversation ID at the client level and using AgentThread with an existing conversation ID. |
|
||||
| [`azure_ai_with_application_endpoint.py`](azure_ai_with_application_endpoint.py) | Demonstrates calling the Azure AI application-scoped endpoint. |
|
||||
|
||||
@@ -4,14 +4,14 @@ import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import Field
|
||||
|
||||
"""
|
||||
Azure AI Agent Basic Example
|
||||
|
||||
This sample demonstrates basic usage of AzureAIClient.
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider.
|
||||
Shows both streaming and non-streaming responses with function tools.
|
||||
"""
|
||||
|
||||
@@ -28,17 +28,18 @@ async def non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
@@ -49,17 +50,18 @@ async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query}")
|
||||
print("Agent: ", end="", flush=True)
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import AgentReference, PromptAgentDefinition
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import Field
|
||||
|
||||
"""
|
||||
Azure AI Project Agent Provider Methods Example
|
||||
|
||||
This sample demonstrates the three main methods of AzureAIProjectAgentProvider:
|
||||
1. create_agent() - Create a new agent on the Azure AI service
|
||||
2. get_agent() - Retrieve an existing agent from the service
|
||||
3. as_agent() - Wrap an SDK agent version object without making HTTP calls
|
||||
|
||||
It also shows how to use a single provider instance to spawn multiple agents
|
||||
with different configurations, which is efficient for multi-agent scenarios.
|
||||
|
||||
Each method returns a ChatAgent that can be used for conversations.
|
||||
"""
|
||||
|
||||
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
|
||||
|
||||
|
||||
async def create_agent_example() -> None:
|
||||
"""Example of using provider.create_agent() to create a new agent.
|
||||
|
||||
This method creates a new agent version on the Azure AI service and returns
|
||||
a ChatAgent. Use this when you want to create a fresh agent with
|
||||
specific configuration.
|
||||
"""
|
||||
print("=== provider.create_agent() Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a new agent with custom configuration
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
instructions="You are a helpful weather assistant. Always be concise.",
|
||||
description="An agent that provides weather information.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
print(f"Created agent: {agent.name}")
|
||||
print(f"Agent ID: {agent.id}")
|
||||
|
||||
query = "What's the weather in Paris?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
async def get_agent_by_name_example() -> None:
|
||||
"""Example of using provider.get_agent(name=...) to retrieve an agent by name.
|
||||
|
||||
This method fetches the latest version of an existing agent from the service.
|
||||
Use this when you know the agent name and want to use the most recent version.
|
||||
"""
|
||||
print("=== provider.get_agent(name=...) Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# First, create an agent using the SDK directly
|
||||
created_agent = await project_client.agents.create_version(
|
||||
agent_name="TestAgentByName",
|
||||
description="Test agent for get_agent by name example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. End each response with '- Your Assistant'.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Get the agent using the provider by name (fetches latest version)
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.get_agent(name=created_agent.name)
|
||||
|
||||
print(f"Retrieved agent: {agent.name}")
|
||||
|
||||
query = "Hello!"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=created_agent.name, agent_version=created_agent.version
|
||||
)
|
||||
|
||||
|
||||
async def get_agent_by_reference_example() -> None:
|
||||
"""Example of using provider.get_agent(reference=...) to retrieve a specific agent version.
|
||||
|
||||
This method fetches a specific version of an agent using an AgentReference.
|
||||
Use this when you need to use a particular version of an agent.
|
||||
"""
|
||||
print("=== provider.get_agent(reference=...) Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# First, create an agent using the SDK directly
|
||||
created_agent = await project_client.agents.create_version(
|
||||
agent_name="TestAgentByReference",
|
||||
description="Test agent for get_agent by reference example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. Always respond in uppercase.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Get the agent using an AgentReference with specific version
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
reference = AgentReference(name=created_agent.name, version=created_agent.version)
|
||||
agent = await provider.get_agent(reference=reference)
|
||||
|
||||
print(f"Retrieved agent: {agent.name} (version via reference)")
|
||||
|
||||
query = "Say hello"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=created_agent.name, agent_version=created_agent.version
|
||||
)
|
||||
|
||||
|
||||
async def get_agent_by_details_example() -> None:
|
||||
"""Example of using provider.get_agent(details=...) with pre-fetched AgentDetails.
|
||||
|
||||
This method uses pre-fetched AgentDetails to get the latest version.
|
||||
Use this when you already have AgentDetails from a previous API call.
|
||||
"""
|
||||
print("=== provider.get_agent(details=...) Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# First, create an agent using the SDK directly
|
||||
created_agent = await project_client.agents.create_version(
|
||||
agent_name="TestAgentByDetails",
|
||||
description="Test agent for get_agent by details example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. Always include an emoji in your response.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Fetch AgentDetails separately (simulating a previous API call)
|
||||
agent_details = await project_client.agents.get(agent_name=created_agent.name)
|
||||
|
||||
# Get the agent using the pre-fetched details (sync - no HTTP call)
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = provider.as_agent(agent_details.versions.latest)
|
||||
|
||||
print(f"Retrieved agent: {agent.name} (from pre-fetched details)")
|
||||
|
||||
query = "How are you today?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=created_agent.name, agent_version=created_agent.version
|
||||
)
|
||||
|
||||
|
||||
async def multiple_agents_example() -> None:
|
||||
"""Example of using a single provider to spawn multiple agents.
|
||||
|
||||
A single provider instance can create multiple agents with different
|
||||
configurations.
|
||||
"""
|
||||
print("=== Multiple Agents from Single Provider Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create multiple specialized agents from the same provider
|
||||
weather_agent = await provider.create_agent(
|
||||
name="WeatherExpert",
|
||||
instructions="You are a weather expert. Provide brief weather information.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
translator_agent = await provider.create_agent(
|
||||
name="Translator",
|
||||
instructions="You are a translator. Translate any text to French. Only output the translation.",
|
||||
)
|
||||
|
||||
poet_agent = await provider.create_agent(
|
||||
name="Poet",
|
||||
instructions="You are a poet. Respond to everything with a short haiku.",
|
||||
)
|
||||
|
||||
print(f"Created agents: {weather_agent.name}, {translator_agent.name}, {poet_agent.name}\n")
|
||||
|
||||
# Use each agent for its specialty
|
||||
weather_query = "What's the weather in London?"
|
||||
print(f"User to WeatherExpert: {weather_query}")
|
||||
weather_result = await weather_agent.run(weather_query)
|
||||
print(f"WeatherExpert: {weather_result}\n")
|
||||
|
||||
translate_query = "Hello, how are you today?"
|
||||
print(f"User to Translator: {translate_query}")
|
||||
translate_result = await translator_agent.run(translate_query)
|
||||
print(f"Translator: {translate_result}\n")
|
||||
|
||||
poet_query = "Tell me about the morning sun"
|
||||
print(f"User to Poet: {poet_query}")
|
||||
poet_result = await poet_agent.run(poet_query)
|
||||
print(f"Poet: {poet_result}\n")
|
||||
|
||||
|
||||
async def as_agent_example() -> None:
|
||||
"""Example of using provider.as_agent() to wrap an SDK object without HTTP calls.
|
||||
|
||||
This method wraps an existing AgentVersionDetails into a ChatAgent without
|
||||
making additional HTTP calls. Use this when you already have the full
|
||||
AgentVersionDetails from a previous SDK operation.
|
||||
"""
|
||||
print("=== provider.as_agent() Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# Create an agent using the SDK directly - this returns AgentVersionDetails
|
||||
agent_version_details = await project_client.agents.create_version(
|
||||
agent_name="TestAgentAsAgent",
|
||||
description="Test agent for as_agent example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. Keep responses under 20 words.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Wrap the SDK object directly without any HTTP calls
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = provider.as_agent(agent_version_details)
|
||||
|
||||
print(f"Wrapped agent: {agent.name} (no HTTP call needed)")
|
||||
print(f"Agent version: {agent_version_details.version}")
|
||||
|
||||
query = "What can you do?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=agent_version_details.name, agent_version=agent_version_details.version
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Azure AI Project Agent Provider Methods Example ===\n")
|
||||
|
||||
await create_agent_example()
|
||||
await get_agent_by_name_example()
|
||||
await get_agent_by_reference_example()
|
||||
await get_agent_by_details_example()
|
||||
await as_agent_example()
|
||||
await multiple_agents_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import Field
|
||||
|
||||
@@ -13,7 +13,7 @@ Azure AI Agent Latest Version Example
|
||||
|
||||
This sample demonstrates how to reuse the latest version of an existing agent
|
||||
instead of creating a new agent version on each instantiation. The first call creates a new agent,
|
||||
while subsequent calls with `use_latest_version=True` reuse the latest agent version.
|
||||
while subsequent calls with `get_agent()` reuse the latest agent version.
|
||||
"""
|
||||
|
||||
|
||||
@@ -28,39 +28,36 @@ def get_weather(
|
||||
async def main() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with AzureCliCredential() as credential:
|
||||
async with (
|
||||
AzureAIClient(
|
||||
credential=credential,
|
||||
).create_agent(
|
||||
name="MyWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
# First query will create a new agent
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# First call creates a new agent
|
||||
agent = await provider.create_agent(
|
||||
name="MyWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Create a new agent instance
|
||||
async with (
|
||||
AzureAIClient(
|
||||
credential=credential,
|
||||
# This parameter will allow to re-use latest agent version
|
||||
# instead of creating a new one
|
||||
use_latest_version=True,
|
||||
).create_agent(
|
||||
name="MyWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
query = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
# Second call retrieves the existing agent (latest version) instead of creating a new one
|
||||
# This is useful when you want to reuse an agent that was created earlier
|
||||
agent2 = await provider.get_agent(
|
||||
name="MyWeatherAgent",
|
||||
tools=get_weather, # Tools must be provided for function tools
|
||||
)
|
||||
|
||||
query = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query}")
|
||||
result = await agent2.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
print(f"First agent ID with version: {agent.id}")
|
||||
print(f"Second agent ID with version: {agent2.id}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -2,36 +2,47 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Agent-to-Agent (A2A) Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with Agent-to-Agent (A2A) capabilities
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Agent-to-Agent (A2A) capabilities
|
||||
to enable communication with other agents using the A2A protocol.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have an A2A connection configured in your Azure AI project
|
||||
and set A2A_PROJECT_CONNECTION_ID environment variable.
|
||||
and set A2A_PROJECT_CONNECTION_ID environment variable.
|
||||
3. (Optional) A2A_ENDPOINT - If the connection is missing target (e.g., "Custom keys" type),
|
||||
set the A2A endpoint URL directly.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Configure A2A tool with connection ID
|
||||
a2a_tool = {
|
||||
"type": "a2a_preview",
|
||||
"project_connection_id": os.environ["A2A_PROJECT_CONNECTION_ID"],
|
||||
}
|
||||
|
||||
# If the connection is missing a target, we need to set the A2A endpoint URL
|
||||
if os.environ.get("A2A_ENDPOINT"):
|
||||
a2a_tool["base_url"] = os.environ["A2A_ENDPOINT"]
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyA2AAgent",
|
||||
instructions="""You are a helpful assistant that can communicate with other agents.
|
||||
Use the A2A tool when you need to interact with other agents to complete tasks
|
||||
or gather information from specialized agents.""",
|
||||
tools={
|
||||
"type": "a2a_preview",
|
||||
"project_connection_id": os.environ["A2A_PROJECT_CONNECTION_ID"],
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
tools=a2a_tool,
|
||||
)
|
||||
|
||||
query = "What can the secondary agent do?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Azure AI Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with Azure AI Search
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Azure AI Search
|
||||
to search through indexed data and answer user questions about it.
|
||||
|
||||
Prerequisites:
|
||||
@@ -21,7 +21,9 @@ Prerequisites:
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MySearchAgent",
|
||||
instructions="""You are a helpful assistant. You must always provide citations for
|
||||
answers using the tool and render them as: `[message_idx:search_idx†source]`.""",
|
||||
@@ -38,8 +40,8 @@ async def main() -> None:
|
||||
]
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "Tell me about insurance options"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Bing Custom Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with Bing Custom Search
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Bing Custom Search
|
||||
to search custom search instances and provide responses with relevant results.
|
||||
|
||||
Prerequisites:
|
||||
@@ -21,7 +21,9 @@ Prerequisites:
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyCustomSearchAgent",
|
||||
instructions="""You are a helpful agent that can use Bing Custom Search tools to assist users.
|
||||
Use the available Bing Custom Search tools to answer questions and perform tasks.""",
|
||||
@@ -36,8 +38,8 @@ async def main() -> None:
|
||||
]
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "Tell me more about foundry agent service"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Bing Grounding Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with Bing Grounding
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Bing Grounding
|
||||
to search the web for current information and provide grounded responses.
|
||||
|
||||
Prerequisites:
|
||||
@@ -27,7 +27,9 @@ To get your Bing connection ID:
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyBingGroundingAgent",
|
||||
instructions="""You are a helpful assistant that can search the web for current information.
|
||||
Use the Bing search tool to find up-to-date information and provide accurate, well-sourced answers.
|
||||
@@ -42,8 +44,8 @@ async def main() -> None:
|
||||
]
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What is today's date and weather in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Browser Automation Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with Browser Automation
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Browser Automation
|
||||
to perform automated web browsing tasks and provide responses based on web interactions.
|
||||
|
||||
Prerequisites:
|
||||
@@ -21,7 +21,9 @@ Prerequisites:
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyBrowserAutomationAgent",
|
||||
instructions="""You are an Agent helping with browser automation tasks.
|
||||
You can answer questions, provide information, and assist with various tasks
|
||||
@@ -34,8 +36,8 @@ async def main() -> None:
|
||||
}
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = """Your goal is to report the percent of Microsoft year-to-date stock price change.
|
||||
To do that, go to the website finance.yahoo.com.
|
||||
At the top of the page, you will find a search bar.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import ChatResponse, HostedCodeInterpreterTool
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from openai.types.responses.response import Response as OpenAIResponse
|
||||
from openai.types.responses.response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall
|
||||
@@ -11,22 +11,24 @@ from openai.types.responses.response_code_interpreter_tool_call import ResponseC
|
||||
"""
|
||||
Azure AI Agent Code Interpreter Example
|
||||
|
||||
This sample demonstrates using HostedCodeInterpreterTool with AzureAIClient
|
||||
This sample demonstrates using HostedCodeInterpreterTool with AzureAIProjectAgentProvider
|
||||
for Python code execution and mathematical problem solving.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing how to use the HostedCodeInterpreterTool with AzureAIClient."""
|
||||
"""Example showing how to use the HostedCodeInterpreterTool with AzureAIProjectAgentProvider."""
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyCodeInterpreterAgent",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
|
||||
tools=HostedCodeInterpreterTool(),
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "Use code to get the factorial of 100?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import (
|
||||
AgentResponseUpdate,
|
||||
ChatAgent,
|
||||
CitationAnnotation,
|
||||
HostedCodeInterpreterTool,
|
||||
HostedFileContent,
|
||||
TextContent,
|
||||
)
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI V2 Code Interpreter File Download Sample
|
||||
|
||||
This sample demonstrates how the AzureAIProjectAgentProvider handles file annotations
|
||||
when code interpreter generates text files. It shows:
|
||||
1. How to extract file IDs and container IDs from annotations
|
||||
2. How to download container files using the OpenAI containers API
|
||||
3. How to save downloaded files locally
|
||||
|
||||
Note: Code interpreter generates files in containers, which require both
|
||||
file_id and container_id to download via client.containers.files.content.retrieve().
|
||||
"""
|
||||
|
||||
QUERY = (
|
||||
"Write a simple Python script that creates a text file called 'sample.txt' containing "
|
||||
"'Hello from the code interpreter!' and save it to disk."
|
||||
)
|
||||
|
||||
|
||||
async def download_container_files(
|
||||
file_contents: list[CitationAnnotation | HostedFileContent], agent: ChatAgent
|
||||
) -> list[Path]:
|
||||
"""Download container files using the OpenAI containers API.
|
||||
|
||||
Code interpreter generates files in containers, which require both file_id
|
||||
and container_id to download. The container_id is stored in additional_properties.
|
||||
|
||||
This function works for both streaming (HostedFileContent) and non-streaming
|
||||
(CitationAnnotation) responses.
|
||||
|
||||
Args:
|
||||
file_contents: List of CitationAnnotation or HostedFileContent objects
|
||||
containing file_id and container_id.
|
||||
agent: The ChatAgent instance with access to the AzureAIClient.
|
||||
|
||||
Returns:
|
||||
List of Path objects for successfully downloaded files.
|
||||
"""
|
||||
if not file_contents:
|
||||
return []
|
||||
|
||||
# Create output directory in system temp folder
|
||||
temp_dir = Path(tempfile.gettempdir())
|
||||
output_dir = temp_dir / "agent_framework_downloads"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
|
||||
print(f"\nDownloading {len(file_contents)} container file(s) to {output_dir.absolute()}...")
|
||||
|
||||
# Access the OpenAI client from AzureAIClient
|
||||
openai_client = agent.chat_client.client
|
||||
|
||||
downloaded_files: list[Path] = []
|
||||
|
||||
for content in file_contents:
|
||||
file_id = content.file_id
|
||||
|
||||
# Extract container_id from additional_properties
|
||||
if not content.additional_properties or "container_id" not in content.additional_properties:
|
||||
print(f" File {file_id}: ✗ Missing container_id")
|
||||
continue
|
||||
|
||||
container_id = content.additional_properties["container_id"]
|
||||
|
||||
# Extract filename based on content type
|
||||
if isinstance(content, CitationAnnotation):
|
||||
filename = content.url or f"{file_id}.txt"
|
||||
# Extract filename from sandbox URL if present (e.g., sandbox:/mnt/data/sample.txt)
|
||||
if filename.startswith("sandbox:"):
|
||||
filename = filename.split("/")[-1]
|
||||
else: # HostedFileContent
|
||||
filename = content.additional_properties.get("filename") or f"{file_id}.txt"
|
||||
|
||||
output_path = output_dir / filename
|
||||
|
||||
try:
|
||||
# Download using containers API
|
||||
print(f" Downloading {filename}...", end="", flush=True)
|
||||
file_content = await openai_client.containers.files.content.retrieve(
|
||||
file_id=file_id,
|
||||
container_id=container_id,
|
||||
)
|
||||
|
||||
# file_content is HttpxBinaryResponseContent, read it
|
||||
content_bytes = file_content.read()
|
||||
|
||||
# Save to disk
|
||||
output_path.write_bytes(content_bytes)
|
||||
file_size = output_path.stat().st_size
|
||||
print(f"({file_size} bytes)")
|
||||
|
||||
downloaded_files.append(output_path)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Failed: {e}")
|
||||
|
||||
return downloaded_files
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
"""Example of downloading files from non-streaming response using CitationAnnotation."""
|
||||
print("=== Non-Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgent",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=HostedCodeInterpreterTool(),
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
|
||||
result = await agent.run(QUERY)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
# Check for annotations in the response
|
||||
annotations_found: list[CitationAnnotation] = []
|
||||
# AgentResponse has messages property, which contains ChatMessage objects
|
||||
for message in result.messages:
|
||||
for content in message.contents:
|
||||
if isinstance(content, TextContent) and content.annotations:
|
||||
for annotation in content.annotations:
|
||||
if isinstance(annotation, CitationAnnotation) and annotation.file_id:
|
||||
annotations_found.append(annotation)
|
||||
print(f"Found file annotation: file_id={annotation.file_id}")
|
||||
if annotation.additional_properties and "container_id" in annotation.additional_properties:
|
||||
print(f" container_id={annotation.additional_properties['container_id']}")
|
||||
|
||||
if annotations_found:
|
||||
print(f"SUCCESS: Found {len(annotations_found)} file annotation(s)")
|
||||
|
||||
# Download the container files
|
||||
downloaded_paths = await download_container_files(annotations_found, agent)
|
||||
|
||||
if downloaded_paths:
|
||||
print("\nDownloaded files available at:")
|
||||
for path in downloaded_paths:
|
||||
print(f" - {path.absolute()}")
|
||||
else:
|
||||
print("WARNING: No file annotations found in non-streaming response")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of downloading files from streaming response using HostedFileContent."""
|
||||
print("\n=== Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgentStreaming",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=HostedCodeInterpreterTool(),
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
file_contents_found: list[HostedFileContent] = []
|
||||
text_chunks: list[str] = []
|
||||
|
||||
async for update in agent.run_stream(QUERY):
|
||||
if isinstance(update, AgentResponseUpdate):
|
||||
for content in update.contents:
|
||||
if isinstance(content, TextContent):
|
||||
if content.text:
|
||||
text_chunks.append(content.text)
|
||||
if content.annotations:
|
||||
for annotation in content.annotations:
|
||||
if isinstance(annotation, CitationAnnotation) and annotation.file_id:
|
||||
print(f"Found streaming CitationAnnotation: file_id={annotation.file_id}")
|
||||
elif isinstance(content, HostedFileContent):
|
||||
file_contents_found.append(content)
|
||||
print(f"Found streaming HostedFileContent: file_id={content.file_id}")
|
||||
if content.additional_properties and "container_id" in content.additional_properties:
|
||||
print(f" container_id={content.additional_properties['container_id']}")
|
||||
|
||||
print(f"\nAgent response: {''.join(text_chunks)[:200]}...")
|
||||
|
||||
if file_contents_found:
|
||||
print(f"SUCCESS: Found {len(file_contents_found)} file reference(s) in streaming")
|
||||
|
||||
# Download the container files
|
||||
downloaded_paths = await download_container_files(file_contents_found, agent)
|
||||
|
||||
if downloaded_paths:
|
||||
print("\n✓ Downloaded files available at:")
|
||||
for path in downloaded_paths:
|
||||
print(f" - {path.absolute()}")
|
||||
else:
|
||||
print("WARNING: No file annotations found in streaming response")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("AzureAIClient Code Interpreter File Download Sample\n")
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+24
-20
@@ -3,19 +3,19 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import (
|
||||
AgentResponseUpdate,
|
||||
CitationAnnotation,
|
||||
HostedCodeInterpreterTool,
|
||||
HostedFileContent,
|
||||
TextContent,
|
||||
)
|
||||
from agent_framework._agents import AgentRunResponseUpdate
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI V2 Code Interpreter File Generation Sample
|
||||
|
||||
This sample demonstrates how the V2 AzureAIClient handles file annotations
|
||||
This sample demonstrates how the AzureAIProjectAgentProvider handles file annotations
|
||||
when code interpreter generates text files. It shows both non-streaming
|
||||
and streaming approaches to verify file ID extraction.
|
||||
"""
|
||||
@@ -26,18 +26,20 @@ QUERY = (
|
||||
)
|
||||
|
||||
|
||||
async def test_non_streaming() -> None:
|
||||
"""Test non-streaming response - should have annotations on TextContent."""
|
||||
print("=== Testing Non-Streaming Response ===")
|
||||
async def non_streaming_example() -> None:
|
||||
"""Example of extracting file annotations from non-streaming response."""
|
||||
print("=== Non-Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgent",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=HostedCodeInterpreterTool(),
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
|
||||
result = await agent.run(QUERY)
|
||||
@@ -45,7 +47,7 @@ async def test_non_streaming() -> None:
|
||||
|
||||
# Check for annotations in the response
|
||||
annotations_found: list[str] = []
|
||||
# AgentRunResponse has messages property, which contains ChatMessage objects
|
||||
# AgentResponse has messages property, which contains ChatMessage objects
|
||||
for message in result.messages:
|
||||
for content in message.contents:
|
||||
if isinstance(content, TextContent) and content.annotations:
|
||||
@@ -60,25 +62,27 @@ async def test_non_streaming() -> None:
|
||||
print("WARNING: No file annotations found in non-streaming response")
|
||||
|
||||
|
||||
async def test_streaming() -> None:
|
||||
"""Test streaming response - check if file content is captured via HostedFileContent."""
|
||||
print("\n=== Testing Streaming Response ===")
|
||||
async def streaming_example() -> None:
|
||||
"""Example of extracting file annotations from streaming response."""
|
||||
print("\n=== Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgentStreaming",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=HostedCodeInterpreterTool(),
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
annotations_found: list[str] = []
|
||||
text_chunks: list[str] = []
|
||||
file_ids_found: list[str] = []
|
||||
|
||||
async for update in agent.run_stream(QUERY):
|
||||
if isinstance(update, AgentRunResponseUpdate):
|
||||
if isinstance(update, AgentResponseUpdate):
|
||||
for content in update.contents:
|
||||
if isinstance(content, TextContent):
|
||||
if content.text:
|
||||
@@ -102,9 +106,9 @@ async def test_streaming() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("AzureAIClient Code Interpreter File Generation Test\n")
|
||||
await test_non_streaming()
|
||||
await test_streaming()
|
||||
print("AzureAIClient Code Interpreter File Generation Sample\n")
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import ChatAgent
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import PromptAgentDefinition
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
@@ -12,19 +11,23 @@ from azure.identity.aio import AzureCliCredential
|
||||
"""
|
||||
Azure AI Agent with Existing Agent Example
|
||||
|
||||
This sample demonstrates working with pre-existing Azure AI Agents by providing
|
||||
agent name and version, showing agent reuse patterns for production scenarios.
|
||||
This sample demonstrates working with pre-existing Azure AI Agents by using provider.get_agent() method,
|
||||
showing agent reuse patterns for production scenarios.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async def using_provider_get_agent() -> None:
|
||||
print("=== Get existing Azure AI agent with provider.get_agent() ===")
|
||||
|
||||
# Create the client
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# Create remote agent using SDK directly
|
||||
azure_ai_agent = await project_client.agents.create_version(
|
||||
agent_name="MyNewTestAgent",
|
||||
description="Agent for testing purposes.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
# Setting specific requirements to verify that this agent is used.
|
||||
@@ -32,27 +35,22 @@ async def main() -> None:
|
||||
),
|
||||
)
|
||||
|
||||
chat_client = AzureAIClient(
|
||||
project_client=project_client,
|
||||
agent_name=azure_ai_agent.name,
|
||||
# Property agent_version is required for existing agents.
|
||||
# If this property is not configured, the client will try to create a new agent using
|
||||
# provided agent_name.
|
||||
# It's also possible to leave agent_version empty but set use_latest_version=True.
|
||||
# This will pull latest available agent version and use that version for operations.
|
||||
agent_version=azure_ai_agent.version,
|
||||
)
|
||||
|
||||
try:
|
||||
async with ChatAgent(
|
||||
chat_client=chat_client,
|
||||
) as agent:
|
||||
query = "How are you?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
# Response that indicates that previously created agent was used:
|
||||
# "I'm here and ready to help you! How can I assist you today? [END]"
|
||||
print(f"Agent: {result}\n")
|
||||
# Get newly created agent as ChatAgent by using provider.get_agent()
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.get_agent(name=azure_ai_agent.name)
|
||||
|
||||
# Verify agent properties
|
||||
print(f"Agent ID: {agent.id}")
|
||||
print(f"Agent name: {agent.name}")
|
||||
print(f"Agent description: {agent.description}")
|
||||
|
||||
query = "How are you?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
# Response that indicates that previously created agent was used:
|
||||
# "I'm here and ready to help you! How can I assist you today? [END]"
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent manually
|
||||
await project_client.agents.delete_version(
|
||||
@@ -60,5 +58,9 @@ async def main() -> None:
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
await using_provider_get_agent()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
+24
-23
@@ -4,7 +4,7 @@ import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import Field
|
||||
@@ -12,7 +12,7 @@ from pydantic import Field
|
||||
"""
|
||||
Azure AI Agent Existing Conversation Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with existing conversation created on service side.
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with existing conversation created on service side.
|
||||
"""
|
||||
|
||||
|
||||
@@ -24,9 +24,9 @@ def get_weather(
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def example_with_client() -> None:
|
||||
"""Example shows how to specify existing conversation ID when initializing Azure AI Client."""
|
||||
print("=== Azure AI Agent With Existing Conversation and Client ===")
|
||||
async def example_with_conversation_id() -> None:
|
||||
"""Example shows how to use existing conversation ID with the provider."""
|
||||
print("=== Azure AI Agent With Existing Conversation ===")
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
@@ -37,24 +37,23 @@ async def example_with_client() -> None:
|
||||
conversation_id = conversation.id
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
|
||||
async with AzureAIClient(
|
||||
project_client=project_client,
|
||||
# Specify conversation ID on client level
|
||||
conversation_id=conversation_id,
|
||||
).create_agent(
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.create_agent(
|
||||
name="BasicAgent",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=get_weather,
|
||||
) as agent:
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}\n")
|
||||
)
|
||||
|
||||
query = "What was my last question?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}\n")
|
||||
# Pass conversation_id at run level
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, conversation_id=conversation_id)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
query = "What was my last question?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, conversation_id=conversation_id)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
|
||||
async def example_with_thread() -> None:
|
||||
@@ -63,12 +62,14 @@ async def example_with_thread() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
AzureAIClient(project_client=project_client).create_agent(
|
||||
):
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.create_agent(
|
||||
name="BasicAgent",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
# Create a conversation using OpenAI client
|
||||
openai_client = project_client.get_openai_client()
|
||||
conversation = await openai_client.conversations.create()
|
||||
@@ -90,7 +91,7 @@ async def example_with_thread() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
await example_with_client()
|
||||
await example_with_conversation_id()
|
||||
await example_with_thread()
|
||||
|
||||
|
||||
|
||||
@@ -5,8 +5,7 @@ import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import ChatAgent
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import Field
|
||||
|
||||
@@ -27,22 +26,22 @@ def get_weather(
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
ChatAgent(
|
||||
chat_client=AzureAIClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
model_deployment_name=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
agent_name="WeatherAgent",
|
||||
),
|
||||
AzureAIProjectAgentProvider(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What's the weather like in New York?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -4,8 +4,8 @@ import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import ChatAgent, HostedFileSearchTool, HostedVectorStoreContent
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.agents.aio import AgentsClient
|
||||
from azure.ai.agents.models import FileInfo, VectorStore
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
@@ -32,7 +32,7 @@ async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
|
||||
AzureAIClient(credential=credential) as client,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
try:
|
||||
# 1. Upload file and create vector store
|
||||
@@ -48,22 +48,21 @@ async def main() -> None:
|
||||
# 2. Create file search tool with uploaded resources
|
||||
file_search_tool = HostedFileSearchTool(inputs=[HostedVectorStoreContent(vector_store_id=vector_store.id)])
|
||||
|
||||
# 3. Create an agent with file search capabilities
|
||||
# The tool_resources are automatically extracted from HostedFileSearchTool
|
||||
async with ChatAgent(
|
||||
chat_client=client,
|
||||
# 3. Create an agent with file search capabilities using the provider
|
||||
agent = await provider.create_agent(
|
||||
name="EmployeeSearchAgent",
|
||||
instructions=(
|
||||
"You are a helpful assistant that can search through uploaded employee files "
|
||||
"to answer questions about employees."
|
||||
),
|
||||
tools=file_search_tool,
|
||||
) as agent:
|
||||
# 4. Simulate conversation with the agent
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
response = await agent.run(user_input)
|
||||
print(f"# Agent: {response.text}")
|
||||
)
|
||||
|
||||
# 4. Simulate conversation with the agent
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
response = await agent.run(user_input)
|
||||
print(f"# Agent: {response.text}")
|
||||
finally:
|
||||
# 5. Cleanup: Delete the vector store and file in case of earlier failure to prevent orphaned resources.
|
||||
if vector_store:
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentProtocol, AgentRunResponse, AgentThread, ChatMessage, HostedMCPTool
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework import AgentProtocol, AgentResponse, AgentThread, ChatMessage, HostedMCPTool
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
@@ -14,7 +14,7 @@ This sample demonstrates integrating hosted Model Context Protocol (MCP) tools w
|
||||
"""
|
||||
|
||||
|
||||
async def handle_approvals_without_thread(query: str, agent: "AgentProtocol") -> AgentRunResponse:
|
||||
async def handle_approvals_without_thread(query: str, agent: "AgentProtocol") -> AgentResponse:
|
||||
"""When we don't have a thread, we need to ensure we return with the input, approval request and approval."""
|
||||
|
||||
result = await agent.run(query, store=False)
|
||||
@@ -35,7 +35,7 @@ async def handle_approvals_without_thread(query: str, agent: "AgentProtocol") ->
|
||||
return result
|
||||
|
||||
|
||||
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread") -> AgentRunResponse:
|
||||
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread") -> AgentResponse:
|
||||
"""Here we let the thread deal with the previous responses, and we just rerun with the approval."""
|
||||
|
||||
result = await agent.run(query, thread=thread)
|
||||
@@ -59,12 +59,13 @@ async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", threa
|
||||
|
||||
async def run_hosted_mcp_without_approval() -> None:
|
||||
"""Example showing MCP Tools without approval."""
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyLearnDocsAgent",
|
||||
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
|
||||
tools=HostedMCPTool(
|
||||
@@ -72,8 +73,8 @@ async def run_hosted_mcp_without_approval() -> None:
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
approval_mode="never_require",
|
||||
),
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query}")
|
||||
result = await handle_approvals_without_thread(query, agent)
|
||||
@@ -84,12 +85,13 @@ async def run_hosted_mcp_with_approval_and_thread() -> None:
|
||||
"""Example showing MCP Tools with approvals using a thread."""
|
||||
print("=== MCP with approvals and with thread ===")
|
||||
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyApiSpecsAgent",
|
||||
instructions="You are a helpful agent that can use MCP tools to assist users.",
|
||||
tools=HostedMCPTool(
|
||||
@@ -97,8 +99,8 @@ async def run_hosted_mcp_with_approval_and_thread() -> None:
|
||||
url="https://gitmcp.io/Azure/azure-rest-api-specs",
|
||||
approval_mode="always_require",
|
||||
),
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
thread = agent.get_new_thread()
|
||||
query = "Please summarize the Azure REST API specifications Readme"
|
||||
print(f"User: {query}")
|
||||
|
||||
@@ -4,13 +4,13 @@ from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
from agent_framework import DataContent, HostedImageGenerationTool
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Image Generation Example
|
||||
|
||||
This sample demonstrates basic usage of AzureAIClient to create an agent
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider to create an agent
|
||||
that can generate images based on user requirements.
|
||||
|
||||
Pre-requisites:
|
||||
@@ -20,12 +20,13 @@ Pre-requisites:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="ImageGenAgent",
|
||||
instructions="Generate images based on user requirements.",
|
||||
tools=[
|
||||
@@ -37,14 +38,14 @@ async def main() -> None:
|
||||
}
|
||||
)
|
||||
],
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "Generate an image of Microsoft logo."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(
|
||||
query,
|
||||
# These additional options are required for image generation
|
||||
additional_chat_options={
|
||||
options={
|
||||
"extra_headers": {"x-ms-oai-image-generation-deployment": "gpt-image-1-mini"},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import MCPStreamableHTTPTool
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
@@ -19,20 +19,22 @@ Pre-requisites:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing use of Local MCP Tool with AzureAIClient."""
|
||||
"""Example showing use of Local MCP Tool with AzureAIProjectAgentProvider."""
|
||||
print("=== Azure AI Agent with Local MCP Tools Example ===\n")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
),
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
# First query
|
||||
first_query = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {first_query}")
|
||||
|
||||
@@ -3,7 +3,7 @@ import asyncio
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
@@ -11,7 +11,7 @@ from azure.identity.aio import AzureCliCredential
|
||||
"""
|
||||
Azure AI Agent with Memory Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with memory search capabilities
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with memory search capabilities
|
||||
to retrieve relevant past user messages and maintain conversation context across sessions.
|
||||
It shows explicit memory store creation using Azure AI Projects client and agent creation
|
||||
using the Agent Framework.
|
||||
@@ -46,18 +46,20 @@ async def main() -> None:
|
||||
)
|
||||
print(f"Created memory store: {memory_store.name} ({memory_store.id}): {memory_store.description}")
|
||||
|
||||
# Then, create the agent using Agent Framework
|
||||
async with AzureAIClient(credential=credential).create_agent(
|
||||
name="MyMemoryAgent",
|
||||
instructions="""You are a helpful assistant that remembers past conversations.
|
||||
Use the memory search tool to recall relevant information from previous interactions.""",
|
||||
tools={
|
||||
"type": "memory_search",
|
||||
"memory_store_name": memory_store.name,
|
||||
"scope": "user_123",
|
||||
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
|
||||
},
|
||||
) as agent:
|
||||
# Then, create the agent using Agent Framework provider
|
||||
async with AzureAIProjectAgentProvider(credential=credential) as provider:
|
||||
agent = await provider.create_agent(
|
||||
name="MyMemoryAgent",
|
||||
instructions="""You are a helpful assistant that remembers past conversations.
|
||||
Use the memory search tool to recall relevant information from previous interactions.""",
|
||||
tools={
|
||||
"type": "memory_search",
|
||||
"memory_store_name": memory_store.name,
|
||||
"scope": "user_123",
|
||||
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
|
||||
},
|
||||
)
|
||||
|
||||
# First interaction - establish some preferences
|
||||
print("=== First conversation ===")
|
||||
query1 = "I prefer dark roast coffee"
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Microsoft Fabric Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with Microsoft Fabric
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Microsoft Fabric
|
||||
to query Fabric data sources and provide responses based on data analysis.
|
||||
|
||||
Prerequisites:
|
||||
@@ -21,7 +21,9 @@ Prerequisites:
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyFabricAgent",
|
||||
instructions="You are a helpful assistant.",
|
||||
tools={
|
||||
@@ -34,8 +36,8 @@ async def main() -> None:
|
||||
]
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "Tell me about sales records"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -4,13 +4,13 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with OpenAPI Tool Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with OpenAPI tools
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with OpenAPI tools
|
||||
to call external APIs defined by OpenAPI specifications.
|
||||
|
||||
Prerequisites:
|
||||
@@ -29,7 +29,9 @@ async def main() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyOpenAPIAgent",
|
||||
instructions="""You are a helpful assistant that can use country APIs to provide information.
|
||||
Use the available OpenAPI tools to answer questions about countries, currencies, and demographics.""",
|
||||
@@ -42,8 +44,8 @@ async def main() -> None:
|
||||
"auth": {"type": "anonymous"},
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What is the name and population of the country that uses currency with abbreviation THB?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
"""
|
||||
Azure AI Agent Response Format Example
|
||||
|
||||
This sample demonstrates basic usage of AzureAIClient with response format,
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider with response format,
|
||||
also known as structured outputs.
|
||||
"""
|
||||
|
||||
@@ -24,23 +24,22 @@ class ReleaseBrief(BaseModel):
|
||||
async def main() -> None:
|
||||
"""Example of using response_format property."""
|
||||
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="ProductMarketerAgent",
|
||||
instructions="Return launch briefs as structured JSON.",
|
||||
) as agent,
|
||||
):
|
||||
# Specify Pydantic model for structured output via default_options
|
||||
default_options={"response_format": ReleaseBrief},
|
||||
)
|
||||
|
||||
query = "Draft a launch brief for the Contoso Note app."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(
|
||||
query,
|
||||
# Specify type to use as response
|
||||
response_format=ReleaseBrief,
|
||||
)
|
||||
result = await agent.run(query)
|
||||
|
||||
if isinstance(result.value, ReleaseBrief):
|
||||
release_brief = result.value
|
||||
|
||||
+14
-15
@@ -2,13 +2,13 @@
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent Response Format Example with Runtime JSON Schema
|
||||
|
||||
This sample demonstrates basic usage of AzureAIClient with response format,
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider with response format,
|
||||
also known as structured outputs.
|
||||
"""
|
||||
|
||||
@@ -29,24 +29,19 @@ runtime_schema = {
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example of using response_format property."""
|
||||
"""Example of using response_format property with a runtime JSON schema."""
|
||||
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
name="ProductMarketerAgent",
|
||||
instructions="Return launch briefs as structured JSON.",
|
||||
) as agent,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
query = "Draft a launch brief for the Contoso Note app."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(
|
||||
query,
|
||||
# Specify type to use as response
|
||||
additional_chat_options={
|
||||
# Pass response_format via default_options using dict schema format
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherDigestAgent",
|
||||
instructions="Return sample weather digest as structured JSON.",
|
||||
default_options={
|
||||
"response_format": {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
@@ -54,10 +49,14 @@ async def main() -> None:
|
||||
"strict": True,
|
||||
"schema": runtime_schema,
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
query = "Draft a sample weather digest."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
print(result.text)
|
||||
|
||||
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with SharePoint Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with SharePoint
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with SharePoint
|
||||
to search through SharePoint content and answer user questions about it.
|
||||
|
||||
Prerequisites:
|
||||
@@ -21,7 +21,9 @@ Prerequisites:
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MySharePointAgent",
|
||||
instructions="""You are a helpful agent that can use SharePoint tools to assist users.
|
||||
Use the available SharePoint tools to answer questions and perform tasks.""",
|
||||
@@ -35,8 +37,8 @@ async def main() -> None:
|
||||
]
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What is Contoso whistleblower policy?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from pydantic import Field
|
||||
|
||||
@@ -30,12 +30,14 @@ async def example_with_automatic_thread_creation() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
# First conversation - no thread provided, will be created automatically
|
||||
query1 = "What's the weather like in Seattle?"
|
||||
print(f"User: {query1}")
|
||||
@@ -59,12 +61,14 @@ async def example_with_thread_persistence_in_memory() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
# Create a new thread that will be reused
|
||||
thread = agent.get_new_thread()
|
||||
|
||||
@@ -100,12 +104,14 @@ async def example_with_existing_thread_id() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
# Start a conversation and get the thread ID
|
||||
thread = agent.get_new_thread()
|
||||
|
||||
@@ -121,21 +127,21 @@ async def example_with_existing_thread_id() -> None:
|
||||
if existing_thread_id:
|
||||
print("\n--- Continuing with the same thread ID in a new agent instance ---")
|
||||
|
||||
async with (
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
) as agent,
|
||||
):
|
||||
# Create a thread with the existing ID
|
||||
thread = agent.get_new_thread(service_thread_id=existing_thread_id)
|
||||
# Create a new agent instance from the same provider
|
||||
agent2 = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query2 = "What was the last city I asked about?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2, thread=thread)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: The agent continues the conversation from the previous thread by using thread ID.\n")
|
||||
# Create a thread with the existing ID
|
||||
thread = agent2.get_new_thread(service_thread_id=existing_thread_id)
|
||||
|
||||
query2 = "What was the last city I asked about?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent2.run(query2, thread=thread)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: The agent continues the conversation from the previous thread by using thread ID.\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import HostedWebSearchTool
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent With Web Search
|
||||
|
||||
This sample demonstrates basic usage of AzureAIClient to create an agent
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider to create an agent
|
||||
that can perform web searches using the HostedWebSearchTool.
|
||||
|
||||
Pre-requisites:
|
||||
@@ -19,17 +19,18 @@ Pre-requisites:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Since no Agent ID is provided, the agent will be automatically created.
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(credential=credential).create_agent(
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="WebsearchAgent",
|
||||
instructions="You are a helpful assistant that can search the web",
|
||||
tools=[HostedWebSearchTool()],
|
||||
) as agent,
|
||||
):
|
||||
)
|
||||
|
||||
query = "What's the weather today in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
|
||||
Reference in New Issue
Block a user