Python: Merge main into feature-durabletask-python branch (#3261)

* Python: Add factory pattern to concurrent orchestration builder (#2738)

* Add factory pattern to concurrent orchestration builder

* Update readme

* Address AI comments

* Fix unit tests

* Fix import

* Prevent multiple calls to set participants or factories

* Add comments

* Mitigate warnings

* Fix mypy

* Address comments

* Address Copilot comments

* Fix tests

* Python: fix: GroupChat ManagerSelectionResponse JSON Schema for OpenAI Structured Outpu… (#2750)

* fix: ManagerSelectionResponse JSON Schema for OpenAI Structured Output Strict Mode

* refactor: install pre-commit then commit again

* Capture file IDs from code interpreter in streaming responses (#2741)

* .NET: [BREAKING] Prevent nulls in AIAgent property (#2719)

* prevent nulls in AIAgent property

* address feedback

* code ql sm04598 (#2723)

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

* .NET: Add Conversation State Sample (Step05) (#2697)

* Initial plan

* Add Agent_OpenAI_Step05_Conversation sample for conversation state management

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

* Update Program.cs comment to accurately describe the sample

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

* Update the code to use the ConversationClient more in line with the samples in OpenAI

* Apply suggestions from code review

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

* Changing sample to use ChatClientAgent and conversationId in GetNewThread

---------

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

* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.7 to 4.0.4.11 (#2777)

---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
  dependency-version: 4.0.4.11
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Bump Azure.Identity from 1.17.0 to 1.17.1 (#2780)

---
updated-dependencies:
- dependency-name: Azure.Identity
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Azure.Identity
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Azure.Identity
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Azure.Identity
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2778)

---
updated-dependencies:
- dependency-name: Azure.AI.AgentServer.AgentFramework
  dependency-version: 1.0.0-beta.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
  dependency-version: 1.0.0-beta.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
  dependency-version: 1.0.0-beta.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Python: added more complete parsing for mcp tool arguments (#2756)

* added more complete parsing for mcp tool arguments

* fixed mypy

* added nonlocal model counter, and some fixes

* fixes in naming logic

* extracted json parsing function, added parametrized test and checked coverage

* Python: Updated package versions (#2784)

* Updated package versions

* Small fix

* Bump actions/checkout from 5 to 6 (#2404)

Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

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

* .NET: adds support for labels in edges,  fixes rendering of labels in dot a… (#1507)

* adds support for labels in edges,  fixes rendering of labels in dot and mermaid, adds rendering of labels in edges

* Update dotnet/src/Microsoft.Agents.AI.Workflows/Visualization/WorkflowVisualizer.cs

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

* escaping edge labels, adding tests for labels containing strange characters that would break the diagram and enabling the previous signature so the API has backwards compatibility.

* Unify label in EdgeData

* Edge API adjustments, removed useless "sanitizer"

* fixed test

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>

* Python: Added custom args and thread object to ai_function kwargs (#2769)

* Added an example of using kwargs in ai_function

* Added thread object to ai_function kwargs

* Updated docs

* Small fix

* Added thread parameter filtering

* Fix WorkflowAgent to include thread convo history. Enable checkpointing. (#2774)

* Update OpenAIResponses.yaml to match AgentSchema (#2598)

1. Update `connection` child types --  `kind: ApiKey` to `kind: key` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/apikeyconnection/

2.  Update `outputSchema`'s `PropertySchema` to be `kind` instead of `type` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/propertyschema/

* Python: Remove warnings from workflow builder on not using factories (#2808)

* Revert concurrent

* Fix comments

* Python: Filter framework kwargs from MCP tool invocations (#2870)

* Filter framework kwargs from MCP tool invocations

* Fixes

* Python: Fix WorkflowAgent to emit yield_output as agent response (#2866)

* Fix WorkflowAgent to emit yield_output as agent response

* use raw_representation

* Raw representation handling

* Python: Use agent description in HandoffBuilder auto-generated tools (#2713) (#2714)

## Summary
Enhanced `HandoffBuilder._apply_auto_tools` to use the target agent's
description when creating handoff tools, providing more informative tool
descriptions for LLMs.

## Changes
- Modified `_apply_auto_tools` to extract `description` from
  `AgentExecutor._agent` when available
- Updated iteration to use `.items()` for more efficient dict traversal
- Handoff tools now use agent descriptions instead of generic placeholders

## Example
Before: "Handoff to the refund_agent agent."
After: "You handle refund requests. Ask for order details and process refunds."

## Testing
- All handoff tests pass (20/20)
- No breaking changes to existing API

Fixes #2713

Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>

* Python: [BREAKING] Observability updates (#2782)

* fixes Python: Add env_file_path parameter to setup_observability() similar to AzureOpenAIChatClient
Fixes #2186

* WIP on updates using configure_azure_monitor

* improved setup and clarity

* fixed root .env.example

* revert changes

* updated files

* updated sample

* updated zero code

* test fixes and fixed links

* fix devui

* removed planning docs

* added enable method and updated readme and samples

* clarified docstring

* add return annotation

* updated naming

* update capatilized version

* updated readme and some fixes

* updated decorator name inline with the rest

* feedback from comments addressed

* Python: Fix middleware terminate flag to exit function calling loop immediately (#2868)

* Fix middleware terminate flag to exit function calling loop immediately

* Eliminating duck typing

* Improve function exec result handling

* Fix race condition

* Fix mypy issues

* Python: Fix context duplication in handoff workflows when restoring from checkpoint (#2867)

* Fix context duplication in handoff workflows when restoring from checkpoint

* Address Copilot PR review

* .NET: Update to latest Azure.AI.*, OpenAI, and M.E.AI* (#2850)

* Update to latest Azure.AI.*, OpenAI, and M.E.AI*

Absorb breaking changes in Responses surface area

* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs

* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs

* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs

* Update dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/Program.cs

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

* Using patch to remove the model is necessary, updated the response client to actually use the the ForAgent

---------

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

* Bump actions/download-artifact from 6 to 7 (#2862)

Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

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

* Bump actions/cache from 4 to 5 (#2861)

Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

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

* Bump actions/upload-artifact from 5 to 6 (#2860)

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

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

* Python : Ollama Connector for Agent Framework (#1104)

* Initial Commit for Olama Connector

* Added Olama Sample

* Add Sample & Fixed Open Telemetry

* Fixed Spelling from Olama to Ollama

* remove"opentelemetry-semantic-conventions-ai ~=0.4.13" since its handled in a different pr

* Added Tool Calling

* Finalizing test cases

* Adjust samples to be more reliable

* Update python/packages/ollama/agent_framework_ollama/_chat_client.py

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

* Update python/packages/ollama/pyproject.toml

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

* Update python/packages/ollama/tests/test_ollama_chat_client.py

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

* Update python/packages/ollama/agent_framework_ollama/_chat_client.py

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

* Improved Docstrings & Sample

* Update python/packages/ollama/agent_framework_ollama/_chat_client.py

Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>

* Integrate PR Feedback
- Divided Streaming and Non-Streaming into independent Methods
- Catch Ollama Validation Error
- Add OTEL Provider Name
- Checked Ollama Messages
- Add Usage Statistics

* Revert setting, so it can be none

* Validate Message formatting between AF and Ollama

* Catch Ollama Error and raise a ServiceResponse Error

* Fix mypy error

* remove .vscode comma

* Add Reasoning support & adjust to new structure

* Add Ollama Multimodality and Reasoning

* Add test cases for reasoning

* Add Tests for Error Handling in Ollama Client

* Update python/samples/getting_started/multimodal_input/ollama_chat_multimodal.py

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

* Integrated Copilot Feedback

* Implement first PR Feedback

* Adjust Readme files for examples

* Adjust argument passing via additional chat options

* Implemented PR Feedback

* Removing Ollama Package from Core and moving samples

* Fix Link & Adding Samples to Main Sample Readme

* Fixing Links in Readme

* Moved Multimodal and Chat Example

* Fixed Link in ChatClient to Ollama

* Fix AgentFramework Links in Ollama Project

* Fix observability breaking change

---------

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

* Skip failing IT (#2904)

* .NET: Cosmos DB UT Fast Skip (For Non-Configured Local envs) (#2906)

* Cosmos DB UT Fast Skip (Non-Configured Local envs) + Long running UT skip in pipeline when no CosmosDB changes happened

* Force a CosmosDB source code change to trigger the pipeline

* Address possible string boolean mismatch

* Add debug

* Enabling emulator always when running IT

* .NET: Add TTLs to durable agent sessions (#2679)

* .NET: Add TTLs to durable agent sessions

* Remove unnecessary async

* PR feedback: clarify UTC

* PR feedback: limit minimum signal delay to <= 5 minutes

* PR feedback: Fix TTL disablement

* Linter: use auto-property

* Fix build break from OpenAI SDK change

* Updated CHANGELOG.md

* PR feedback

* Reduce default TTL to 14 days to work around DTS bug

* Python:  Update Mem0Provider to use v2 search API `filters` parameter (#2766)

* short fix to move id parameters to filters object

* added tests

* small fix

* mem0 dependency update

* Updated package versions (#2913)

* .NET: Switch to new "Run" method name. (#2843)

* Switch to new "RunAgent" method name.

* Try to disable false positive naming warning.

* Add comment about disabled warnings.

* Rename `RunAgent` to just `Run`.

* Update CHANGELOG.

* Python: Switch to new "run" method name. (#2890)

* Switch to `run` method.

* Add support for deprecated `run_agent`.

* Fix entity method name.

* Fix method name and improve tests.

* Update comment.

* Update Python CHANGELOG.

* [BREAKING] Python: Add factory pattern to handoff orchestration builder (#2844)

* WIP: Factory pattern to handoff

* Add factory pattern to concurrent orchestration builder; Next: tests and sample verification

* Add tests and improve comments

* Fix mypy

* Simplify handoff_simple.py

* Simplify handoff_autonoumous.py and bug fix

* Update readme

* Address Copilot comments

* Python: Flow custom kwargs to agents via Workflow SharedState (#2894)

* Flow custom kwargs to agents via SharedState

* Address Copilot feedback

* Improve sample typing

* Fix test

* Fix Pydantic error when using Literal type for tool params (#2893)

* Updated Ollama package version (#2920)

* Python: Azure AI Agent with Bing Grounding Citations Sample (#2892)

* bing grounding sample with citations

* small fix

* fix

* .NET: Make DelegatingAIAgent abstract (#2797)

* Initial plan

* Make DelegatingAIAgent abstract

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

---------

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

* Added additional arguments for Azure AI agent (#2922)

* Python: Correction of MCP image type conversion in  _mcp.py (#2901)

* Correction of MCP image type conversion in  _mcp.py

* Added a new overload to the init function of the DataContent() type of the Agent Framework, edited the test case to correctly test the usage of the data and uri fields while using DataContent()

* Fixed tests related to the changes of the DataContent type, added testing for both string and byte representations

* Pass kwargs into subworkflows (#2923)

* Python: Move ollama samples to samples getting started dir (#2921)

* Move ollama samples to samples getting started dir

* Address feedback

* Python: fix: correct BadRequestError when using Pydantic model in response_fo… (#1843)

* fix: correct BadRequestError when using Pydantic model in response_format

* Fix lint

---------

Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>

* .NET: [Breaking] Delete display name property (#2758)

* delete the AIAgent.DisplayName property

* use agent name as a first value for activity display name

* Update dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs

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

---------

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

* Python: cleanup and refactoring of chat clients (#2937)

* refactoring and unifying naming schemes of internal methods of chat clients

* set tool_choice to auto

* fix for mypy

* added note on naming and fix #2951

* fix responses

* fixes in azure ai agents client

* Python: Workflow add option to visualize internal executors (#2917)

* Workflow add option to visualize internal executors

* Address Copilot comments

* Python: Fixes Run ID and Thread ID casing to align with AG-UI Typescript SDK (#2948)

* added camelCase input to run id and thread id aligning with @ag-ui/core

* fixed per copilot suggestions

* Python: Add workflow cancellation sample (#2732)

* Add workflow cancellation sample

Add sample demonstrating how to cancel a running workflow using asyncio
tasks. Shows both cancellation mid-execution and normal completion paths.
Useful for implementing timeouts, graceful shutdown, or A2A executors.

* update docstring

* .NET: Update Anthropic package to version 12.0.0 (#2914)

* Initial plan

* Update Anthropic package to version 12.0.0

Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>

---------

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

* Python: Add Azure Managed Redis Support with Credential Provider (#2887)

* azure redis support

* small fixes

* azure managed redis sample

* fixes

* Bump CommunityToolkit.Aspire.OllamaSharp from 13.0.0-beta.440 to 13.0.0 (#2856)

---
updated-dependencies:
- dependency-name: CommunityToolkit.Aspire.OllamaSharp
  dependency-version: 13.0.0
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.11 to 4.0.5 (#2853)

---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
  dependency-version: 4.0.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2854)

---
updated-dependencies:
- dependency-name: Azure.AI.AgentServer.AgentFramework
  dependency-version: 1.0.0-beta.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
  dependency-version: 1.0.0-beta.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Python: Fix WorkflowAgent event handling and kwargs forwarding (#2946)

* Fix kwargs propagation through workflow.as_agent()

* Fix WorkflowAgent to respect AgentExecutor output_response setting

* .NET: Use GrpcEntityRunner instead of TaskEntityDispatcher (#2759)

* Use GrpcEntityRunner instead of TaskEntityDispatcher

* Pin to Durable worker 1.11.0

* Set the invocation result

* Update all Durable packages

* Update changelog, rename dispatcher to encondedEntityRequest

* Python: Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG (#2968)

* Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG

* update lock

* Fix formatting

* Fix ChatKit typing

* Python: Introducing Foundry Local Chat Clients (#2915)

* redo foundry local chat client

* fix mypy and spelling

* better docstring, updated sample

* fixed tests and added tests

* small sample update

* Updated package versions (#2978)

* Python: Added GitHub MCP sample with PAT (#2967)

* added github mcp sample with PAT

* addressed copilot fixes

* env fix

* Python: Preserve reasoning blocks with OpenRouter (#2950)

* Preserve reasoning blocks with OpenRouter

* Put encrypted reasoning in TextReasoningContent

* Remove unneccessary change

* Fix docs

* Support streaming

* Fix handling None in TextReasoningContent.text

* Python: Added response.created and response.in_progress event process to OpenAIBaseResponseClient (#2975)

* added response.created and response.in_progress to include response.id

* better doc string

* added tests for the new streaming event types

* Python: Introducing support for Bedrock-hosted models (Anthropic, Cohere, etc.) (#2610)

* Pushing the bedrock related changes to the new branch after addressing the review comments

* 2524 Addressed the second round review comments

* 2524 Addressed few more minor comments on the PR

* resolving the merge conflict

* 2524 resolved the uv.lock conflicts

* 2524 addressed more comments

* 2524 removed the print statement to fix the checks failure

* 2524 resolved the CI failure issues

* 2524 fixing the CI breaks

* 2524 Addressed the review comment

* 2524 resolved conflict

---------

Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>

* .NET: [Durable Agents] Reliable streaming sample (#2942)

* .NET: [Durable Agents] Reliable streaming sample

* Add automated validation for new sample

* Address Copilot PR feedback

* Fix typo in README.md about agent definitions (#2634)

* Fix typo in README.md about agent definitions

* Update agent-samples/README.md

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

---------

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

* Python: latency improvements (#3014)

* latency improvements

* fixed mypy, added coding standards and instructions

* slight logic improvement

* Python: Updated package versions (#3024)

* Updated package versions

* Updated changelog

* Python: add powerfx safe mode (#3028)

* add powerfx safe mode

* improved docstring and aligned env_file loading

* ensured test uses reset

* .NET: [Breaking] Introduce RunCoreAsync/RunCoreStreamingAsync delegation pattern in AIAgent (#2749)

* Initial plan

* Refactor AIAgent: Make RunAsync and RunStreamingAsync non-abstract, add RunCoreAsync and RunCoreStreamingAsync

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Fix infinite recursion in test implementations

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Make RunAsync and RunStreamingAsync non-virtual as requested

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Fix DelegatingAIAgent subclasses to use RunCoreAsync/RunCoreStreamingAsync

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Fix XML documentation references in AnonymousDelegatingAIAgent

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Restore <see cref> tags with proper qualified signatures in AnonymousDelegatingAIAgent

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Rollback unnecessary XML documentation changes in AnonymousDelegatingAIAgent

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Remove pragma and update crefs to RunCoreAsync/RunCoreStreamingAsync

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Fix EntityAgentWrapper to call base.RunCoreAsync/RunCoreStreamingAsync

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* fix compilation issues

* fix compilatio issue

* fix tests

* fix unit tests

* fix unit test

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>

* add issue template and additional labeling (#3006)

* fix and extra int test (#3037)

* .NET: [BREAKING] Refactor ChatMessageStore methods to be similar to AIContextProvider and add filtering support (#2604)

* Refactor ChatMessageStore methods to be similar to AIContextProvider

* Fix file encoding

* Ensure that AIContextProvider messages area also persisted.

* Update formatting and seal context classes

* Improve formatting

* Remove optional messages from constructor and add unit test

* Add ChatMessageStore filtering via a decorator

* Update sample and cosmos message store to store AIContextProvider messages in right order. Fix unit tests.

* Update Workflowmessage store to use aicontext provider messages.

* Apply suggestions from code review

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

* Apply suggestions from code review

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

* Improve xml docs messaging

* Address code review comments.

* Also notify message store on failure

---------

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

* [BREAKING] Remove unused AgentThreadMetadata (#3067)

* Remove unused AgentThreadMetadata

* Update DurableTask Changelog

* Python: Fix AzureAIClient failure when conversation history contains assistant messages (#3076)

* Fix AzureAIClient failure when conversation history contains assistant messages

* Address PR review feedback: improve docstring and test assertions

* Remove redundant cast

* Fix: Update OTLP exporter protocol conditions (#3070)

* Python: Fix ExecutorInvokedEvent and ExecutorCompletedEvent observability data (#3090)

* Fix ExecutorInvokedEvent.data mutation bug

* Fix bug related to not yielding output type

* .NET: Seal ChatClientAgentThread (#2842)

* Initial plan

* Seal ChatClientAgentThread class

Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>

---------

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

* Fix broken strands urls. (#3102)

* Fix broken strands urls.

* Fix typos

* .NET: Fix message ordering inconsistency when using AIContextProvider (#2659)

* Initial plan

* Fix message ordering inconsistency when using AIContextProvider

Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>

* Revert to original message ordering: Input, AIContextProvider, Response

Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>

* Reorder messages to ChatClient to match MessageStore order: Existing, Input, AIContextProvider

Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>

* Remove redundant test methods as existing tests already verify the behavior

Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>

* fix: tool_choice parameter not being honored when passed to agent.run() (#3095)

* sharepoint sample fix (#3108)

* Bump versions to 1.0.0b260106 for a release. Update CHANGELOG.md (#3109)

* Bump Bedrock version to latest (#3110)

* Python: Fix MCP tool result serialization for list[TextContent] (#2523)

* Fix MCP tool result serialization for list[TextContent]

When MCP tools return results containing list[TextContent], they were
incorrectly serialized to object repr strings like:
'[<agent_framework._types.TextContent object at 0x...>]'

This fix properly extracts text content from list items by:
1. Checking if items have a 'text' attribute (TextContent)
2. Using model_dump() for items that support it
3. Falling back to str() for other types
4. Joining single items as plain text, multiple items as JSON array

Fixes #2509

* Address PR review feedback for MCP tool result serialization

- Extract serialize_content_result() to shared _utils.py
- Fix logic: use texts[0] instead of join for single item
- Add type annotation: texts: list[str] = []
- Return empty string for empty list instead of '[]'
- Move import json to file top level
- Add comprehensive unit tests for serialization

* Address PR review feedback: fix type checking and double serialization

- Add isinstance(item.text, str) check to ensure text attribute is a string
- Fix double-serialization issue by keeping model_dump results as dicts
  until final json.dumps (removes escaped JSON strings in arrays)
- Improve docstring with detailed return value documentation
- Add test for non-string text attribute handling
- Add tests for list type tool results in _events.py path

* Simplify PR: minimal changes to fix MCP tool result serialization

Addresses reviewer feedback about excessive refactoring:
- Reset _events.py to original structure
- Only add import and use serialize_content_result in one location
- All review comments addressed in serialize_content_result():
  - Added isinstance(item.text, str) check
  - Use model_dump(mode="json") to avoid double-serialization
  - Improved docstring with explicit return value documentation
  - Empty list returns "" instead of "[]"

* Refactor: Move MCP TextContent serialization to core prepare_function_call_results

Per reviewer feedback, moved the TextContent serialization logic from
ag-ui's serialize_content_result to the core package's
prepare_function_call_results function.

Changes:
- Added handling for objects with 'text' attribute (like MCP TextContent)
  in _prepare_function_call_results_as_dumpable
- Removed serialize_content_result from ag-ui/_utils.py
- Updated _events.py and _message_adapters.py to use
  prepare_function_call_results from core package
- Updated tests to match the core function's behavior

* Fix failing tests for prepare_function_call_results behavior

- test_tool_result_with_none: Update expected value to 'null' (JSON serialization of None)
- test_tool_result_with_model_dump_objects: Use Pydantic BaseModel instead of plain class

* Fix B903 linter error: Convert MockTextContent to dataclass

The ruff linter was reporting B903 (class could be dataclass or namedtuple)
for the MockTextContent test helper classes. This commit converts them to
dataclasses to satisfy the linter check.

* Python: Improve DevUI, add Context Inspector view as new tab under traces (#2742)

* Improve DevUI, add Context Inspector view as new tab under traces

* fix mypy errors

* fix: Handle stale MCP connections in DevUI executor

MCP tools can become stale when HTTP streaming responses end - the underlying
stdio streams close but `is_connected` remains True. This causes subsequent
requests to fail with `ClosedResourceError`.

Add `_ensure_mcp_connections()` to detect and reconnect stale MCP tools before
agent execution. This is a workaround for an upstream Agent Framework issue
where connection state isn't properly tracked.

Fixes MCP tools failing on second HTTP request in DevUI.

fixes  #1476 #1515 #2865

* fix #1572 report import dependency errors more clearly

* Ensure there is streaming toggle where users can select streaming vs non streaming mode in devui . Fixes .NET: [Python] DevUI tool call rendering in non-streaming mode?

* remove unused dead code

* improve ux - workflows with agents show a chat component in execution timelien, also ensure magentic final output shows correctly

* update ui build

* update devui to use instrumentation instead of tracing, other instrumentation and type/instance check fixes

* .NET: Seal factory contexts and add non JSO deserialize overloads (#3066)

* Seal factory contexts and add non JSO deserialize overloads

* Apply suggestions from code review

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

---------

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

* Enable blank issues in issue template configuration

Need to re-enable creating blank issues

* updated templates (#3106)

* updated templates

* enabled blank and fixed triage

* made language optional and moved to the bottom for features

* Python: Streaming sample for azurefunctions (#3057)

* Streaming sample for azurefunctions

* Fixed links and sample name

* Addressed feedback

* Addressed feedback

* Fixed integration tests

* Updated test

* Python: fix(azure-ai): Fix response_format handling for structured outputs (#3114)

* fix(azure-ai): read response_format from chat_options instead of run_options

* refactor: use explicit None checks for response_format

* Fix mypy error

* Mypy fix

* Python: Bump python version to 1.0.0b260107 for a release (#3128)

* Bump python version to 1.0.0b260107 for a release

* Update changelog

* Make A2AAgent public, so that it's concrete implementation methods can be used. (#3119)

* .NET: Map additional props <-> A2A metadata (#3137)

* map additional props from agent run options to a2a request metadata

* small touches

* add unit tests for new extension methods

* Sort using

* add unit test

* add additiona unit tests

* special case json element to avoid unnecessary serialization

* Python: Fix Anthropic streaming response bugs (#3141)

* test commit identity

* fix(anthropic): fix raw_representation and finish_reason in streaming

* lint fix

* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.5 to 4.0.5.1 (#2994)

---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
  dependency-version: 4.0.5.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* Bump Anthropic from 12.0.0 to 12.0.1 (#2993)

---
updated-dependencies:
- dependency-name: Anthropic
  dependency-version: 12.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* .NET: [Breaking] Prevent loss of input messages & streamed updates when resuming streaming (#2748)

* save input messages and stream updates to the continuation token to be able to use them in the last successful stream resumption call.

* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs

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

* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs

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

* Update dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs

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

* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs

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

* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs

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

* fix typo

* init continuation token from chat response

* remove unnecessary types for source generation

* remove check for continuation token passed at initial run

* remove check for continuation token pass at initial run

* centralize continuation token parsing

* update xml comments

* use readonly collection instead of enumerable

---------

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

* .NET: fix: Expose WorkflowErrorEvent as ErrorContent (#2762)

* fix: Expose WorkflowErrorEvent as ErrorContent

When hosted using .AsAgent(), Workflows were not exposing inner errors coming as Exceptions (through the WorkflowErrorEvent)

The fix is to convert their message to an ErrorContent on the way out, rather than rely on the default "empty update" to collect the raw event.

* feat: Add a way to show/suppress exception information

* Bump Microsoft.Agents.AI.Workflows from 1.0.0-preview.251125.1 to 1.0.0-preview.251219.1 (#2997)

---
updated-dependencies:
- dependency-name: Microsoft.Agents.AI.Workflows
  dependency-version: 1.0.0-preview.251219.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

* .NET: Add Run overloads to expose ChatClientAgentRunOptions in IntelliSense (#3115)

* Initial plan

* Add ChatClientAgentExtensions for improved discoverability of ChatClientAgentRunOptions

Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>

* Address code review feedback - use collection expression syntax

Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>

* Apply suggestion from @westey-m

* Fix issues with Copilot implementation

* Add additional tests for structured output overloads.

---------

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

* Python: Add tool call/result content types and update connectors and samples (#2971)

* Add new AI content types and image tool support

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Add Python content types for tool calls/results and image generation tool support

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Address review feedback for tool content and samples

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Tighten image generation typing and sample tools list

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Align image generation output typing

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Handle MCP naming, image options mapping, and connector tool content

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Allow MCP call in function approval request

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Remove raw image_generation tool remapping

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Restore Anthropic tool_use to function calls unless code execution

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Fix lint issues for hosted file docstring and MCP parsing

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Import ChatResponse types in Anthropic client

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Fix Anthropics citation type imports and MCP typing for handoff/tools

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Skip lightning tests without agentlightning and fix function call import

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* fix lint on lab package

* rebuilt anthropic parsing

* redid anthropic parsing

* typo

* updated parsing and added missing docstrings

* fix tests

* mypy fixes

* second mypy fix

* add new class to other samples

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu>

* Bump Google.GenAI from 0.6.0 to 0.9.0 (#2995)

---
updated-dependencies:
- dependency-name: Google.GenAI
  dependency-version: 0.9.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

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

* Bump js-yaml from 4.1.0 to 4.1.1 in /python/packages/devui/frontend (#3123)

Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.0 to 4.1.1.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.1.1
  dependency-type: indirect
...

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

* Updated package versions (#3144)

* .NET: Bump Microsoft.Agents.AI.OpenAI and Microsoft.Extensions.AI.OpenAI (#2996)

* Bump Microsoft.Agents.AI.OpenAI and Microsoft.Extensions.AI.OpenAI

Bumps Microsoft.Agents.AI.OpenAI from 1.0.0-preview.251125.1 to 1.0.0-preview.251219.1
Bumps Microsoft.Extensions.AI.OpenAI from 10.1.0-preview.1.25608.1 to 10.1.1-preview.1.25612.2

---
updated-dependencies:
- dependency-name: Microsoft.Agents.AI.OpenAI
  dependency-version: 1.0.0-preview.251219.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Microsoft.Extensions.AI.OpenAI
  dependency-version: 10.1.1-preview.1.25612.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Microsoft.Agents.AI.OpenAI
  dependency-version: 1.0.0-preview.251219.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: Microsoft.Extensions.AI.OpenAI
  dependency-version: 10.1.1-preview.1.25612.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

* Fixed samples

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>

* Python: fix(ag-ui): Execute tools with approval_mode, fix shared state, code cleanup  (#3079)

* fix(ag-ui): execute tools after approval in human-in-the-loop flow

* Fix shared state bug

* Bug fix finalized

* Refactoring to clean up code

* Code cleanup

* More fixes

* More code cleanup

* Add version detection in __init__.py to ruff ignore list

* Track agent name with updates for workflow agent (#3146)

* Python: Fix AzureAIClient tool call bug for AG-UI use (#3148)

* Fiz AzureAIClient tool call bug

* Address copilot feedback

* Python: multiple bug fixes (#3150)

* fix Python: kwargs are not passed to _prepare_thread_and_messages in ChatAgent.run
Fixes #3118

* fix Python: [Bug]: model_id versus model_deployment_name is confusing in Azure AI Agents
Fixes #3147

* add types

* fixed type and docstring

* fix(anthropic): fix duplicate ToolCallStartEvent in streaming tool calls (#3051)

When processing `input_json_delta` events, the Anthropic client was
passing the tool name from the previous `tool_use` event. This caused
ag-ui's `_handle_function_call_content` to emit a `ToolCallStartEvent`
for every streaming chunk (since it triggers on `if content.name:`).

This fix changes the behavior to pass an empty string for `name` in
`input_json_delta` events, matching OpenAI's behavior where streaming
argument chunks have `name=""`. The initial `tool_use` event still
provides the tool name, so only one `ToolCallStartEvent` is emitted.

Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>

* .NET: [BREAKING] Change GetNewThread and DeserializeThread to async (#3152)

* Change GetNewThread and DeserializeThread plus ChatMessageStore and AIContextProvider Factories to async

* Merge fixes

* Fix Ollama model env var in documentation (#3156)

Signed-off-by: Dina Suehiro Jones <dina.s.jones@intel.com>

* Python: Add Pydantic request model and OpenAPI tags support to AG-UI FastAPI endpoint (#2522)

* feat(ag-ui): Add Pydantic request model and OpenAPI tags support

- Add AGUIRequest Pydantic model in _types.py with field descriptions
- Update add_agent_framework_fastapi_endpoint() to accept tags parameter
- Use AGUIRequest model for automatic validation and OpenAPI schema generation
- Export AGUIRequest and DEFAULT_TAGS in __init__.py
- Update test_endpoint.py to expect 422 for invalid requests
- Add tests for OpenAPI schema, default tags, custom tags, and validation

Benefits:
- Better API documentation with complete request schema in Swagger UI
- Automatic request validation with Pydantic
- Organized endpoints under 'AG-UI' tag instead of 'default'
- Improved developer experience and type safety

Fixes #<issue-number>

* test(ag-ui): Add test for internal error handling to achieve 100% coverage

- Add test_endpoint_internal_error_handling() to cover exception handling code
- Mock copy.deepcopy to simulate internal error during default_state processing
- Add type: ignore for FastAPI tags parameter (known pyright compatibility issue)
- Achieves 100% test coverage for _endpoint.py (previously missing lines 103-105)

* .NET: Improve resolving `AITool` from DI (#3175)

* remove localagenttoolregistry

* also give the factory method API

* Python: Fix MCPStreamableHTTPTool to use new streamable_http_client API (#3088)

* Fix MCPStreamableHTTPTool to use new streamable_http_client API with proper httpx client cleanup

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Update docstring to reflect new streamable_http_client API usage

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Refactor MCPStreamableHTTPTool to accept optional http_client parameter and delegate client creation to streamable_http_client

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Update mcp package minimum version to 1.24.0 for streamable_http_client API support

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Fix critical bugs: apply headers/timeout/sse_read_timeout when creating httpx client, add version constraint <2, and properly manage client lifecycle

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Simplify implementation: remove headers/timeout/sse_read_timeout params, remove kwargs, remove close() override per feedback

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Add back **kwargs parameter for backward compatibility (accepted but not used)

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* Remove unused httpx import from test file

Note: The uv.lock file needs to be updated with 'uv sync' to reflect the mcp version constraint change (>=1.24.0,<2)

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>

* cicd fixes

* udpated samples with headers examples

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu>

* azureai direct a2a endpoint support (#3127)

* Python: [BREAKING]: removed display_name, renamed context_providers, middleware and AggregateContextProvider (#3139)

* removed display_name, renamed context_providers, middleware and AggregateContextProvider

* fixes

* fixed test

* testfix

* removed mistakenly put back test

* updated new test

* rename middlewares to middleware

* middleware fixes

* Python: MCP Improvements: improved connection loss behavior, pagination for loading and a param to control representation (#3154)

* pagination support (#2848) added a parse_tool_result param and connection loss (#2884)

* fix #3153

* improved connection handling

* improved logic

* Python: Add declarative workflow runtime (#2815)

* Further support for declarative python workflows

* Add tests. Clean up for typing and formatting

* Improvements and cleanup

* Typing cleanup. Improve docstrings

* Proper code in docstrings

* Fix malformed code-block directive in docstring

* Remove dead links

* PR feedback

* Address PR feedback

* Address PR feedback

* Remove sl

* Update devui frontend

* More cleanup

* Fix uv lock

* Skip Py 3.14 tests as powerfx doesn't support it

* Fix mypy error

* Fix for tool calls

* Removed stale docstring

* Fix lint

* Standardize on .NET namespaces. Revert DevUI changes (bring in later)

* Implement remaining items for Python declarative support to match dotnet

* point URL to agent, not to agentcard (#3176)

* Python: [BREAKING]: Introducing Options as TypedDict and Generic (#3140)

* WIP typeddict for options

* updated all clients and ChatAgents

* updated everything

* added ADR

* fix mypy

* proper typevar imports

* fixed import

* fixed other imports

* slight update in the sample

* updated from feedback

* fixes

* fixed missing covariants and test fixes

* fixed typing

* updated anthropic thinking config

* ruff fixes

* fixed int tests

* fix tests and mypy

* updated integration tests

* updated docstring and test fix

* improved options handling in obser

* mypy fix

* updated a host of integration tests

* fix tests

* bedrock fix

* [BREAKING] Python: Refactor orchestrations (#3023)

* Group chat refactoring Part 1; Next: HIL and handoff

* Add agent approval flow; next samples

* WIP: samples

* WIP: HIL samples

* Group chat HIL working; next: handoff

* Fix group chat tool approval sample

* WIP: refactor handoff; next handoff handling

* Handoff done; next handoff samples and concurrent and sequential

* Handoff samples, concurrent, and sequential done; next Magentic

* WIP: magentic; next test with samples + HIL

* Magentic Working; next fix all samples and tests

* Fix handoff samples; next tests

* WIP: fixing tests; some orchestration as agent samples are failing

* Group chat unit tests done

* Handoff  unit tests done

* Remove old orchestration_request_info and fix related tests

* Magentic unit tests done

* Fix samples

* Fix test

* Fix test 2

* mypy

* Address comments

* Update readme

* Address comments

* Address comments 2

* Replace display name

* Python: ADR for create/get agent API (#2618)

* ADR for create/get agent API

* Updated ADR with implementation options

* Small updates

* Updated decision outcome section

* Updated broken links

* Small updates

* Fixed merge conflicts

* Small fix

* Updated decision outcome section

* Small fixes

* Updated provider naming based on client SDK

* Add ignored parameter for CodeQL in workflow (#3204)

* Implement IReadOnlyList on InMemoryChatMessageStore (#3205)

* .NET: Make ChatMessageStore and AIContextProvider context props settable (#3196)

* Make ChatMessageStore and AIContextProvider context props setable

* Add validation to preserve non-null requirement of certain properties.

* Fix broken tests.

* Python: Add dependencies param to ag-ui FastAPI endpoint (#3191)

* Add dependencies param to ag-ui FastAPI endpoint

* Address Copilot feedback

* renamed all (#3207)

* Python: ADR for simplified get response (#3098)

* ADR for simplified get response

* updated some language, added agent option and code comparison

* small update in sample

* added workflows and expanded some points

* changed decision and number

* updated with stream=False default

* .NET: [Breaking] Rename`AgentRunResponse` and `AgentRunResponseUpdate` classes (#3197)

* rename AgentRunResponse and AgentRunResponseUpdate classes - part1

* rename varialbles, parameters, methods and tests

* rollback unnecessary changes

* .NET: [Breaking] Rename AgentRunResponseEvent and AgentRunUpdateEvent classes (#3214)

* rename AgentRunResponseEvent and AgentRunUpdateEvent classes

* rollback unnecessary changes

* Python: Create/Get Agent API for Azure V2 (#3059)

* Added get_agent method to Azure AI V2

* Small fixes

* Small fix

* Removed AzureAIAgentProvider

* Added create_agent method

* Small fixes

* Fixed code interpreter tool mapping

* Added agent provider for V2 client

* Updated response format handling

* Added provider example

* Fixed errors

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

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

* Small fix

* Updates from merge

* Resolved comments

* Resolved comments

---------

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

* Python: Add more specific exceptions to Workflow (#3188)

* Add more specifc workflow exceptions

* Fix tests

* AI comments

* Misc

* Python: Added AzureAI sample for downloading code interpreter generated files (#3189)

* added azure ai code interpreter file download sample

* copilot fix suggestions

* function name fixes + readme update

* small fix

* update package versions (#3223)

Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>

* Python: fix(core): correct FunctionResultContent ordering in WorkflowAgent.merge_updates (#3168)

* fix(core): simplify FunctionResultContent ordering in WorkflowAgent.merge_updates

* improve comment

* Fix name

* fix(workflows): rename WorkflowOutputEvent.source_executor_id to executor_id for API consistency (#3166)

* Python: fix(ag-ui): add MCP tool support for AG-UI approval flows (#3212)

* add MCP tool support for AG-UI approval flows

* use attribute in place of property

* Python: Properly configure structured outputs based on new options dict (#3213)

* Properly configure structured outputs based on new options dict

* Fix mypy

* .NET: Merge AgentRunOptions.AdditionalProperties into ChatOptions.AdditionalProperties (#3184)

* Merge AgentRunOptions.AdditionalProperties into ChatOptions.AdditionalProperties

* Fix namespace and typo.

* .NET: Update Google.GenAI to 0.11.0 and remove polyfill implementations (#3232)

* Initial plan

* Update Google.GenAI to 0.11.0 and remove polyfill files

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

---------

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

* .NET: [BREAKING] Renamed CreateAIAgent/GetAIAgent to AsAIAgent (#3222)

* Renamed chat client extension method

* Additional renaming

* Updated documentation

* Fixed tests

* Small fix

* Small fix

* Updated DurableAIAgent and fixed integration tests (#3241)

* Python: Create/Get Agent API for Azure V1 (#3192)

* Added provider implementation for Azure AI V1

* Small fixes

* Fixed OpenAPI example

* Fixed local MCP example

* Fixed hosted MCP example

* Fixed file search sample

* Small fixes

* Resolved comments

* Doc updates

* Bump azure-core from 1.37.0 to 1.38.0 in /python (#3209)

Bumps [azure-core](https://github.com/Azure/azure-sdk-for-python) from 1.37.0 to 1.38.0.
- [Release notes](https://github.com/Azure/azure-sdk-for-python/releases)
- [Commits](https://github.com/Azure/azure-sdk-for-python/compare/azure-core_1.37.0...azure-core_1.38.0)

---
updated-dependencies:
- dependency-name: azure-core
  dependency-version: 1.38.0
  dependency-type: indirect
...

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

* Python: Create/Get Agent API for OpenAI Assistants (#3208)

* Added provider implementation

* Added example with response format

* Small improvements

* Python: (AG-UI) Support service-managed thread on AG-UI  (#3136)

* added service thread support

* set service_thread_id to only supplied_thread_id

* uses raw_representation to extract the conversation_id

* removed accidental edit

* updated test to use raw_representation

* resolves copilot review feedback

* revert back StubAgent, since not used

* removed relative module import

* removed hasattr check per PR feedback

* Create/Get Agent API - fixes and example improvements (#3246)

* Fix merge conflicts

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Dina Suehiro Jones <dina.s.jones@intel.com>
Co-authored-by: Tao Chen <taochen@microsoft.com>
Co-authored-by: Kurt <65111699+q33566@users.noreply.github.com>
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: Korolev Dmitry <deagle.gross@gmail.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: Jose Luis Latorre Millas <joslat@gmail.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Richard Ortega <richardjortega@gmail.com>
Co-authored-by: 刘邦学AI <lbbniu@gmail.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Nico Möller <nkm-moeller@mail.de>
Co-authored-by: Chris Gillum <cgillum@microsoft.com>
Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com>
Co-authored-by: Phillip Hoff <phillip.hoff@gmail.com>
Co-authored-by: Ege Ozan Özyedek <36128615+egeozanozyedek@users.noreply.github.com>
Co-authored-by: samueljohnsiby <66901393+samueljohnsiby@users.noreply.github.com>
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
Co-authored-by: Hao Luo <338265+howlowck@users.noreply.github.com>
Co-authored-by: Victor Dibia <chuvidi2003@gmail.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: Jacob Viau <javia@microsoft.com>
Co-authored-by: SuperKenVery <39673849+SuperKenVery@users.noreply.github.com>
Co-authored-by: Sunil Dutta <dutta.2003@gmail.com>
Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>
Co-authored-by: Syrine Chelly <62653967+SyChell@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
Co-authored-by: westey <164392973+westey-m@users.noreply.github.com>
Co-authored-by: takanori-terai <123897708+takanori-terai@users.noreply.github.com>
Co-authored-by: claude89757 <138977524+claude89757@users.noreply.github.com>
Co-authored-by: Gavin Aguiar <80794152+gavin-aguiar@users.noreply.github.com>
Co-authored-by: Sukeesh <vsukeeshbabu@gmail.com>
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu>
Co-authored-by: Ao Chen <chenao3220@gmail.com>
Co-authored-by: Dina Suehiro Jones <dina.s.jones@intel.com>
This commit is contained in:
Laveesh Rohra
2026-01-16 16:59:49 -08:00
committed by GitHub
Unverified
parent 3df916064c
commit cd77193742
789 changed files with 43657 additions and 21320 deletions
@@ -3,7 +3,7 @@
import asyncio
from agent_framework import HostedMCPTool, HostedWebSearchTool, TextReasoningContent, UsageContent
from agent_framework.anthropic import AnthropicClient
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
"""
Anthropic Chat Agent Example
@@ -15,9 +15,9 @@ This sample demonstrates using Anthropic with:
"""
async def streaming_example() -> None:
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient().create_agent(
agent = AnthropicClient[AnthropicChatOptions]().create_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
@@ -27,10 +27,12 @@ async def streaming_example() -> None:
),
HostedWebSearchTool(),
],
# anthropic needs a value for the max_tokens parameter
# we set it to 1024, but you can override like this:
max_tokens=20000,
additional_chat_options={"thinking": {"type": "enabled", "budget_tokens": 10000}},
default_options={
# anthropic needs a value for the max_tokens parameter
# we set it to 1024, but you can override like this:
"max_tokens": 20000,
"thinking": {"type": "enabled", "budget_tokens": 10000},
},
)
query = "Can you compare Python decorators with C# attributes?"
@@ -48,11 +50,5 @@ async def streaming_example() -> None:
print("\n")
async def main() -> None:
print("=== Anthropic Example ===")
await streaming_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -38,10 +38,12 @@ async def main() -> None:
),
HostedWebSearchTool(),
],
# anthropic needs a value for the max_tokens parameter
# we set it to 1024, but you can override like this:
max_tokens=20000,
additional_chat_options={"thinking": {"type": "enabled", "budget_tokens": 10000}},
default_options={
# anthropic needs a value for the max_tokens parameter
# we set it to 1024, but you can override like this:
"max_tokens": 20000,
"thinking": {"type": "enabled", "budget_tokens": 10000},
},
)
query = "Can you compare Python decorators with C# attributes?"
@@ -5,7 +5,7 @@ import logging
from pathlib import Path
from agent_framework import HostedCodeInterpreterTool, HostedFileContent
from agent_framework.anthropic import AnthropicClient
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
logger = logging.getLogger(__name__)
"""
@@ -22,7 +22,7 @@ This sample demonstrates using Anthropic with:
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
client = AnthropicClient(additional_beta_flags=["skills-2025-10-02"])
client = AnthropicClient[AnthropicChatOptions](additional_beta_flags=["skills-2025-10-02"])
# List Anthropic-managed Skills
skills = await client.anthropic_client.beta.skills.list(source="anthropic", betas=["skills-2025-10-02"])
@@ -35,8 +35,8 @@ async def main() -> None:
name="DocsAgent",
instructions="You are a helpful agent for creating powerpoint presentations.",
tools=HostedCodeInterpreterTool(),
max_tokens=20000,
additional_chat_options={
default_options={
"max_tokens": 20000,
"thinking": {"type": "enabled", "budget_tokens": 10000},
"container": {"skills": [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]},
},
@@ -6,8 +6,9 @@ This folder contains examples demonstrating different ways to create and use age
| File | Description |
|------|-------------|
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIClient`. Demonstrates both streaming and non-streaming responses with function tools. Shows automatic agent creation and basic weather functionality. |
| [`azure_ai_use_latest_version.py`](azure_ai_use_latest_version.py) | Demonstrates how to reuse the latest version of an existing agent instead of creating a new agent version on each instantiation using the `use_latest_version=True` parameter. |
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIProjectAgentProvider`. Demonstrates both streaming and non-streaming responses with function tools. Shows automatic agent creation and basic weather functionality. |
| [`azure_ai_provider_methods.py`](azure_ai_provider_methods.py) | Comprehensive guide to `AzureAIProjectAgentProvider` methods: `create_agent()` for creating new agents, `get_agent()` for retrieving existing agents (by name, reference, or details), and `as_agent()` for wrapping SDK objects without HTTP calls. |
| [`azure_ai_use_latest_version.py`](azure_ai_use_latest_version.py) | Demonstrates how to reuse the latest version of an existing agent instead of creating a new agent version on each instantiation by using `provider.get_agent()` to retrieve the latest version. |
| [`azure_ai_with_agent_to_agent.py`](azure_ai_with_agent_to_agent.py) | Shows how to use Agent-to-Agent (A2A) capabilities with Azure AI agents to enable communication with other agents using the A2A protocol. Requires an A2A connection configured in your Azure AI project. |
| [`azure_ai_with_azure_ai_search.py`](azure_ai_with_azure_ai_search.py) | Shows how to use Azure AI Search with Azure AI agents to search through indexed data and answer user questions with proper citations. Requires an Azure AI Search connection and index configured in your Azure AI project. |
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to search the web for current information and provide grounded responses with citations. Requires a Bing connection configured in your Azure AI project. |
@@ -15,6 +16,7 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_ai_with_browser_automation.py`](azure_ai_with_browser_automation.py) | Shows how to use Browser Automation with Azure AI agents to perform automated web browsing tasks and provide responses based on web interactions. Requires a Browser Automation connection configured in your Azure AI project. |
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use the `HostedCodeInterpreterTool` with Azure AI agents to write and execute Python code for mathematical problem solving and data analysis. |
| [`azure_ai_with_code_interpreter_file_generation.py`](azure_ai_with_code_interpreter_file_generation.py) | Shows how to retrieve file IDs from code interpreter generated files using both streaming and non-streaming approaches. |
| [`azure_ai_with_code_interpreter_file_download.py`](azure_ai_with_code_interpreter_file_download.py) | Shows how to download files generated by code interpreter using the OpenAI containers API. |
| [`azure_ai_with_existing_agent.py`](azure_ai_with_existing_agent.py) | Shows how to work with a pre-existing agent by providing the agent name and version to the Azure AI client. Demonstrates agent reuse patterns for production scenarios. |
| [`azure_ai_with_existing_conversation.py`](azure_ai_with_existing_conversation.py) | Demonstrates how to use an existing conversation created on the service side with Azure AI agents. Shows two approaches: specifying conversation ID at the client level and using AgentThread with an existing conversation ID. |
| [`azure_ai_with_application_endpoint.py`](azure_ai_with_application_endpoint.py) | Demonstrates calling the Azure AI application-scoped endpoint. |
@@ -4,14 +4,14 @@ import asyncio
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
"""
Azure AI Agent Basic Example
This sample demonstrates basic usage of AzureAIClient.
This sample demonstrates basic usage of AzureAIProjectAgentProvider.
Shows both streaming and non-streaming responses with function tools.
"""
@@ -28,17 +28,18 @@ async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
@@ -49,17 +50,18 @@ async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
query = "What's the weather like in Tokyo?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
@@ -0,0 +1,293 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import AgentReference, PromptAgentDefinition
from azure.identity.aio import AzureCliCredential
from pydantic import Field
"""
Azure AI Project Agent Provider Methods Example
This sample demonstrates the three main methods of AzureAIProjectAgentProvider:
1. create_agent() - Create a new agent on the Azure AI service
2. get_agent() - Retrieve an existing agent from the service
3. as_agent() - Wrap an SDK agent version object without making HTTP calls
It also shows how to use a single provider instance to spawn multiple agents
with different configurations, which is efficient for multi-agent scenarios.
Each method returns a ChatAgent that can be used for conversations.
"""
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def create_agent_example() -> None:
"""Example of using provider.create_agent() to create a new agent.
This method creates a new agent version on the Azure AI service and returns
a ChatAgent. Use this when you want to create a fresh agent with
specific configuration.
"""
print("=== provider.create_agent() Example ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a new agent with custom configuration
agent = await provider.create_agent(
name="WeatherAssistant",
instructions="You are a helpful weather assistant. Always be concise.",
description="An agent that provides weather information.",
tools=get_weather,
)
print(f"Created agent: {agent.name}")
print(f"Agent ID: {agent.id}")
query = "What's the weather in Paris?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
async def get_agent_by_name_example() -> None:
"""Example of using provider.get_agent(name=...) to retrieve an agent by name.
This method fetches the latest version of an existing agent from the service.
Use this when you know the agent name and want to use the most recent version.
"""
print("=== provider.get_agent(name=...) Example ===")
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
):
# First, create an agent using the SDK directly
created_agent = await project_client.agents.create_version(
agent_name="TestAgentByName",
description="Test agent for get_agent by name example.",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant. End each response with '- Your Assistant'.",
),
)
try:
# Get the agent using the provider by name (fetches latest version)
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = await provider.get_agent(name=created_agent.name)
print(f"Retrieved agent: {agent.name}")
query = "Hello!"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
finally:
# Clean up the agent
await project_client.agents.delete_version(
agent_name=created_agent.name, agent_version=created_agent.version
)
async def get_agent_by_reference_example() -> None:
"""Example of using provider.get_agent(reference=...) to retrieve a specific agent version.
This method fetches a specific version of an agent using an AgentReference.
Use this when you need to use a particular version of an agent.
"""
print("=== provider.get_agent(reference=...) Example ===")
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
):
# First, create an agent using the SDK directly
created_agent = await project_client.agents.create_version(
agent_name="TestAgentByReference",
description="Test agent for get_agent by reference example.",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant. Always respond in uppercase.",
),
)
try:
# Get the agent using an AgentReference with specific version
provider = AzureAIProjectAgentProvider(project_client=project_client)
reference = AgentReference(name=created_agent.name, version=created_agent.version)
agent = await provider.get_agent(reference=reference)
print(f"Retrieved agent: {agent.name} (version via reference)")
query = "Say hello"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
finally:
# Clean up the agent
await project_client.agents.delete_version(
agent_name=created_agent.name, agent_version=created_agent.version
)
async def get_agent_by_details_example() -> None:
"""Example of using provider.get_agent(details=...) with pre-fetched AgentDetails.
This method uses pre-fetched AgentDetails to get the latest version.
Use this when you already have AgentDetails from a previous API call.
"""
print("=== provider.get_agent(details=...) Example ===")
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
):
# First, create an agent using the SDK directly
created_agent = await project_client.agents.create_version(
agent_name="TestAgentByDetails",
description="Test agent for get_agent by details example.",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant. Always include an emoji in your response.",
),
)
try:
# Fetch AgentDetails separately (simulating a previous API call)
agent_details = await project_client.agents.get(agent_name=created_agent.name)
# Get the agent using the pre-fetched details (sync - no HTTP call)
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = provider.as_agent(agent_details.versions.latest)
print(f"Retrieved agent: {agent.name} (from pre-fetched details)")
query = "How are you today?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
finally:
# Clean up the agent
await project_client.agents.delete_version(
agent_name=created_agent.name, agent_version=created_agent.version
)
async def multiple_agents_example() -> None:
"""Example of using a single provider to spawn multiple agents.
A single provider instance can create multiple agents with different
configurations.
"""
print("=== Multiple Agents from Single Provider Example ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create multiple specialized agents from the same provider
weather_agent = await provider.create_agent(
name="WeatherExpert",
instructions="You are a weather expert. Provide brief weather information.",
tools=get_weather,
)
translator_agent = await provider.create_agent(
name="Translator",
instructions="You are a translator. Translate any text to French. Only output the translation.",
)
poet_agent = await provider.create_agent(
name="Poet",
instructions="You are a poet. Respond to everything with a short haiku.",
)
print(f"Created agents: {weather_agent.name}, {translator_agent.name}, {poet_agent.name}\n")
# Use each agent for its specialty
weather_query = "What's the weather in London?"
print(f"User to WeatherExpert: {weather_query}")
weather_result = await weather_agent.run(weather_query)
print(f"WeatherExpert: {weather_result}\n")
translate_query = "Hello, how are you today?"
print(f"User to Translator: {translate_query}")
translate_result = await translator_agent.run(translate_query)
print(f"Translator: {translate_result}\n")
poet_query = "Tell me about the morning sun"
print(f"User to Poet: {poet_query}")
poet_result = await poet_agent.run(poet_query)
print(f"Poet: {poet_result}\n")
async def as_agent_example() -> None:
"""Example of using provider.as_agent() to wrap an SDK object without HTTP calls.
This method wraps an existing AgentVersionDetails into a ChatAgent without
making additional HTTP calls. Use this when you already have the full
AgentVersionDetails from a previous SDK operation.
"""
print("=== provider.as_agent() Example ===")
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
):
# Create an agent using the SDK directly - this returns AgentVersionDetails
agent_version_details = await project_client.agents.create_version(
agent_name="TestAgentAsAgent",
description="Test agent for as_agent example.",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant. Keep responses under 20 words.",
),
)
try:
# Wrap the SDK object directly without any HTTP calls
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = provider.as_agent(agent_version_details)
print(f"Wrapped agent: {agent.name} (no HTTP call needed)")
print(f"Agent version: {agent_version_details.version}")
query = "What can you do?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
finally:
# Clean up the agent
await project_client.agents.delete_version(
agent_name=agent_version_details.name, agent_version=agent_version_details.version
)
async def main() -> None:
print("=== Azure AI Project Agent Provider Methods Example ===\n")
await create_agent_example()
await get_agent_by_name_example()
await get_agent_by_reference_example()
await get_agent_by_details_example()
await as_agent_example()
await multiple_agents_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -4,7 +4,7 @@ import asyncio
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -13,7 +13,7 @@ Azure AI Agent Latest Version Example
This sample demonstrates how to reuse the latest version of an existing agent
instead of creating a new agent version on each instantiation. The first call creates a new agent,
while subsequent calls with `use_latest_version=True` reuse the latest agent version.
while subsequent calls with `get_agent()` reuse the latest agent version.
"""
@@ -28,39 +28,36 @@ def get_weather(
async def main() -> None:
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with AzureCliCredential() as credential:
async with (
AzureAIClient(
credential=credential,
).create_agent(
name="MyWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
# First query will create a new agent
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# First call creates a new agent
agent = await provider.create_agent(
name="MyWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
)
# Create a new agent instance
async with (
AzureAIClient(
credential=credential,
# This parameter will allow to re-use latest agent version
# instead of creating a new one
use_latest_version=True,
).create_agent(
name="MyWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
query = "What's the weather like in Tokyo?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
# Second call retrieves the existing agent (latest version) instead of creating a new one
# This is useful when you want to reuse an agent that was created earlier
agent2 = await provider.get_agent(
name="MyWeatherAgent",
tools=get_weather, # Tools must be provided for function tools
)
query = "What's the weather like in Tokyo?"
print(f"User: {query}")
result = await agent2.run(query)
print(f"Agent: {result}\n")
print(f"First agent ID with version: {agent.id}")
print(f"Second agent ID with version: {agent2.id}")
if __name__ == "__main__":
@@ -2,36 +2,47 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Agent-to-Agent (A2A) Example
This sample demonstrates usage of AzureAIClient with Agent-to-Agent (A2A) capabilities
This sample demonstrates usage of AzureAIProjectAgentProvider with Agent-to-Agent (A2A) capabilities
to enable communication with other agents using the A2A protocol.
Prerequisites:
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
2. Ensure you have an A2A connection configured in your Azure AI project
and set A2A_PROJECT_CONNECTION_ID environment variable.
and set A2A_PROJECT_CONNECTION_ID environment variable.
3. (Optional) A2A_ENDPOINT - If the connection is missing target (e.g., "Custom keys" type),
set the A2A endpoint URL directly.
"""
async def main() -> None:
# Configure A2A tool with connection ID
a2a_tool = {
"type": "a2a_preview",
"project_connection_id": os.environ["A2A_PROJECT_CONNECTION_ID"],
}
# If the connection is missing a target, we need to set the A2A endpoint URL
if os.environ.get("A2A_ENDPOINT"):
a2a_tool["base_url"] = os.environ["A2A_ENDPOINT"]
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyA2AAgent",
instructions="""You are a helpful assistant that can communicate with other agents.
Use the A2A tool when you need to interact with other agents to complete tasks
or gather information from specialized agents.""",
tools={
"type": "a2a_preview",
"project_connection_id": os.environ["A2A_PROJECT_CONNECTION_ID"],
},
) as agent,
):
tools=a2a_tool,
)
query = "What can the secondary agent do?"
print(f"User: {query}")
result = await agent.run(query)
@@ -2,13 +2,13 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Azure AI Search Example
This sample demonstrates usage of AzureAIClient with Azure AI Search
This sample demonstrates usage of AzureAIProjectAgentProvider with Azure AI Search
to search through indexed data and answer user questions about it.
Prerequisites:
@@ -21,7 +21,9 @@ Prerequisites:
async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MySearchAgent",
instructions="""You are a helpful assistant. You must always provide citations for
answers using the tool and render them as: `[message_idx:search_idx†source]`.""",
@@ -38,8 +40,8 @@ async def main() -> None:
]
},
},
) as agent,
):
)
query = "Tell me about insurance options"
print(f"User: {query}")
result = await agent.run(query)
@@ -2,13 +2,13 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Bing Custom Search Example
This sample demonstrates usage of AzureAIClient with Bing Custom Search
This sample demonstrates usage of AzureAIProjectAgentProvider with Bing Custom Search
to search custom search instances and provide responses with relevant results.
Prerequisites:
@@ -21,7 +21,9 @@ Prerequisites:
async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyCustomSearchAgent",
instructions="""You are a helpful agent that can use Bing Custom Search tools to assist users.
Use the available Bing Custom Search tools to answer questions and perform tasks.""",
@@ -36,8 +38,8 @@ async def main() -> None:
]
},
},
) as agent,
):
)
query = "Tell me more about foundry agent service"
print(f"User: {query}")
result = await agent.run(query)
@@ -2,13 +2,13 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Bing Grounding Example
This sample demonstrates usage of AzureAIClient with Bing Grounding
This sample demonstrates usage of AzureAIProjectAgentProvider with Bing Grounding
to search the web for current information and provide grounded responses.
Prerequisites:
@@ -27,7 +27,9 @@ To get your Bing connection ID:
async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyBingGroundingAgent",
instructions="""You are a helpful assistant that can search the web for current information.
Use the Bing search tool to find up-to-date information and provide accurate, well-sourced answers.
@@ -42,8 +44,8 @@ async def main() -> None:
]
},
},
) as agent,
):
)
query = "What is today's date and weather in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
@@ -2,13 +2,13 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Browser Automation Example
This sample demonstrates usage of AzureAIClient with Browser Automation
This sample demonstrates usage of AzureAIProjectAgentProvider with Browser Automation
to perform automated web browsing tasks and provide responses based on web interactions.
Prerequisites:
@@ -21,7 +21,9 @@ Prerequisites:
async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyBrowserAutomationAgent",
instructions="""You are an Agent helping with browser automation tasks.
You can answer questions, provide information, and assist with various tasks
@@ -34,8 +36,8 @@ async def main() -> None:
}
},
},
) as agent,
):
)
query = """Your goal is to report the percent of Microsoft year-to-date stock price change.
To do that, go to the website finance.yahoo.com.
At the top of the page, you will find a search bar.
@@ -3,7 +3,7 @@
import asyncio
from agent_framework import ChatResponse, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from openai.types.responses.response import Response as OpenAIResponse
from openai.types.responses.response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall
@@ -11,22 +11,24 @@ from openai.types.responses.response_code_interpreter_tool_call import ResponseC
"""
Azure AI Agent Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with AzureAIClient
This sample demonstrates using HostedCodeInterpreterTool with AzureAIProjectAgentProvider
for Python code execution and mathematical problem solving.
"""
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with AzureAIClient."""
"""Example showing how to use the HostedCodeInterpreterTool with AzureAIProjectAgentProvider."""
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyCodeInterpreterAgent",
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=HostedCodeInterpreterTool(),
) as agent,
):
)
query = "Use code to get the factorial of 100?"
print(f"User: {query}")
result = await agent.run(query)
@@ -0,0 +1,219 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import tempfile
from pathlib import Path
from agent_framework import (
AgentResponseUpdate,
ChatAgent,
CitationAnnotation,
HostedCodeInterpreterTool,
HostedFileContent,
TextContent,
)
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI V2 Code Interpreter File Download Sample
This sample demonstrates how the AzureAIProjectAgentProvider handles file annotations
when code interpreter generates text files. It shows:
1. How to extract file IDs and container IDs from annotations
2. How to download container files using the OpenAI containers API
3. How to save downloaded files locally
Note: Code interpreter generates files in containers, which require both
file_id and container_id to download via client.containers.files.content.retrieve().
"""
QUERY = (
"Write a simple Python script that creates a text file called 'sample.txt' containing "
"'Hello from the code interpreter!' and save it to disk."
)
async def download_container_files(
file_contents: list[CitationAnnotation | HostedFileContent], agent: ChatAgent
) -> list[Path]:
"""Download container files using the OpenAI containers API.
Code interpreter generates files in containers, which require both file_id
and container_id to download. The container_id is stored in additional_properties.
This function works for both streaming (HostedFileContent) and non-streaming
(CitationAnnotation) responses.
Args:
file_contents: List of CitationAnnotation or HostedFileContent objects
containing file_id and container_id.
agent: The ChatAgent instance with access to the AzureAIClient.
Returns:
List of Path objects for successfully downloaded files.
"""
if not file_contents:
return []
# Create output directory in system temp folder
temp_dir = Path(tempfile.gettempdir())
output_dir = temp_dir / "agent_framework_downloads"
output_dir.mkdir(exist_ok=True)
print(f"\nDownloading {len(file_contents)} container file(s) to {output_dir.absolute()}...")
# Access the OpenAI client from AzureAIClient
openai_client = agent.chat_client.client
downloaded_files: list[Path] = []
for content in file_contents:
file_id = content.file_id
# Extract container_id from additional_properties
if not content.additional_properties or "container_id" not in content.additional_properties:
print(f" File {file_id}: ✗ Missing container_id")
continue
container_id = content.additional_properties["container_id"]
# Extract filename based on content type
if isinstance(content, CitationAnnotation):
filename = content.url or f"{file_id}.txt"
# Extract filename from sandbox URL if present (e.g., sandbox:/mnt/data/sample.txt)
if filename.startswith("sandbox:"):
filename = filename.split("/")[-1]
else: # HostedFileContent
filename = content.additional_properties.get("filename") or f"{file_id}.txt"
output_path = output_dir / filename
try:
# Download using containers API
print(f" Downloading {filename}...", end="", flush=True)
file_content = await openai_client.containers.files.content.retrieve(
file_id=file_id,
container_id=container_id,
)
# file_content is HttpxBinaryResponseContent, read it
content_bytes = file_content.read()
# Save to disk
output_path.write_bytes(content_bytes)
file_size = output_path.stat().st_size
print(f"({file_size} bytes)")
downloaded_files.append(output_path)
except Exception as e:
print(f"Failed: {e}")
return downloaded_files
async def non_streaming_example() -> None:
"""Example of downloading files from non-streaming response using CitationAnnotation."""
print("=== Non-Streaming Response Example ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgent",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
)
print(f"User: {QUERY}\n")
result = await agent.run(QUERY)
print(f"Agent: {result.text}\n")
# Check for annotations in the response
annotations_found: list[CitationAnnotation] = []
# AgentResponse has messages property, which contains ChatMessage objects
for message in result.messages:
for content in message.contents:
if isinstance(content, TextContent) and content.annotations:
for annotation in content.annotations:
if isinstance(annotation, CitationAnnotation) and annotation.file_id:
annotations_found.append(annotation)
print(f"Found file annotation: file_id={annotation.file_id}")
if annotation.additional_properties and "container_id" in annotation.additional_properties:
print(f" container_id={annotation.additional_properties['container_id']}")
if annotations_found:
print(f"SUCCESS: Found {len(annotations_found)} file annotation(s)")
# Download the container files
downloaded_paths = await download_container_files(annotations_found, agent)
if downloaded_paths:
print("\nDownloaded files available at:")
for path in downloaded_paths:
print(f" - {path.absolute()}")
else:
print("WARNING: No file annotations found in non-streaming response")
async def streaming_example() -> None:
"""Example of downloading files from streaming response using HostedFileContent."""
print("\n=== Streaming Response Example ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgentStreaming",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
)
print(f"User: {QUERY}\n")
file_contents_found: list[HostedFileContent] = []
text_chunks: list[str] = []
async for update in agent.run_stream(QUERY):
if isinstance(update, AgentResponseUpdate):
for content in update.contents:
if isinstance(content, TextContent):
if content.text:
text_chunks.append(content.text)
if content.annotations:
for annotation in content.annotations:
if isinstance(annotation, CitationAnnotation) and annotation.file_id:
print(f"Found streaming CitationAnnotation: file_id={annotation.file_id}")
elif isinstance(content, HostedFileContent):
file_contents_found.append(content)
print(f"Found streaming HostedFileContent: file_id={content.file_id}")
if content.additional_properties and "container_id" in content.additional_properties:
print(f" container_id={content.additional_properties['container_id']}")
print(f"\nAgent response: {''.join(text_chunks)[:200]}...")
if file_contents_found:
print(f"SUCCESS: Found {len(file_contents_found)} file reference(s) in streaming")
# Download the container files
downloaded_paths = await download_container_files(file_contents_found, agent)
if downloaded_paths:
print("\n✓ Downloaded files available at:")
for path in downloaded_paths:
print(f" - {path.absolute()}")
else:
print("WARNING: No file annotations found in streaming response")
async def main() -> None:
print("AzureAIClient Code Interpreter File Download Sample\n")
await non_streaming_example()
await streaming_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -3,19 +3,19 @@
import asyncio
from agent_framework import (
AgentResponseUpdate,
CitationAnnotation,
HostedCodeInterpreterTool,
HostedFileContent,
TextContent,
)
from agent_framework._agents import AgentRunResponseUpdate
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI V2 Code Interpreter File Generation Sample
This sample demonstrates how the V2 AzureAIClient handles file annotations
This sample demonstrates how the AzureAIProjectAgentProvider handles file annotations
when code interpreter generates text files. It shows both non-streaming
and streaming approaches to verify file ID extraction.
"""
@@ -26,18 +26,20 @@ QUERY = (
)
async def test_non_streaming() -> None:
"""Test non-streaming response - should have annotations on TextContent."""
print("=== Testing Non-Streaming Response ===")
async def non_streaming_example() -> None:
"""Example of extracting file annotations from non-streaming response."""
print("=== Non-Streaming Response Example ===")
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgent",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
) as agent,
):
)
print(f"User: {QUERY}\n")
result = await agent.run(QUERY)
@@ -45,7 +47,7 @@ async def test_non_streaming() -> None:
# Check for annotations in the response
annotations_found: list[str] = []
# AgentRunResponse has messages property, which contains ChatMessage objects
# AgentResponse has messages property, which contains ChatMessage objects
for message in result.messages:
for content in message.contents:
if isinstance(content, TextContent) and content.annotations:
@@ -60,25 +62,27 @@ async def test_non_streaming() -> None:
print("WARNING: No file annotations found in non-streaming response")
async def test_streaming() -> None:
"""Test streaming response - check if file content is captured via HostedFileContent."""
print("\n=== Testing Streaming Response ===")
async def streaming_example() -> None:
"""Example of extracting file annotations from streaming response."""
print("\n=== Streaming Response Example ===")
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgentStreaming",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
) as agent,
):
)
print(f"User: {QUERY}\n")
annotations_found: list[str] = []
text_chunks: list[str] = []
file_ids_found: list[str] = []
async for update in agent.run_stream(QUERY):
if isinstance(update, AgentRunResponseUpdate):
if isinstance(update, AgentResponseUpdate):
for content in update.contents:
if isinstance(content, TextContent):
if content.text:
@@ -102,9 +106,9 @@ async def test_streaming() -> None:
async def main() -> None:
print("AzureAIClient Code Interpreter File Generation Test\n")
await test_non_streaming()
await test_streaming()
print("AzureAIClient Code Interpreter File Generation Sample\n")
await non_streaming_example()
await streaming_example()
if __name__ == "__main__":
@@ -3,8 +3,7 @@
import asyncio
import os
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
from azure.identity.aio import AzureCliCredential
@@ -12,19 +11,23 @@ from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Existing Agent Example
This sample demonstrates working with pre-existing Azure AI Agents by providing
agent name and version, showing agent reuse patterns for production scenarios.
This sample demonstrates working with pre-existing Azure AI Agents by using provider.get_agent() method,
showing agent reuse patterns for production scenarios.
"""
async def main() -> None:
async def using_provider_get_agent() -> None:
print("=== Get existing Azure AI agent with provider.get_agent() ===")
# Create the client
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
):
# Create remote agent using SDK directly
azure_ai_agent = await project_client.agents.create_version(
agent_name="MyNewTestAgent",
description="Agent for testing purposes.",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
# Setting specific requirements to verify that this agent is used.
@@ -32,27 +35,22 @@ async def main() -> None:
),
)
chat_client = AzureAIClient(
project_client=project_client,
agent_name=azure_ai_agent.name,
# Property agent_version is required for existing agents.
# If this property is not configured, the client will try to create a new agent using
# provided agent_name.
# It's also possible to leave agent_version empty but set use_latest_version=True.
# This will pull latest available agent version and use that version for operations.
agent_version=azure_ai_agent.version,
)
try:
async with ChatAgent(
chat_client=chat_client,
) as agent:
query = "How are you?"
print(f"User: {query}")
result = await agent.run(query)
# Response that indicates that previously created agent was used:
# "I'm here and ready to help you! How can I assist you today? [END]"
print(f"Agent: {result}\n")
# Get newly created agent as ChatAgent by using provider.get_agent()
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = await provider.get_agent(name=azure_ai_agent.name)
# Verify agent properties
print(f"Agent ID: {agent.id}")
print(f"Agent name: {agent.name}")
print(f"Agent description: {agent.description}")
query = "How are you?"
print(f"User: {query}")
result = await agent.run(query)
# Response that indicates that previously created agent was used:
# "I'm here and ready to help you! How can I assist you today? [END]"
print(f"Agent: {result}\n")
finally:
# Clean up the agent manually
await project_client.agents.delete_version(
@@ -60,5 +58,9 @@ async def main() -> None:
)
async def main() -> None:
await using_provider_get_agent()
if __name__ == "__main__":
asyncio.run(main())
@@ -4,7 +4,7 @@ import os
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -12,7 +12,7 @@ from pydantic import Field
"""
Azure AI Agent Existing Conversation Example
This sample demonstrates usage of AzureAIClient with existing conversation created on service side.
This sample demonstrates usage of AzureAIProjectAgentProvider with existing conversation created on service side.
"""
@@ -24,9 +24,9 @@ def get_weather(
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
async def example_with_client() -> None:
"""Example shows how to specify existing conversation ID when initializing Azure AI Client."""
print("=== Azure AI Agent With Existing Conversation and Client ===")
async def example_with_conversation_id() -> None:
"""Example shows how to use existing conversation ID with the provider."""
print("=== Azure AI Agent With Existing Conversation ===")
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
@@ -37,24 +37,23 @@ async def example_with_client() -> None:
conversation_id = conversation.id
print(f"Conversation ID: {conversation_id}")
async with AzureAIClient(
project_client=project_client,
# Specify conversation ID on client level
conversation_id=conversation_id,
).create_agent(
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = await provider.create_agent(
name="BasicAgent",
instructions="You are a helpful agent.",
tools=get_weather,
) as agent:
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result.text}\n")
)
query = "What was my last question?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result.text}\n")
# Pass conversation_id at run level
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query, conversation_id=conversation_id)
print(f"Agent: {result.text}\n")
query = "What was my last question?"
print(f"User: {query}")
result = await agent.run(query, conversation_id=conversation_id)
print(f"Agent: {result.text}\n")
async def example_with_thread() -> None:
@@ -63,12 +62,14 @@ async def example_with_thread() -> None:
async with (
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
AzureAIClient(project_client=project_client).create_agent(
):
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = await provider.create_agent(
name="BasicAgent",
instructions="You are a helpful agent.",
tools=get_weather,
) as agent,
):
)
# Create a conversation using OpenAI client
openai_client = project_client.get_openai_client()
conversation = await openai_client.conversations.create()
@@ -90,7 +91,7 @@ async def example_with_thread() -> None:
async def main() -> None:
await example_with_client()
await example_with_conversation_id()
await example_with_thread()
@@ -5,8 +5,7 @@ import os
from random import randint
from typing import Annotated
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -27,22 +26,22 @@ def get_weather(
async def main() -> None:
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIClient(
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
model_deployment_name=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
credential=credential,
agent_name="WeatherAgent",
),
AzureAIProjectAgentProvider(
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
credential=credential,
) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
query = "What's the weather like in New York?"
print(f"User: {query}")
result = await agent.run(query)
@@ -4,8 +4,8 @@ import asyncio
import os
from pathlib import Path
from agent_framework import ChatAgent, HostedFileSearchTool, HostedVectorStoreContent
from agent_framework.azure import AzureAIClient
from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.agents.aio import AgentsClient
from azure.ai.agents.models import FileInfo, VectorStore
from azure.identity.aio import AzureCliCredential
@@ -32,7 +32,7 @@ async def main() -> None:
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIClient(credential=credential) as client,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
try:
# 1. Upload file and create vector store
@@ -48,22 +48,21 @@ async def main() -> None:
# 2. Create file search tool with uploaded resources
file_search_tool = HostedFileSearchTool(inputs=[HostedVectorStoreContent(vector_store_id=vector_store.id)])
# 3. Create an agent with file search capabilities
# The tool_resources are automatically extracted from HostedFileSearchTool
async with ChatAgent(
chat_client=client,
# 3. Create an agent with file search capabilities using the provider
agent = await provider.create_agent(
name="EmployeeSearchAgent",
instructions=(
"You are a helpful assistant that can search through uploaded employee files "
"to answer questions about employees."
),
tools=file_search_tool,
) as agent:
# 4. Simulate conversation with the agent
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
response = await agent.run(user_input)
print(f"# Agent: {response.text}")
)
# 4. Simulate conversation with the agent
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
response = await agent.run(user_input)
print(f"# Agent: {response.text}")
finally:
# 5. Cleanup: Delete the vector store and file in case of earlier failure to prevent orphaned resources.
if vector_store:
@@ -3,8 +3,8 @@
import asyncio
from typing import Any
from agent_framework import AgentProtocol, AgentRunResponse, AgentThread, ChatMessage, HostedMCPTool
from agent_framework.azure import AzureAIClient
from agent_framework import AgentProtocol, AgentResponse, AgentThread, ChatMessage, HostedMCPTool
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -14,7 +14,7 @@ This sample demonstrates integrating hosted Model Context Protocol (MCP) tools w
"""
async def handle_approvals_without_thread(query: str, agent: "AgentProtocol") -> AgentRunResponse:
async def handle_approvals_without_thread(query: str, agent: "AgentProtocol") -> AgentResponse:
"""When we don't have a thread, we need to ensure we return with the input, approval request and approval."""
result = await agent.run(query, store=False)
@@ -35,7 +35,7 @@ async def handle_approvals_without_thread(query: str, agent: "AgentProtocol") ->
return result
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread") -> AgentRunResponse:
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread") -> AgentResponse:
"""Here we let the thread deal with the previous responses, and we just rerun with the approval."""
result = await agent.run(query, thread=thread)
@@ -59,12 +59,13 @@ async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", threa
async def run_hosted_mcp_without_approval() -> None:
"""Example showing MCP Tools without approval."""
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyLearnDocsAgent",
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
tools=HostedMCPTool(
@@ -72,8 +73,8 @@ async def run_hosted_mcp_without_approval() -> None:
url="https://learn.microsoft.com/api/mcp",
approval_mode="never_require",
),
) as agent,
):
)
query = "How to create an Azure storage account using az cli?"
print(f"User: {query}")
result = await handle_approvals_without_thread(query, agent)
@@ -84,12 +85,13 @@ async def run_hosted_mcp_with_approval_and_thread() -> None:
"""Example showing MCP Tools with approvals using a thread."""
print("=== MCP with approvals and with thread ===")
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyApiSpecsAgent",
instructions="You are a helpful agent that can use MCP tools to assist users.",
tools=HostedMCPTool(
@@ -97,8 +99,8 @@ async def run_hosted_mcp_with_approval_and_thread() -> None:
url="https://gitmcp.io/Azure/azure-rest-api-specs",
approval_mode="always_require",
),
) as agent,
):
)
thread = agent.get_new_thread()
query = "Please summarize the Azure REST API specifications Readme"
print(f"User: {query}")
@@ -4,13 +4,13 @@ from pathlib import Path
import aiofiles
from agent_framework import DataContent, HostedImageGenerationTool
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Image Generation Example
This sample demonstrates basic usage of AzureAIClient to create an agent
This sample demonstrates basic usage of AzureAIProjectAgentProvider to create an agent
that can generate images based on user requirements.
Pre-requisites:
@@ -20,12 +20,13 @@ Pre-requisites:
async def main() -> None:
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ImageGenAgent",
instructions="Generate images based on user requirements.",
tools=[
@@ -37,14 +38,14 @@ async def main() -> None:
}
)
],
) as agent,
):
)
query = "Generate an image of Microsoft logo."
print(f"User: {query}")
result = await agent.run(
query,
# These additional options are required for image generation
additional_chat_options={
options={
"extra_headers": {"x-ms-oai-image-generation-deployment": "gpt-image-1-mini"},
},
)
@@ -3,7 +3,7 @@
import asyncio
from agent_framework import MCPStreamableHTTPTool
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -19,20 +19,22 @@ Pre-requisites:
async def main() -> None:
"""Example showing use of Local MCP Tool with AzureAIClient."""
"""Example showing use of Local MCP Tool with AzureAIProjectAgentProvider."""
print("=== Azure AI Agent with Local MCP Tools Example ===\n")
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
tools=MCPStreamableHTTPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
) as agent,
):
)
# First query
first_query = "How to create an Azure storage account using az cli?"
print(f"User: {first_query}")
@@ -3,7 +3,7 @@ import asyncio
import os
import uuid
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions
from azure.identity.aio import AzureCliCredential
@@ -11,7 +11,7 @@ from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Memory Search Example
This sample demonstrates usage of AzureAIClient with memory search capabilities
This sample demonstrates usage of AzureAIProjectAgentProvider with memory search capabilities
to retrieve relevant past user messages and maintain conversation context across sessions.
It shows explicit memory store creation using Azure AI Projects client and agent creation
using the Agent Framework.
@@ -46,18 +46,20 @@ async def main() -> None:
)
print(f"Created memory store: {memory_store.name} ({memory_store.id}): {memory_store.description}")
# Then, create the agent using Agent Framework
async with AzureAIClient(credential=credential).create_agent(
name="MyMemoryAgent",
instructions="""You are a helpful assistant that remembers past conversations.
Use the memory search tool to recall relevant information from previous interactions.""",
tools={
"type": "memory_search",
"memory_store_name": memory_store.name,
"scope": "user_123",
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
},
) as agent:
# Then, create the agent using Agent Framework provider
async with AzureAIProjectAgentProvider(credential=credential) as provider:
agent = await provider.create_agent(
name="MyMemoryAgent",
instructions="""You are a helpful assistant that remembers past conversations.
Use the memory search tool to recall relevant information from previous interactions.""",
tools={
"type": "memory_search",
"memory_store_name": memory_store.name,
"scope": "user_123",
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
},
)
# First interaction - establish some preferences
print("=== First conversation ===")
query1 = "I prefer dark roast coffee"
@@ -2,13 +2,13 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Microsoft Fabric Example
This sample demonstrates usage of AzureAIClient with Microsoft Fabric
This sample demonstrates usage of AzureAIProjectAgentProvider with Microsoft Fabric
to query Fabric data sources and provide responses based on data analysis.
Prerequisites:
@@ -21,7 +21,9 @@ Prerequisites:
async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyFabricAgent",
instructions="You are a helpful assistant.",
tools={
@@ -34,8 +36,8 @@ async def main() -> None:
]
},
},
) as agent,
):
)
query = "Tell me about sales records"
print(f"User: {query}")
result = await agent.run(query)
@@ -4,13 +4,13 @@ import json
from pathlib import Path
import aiofiles
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with OpenAPI Tool Example
This sample demonstrates usage of AzureAIClient with OpenAPI tools
This sample demonstrates usage of AzureAIProjectAgentProvider with OpenAPI tools
to call external APIs defined by OpenAPI specifications.
Prerequisites:
@@ -29,7 +29,9 @@ async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyOpenAPIAgent",
instructions="""You are a helpful assistant that can use country APIs to provide information.
Use the available OpenAPI tools to answer questions about countries, currencies, and demographics.""",
@@ -42,8 +44,8 @@ async def main() -> None:
"auth": {"type": "anonymous"},
},
},
) as agent,
):
)
query = "What is the name and population of the country that uses currency with abbreviation THB?"
print(f"User: {query}")
result = await agent.run(query)
@@ -2,14 +2,14 @@
import asyncio
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from pydantic import BaseModel, ConfigDict
"""
Azure AI Agent Response Format Example
This sample demonstrates basic usage of AzureAIClient with response format,
This sample demonstrates basic usage of AzureAIProjectAgentProvider with response format,
also known as structured outputs.
"""
@@ -24,23 +24,22 @@ class ReleaseBrief(BaseModel):
async def main() -> None:
"""Example of using response_format property."""
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ProductMarketerAgent",
instructions="Return launch briefs as structured JSON.",
) as agent,
):
# Specify Pydantic model for structured output via default_options
default_options={"response_format": ReleaseBrief},
)
query = "Draft a launch brief for the Contoso Note app."
print(f"User: {query}")
result = await agent.run(
query,
# Specify type to use as response
response_format=ReleaseBrief,
)
result = await agent.run(query)
if isinstance(result.value, ReleaseBrief):
release_brief = result.value
@@ -2,13 +2,13 @@
import asyncio
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent Response Format Example with Runtime JSON Schema
This sample demonstrates basic usage of AzureAIClient with response format,
This sample demonstrates basic usage of AzureAIProjectAgentProvider with response format,
also known as structured outputs.
"""
@@ -29,24 +29,19 @@ runtime_schema = {
async def main() -> None:
"""Example of using response_format property."""
"""Example of using response_format property with a runtime JSON schema."""
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
name="ProductMarketerAgent",
instructions="Return launch briefs as structured JSON.",
) as agent,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
query = "Draft a launch brief for the Contoso Note app."
print(f"User: {query}")
result = await agent.run(
query,
# Specify type to use as response
additional_chat_options={
# Pass response_format via default_options using dict schema format
agent = await provider.create_agent(
name="WeatherDigestAgent",
instructions="Return sample weather digest as structured JSON.",
default_options={
"response_format": {
"type": "json_schema",
"json_schema": {
@@ -54,10 +49,14 @@ async def main() -> None:
"strict": True,
"schema": runtime_schema,
},
},
}
},
)
query = "Draft a sample weather digest."
print(f"User: {query}")
result = await agent.run(query)
print(result.text)
@@ -2,13 +2,13 @@
import asyncio
import os
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with SharePoint Example
This sample demonstrates usage of AzureAIClient with SharePoint
This sample demonstrates usage of AzureAIProjectAgentProvider with SharePoint
to search through SharePoint content and answer user questions about it.
Prerequisites:
@@ -21,7 +21,9 @@ Prerequisites:
async def main() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MySharePointAgent",
instructions="""You are a helpful agent that can use SharePoint tools to assist users.
Use the available SharePoint tools to answer questions and perform tasks.""",
@@ -35,8 +37,8 @@ async def main() -> None:
]
},
},
) as agent,
):
)
query = "What is Contoso whistleblower policy?"
print(f"User: {query}")
result = await agent.run(query)
@@ -4,7 +4,7 @@ import asyncio
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -30,12 +30,14 @@ async def example_with_automatic_thread_creation() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# First conversation - no thread provided, will be created automatically
query1 = "What's the weather like in Seattle?"
print(f"User: {query1}")
@@ -59,12 +61,14 @@ async def example_with_thread_persistence_in_memory() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# Create a new thread that will be reused
thread = agent.get_new_thread()
@@ -100,12 +104,14 @@ async def example_with_existing_thread_id() -> None:
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# Start a conversation and get the thread ID
thread = agent.get_new_thread()
@@ -121,21 +127,21 @@ async def example_with_existing_thread_id() -> None:
if existing_thread_id:
print("\n--- Continuing with the same thread ID in a new agent instance ---")
async with (
AzureAIClient(credential=credential).create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
# Create a thread with the existing ID
thread = agent.get_new_thread(service_thread_id=existing_thread_id)
# Create a new agent instance from the same provider
agent2 = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
)
query2 = "What was the last city I asked about?"
print(f"User: {query2}")
result2 = await agent.run(query2, thread=thread)
print(f"Agent: {result2.text}")
print("Note: The agent continues the conversation from the previous thread by using thread ID.\n")
# Create a thread with the existing ID
thread = agent2.get_new_thread(service_thread_id=existing_thread_id)
query2 = "What was the last city I asked about?"
print(f"User: {query2}")
result2 = await agent2.run(query2, thread=thread)
print(f"Agent: {result2.text}")
print("Note: The agent continues the conversation from the previous thread by using thread ID.\n")
async def main() -> None:
@@ -3,13 +3,13 @@
import asyncio
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIClient
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent With Web Search
This sample demonstrates basic usage of AzureAIClient to create an agent
This sample demonstrates basic usage of AzureAIProjectAgentProvider to create an agent
that can perform web searches using the HostedWebSearchTool.
Pre-requisites:
@@ -19,17 +19,18 @@ Pre-requisites:
async def main() -> None:
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(credential=credential).create_agent(
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WebsearchAgent",
instructions="You are a helpful assistant that can search the web",
tools=[HostedWebSearchTool()],
) as agent,
):
)
query = "What's the weather today in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
@@ -1,27 +1,53 @@
# Azure AI Agent Examples
This folder contains examples demonstrating different ways to create and use agents with the Azure AI chat client from the `agent_framework.azure` package. These examples use the `AzureAIAgentClient` with the `azure-ai-agents` 1.x (V1) API surface. For updated V2 (`azure-ai-projects` 2.x) samples, see the [Azure AI V2 examples folder](../azure_ai/).
This folder contains examples demonstrating different ways to create and use agents with Azure AI using the `AzureAIAgentsProvider` from the `agent_framework.azure` package. These examples use the `azure-ai-agents` 1.x (V1) API surface. For updated V2 (`azure-ai-projects` 2.x) samples, see the [Azure AI V2 examples folder](../azure_ai/).
## Provider Pattern
All examples in this folder use the `AzureAIAgentsProvider` class which provides a high-level interface for agent operations:
- **`create_agent()`** - Create a new agent on the Azure AI service
- **`get_agent()`** - Retrieve an existing agent by ID or from a pre-fetched Agent object
- **`as_agent()`** - Wrap an SDK Agent object as a ChatAgent without HTTP calls
```python
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyAgent",
instructions="You are a helpful assistant.",
tools=my_function,
)
result = await agent.run("Hello!")
```
## Examples
| File | Description |
|------|-------------|
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `ChatAgent` with `AzureAIAgentClient`. It automatically handles all configuration using environment variables. |
| [`azure_ai_provider_methods.py`](azure_ai_provider_methods.py) | Comprehensive example demonstrating all `AzureAIAgentsProvider` methods: `create_agent()`, `get_agent()`, `as_agent()`, and managing multiple agents from a single provider. |
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIAgentsProvider`. It automatically handles all configuration using environment variables. Shows both streaming and non-streaming responses. |
| [`azure_ai_with_bing_custom_search.py`](azure_ai_with_bing_custom_search.py) | Shows how to use Bing Custom Search with Azure AI agents to find real-time information from the web using custom search configurations. Demonstrates how to set up and use HostedWebSearchTool with custom search instances. |
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to find real-time information from the web. Demonstrates web search capabilities with proper source citations and comprehensive error handling. |
| [`azure_ai_with_bing_grounding_citations.py`](azure_ai_with_bing_grounding_citations.py) | Demonstrates how to extract and display citations from Bing Grounding search responses. Shows how to collect citation annotations (title, URL, snippet) during streaming responses, enabling users to verify sources and access referenced content. |
| [`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.py`](azure_ai_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with Azure AI agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`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 ID to the Azure AI chat client. This example also demonstrates proper cleanup of manually created agents. |
| [`azure_ai_with_existing_thread.py`](azure_ai_with_existing_thread.py) | Shows how to work with a pre-existing thread by providing the thread ID to the Azure AI chat client. This example also demonstrates proper cleanup of manually created threads. |
| [`azure_ai_with_explicit_settings.py`](azure_ai_with_explicit_settings.py) | Shows how to create an agent with explicitly configured `AzureAIAgentClient` settings, including project endpoint, model deployment, credentials, and agent name. |
| [`azure_ai_with_azure_ai_search.py`](azure_ai_with_azure_ai_search.py) | Demonstrates how to use Azure AI Search with Azure AI agents to search through indexed data. Shows how to configure search parameters, query types, and integrate with existing search indexes. |
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Demonstrates how to use the HostedFileSearchTool with Azure AI agents to search through uploaded documents. Shows file upload, vector store creation, and querying document content. Includes both streaming and non-streaming examples. |
| [`azure_ai_with_existing_agent.py`](azure_ai_with_existing_agent.py) | Shows how to work with an existing SDK Agent object using `provider.as_agent()`. This wraps the agent without making HTTP calls. |
| [`azure_ai_with_existing_thread.py`](azure_ai_with_existing_thread.py) | Shows how to work with a pre-existing thread by providing the thread ID. Demonstrates proper cleanup of manually created threads. |
| [`azure_ai_with_explicit_settings.py`](azure_ai_with_explicit_settings.py) | Shows how to create an agent with explicitly configured provider settings, including project endpoint and model deployment name. |
| [`azure_ai_with_azure_ai_search.py`](azure_ai_with_azure_ai_search.py) | Demonstrates how to use Azure AI Search with Azure AI agents. Shows how to create an agent with search tools using the SDK directly and wrap it with `provider.get_agent()`. |
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Demonstrates how to use the HostedFileSearchTool with Azure AI agents to search through uploaded documents. Shows file upload, vector store creation, and querying document content. |
| [`azure_ai_with_function_tools.py`](azure_ai_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to integrate Azure AI agents with hosted Model Context Protocol (MCP) servers for enhanced functionality and tool integration. Demonstrates remote MCP server connections and tool discovery. |
| [`azure_ai_with_local_mcp.py`](azure_ai_with_local_mcp.py) | Shows how to integrate Azure AI agents with local Model Context Protocol (MCP) servers for enhanced functionality and tool integration. Demonstrates both agent-level and run-level tool configuration. |
| [`azure_ai_with_multiple_tools.py`](azure_ai_with_multiple_tools.py) | Demonstrates how to use multiple tools together with Azure AI agents, including web search, MCP servers, and function tools. Shows coordinated multi-tool interactions and approval workflows. |
| [`azure_ai_with_openapi_tools.py`](azure_ai_with_openapi_tools.py) | Demonstrates how to use OpenAPI tools with Azure AI agents to integrate external REST APIs. Shows OpenAPI specification loading, anonymous authentication, thread context management, and coordinated multi-API conversations using weather and countries APIs. |
| [`azure_ai_with_openapi_tools.py`](azure_ai_with_openapi_tools.py) | Demonstrates how to use OpenAPI tools with Azure AI agents to integrate external REST APIs. Shows OpenAPI specification loading, anonymous authentication, thread context management, and coordinated multi-API conversations. |
| [`azure_ai_with_response_format.py`](azure_ai_with_response_format.py) | Demonstrates how to use structured outputs with Azure AI agents using Pydantic models. |
| [`azure_ai_with_thread.py`](azure_ai_with_thread.py) | Demonstrates thread management with Azure AI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
## Environment Variables
@@ -4,14 +4,14 @@ import asyncio
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
"""
Azure AI Agent Basic Example
This sample demonstrates basic usage of AzureAIAgentClient to create agents with automatic
This sample demonstrates basic usage of AzureAIAgentsProvider to create agents with automatic
lifecycle management. Shows both streaming and non-streaming responses with function tools.
"""
@@ -28,18 +28,17 @@ async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
# Since no Agent ID is provided, the agent will be automatically created
# and deleted after getting a response
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
@@ -50,18 +49,17 @@ async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
# Since no Agent ID is provided, the agent will be automatically created
# and deleted after getting a response
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
query = "What's the weather like in Portland?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
@@ -0,0 +1,142 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from random import randint
from typing import Annotated
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field
"""
Azure AI Agent Provider Methods Example
This sample demonstrates the methods available on the AzureAIAgentsProvider class:
- create_agent(): Create a new agent on the service
- get_agent(): Retrieve an existing agent by ID
- as_agent(): Wrap an SDK Agent object without making HTTP calls
"""
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
async def create_agent_example() -> None:
"""Create a new agent using provider.create_agent()."""
print("\n--- create_agent() ---")
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
)
print(f"Created: {agent.name} (ID: {agent.id})")
result = await agent.run("What's the weather in Seattle?")
print(f"Response: {result}")
async def get_agent_example() -> None:
"""Retrieve an existing agent by ID using provider.get_agent()."""
print("\n--- get_agent() ---")
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
# Create an agent directly with SDK (simulating pre-existing agent)
sdk_agent = await agents_client.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="ExistingAgent",
instructions="You always respond with 'Hello!'",
)
try:
# Retrieve using provider
agent = await provider.get_agent(sdk_agent.id)
print(f"Retrieved: {agent.name} (ID: {agent.id})")
result = await agent.run("Hi there!")
print(f"Response: {result}")
finally:
await agents_client.delete_agent(sdk_agent.id)
async def as_agent_example() -> None:
"""Wrap an SDK Agent object using provider.as_agent()."""
print("\n--- as_agent() ---")
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
# Create agent using SDK
sdk_agent = await agents_client.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="WrappedAgent",
instructions="You respond with poetry.",
)
try:
# Wrap synchronously (no HTTP call)
agent = provider.as_agent(sdk_agent)
print(f"Wrapped: {agent.name} (ID: {agent.id})")
result = await agent.run("Tell me about the sunset.")
print(f"Response: {result}")
finally:
await agents_client.delete_agent(sdk_agent.id)
async def multiple_agents_example() -> None:
"""Create and manage multiple agents with a single provider."""
print("\n--- Multiple Agents ---")
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
weather_agent = await provider.create_agent(
name="WeatherSpecialist",
instructions="You are a weather specialist.",
tools=get_weather,
)
greeter_agent = await provider.create_agent(
name="GreeterAgent",
instructions="You are a friendly greeter.",
)
print(f"Created: {weather_agent.name}, {greeter_agent.name}")
greeting = await greeter_agent.run("Hello!")
print(f"Greeter: {greeting}")
weather = await weather_agent.run("What's the weather in Tokyo?")
print(f"Weather: {weather}")
async def main() -> None:
print("Azure AI Agent Provider Methods")
await create_agent_example()
await get_agent_example()
await as_agent_example()
await multiple_agents_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -3,8 +3,8 @@
import asyncio
import os
from agent_framework import ChatAgent, CitationAnnotation
from agent_framework.azure import AzureAIAgentClient
from agent_framework import CitationAnnotation
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import ConnectionType
@@ -41,6 +41,7 @@ async def main() -> None:
AzureCliCredential() as credential,
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
ai_search_conn_id = ""
async for connection in project_client.connections.list():
@@ -48,7 +49,8 @@ async def main() -> None:
ai_search_conn_id = connection.id
break
# 1. Create Azure AI agent with the search tool
# 1. Create Azure AI agent with the search tool using SDK directly
# (Azure AI Search tool requires special tool_resources configuration)
azure_ai_agent = await agents_client.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="HotelSearchAgent",
@@ -70,47 +72,42 @@ async def main() -> None:
},
)
# 2. Create chat client with the existing agent
chat_client = AzureAIAgentClient(agents_client=agents_client, agent_id=azure_ai_agent.id)
try:
async with ChatAgent(
chat_client=chat_client,
# Additional instructions for this specific conversation
instructions=("You are a helpful agent that uses the search tool and index to find hotel information."),
) as agent:
print("This agent uses raw Azure AI Search tool to search hotel data.\n")
# 2. Use provider.as_agent() to wrap the existing agent
agent = provider.as_agent(agent=azure_ai_agent)
# 3. Simulate conversation with the agent
user_input = (
"Use Azure AI search knowledge tool to find detailed information about a winter hotel."
" Use the search tool and index." # You can modify prompt to force tool usage
)
print(f"User: {user_input}")
print("Agent: ", end="", flush=True)
print("This agent uses raw Azure AI Search tool to search hotel data.\n")
# Stream the response and collect citations
citations: list[CitationAnnotation] = []
async for chunk in agent.run_stream(user_input):
if chunk.text:
print(chunk.text, end="", flush=True)
# 3. Simulate conversation with the agent
user_input = (
"Use Azure AI search knowledge tool to find detailed information about a winter hotel."
" Use the search tool and index." # You can modify prompt to force tool usage
)
print(f"User: {user_input}")
print("Agent: ", end="", flush=True)
# Collect citations from Azure AI Search responses
for content in getattr(chunk, "contents", []):
annotations = getattr(content, "annotations", [])
if annotations:
citations.extend(annotations)
# Stream the response and collect citations
citations: list[CitationAnnotation] = []
async for chunk in agent.run_stream(user_input):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
# Collect citations from Azure AI Search responses
for content in getattr(chunk, "contents", []):
annotations = getattr(content, "annotations", [])
if annotations:
citations.extend(annotations)
# Display collected citation
if citations:
print("\n\nCitation:")
for i, citation in enumerate(citations, 1):
print(f"[{i}] {citation.url}")
print()
print("\n" + "=" * 50 + "\n")
print("Hotel search conversation completed!")
# Display collected citation
if citations:
print("\n\nCitation:")
for i, citation in enumerate(citations, 1):
print(f"[{i}] {citation.url}")
print("\n" + "=" * 50 + "\n")
print("Hotel search conversation completed!")
finally:
# Clean up the agent manually
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import ChatAgent, HostedWebSearchTool
from agent_framework.azure import AzureAIAgentClient
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -37,19 +37,20 @@ async def main() -> None:
description="Search the web for current information using Bing Custom Search",
)
# 2. Use AzureAIAgentClient as async context manager for automatic cleanup
# 2. Use AzureAIAgentsProvider for agent creation and management
async with (
AzureAIAgentClient(credential=AzureCliCredential()) as client,
ChatAgent(
chat_client=client,
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BingSearchAgent",
instructions=(
"You are a helpful agent that can use Bing Custom Search tools to assist users. "
"Use the available Bing Custom Search tools to answer questions and perform tasks."
),
tools=bing_search_tool,
) as agent,
):
)
# 3. Demonstrate agent capabilities with bing custom search
print("=== Azure AI Agent with Bing Custom Search ===\n")
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import ChatAgent, HostedWebSearchTool
from agent_framework_azure_ai import AzureAIAgentClient
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -32,11 +32,12 @@ async def main() -> None:
description="Search the web for current information using Bing",
)
# 2. Use AzureAIAgentClient as async context manager for automatic cleanup
# 2. Use AzureAIAgentsProvider for agent creation and management
async with (
AzureAIAgentClient(credential=AzureCliCredential()) as client,
ChatAgent(
chat_client=client,
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BingSearchAgent",
instructions=(
"You are a helpful assistant that can search the web for current information. "
@@ -44,9 +45,9 @@ async def main() -> None:
"well-sourced answers. Always cite your sources when possible."
),
tools=bing_search_tool,
) as agent,
):
# 4. Demonstrate agent capabilities with web search
)
# 3. Demonstrate agent capabilities with web search
print("=== Azure AI Agent with Bing Grounding Search ===\n")
user_input = "What is the most popular programming language?"
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import ChatAgent, CitationAnnotation, HostedWebSearchTool
from agent_framework.azure import AzureAIAgentClient
from agent_framework import CitationAnnotation, HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -34,11 +34,12 @@ async def main() -> None:
description="Search the web for current information using Bing",
)
# 2. Use AzureAIAgentClient as async context manager for automatic cleanup
# 2. Use AzureAIAgentsProvider for agent creation and management
async with (
AzureAIAgentClient(credential=AzureCliCredential()) as client,
ChatAgent(
chat_client=client,
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="BingSearchAgent",
instructions=(
"You are a helpful assistant that can search the web for current information. "
@@ -46,8 +47,8 @@ async def main() -> None:
"well-sourced answers. Always cite your sources when possible."
),
tools=bing_search_tool,
) as agent,
):
)
# 3. Demonstrate agent capabilities with web search
print("=== Azure AI Agent with Bing Grounding Search ===\n")
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import AgentRunResponse, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentClient
from agent_framework import AgentResponse, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.models import (
RunStepDeltaCodeInterpreterDetailItemObject,
)
@@ -17,7 +17,7 @@ for Python code execution and mathematical problem solving.
"""
def print_code_interpreter_inputs(response: AgentRunResponse) -> None:
def print_code_interpreter_inputs(response: AgentResponse) -> None:
"""Helper method to access code interpreter data."""
print("\nCode Interpreter Inputs during the run:")
@@ -39,16 +39,16 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential) as chat_client,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = chat_client.create_agent(
agent = await provider.create_agent(
name="CodingAgent",
instructions=("You are a helpful assistant that can write and execute Python code to solve problems."),
tools=HostedCodeInterpreterTool(),
)
query = "Generate the factorial of 100 using python code, show the code and execute it."
print(f"User: {query}")
response = await AgentRunResponse.from_agent_response_generator(agent.run_stream(query))
response = await agent.run(query)
print(f"Agent: {response}")
# To review the code interpreter outputs, you can access
# them from the response raw_representations, just uncomment the next line:
@@ -1,15 +1,21 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework import AgentRunResponseUpdate, ChatAgent, HostedCodeInterpreterTool, HostedFileContent
from agent_framework.azure import AzureAIAgentClient
from agent_framework import (
AgentResponseUpdate,
HostedCodeInterpreterTool,
HostedFileContent,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent Code Interpreter File Generation Example
This sample demonstrates using HostedCodeInterpreterTool with AzureAIAgentClient
This sample demonstrates using HostedCodeInterpreterTool with AzureAIAgentsProvider
to generate a text file and then retrieve it.
The test flow:
@@ -23,79 +29,77 @@ The test flow:
async def main() -> None:
"""Test file generation and retrieval with code interpreter."""
async with AzureCliCredential() as credential:
client = AzureAIAgentClient(credential=credential)
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
agent = await provider.create_agent(
name="CodeInterpreterAgent",
instructions=(
"You are a Python code execution assistant. "
"ALWAYS use the code interpreter tool to execute Python code when asked to create files. "
"Write actual Python code to create files, do not just describe what you would do."
),
tools=[HostedCodeInterpreterTool()],
)
try:
async with ChatAgent(
chat_client=client,
instructions=(
"You are a Python code execution assistant. "
"ALWAYS use the code interpreter tool to execute Python code when asked to create files. "
"Write actual Python code to create files, do not just describe what you would do."
),
tools=[HostedCodeInterpreterTool()],
) as agent:
# Be very explicit about wanting code execution and a download link
query = (
"Use the code interpreter to execute this Python code and then provide me "
"with a download link for the generated file:\n"
"```python\n"
"with open('/mnt/data/sample.txt', 'w') as f:\n"
" f.write('Hello, World! This is a test file.')\n"
"'/mnt/data/sample.txt'\n" # Return the path so it becomes downloadable
"```"
)
print(f"User: {query}\n")
print("=" * 60)
# Be very explicit about wanting code execution and a download link
query = (
"Use the code interpreter to execute this Python code and then provide me "
"with a download link for the generated file:\n"
"```python\n"
"with open('/mnt/data/sample.txt', 'w') as f:\n"
" f.write('Hello, World! This is a test file.')\n"
"'/mnt/data/sample.txt'\n" # Return the path so it becomes downloadable
"```"
)
print(f"User: {query}\n")
print("=" * 60)
# Collect file_ids from the response
file_ids: list[str] = []
# Collect file_ids from the response
file_ids: list[str] = []
async for chunk in agent.run_stream(query):
if not isinstance(chunk, AgentRunResponseUpdate):
continue
async for chunk in agent.run_stream(query):
if not isinstance(chunk, AgentResponseUpdate):
continue
for content in chunk.contents:
if content.type == "text":
print(content.text, end="", flush=True)
elif content.type == "hosted_file":
if isinstance(content, HostedFileContent):
file_ids.append(content.file_id)
print(f"\n[File generated: {content.file_id}]")
for content in chunk.contents:
if content.type == "text":
print(content.text, end="", flush=True)
elif content.type == "hosted_file" and isinstance(content, HostedFileContent):
file_ids.append(content.file_id)
print(f"\n[File generated: {content.file_id}]")
print("\n" + "=" * 60)
print("\n" + "=" * 60)
# Attempt to retrieve discovered files
if file_ids:
print(f"\nAttempting to retrieve {len(file_ids)} file(s):")
for file_id in file_ids:
try:
file_info = await client.agents_client.files.get(file_id)
print(f" File {file_id}: Retrieved successfully")
print(f" Filename: {file_info.filename}")
print(f" Purpose: {file_info.purpose}")
print(f" Bytes: {file_info.bytes}")
except Exception as e:
print(f" File {file_id}: FAILED to retrieve - {e}")
else:
print("No file IDs were captured from the response.")
# List all files to see if any exist
print("\nListing all files in the agent service:")
# Attempt to retrieve discovered files
if file_ids:
print(f"\nAttempting to retrieve {len(file_ids)} file(s):")
for file_id in file_ids:
try:
files_list = await client.agents_client.files.list()
count = 0
for file_info in files_list.data:
count += 1
print(f" - {file_info.id}: {file_info.filename} ({file_info.purpose})")
if count == 0:
print(" No files found.")
file_info = await agents_client.files.get(file_id)
print(f" File {file_id}: Retrieved successfully")
print(f" Filename: {file_info.filename}")
print(f" Purpose: {file_info.purpose}")
print(f" Bytes: {file_info.bytes}")
except Exception as e:
print(f" Failed to list files: {e}")
print(f" File {file_id}: FAILED to retrieve - {e}")
else:
print("No file IDs were captured from the response.")
finally:
await client.close()
# List all files to see if any exist
print("\nListing all files in the agent service:")
try:
files_list = await agents_client.files.list()
count = 0
for file_info in files_list.data:
count += 1
print(f" - {file_info.id}: {file_info.filename} ({file_info.purpose})")
if count == 0:
print(" No files found.")
except Exception as e:
print(f" Failed to list files: {e}")
if __name__ == "__main__":
@@ -3,8 +3,7 @@
import asyncio
import os
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.identity.aio import AzureCliCredential
@@ -17,37 +16,29 @@ agent IDs, showing agent reuse patterns for production scenarios.
async def main() -> None:
print("=== Azure AI Chat Client with Existing Agent ===")
print("=== Azure AI Agent with Existing Agent ===")
# Create the client
# Create the client and provider
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
# Create an agent on the service with default instructions
# These instructions will persist on created agent for every run.
azure_ai_agent = await agents_client.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
# Create remote agent with default instructions
# These instructions will persist on created agent for every run.
instructions="End each response with [END].",
)
chat_client = AzureAIAgentClient(agents_client=agents_client, agent_id=azure_ai_agent.id)
try:
async with ChatAgent(
chat_client=chat_client,
# Instructions here are applicable only to this ChatAgent instance
# These instructions will be combined with instructions on existing remote agent.
# The final instructions during the execution will look like:
# "'End each response with [END]. Respond with 'Hello World' only'"
instructions="Respond with 'Hello World' only",
) as agent:
query = "How are you?"
print(f"User: {query}")
result = await agent.run(query)
# Based on local and remote instructions, the result will be
# 'Hello World [END]'.
print(f"Agent: {result}\n")
# Wrap existing agent instance using provider.as_agent()
agent = provider.as_agent(azure_ai_agent)
query = "How are you?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
finally:
# Clean up the agent manually
await agents_client.delete_agent(azure_ai_agent.id)
@@ -5,8 +5,7 @@ import os
from random import randint
from typing import Annotated
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -28,28 +27,29 @@ def get_weather(
async def main() -> None:
print("=== Azure AI Chat Client with Existing Thread ===")
print("=== Azure AI Agent with Existing Thread ===")
# Create the client
# Create the client and provider
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
# Create an thread that will persist
# Create a thread that will persist
created_thread = await agents_client.threads.create()
try:
async with ChatAgent(
# passing in the client is optional here, so if you take the agent_id from the portal
# you can use it directly without the two lines above.
chat_client=AzureAIAgentClient(agents_client=agents_client),
# Create agent using provider
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
thread = agent.get_new_thread(service_thread_id=created_thread.id)
assert thread.is_initialized
result = await agent.run("What's the weather like in Tokyo?", thread=thread)
print(f"Result: {result}\n")
)
thread = agent.get_new_thread(service_thread_id=created_thread.id)
assert thread.is_initialized
result = await agent.run("What's the weather like in Tokyo?", thread=thread)
print(f"Result: {result}\n")
finally:
# Clean up the thread manually
await agents_client.threads.delete(created_thread.id)
@@ -5,8 +5,7 @@ import os
from random import randint
from typing import Annotated
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -27,26 +26,23 @@ def get_weather(
async def main() -> None:
print("=== Azure AI Chat Client with Explicit Settings ===")
print("=== Azure AI Agent with Explicit Settings ===")
# Since no Agent ID is provided, the agent will be automatically created
# and deleted after getting a response
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
model_deployment_name=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
credential=credential,
agent_name="WeatherAgent",
should_cleanup_agent=True, # Set to False if you want to disable automatic agent cleanup
),
AzureAIAgentsProvider(
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential,
) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
result = await agent.run("What's the weather like in New York?")
print(f"Result: {result}\n")
@@ -1,10 +1,12 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from pathlib import Path
from agent_framework import ChatAgent, HostedFileSearchTool, HostedVectorStoreContent
from agent_framework.azure import AzureAIAgentClient
from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.ai.agents.models import FileInfo, VectorStore
from azure.identity.aio import AzureCliCredential
@@ -24,67 +26,54 @@ USER_INPUTS = [
async def main() -> None:
"""Main function demonstrating Azure AI agent with file search capabilities."""
client = AzureAIAgentClient(credential=AzureCliCredential())
file: FileInfo | None = None
vector_store: VectorStore | None = None
try:
# 1. Upload file and create vector store
pdf_file_path = Path(__file__).parent.parent / "resources" / "employees.pdf"
print(f"Uploading file from: {pdf_file_path}")
async with (
AzureCliCredential() as credential,
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
try:
# 1. Upload file and create vector store
pdf_file_path = Path(__file__).parent.parent / "resources" / "employees.pdf"
print(f"Uploading file from: {pdf_file_path}")
file = await client.agents_client.files.upload_and_poll(file_path=str(pdf_file_path), purpose="assistants")
print(f"Uploaded file, file ID: {file.id}")
file = await agents_client.files.upload_and_poll(file_path=str(pdf_file_path), purpose="assistants")
print(f"Uploaded file, file ID: {file.id}")
vector_store = await client.agents_client.vector_stores.create_and_poll(
file_ids=[file.id], name="my_vectorstore"
)
print(f"Created vector store, vector store ID: {vector_store.id}")
vector_store = await agents_client.vector_stores.create_and_poll(file_ids=[file.id], name="my_vectorstore")
print(f"Created vector store, vector store ID: {vector_store.id}")
# 2. Create file search tool with uploaded resources
file_search_tool = HostedFileSearchTool(inputs=[HostedVectorStoreContent(vector_store_id=vector_store.id)])
# 2. Create file search tool with uploaded resources
file_search_tool = HostedFileSearchTool(inputs=[HostedVectorStoreContent(vector_store_id=vector_store.id)])
# 3. Create an agent with file search capabilities
agent = await provider.create_agent(
name="EmployeeSearchAgent",
instructions=(
"You are a helpful assistant that can search through uploaded employee files "
"to answer questions about employees."
),
tools=file_search_tool,
)
# 3. Create an agent with file search capabilities
# The tool_resources are automatically extracted from HostedFileSearchTool
async with ChatAgent(
chat_client=client,
name="EmployeeSearchAgent",
instructions=(
"You are a helpful assistant that can search through uploaded employee files "
"to answer questions about employees."
),
tools=file_search_tool,
) as agent:
# 4. Simulate conversation with the agent
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
response = await agent.run(user_input)
print(f"# Agent: {response.text}")
finally:
# 5. Cleanup: Delete the vector store and file
try:
if vector_store:
await client.agents_client.vector_stores.delete(vector_store.id)
await agents_client.vector_stores.delete(vector_store.id)
if file:
await client.agents_client.files.delete(file.id)
await agents_client.files.delete(file.id)
except Exception:
# Ignore cleanup errors to avoid masking issues
pass
finally:
# 6. Cleanup: Delete the vector store and file in case of earlier failure to prevent orphaned resources.
# Refreshing the client is required since chat agent closes it
client = AzureAIAgentClient(credential=AzureCliCredential())
try:
if vector_store:
await client.agents_client.vector_stores.delete(vector_store.id)
if file:
await client.agents_client.files.delete(file.id)
except Exception:
# Ignore cleanup errors to avoid masking issues
pass
finally:
await client.close()
if __name__ == "__main__":
@@ -5,8 +5,7 @@ from datetime import datetime, timezone
from random import randint
from typing import Annotated
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -42,12 +41,14 @@ async def tools_on_agent_level() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="AssistantAgent",
instructions="You are a helpful assistant that can provide weather and time information.",
tools=[get_weather, get_time], # Tools defined at agent creation
) as agent,
):
)
# First query - agent can use weather tool
query1 = "What's the weather like in New York?"
print(f"User: {query1}")
@@ -76,12 +77,14 @@ async def tools_on_run_level() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="AssistantAgent",
instructions="You are a helpful assistant.",
# No tools defined here
) as agent,
):
)
# First query with weather tool
query1 = "What's the weather like in Seattle?"
print(f"User: {query1}")
@@ -110,12 +113,14 @@ async def mixed_tools_example() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="AssistantAgent",
instructions="You are a comprehensive assistant that can help with various information requests.",
tools=[get_weather], # Base tool available for all queries
) as agent,
):
)
# Query using both agent tool and additional run-method tools
query = "What's the weather in Denver and what's the current UTC time?"
print(f"User: {query}")
@@ -3,8 +3,8 @@
import asyncio
from typing import Any
from agent_framework import AgentProtocol, AgentRunResponse, AgentThread, HostedMCPTool
from agent_framework.azure import AzureAIAgentClient
from agent_framework import AgentProtocol, AgentResponse, AgentThread, HostedMCPTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -15,7 +15,7 @@ servers, including user approval workflows for function call security.
"""
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread") -> AgentRunResponse:
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread") -> AgentResponse:
"""Here we let the thread deal with the previous responses, and we just rerun with the approval."""
from agent_framework import ChatMessage
@@ -42,9 +42,9 @@ async def main() -> None:
"""Example showing Hosted MCP tools for a Azure AI Agent."""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential) as chat_client,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = chat_client.create_agent(
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import ChatAgent, MCPStreamableHTTPTool
from agent_framework.azure import AzureAIAgentClient
from agent_framework import MCPStreamableHTTPTool
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -27,12 +27,12 @@ async def mcp_tools_on_run_level() -> None:
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
) as mcp_server,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
) as agent,
):
)
# First query
query1 = "How to create an Azure storage account using az cli?"
print(f"User: {query1}")
@@ -47,34 +47,37 @@ async def mcp_tools_on_run_level() -> None:
async def mcp_tools_on_agent_level() -> None:
"""Example showing tools defined when creating the agent."""
"""Example showing local MCP tools passed when creating the agent."""
print("=== Tools Defined on Agent Level ===")
# 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.
# The ChatAgent will connect to the MCP server through its context manager
# and discover tools at runtime
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
tools=MCPStreamableHTTPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
) as agent,
):
# First query
query1 = "How to create an Azure storage account using az cli?"
print(f"User: {query1}")
result1 = await agent.run(query1)
print(f"{agent.name}: {result1}\n")
print("\n=======================================\n")
# Second query
query2 = "What is Microsoft Agent Framework?"
print(f"User: {query2}")
result2 = await agent.run(query2)
print(f"{agent.name}: {result2}\n")
)
# Use agent as context manager to connect MCP tools
async with agent:
# First query
query1 = "How to create an Azure storage account using az cli?"
print(f"User: {query1}")
result1 = await agent.run(query1)
print(f"{agent.name}: {result1}\n")
print("\n=======================================\n")
# Second query
query2 = "What is Microsoft Agent Framework?"
print(f"User: {query2}")
result2 = await agent.run(query2)
print(f"{agent.name}: {result2}\n")
async def main() -> None:
@@ -10,7 +10,7 @@ from agent_framework import (
HostedMCPTool,
HostedWebSearchTool,
)
from agent_framework.azure import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -67,9 +67,9 @@ async def main() -> None:
"""Example showing Hosted MCP tools for a Azure AI Agent."""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential) as chat_client,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = chat_client.create_agent(
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=[
@@ -5,8 +5,7 @@ import json
from pathlib import Path
from typing import Any
from agent_framework import ChatAgent
from agent_framework_azure_ai import AzureAIAgentClient
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.models import OpenApiAnonymousAuthDetails, OpenApiTool
from azure.identity.aio import AzureCliCredential
@@ -40,8 +39,11 @@ async def main() -> None:
# 1. Load OpenAPI specifications (synchronous operation)
weather_openapi_spec, countries_openapi_spec = load_openapi_specs()
# 2. Use AzureAIAgentClient as async context manager for automatic cleanup
async with AzureAIAgentClient(credential=AzureCliCredential()) as client:
# 2. Use AzureAIAgentsProvider for agent creation and management
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# 3. Create OpenAPI tools using Azure AI's OpenApiTool
auth = OpenApiAnonymousAuthDetails()
@@ -62,8 +64,7 @@ async def main() -> None:
# 4. Create an agent with OpenAPI tools
# Note: We need to pass the Azure AI native OpenApiTool definitions directly
# since the agent framework doesn't have a HostedOpenApiTool wrapper yet
async with ChatAgent(
chat_client=client,
agent = await provider.create_agent(
name="OpenAPIAgent",
instructions=(
"You are a helpful assistant that can search for country information "
@@ -73,18 +74,19 @@ async def main() -> None:
),
# Pass the raw tool definitions from Azure AI's OpenApiTool
tools=[*openapi_countries.definitions, *openapi_weather.definitions],
) as agent:
# 5. Simulate conversation with the agent maintaining thread context
print("=== Azure AI Agent with OpenAPI Tools ===\n")
)
# Create a thread to maintain conversation context across multiple runs
thread = agent.get_new_thread()
# 5. Simulate conversation with the agent maintaining thread context
print("=== Azure AI Agent with OpenAPI Tools ===\n")
for user_input in USER_INPUTS:
print(f"User: {user_input}")
# Pass the thread to maintain context across multiple agent.run() calls
response = await agent.run(user_input, thread=thread)
print(f"Agent: {response.text}\n")
# Create a thread to maintain conversation context across multiple runs
thread = agent.get_new_thread()
for user_input in USER_INPUTS:
print(f"User: {user_input}")
# Pass the thread to maintain context across multiple agent.run() calls
response = await agent.run(user_input, thread=thread)
print(f"Agent: {response.text}\n")
if __name__ == "__main__":
@@ -0,0 +1,83 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
from pydantic import BaseModel, ConfigDict
"""
Azure AI Agent Provider Response Format Example
This sample demonstrates using AzureAIAgentsProvider with response_format
for structured outputs in two ways:
1. Setting default response_format at agent creation time (default_options)
2. Overriding response_format at runtime (options parameter in agent.run)
"""
class WeatherInfo(BaseModel):
"""Structured weather information."""
location: str
temperature: int
conditions: str
recommendation: str
model_config = ConfigDict(extra="forbid")
class CityInfo(BaseModel):
"""Structured city information."""
city_name: str
population: int
country: str
model_config = ConfigDict(extra="forbid")
async def main() -> None:
"""Example of using response_format at creation time and runtime."""
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create agent with default response_format (WeatherInfo)
agent = await provider.create_agent(
name="StructuredReporter",
instructions="Return structured JSON based on the requested format.",
default_options={"response_format": WeatherInfo},
)
# Request 1: Uses default response_format from agent creation
print("--- Request 1: Using default response_format (WeatherInfo) ---")
query1 = "What's the weather like in Paris today?"
print(f"User: {query1}")
result1 = await agent.run(query1)
if isinstance(result1.value, WeatherInfo):
weather = result1.value
print("Agent:")
print(f" Location: {weather.location}")
print(f" Temperature: {weather.temperature}")
print(f" Conditions: {weather.conditions}")
print(f" Recommendation: {weather.recommendation}")
# Request 2: Override response_format at runtime with CityInfo
print("\n--- Request 2: Runtime override with CityInfo ---")
query2 = "Tell me about Tokyo."
print(f"User: {query2}")
result2 = await agent.run(query2, options={"response_format": CityInfo})
if isinstance(result2.value, CityInfo):
city = result2.value
print("Agent:")
print(f" City: {city.city_name}")
print(f" Population: {city.population}")
print(f" Country: {city.country}")
if __name__ == "__main__":
asyncio.run(main())
@@ -4,8 +4,8 @@ import asyncio
from random import randint
from typing import Annotated
from agent_framework import AgentThread, ChatAgent
from agent_framework.azure import AzureAIAgentClient
from agent_framework import AgentThread
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
from pydantic import Field
@@ -33,12 +33,14 @@ async def example_with_automatic_thread_creation() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# First conversation - no thread provided, will be created automatically
first_query = "What's the weather like in Seattle?"
print(f"User: {first_query}")
@@ -62,12 +64,14 @@ async def example_with_thread_persistence() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# Create a new thread that will be reused
thread = agent.get_new_thread()
@@ -103,12 +107,14 @@ async def example_with_existing_thread_id() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# Start a conversation and get the thread ID
thread = agent.get_new_thread()
first_query = "What's the weather in Paris?"
@@ -123,15 +129,17 @@ async def example_with_existing_thread_id() -> None:
if existing_thread_id:
print("\n--- Continuing with the same thread ID in a new agent instance ---")
# Create a new agent instance but use the existing thread ID
# Create a new provider and agent but use the existing thread ID
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(thread_id=existing_thread_id, credential=credential),
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent,
):
)
# Create a thread with the existing ID
thread = AgentThread(service_thread_id=existing_thread_id)
@@ -2,7 +2,7 @@
import asyncio
from agent_framework import AgentRunResponseUpdate, ChatAgent, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework import AgentResponseUpdate, ChatAgent, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.azure import AzureOpenAIAssistantsClient
from azure.identity import AzureCliCredential
from openai.types.beta.threads.runs import (
@@ -21,7 +21,7 @@ for Python code execution and mathematical problem solving.
"""
def get_code_interpreter_chunk(chunk: AgentRunResponseUpdate) -> str | None:
def get_code_interpreter_chunk(chunk: AgentResponseUpdate) -> str | None:
"""Helper method to access code interpreter data."""
if (
isinstance(chunk.raw_representation, ChatResponseUpdate)
@@ -5,8 +5,8 @@ from collections.abc import AsyncIterable
from typing import Any
from agent_framework import (
AgentRunResponse,
AgentRunResponseUpdate,
AgentResponse,
AgentResponseUpdate,
AgentThread,
BaseAgent,
ChatMessage,
@@ -60,7 +60,7 @@ class EchoAgent(BaseAgent):
*,
thread: AgentThread | None = None,
**kwargs: Any,
) -> AgentRunResponse:
) -> AgentResponse:
"""Execute the agent and return a complete response.
Args:
@@ -69,7 +69,7 @@ class EchoAgent(BaseAgent):
**kwargs: Additional keyword arguments.
Returns:
An AgentRunResponse containing the agent's reply.
An AgentResponse containing the agent's reply.
"""
# Normalize input messages to a list
normalized_messages = self._normalize_messages(messages)
@@ -93,7 +93,7 @@ class EchoAgent(BaseAgent):
if thread is not None:
await self._notify_thread_of_new_messages(thread, normalized_messages, response_message)
return AgentRunResponse(messages=[response_message])
return AgentResponse(messages=[response_message])
async def run_stream(
self,
@@ -101,7 +101,7 @@ class EchoAgent(BaseAgent):
*,
thread: AgentThread | None = None,
**kwargs: Any,
) -> AsyncIterable[AgentRunResponseUpdate]:
) -> AsyncIterable[AgentResponseUpdate]:
"""Execute the agent and yield streaming response updates.
Args:
@@ -110,7 +110,7 @@ class EchoAgent(BaseAgent):
**kwargs: Additional keyword arguments.
Yields:
AgentRunResponseUpdate objects containing chunks of the response.
AgentResponseUpdate objects containing chunks of the response.
"""
# Normalize input messages to a list
normalized_messages = self._normalize_messages(messages)
@@ -131,7 +131,7 @@ class EchoAgent(BaseAgent):
# Add space before word except for the first one
chunk_text = f" {word}" if i > 0 else word
yield AgentRunResponseUpdate(
yield AgentResponseUpdate(
contents=[TextContent(text=chunk_text)],
role=Role.ASSISTANT,
)
@@ -158,7 +158,6 @@ async def main() -> None:
# Test non-streaming
print(f"Agent Name: {echo_agent.name}")
print(f"Agent ID: {echo_agent.id}")
print(f"Display Name: {echo_agent.display_name}")
query = "Hello, custom agent!"
print(f"\nUser: {query}")
@@ -2,13 +2,13 @@
import asyncio
import random
import sys
from collections.abc import AsyncIterable, MutableSequence
from typing import Any, ClassVar
from typing import Any, ClassVar, Generic
from agent_framework import (
BaseChatClient,
ChatMessage,
ChatOptions,
ChatResponse,
ChatResponseUpdate,
Role,
@@ -16,6 +16,12 @@ from agent_framework import (
use_chat_middleware,
use_function_invocation,
)
from agent_framework._clients import TOptions_co
if sys.version_info >= (3, 12):
from typing import override # type: ignore # pragma: no cover
else:
from typing_extensions import override # type: ignore[import] # pragma: no cover
"""
Custom Chat Client Implementation Example
@@ -27,7 +33,7 @@ showing integration with ChatAgent and both streaming and non-streaming response
@use_function_invocation
@use_chat_middleware
class EchoingChatClient(BaseChatClient):
class EchoingChatClient(BaseChatClient[TOptions_co], Generic[TOptions_co]):
"""A custom chat client that echoes messages back with modifications.
This demonstrates how to implement a custom chat client by extending BaseChatClient
@@ -46,11 +52,12 @@ class EchoingChatClient(BaseChatClient):
super().__init__(**kwargs)
self.prefix = prefix
@override
async def _inner_get_response(
self,
*,
messages: MutableSequence[ChatMessage],
chat_options: ChatOptions,
options: dict[str, Any],
**kwargs: Any,
) -> ChatResponse:
"""Echo back the user's message with a prefix."""
@@ -77,16 +84,17 @@ class EchoingChatClient(BaseChatClient):
response_id=f"echo-resp-{random.randint(1000, 9999)}",
)
@override
async def _inner_get_streaming_response(
self,
*,
messages: MutableSequence[ChatMessage],
chat_options: ChatOptions,
options: dict[str, Any],
**kwargs: Any,
) -> AsyncIterable[ChatResponseUpdate]:
"""Stream back the echoed message character by character."""
# Get the complete response first
response = await self._inner_get_response(messages=messages, chat_options=chat_options, **kwargs)
response = await self._inner_get_response(messages=messages, options=options, **kwargs)
if response.messages:
response_text = response.messages[0].text or ""
@@ -123,7 +131,6 @@ async def main() -> None:
)
print(f"\nAgent Name: {echo_agent.name}")
print(f"Agent Display Name: {echo_agent.display_name}")
# Test non-streaming with agent
query = "This is a test message"
@@ -40,8 +40,8 @@ Set the following environment variables:
- `OLLAMA_HOST`: The base URL for your Ollama server (optional, defaults to `http://localhost:11434`)
- Example: `export OLLAMA_HOST="http://localhost:11434"`
- `OLLAMA_CHAT_MODEL_ID`: The model name to use
- Example: `export OLLAMA_CHAT_MODEL_ID="qwen2.5:8b"`
- `OLLAMA_MODEL_ID`: The model name to use
- Example: `export OLLAMA_MODEL_ID="qwen2.5:8b"`
- Must be a model you have pulled with Ollama
### For OpenAI Client with Ollama (`ollama_with_openai_chat_client.py`)
@@ -12,7 +12,7 @@ This sample demonstrates implementing a Ollama agent with basic tool usage.
Ensure to install Ollama and have a model running locally before running the sample
Not all Models support function calling, to test function calling try llama3.2 or qwen3:4b
Set the model to use via the OLLAMA_CHAT_MODEL_ID environment variable or modify the code below.
Set the model to use via the OLLAMA_MODEL_ID environment variable or modify the code below.
https://ollama.com/
"""
@@ -12,7 +12,7 @@ This sample demonstrates implementing a Ollama agent with reasoning.
Ensure to install Ollama and have a model running locally before running the sample
Not all Models support reasoning, to test reasoning try qwen3:8b
Set the model to use via the OLLAMA_CHAT_MODEL_ID environment variable or modify the code below.
Set the model to use via the OLLAMA_MODEL_ID environment variable or modify the code below.
https://ollama.com/
"""
@@ -24,7 +24,7 @@ async def reasoning_example() -> None:
agent = OllamaChatClient().create_agent(
name="TimeAgent",
instructions="You are a helpful agent answer in one sentence.",
additional_chat_options={"think": True}, # Enable Reasoning on agent level
default_options={"think": True}, # Enable Reasoning on agent level
)
query = "Hey what is 3+4? Can you explain how you got to that answer?"
print(f"User: {query}")
@@ -12,7 +12,7 @@ This sample demonstrates using the native Ollama Chat Client directly.
Ensure to install Ollama and have a model running locally before running the sample.
Not all Models support function calling, to test function calling try llama3.2
Set the model to use via the OLLAMA_CHAT_MODEL_ID environment variable or modify the code below.
Set the model to use via the OLLAMA_MODEL_ID environment variable or modify the code below.
https://ollama.com/
"""
@@ -12,7 +12,7 @@ This sample demonstrates implementing a Ollama agent with multimodal input capab
Ensure to install Ollama and have a model running locally before running the sample
Not all Models support multimodal input, to test multimodal input try gemma3:4b
Set the model to use via the OLLAMA_CHAT_MODEL_ID environment variable or modify the code below.
Set the model to use via the OLLAMA_MODEL_ID environment variable or modify the code below.
https://ollama.com/
"""
@@ -6,13 +6,15 @@ This folder contains examples demonstrating different ways to create and use age
| File | Description |
|------|-------------|
| [`openai_assistants_basic.py`](openai_assistants_basic.py) | The simplest way to create an agent using `ChatAgent` with `OpenAIAssistantsClient`. Shows both streaming and non-streaming responses with automatic assistant creation and cleanup. |
| [`openai_assistants_with_code_interpreter.py`](openai_assistants_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_assistants_with_existing_assistant.py`](openai_assistants_with_existing_assistant.py) | Shows how to work with a pre-existing assistant by providing the assistant ID to the OpenAI Assistants client. Demonstrates proper cleanup of manually created assistants. |
| [`openai_assistants_with_explicit_settings.py`](openai_assistants_with_explicit_settings.py) | Shows how to initialize an agent with a specific assistants client, configuring settings explicitly including API key and model ID. |
| [`openai_assistants_with_file_search.py`](openai_assistants_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. |
| [`openai_assistants_with_function_tools.py`](openai_assistants_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
| [`openai_assistants_with_thread.py`](openai_assistants_with_thread.py) | Demonstrates thread management with OpenAI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
| [`openai_assistants_basic.py`](openai_assistants_basic.py) | Basic usage of `OpenAIAssistantProvider` with streaming and non-streaming responses. |
| [`openai_assistants_provider_methods.py`](openai_assistants_provider_methods.py) | Demonstrates all `OpenAIAssistantProvider` methods: `create_agent()`, `get_agent()`, and `as_agent()`. |
| [`openai_assistants_with_code_interpreter.py`](openai_assistants_with_code_interpreter.py) | Using `HostedCodeInterpreterTool` with `OpenAIAssistantProvider` to execute Python code. |
| [`openai_assistants_with_existing_assistant.py`](openai_assistants_with_existing_assistant.py) | Working with pre-existing assistants using `get_agent()` and `as_agent()` methods. |
| [`openai_assistants_with_explicit_settings.py`](openai_assistants_with_explicit_settings.py) | Configuring `OpenAIAssistantProvider` with explicit settings including API key and model ID. |
| [`openai_assistants_with_file_search.py`](openai_assistants_with_file_search.py) | Using `HostedFileSearchTool` with `OpenAIAssistantProvider` for file search capabilities. |
| [`openai_assistants_with_function_tools.py`](openai_assistants_with_function_tools.py) | Function tools with `OpenAIAssistantProvider` at both agent-level and query-level. |
| [`openai_assistants_with_response_format.py`](openai_assistants_with_response_format.py) | Structured outputs with `OpenAIAssistantProvider` using Pydantic models. |
| [`openai_assistants_with_thread.py`](openai_assistants_with_thread.py) | Thread management with `OpenAIAssistantProvider` for conversation context persistence. |
| [`openai_chat_client_basic.py`](openai_chat_client_basic.py) | The simplest way to create an agent using `ChatAgent` with `OpenAIChatClient`. Shows both streaming and non-streaming responses for chat-based interactions with OpenAI models. |
| [`openai_chat_client_with_explicit_settings.py`](openai_chat_client_with_explicit_settings.py) | Shows how to initialize an agent with a specific chat client, configuring settings explicitly including API key and model ID. |
| [`openai_chat_client_with_function_tools.py`](openai_chat_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
@@ -1,16 +1,18 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from random import randint
from typing import Annotated
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import Field
"""
OpenAI Assistants Basic Example
This sample demonstrates basic usage of OpenAIAssistantsClient with automatic
This sample demonstrates basic usage of OpenAIAssistantProvider with automatic
assistant lifecycle management, showing both streaming and non-streaming responses.
"""
@@ -20,35 +22,50 @@ def get_weather(
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
# Since no assistant ID is provided, the assistant will be automatically created
# and deleted after getting a response
async with OpenAIAssistantsClient().create_agent(
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Create a new assistant via the provider
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
tools=[get_weather],
)
try:
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
finally:
# Clean up the assistant from OpenAI
await client.beta.assistants.delete(agent.id)
async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
# Since no assistant ID is provided, the assistant will be automatically created
# and deleted after getting a response
async with OpenAIAssistantsClient().create_agent(
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Create a new assistant via the provider
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
tools=[get_weather],
)
try:
query = "What's the weather like in Portland?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
@@ -56,10 +73,13 @@ async def streaming_example() -> None:
if chunk.text:
print(chunk.text, end="", flush=True)
print("\n")
finally:
# Clean up the assistant from OpenAI
await client.beta.assistants.delete(agent.id)
async def main() -> None:
print("=== Basic OpenAI Assistants Chat Client Agent Example ===")
print("=== Basic OpenAI Assistants Provider Example ===")
await non_streaming_example()
await streaming_example()
@@ -0,0 +1,149 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from random import randint
from typing import Annotated
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import Field
"""
OpenAI Assistant Provider Methods Example
This sample demonstrates the methods available on the OpenAIAssistantProvider class:
- create_agent(): Create a new assistant on the service
- get_agent(): Retrieve an existing assistant by ID
- as_agent(): Wrap an SDK Assistant object without making HTTP calls
"""
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def create_agent_example() -> None:
"""Create a new assistant using provider.create_agent()."""
print("\n--- create_agent() ---")
async with (
AsyncOpenAI() as client,
OpenAIAssistantProvider(client) as provider,
):
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful weather assistant.",
tools=[get_weather],
)
try:
print(f"Created: {agent.name} (ID: {agent.id})")
result = await agent.run("What's the weather in Seattle?")
print(f"Response: {result}")
finally:
await client.beta.assistants.delete(agent.id)
async def get_agent_example() -> None:
"""Retrieve an existing assistant by ID using provider.get_agent()."""
print("\n--- get_agent() ---")
async with (
AsyncOpenAI() as client,
OpenAIAssistantProvider(client) as provider,
):
# Create an assistant directly with SDK (simulating pre-existing assistant)
sdk_assistant = await client.beta.assistants.create(
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
name="ExistingAssistant",
instructions="You always respond with 'Hello!'",
)
try:
# Retrieve using provider
agent = await provider.get_agent(sdk_assistant.id)
print(f"Retrieved: {agent.name} (ID: {agent.id})")
result = await agent.run("Hi there!")
print(f"Response: {result}")
finally:
await client.beta.assistants.delete(sdk_assistant.id)
async def as_agent_example() -> None:
"""Wrap an SDK Assistant object using provider.as_agent()."""
print("\n--- as_agent() ---")
async with (
AsyncOpenAI() as client,
OpenAIAssistantProvider(client) as provider,
):
# Create assistant using SDK
sdk_assistant = await client.beta.assistants.create(
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
name="WrappedAssistant",
instructions="You respond with poetry.",
)
try:
# Wrap synchronously (no HTTP call)
agent = provider.as_agent(sdk_assistant)
print(f"Wrapped: {agent.name} (ID: {agent.id})")
result = await agent.run("Tell me about the sunset.")
print(f"Response: {result}")
finally:
await client.beta.assistants.delete(sdk_assistant.id)
async def multiple_agents_example() -> None:
"""Create and manage multiple assistants with a single provider."""
print("\n--- Multiple Agents ---")
async with (
AsyncOpenAI() as client,
OpenAIAssistantProvider(client) as provider,
):
weather_agent = await provider.create_agent(
name="WeatherSpecialist",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a weather specialist.",
tools=[get_weather],
)
greeter_agent = await provider.create_agent(
name="GreeterAgent",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a friendly greeter.",
)
try:
print(f"Created: {weather_agent.name}, {greeter_agent.name}")
greeting = await greeter_agent.run("Hello!")
print(f"Greeter: {greeting}")
weather = await weather_agent.run("What's the weather in Tokyo?")
print(f"Weather: {weather}")
finally:
await client.beta.assistants.delete(weather_agent.id)
await client.beta.assistants.delete(greeter_agent.id)
async def main() -> None:
print("OpenAI Assistant Provider Methods")
await create_agent_example()
await get_agent_example()
await as_agent_example()
await multiple_agents_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -1,9 +1,11 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework import AgentRunResponseUpdate, ChatAgent, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework import AgentResponseUpdate, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from openai.types.beta.threads.runs import (
CodeInterpreterToolCallDelta,
RunStepDelta,
@@ -20,7 +22,7 @@ for Python code execution and mathematical problem solving.
"""
def get_code_interpreter_chunk(chunk: AgentRunResponseUpdate) -> str | None:
def get_code_interpreter_chunk(chunk: AgentResponseUpdate) -> str | None:
"""Helper method to access code interpreter data."""
if (
isinstance(chunk.raw_representation, ChatResponseUpdate)
@@ -41,13 +43,19 @@ def get_code_interpreter_chunk(chunk: AgentRunResponseUpdate) -> str | None:
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with OpenAI Assistants."""
print("=== OpenAI Assistants Agent with Code Interpreter Example ===")
print("=== OpenAI Assistants Provider with Code Interpreter Example ===")
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
agent = await provider.create_agent(
name="CodeHelper",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=HostedCodeInterpreterTool(),
) as agent:
tools=[HostedCodeInterpreterTool()],
)
try:
query = "Use code to get the factorial of 100?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
@@ -60,6 +68,8 @@ async def main() -> None:
generated_code += code_interpreter_chunk
print(f"\nGenerated code:\n{generated_code}")
finally:
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
@@ -5,8 +5,7 @@ import os
from random import randint
from typing import Annotated
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import Field
@@ -14,7 +13,7 @@ from pydantic import Field
OpenAI Assistants with Existing Assistant Example
This sample demonstrates working with pre-existing OpenAI Assistants
using existing assistant IDs rather than creating new ones.
using the provider's get_agent() and as_agent() methods.
"""
@@ -23,31 +22,86 @@ def get_weather(
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def example_get_agent_by_id() -> None:
"""Example: Using get_agent() to retrieve an existing assistant by ID."""
print("=== Get Existing Assistant by ID ===")
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Create an assistant via SDK (simulating an existing assistant)
created_assistant = await client.beta.assistants.create(
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
name="WeatherAssistant",
tools=[
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a given location.",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string", "description": "The location"}},
"required": ["location"],
},
},
}
],
)
print(f"Created assistant: {created_assistant.id}")
try:
# Use get_agent() to retrieve the existing assistant
agent = await provider.get_agent(
assistant_id=created_assistant.id,
tools=[get_weather], # Required: implementation for function tools
instructions="You are a helpful weather agent.",
)
result = await agent.run("What's the weather like in Tokyo?")
print(f"Agent: {result}\n")
finally:
await client.beta.assistants.delete(created_assistant.id)
print("Assistant deleted.\n")
async def example_as_agent_wrap_sdk_object() -> None:
"""Example: Using as_agent() to wrap an existing SDK Assistant object."""
print("=== Wrap Existing SDK Assistant Object ===")
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Create and fetch an assistant via SDK
created_assistant = await client.beta.assistants.create(
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
name="SimpleAssistant",
instructions="You are a friendly assistant.",
)
print(f"Created assistant: {created_assistant.id}")
try:
# Use as_agent() to wrap the SDK object
agent = provider.as_agent(
created_assistant,
instructions="You are an extremely helpful assistant. Be enthusiastic!",
)
result = await agent.run("Hello! What can you help me with?")
print(f"Agent: {result}\n")
finally:
await client.beta.assistants.delete(created_assistant.id)
print("Assistant deleted.\n")
async def main() -> None:
print("=== OpenAI Assistants Chat Client with Existing Assistant ===")
print("=== OpenAI Assistants Provider with Existing Assistant Examples ===\n")
# Create the client
client = AsyncOpenAI()
# Create an assistant that will persist
created_assistant = await client.beta.assistants.create(
model=os.environ["OPENAI_CHAT_MODEL_ID"], name="WeatherAssistant"
)
try:
async with ChatAgent(
chat_client=OpenAIAssistantsClient(async_client=client, assistant_id=created_assistant.id),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
result = await agent.run("What's the weather like in Tokyo?")
print(f"Result: {result}\n")
finally:
# Clean up the assistant manually
await client.beta.assistants.delete(created_assistant.id)
await example_get_agent_by_id()
await example_as_agent_wrap_sdk_object()
if __name__ == "__main__":
@@ -5,7 +5,8 @@ import os
from random import randint
from typing import Annotated
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import Field
"""
@@ -21,21 +22,28 @@ def get_weather(
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def main() -> None:
print("=== OpenAI Assistants Client with Explicit Settings ===")
print("=== OpenAI Assistants Provider with Explicit Settings ===")
async with OpenAIAssistantsClient(
model_id=os.environ["OPENAI_CHAT_MODEL_ID"],
api_key=os.environ["OPENAI_API_KEY"],
).create_agent(
# Create client with explicit API key
client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
provider = OpenAIAssistantProvider(client)
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ["OPENAI_CHAT_MODEL_ID"],
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
tools=[get_weather],
)
try:
result = await agent.run("What's the weather like in New York?")
print(f"Result: {result}\n")
finally:
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
@@ -1,9 +1,11 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework import ChatAgent, HostedFileSearchTool, HostedVectorStoreContent
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
"""
OpenAI Assistants with File Search Example
@@ -12,41 +14,43 @@ This sample demonstrates using HostedFileSearchTool with OpenAI Assistants
for document-based question answering and information retrieval.
"""
# Helper functions
async def create_vector_store(client: OpenAIAssistantsClient) -> tuple[str, HostedVectorStoreContent]:
async def create_vector_store(client: AsyncOpenAI) -> tuple[str, HostedVectorStoreContent]:
"""Create a vector store with sample documents."""
file = await client.client.files.create(
file = await client.files.create(
file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."), purpose="user_data"
)
vector_store = await client.client.vector_stores.create(
vector_store = await client.vector_stores.create(
name="knowledge_base",
expires_after={"anchor": "last_active_at", "days": 1},
)
result = await client.client.vector_stores.files.create_and_poll(vector_store_id=vector_store.id, file_id=file.id)
result = await client.vector_stores.files.create_and_poll(vector_store_id=vector_store.id, file_id=file.id)
if result.last_error is not None:
raise Exception(f"Vector store file processing failed with status: {result.last_error.message}")
return file.id, HostedVectorStoreContent(vector_store_id=vector_store.id)
async def delete_vector_store(client: OpenAIAssistantsClient, file_id: str, vector_store_id: str) -> None:
async def delete_vector_store(client: AsyncOpenAI, file_id: str, vector_store_id: str) -> None:
"""Delete the vector store after using it."""
await client.client.vector_stores.delete(vector_store_id=vector_store_id)
await client.client.files.delete(file_id=file_id)
await client.vector_stores.delete(vector_store_id=vector_store_id)
await client.files.delete(file_id=file_id)
async def main() -> None:
print("=== OpenAI Assistants Client Agent with File Search Example ===\n")
print("=== OpenAI Assistants Provider with File Search Example ===\n")
client = OpenAIAssistantsClient()
async with ChatAgent(
chat_client=client,
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
agent = await provider.create_agent(
name="SearchAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful assistant that searches files in a knowledge base.",
tools=HostedFileSearchTool(),
) as agent:
tools=[HostedFileSearchTool()],
)
try:
query = "What is the weather today? Do a file search to find the answer."
file_id, vector_store = await create_vector_store(client)
@@ -57,7 +61,10 @@ async def main() -> None:
):
if chunk.text:
print(chunk.text, end="", flush=True)
await delete_vector_store(client, file_id, vector_store.vector_store_id)
finally:
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
@@ -1,12 +1,13 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from datetime import datetime, timezone
from random import randint
from typing import Annotated
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import Field
"""
@@ -22,7 +23,7 @@ def get_weather(
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
def get_time() -> str:
@@ -35,13 +36,19 @@ async def tools_on_agent_level() -> None:
"""Example showing tools defined when creating the agent."""
print("=== Tools Defined on Agent Level ===")
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
agent = await provider.create_agent(
name="InfoAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful assistant that can provide weather and time information.",
tools=[get_weather, get_time], # Tools defined at agent creation
) as agent:
)
try:
# First query - agent can use weather tool
query1 = "What's the weather like in New York?"
print(f"User: {query1}")
@@ -59,47 +66,63 @@ async def tools_on_agent_level() -> None:
print(f"User: {query3}")
result3 = await agent.run(query3)
print(f"Agent: {result3}\n")
finally:
await client.beta.assistants.delete(agent.id)
async def tools_on_run_level() -> None:
"""Example showing tools passed to the run method."""
print("=== Tools Passed to Run Method ===")
# Agent created without tools
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Agent created with base tools, additional tools can be passed at run time
agent = await provider.create_agent(
name="FlexibleAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful assistant.",
# No tools defined here
) as agent:
# First query with weather tool
tools=[get_weather], # Base tool
)
try:
# First query using base weather tool
query1 = "What's the weather like in Seattle?"
print(f"User: {query1}")
result1 = await agent.run(query1, tools=[get_weather]) # Tool passed to run method
result1 = await agent.run(query1)
print(f"Agent: {result1}\n")
# Second query with time tool
# Second query with additional time tool
query2 = "What's the current UTC time?"
print(f"User: {query2}")
result2 = await agent.run(query2, tools=[get_time]) # Different tool for this query
result2 = await agent.run(query2, tools=[get_time]) # Additional tool for this query
print(f"Agent: {result2}\n")
# Third query with multiple tools
# Third query with both tools
query3 = "What's the weather in Chicago and what's the current UTC time?"
print(f"User: {query3}")
result3 = await agent.run(query3, tools=[get_weather, get_time]) # Multiple tools
result3 = await agent.run(query3, tools=[get_time]) # Time tool adds to weather
print(f"Agent: {result3}\n")
finally:
await client.beta.assistants.delete(agent.id)
async def mixed_tools_example() -> None:
"""Example showing both agent-level tools and run-method tools."""
print("=== Mixed Tools Example (Agent + Run Method) ===")
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# Agent created with some base tools
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
agent = await provider.create_agent(
name="ComprehensiveAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a comprehensive assistant that can help with various information requests.",
tools=[get_weather], # Base tool available for all queries
) as agent:
)
try:
# Query using both agent tool and additional run-method tools
query = "What's the weather in Denver and what's the current UTC time?"
print(f"User: {query}")
@@ -110,10 +133,12 @@ async def mixed_tools_example() -> None:
tools=[get_time], # Additional tools for this specific query
)
print(f"Agent: {result}\n")
finally:
await client.beta.assistants.delete(agent.id)
async def main() -> None:
print("=== OpenAI Assistants Chat Client Agent with Function Tools Examples ===\n")
print("=== OpenAI Assistants Provider with Function Tools Examples ===\n")
await tools_on_agent_level()
await tools_on_run_level()
@@ -0,0 +1,88 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import BaseModel, ConfigDict
"""
OpenAI Assistant Provider Response Format Example
This sample demonstrates using OpenAIAssistantProvider with response_format
for structured outputs in two ways:
1. Setting default response_format at agent creation time (default_options)
2. Overriding response_format at runtime (options parameter in agent.run)
"""
class WeatherInfo(BaseModel):
"""Structured weather information."""
location: str
temperature: int
conditions: str
recommendation: str
model_config = ConfigDict(extra="forbid")
class CityInfo(BaseModel):
"""Structured city information."""
city_name: str
population: int
country: str
model_config = ConfigDict(extra="forbid")
async def main() -> None:
"""Example of using response_format at creation time and runtime."""
async with (
AsyncOpenAI() as client,
OpenAIAssistantProvider(client) as provider,
):
# Create agent with default response_format (WeatherInfo)
agent = await provider.create_agent(
name="StructuredReporter",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="Return structured JSON based on the requested format.",
default_options={"response_format": WeatherInfo},
)
try:
# Request 1: Uses default response_format from agent creation
print("--- Request 1: Using default response_format (WeatherInfo) ---")
query1 = "What's the weather like in Paris today?"
print(f"User: {query1}")
result1 = await agent.run(query1)
if isinstance(result1.value, WeatherInfo):
weather = result1.value
print("Agent:")
print(f" Location: {weather.location}")
print(f" Temperature: {weather.temperature}")
print(f" Conditions: {weather.conditions}")
print(f" Recommendation: {weather.recommendation}")
# Request 2: Override response_format at runtime with CityInfo
print("\n--- Request 2: Runtime override with CityInfo ---")
query2 = "Tell me about Tokyo."
print(f"User: {query2}")
result2 = await agent.run(query2, options={"response_format": CityInfo})
if isinstance(result2.value, CityInfo):
city = result2.value
print("Agent:")
print(f" City: {city.city_name}")
print(f" Population: {city.population}")
print(f" Country: {city.country}")
finally:
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
asyncio.run(main())
@@ -1,11 +1,13 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from random import randint
from typing import Annotated
from agent_framework import AgentThread, ChatAgent
from agent_framework.openai import OpenAIAssistantsClient
from agent_framework import AgentThread
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI
from pydantic import Field
"""
@@ -21,18 +23,24 @@ def get_weather(
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def example_with_automatic_thread_creation() -> None:
"""Example showing automatic thread creation (service-managed thread)."""
print("=== Automatic Thread Creation Example ===")
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
tools=[get_weather],
)
try:
# First conversation - no thread provided, will be created automatically
query1 = "What's the weather like in Seattle?"
print(f"User: {query1}")
@@ -45,6 +53,8 @@ async def example_with_automatic_thread_creation() -> None:
result2 = await agent.run(query2)
print(f"Agent: {result2.text}")
print("Note: Each call creates a separate thread, so the agent doesn't remember previous context.\n")
finally:
await client.beta.assistants.delete(agent.id)
async def example_with_thread_persistence() -> None:
@@ -52,11 +62,17 @@ async def example_with_thread_persistence() -> None:
print("=== Thread Persistence Example ===")
print("Using the same thread across multiple conversations to maintain context.\n")
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
tools=[get_weather],
)
try:
# Create a new thread that will be reused
thread = agent.get_new_thread()
@@ -78,6 +94,8 @@ async def example_with_thread_persistence() -> None:
result3 = await agent.run(query3, thread=thread)
print(f"Agent: {result3.text}")
print("Note: The agent remembers context from previous messages in the same thread.\n")
finally:
await client.beta.assistants.delete(agent.id)
async def example_with_existing_thread_id() -> None:
@@ -85,14 +103,22 @@ async def example_with_existing_thread_id() -> None:
print("=== Existing Thread ID Example ===")
print("Using a specific thread ID to continue an existing conversation.\n")
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
# First, create a conversation and capture the thread ID
existing_thread_id = None
assistant_id = None
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
agent = await provider.create_agent(
name="WeatherAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
tools=[get_weather],
)
assistant_id = agent.id
try:
# Start a conversation and get the thread ID
thread = agent.get_new_thread()
query1 = "What's the weather in Paris?"
@@ -104,27 +130,30 @@ async def example_with_existing_thread_id() -> None:
existing_thread_id = thread.service_thread_id
print(f"Thread ID: {existing_thread_id}")
if existing_thread_id:
print("\n--- Continuing with the same thread ID in a new agent instance ---")
if existing_thread_id:
print("\n--- Continuing with the same thread ID using get_agent ---")
# Get the existing assistant by ID
agent2 = await provider.get_agent(
assistant_id=assistant_id,
tools=[get_weather], # Must provide function implementations
)
# Create a new agent instance but use the existing thread ID
async with ChatAgent(
chat_client=OpenAIAssistantsClient(thread_id=existing_thread_id),
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
# Create a thread with the existing ID
thread = AgentThread(service_thread_id=existing_thread_id)
query2 = "What was the last city I asked about?"
print(f"User: {query2}")
result2 = await agent.run(query2, thread=thread)
result2 = await agent2.run(query2, thread=thread)
print(f"Agent: {result2.text}")
print("Note: The agent continues the conversation from the previous thread.\n")
finally:
if assistant_id:
await client.beta.assistants.delete(assistant_id)
async def main() -> None:
print("=== OpenAI Assistants Chat Client Agent Thread Management Examples ===\n")
print("=== OpenAI Assistants Provider Thread Management Examples ===\n")
await example_with_automatic_thread_creation()
await example_with_thread_persistence()
@@ -3,7 +3,7 @@
import asyncio
import json
from agent_framework.openai import OpenAIChatClient
from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions
"""
OpenAI Chat Client Runtime JSON Schema Example
@@ -32,7 +32,7 @@ runtime_schema = {
async def non_streaming_example() -> None:
print("=== Non-streaming runtime JSON schema example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient[OpenAIChatOptions]().create_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -42,7 +42,7 @@ async def non_streaming_example() -> None:
response = await agent.run(
query,
additional_chat_options={
options={
"response_format": {
"type": "json_schema",
"json_schema": {
@@ -76,7 +76,7 @@ async def streaming_example() -> None:
chunks: list[str] = []
async for chunk in agent.run_stream(
query,
additional_chat_options={
options={
"response_format": {
"type": "json_schema",
"json_schema": {
@@ -2,7 +2,7 @@
import asyncio
from agent_framework.openai import OpenAIResponsesClient
from agent_framework.openai import OpenAIResponsesClient, OpenAIResponsesOptions
"""
OpenAI Responses Client Reasoning Example
@@ -10,19 +10,20 @@ OpenAI Responses Client Reasoning Example
This sample demonstrates advanced reasoning capabilities using OpenAI's gpt-5 models,
showing step-by-step reasoning process visualization and complex problem-solving.
This uses the additional_chat_options parameter to enable reasoning with high effort and detailed summaries.
You can also set these options at the run level, since they are api and/or provider specific, you will need to lookup
the correct values for your provider, since these are passed through as-is.
This uses the default_options parameter to enable reasoning with high effort and detailed summaries.
You can also set these options at the run level using the options parameter.
Since these are api and/or provider specific, you will need to lookup
the correct values for your provider, as they are passed through as-is.
In this case they are here: https://platform.openai.com/docs/api-reference/responses/create#responses-create-reasoning
"""
agent = OpenAIResponsesClient(model_id="gpt-5").create_agent(
agent = OpenAIResponsesClient[OpenAIResponsesOptions](model_id="gpt-5").create_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.",
additional_chat_options={"reasoning": {"effort": "high", "summary": "detailed"}},
default_options={"reasoning": {"effort": "high", "summary": "detailed"}},
)
@@ -42,7 +42,7 @@ async def non_streaming_example() -> None:
response = await agent.run(
query,
additional_chat_options={
options={
"response_format": {
"type": "json_schema",
"json_schema": {
@@ -76,7 +76,7 @@ async def streaming_example() -> None:
chunks: list[str] = []
async for chunk in agent.run_stream(
query,
additional_chat_options={
options={
"response_format": {
"type": "json_schema",
"json_schema": {
@@ -2,7 +2,7 @@
import asyncio
from agent_framework import AgentRunResponse
from agent_framework import AgentResponse
from agent_framework.openai import OpenAIResponsesClient
from pydantic import BaseModel
@@ -35,7 +35,7 @@ async def non_streaming_example() -> None:
print(f"User: {query}")
# Get structured response from the agent using response_format parameter
result = await agent.run(query, response_format=OutputStruct)
result = await agent.run(query, options={"response_format": OutputStruct})
# Access the structured output directly from the response value
if result.value:
@@ -60,17 +60,17 @@ async def streaming_example() -> None:
query = "Tell me about Tokyo, Japan"
print(f"User: {query}")
# Get structured response from streaming agent using AgentRunResponse.from_agent_response_generator
# This method collects all streaming updates and combines them into a single AgentRunResponse
result = await AgentRunResponse.from_agent_response_generator(
agent.run_stream(query, response_format=OutputStruct),
# Get structured response from streaming agent using AgentResponse.from_agent_response_generator
# This method collects all streaming updates and combines them into a single AgentResponse
result = await AgentResponse.from_agent_response_generator(
agent.run_stream(query, options={"response_format": OutputStruct}),
output_format_type=OutputStruct,
)
# Access the structured output directly from the response value
if result.value:
structured_data: OutputStruct = result.value # type: ignore
print("Structured Output (from streaming with AgentRunResponse.from_agent_response_generator):")
print("Structured Output (from streaming with AgentResponse.from_agent_response_generator):")
print(f"City: {structured_data.city}")
print(f"Description: {structured_data.description}")
else: