.NET: Python: Merge main into feature-durabletask branch (#3385)

* 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)

* .NET Purview Middleware: Improve Background Job Runner Injection (#3256)

* Clean up background job dependency injection

* Fix xml documentation grammar

* Python: [BREAKING] Renamed create_agent to as_agent (#3249)

* Renamed create_agent to as_agent

* Override for as_agent

* Added override

* Python: Update package version (#3258)

* package version 260116

* removed name tags

* Python: Fixed Azure chat client for asynchronous filtering (#3260)

* Fixed Azure chat client for asynchronous filtering

* Updated test

* Python: Fixed use_agent_middleware calling private _normalize_messages (#3264)

* Fix use_agent_middleware calling private _normalize_messages

* Fixed A2A and Copilot Studio agent

* Python: Added rai_config to Azure AI agent creation (#3265)

* Add kwargs to create_agent method

* Added test for kwargs

* Addressed comment

* Added doc string

* Python: Filter conversation_id when passing kwargs to agent as tool (#3266)

* Filter conversation_id when passing kwargs to agent as tool

* Small fix

* Update python/samples/getting_started/agents/azure_ai/README.md

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update python/samples/getting_started/agents/openai/openai_responses_client_with_agent_as_tool.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update python/samples/getting_started/agents/azure_ai/azure_ai_with_agent_as_tool.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Bump actions/setup-dotnet from 5.0.1 to 5.1.0 (#3273)

Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 5.0.1 to 5.1.0.
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/v5.0.1...v5.1.0)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-version: 5.1.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>

* Update ignored checks in merge-gatekeeper workflow

* Python: [BREAKING] Make response_format validation errors visible to users (#3274)

* Make response_format validation errors visible to users

* Small fix

* Addressed comments

* Python: fix(declarative): Fix MCP tool connection not passed from YAML to Azure AI agent creation API (#3248)

* fix(declarative): Fix MCP tool connection not passed from YAML

* Add samples to README

* Fix mypy

* Fix mypy again

* Address PR comments

* fix #3171, ensure proper form rendering for int (#3201)

* Bump uv from 0.9.25 to 0.9.26 in /python (#3288)

Bumps [uv](https://github.com/astral-sh/uv) from 0.9.25 to 0.9.26.
- [Release notes](https://github.com/astral-sh/uv/releases)
- [Changelog](https://github.com/astral-sh/uv/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/uv/compare/0.9.25...0.9.26)

---
updated-dependencies:
- dependency-name: uv
  dependency-version: 0.9.26
  dependency-type: direct:development
  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 ruff from 0.14.11 to 0.14.13 in /python (#3287)

Bumps [ruff](https://github.com/astral-sh/ruff) from 0.14.11 to 0.14.13.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.14.11...0.14.13)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.14.13
  dependency-type: direct:development
  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 tar from 7.4.3 to 7.5.3 in /python/packages/devui/frontend (#3267)

Bumps [tar](https://github.com/isaacs/node-tar) from 7.4.3 to 7.5.3.
- [Release notes](https://github.com/isaacs/node-tar/releases)
- [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-tar/compare/v7.4.3...v7.5.3)

---
updated-dependencies:
- dependency-name: tar
  dependency-version: 7.5.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* .NET: Delete sync extension methods for agent (#3291)

* Delete sync extension methods for agent

* Fix comments and obsolete attribute

* Remove more sync methods.

* Fix naming and comments.

* Fix unit tests

* Python: Fix: Add system_instructions to ChatClient LLM span tracing (#3164)

* Fix: Add system_instructions to ChatClient LLM span tracing

- Add system_instructions parameter to _capture_messages() calls in
  _trace_get_response() and _trace_get_streaming_response()
- Extract instructions from chat_options in kwargs
- Add unit tests to verify system_instructions are captured correctly

When using ChatClient with ChatOptions.instructions, the OpenTelemetry
LLM span was missing system messages in gen_ai.input.messages and the
gen_ai.system_instructions attribute was not being set.

This fix aligns the ChatClient-level tracing with the Agent-level
tracing which already correctly passes system_instructions.

Fixes #3163

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add edge case tests for system_instructions

- Add test for empty string instructions (should not set attribute)
- Add test for list-type instructions (verify multiple items captured)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Simplify: use options.get('instructions') directly instead of kwargs.get('chat_options')

Addresses reviewer feedback:
- Removed unnecessary chat_options variable from kwargs
- Directly access instructions from the options parameter
- Updated tests to use dict syntax for options (TypedDict convention)

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>

* Improve PR number handling in workflow (#3302)

* Improve PR number handling in workflow

Refine PR number extraction and validation method.

* Update .github/workflows/python-test-coverage-report.yml

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Fix error message for invalid PR number

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* .NET: Update Microsoft.Extensions.AI.* packages to 10.2.0 (#3211)

* Initial plan

* Update Microsoft.Extensions.AI.* to 10.2.0 and fix timestamp behavior tests

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>

* .NET: Pass AdditionalProperties from parent to child when exposing an agent as a FunctionTool (#3219)

* Pass AdditionalProperties from parent to child when exposing an agent as a FunctionTool

* Rename variable to improve readability.

* 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>

* Python: [Breaking] Simplified Content types to a single class with classmethod constructors. (#3252)

* ported Content to a new model

* fixed linting

* fixes

* fixed data format handling

* fix for 3.10 mypy

* fix

* fix int test

* .NET: Durable Agent samples and automated validation for non-Azure Functions (#3042)

* Durable Agent samples and automated validation for non-Azure Functions

* Update test projects

* fix file encoding

* Remove AgentThreadMetadata usage

* Absorb breaking change from #3152

* Absorb newer breaking changes (AgentRunResponse --> AgentResponse)

* Absorb more breaking changes (see #3222)

* Improve integration test reliability (isolated task hubs, etc.)

* Fix flakey streaming test

---------

Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>

* Python: fix(core): handle anyio cancel scope errors during MCP connection cleanup (#3277)

* fix(core): handle anyio cancel scope errors during MCP connection cleanup

* Address Copilot feedback

* Python: fix(ag-ui): properly handle json serialize with handoff workflows as agent (#3275)

* fix(ag-ui): properly handle json serialize with handoff workflows as agent

* Other improvements around handling non-serializable objects

* Bump tomli from 2.3.0 to 2.4.0 in /python (#3182)

Bumps [tomli](https://github.com/hukkin/tomli) from 2.3.0 to 2.4.0.
- [Changelog](https://github.com/hukkin/tomli/blob/master/CHANGELOG.md)
- [Commits](https://github.com/hukkin/tomli/compare/2.3.0...2.4.0)

---
updated-dependencies:
- dependency-name: tomli
  dependency-version: 2.4.0
  dependency-type: direct:development
  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>

* .Net: Fix DebuggerDisplay attribute to reference existing property (#3326)

* Initial plan

* Fix DebuggerDisplay attribute to use Name instead of DisplayName

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: Add sample to show multiple AIContextProvider usage (#3284)

* Add sample to show multiple AIContextProvider usage

* Update comment.

* Update messaging in README.

* Address PR comments.

---------

Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>

* .NET: Update Conversation Sample to use Conversation Id instead (#3180)

* Update Conversation Sample to use conversation Id instead

* Remove Run infix

* Remove the sync GetAIAgent from sample

* Python: Fix local MCP tools with `AzureAIProjectAgentProvider` (#3315)

* azureai v2 local mcp fix

* addressed copilot comments

* .NET: Improve readme for agents V2 (#3285)

* Improve readme for agents V2

* Architectural justification

* Update dotnet/samples/GettingStarted/FoundryAgents/README.md

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Bump pyasn1 from 0.6.1 to 0.6.2 in /python (#3257)

Bumps [pyasn1](https://github.com/pyasn1/pyasn1) from 0.6.1 to 0.6.2.
- [Release notes](https://github.com/pyasn1/pyasn1/releases)
- [Changelog](https://github.com/pyasn1/pyasn1/blob/main/CHANGES.rst)
- [Commits](https://github.com/pyasn1/pyasn1/compare/v0.6.1...v0.6.2)

---
updated-dependencies:
- dependency-name: pyasn1
  dependency-version: 0.6.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* .NET: Fix DebuggerDisplay attribute in AIAgent.cs to reference existing properties (#2985)

* Initial plan

* Fix DebuggerDisplay attribute in AIAgent.cs to reference existing properties

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>
Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>

* Python: feat(anthropic): Add response_format support for structured outputs (#3301)

* fix(anthropic): Add response_format support for structured outputs

* only use from options

* use native way of response format

* ruff lint fix

* address comment; handle dict

* Updated package versions (#3335)

* Set min version of dependent azure-ai-projects to 2.0.0b3 (#3347)

* Adding feature collections ADR (#3332)

* .NET: [Breaking] Allow passing auth token credential to cosmosdb extensions (#3250)

* allow passing token credentials to cosmosdb extensions

* Update dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosDBWorkflowExtensions.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosDBWorkflowExtensions.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update dotnet/src/Microsoft.Agents.AI.CosmosNoSql/CosmosDBChatExtensions.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: Subworkflows do not work well with HostAsAgent (#3240)

Subworkflows run into issues with Checkpointing and the Chat Protocol:

* The concurrency rework made subtle changes in behaviour that introduced a hang when using subworkflows with ChatProtocol and streaming execution.
* The ResetAsync() implementation in WorkflowHostExecutor was improperly resetting the joinContext - this was happening on restore checkpoint _after_ the join context was attached when
* Subworkflows cannot be used as the start node when hosted AsAgent due to inability to treat Catch-All as a Chat Protocol
* Subworkflow ownership issue when used in non-concurrent mode after finishing a run

Also fixes:
* When ChatMessages are output by executors that are not agents, there is no corresponding AgentResponseUpdate/AgentResponse event

Breaking Changes
* [BREAKING CHANGE] It is possible to provide the wrong RunId when resuming from CheckpointInfo (even though the data already exists on CheckpointInfo)

* Python: .NET: Executor source gen for workflow executor routing (#3131)

* Roslyn Source Generators for Workflow Executor Routing.

* Update dotnet/src/Microsoft.Agents.AI.Workflows.Generators/ExecutorRouteGenerator.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* WIP.

* All fixed up except dangling sends/yields attriutes, working on that next.

* Add protocol-only generation for SendsMessage/YieldsOutput attributes

* Ensuring collections that can change order are sorted to enable pipeline caching.

* Improvents per PR feedback.

---------

Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* .NET: Joslat fix sample issue (#3270)

* 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

* Fix in Sample

* update

---------

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>

* .NET: Improve unit test coverage for Microsoft.Agents.AI.OpenAI (#3349)

* Initial plan

* Add unit tests for Microsoft.Agents.AI.OpenAI to improve code coverage

Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>

* Address code review feedback: remove unused using directives

Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>

* Fix format issues: file encoding and remove unused using directives

Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>

* Fix redundant cast error by using named parameter

Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>

* Remove excessive inline comments per PR review feedback

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>

* Revert to main

* Python: Fix: Verify types during checkpoint deserialization to prevent marker spoofing (#3243)

* Initial plan

* Add validation for reserved keywords in checkpoint encoding/decoding

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Refactor to eliminate duplicate code in model protocol detection

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Fix pyright type narrowing issue for dataclass check

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Add comprehensive unit tests for checkpoint encoding

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Remove serialization-time reserved keyword validation to fix failing tests

The serialization-time validation was too aggressive and blocked legitimate use cases
where encoded data was being re-encoded. Security is now enforced only at deserialization
time by validating that classes marked with DATACLASS_MARKER are actual dataclasses and
classes marked with MODEL_MARKER actually support the model protocol.

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Apply ruff formatting to checkpoint encoding file

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Changes before error encountered

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>

* Revert "Changes before error encountered"

This reverts commit f515b880dc.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: Tao Chen <taochen@microsoft.com>

* Python: Fix azurefunctions MCP tool invocation to use correct agent  (#3339)

* MCP tool fix for azurefunctions

* Moving logic to check for thread id

* Adding ReflectExecutors method to Workflow. (#3389)

* Fix merge conflicts

* Python: [BREAKING] simplify ag-ui run logic, fix mcp bugs, fix anthropic client issues in ag-ui (#3322)

* Refactor ag-ui to simplify flow

* Refactoring

* Fix backend tool

* Update tests

* Improvements

* Fix mypy

* Fixes

* Fix json serialize errors

* Python: fix(core): filter out internal args when passing kwargs to MCP tools (#3292)

* fix(core): filter conversation_id when passing kwargs to MCP tools

* Filter out options too

* Fix uv.lock conflict

* Python: Added tests for OpenAI content types + Unit test improvement (#3259)

* added tests for content types+ unit test improvement

* small fixes

* small fix

* Python: Prefer runtime `kwargs` for `conversation_id` in OpenAI Responses client (#3312)

* prefer kwargs conversation_id over options

* addressed comments

* Python: Azure AI mapping HostedImageGenerationTool to ImageGenTool (#3263)

* azureai image gen sample fix

* mypy fixes

* addressed comments + mapping updates

* image model fix

* content type fix

* Python: add(azure-ai): support reasoning config for AzureAIClient (#3403)

* add(azure-ai): support reasoning config for AzureAIClient

* Update sample

* Merge main

* improvements

* improve sample

* .NET: Allow overriding the ChatMessageStore to be used per agent run. (#3330)

* Allow overriding the ChatMessageStore to be used per agent run.

* Fix typos

* Fix Add and add TryAdd, Contains and Remove

* Update instructions to require automatically building and formatting (#3412)

* .NET: Rename ChatMessageStore to ChatHistoryProvider (#3375)

* Rename ChatMessageStore to ChatHistoryProvider

* Fix merge issue

* Fixed PR comments

* Fix tests after property rename

* Add unit tests and fix merge issues

* Fix encoding

---------

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>
Co-authored-by: eoindoherty1 <eoindoherty@microsoft.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Darren Cohen <39422044+dargilco@users.noreply.github.com>
Co-authored-by: Ben Thomas <ben.thomas@microsoft.com>
Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: Shyju Krishnankutty <connectshyju@gmail.com>
This commit is contained in:
Laveesh Rohra
2026-01-23 10:31:54 -08:00
committed by GitHub
Unverified
parent ff839435a2
commit 172423aab7
552 changed files with 23634 additions and 14420 deletions
+26
View File
@@ -180,6 +180,17 @@ The recommended way to use Ollama is via the native `OllamaChatClient` from the
| [`getting_started/context_providers/simple_context_provider.py`](./getting_started/context_providers/simple_context_provider.py) | Simple context provider implementation example |
| [`getting_started/context_providers/aggregate_context_provider.py`](./getting_started/context_providers/aggregate_context_provider.py) | Shows how to combine multiple context providers using an AggregateContextProvider |
## Declarative
| File | Description |
|------|-------------|
| [`getting_started/declarative/azure_openai_responses_agent.py`](./getting_started/declarative/azure_openai_responses_agent.py) | Basic agent using Azure OpenAI with structured responses |
| [`getting_started/declarative/get_weather_agent.py`](./getting_started/declarative/get_weather_agent.py) | Agent with custom function tools using declarative bindings |
| [`getting_started/declarative/inline_yaml.py`](./getting_started/declarative/inline_yaml.py) | Agent created from inline YAML string |
| [`getting_started/declarative/mcp_tool_yaml.py`](./getting_started/declarative/mcp_tool_yaml.py) | MCP tool configuration with API key and Azure Foundry connection auth |
| [`getting_started/declarative/microsoft_learn_agent.py`](./getting_started/declarative/microsoft_learn_agent.py) | Agent with MCP server integration for Microsoft Learn documentation |
| [`getting_started/declarative/openai_responses_agent.py`](./getting_started/declarative/openai_responses_agent.py) | Basic agent using OpenAI directly |
## DevUI
| File | Description |
@@ -242,6 +253,21 @@ The recommended way to use Ollama is via the native `OllamaChatClient` from the
| [`getting_started/azure_functions/05_multi_agent_orchestration_concurrency/`](./getting_started/azure_functions/05_multi_agent_orchestration_concurrency/) | Run two agents concurrently within a durable orchestration and combine their domain-specific outputs. |
| [`getting_started/azure_functions/06_multi_agent_orchestration_conditionals/`](./getting_started/azure_functions/06_multi_agent_orchestration_conditionals/) | Route orchestration logic based on structured agent responses for spam detection and reply drafting. |
| [`getting_started/azure_functions/07_single_agent_orchestration_hitl/`](./getting_started/azure_functions/07_single_agent_orchestration_hitl/) | Implement a human-in-the-loop approval loop that iterates on agent output inside a durable orchestration. |
| [`getting_started/azure_functions/08_mcp_server/`](./getting_started/azure_functions/08_mcp_server/) | Configure agents as both HTTP endpoints and MCP tools for flexible integration patterns. |
## Durable Task
These samples demonstrate durable agent hosting using the Durable Task Scheduler with a worker-client architecture pattern, enabling distributed agent execution with persistent conversation state.
| Sample | Description |
|--------|-------------|
| [`getting_started/durabletask/01_single_agent/`](./getting_started/durabletask/01_single_agent/) | Host a single conversational agent with worker-client architecture and agent state management. |
| [`getting_started/durabletask/02_multi_agent/`](./getting_started/durabletask/02_multi_agent/) | Host multiple domain-specific agents and route requests based on question topic. |
| [`getting_started/durabletask/03_single_agent_streaming/`](./getting_started/durabletask/03_single_agent_streaming/) | Implement reliable streaming using Redis Streams with cursor-based resumption for durable agents. |
| [`getting_started/durabletask/04_single_agent_orchestration_chaining/`](./getting_started/durabletask/04_single_agent_orchestration_chaining/) | Chain multiple agent invocations using durable orchestration while preserving conversation context. |
| [`getting_started/durabletask/05_multi_agent_orchestration_concurrency/`](./getting_started/durabletask/05_multi_agent_orchestration_concurrency/) | Run multiple agents concurrently within an orchestration and aggregate their responses. |
| [`getting_started/durabletask/06_multi_agent_orchestration_conditionals/`](./getting_started/durabletask/06_multi_agent_orchestration_conditionals/) | Implement conditional branching with spam detection using structured outputs and activity functions. |
| [`getting_started/durabletask/07_single_agent_orchestration_hitl/`](./getting_started/durabletask/07_single_agent_orchestration_hitl/) | Human-in-the-loop pattern with external event handling, timeouts, and iterative refinement. |
## Observability
@@ -59,17 +59,17 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
researcher = client.create_agent(
researcher = client.as_agent(
name="researcher",
instructions="You are a researcher. Provide facts and data about the topic.",
)
writer = client.create_agent(
writer = client.as_agent(
name="writer",
instructions="You are a writer. Turn research into engaging content.",
)
editor = client.create_agent(
editor = client.as_agent(
name="editor",
instructions="You are an editor. Review and finalize the content.",
)
@@ -109,17 +109,17 @@ async def run_agent_framework_with_cycle() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
researcher = client.create_agent(
researcher = client.as_agent(
name="researcher",
instructions="You are a researcher. Provide facts and data about the topic.",
)
writer = client.create_agent(
writer = client.as_agent(
name="writer",
instructions="You are a writer. Turn research into engaging content.",
)
editor = client.create_agent(
editor = client.as_agent(
name="editor",
instructions="You are an editor. Review and finalize the content. End with APPROVED if satisfied.",
)
@@ -65,19 +65,19 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
python_expert = client.create_agent(
python_expert = client.as_agent(
name="python_expert",
instructions="You are a Python programming expert. Answer Python-related questions.",
description="Expert in Python programming",
)
javascript_expert = client.create_agent(
javascript_expert = client.as_agent(
name="javascript_expert",
instructions="You are a JavaScript programming expert. Answer JavaScript-related questions.",
description="Expert in JavaScript programming",
)
database_expert = client.create_agent(
database_expert = client.as_agent(
name="database_expert",
instructions="You are a database expert. Answer SQL and database-related questions.",
description="Expert in databases and SQL",
@@ -87,7 +87,7 @@ async def run_agent_framework() -> None:
GroupChatBuilder()
.participants([python_expert, javascript_expert, database_expert])
.set_manager(
manager=client.create_agent(
manager=client.as_agent(
name="selector_manager",
instructions="Based on the conversation, select the most appropriate expert to respond next.",
),
@@ -108,7 +108,7 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create triage agent
triage_agent = client.create_agent(
triage_agent = client.as_agent(
name="triage",
instructions=(
"You are a triage agent. Analyze the user's request and route to the appropriate specialist:\n"
@@ -119,14 +119,14 @@ async def run_agent_framework() -> None:
)
# Create billing specialist
billing_agent = client.create_agent(
billing_agent = client.as_agent(
name="billing_agent",
instructions="You are a billing specialist. Help with payment and billing questions. Provide clear assistance.",
description="Handles billing and payment questions",
)
# Create technical support specialist
tech_support = client.create_agent(
tech_support = client.as_agent(
name="technical_support",
instructions="You are technical support. Help with technical issues. Provide clear assistance.",
description="Handles technical support questions",
@@ -69,19 +69,19 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
researcher = client.create_agent(
researcher = client.as_agent(
name="researcher",
instructions="You are a research analyst. Gather and analyze information.",
description="Research analyst for data gathering",
)
coder = client.create_agent(
coder = client.as_agent(
name="coder",
instructions="You are a programmer. Write code based on requirements.",
description="Software developer for implementation",
)
reviewer = client.create_agent(
reviewer = client.as_agent(
name="reviewer",
instructions="You are a code reviewer. Review code for quality and correctness.",
description="Code reviewer for quality assurance",
@@ -33,7 +33,7 @@ async def run_agent_framework() -> None:
# AF constructs a lightweight ChatAgent backed by OpenAIChatClient
client = OpenAIChatClient(model_id="gpt-4.1-mini")
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful assistant. Answer in one sentence.",
)
@@ -65,7 +65,7 @@ async def run_agent_framework() -> None:
# Create agent with tool
client = OpenAIChatClient(model_id="gpt-4.1-mini")
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful assistant. Use available tools to answer questions.",
tools=[get_weather],
@@ -40,7 +40,7 @@ async def run_agent_framework() -> None:
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient(model_id="gpt-4.1-mini")
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful math tutor.",
)
@@ -54,7 +54,7 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized writer agent
writer = client.create_agent(
writer = client.as_agent(
name="writer",
instructions="You are a creative writer. Write short, engaging content.",
)
@@ -68,7 +68,7 @@ async def run_agent_framework() -> None:
)
# Create coordinator agent with writer tool
coordinator = client.create_agent(
coordinator = client.as_agent(
name="coordinator",
instructions="You coordinate with specialized agents. Delegate writing tasks to the writer agent.",
tools=[writer_tool],
@@ -8,7 +8,7 @@ from azure.identity import DefaultAzureCredential
def main():
# Create an Agent using the Azure OpenAI Chat Client with a MCP Tool that connects to Microsoft Learn MCP
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
@@ -93,7 +93,7 @@ class TextSearchContextProvider(ContextProvider):
def main():
# Create an Agent using the Azure OpenAI Chat Client
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
name="SupportSpecialist",
instructions=(
"You are a helpful support specialist for Contoso Outdoors. "
@@ -8,21 +8,21 @@ from azure.identity import DefaultAzureCredential # pyright: ignore[reportUnkno
def main():
# Create agents
researcher = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
researcher = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
instructions=(
"You're an expert market and product researcher. "
"Given a prompt, provide concise, factual insights, opportunities, and risks."
),
name="researcher",
)
marketer = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
marketer = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
instructions=(
"You're a creative marketing strategist. "
"Craft compelling value propositions and target messaging aligned to the prompt."
),
name="marketer",
)
legal = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
legal = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
instructions=(
"You're a cautious legal/compliance reviewer. "
"Highlight constraints, disclaimers, and policy concerns based on the prompt."
@@ -93,7 +93,7 @@ def get_weather(
def build_agent() -> ChatAgent:
"""Create and return the chat agent instance with weather tool registered."""
return OpenAIChatClient().create_agent(
return OpenAIChatClient().as_agent(
name="WeatherAgent", instructions="You are a helpful weather agent.", tools=get_weather
)
@@ -78,7 +78,7 @@ class ResearchLead(Executor):
def __init__(self, chat_client: AzureAIClient, id: str = "travel-planning-coordinator"):
# store=True to preserve conversation history for evaluation
self.agent = chat_client.create_agent(
self.agent = chat_client.as_agent(
id="travel-planning-coordinator",
instructions=(
"You are the final coordinator. You will receive responses from multiple agents: "
@@ -220,7 +220,7 @@ async def _create_workflow(project_client, credential):
travel_request_handler_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="travel-request-handler"
)
travel_request_handler = travel_request_handler_client.create_agent(
travel_request_handler = travel_request_handler_client.as_agent(
id="travel-request-handler",
instructions=(
"You receive user travel queries and relay them to specialized agents. Extract key information: destination, dates, budget, and preferences. Pass this information forward clearly to the next agents."
@@ -233,7 +233,7 @@ async def _create_workflow(project_client, credential):
hotel_search_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="hotel-search-agent"
)
hotel_search_agent = hotel_search_client.create_agent(
hotel_search_agent = hotel_search_client.as_agent(
id="hotel-search-agent",
instructions=(
"You are a hotel search specialist. Your task is ONLY to search for and provide hotel information. Use search_hotels to find options, get_hotel_details for specifics, and check_availability to verify rooms. Output format: List hotel names, prices per night, total cost for the stay, locations, ratings, amenities, and addresses. IMPORTANT: Only provide hotel information without additional commentary."
@@ -247,7 +247,7 @@ async def _create_workflow(project_client, credential):
flight_search_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="flight-search-agent"
)
flight_search_agent = flight_search_client.create_agent(
flight_search_agent = flight_search_client.as_agent(
id="flight-search-agent",
instructions=(
"You are a flight search specialist. Your task is ONLY to search for and provide flight information. Use search_flights to find options, get_flight_details for specifics, and check_availability for seats. Output format: List flight numbers, airlines, departure/arrival times, prices, durations, and cabin class. IMPORTANT: Only provide flight information without additional commentary."
@@ -261,7 +261,7 @@ async def _create_workflow(project_client, credential):
activity_search_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="activity-search-agent"
)
activity_search_agent = activity_search_client.create_agent(
activity_search_agent = activity_search_client.as_agent(
id="activity-search-agent",
instructions=(
"You are an activities specialist. Your task is ONLY to search for and provide activity information. Use search_activities to find options for activities. Output format: List activity names, descriptions, prices, durations, ratings, and categories. IMPORTANT: Only provide activity information without additional commentary."
@@ -275,7 +275,7 @@ async def _create_workflow(project_client, credential):
booking_confirmation_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="booking-confirmation-agent"
)
booking_confirmation_agent = booking_confirmation_client.create_agent(
booking_confirmation_agent = booking_confirmation_client.as_agent(
id="booking-confirmation-agent",
instructions=(
"You confirm bookings. Use check_hotel_availability and check_flight_availability to verify slots, then confirm_booking to finalize. Provide ONLY: confirmation numbers, booking references, and confirmation status."
@@ -289,7 +289,7 @@ async def _create_workflow(project_client, credential):
booking_payment_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="booking-payment-agent"
)
booking_payment_agent = booking_payment_client.create_agent(
booking_payment_agent = booking_payment_client.as_agent(
id="booking-payment-agent",
instructions=(
"You process payments. Use validate_payment_method to verify payment, then process_payment to complete transactions. Provide ONLY: payment confirmation status, transaction IDs, and payment amounts."
@@ -303,7 +303,7 @@ async def _create_workflow(project_client, credential):
booking_info_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="booking-info-aggregation-agent"
)
booking_info_aggregation_agent = booking_info_client.create_agent(
booking_info_aggregation_agent = booking_info_client.as_agent(
id="booking-info-aggregation-agent",
instructions=(
"You aggregate hotel and flight search results. Receive options from search agents and organize them. Provide: top 2-3 hotel options with prices and top 2-3 flight options with prices in a structured format."
@@ -17,7 +17,7 @@ This sample demonstrates using Anthropic with:
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient[AnthropicChatOptions]().create_agent(
agent = AnthropicClient[AnthropicChatOptions]().as_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
@@ -43,7 +43,7 @@ async def main() -> None:
if isinstance(content, TextReasoningContent):
print(f"\033[32m{content.text}\033[0m", end="", flush=True)
if isinstance(content, UsageContent):
print(f"\n\033[34m[Usage so far: {content.details}]\033[0m\n", end="", flush=True)
print(f"\n\033[34m[Usage so far: {content.usage_details}]\033[0m\n", end="", flush=True)
if chunk.text:
print(chunk.text, end="", flush=True)
@@ -26,7 +26,7 @@ async def non_streaming_example() -> None:
print("=== Non-streaming Response Example ===")
agent = AnthropicClient(
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -43,7 +43,7 @@ async def streaming_example() -> None:
print("=== Streaming Response Example ===")
agent = AnthropicClient(
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -28,7 +28,7 @@ To use the Foundry integration ensure you have the following environment variabl
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient(anthropic_client=AsyncAnthropicFoundry()).create_agent(
agent = AnthropicClient(anthropic_client=AsyncAnthropicFoundry()).as_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
@@ -54,7 +54,7 @@ async def main() -> None:
if isinstance(content, TextReasoningContent):
print(f"\033[32m{content.text}\033[0m", end="", flush=True)
if isinstance(content, UsageContent):
print(f"\n\033[34m[Usage so far: {content.details}]\033[0m\n", end="", flush=True)
print(f"\n\033[34m[Usage so far: {content.usage_details}]\033[0m\n", end="", flush=True)
if chunk.text:
print(chunk.text, end="", flush=True)
@@ -31,7 +31,7 @@ async def main() -> None:
# Create a agent with the pptx skill enabled
# Skills also need the code interpreter tool to function
agent = client.create_agent(
agent = client.as_agent(
name="DocsAgent",
instructions="You are a helpful agent for creating powerpoint presentations.",
tools=HostedCodeInterpreterTool(),
@@ -61,7 +61,7 @@ async def main() -> None:
case "text_reasoning":
print(f"\033[32m{content.text}\033[0m", end="", flush=True)
case "usage":
print(f"\n\033[34m[Usage so far: {content.details}]\033[0m\n", end="", flush=True)
print(f"\n\033[34m[Usage so far: {content.usage_details}]\033[0m\n", end="", flush=True)
case "hosted_file":
# Catch generated files
files.append(content)
@@ -9,6 +9,7 @@ This folder contains examples demonstrating different ways to create and use age
| [`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_as_tool.py`](azure_ai_with_agent_as_tool.py) | Shows how to use the agent-as-tool pattern with Azure AI agents, where one agent delegates work to specialized sub-agents wrapped as tools using `as_tool()`. Demonstrates hierarchical agent architectures. |
| [`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. |
@@ -17,6 +18,7 @@ This folder contains examples demonstrating different ways to create and use age
| [`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_content_filtering.py`](azure_ai_with_content_filtering.py) | Shows how to enable content filtering (RAI policy) on Azure AI agents using `RaiConfig`. Requires creating an RAI policy in Azure AI Foundry portal first. |
| [`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. |
@@ -34,6 +36,7 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_ai_with_memory_search.py`](azure_ai_with_memory_search.py) | Shows how to use memory search functionality with Azure AI agents for conversation persistence. Demonstrates creating memory stores and enabling agents to search through conversation history. |
| [`azure_ai_with_microsoft_fabric.py`](azure_ai_with_microsoft_fabric.py) | Shows how to use Microsoft Fabric with Azure AI agents to query Fabric data sources and provide responses based on data analysis. Requires a Microsoft Fabric connection configured in your Azure AI project. |
| [`azure_ai_with_openapi.py`](azure_ai_with_openapi.py) | Shows how to integrate OpenAPI specifications with Azure AI agents using dictionary-based tool configuration. Demonstrates using external REST APIs for dynamic data lookup. |
| [`azure_ai_with_reasoning.py`](azure_ai_with_reasoning.py) | Shows how to enable reasoning for a model that supports it. |
| [`azure_ai_with_web_search.py`](azure_ai_with_web_search.py) | Shows how to use the `HostedWebSearchTool` with Azure AI agents to perform web searches and retrieve up-to-date information from the internet. |
## Environment Variables
@@ -145,49 +145,6 @@ async def get_agent_by_reference_example() -> None:
)
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.
@@ -284,7 +241,6 @@ async def main() -> None:
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()
@@ -0,0 +1,70 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from collections.abc import Awaitable, Callable
from agent_framework import FunctionInvocationContext
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent-as-Tool Example
Demonstrates hierarchical agent architectures where one agent delegates
work to specialized sub-agents wrapped as tools using as_tool().
This pattern is useful when you want a coordinator agent to orchestrate
multiple specialized agents, each focusing on specific tasks.
"""
async def logging_middleware(
context: FunctionInvocationContext,
next: Callable[[FunctionInvocationContext], Awaitable[None]],
) -> None:
"""Middleware that logs tool invocations to show the delegation flow."""
print(f"[Calling tool: {context.function.name}]")
print(f"[Request: {context.arguments}]")
await next(context)
print(f"[Response: {context.result}]")
async def main() -> None:
print("=== Azure AI Agent-as-Tool Pattern ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a specialized writer agent
writer = await provider.create_agent(
name="WriterAgent",
instructions="You are a creative writer. Write short, engaging content.",
)
# Convert writer agent to a tool using as_tool()
writer_tool = writer.as_tool(
name="creative_writer",
description="Generate creative content like taglines, slogans, or short copy",
arg_name="request",
arg_description="What to write",
)
# Create coordinator agent with writer as a tool
coordinator = await provider.create_agent(
name="CoordinatorAgent",
instructions="You coordinate with specialized agents. Delegate writing tasks to the creative_writer tool.",
tools=[writer_tool],
middleware=[logging_middleware],
)
query = "Create a tagline for a coffee shop"
print(f"User: {query}")
result = await coordinator.run(query)
print(f"Coordinator: {result}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -4,10 +4,7 @@ import asyncio
from agent_framework import (
AgentResponseUpdate,
CitationAnnotation,
HostedCodeInterpreterTool,
HostedFileContent,
TextContent,
)
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
@@ -50,9 +47,9 @@ async def non_streaming_example() -> None:
# 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:
if content.type == "text" and content.annotations:
for annotation in content.annotations:
if isinstance(annotation, CitationAnnotation) and annotation.file_id:
if annotation.file_id:
annotations_found.append(annotation.file_id)
print(f"Found file annotation: file_id={annotation.file_id}")
@@ -84,15 +81,15 @@ async def streaming_example() -> None:
async for update in agent.run_stream(QUERY):
if isinstance(update, AgentResponseUpdate):
for content in update.contents:
if isinstance(content, TextContent):
if content.type == "text":
if content.text:
text_chunks.append(content.text)
if content.annotations:
for annotation in content.annotations:
if isinstance(annotation, CitationAnnotation) and annotation.file_id:
if annotation.file_id:
annotations_found.append(annotation.file_id)
print(f"Found streaming annotation: file_id={annotation.file_id}")
elif isinstance(content, HostedFileContent):
elif content.type == "hosted_file":
file_ids_found.append(content.file_id)
print(f"Found streaming HostedFileContent: file_id={content.file_id}")
@@ -0,0 +1,66 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.models import RaiConfig
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Content Filtering (RAI Policy) Example
This sample demonstrates how to enable content filtering on Azure AI agents using RaiConfig.
Prerequisites:
1. Create an RAI Policy in Azure AI Foundry portal:
- Go to Azure AI Foundry > Your Project > Guardrails + Controls > Content Filters
- Create a new content filter or use an existing one
- Note the policy name
2. Set environment variables:
- AZURE_AI_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
- AZURE_AI_MODEL_DEPLOYMENT_NAME: Your model deployment name
3. Run `az login` to authenticate
"""
async def main() -> None:
print("=== Azure AI Agent with Content Filtering ===\n")
# Replace with your RAI policy from Azure AI Foundry portal
rai_policy_name = (
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/"
"Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{policyName}"
)
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create agent with content filtering enabled via default_options
agent = await provider.create_agent(
name="ContentFilteredAgent",
instructions="You are a helpful assistant.",
default_options={"rai_config": RaiConfig(rai_policy_name=rai_policy_name)},
)
# Test with a normal query
query = "What is the capital of France?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
# Test with a query that might trigger content filtering
# (depending on your RAI policy configuration)
query2 = "Tell me something inappropriate."
print(f"User: {query2}")
try:
result2 = await agent.run(query2)
print(f"Agent: {result2}\n")
except Exception as e:
print(f"Content filter triggered: {e}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -1,9 +1,12 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import base64
import tempfile
from pathlib import Path
from urllib import request as urllib_request
import aiofiles
from agent_framework import DataContent, HostedImageGenerationTool
from agent_framework import HostedImageGenerationTool
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
@@ -32,10 +35,14 @@ async def main() -> None:
tools=[
HostedImageGenerationTool(
options={
"model": "gpt-image-1-mini",
"model_id": "gpt-image-1",
"image_size": "1024x1024",
"media_type": "png",
},
additional_properties={
"quality": "low",
"size": "1024x1024",
}
"background": "opaque",
},
)
],
)
@@ -54,17 +61,36 @@ async def main() -> None:
# Save the image to a file
print("Downloading generated image...")
image_data = [
content
content.outputs
for content in result.messages[0].contents
if isinstance(content, DataContent) and content.media_type == "image/png"
if content.type == "image_generation_tool_result" and content.outputs is not None
]
if image_data and image_data[0]:
# Save to the same directory as this script
# Save to the OS temporary directory
filename = "microsoft.png"
current_dir = Path(__file__).parent.resolve()
file_path = current_dir / filename
file_path = Path(tempfile.gettempdir()) / filename
# outputs can be a list of Content items (data/uri) or a single item
out = image_data[0][0] if isinstance(image_data[0], list) else image_data[0]
data_bytes: bytes | None = None
uri = getattr(out, "uri", None)
if isinstance(uri, str):
if ";base64," in uri:
try:
b64 = uri.split(";base64,", 1)[1]
data_bytes = base64.b64decode(b64)
except Exception:
data_bytes = None
else:
try:
data_bytes = await asyncio.to_thread(lambda: urllib_request.urlopen(uri).read())
except Exception:
data_bytes = None
if data_bytes is None:
raise RuntimeError("Image output present but could not retrieve bytes.")
async with aiofiles.open(file_path, "wb") as f:
await f.write(image_data[0].get_data_bytes())
await f.write(data_bytes)
print(f"Image downloaded and saved to: {file_path}")
else:
@@ -22,6 +22,11 @@ async def main() -> None:
"""Example showing use of Local MCP Tool with AzureAIProjectAgentProvider."""
print("=== Azure AI Agent with Local MCP Tools Example ===\n")
mcp_tool = MCPStreamableHTTPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
)
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
@@ -29,23 +34,22 @@ async def main() -> None:
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",
),
tools=mcp_tool,
)
# First query
first_query = "How to create an Azure storage account using az cli?"
print(f"User: {first_query}")
first_result = await agent.run(first_query)
print(f"Agent: {first_result}")
print("\n=======================================\n")
# Second query
second_query = "What is Microsoft Agent Framework?"
print(f"User: {second_query}")
second_result = await agent.run(second_query)
print(f"Agent: {second_result}")
# Use agent as context manager to ensure proper cleanup
async with agent:
# First query
first_query = "How to create an Azure storage account using az cli?"
print(f"User: {first_query}")
first_result = await agent.run(first_query)
print(f"Agent: {first_result}")
print("\n=======================================\n")
# Second query
second_query = "What is Microsoft Agent Framework?"
print(f"User: {second_query}")
second_result = await agent.run(second_query)
print(f"Agent: {second_result}")
if __name__ == "__main__":
@@ -0,0 +1,94 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.models import Reasoning
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Reasoning Example
Demonstrates how to enable reasoning capabilities using the Reasoning option.
Shows both non-streaming and streaming approaches, including how to access
reasoning content (type="text_reasoning") separately from answer content.
Requires a reasoning-capable model (e.g., gpt-5.2) deployed in your Azure AI Project configured
as `AZURE_AI_MODEL_DEPLOYMENT_NAME` in your environment.
"""
async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ReasoningWeatherAgent",
instructions="You are a helpful weather agent who likes to understand the underlying physics.",
default_options={"reasoning": Reasoning(effort="medium", summary="concise")},
)
query = "How does the Bernoulli effect work?"
print(f"User: {query}")
result = await agent.run(query)
for msg in result.messages:
for content in msg.contents:
if content.type == "text_reasoning":
print(f"[Reasoning]: {content.text}")
elif content.type == "text":
print(f"[Answer]: {content.text}")
print()
async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ReasoningWeatherAgent",
instructions="You are a helpful weather agent who likes to understand the underlying physics.",
default_options={"reasoning": Reasoning(effort="medium", summary="concise")},
)
query = "Help explain how air updrafts work?"
print(f"User: {query}")
shown_reasoning_label = False
shown_text_label = False
async for chunk in agent.run_stream(query):
for content in chunk.contents:
if content.type == "text_reasoning":
if not shown_reasoning_label:
print("[Reasoning]: ", end="", flush=True)
shown_reasoning_label = True
print(content.text, end="", flush=True)
elif content.type == "text":
if not shown_text_label:
print("\n\n[Answer]: ", end="", flush=True)
shown_text_label = True
print(content.text, end="", flush=True)
print("\n")
async def main() -> None:
print("=== Azure AI Agent with Reasoning Example ===")
# await non_streaming_example()
await streaming_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -41,12 +41,13 @@ async def main() -> None:
print(f"User: {query}")
result = await agent.run(query)
if isinstance(result.value, ReleaseBrief):
release_brief = result.value
if release_brief := result.try_parse_value(ReleaseBrief):
print("Agent:")
print(f"Feature: {release_brief.feature}")
print(f"Benefit: {release_brief.benefit}")
print(f"Launch date: {release_brief.launch_date}")
else:
print(f"Failed to parse response: {result.text}")
if __name__ == "__main__":
@@ -3,7 +3,7 @@
import asyncio
import os
from agent_framework import CitationAnnotation
from agent_framework import Annotation
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.ai.projects.aio import AIProjectClient
@@ -85,13 +85,11 @@ async def main() -> None:
)
print(f"User: {user_input}")
print("Agent: ", end="", flush=True)
# Stream the response and collect citations
citations: list[CitationAnnotation] = []
citations: list[Annotation] = []
async for chunk in agent.run_stream(user_input):
if chunk.text:
print(chunk.text, end="", flush=True)
# Collect citations from Azure AI Search responses
for content in getattr(chunk, "contents", []):
annotations = getattr(content, "annotations", [])
@@ -104,7 +102,7 @@ async def main() -> None:
if citations:
print("\n\nCitation:")
for i, citation in enumerate(citations, 1):
print(f"[{i}] {citation.url}")
print(f"[{i}] {citation.get('url')}")
print("\n" + "=" * 50 + "\n")
print("Hotel search conversation completed!")
@@ -2,7 +2,7 @@
import asyncio
from agent_framework import CitationAnnotation, HostedWebSearchTool
from agent_framework import Annotation, HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
@@ -57,7 +57,7 @@ async def main() -> None:
print("Agent: ", end="", flush=True)
# Stream the response and collect citations
citations: list[CitationAnnotation] = []
citations: list[Annotation] = []
async for chunk in agent.run_stream(user_input):
if chunk.text:
print(chunk.text, end="", flush=True)
@@ -74,9 +74,9 @@ async def main() -> None:
if citations:
print("\n\nCitations:")
for i, citation in enumerate(citations, 1):
print(f"[{i}] {citation.title}: {citation.url}")
if citation.snippet:
print(f" Snippet: {citation.snippet}")
print(f"[{i}] {citation['title']}: {citation.get('url')}")
if "snippet" in citation:
print(f" Snippet: {citation.get('snippet')}")
else:
print("\nNo citations found in the response.")
@@ -56,13 +56,14 @@ async def main() -> None:
result1 = await agent.run(query1)
if isinstance(result1.value, WeatherInfo):
weather = result1.value
if weather := result1.try_parse_value(WeatherInfo):
print("Agent:")
print(f" Location: {weather.location}")
print(f" Temperature: {weather.temperature}")
print(f" Conditions: {weather.conditions}")
print(f" Recommendation: {weather.recommendation}")
else:
print(f"Failed to parse response: {result1.text}")
# Request 2: Override response_format at runtime with CityInfo
print("\n--- Request 2: Runtime override with CityInfo ---")
@@ -71,12 +72,13 @@ async def main() -> None:
result2 = await agent.run(query2, options={"response_format": CityInfo})
if isinstance(result2.value, CityInfo):
city = result2.value
if city := result2.try_parse_value(CityInfo):
print("Agent:")
print(f" City: {city.city_name}")
print(f" Population: {city.population}")
print(f" Country: {city.country}")
else:
print(f"Failed to parse response: {result2.text}")
if __name__ == "__main__":
@@ -32,7 +32,7 @@ async def non_streaming_example() -> None:
# and deleted after getting a response
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).create_agent(
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
@@ -48,7 +48,7 @@ async def streaming_example() -> None:
# Since no assistant ID is provided, the assistant will be automatically created
# and deleted after getting a response
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).create_agent(
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
@@ -34,7 +34,7 @@ async def main() -> None:
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
credential=AzureCliCredential(),
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
@@ -31,7 +31,7 @@ async def non_streaming_example() -> None:
# Create agent with Azure Chat Client
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -49,7 +49,7 @@ async def streaming_example() -> None:
# Create agent with Azure Chat Client
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -34,7 +34,7 @@ async def main() -> None:
deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
credential=AzureCliCredential(),
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -30,7 +30,7 @@ async def non_streaming_example() -> None:
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -47,7 +47,7 @@ async def streaming_example() -> None:
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -18,7 +18,7 @@ async def main():
print("=== Azure Responses Agent with Image Analysis ===")
# 1. Create an Azure Responses agent with vision capabilities
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
name="VisionAgent",
instructions="You are a helpful agent that can analyze images.",
)
@@ -34,7 +34,7 @@ async def main() -> None:
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
credential=AzureCliCredential(),
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -37,7 +37,7 @@ async def main():
credential=credential,
)
agent: ChatAgent = responses_client.create_agent(
agent: ChatAgent = responses_client.as_agent(
name="DocsAgent",
instructions=("You are a helpful assistant that can help with Microsoft documentation questions."),
)
@@ -125,7 +125,7 @@ async def main() -> None:
print(f"Direct response: {direct_response.messages[0].text}")
# Create an agent using the custom chat client
echo_agent = echo_client.create_agent(
echo_agent = echo_client.as_agent(
name="EchoAgent",
instructions="You are a helpful assistant that echoes back what users say.",
)
@@ -27,7 +27,7 @@ async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
agent = OllamaChatClient().create_agent(
agent = OllamaChatClient().as_agent(
name="TimeAgent",
instructions="You are a helpful time agent answer in one sentence.",
tools=get_time,
@@ -43,7 +43,7 @@ async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
agent = OllamaChatClient().create_agent(
agent = OllamaChatClient().as_agent(
name="TimeAgent",
instructions="You are a helpful time agent answer in one sentence.",
tools=get_time,
@@ -21,7 +21,7 @@ https://ollama.com/
async def reasoning_example() -> None:
print("=== Response Reasoning Example ===")
agent = OllamaChatClient().create_agent(
agent = OllamaChatClient().as_agent(
name="TimeAgent",
instructions="You are a helpful agent answer in one sentence.",
default_options={"think": True}, # Enable Reasoning on agent level
@@ -2,7 +2,7 @@
import asyncio
from agent_framework import ChatMessage, DataContent, Role, TextContent
from agent_framework import ChatMessage, Content, Role
from agent_framework.ollama import OllamaChatClient
"""
@@ -35,8 +35,8 @@ async def test_image() -> None:
message = ChatMessage(
role=Role.USER,
contents=[
TextContent(text="What's in this image?"),
DataContent(uri=image_uri, media_type="image/png"),
Content.from_text(text="What's in this image?"),
Content.from_uri(uri=image_uri, media_type="image/png"),
],
)
@@ -36,7 +36,7 @@ async def non_streaming_example() -> None:
api_key="ollama", # Just a placeholder, Ollama doesn't require API key
base_url=os.getenv("OLLAMA_ENDPOINT"),
model_id=os.getenv("OLLAMA_MODEL"),
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -56,7 +56,7 @@ async def streaming_example() -> None:
api_key="ollama", # Just a placeholder, Ollama doesn't require API key
base_url=os.getenv("OLLAMA_ENDPOINT"),
model_id=os.getenv("OLLAMA_MODEL"),
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -27,6 +27,7 @@ This folder contains examples demonstrating different ways to create and use age
| [`openai_responses_client_image_generation.py`](openai_responses_client_image_generation.py) | Demonstrates how to use image generation capabilities with OpenAI agents to create images based on text descriptions. Requires PIL (Pillow) for image display. |
| [`openai_responses_client_reasoning.py`](openai_responses_client_reasoning.py) | Demonstrates how to use reasoning capabilities with OpenAI agents, showing how the agent can provide detailed reasoning for its responses. |
| [`openai_responses_client_streaming_image_generation.py`](openai_responses_client_streaming_image_generation.py) | Demonstrates streaming image generation with partial images for real-time image creation feedback and improved user experience. |
| [`openai_responses_client_with_agent_as_tool.py`](openai_responses_client_with_agent_as_tool.py) | Shows how to use the agent-as-tool pattern with OpenAI Responses Client, where one agent delegates work to specialized sub-agents wrapped as tools using `as_tool()`. Demonstrates hierarchical agent architectures. |
| [`openai_responses_client_with_code_interpreter.py`](openai_responses_client_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with OpenAI agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`openai_responses_client_with_explicit_settings.py`](openai_responses_client_with_explicit_settings.py) | Shows how to initialize an agent with a specific responses client, configuring settings explicitly including API key and model ID. |
| [`openai_responses_client_with_file_search.py`](openai_responses_client_with_file_search.py) | Demonstrates how to use file search capabilities with OpenAI agents, allowing the agent to search through uploaded files to answer questions. |
@@ -59,13 +59,14 @@ async def main() -> None:
result1 = await agent.run(query1)
if isinstance(result1.value, WeatherInfo):
weather = result1.value
if weather := result1.try_parse_value(WeatherInfo):
print("Agent:")
print(f" Location: {weather.location}")
print(f" Temperature: {weather.temperature}")
print(f" Conditions: {weather.conditions}")
print(f" Recommendation: {weather.recommendation}")
else:
print(f"Failed to parse response: {result1.text}")
# Request 2: Override response_format at runtime with CityInfo
print("\n--- Request 2: Runtime override with CityInfo ---")
@@ -74,12 +75,13 @@ async def main() -> None:
result2 = await agent.run(query2, options={"response_format": CityInfo})
if isinstance(result2.value, CityInfo):
city = result2.value
if city := result2.try_parse_value(CityInfo):
print("Agent:")
print(f" City: {city.city_name}")
print(f" Population: {city.population}")
print(f" Country: {city.country}")
else:
print(f"Failed to parse response: {result2.text}")
finally:
await client.beta.assistants.delete(agent.id)
@@ -26,7 +26,7 @@ async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -42,7 +42,7 @@ async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -30,7 +30,7 @@ async def main() -> None:
agent = OpenAIChatClient(
model_id=os.environ["OPENAI_CHAT_MODEL_ID"],
api_key=os.environ["OPENAI_API_KEY"],
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -55,7 +55,7 @@ async def mcp_tools_on_agent_level() -> None:
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
# The agent will connect to the MCP server through its context manager.
async with OpenAIChatClient().create_agent(
async with OpenAIChatClient().as_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
@@ -32,7 +32,7 @@ runtime_schema = {
async def non_streaming_example() -> None:
print("=== Non-streaming runtime JSON schema example ===")
agent = OpenAIChatClient[OpenAIChatOptions]().create_agent(
agent = OpenAIChatClient[OpenAIChatOptions]().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -65,7 +65,7 @@ async def non_streaming_example() -> None:
async def streaming_example() -> None:
print("=== Streaming runtime JSON schema example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -17,7 +17,7 @@ async def main():
print("=== OpenAI Responses Agent with Image Analysis ===")
# 1. Create an OpenAI Responses agent with vision capabilities
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="VisionAgent",
instructions="You are a helpful agent that can analyze images.",
)
@@ -48,7 +48,7 @@ async def main() -> None:
print("=== OpenAI Responses Image Generation Agent Example ===")
# Create an agent with customized image generation options
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
instructions="You are a helpful AI that can generate images.",
tools=[
HostedImageGenerationTool(
@@ -19,7 +19,7 @@ In this case they are here: https://platform.openai.com/docs/api-reference/respo
"""
agent = OpenAIResponsesClient[OpenAIResponsesOptions](model_id="gpt-5").create_agent(
agent = OpenAIResponsesClient[OpenAIResponsesOptions](model_id="gpt-5").as_agent(
name="MathHelper",
instructions="You are a personal math tutor. When asked a math question, "
"reason over how best to approach the problem and share your thought process.",
@@ -66,7 +66,7 @@ async def streaming_reasoning_example() -> None:
usage = content
print("\n")
if usage:
print(f"Usage: {usage.details}")
print(f"Usage: {usage.usage_details}")
async def main() -> None:
@@ -42,7 +42,7 @@ async def main():
print("=== OpenAI Streaming Image Generation Example ===\n")
# Create agent with streaming image generation enabled
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
instructions="You are a helpful agent that can generate images.",
tools=[
HostedImageGenerationTool(
@@ -0,0 +1,67 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from collections.abc import Awaitable, Callable
from agent_framework import FunctionInvocationContext
from agent_framework.openai import OpenAIResponsesClient
"""
OpenAI Responses Client Agent-as-Tool Example
Demonstrates hierarchical agent architectures where one agent delegates
work to specialized sub-agents wrapped as tools using as_tool().
This pattern is useful when you want a coordinator agent to orchestrate
multiple specialized agents, each focusing on specific tasks.
"""
async def logging_middleware(
context: FunctionInvocationContext,
next: Callable[[FunctionInvocationContext], Awaitable[None]],
) -> None:
"""Middleware that logs tool invocations to show the delegation flow."""
print(f"[Calling tool: {context.function.name}]")
print(f"[Request: {context.arguments}]")
await next(context)
print(f"[Response: {context.result}]")
async def main() -> None:
print("=== OpenAI Responses Client Agent-as-Tool Pattern ===")
client = OpenAIResponsesClient()
# Create a specialized writer agent
writer = client.as_agent(
name="WriterAgent",
instructions="You are a creative writer. Write short, engaging content.",
)
# Convert writer agent to a tool using as_tool()
writer_tool = writer.as_tool(
name="creative_writer",
description="Generate creative content like taglines, slogans, or short copy",
arg_name="request",
arg_description="What to write",
)
# Create coordinator agent with writer as a tool
coordinator = client.as_agent(
name="CoordinatorAgent",
instructions="You coordinate with specialized agents. Delegate writing tasks to the creative_writer tool.",
tools=[writer_tool],
middleware=[logging_middleware],
)
query = "Create a tagline for a coffee shop"
print(f"User: {query}")
result = await coordinator.run(query)
print(f"Coordinator: {result}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -30,7 +30,7 @@ async def main() -> None:
agent = OpenAIResponsesClient(
model_id=os.environ["OPENAI_RESPONSES_MODEL_ID"],
api_key=os.environ["OPENAI_API_KEY"],
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -32,7 +32,7 @@ runtime_schema = {
async def non_streaming_example() -> None:
print("=== Non-streaming runtime JSON schema example ===")
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -65,7 +65,7 @@ async def non_streaming_example() -> None:
async def streaming_example() -> None:
print("=== Streaming runtime JSON schema example ===")
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -25,7 +25,7 @@ async def non_streaming_example() -> None:
print("=== Non-streaming example ===")
# Create an OpenAI Responses agent
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="CityAgent",
instructions="You are a helpful agent that describes cities in a structured format.",
)
@@ -37,21 +37,20 @@ async def non_streaming_example() -> None:
# Get structured response from the agent using response_format parameter
result = await agent.run(query, options={"response_format": OutputStruct})
# Access the structured output directly from the response value
if result.value:
structured_data: OutputStruct = result.value # type: ignore
print("Structured Output Agent (from result.value):")
# Access the structured output using try_parse_value for safe parsing
if structured_data := result.try_parse_value(OutputStruct):
print("Structured Output Agent (from result.try_parse_value):")
print(f"City: {structured_data.city}")
print(f"Description: {structured_data.description}")
else:
print("Error: No structured data found in result.value")
print(f"Failed to parse response: {result.text}")
async def streaming_example() -> None:
print("=== Streaming example ===")
# Create an OpenAI Responses agent
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="CityAgent",
instructions="You are a helpful agent that describes cities in a structured format.",
)
@@ -67,14 +66,13 @@ async def streaming_example() -> None:
output_format_type=OutputStruct,
)
# Access the structured output directly from the response value
if result.value:
structured_data: OutputStruct = result.value # type: ignore
# Access the structured output using try_parse_value for safe parsing
if structured_data := result.try_parse_value(OutputStruct):
print("Structured Output (from streaming with AgentResponse.from_agent_response_generator):")
print(f"City: {structured_data.city}")
print(f"Description: {structured_data.description}")
else:
print("Error: No structured data found in result.value")
print(f"Failed to parse response: {result.text}")
async def main() -> None:
@@ -16,7 +16,7 @@ from azure.identity import AzureCliCredential
def _create_agent() -> Any:
"""Create the Joker agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
@@ -52,13 +52,13 @@ def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> dict[str,
# 1. Create multiple agents, each with its own instruction set and tools.
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
weather_agent = chat_client.create_agent(
weather_agent = chat_client.as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant. Provide current weather information.",
tools=[get_weather],
)
math_agent = chat_client.create_agent(
math_agent = chat_client.as_agent(
name="MathAgent",
instructions="You are a helpful math assistant. Help users with calculations like tip calculations.",
tools=[calculate_tip],
@@ -29,7 +29,6 @@ from agent_framework.azure import (
AzureOpenAIChatClient,
)
from azure.identity import AzureCliCredential
from redis_stream_response_handler import RedisStreamResponseHandler, StreamChunk
from tools import get_local_events, get_weather_forecast
@@ -152,7 +151,7 @@ redis_callback = RedisStreamCallback()
# Create the travel planner agent
def create_travel_agent():
"""Create the TravelPlanner agent with tools."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="TravelPlanner",
instructions="""You are an expert travel planner who creates detailed, personalized travel itineraries.
When asked to plan a trip, you should:
@@ -292,24 +291,21 @@ def _format_chunk(chunk: StreamChunk, use_sse_format: bool) -> str:
"""Format a text chunk."""
if use_sse_format:
return _format_sse_event("message", chunk.text, chunk.entry_id)
else:
return chunk.text
return chunk.text
def _format_end_of_stream(entry_id: str, use_sse_format: bool) -> str:
"""Format end-of-stream marker."""
if use_sse_format:
return _format_sse_event("done", "[DONE]", entry_id)
else:
return "\n"
return "\n"
def _format_error(error: str, use_sse_format: bool) -> str:
"""Format error message."""
if use_sse_format:
return _format_sse_event("error", error, None)
else:
return f"\n[Error: {error}]\n"
return f"\n[Error: {error}]\n"
def _format_sse_event(event_type: str, data: str, event_id: str | None = None) -> str:
@@ -33,7 +33,7 @@ def _create_writer_agent() -> Any:
"when given an improved sentence you polish it further."
)
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WRITER_AGENT_NAME,
instructions=instructions,
)
@@ -30,12 +30,12 @@ CHEMIST_AGENT_NAME = "ChemistAgent"
def _create_agents() -> list[Any]:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
physicist = chat_client.create_agent(
physicist = chat_client.as_agent(
name=PHYSICIST_AGENT_NAME,
instructions="You are an expert in physics. You answer questions from a physics perspective.",
)
chemist = chat_client.create_agent(
chemist = chat_client.as_agent(
name=CHEMIST_AGENT_NAME,
instructions="You are an expert in chemistry. You answer questions from a chemistry perspective.",
)
@@ -12,7 +12,7 @@ Functions host."""
import json
import logging
from collections.abc import Generator, Mapping
from typing import Any, cast
from typing import Any
import azure.functions as func
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
@@ -45,12 +45,12 @@ class EmailPayload(BaseModel):
def _create_agents() -> list[Any]:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
spam_agent = chat_client.create_agent(
spam_agent = chat_client.as_agent(
name=SPAM_AGENT_NAME,
instructions="You are a spam detection assistant that identifies spam emails.",
)
email_agent = chat_client.create_agent(
email_agent = chat_client.as_agent(
name=EMAIL_AGENT_NAME,
instructions="You are an email assistant that helps users draft responses to emails with professionalism.",
)
@@ -102,7 +102,9 @@ def spam_detection_orchestration(context: DurableOrchestrationContext) -> Genera
options={"response_format": SpamDetectionResult},
)
spam_result = cast(SpamDetectionResult, spam_result_raw.value)
spam_result = spam_result_raw.try_parse_value(SpamDetectionResult)
if spam_result is None:
raise ValueError("Failed to parse spam detection result")
if spam_result.is_spam:
result = yield context.call_activity("handle_spam_email", spam_result.reason) # type: ignore[misc]
@@ -123,7 +125,9 @@ def spam_detection_orchestration(context: DurableOrchestrationContext) -> Genera
options={"response_format": EmailResponse},
)
email_result = cast(EmailResponse, email_result_raw.value)
email_result = email_result_raw.try_parse_value(EmailResponse)
if email_result is None:
raise ValueError("Failed to parse email response")
result = yield context.call_activity("send_email", email_result.response) # type: ignore[misc]
return result
@@ -51,7 +51,7 @@ def _create_writer_agent() -> Any:
"Return your response as JSON with 'title' and 'content' fields."
)
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WRITER_AGENT_NAME,
instructions=instructions,
)
@@ -103,7 +103,7 @@ def content_generation_hitl_orchestration(context: DurableOrchestrationContext)
content = initial_raw.value
if content is None or not isinstance(content, GeneratedContent):
if content is None:
raise ValueError("Agent returned no content after extraction.")
attempt = 0
@@ -152,11 +152,9 @@ def content_generation_hitl_orchestration(context: DurableOrchestrationContext)
options={"response_format": GeneratedContent},
)
rewritten_value = rewritten_raw.value
if rewritten_value is None or not isinstance(rewritten_value, GeneratedContent):
content = rewritten_raw.try_parse_value(GeneratedContent)
if content is None:
raise ValueError("Agent returned no content after rewrite.")
content = rewritten_value
else:
context.set_custom_status(
f"Human approval timed out after {payload.approval_timeout_hours} hour(s). Treating as rejection."
@@ -145,17 +145,17 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
chat_client = AzureOpenAIChatClient()
# Define agents with different roles
joker_agent = chat_client.create_agent(
joker_agent = chat_client.as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
stock_agent = chat_client.create_agent(
stock_agent = chat_client.as_agent(
name="StockAdvisor",
instructions="Check stock prices.",
)
plant_agent = chat_client.create_agent(
plant_agent = chat_client.as_agent(
name="PlantAdvisor",
instructions="Recommend plants.",
description="Get plant recommendations.",
@@ -30,19 +30,19 @@ chat_client = AzureOpenAIChatClient()
# Define three AI agents with different roles
# Agent 1: Joker - HTTP trigger only (default)
agent1 = chat_client.create_agent(
agent1 = chat_client.as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
# Agent 2: StockAdvisor - MCP tool trigger only
agent2 = chat_client.create_agent(
agent2 = chat_client.as_agent(
name="StockAdvisor",
instructions="Check stock prices.",
)
# Agent 3: PlantAdvisor - Both HTTP and MCP tool triggers
agent3 = chat_client.create_agent(
agent3 = chat_client.as_agent(
name="PlantAdvisor",
instructions="Recommend plants.",
description="Get plant recommendations.",
@@ -44,11 +44,16 @@ async def main() -> None:
client.get_streaming_response(message, tools=get_weather, options={"response_format": OutputStruct}),
output_format_type=OutputStruct,
)
print(f"Assistant: {response.value}")
if result := response.try_parse_value(OutputStruct):
print(f"Assistant: {result}")
else:
print(f"Assistant: {response.text}")
else:
response = await client.get_response(message, tools=get_weather, options={"response_format": OutputStruct})
print(f"Assistant: {response.value}")
if result := response.try_parse_value(OutputStruct):
print(f"Assistant: {result}")
else:
print(f"Assistant: {response.text}")
if __name__ == "__main__":
@@ -32,7 +32,7 @@ async def main() -> None:
# For Mem0 authentication, set Mem0 API key via "api_key" parameter or MEM0_API_KEY environment variable.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="FriendlyAssistant",
instructions="You are a friendly assistant.",
tools=retrieve_company_report,
@@ -35,7 +35,7 @@ async def main() -> None:
local_mem0_client = AsyncMemory()
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="FriendlyAssistant",
instructions="You are a friendly assistant.",
tools=retrieve_company_report,
@@ -27,7 +27,7 @@ async def example_global_thread_scope() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="GlobalMemoryAssistant",
instructions="You are an assistant that remembers user preferences across conversations.",
tools=get_user_preferences,
@@ -65,7 +65,7 @@ async def example_per_operation_thread_scope() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="ScopedMemoryAssistant",
instructions="You are an assistant with thread-scoped memory.",
tools=get_user_preferences,
@@ -113,14 +113,14 @@ async def example_multiple_agents() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="PersonalAssistant",
instructions="You are a personal assistant that helps with personal tasks.",
context_provider=Mem0Provider(
agent_id=agent_id_1,
),
) as personal_agent,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WorkAssistant",
instructions="You are a work assistant that helps with professional tasks.",
context_provider=Mem0Provider(
@@ -77,7 +77,7 @@ async def main() -> None:
client = OpenAIChatClient()
# Create agent with Azure Redis store
agent = client.create_agent(
agent = client.as_agent(
name="AzureRedisAssistant",
instructions="You are a helpful assistant.",
chat_message_store_factory=chat_message_store_factory,
@@ -178,7 +178,7 @@ async def main() -> None:
client = OpenAIChatClient(model_id=os.getenv("OPENAI_CHAT_MODEL_ID"), api_key=os.getenv("OPENAI_API_KEY"))
# Create agent wired to the Redis context provider. The provider automatically
# persists conversational details and surfaces relevant context on each turn.
agent = client.create_agent(
agent = client.as_agent(
name="MemoryEnhancedAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -220,7 +220,7 @@ async def main() -> None:
# Create agent exposing the flight search tool. Tool outputs are captured by the
# provider and become retrievable context for later turns.
client = OpenAIChatClient(model_id=os.getenv("OPENAI_CHAT_MODEL_ID"), api_key=os.getenv("OPENAI_API_KEY"))
agent = client.create_agent(
agent = client.as_agent(
name="MemoryEnhancedAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -63,7 +63,7 @@ async def main() -> None:
client = OpenAIChatClient(model_id=os.getenv("OPENAI_CHAT_MODEL_ID"), api_key=os.getenv("OPENAI_API_KEY"))
# Create agent wired to the Redis context provider. The provider automatically
# persists conversational details and surfaces relevant context on each turn.
agent = client.create_agent(
agent = client.as_agent(
name="MemoryEnhancedAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -63,7 +63,7 @@ async def example_global_thread_scope() -> None:
scope_to_per_operation_thread_id=False, # Share memories across all threads
)
agent = client.create_agent(
agent = client.as_agent(
name="GlobalMemoryAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -125,7 +125,7 @@ async def example_per_operation_thread_scope() -> None:
vector_distance_metric="cosine",
)
agent = client.create_agent(
agent = client.as_agent(
name="ScopedMemoryAssistant",
instructions="You are an assistant with thread-scoped memory.",
context_provider=provider,
@@ -190,7 +190,7 @@ async def example_multiple_agents() -> None:
vector_distance_metric="cosine",
)
personal_agent = client.create_agent(
personal_agent = client.as_agent(
name="PersonalAssistant",
instructions="You are a personal assistant that helps with personal tasks.",
context_provider=personal_provider,
@@ -208,7 +208,7 @@ async def example_multiple_agents() -> None:
vector_distance_metric="cosine",
)
work_agent = client.create_agent(
work_agent = client.as_agent(
name="WorkAssistant",
instructions="You are a work assistant that helps with professional tasks.",
context_provider=work_provider,
@@ -52,11 +52,11 @@ class UserInfoMemory(ContextProvider):
)
# Update user info with extracted data
if result.value and isinstance(result.value, UserInfo):
if self.user_info.name is None and result.value.name:
self.user_info.name = result.value.name
if self.user_info.age is None and result.value.age:
self.user_info.age = result.value.age
if extracted := result.try_parse_value(UserInfo):
if self.user_info.name is None and extracted.name:
self.user_info.name = extracted.name
if self.user_info.age is None and extracted.age:
self.user_info.age = extracted.age
except Exception:
pass # Failed to extract, continue without updating
@@ -20,7 +20,11 @@ async def main():
agent = AgentFactory(client_kwargs={"credential": AzureCliCredential()}).create_agent_from_yaml(yaml_str)
# use the agent
response = await agent.run("Why is the sky blue, answer in Dutch?")
print("Agent response:", response.value.model_dump_json(indent=2))
# Use try_parse_value() for safe parsing - returns None if no response_format or parsing fails
if parsed := response.try_parse_value():
print("Agent response:", parsed.model_dump_json(indent=2))
else:
print("Agent response:", response.text)
if __name__ == "__main__":
@@ -0,0 +1,161 @@
# Copyright (c) Microsoft. All rights reserved.
"""
MCP Tool via YAML Declaration
This sample demonstrates how to create agents with MCP (Model Context Protocol)
tools using YAML declarations and the declarative AgentFactory.
Key Features Demonstrated:
1. Loading agent definitions from YAML using AgentFactory
2. Configuring MCP tools with different authentication methods:
- API key authentication (OpenAI.Responses provider)
- Azure AI Foundry connection references (AzureAI.ProjectProvider)
Authentication Options:
- OpenAI.Responses: Supports inline API key auth via headers
- AzureAI.ProjectProvider: Uses Foundry connections for secure credential storage
(no secrets passed in API calls - connection name references pre-configured auth)
Prerequisites:
- `pip install agent-framework-openai agent-framework-declarative --pre`
- For OpenAI example: Set OPENAI_API_KEY and GITHUB_PAT environment variables
- For Azure AI example: Set up a Foundry connection in your Azure AI project
"""
import asyncio
from agent_framework.declarative import AgentFactory
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Example 1: OpenAI.Responses with API key authentication
# Uses inline API key - suitable for OpenAI provider which supports headers
YAML_OPENAI_WITH_API_KEY = """
kind: Prompt
name: GitHubAgent
displayName: GitHub Assistant
description: An agent that can interact with GitHub using the MCP protocol
instructions: |
You are a helpful assistant that can interact with GitHub.
You can search for repositories, read file contents, and check issues.
Always be clear about what operations you're performing.
model:
id: gpt-4o
provider: OpenAI.Responses # Uses OpenAI's Responses API (requires OPENAI_API_KEY env var)
tools:
- kind: mcp
name: github-mcp
description: GitHub MCP tool for repository operations
url: https://api.githubcopilot.com/mcp/
connection:
kind: key
apiKey: =Env.GITHUB_PAT # PowerFx syntax to read from environment variable
approvalMode: never
allowedTools:
- get_file_contents
- get_me
- search_repositories
- search_code
- list_issues
"""
# Example 2: Azure AI with Foundry connection reference
# No secrets in YAML - references a pre-configured Foundry connection by name
# The connection stores credentials securely in Azure AI Foundry
YAML_AZURE_AI_WITH_FOUNDRY_CONNECTION = """
kind: Prompt
name: GitHubAgent
displayName: GitHub Assistant
description: An agent that can interact with GitHub using the MCP protocol
instructions: |
You are a helpful assistant that can interact with GitHub.
You can search for repositories, read file contents, and check issues.
Always be clear about what operations you're performing.
model:
id: gpt-4o
provider: AzureAI.ProjectProvider
tools:
- kind: mcp
name: github-mcp
description: GitHub MCP tool for repository operations
url: https://api.githubcopilot.com/mcp/
connection:
kind: remote
authenticationMode: oauth
name: github-mcp-oauth-connection # References a Foundry connection
approvalMode: never
allowedTools:
- get_file_contents
- get_me
- search_repositories
- search_code
- list_issues
"""
async def run_openai_example():
"""Run the OpenAI.Responses example with API key auth."""
print("=" * 60)
print("Example 1: OpenAI.Responses with API Key Authentication")
print("=" * 60)
factory = AgentFactory(
safe_mode=False, # Allow PowerFx env var resolution (=Env.VAR_NAME)
)
print("\nCreating agent from YAML definition...")
agent = factory.create_agent_from_yaml(YAML_OPENAI_WITH_API_KEY)
async with agent:
query = "What is my GitHub username?"
print(f"\nUser: {query}")
response = await agent.run(query)
print(f"\nAgent: {response.text}")
async def run_azure_ai_example():
"""Run the Azure AI example with Foundry connection.
Prerequisites:
1. Create a Foundry connection named 'github-mcp-oauth-connection' in your
Azure AI project with OAuth credentials for GitHub
2. Set PROJECT_ENDPOINT environment variable to your Azure AI project endpoint
"""
print("=" * 60)
print("Example 2: Azure AI with Foundry Connection Reference")
print("=" * 60)
from azure.identity import DefaultAzureCredential
factory = AgentFactory(client_kwargs={"credential": DefaultAzureCredential()})
print("\nCreating agent from YAML definition...")
# Use async method for provider-based agent creation
agent = await factory.create_agent_from_yaml_async(YAML_AZURE_AI_WITH_FOUNDRY_CONNECTION)
async with agent:
query = "What is my GitHub username?"
print(f"\nUser: {query}")
response = await agent.run(query)
print(f"\nAgent: {response.text}")
async def main():
"""Run the MCP tool examples."""
# Run the OpenAI example
await run_openai_example()
# Run the Azure AI example (uncomment to run)
# Requires: Foundry connection set up and PROJECT_ENDPOINT env var
# await run_azure_ai_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -19,7 +19,11 @@ async def main():
agent = AgentFactory().create_agent_from_yaml(yaml_str)
# use the agent
response = await agent.run("Why is the sky blue, answer in Dutch?")
print("Agent response:", response.value)
# Use try_parse_value() for safe parsing - returns None if no response_format or parsing fails
if parsed := response.try_parse_value():
print("Agent response:", parsed)
else:
print("Agent response:", response.text)
if __name__ == "__main__":
@@ -62,7 +62,7 @@ def is_approved(message: Any) -> bool:
chat_client = AzureOpenAIChatClient(api_key=os.environ.get("AZURE_OPENAI_API_KEY", ""))
# Create Writer agent - generates content
writer = chat_client.create_agent(
writer = chat_client.as_agent(
name="Writer",
instructions=(
"You are an excellent content writer. "
@@ -72,7 +72,7 @@ writer = chat_client.create_agent(
)
# Create Reviewer agent - evaluates and provides structured feedback
reviewer = chat_client.create_agent(
reviewer = chat_client.as_agent(
name="Reviewer",
instructions=(
"You are an expert content reviewer. "
@@ -90,7 +90,7 @@ reviewer = chat_client.create_agent(
)
# Create Editor agent - improves content based on feedback
editor = chat_client.create_agent(
editor = chat_client.as_agent(
name="Editor",
instructions=(
"You are a skilled editor. "
@@ -101,7 +101,7 @@ editor = chat_client.create_agent(
)
# Create Publisher agent - formats content for publication
publisher = chat_client.create_agent(
publisher = chat_client.as_agent(
name="Publisher",
instructions=(
"You are a publishing agent. "
@@ -111,7 +111,7 @@ publisher = chat_client.create_agent(
)
# Create Summarizer agent - creates final publication report
summarizer = chat_client.create_agent(
summarizer = chat_client.as_agent(
name="Summarizer",
instructions=(
"You are a summarizer agent. "
@@ -13,6 +13,7 @@ import asyncio
import logging
import os
from agent_framework import ChatAgent
from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentWorker
from azure.identity import AzureCliCredential, DefaultAzureCredential
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
@@ -22,13 +23,13 @@ logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
def create_joker_agent():
def create_joker_agent() -> ChatAgent:
"""Create the Joker agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Joker agent
ChatAgent: The configured Joker agent
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
@@ -62,9 +62,9 @@ def create_weather_agent():
"""Create the Weather agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Weather agent with weather tool
ChatAgent: The configured Weather agent with weather tool
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WEATHER_AGENT_NAME,
instructions="You are a helpful weather assistant. Provide current weather information.",
tools=[get_weather],
@@ -75,9 +75,9 @@ def create_math_agent():
"""Create the Math agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Math agent with calculation tools
ChatAgent: The configured Math agent with calculation tools
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=MATH_AGENT_NAME,
instructions="You are a helpful math assistant. Help users with calculations like tip calculations.",
tools=[calculate_tip],
@@ -18,7 +18,7 @@ import os
from datetime import timedelta
import redis.asyncio as aioredis
from agent_framework import AgentResponseUpdate
from agent_framework import AgentResponseUpdate, ChatAgent
from agent_framework.azure import (
AgentCallbackContext,
AgentResponseCallbackProtocol,
@@ -144,13 +144,13 @@ class RedisStreamCallback(AgentResponseCallbackProtocol):
logger.error(f"Error writing end-of-stream marker: {ex}", exc_info=True)
def create_travel_agent():
def create_travel_agent() -> "ChatAgent":
"""Create the TravelPlanner agent using Azure OpenAI.
Returns:
AgentProtocol: The configured TravelPlanner agent with travel planning tools.
ChatAgent: The configured TravelPlanner agent with travel planning tools.
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="TravelPlanner",
instructions="""You are an expert travel planner who creates detailed, personalized travel itineraries.
When asked to plan a trip, you should:
@@ -15,7 +15,7 @@ from collections.abc import Generator
import logging
import os
from agent_framework import AgentResponse
from agent_framework import AgentResponse, ChatAgent
from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker
from azure.identity import AzureCliCredential, DefaultAzureCredential
from durabletask.task import OrchestrationContext, Task
@@ -29,21 +29,21 @@ logger = logging.getLogger(__name__)
WRITER_AGENT_NAME = "WriterAgent"
def create_writer_agent():
def create_writer_agent() -> "ChatAgent":
"""Create the Writer agent using Azure OpenAI.
This agent refines short pieces of text, enhancing initial sentences
and polishing improved versions further.
Returns:
AgentProtocol: The configured Writer agent
ChatAgent: The configured Writer agent
"""
instructions = (
"You refine short pieces of text. When given an initial sentence you enhance it;\n"
"when given an improved sentence you polish it further."
)
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WRITER_AGENT_NAME,
instructions=instructions,
)
@@ -16,7 +16,7 @@ import logging
import os
from typing import Any
from agent_framework import AgentResponse
from agent_framework import AgentResponse, ChatAgent
from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker
from azure.identity import AzureCliCredential, DefaultAzureCredential
from durabletask.task import OrchestrationContext, when_all, Task
@@ -31,25 +31,25 @@ PHYSICIST_AGENT_NAME = "PhysicistAgent"
CHEMIST_AGENT_NAME = "ChemistAgent"
def create_physicist_agent():
def create_physicist_agent() -> "ChatAgent":
"""Create the Physicist agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Physicist agent
ChatAgent: The configured Physicist agent
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=PHYSICIST_AGENT_NAME,
instructions="You are an expert in physics. You answer questions from a physics perspective.",
)
def create_chemist_agent():
def create_chemist_agent() -> "ChatAgent":
"""Create the Chemist agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Chemist agent
ChatAgent: The configured Chemist agent
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=CHEMIST_AGENT_NAME,
instructions="You are an expert in chemistry. You answer questions from a chemistry perspective.",
)
@@ -16,7 +16,7 @@ import logging
import os
from typing import Any, cast
from agent_framework import AgentResponse
from agent_framework import AgentResponse, ChatAgent
from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker
from azure.identity import AzureCliCredential, DefaultAzureCredential
from durabletask.task import ActivityContext, OrchestrationContext, Task
@@ -49,25 +49,25 @@ class EmailPayload(BaseModel):
email_content: str
def create_spam_agent():
def create_spam_agent() -> "ChatAgent":
"""Create the Spam Detection agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Spam Detection agent
ChatAgent: The configured Spam Detection agent
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=SPAM_AGENT_NAME,
instructions="You are a spam detection assistant that identifies spam emails.",
)
def create_email_agent():
def create_email_agent() -> "ChatAgent":
"""Create the Email Assistant agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Email Assistant agent
ChatAgent: The configured Email Assistant agent
"""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=EMAIL_AGENT_NAME,
instructions="You are an email assistant that helps users draft responses to emails with professionalism.",
)
@@ -17,7 +17,7 @@ import logging
import os
from typing import Any, cast
from agent_framework import AgentResponse
from agent_framework import AgentResponse, ChatAgent
from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker
from azure.identity import AzureCliCredential, DefaultAzureCredential
from durabletask.task import ActivityContext, OrchestrationContext, Task, when_any # type: ignore
@@ -52,11 +52,11 @@ class HumanApproval(BaseModel):
feedback: str = ""
def create_writer_agent():
def create_writer_agent() -> "ChatAgent":
"""Create the Writer agent using Azure OpenAI.
Returns:
AgentProtocol: The configured Writer agent
ChatAgent: The configured Writer agent
"""
instructions = (
"You are a professional content writer who creates high-quality articles on various topics. "
@@ -65,7 +65,7 @@ def create_writer_agent():
"Limit response to 300 words or less."
)
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WRITER_AGENT_NAME,
instructions=instructions,
)
@@ -7,6 +7,7 @@ This directory contains samples for durable agent hosting using the Durable Task
### Basic Patterns
- **[01_single_agent](01_single_agent/)**: Host a single conversational agent and interact with it via a client. Demonstrates basic worker-client architecture and agent state management.
- **[02_multi_agent](02_multi_agent/)**: Host multiple domain-specific agents (physicist and chemist) and route requests to the appropriate agent based on the question topic.
- **[03_single_agent_streaming](03_single_agent_streaming/)**: Enable reliable, resumable streaming using Redis Streams with agent response callbacks. Demonstrates non-blocking agent execution and cursor-based resumption for disconnected clients.
### Orchestration Patterns
- **[04_single_agent_orchestration_chaining](04_single_agent_orchestration_chaining/)**: Chain multiple invocations of the same agent using durable orchestration, preserving conversation context across sequential runs.
@@ -113,7 +113,7 @@ async def main() -> None:
credential = AzureCliCredential()
# 2. Create agent inline
agent = AzureOpenAIChatClient(credential=credential).create_agent(
agent = AzureOpenAIChatClient(credential=credential).as_agent(
model="gpt-4o",
instructions="You are a helpful financial advisor..."
)
@@ -41,7 +41,7 @@ async def main() -> None:
# Create the agent
# Constructor automatically reads from environment variables:
# AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_DEPLOYMENT_NAME, AZURE_OPENAI_API_KEY
agent = AzureOpenAIChatClient(credential=credential).create_agent(
agent = AzureOpenAIChatClient(credential=credential).as_agent(
name="FinancialAdvisor",
instructions="""You are a professional financial advisor assistant.
@@ -275,7 +275,7 @@ async def run_self_reflection_batch(
agent = AzureOpenAIChatClient(
credential=AzureCliCredential(),
deployment_name=agent_model,
).create_agent(
).as_agent(
instructions="You are a helpful agent.",
)
@@ -48,7 +48,7 @@ def get_item_price(
async def run() -> None:
# Define an agent
# Agent's name and description provide better context for AI model
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="RestaurantAgent",
description="Answer questions about the menu.",
tools=[get_specials, get_item_price],
@@ -166,7 +166,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -142,7 +142,7 @@ async def class_based_chat_middleware() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="EnhancedChatAgent",
instructions="You are a helpful AI assistant.",
# Register class-based middleware at agent level (applies to all runs)
@@ -164,7 +164,7 @@ async def function_based_chat_middleware() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="FunctionMiddlewareAgent",
instructions="You are a helpful AI assistant.",
# Register function-based middleware at agent level
@@ -194,7 +194,7 @@ async def run_level_middleware() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="RunLevelAgent",
instructions="You are a helpful AI assistant.",
tools=get_weather,
@@ -99,7 +99,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -70,7 +70,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="TimeAgent",
instructions="You are a helpful time assistant. Call get_current_time when asked about time.",
tools=get_current_time,
@@ -58,7 +58,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="DataAgent",
instructions="You are a helpful data assistant. Use the data service tool to fetch information for users.",
tools=unstable_data_service,
@@ -83,7 +83,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -110,7 +110,7 @@ async def pre_termination_middleware() -> None:
print("\n--- Example 1: Pre-termination Middleware ---")
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -137,7 +137,7 @@ async def post_termination_middleware() -> None:
print("\n--- Example 2: Post-termination Middleware ---")
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -83,7 +83,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant. Use the weather tool to get current conditions.",
tools=get_weather,
@@ -147,7 +147,7 @@ async def pattern_1_single_agent_with_closure() -> None:
client = OpenAIChatClient(model_id="gpt-4o-mini")
# Create agent with both tools and shared context via middleware
communication_agent = client.create_agent(
communication_agent = client.as_agent(
name="communication_agent",
instructions=(
"You are a communication assistant that can send emails and notifications. "
@@ -294,14 +294,14 @@ async def pattern_2_hierarchical_with_kwargs_propagation() -> None:
client = OpenAIChatClient(model_id="gpt-4o-mini")
# Create specialized sub-agents
email_agent = client.create_agent(
email_agent = client.as_agent(
name="email_agent",
instructions="You send emails using the send_email_v2 tool.",
tools=[send_email_v2],
middleware=[email_kwargs_tracker],
)
sms_agent = client.create_agent(
sms_agent = client.as_agent(
name="sms_agent",
instructions="You send SMS messages using the send_sms tool.",
tools=[send_sms],
@@ -309,7 +309,7 @@ async def pattern_2_hierarchical_with_kwargs_propagation() -> None:
)
# Create coordinator that delegates to sub-agents
coordinator = client.create_agent(
coordinator = client.as_agent(
name="coordinator",
instructions=(
"You coordinate communication tasks. "
@@ -396,7 +396,7 @@ async def pattern_3_hierarchical_with_middleware() -> None:
client = OpenAIChatClient(model_id="gpt-4o-mini")
# Sub-agent with validation middleware
protected_agent = client.create_agent(
protected_agent = client.as_agent(
name="protected_agent",
instructions="You perform protected operations that require authentication.",
tools=[protected_operation],
@@ -404,7 +404,7 @@ async def pattern_3_hierarchical_with_middleware() -> None:
)
# Coordinator delegates to protected agent
coordinator = client.create_agent(
coordinator = client.as_agent(
name="coordinator",
instructions="You coordinate protected operations. Delegate to protected_executor.",
tools=[

Some files were not shown because too many files have changed in this diff Show More