* 1. Add reproduction test for issue #4155: workflow.run Activity never stopped in streaming OffThread path
The WorkflowRunActivity_IsStopped_Streaming_OffThread test demonstrates that
the workflow.run OpenTelemetry Activity created in StreamingRunEventStream.RunLoopAsync
is started but never stopped when using the OffThread/Default streaming execution.
The background run loop keeps running after event consumption completes, so the
using Activity? declaration never disposes until explicit StopAsync() is called.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2. Fix workflow.run Activity never stopped in streaming OffThread execution (#4155)
The workflow.run OpenTelemetry Activity in StreamingRunEventStream.RunLoopAsync
was scoped to the method lifetime via 'using'. Since the run loop only exits on
cancellation, the Activity was never stopped/exported until explicit disposal.
Fix: Remove 'using' and explicitly dispose the Activity when the workflow reaches
Idle status (all supersteps complete). A safety-net disposal in the finally block
handles cancellation and error paths.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add root-level workflow.session activity spanning run loop lifetime\n\nImplements two-level telemetry hierarchy per PR feedback from lokitoth:\n- workflow.session: spans the entire run loop / stream lifetime\n- workflow_invoke: per input-to-halt cycle, nested within the session\n\nThis ensures the session activity stays open across multiple turns,\nwhile individual run activities are created and disposed per cycle.\n\nAlso fixes linkedSource CancellationTokenSource disposal leak in\nStreamingRunEventStream (added using declaration)."
* Address Copilot review: fix Activity/CTS disposal, rename activity, add error tag\n\n1. LockstepRunEventStream: Remove 'using' from Activity in async iterator\n and manually dispose in finally block (fixes#4155 pattern). Also dispose\n linkedSource CTS in finally to prevent leak.\n2. Tags.cs: Add ErrorMessage (\"error.message\") tag for runtime errors,\n distinct from BuildErrorMessage (\"build.error.message\").\n3. ActivityNames: Rename WorkflowRun from \"workflow_invoke\" to \"workflow.run\"\n for cross-language consistency.\n4. WorkflowTelemetryContext: Fix XML doc to say \"outer/parent span\" instead\n of \"root-level span\".\n5. ObservabilityTests: Assert WorkflowSession absence when DisableWorkflowRun\n is true.\n6. WorkflowRunActivityStopTests: Fix streaming test race by disposing\n StreamingRun before asserting activities are stopped.\n7. StreamingRunEventStream/LockstepRunEventStream: Use Tags.ErrorMessage\n instead of Tags.BuildErrorMessage for runtime error events."
* Review fixes: revert workflow_invoke rename, use 'using' for linkedSource, move SessionStarted earlier\n\n- Revert ActivityNames.WorkflowRun back to \"workflow_invoke\" (OTEL semantic convention contract)\n- Use 'using' declaration for linkedSource CTS in LockstepRunEventStream (no timing sensitivity)\n- Move SessionStarted event before WaitForInputAsync in StreamingRunEventStream to match Lockstep behavior"
* Improve naming and comments in WorkflowRunActivityStopTests"
* Prevent session Activity.Current leak in lockstep mode, add nesting test
Save and restore Activity.Current in LockstepRunEventStream.Start() so the
session activity doesn't leak into caller code via AsyncLocal. Re-establish
Activity.Current = sessionActivity before creating the run activity in
TakeEventStreamAsync to preserve parent-child nesting.
Add test verifying app activities after RunAsync are not parented under the
session, and that the workflow_invoke activity nests under the session."
* Fix stale XML doc: WorkflowRun -> WorkflowInvoke in ObservabilityTests
---------
Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Phase 2: Embedding clients for Ollama, Bedrock, and Azure AI Inference
Add embedding client implementations to existing provider packages:
- OllamaEmbeddingClient: Text embeddings via Ollama's embed API
- BedrockEmbeddingClient: Text embeddings via Amazon Titan on Bedrock
- AzureAIInferenceEmbeddingClient: Text and image embeddings via Azure AI
Inference, supporting Content | str input with separate model IDs for
text (AZURE_AI_INFERENCE_EMBEDDING_MODEL_ID) and image
(AZURE_AI_INFERENCE_IMAGE_EMBEDDING_MODEL_ID) endpoints
Additional changes:
- Rename EmbeddingCoT -> EmbeddingT, EmbeddingOptionsCoT -> EmbeddingOptionsT
- Add otel_provider_name passthrough to all embedding clients
- Register integration pytest marker in all packages
- Add lazy-loading namespace exports for Ollama and Bedrock embeddings
- Add image embedding sample using Cohere-embed-v3-english
- Add azure-ai-inference dependency to azure-ai package
Part of #1188
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix mypy duplicate name and ruff lint issues
- Rename second 'vector' variable to 'img_vector' in image embedding loop
- Combine nested with statements in tests
- Remove unused result assignments in tests
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* updates from feedback
* Fix CI failures in embedding usage handling
- Fix Azure AI embedding mypy issues by normalizing vectors to list[float],
safely accumulating optional usage token fields, and filtering None entries
before constructing GeneratedEmbeddings
- Avoid Bandit false positive by initializing usage details as an empty dict
- Update OpenAI embedding tests to assert canonical usage keys
(input_token_count/total_token_count)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Bump RCNumber from 1 to 2
- Update GitTag to 1.0.0-rc2
- Update preview date stamps from 260219 to 260225
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* small updates and improvements in the azure AISearch provider
* Fix mypy errors and embedding function test
- Use separate variable for embeddings result to avoid mypy type reassignment error
- Fix test_vectorized_query_with_embedding_function: use real async function
instead of AsyncMock which falsely matches SupportsGetEmbeddings protocol
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fixes from feedback
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: use HasSchema check in DetermineElementType to prevent empty records
When parsing JSON arrays containing objects without a predefined schema,
`DetermineElementType()` was creating a `VariableType` with an empty
(non-null) schema via `targetType.Schema?.Select(...) ?? []`. This caused
`ParseRecord` to take the schema-based parsing path, iterating over zero
schema fields and silently discarding all JSON properties.
The fix checks `targetType.HasSchema` and falls back to
`VariableType.RecordType` (which has `Schema = null`) when no schema is
defined, ensuring `ParseRecord` takes the dynamic `ParseValues()` path
that preserves all JSON properties.
Closes#4195
* test: add regression tests for schema-less JSON array-of-objects parsing (#4195)
Add two regression tests to JsonDocumentExtensionsTests:
1. ParseRecord_ObjectWithArrayOfObjects_NoSchema_PreservesNestedProperties
- Parses a JSON object containing an array of objects using
VariableType.RecordType (no schema) and verifies that nested
object properties (name, role) are preserved in each element.
- This is the exact scenario from issue #4195 where objects in
arrays were being returned as empty dictionaries.
2. ParseList_ArrayOfObjects_NoSchema_PreservesProperties
- Parses a JSON array of objects directly via ParseList with
VariableType.ListType (no schema) and verifies all properties
are preserved.
Both tests follow the existing Arrange/Act/Assert pattern and would
have failed before the DetermineElementType() fix (empty dictionaries
instead of populated ones).
* Fix thread corruption when max_iterations exhausted (#1366)
When the function invocation loop exhausts max_iterations while the model
keeps requesting tools, the failsafe code path (calling the model with
tool_choice='none' and prepending fcc_messages) was unreachable because
'if response is not None: return response' short-circuited before it.
The fix removes the premature return so the failsafe always runs after
loop exhaustion, making a final model call with tool_choice='none' to
produce a clean text answer and prepending accumulated fcc_messages from
prior iterations. This matches the existing pattern used by the error
threshold and max_function_calls paths.
Also unskips test_max_iterations_limit and test_streaming_max_iterations_limit
which were previously skipped with 'needs investigation in unified API'.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add fix report for issue #1366
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix ruff formatting in _tools.py and test_issue_1366_thread_corruption.py
Apply ruff format to fix multi-line string concatenation and function call
formatting issues flagged by the linter.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add quality review for issue #1366 fix
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Remove temporary investigation docs.
* Address PR review: explicit enabled check in log condition, clarify mock behavior in test
- Add explicit function_invocation_configuration['enabled'] check to the
'Maximum iterations reached' log condition in both non-streaming and
streaming paths, making intent clearer when function invocation is disabled.
- Add comment in test_thread_safe_after_max_iterations_with_agent explaining
that the failsafe response (tool_choice='none') is provided automatically
by the mock client, not from run_responses.
* Blend fix and tests into project without issue-specific callouts
- Remove issue #1366 references from _tools.py comments
- Move regression tests from standalone test_issue_1366_thread_corruption.py
into test_function_invocation_logic.py alongside existing max_iterations tests
- Clean up test docstrings to describe behavior generically
- Delete the standalone issue-specific test file
---------
Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: prevent doubled tool_call arguments in MESSAGES_SNAPSHOT
When streaming with client-side tools, some providers send a full-
arguments replay after the streaming deltas complete. The `_emit_tool_call`
function unconditionally appends every arguments delta to the internal
`flow.tool_calls_by_id` tracking dictionary via `+=`. When the replay
contains the exact same complete arguments string that was already
accumulated from prior deltas, the arguments get doubled (e.g.,
`{"todoText":"buy groceries"}{"todoText":"buy groceries"}`).
This causes `MESSAGES_SNAPSHOT` events to contain invalid doubled JSON in
`tool_calls[].function.arguments`, breaking any client or middleware that
relies on snapshots for state reconstruction.
The fix adds a guard (mirroring the existing duplicate guard in
`_emit_text`) that detects when the incoming delta exactly equals the
already-accumulated arguments string, indicating a full-arguments replay
rather than an incremental delta. In this case the append is skipped,
preventing the doubling.
The `ToolCallArgsEvent` deltas are still emitted correctly for real-time
streaming — only the internal snapshot accumulator is guarded.
Fixes#4194
* fix: move duplicate check before event emission + add test
Address Copilot review feedback:
1. Move duplicate full-arguments replay detection BEFORE emitting
ToolCallArgsEvent, for consistency with _emit_text() which returns
early without emitting any events on replay detection.
2. Add test_emit_tool_call_skips_duplicate_full_arguments_replay() to
verify the duplicate detection behavior for tool call arguments,
matching the existing test pattern for text content.
* updated integration tests and guidance
* fixed merge test
* updated integration tests
* fix: remove duplicate --dist loadfile flag from pytest-xdist config
Only one --dist mode can be active at a time; the second value silently
overrides the first. Keep --dist worksteal (dynamic load balancing) and
remove the redundant --dist loadfile from all workflow files and
pyproject.toml configs.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* docs: add keep-in-sync notes for merge and integration test workflows
Both python-merge-tests.yml and python-integration-tests.yml share the
same parallel job structure. Added sync reminders in workflow file
comments, the python-testing SKILL.md, and CODING_STANDARD.md.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* refactor: remove RUN_INTEGRATION_TESTS flag
Integration test gating now uses two mechanisms:
- `@pytest.mark.integration` for test selection via `-m` filtering
- `skip_if_*_disabled` for credential/service availability checks
The RUN_INTEGRATION_TESTS env var was redundant since the marker handles
selection and the skip decorators already check for actual credentials.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: sync missing env vars from merge-tests to integration-tests
Add OPENAI_EMBEDDINGS_MODEL_ID and AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME
to python-integration-tests.yml to match python-merge-tests.yml.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: remove remaining RUN_INTEGRATION_TESTS from embedding tests and docs
Missed test_openai_embedding_client.py and vector-stores README in the
earlier cleanup.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* set functions tests to 3.10
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* feat(python): Add embedding abstractions and OpenAI implementation (Phase 1)
This PR contains two parts:
1. **Overall migration plan** for porting vector stores and embeddings from
Semantic Kernel to Agent Framework (docs/features/vector-stores-and-embeddings/README.md)
covering all 10 phases from core abstractions through connectors and TextSearch.
2. **Phase 1 implementation** — core embedding abstractions and OpenAI/Azure OpenAI
embedding clients:
Core types (_types.py):
- EmbeddingGenerationOptions TypedDict (total=False)
- Embedding[EmbeddingT] generic class with model_id, dimensions, created_at
- GeneratedEmbeddings[EmbeddingT, EmbeddingOptionsT] list container with options, usage
- EmbeddingInputT (default str) and EmbeddingT (default list[float]) TypeVars
Protocol + base class (_clients.py):
- SupportsGetEmbeddings protocol — Generic[EmbeddingInputT, EmbeddingT, OptionsContraT]
- BaseEmbeddingClient ABC — Generic[EmbeddingInputT, EmbeddingT, OptionsCoT]
Telemetry (observability.py):
- EmbeddingTelemetryLayer with gen_ai.operation.name = "embeddings"
OpenAI implementation (openai/_embedding_client.py):
- RawOpenAIEmbeddingClient, OpenAIEmbeddingClient, OpenAIEmbeddingOptions
- Uses _ensure_client() factory pattern
Azure OpenAI implementation (azure/_embedding_client.py):
- AzureOpenAIEmbeddingClient following AzureOpenAIChatClient pattern
- Supports API key, Entra ID credentials, env var configuration
Tests:
- 47 unit tests for types, protocol, base class, OpenAI, and Azure clients
- 6 integration tests (gated behind RUN_INTEGRATION_TESTS + credentials)
Samples:
- samples/02-agents/embeddings/openai_embeddings.py
- samples/02-agents/embeddings/azure_openai_embeddings.py
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Add AzureOpenAIEmbeddingClient to azure __init__.pyi stub
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* ci: Add embedding env vars to Python integration tests
Map OPENAI_EMBEDDING_MODEL_ID and AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME
from GitHub vars to the integration test environment.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Handle base64 encoding_format in OpenAI embedding client
When encoding_format='base64' is used, the OpenAI API returns base64-encoded
floats instead of a JSON array. Decode these automatically to list[float]
so the return type stays consistent regardless of encoding format.
Also adds a unit test for base64 decoding and fixes minor docstring/import issues.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Only record INPUT_TOKENS for embedding telemetry
Embeddings have no output/completion tokens. Remove OUTPUT_TOKENS recording
which was double-counting prompt_tokens via the total_tokens fallback.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Resolve mypy variance error and lint warning
Use contravariant/covariant TypeVars for SupportsGetEmbeddings Protocol.
Combine nested if into single statement in telemetry layer.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Make EmbeddingCoT invariant for mypy compatibility
GeneratedEmbeddings is invariant in its type param, so the Protocol
TypeVar cannot be covariant.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Address PR review - empty values guard, service_url for telemetry
- Add early return for empty values in get_embeddings to avoid unnecessary API calls
- Add service_url() method to RawOpenAIEmbeddingClient for proper telemetry endpoint reporting
- Add test for empty values behavior
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Python: Fix OpenAI chat client compatibility with third-party endpoints and OTel 0.4.14 (#4161)
* Fix system message content sent as list instead of string
Some OpenAI-compatible endpoints (e.g. NVIDIA NIM) reject system messages
when content is a list of content parts. This change flattens system and
developer message content to a plain string in the Chat Completions client.
Fixes https://github.com/microsoft/agent-framework/issues/1407
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix compatibility with opentelemetry-semantic-conventions-ai 0.4.14
Version 0.4.14 removed several LLM_* attributes from SpanAttributes
(LLM_SYSTEM, LLM_REQUEST_MODEL, LLM_RESPONSE_MODEL, LLM_REQUEST_MAX_TOKENS,
LLM_REQUEST_TEMPERATURE, LLM_REQUEST_TOP_P, LLM_TOKEN_TYPE).
Move these to the OtelAttr enum with their well-known gen_ai.* string values
and update all references in observability.py and tests.
Fixes https://github.com/microsoft/agent-framework/issues/4160
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Flatten text-only message content to string for all roles
Extend the system/developer fix to all message roles. Text-only content
lists are now post-processed into plain strings, while multimodal content
(text + images/audio) remains as a list. This fixes compatibility with
OpenAI-like endpoints that cannot deserialize list content (e.g. Foundry
Local's Neutron backend).
Partially fixes https://github.com/microsoft/agent-framework/issues/4084
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix streaming text lost when usage data in same chunk
Some providers (e.g. Gemini) include both usage data and text content
in the same streaming chunk. The early return on chunk.usage caused
text and tool call parsing to be skipped entirely. Remove the early
return and process usage alongside text/tool calls.
Fixes https://github.com/microsoft/agent-framework/issues/3434
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix mypy errors in _chat_client.py
Rename shadowed variable 'args' in system/developer branch to 'sys_args'
and rename loop variable 'content' to 'msg_content' to avoid type conflict.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* reorder imports
* fix: Use OtelAttr.REQUEST_MODEL instead of removed SpanAttributes.LLM_REQUEST_MODEL
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* docs: Add score_threshold to vector store plan
Reference SK .NET PR #13501 for score threshold filtering semantics.
Include score_threshold in SearchOptions from Phase 3.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* docs: Add reference to roji's SK .NET MEVD work for SQL connectors
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: Clear env vars in construction tests to avoid CI leakage
Tests for missing API key / model ID now use monkeypatch.delenv to ensure
env vars from the integration test environment don't prevent the expected
ValueError from being raised.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Python: Enhance Azure AI Search citations with document URLs in Foundry V2 (Responses API)
Override _parse_response_from_openai and _parse_chunk_from_openai in
RawAzureAIClient to extract get_urls from azure_ai_search_call_output
items and enrich url_citation annotations with document-specific URLs.
- Non-streaming: first pass collects get_urls, post-processes annotations
- Streaming: captures search output state, enriches url_citation events
(also handles url_citation annotation type not handled by base class)
- Updated V2 sample to demonstrate citation URL extraction
- Added 14 unit tests covering extraction, enrichment, and edge cases
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* refactor: rework search citation enrichment to override _inner_get_response
- Remove all direct openai/pydantic imports from _client.py
- Override _inner_get_response instead of _parse_response_from_openai/_parse_chunk_from_openai
- Use closure-local state for streaming instead of instance-level _streaming_search_get_urls
- Add _build_url_citation_content helper for streaming url_citation handling
- Fix mypy errors by using str(value or '') for Annotation TypedDict fields
- Fix docstring to say 'citation' instead of 'url_citation'
- Update tests to match new approach
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: handle streaming search citations from output_item.done events
The azure_ai_search_call_output item only has populated output data
(including get_urls) in the response.output_item.done event, not in
the response.output_item.added event. Also removed the search_get_urls
guard on url_citation handling so annotations are always produced even
if get_urls haven't been captured yet.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* addressed comments
* refactor: address PR review - eliminate type: ignore[assignment] pattern
Call super()._inner_get_response() independently in each branch instead
of once at the top with union type reassignment. Non-streaming uses
two-arg super() in the closure; streaming uses cast() for type narrowing.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* refactor: remove defensive patterns per PR review
- Replace all getattr() with direct attribute access
- Remove cast() for streaming branch, use type: ignore[assignment]
- Simplify _build_url_citation_content to use dict access directly
- Simplify _extract_azure_search_urls to use item.type/item.output
- Handle empty list output from streaming 'added' events
- Update tests to match actual runtime types (objects, not dicts)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* mypy fix
* small fixes
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add max_function_calls to FunctionInvocationConfiguration (#2329)
Add a new per-request max_function_calls setting to FunctionInvocationConfiguration
that limits the total number of individual function invocations across all iterations
within a single get_response call. This complements max_iterations (which limits LLM
roundtrips) by providing a hard cap on actual tool executions regardless of parallelism.
- Add max_function_calls field to FunctionInvocationConfiguration (default: None/unlimited)
- Track cumulative function call count in both streaming and non-streaming tool loops
- Force tool_choice='none' when the limit is reached
- Add validation in normalize_function_invocation_configuration
- Improve docstrings for FunctionInvocationConfiguration, FunctionTool, and @tool
to clarify semantics of max_iterations vs max_function_calls vs max_invocations
- Add tests for parallel calls, single calls, unlimited mode, and config validation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add sample for controlling total tool executions
Showcases all three mechanisms for limiting tool executions:
1. max_iterations — caps LLM roundtrips
2. max_function_calls — caps total individual function invocations per request
3. max_invocations — lifetime cap on a specific tool instance
Plus a combined scenario demonstrating defense in depth.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Suppress ruff E305/fmt in hosting sample to preserve XML doc tags
The XML snippet tags (# <create_agent> / # </create_agent>) are used for
docs extraction and must stay adjacent to the code they wrap. Both ruff
check (E305) and ruff format add blank lines after the function definition,
pushing the closing tag away. Suppress with ruff: noqa: E305 and fmt: off.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add per-agent tool wrapping scenario to control_total_tool_executions sample
Show that wrapping the same callable with @tool multiple times creates
independent FunctionTool instances with separate invocation counters,
enabling per-agent max_invocations budgets for shared functions.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Clarify max_function_calls is a best-effort limit
The limit is checked after each batch of parallel calls completes, so the
current batch always runs to completion even if it overshoots the limit.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Address PR review: fix docstring reference, clarify best-effort in sample
- Fix malformed Sphinx :attr: role in FunctionTool docstring — use plain
backtick reference instead
- Update sample to say 'best-effort cap' instead of 'hard cap' for
max_function_calls, noting it's checked between iterations
- Parametrize pattern is correct (fixture override, matching existing tests)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* clarify max_invocations limits
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix structured_output propagation in ClaudeAgent
Capture structured_output from ResultMessage in _get_stream() and
propagate it to AgentResponse.value via a custom finalizer. Previously
structured_output was silently discarded, making output_format unusable.
Fixes#4095
* Address review feedback: use value parameter instead of private properties
- Extend AgentResponse.from_updates() to accept optional value parameter
- Remove structured_output yield from _get_stream()
- Update _finalize_response() to pass value via public API
- Update streaming test to use get_final_response()
* Fix mypy errors: add value parameter to from_updates overloads
Add value parameter to both @overload signatures of
AgentResponse.from_updates() so mypy recognizes the argument.
---------
Co-authored-by: Amit Mukherjee <amimukherjee@microsoft.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
* .NET: Add Web Search sample #3674
* .NET: Fix WebSearch sample to use Responses API built-in web search
Remove incorrect Bing Grounding connection ID requirement from the
WebSearch sample. The web search tool uses the OpenAI Responses API
built-in capability and does not need a connection ID.
- Remove AZURE_FOUNDRY_BING_CONNECTION_ID env var requirement
- Use HostedWebSearchTool() without connectionId properties
- Refactor creation options into local functions (MEAI + NativeSDK)
- Switch from AzureCliCredential to DefaultAzureCredential
- Update README to reflect correct prerequisites
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix README to align DefaultAzureCredential docs with code
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Address review: add project to solution, README, simplify response text
- Add FoundryAgents_Step25_WebSearch to agent-framework-dotnet.slnx
- Add web search sample entry to parent FoundryAgents README.md
- Simplify text response extraction to use response.Text directly
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix merge conflict in slnx solution file
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
When converting base AgentRunOptions to ChatClientAgentRunOptions, the middleware
now preserves AllowBackgroundResponses, ContinuationToken, and AdditionalProperties
in addition to ResponseFormat.
Added unit test verifying all properties are preserved during the conversion.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Updated merge test permissions
* Removed repo check
* Added fetch from main for comparison
* Updated path detection logic
* Small updates
* Reverted file rename
* Created dedicated workflows for integration tests
* Small fix for Python
* Small fixes
* Small update
* Small update
* Added tests check for Python
* Add ChatClient decorator for calling AIContextProviders
* Format new files
* Address PR comments
* Revert problematic change
* Rename Use to UseAIContextProvider
* fix Workflow.as_agent() streaming regression in ag-ui
* Address PR feedback
* workflows wip
* wip
* wip
* Workflow AG-UI demo
* Fixes for handoff workflow demo
* Fixes to workflows support in AG-UI
* Fixes
* Add headers to some demo files
* Fix comment
* Fixes for store
* Make _input_schema lazy-loaded
* fix mypy
* revert session change to handoff only for now
---------
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
* Fix system message content sent as list instead of string
Some OpenAI-compatible endpoints (e.g. NVIDIA NIM) reject system messages
when content is a list of content parts. This change flattens system and
developer message content to a plain string in the Chat Completions client.
Fixes https://github.com/microsoft/agent-framework/issues/1407
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix compatibility with opentelemetry-semantic-conventions-ai 0.4.14
Version 0.4.14 removed several LLM_* attributes from SpanAttributes
(LLM_SYSTEM, LLM_REQUEST_MODEL, LLM_RESPONSE_MODEL, LLM_REQUEST_MAX_TOKENS,
LLM_REQUEST_TEMPERATURE, LLM_REQUEST_TOP_P, LLM_TOKEN_TYPE).
Move these to the OtelAttr enum with their well-known gen_ai.* string values
and update all references in observability.py and tests.
Fixes https://github.com/microsoft/agent-framework/issues/4160
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Flatten text-only message content to string for all roles
Extend the system/developer fix to all message roles. Text-only content
lists are now post-processed into plain strings, while multimodal content
(text + images/audio) remains as a list. This fixes compatibility with
OpenAI-like endpoints that cannot deserialize list content (e.g. Foundry
Local's Neutron backend).
Partially fixes https://github.com/microsoft/agent-framework/issues/4084
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix streaming text lost when usage data in same chunk
Some providers (e.g. Gemini) include both usage data and text content
in the same streaming chunk. The early return on chunk.usage caused
text and tool call parsing to be skipped entirely. Remove the early
return and process usage alongside text/tool calls.
Fixes https://github.com/microsoft/agent-framework/issues/3434
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix mypy errors in _chat_client.py
Rename shadowed variable 'args' in system/developer branch to 'sys_args'
and rename loop variable 'content' to 'msg_content' to avoid type conflict.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Extract 11 private const string fields for vector store property names
(Key, Role, MessageId, AuthorName, ApplicationId, AgentId, UserId,
SessionId, Content, CreatedAt, ContentEmbedding) and replace all inline
usages across the collection definition, store dictionary, search result
access, and filter expressions.
Fixes#3801
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add Azure AI Foundry Memory Context Provider with unit tests
* Add FoundryMemory integration tests and sample application
* Fix ClearStoredMemoriesAsync to handle 404 gracefully and rename to EnsureStoredMemoriesDeletedAsync
* Refactor FoundryMemory: simplify architecture and add memory store creation
- Remove IFoundryMemoryOperations interface (was only for test mocking)
- Remove AIProjectClientMemoryOperations wrapper class
- Provider now directly uses AIProjectClient with internal extension methods
- Extension methods return actual response models instead of extracted values
- Remove WaitForUpdateCompletionAsync from provider (sample uses delay)
- Simplify EnsureMemoryStoreCreatedAsync to return Task instead of Task<bool>
- Add memory store creation with chat_model and embedding_model
- Add UpdateMemoriesResponse with SupersededBy and Error fields
- Simplify unit tests to focus on constructor validation and serialization
- Update sample to use simple delay for memory processing wait
* Add waiting operation for memory store updates
* Fix UTF-8 BOM encoding for FoundryMemory csproj files
* Update copilot instructions for UTF-8 BOM and fix sample API rename
* Fix UTF-8 BOM encoding for TestableAIProjectClient.cs
* Add missing response headers for TS
* Changing default embedding
* Using the SDK Models
* Program update
* Remove debugging code from sample
* Adapt FoundryMemoryProvider to new AIContextProvider API and add UTF-8 BOM instruction
- Override ProvideAIContextAsync/StoreAIContextAsync instead of removed virtual InvokingAsync/InvokedAsync
- Use ProviderSessionState<State> for session-scoped state management (matching Mem0Provider pattern)
- Replace constructor-based scope with stateInitializer delegate
- Remove Serialize method (no longer on base class)
- Add SearchInputMessageFilter, StorageInputMessageFilter, StateKey to options
- Update sample to use AIContextProviders list instead of AIContextProviderFactory
- Update unit and integration tests for new API
- Add UTF-8 BOM encoding and --tl:off instructions to dotnet/AGENTS.md
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Use DefaultAzureCredential in Foundry Memory sample
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Address PR review comments for FoundryMemoryProvider
- Move memoryStoreName from options to required constructor parameter
- Make FoundryMemoryProviderScope require non-null/whitespace scope in constructor
- Make Scope property read-only (getter only)
- Replace ConcurrentQueue with single last update ID to fix memory leak
- Only clear pending update ID after successful completion
- Add delete success logging
- Mark FoundryMemoryProvider with [Experimental] attribute
- Update unit tests for new API signatures
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Use Throw.IfNullOrWhitespace for scope and memoryStoreName validation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* refactor: Normalize Run/RunStreaming with AIAgent
* refactor: Clarify Session vs. Run -level concepts
* Rename RunId to SessionId to better match Run/Session terminology in AIAgent
* [BREAKING]: Will break existing checkpointed sessions in CosmosDb due to field rename
* refactor: Rename and simplify interface around getting typed data out of ExternalRequest/Response
* Also adds hints around using value types in PortableValue
* refactor: Rename AddFanInEdge to AddFanInBarrierEdge
This will prevent a breaking change later when we introduce a programmable FanIn edge, analogous to the FanOut edge's EdgeSelector.
The goal, in the long run is to support a number of different FanIn scenarios, with naive FanIn (no barrier) by default, similar to FanOut.
* refactor: AsAgent(this Workflow, ...) => AsAIAgent(...)
* misc - part1: SwitchBuilder internal
---------
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
* fix: strip function_call and text_reasoning from cross-agent workflow handoff
When a reasoning model (e.g. gpt-5-mini) runs as Agent 1 in a workflow, its
response includes text_reasoning items (with server-scoped IDs like rs_XXXX)
and function_call items. Forwarding these to Agent 2 in a fresh conversation
caused API errors because the reasoning/call IDs are scoped to the original
stored response context.
Changes:
- Strip 'function_call', 'text_reasoning', 'function_approval_request', and
'function_approval_response' from handoff messages in _agent_executor.py
- Keep 'function_result' so the actual tool output content is preserved for
the next agent's context
- Update unit tests to reflect that function_result messages survive handoff
(messages grow from 2→3: user, tool(result), assistant(summary))
- Fix incorrect test assertions in test_function_invocation_stop_clears_*
that assumed the client layer updates session.service_session_id
- Also fixed _extract_function_calls to search all messages with call_id
deduplication, and the error-limit stop path to submit function_call_output
items before halting (via tool_choice=none cleanup call)
Relates to: https://github.com/microsoft/agent-framework/issues/4047
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix: reasoning model workflow handoff and history serialization
Fixes multiple related issues when using reasoning models (gpt-5-mini,
gpt-5.2) in multi-agent workflows that chain agents via from_response
or replay full conversation history via AgentExecutorRequest.
## Reasoning items always emitted on output_item.added
When a reasoning model produces encrypted or hidden reasoning (no
visible text), the Responses API still fires a reasoning output item
without any reasoning_text.delta events. Previously no text_reasoning
Content was emitted in that case, making it invisible to downstream
logic. Both the non-streaming (_parse_response_from_openai) and
streaming (output_item.added) paths now always emit at least one
text_reasoning Content — with empty text if no content is available —
so co-occurrence detection and serialization guards work reliably.
## Reasoning items only serialized when paired with a function_call
The Responses API only accepts reasoning items in input when they
directly preceded a function_call in the original response. Sending a
reasoning item that preceded a text response (no tool call) causes:
"reasoning was provided without its required following item"
_prepare_message_for_openai now checks has_function_call per message
and skips text_reasoning serialization when there is no accompanying
function_call.
## summary field is an array, not an object
The reasoning item summary field sent to the Responses API must be an
array of objects ([{"type": "summary_text", "text": ...}]), not a
single object. Fixed _prepare_content_for_openai accordingly.
## service_session_id cleared when explicit history is provided
When a workflow coordinator replays a full conversation (including
function calls from a previous agent run) back to an executor via
AgentExecutorRequest or from_response, the executor's session still
held a service_session_id (previous_response_id) from the prior run.
The API then received the same function-call items twice — once from
previous_response_id (server-stored) and once from the explicit input —
causing: "Duplicate item found with id fc_...".
AgentExecutor.run (when should_respond=True) and from_response now
reset self._session.service_session_id = None before running so that
explicit input is the sole source of conversation context.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* small improvements in text reasoning
* refactor: add reset_service_session to AgentExecutorRequest for explicit history replay
Replace the implicit 'always clear service_session_id when should_respond=True'
with an explicit opt-in field on AgentExecutorRequest.
The old approach used should_respond=True as a proxy for 'full history replay',
but that conflates two distinct intents:
- Orchestrations group chat sends should_respond=True with an empty/single-message
list (not a full replay) — unnecessarily clearing service_session_id.
- HITL / feedback coordinators send the full prior conversation and truly need
a fresh service session ID to avoid duplicate-item API errors.
Changes:
- Add AgentExecutorRequest.reset_service_session: bool = False
- AgentExecutor.run only clears service_session_id when this flag is True
- AgentExecutor.from_response unchanged (always clears; always full conversation)
- Set reset_service_session=True in all full-history-replay call sites:
agents_with_HITL.py, azure_chat_agents_tool_calls_with_feedback.py,
autogen-migration round-robin coordinator, tau2 runner
- Update _FullHistoryReplayCoordinator test helper to pass the flag
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* comment update
* fixes from feedback
* fix test
* reverted changes to agent executor
* fix: remove reset_service_session from tau2 runner
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* two other reverts
* fix sample
---------
Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix handoff orchestration not passing user message to handoff target agent (#3161)
Filter out internal handoff function call and tool result messages before
passing conversation history to the target agent's LLM. These messages
confused the model into ignoring the original user question.
* Add handoff tool call filtering behavior and enhance workflow builder
- Introduced HandoffToolCallFilteringBehavior enum to specify filtering behavior for tool call contents in handoff workflows.
- Updated HandoffsWorkflowBuilder to support customizable handoff instructions and tool call filtering behavior.
- Enhanced HandoffAgentExecutor to utilize new filtering options for improved message handling during agent handoffs.
* Enhance handoff message filtering logic and add unit tests for filtering behaviors
* Refactor HandoffMessagesFilter to remove unused handoff function names and enhance filtering logic for non-handoff function calls
* Refactor HandoffMessagesFilter to streamline FilterCandidateState initialization and improve clarity
* Refactor HandoffMessagesFilter to improve filtering logic and add integration tests for handoff workflows
* fix: HandoffAgentExecutor tests
* [BREAKING] refactor: Decouple Checkpointing and Execution APIs
With this change, Checkpointing becomes an property of an IWorkflowExecutionEnvironment. This lets environments that are tightly-coupled to their CheckpointManager avoid needing to present APIs that would not work (e.g. taking in an InMemory CheckpointManager for Durable Tasks, for example)
* refactor: Normalize IsCheckpointingEnabled naming
- Rename UserNameProvider → UserMemoryProvider
- Use session state (state dict) instead of instance variables
- Use context.extend_instructions() instead of context.instructions.append()
- Use DEFAULT_SOURCE_ID class attribute
- Fix imports to use public agent_framework API
- Add session state inspection at end of sample
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Track the last CheckpointInfo in InProcessRunner so that newly created
checkpoints reference their parent. When resuming from a checkpoint,
the resumed-from checkpoint becomes the parent of the next checkpoint.
Adds tests verifying:
- First checkpoint has null parent
- Subsequent checkpoints chain parents correctly
- Checkpoint after resume references the resumed-from checkpoint
* feat: Implement Polymorphic Routing
* feat: Add support for Send/Yield annotations with basic Executor
* Adds annotations to Declarative workflow executors
* fix: Address PR Comments
* Implicit filter in collection loops
* Remove debug / usused / superfluous code
* Fix ProtocolBuilder implicit output registrations
* Fix logic error in ExecuteRouteGeneratorTests.ClassWithManualConfigureProtocol_DoesNotGenerate
* fix: Solidify type checks and send/yield type registrations
* fix: Suppress generation of TurnTokens out of AggregateTurnMessagesExecutor
* Fixes an issue where ConcurrentEndExecutor is not expecting TurnTokens.
* fix: Add ProtocolBuilder support for chained-delegation
* Updates Declarative pacakge to rely on chained-delegation Send/Yield registration
* Renames DeclarativeActionExectuor's new ExecuteAsync to ExecuteActionAsync to avoid colliding with Executor.ExecutoeAsync
* fix: Address PR Comments
* Fixes type mapping in FanInEdgeRunner
* Fixes and expalins send/yield type registration in FunctionExecutor
* fixup: build-break
* fix: Add missing SendsMesage declaration to InvokeAzureAgentExecutor
* Fix FoundryAgents_Step15_ComputerUse sample for Azure Agents API
The Azure Agents API rejects previous_response_id alongside computer_call_output
items, unlike the vanilla OpenAI Responses API. This fix:
- Send all prior response output items (reasoning, computer_call, etc.) as input
items in follow-up calls so the API has full conversation context
- Create a fresh session per call to avoid ConversationId/previous_response_id
- Use currentCallId instead of initialCallId for computer_call_output
- Clear ContinuationToken after polling to prevent stale tokens
- Remove unused initialCallId tracking variable
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Address comments
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Initial Implementation of InvokeFunctionTool
* Added unit test for InvokeFunctionTool executor.
* Implemented unit and integration tests for InvokeFunctionTool.
* Add sample for InvokeFunctionTool in declarative workflows.
* Remove unused sample and updated comments.
* Updating to official OM release with InvokeFunctionTool
* Fix formatting issues.
* Updated PowerFx version
* Update test fixture
* Cleanup - Removed unused method in InvokeFunctionToolExecutor
* Update test based on PR feedback.
* Update based on PR comments
* Rename WorkflowOutputEvent.SourceId to ExecutorId for Python consistency
- Rename SourceId property to ExecutorId in WorkflowOutputEvent
- Add [Obsolete] SourceId property for backward compatibility
- Update all test usages to use ExecutorId
Resolves part of #2938
* Unify AgentResponse events with WorkflowOutputEvent (#2938)
- Change AgentResponseEvent and AgentResponseUpdateEvent to inherit from
WorkflowOutputEvent instead of ExecutorEvent
- Update AIAgentHostExecutor and HandoffAgentExecutor to use YieldOutputAsync()
instead of AddEventAsync() for agent outputs
- Add special-casing in InProcessRunnerContext.YieldOutputAsync() to create
specific event types for AgentResponse and AgentResponseUpdate, bypassing
OutputFilter for backwards compatibility
- Update TestRunContext and TestWorkflowContext with same special-casing
- Add regression tests in AgentEventsTests
* refactor: Seal AgentResponse events
- Update ModelContextProtocol NuGet package from 0.4.0-preview.3 to 0.8.0-preview.1
- Update System.Net.ServerSentEvents from 10.0.1 to 10.0.3
- Fix OAuth config to use DynamicClientRegistration in Agent_MCP_Server_Auth
- Fix incorrect sample name references in README files
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Initial plan
* Add Foundry evaluation samples for Red Teaming and Self-Reflection
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Refactor evaluation samples with real implementations in local functions
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Uncomment function signatures and bodies, keep only invocations commented
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Update Foundry evaluation samples with observability support
* Restructure evaluation samples to follow FoundryAgents naming convention
- Rename Evaluation/Evaluation_StepXX to FoundryAgents_Evaluations_StepXX
- Add evaluation projects to slnx
- Fix var usage, apply dotnet format, use DefaultAzureCredential
- Add try/finally for agent cleanup
- Fix evaluator deployment name separation in Step02
- Update README references
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Rewrite Step01 to use Azure.AI.Projects RedTeam API and address review comments
- Replace safety evaluator sample with actual Red Teaming using AIProjectClient.RedTeams
- Use AttackStrategy (Easy, Moderate, Jailbreak) and RiskCategory from Azure.AI.Projects
- Remove Microsoft.Extensions.AI.Evaluation.Safety dependency from Step01
- Add DefaultAzureCredential warning comments to Step02
- Remove unused bestResponse variable in Step02
- Add session isolation comments in self-reflection loop
- Fix stale directory references in READMEs
- Fix misleading evaluation overview link in main README
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add note about agent-targeted red teaming limitations in README
The .NET RedTeam API currently only supports model deployment targets
via AzureOpenAIModelConfiguration. Agent-targeted red teaming with
AzureAIAgentTarget is documented in concept docs but not yet available
in the SDK's RedTeam constructor. Results appear in classic portal view.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add classic Foundry disclaimer to red teaming sample README
Clarify that this sample uses the classic Azure AI Foundry red teaming
API (/redTeams/runs). The new Foundry portal uses a separate evaluation-
based API not yet available in the .NET SDK. AzureAIAgentTarget exists
in the SDK but is consumed by the Evaluation Taxonomy API, not RedTeam.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Address PR review comments on Step02 SelfReflection
- Pass full prompt (with context) to evaluator messages instead of just
the question, so evaluator input matches what the agent received
- Include previous response text in self-reflection refinement prompt
so the LLM can meaningfully improve its answer across iterations
- Inline CreateKnowledgeAgent helper (single use, single statement)
- Add comment clarifying why RunCombinedQualityAndSafetyEvaluation
intentionally passes only the question (no context)
Co-authored-by: Copilot <223556219+Copilot@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>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Python: improve .env precedence and observability samples
- Switch load_settings to explicit precedence: overrides -> explicit .env -> environment -> defaults\n- Raise when env_file_path is provided but missing\n- Update settings docs and tests for new behavior\n- Refresh observability samples and README guidance for env loading options\n\nCloses #3864\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fixed some imports
* Fix load_settings CI regressions
Allow explicit env_file_path values that exist but are not regular files (for example /dev/null) by checking path existence before dotenv parsing, and restore a dict accumulator with typed return cast to satisfy mypy.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Avoid implicit dotenv in observability
Only load dotenv in observability helpers when env_file_path is explicitly provided, and remove test os.devnull workarounds that are no longer necessary.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fix streaming branch in weather override middleware sample
The streaming branch of weather_override_middleware only prefixed the
original weather data via a transform hook instead of replacing the
content with the 'perfect weather' override like the non-streaming
branch does. Replace with a new ResponseStream that yields the override
content as ChatResponseUpdate chunks.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Fixed exception handling middleware sample
* Fixed runtime context delegation middleware example
* Fixed multimodal input examples
* Small update
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add workflow support for Azure Functions
* fix compatability with latest framework changes and add integration tests
* refactor code
* remove white space
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* align help text with actual port used
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* replace instance id with a place holder
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* remove unused import
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* remove redundant typing import and fix SIM115
* fix latest breaking changes
* fix mypy issues
* clean up imports
* define source marker strings as constants
* fix json module name
* refactor _extract_message_content_from_dict
* refactor serialization
* add helper method for error response construction and remove _extract_message_content_from_dict since it is not needed
* use strict tpe checking for edges
* change how duplicate agent registrations are handled
* cancel approval_task on HITL timeout
* update docstring
* fix: align azurefunctions package with core API changes after rebase
- State.import_state/export_state are now sync (removed await)
- Add State.commit() before export_state() in activity execution
- Rename executor parameter shared_state -> state
- Rename ctx.set_shared_state/get_shared_state -> set_state/get_state (sync)
- WorkflowBuilder now takes start_executor as constructor kwarg
- Update WorkflowOutputEvent -> WorkflowEvent with type='output'
- Update RequestInfoEvent -> WorkflowEvent[Any]
- Update SharedState -> State in test imports
- Update duplicate agent name tests to match new warning behavior
- Update sample README API references
* fix sample check errors
* fix mypy issues
* fix trailing white spaces
* fix test imports
* feat: add durable workflow samples and adapt to main branch changes
- Add workflow samples 09-12 to 04-hosting/azure_functions/
- Adapt to ChatMessage -> Message rename from main
- Adapt to pickle-based checkpoint encoding from main
- Simplify _serialization.py to delegate to core encode/decode
- Fix Message -> WorkflowMessage disambiguation in _context.py
- Remove non-existent _checkpoint_summary import
* fix: update create_checkpoint signature to match superclass
* fix: correct relative link in HITL sample README
* fix: resolve import breakage after rebase (State, DurableAgentThread, get_logger)
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
Enable automatic synchronization with the active item in VS Code for better
developer experience when working with .NET projects.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* feat: Inject OpenTelemetry trace context into MCP requests and update documentation
* Update python/samples/getting_started/observability/README.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/core/tests/core/test_mcp.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* refactor: move opentelemetry import to module level
OpenTelemetry is a hard dependency of agent-framework-core (per
pyproject.toml), so the try/except ImportError guard was dead code.
Move the import to the top of the file to fail fast on missing
dependencies instead of silently hiding installation issues.
---------
Co-authored-by: Pete Roden <Pete.Roden@microsoft.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Fix#3600: Pass JSON schemas through without Pydantic conversion
This change optimizes FunctionTool and MCP flows by passing JSON schemas
directly to providers without converting them to Pydantic models first.
Key changes:
- Store JSON schema as-is when supplied to FunctionTool
- Skip Pydantic model_validate for schema-supplied tools in invoke()
- Return MCP tool schemas directly without conversion
- Add comprehensive tests for schema passthrough behavior
Performance benefits:
- Eliminates expensive Pydantic model creation for supplied schemas
- Preserves exact schema structure (additionalProperties, custom fields, etc.)
- Reduces memory overhead and initialization time
Maintains backward compatibility:
- Function signature inference still uses Pydantic models
- Explicit Pydantic models passed as input_model work as before
- All existing tests pass
* Fix schema passthrough validation and remove helper
* Simplify FunctionTool without generic model dependency
* Fix FunctionTool typing fallout in 3600
* Remove FunctionTool[Any] compatibility shim
* Use serializable kwargs in OTEL tool args
* .NET: [BREAKING] Add session statebag to use for state storage instead of inside providers (#3737)
* Add a StateBag to AgentSession and pass Agent and AgentSession to AIContextProvider and ChatHistoryProviders
* Convert all AIContextProviders to use the statebag
* Update InMemoryChatHistoryProvider to use StateBag
* Update Comsos and Workflow ChatHistoryProviders
* Update 3rd party chat history storage sample.
* Remove serialize method from providers
* Replacing provider factories with properties
* Remove Providers from Session and flatten state bag serialization
* Update samples to use getservice on agent
* Updated additional session types to serialize statebag
* Fix regression
* Address PR comments
* Address PR comments.
* Fix formatting
* Fix unit tests
* Remove InMemoryAgentSession since it is not required anymore.
* Address PR comments
* Convert sessions for A2AAgent, ChatClientAgent, CopilotStudioAgent and GithubCopilotAgent to use regular json serialization.
* Fix durable agent session jso usgae
* Add jso to InMemory and Workflow ChatHistoryProviders
* Update InMemoryChatHistoryProvider to use an options class for it's many optional settings.
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Address PR feedback
* Fix verification bug.
* Improve state bag thread safety
* Address PR comments and fix unit tests
* Address PR comments
* Fix unit test
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Add a public StateKey property to providers (#3810)
* .NET: [BREAKING] Update providers in such a way that they can participate in a pipeline (#3846)
* Make providers pipeline capable
* Fix unit tests
* Move source stamping to providers from base class
* Also update samples.
* Address PR comments
* Rename AsAgentRequestMessageSourcedMessage to WithAgentRequestMessageSource
* .NET: [BREAKING] Add consistent message filtering to all providers. (#3851)
* Add consistent message filtering to all providers.
* Remove old chat history filtering classes
* Fix merge issues
* Fix unit test
* Enforce non-nullable property
* Fix merging bug and make troubleshooting source info easier by adding tostring implementation
* .NET: [BREAKING] Add support for multiple AIContextProviders on a ChatClientAgent (#3863)
* Add support for multiple AIContextProviders on a ChatClientAgent
* Address PR comments and fix tests
* Address PR comments.
* .NET: [BREAKING]Delay AIContext Materialization until the end of the pipeline is reached. (#3883)
* Delay AIContext Materialization until the end of the pipeline is reached.
* Address PR comments.
* Address PR comments
* Modify InvokedContext to be immutable (#3888)
* .NET: Address Feedback on StateBag feature branch PR (#3910)
* Address Feedback on statebag feature branch PR
* Update dotnet/src/Microsoft.Agents.AI.DurableTask/CHANGELOG.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Address PR comments
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Python: Replace wildcard imports with explicit imports
- Replace all 'from ... import *' with explicit symbol imports
- Add __all__ declarations to namespace packages for re-exports
- Update CODING_STANDARD.md to prohibit wildcard imports
- Maintain exported API and preserve all functionality
fixes#3605
* Refine wildcard guidance example text
* Simplify explicit exports without self-aliases
* fix: prevent repeating instructions in continued Responses API conversations
- Instructions are now only prepended to messages on the first turn
- When conversation_id/response_id exists (continuation), instructions are skipped
- Covers OpenAI and Azure Responses API paths
- Adds regression tests for all continuation scenarios
Fixes#3498
* Apply lint fixes to continuation tests
* Consolidate responses continuation tests
* PR2: Wire context provider pipeline and update all internal consumers
- Replace AgentThread with AgentSession across all packages
- Replace ContextProvider with BaseContextProvider across all packages
- Replace context_provider param with context_providers (Sequence)
- Replace thread= with session= in run() signatures
- Replace get_new_thread() with create_session()
- Add get_session(service_session_id) to agent interface
- DurableAgentThread -> DurableAgentSession
- Remove _notify_thread_of_new_messages from WorkflowAgent
- Wire before_run/after_run context provider pipeline in RawAgent
- Auto-inject InMemoryHistoryProvider when no providers configured
* fix: update all tests for context provider pipeline, fix lazy-loaders, remove old test files
* refactor: update all sample files for context provider pipeline (AgentThread→AgentSession, ContextProvider→BaseContextProvider)
* fix: update remaining ag-ui references (client docstring, getting_started sample)
* fix: make get_session service_session_id keyword-only to avoid confusion with session_id
* refactor: rename _RunContext.thread_messages to session_messages
* refactor: remove _threads.py, _memory.py, and old provider files; migrate devui to use plain message lists
* rename: remove _new_ prefix from test files
* refactor: rewrite SlidingWindowChatMessageStore as SlidingWindowHistoryProvider(InMemoryHistoryProvider)
* fix: read full history from session state directly instead of reaching into provider internals
* fix: update stale .pyi stubs, sample imports, and README references for new provider types
* fix: remove stale message_store, _notify_thread_of_new_messages, and session_id.key references in samples
* refactor: merge context_providers and sessions sample folders into sessions, remove aggregate_context_provider
* refactor: UserInfoMemory stores state in session.state instead of instance attributes
* feat: add Pydantic BaseModel support to session state serialization
Pydantic models stored in session.state are now automatically serialized
via model_dump() and restored via model_validate() during to_dict()/from_dict()
round-trips. Models are auto-registered on first serialization; use
register_state_type() for cold-start deserialization.
Also export register_state_type as a public API.
* fix mem0
* Update sample README links and descriptions for session terminology
- Replace 'thread' with 'session' in sample descriptions across all READMEs
- Update file links for renamed samples (mem0_sessions, redis_sessions, etc.)
- Fix Threads section → Sessions section in main samples/README.md
- Update tools, middleware, workflows, durabletask, azure_functions READMEs
- Update architecture diagrams in concepts/tools/README.md
- Update migration guides (autogen, semantic-kernel)
* Fix broken Redis README link to renamed sample
* Fix Mem0 OSS client search: pass scoping params as direct kwargs
AsyncMemory (OSS) expects user_id/agent_id/run_id as direct kwargs,
while AsyncMemoryClient (Platform) expects them in a filters dict.
Adds tests for both client types.
Port of fix from #3844 to new Mem0ContextProvider.
* Fix rebase issues: restore missing _conversation_state.py and checkpoint decode logic
- Add back _conversation_state.py (encode/decode_chat_messages) lost in rebase
- Fix on_checkpoint_restore to decode cache/conversation with decode_chat_messages
- Fix on_checkpoint_restore to use decode_checkpoint_value for pending requests
- Add tests/workflow/__init__.py for relative import support
- Fix test_agent_executor checkpoint selection (checkpoints[1] not superstep)
* Add STORES_BY_DEFAULT ClassVar to skip redundant InMemoryHistoryProvider injection
Chat clients that store history server-side by default (OpenAI Responses API,
Azure AI Agent) now declare STORES_BY_DEFAULT = True. The agent checks this
during auto-injection and skips InMemoryHistoryProvider unless the user
explicitly sets store=False.
* Fix broken markdown links in azure_ai and redis READMEs
* Fix getting-started samples to use session API instead of removed thread/ContextProvider API
* updates to workflow as agent
* fix group chat import
* Rename Thread→Session throughout, fix service_session_id propagation, remove stale AGUIThread
- Fix: Propagate conversation_id from ChatResponse back to session.service_session_id
in both streaming and non-streaming paths in _agents.py
- Rename AgentThreadException → AgentSessionException
- Remove stale AGUIThread from ag_ui lazy-loader
- Rename use_service_thread → use_service_session in ag-ui package
- Rename test functions from *_thread_* to *_session_*
- Rename sample files from *_thread* to *_session*
- Update docstrings and comments: thread → session
- Update _mcp.py kwargs filter: add 'session' alongside 'thread'
- Fix ContinuationToken docstring example: thread=thread → session=session
- Fix _clients.py docstring: 'Agent threads' → 'Agent sessions'
* Fix broken markdown links after thread→session file renames
* fix azure ai test
* Update GitHub.Copilot.SDK to 0.1.23 and copy new session config properties
- Bump GitHub.Copilot.SDK from 0.1.18 to 0.1.23
- Add new SessionConfig properties: ReasoningEffort, Hooks, OnUserInputRequest,
WorkingDirectory, ConfigDir, InfiniteSessions
- Add missing ResumeSessionConfig properties: Model, SystemMessage,
AvailableTools, ExcludedTools, ReasoningEffort, Hooks, OnUserInputRequest,
WorkingDirectory, ConfigDir, InfiniteSessions
- Fix UserMessageDataAttachmentsItem -> UserMessageDataAttachmentsItemFile
for new polymorphic attachment API
- Add unit tests for new session config properties
* Address PR review: centralize config mapping and improve test coverage
- Extract CopySessionConfig/CopyResumeSessionConfig as internal static helpers
to eliminate duplicated mapping logic between RunCoreStreamingAsync and
CreateResumeConfig (addresses reviewer comment on drift risk)
- Add InternalsVisibleTo for unit test project
- Replace shallow constructor tests with comprehensive property-verification
tests that validate every config property is correctly copied, including
OnUserInputRequest (addresses reviewer comments on test coverage)
* Remove accidentally committed git-lfs hooks
* restructure: Python samples into progressive 01-05 layout
- 01-get-started/: 6 numbered steps (hello agent → hosting)
- 02-agents/: all agent concept samples (tools, middleware, providers, etc.)
- 03-workflows/: ALL existing workflow samples preserved as-is
- 04-hosting/: azure-functions, durabletask, a2a
- 05-end-to-end/: demos, evaluation, hosted agents
- Old files moved to _to_delete/ for review
- Added AGENTS.md with structure documentation
- autogen-migration/ and semantic-kernel-migration/ preserved at root
* fix: switch to AzureOpenAI Foundry, fix CI failures
- Switch all 01-get-started samples to AzureOpenAIResponsesClient with
Azure AI Foundry project endpoint (AZURE_AI_PROJECT_ENDPOINT +
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME + AzureCliCredential)
- Add _to_delete/ and 05-end-to-end/ to pyrightconfig.samples.json excludes
- Fix test paths in packages/ that referenced old getting_started/ dirs:
durabletask conftest + streaming test, azurefunctions conftest,
devui conftest + capture_messages + openai_sdk_integration
- Fix workflow_as_agent_human_in_the_loop.py import (sibling import)
- Update hosting READMEs and tool comment paths
- Replace root README.md with new structure overview
- Update AGENTS.md to document Azure OpenAI Foundry as default provider
* cleanup: remove _to_delete folder, copy resource files to active dirs
All files in _to_delete/ were either:
- Exact duplicates of files in the new structure (240 files)
- Same file with only comment path updates (100 files)
- One import-fix diff (workflow_as_agent_human_in_the_loop.py)
- One superseded minimal_sample.py
Resource files (sample.pdf, countries.json, employees.pdf, weather.json)
copied to 02-agents/sample_assets/ and 02-agents/resources/ since active
samples reference them.
* fix: address PR review comments, centralize resources, remove root duplicates
- Fix type annotation in 04_memory.py (string union -> proper types)
- Fix old sample paths in observability files
- Fix grammar/spelling in observability samples
- Move sample_assets/ and resources/ to shared/ folder
- Remove 8 duplicate observability files from 02-agents root
- Update resource path references in multimodal_input and provider samples
* fix: update broken links from old getting_started paths to new structure
- Update relative paths in READMEs: getting_started/ → 01-get-started/,
02-agents/, 03-workflows/, 04-hosting/, 05-end-to-end/
- Fix absolute GitHub URLs in package READMEs
- Fix broken link in ollama package README
* fix: convert absolute GitHub URLs to relative paths for link checker
Absolute URLs to python/samples/ on main branch 404 until PR merges.
Converted to relative paths that linkspector can verify locally.
* fix: update link for handoff sample moved to orchestrations/
* fix: update chatkit-integration README path from demos/ to 05-end-to-end/
* fix: update broken links in orchestrations README to match flat directory structure
* Centralize tool result parsing in FunctionTool.invoke()
- Add parse_result static method to FunctionTool that converts raw
function return values to strings at invocation time
- Add result_parser parameter to FunctionTool and @tool decorator
for custom parsing
- Remove prepare_function_call_results from all 9 consumer files
and from the public API
- Update MCPTool to parse MCP types directly to strings via
_parse_tool_result_from_mcp and _parse_prompt_result_from_mcp
- Change MCPTool parse_tool_results/parse_prompt_results type from
Literal[True] | Callable | None to Callable | None
- Remove ReturnT type parameter from FunctionTool (now single
generic ArgsT since invoke() always returns str)
- Update all subclass signatures and docstrings
Fixes#1147
* Fix test_mcp_tool_call_tool_with_meta_integration for string results
The test was still accessing result[0].additional_properties but
invoke() now returns a string, not a list of Content objects.
* Fix SIM108 lint: use binary operator for output assignment
* Fix bedrock: use FunctionTool.parse_result instead of str() fallback
str(result) turns None into literal 'None' and dicts into Python reprs
with single quotes, breaking JSON parsing. Use the shared parse_result
which handles None as '' and serializes via json.dumps.
* updated lock
* updates from feedback
* Replace Pydantic Settings with TypedDict + load_settings()
- Remove pydantic-settings dependency, add python-dotenv
- Delete _pydantic.py (AFBaseSettings, HTTPsUrl)
- Add _settings.py with generic load_settings() function, SecretString,
type coercion, and Required field validation (SettingNotFoundError)
- Convert all 13 settings classes from AFBaseSettings subclasses to
TypedDict definitions with load_settings() calls
- Update all consumers from attribute access to dict access
- Add 20 unit tests for load_settings() covering basic loading, dotenv,
SecretString, type coercion, and required field validation
- Update all existing tests for new settings patterns
* Fix mypy type errors from settings conversion
- Fix str | None attribute access in responses_client (walrus operator)
- Fix SecretString | None narrowing in bedrock (type: ignore after guard)
- Convert _context_provider.py attribute access to dict access (missed file)
- Fix endpoint type narrowing in search_provider and context_provider
- Fix purview: str | None .rstrip(), int | None defaults, urlparse bytes
* Address PR review: required_fields param, type validation, fixes
- Move required field validation from TypedDict annotations (Required)
to a required_fields parameter on load_settings(), enabling runtime
decisions about which fields are required
- Remove Required imports and restore from __future__ import annotations
in ollama and foundry_local
- Add _check_override_type() for deterministic ServiceInitializationError
on invalid override types (e.g. dict passed for str field)
- Fix all multi-exception test catches back to single exception type
- Fix Ollama host=None: use .get() so None is passed through to SDK default
- Fix Purview processor: use explicit is-None checks instead of or operator
- Remove unused BaseModel import from openai/_shared.py
- Add 4 new tests (24 total): required_fields param, type validation
* Fix type validation: allow int for float fields
_check_override_type now permits int values for float-typed fields,
matching Python's standard numeric promotion behavior.
* fix: wrap urlparse arg with str() to fix mypy bytes endswith error
* Initial plan
* feat: extend AzureOpenAIResponsesClient to support Foundry project endpoints
Add project_client and project_endpoint parameters to allow creating
the client via an Azure AI Foundry project. When provided, the client
uses AIProjectClient.get_openai_client() to obtain the OpenAI client.
The azure-ai-projects package is imported lazily and only required
when using the project endpoint path.
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* fix: address code review - remove duplicate MagicMock imports in tests
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* fix: add type field to Responses API input items and add Foundry sample
- Add 'type: message' to input items in _prepare_message_for_openai
to comply with the Responses API schema requirement
- Filter out empty dicts from unsupported content types to prevent
sending items with invalid empty type values
- Add azure_responses_client_with_foundry.py sample demonstrating
AzureOpenAIResponsesClient with project_endpoint
- Update README and pyrightconfig.samples.json accordingly
* updates to response format and setup
* fix: patch AIProjectClient at correct module path in test
Patch agent_framework.azure._responses_client.AIProjectClient instead of
azure.ai.projects.aio.AIProjectClient since the import is at module level.
* docs: add Foundry sample to READMEs and document AZURE_AI_PROJECT_ENDPOINT env var
---------
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>
* Initial plan
* Add comprehensive unit tests for EditTableV2Executor
- Test AddItemOperation with record and scalar values
- Test ClearItemsOperation
- Test RemoveItemOperation
- Test TakeLastItemOperation (with items and empty table)
- Test TakeFirstItemOperation (with items and empty table)
- Test error cases (null ItemsVariable, non-table variable)
- Include ExecuteTestAsync and CreateModel helper methods
- All 10 tests passing
Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>
* Add comprehensive unit tests for EditTableV2Executor - complete with 100% coverage
- Added 13 comprehensive tests covering all code paths
- Test AddItemOperation with record and scalar values
- Test ClearItemsOperation
- Test RemoveItemOperation (including non-table value case)
- Test TakeLastItemOperation (with items and empty table)
- Test TakeFirstItemOperation (with items and empty table)
- Test error cases (null ItemsVariable, non-table variable, null operation values)
- Include ExecuteTestAsync and CreateModel helper methods
- 100% line and branch coverage achieved
Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>
* Update tests / refine product code
* Checkpoint
* Updated
* Update dotnet/tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/ObjectModel/SetTextVariableExecutorTest.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Address code review feedback
- Fix typo: rename metadataExpresssion to metadataExpression
- Fix test name in AddMessageWithMetadataAsync (was using wrong test name)
- Fix test name in ClearGlobalScopeAsync (was using wrong test name)
- Remove pre-population in SetTextVariableExecutorTest that made tests ineffective
- Use explicit .Where() filter in SetMultipleVariablesExecutorTest foreach loop
Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: crickman <66376200+crickman@users.noreply.github.com>
Co-authored-by: Chris Rickman <crickman@microsoft.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* PR1: Add core context provider types and tests
New types in _sessions.py (no changes to existing code):
- SessionContext: per-invocation state with extend_messages/get_messages/
extend_instructions/extend_tools and read-only response property
- _ContextProviderBase: base class with before_run/after_run hooks
- _HistoryProviderBase: storage base with load/store flags, abstract
get_messages/save_messages, default before_run/after_run
- AgentSession: lightweight session with state dict, to_dict/from_dict
- InMemoryHistoryProvider: built-in provider storing in session.state
35 unit tests covering all classes and configuration flags.
* feat: keyword-only params, stateless InMemoryHistoryProvider, deep serialization
- Make before_run/after_run parameters keyword-only
- InMemoryHistoryProvider stores ChatMessage objects directly (no per-cycle serialization)
- Deep serialization via to_dict/from_dict only at session boundary
- State type registry for automatic deserialization of registered types
- Updated tests for new serialization approach
* feat: add new-pattern provider implementations for external packages
- _RedisContextProvider(BaseContextProvider) - Redis search/vector context
- _RedisHistoryProvider(BaseHistoryProvider) - Redis-backed message storage
- _Mem0ContextProvider(BaseContextProvider) - Mem0 semantic memory
- _AzureAISearchContextProvider(BaseContextProvider) - Azure AI Search (semantic + agentic)
All use temporary _ prefix names for side-by-side coexistence with existing providers.
Will be renamed in PR2 when old ContextProvider/ChatMessageStore are removed.
* test: add tests for new-pattern provider implementations
- 32 tests for _RedisContextProvider and _RedisHistoryProvider
- 29 tests for _Mem0ContextProvider
- 17 tests for _AzureAISearchContextProvider
* fix: address PR review comments and CI failures
- Move module docstring before imports in _sessions.py (review comment)
- Import TYPE_CHECKING unconditionally in Redis _context_provider.py (NameError on Python <3.12)
- Fix Mem0 test_init_auto_creates_client_when_none to patch at class level
* feat: add source attribution to extend_messages
Set attribution marker in additional_properties for each message
added via extend_messages(), matching the tool attribution pattern.
Uses setdefault to preserve any existing attribution.
* refactor: make attribution value a dict with source_id key
* add attribution and use sets for filters
* Add source_type to message attribution and copy messages in extend_messages
- SessionContext.extend_messages now accepts source as str or object with
source_id attribute; when an object is passed, its class name is recorded
as source_type in the attribution dict
- Messages are shallow-copied before attribution is added so callers'
original objects are never mutated
- Filter framework-internal keys (attribution) from A2A wire metadata
to prevent leaking internal state over the wire
* fix: correct mypy type: ignore comment from union-attr to attr-defined
* set attribution to _attribution
* adjusted naming of bools
* Python: Add long-running agents and background responses support
- Add ContinuationToken TypedDict to core types
- Add continuation_token field to ChatResponse, ChatResponseUpdate,
AgentResponse, and AgentResponseUpdate
- Add background and continuation_token options to OpenAIResponsesOptions
- Implement polling via responses.retrieve() and streaming resumption
in RawOpenAIResponsesClient
- Propagate continuation tokens through agent run() and
map_chat_to_agent_update
- Fix streaming telemetry 'Failed to detach context' error in both
ChatTelemetryLayer and AgentTelemetryLayer by avoiding
trace.use_span() context attachment for async-managed spans
- Add 14 unit tests for continuation token types and background flows
- Add background_responses sample showing polling and stream resumption
Fixes#2478
* Python: Add A2A long-running task support via ContinuationToken
- Make ContinuationToken provider-agnostic (total=False, optional task_id/context_id fields)
- Add background param to A2AAgent.run() controlling token emission
- Add poll_task() for single-request task state retrieval
- Add resubscribe support via continuation_token param on run()
- Extract _updates_from_task() and _map_a2a_stream() for cleaner code
- Streamline run()/streaming by removing intermediate _stream_updates wrapper
- Update A2A sample to show background=False (default) with link to background_responses sample
- Remove stale BareAgent from __all__
- Add 12 new A2A continuation token tests
* fix logic for overriding continuation token when done
* refactored ContinuationToken setup
* Update message source code to match python.
* Apply suggestion from @Copilot
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Address PR comment
* Move setting of source information to extension method
* Add underscore for attribution key to indicate internal usage
* Stick to version 102 of the SDK since 103 is causing issues.
* Revert global.json change
* Fix unit test
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
RunCoreStreamingAsync was passing inputMessagesForProviders (which lacks
chat history) to GetStreamingResponseAsync instead of
inputMessagesForChatClient (which includes chat history). This caused
streaming runs to lose conversation context on subsequent calls.
The non-streaming path (RunCoreAsync) already correctly used
inputMessagesForChatClient. This aligns the streaming path to match.
Also adds a unit test that validates chat history is included in
messages sent to the chat client during streaming on subsequent calls.
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: lokitoth <6936551+lokitoth@users.noreply.github.com>
* Python: fix prek runner running fmt/lint in all packages on core change
When a core package file changed, run_tasks_in_changed_packages.py ran
fmt, lint, and pyright in ALL 22 packages (66 tasks). Only type-checking
tasks (pyright, mypy) need to propagate to all packages since type
changes in core affect downstream packages. File-local tasks (fmt, lint)
only need to run in packages with actual file changes.
This reduces a core-only change from 66 tasks to 24 tasks (2 local +
22 pyright).
Also adds no-commit-to-branch builtin hook to protect the main branch
from direct commits.
* Python: add agent skills extracted from AGENTS.md and coding standards
Add 5 skills to python/.github/skills/ following the Agent Skills format:
- python-development: coding standards, type annotations, docstrings, logging
- python-testing: test structure, fixtures, running tests, async mode
- python-code-quality: linting, formatting, type checking, prek hooks, CI
- python-package-management: monorepo structure, lazy loading, versioning
- python-samples: sample structure, PEP 723, documentation guidelines
* Python: deduplicate AGENTS.md and instructions with agent skills
* updated skills
* fixes from review
* Python: increase timeout for web search integration test
* Add ADR for Python ContextMiddleware unification
* Add session serialization/deserialization design to ADR
* Add Related Issues section mapping to ADR
* Update session management: create_session, get_session_by_id, agent.serialize_session
* ADR: Add hooks alternative, context compaction discussion, and PR feedback
- Add Option 3: ContextHooks with before_run/after_run pattern
- Add detailed pros/cons for both wrapper and hooks approaches
- Add Open Discussion section on context compaction strategies
- Clarify response_messages is read-only (use AgentMiddleware for modifications)
- Add SimpleRAG examples showing input-only filtering
- Clarify default storage only added when NO middleware configured
- Add RAGWithBuffer examples for self-managed history
- Rename hook methods to before_run/after_run
* ADR: Restructure and add .NET comparison
- Add class hierarchy clarification for both options
- Merge detailed design sections (side-by-side comparison)
- Move detailed design before decision outcome
- Move compaction discussion after decision
- Add .NET implementation comparison (feature equivalence)
- Update .NET method names to match actual implementation
- Rename hook methods to before_run/after_run
- Fix storage context table for injected context
* tweaks
* fix smart load
* ADR: Add naming discussion note for ContextHooks
- Note that class and method names are open for discussion
- Add alternative method naming options table
- Include invoking/invoked as option matching current Python and .NET
* Update context middleware design: remove smart mode, add attribution filtering
- Remove smart mode for load_messages (now explicit bool, default True)
- Add attribution marker in additional_properties for message filtering
- Update validation to warn on multiple or zero storage loaders
- Add note about ChatReducer naming from .NET
- Note that attribution should not be propagated to storage
* Add Decision 2: Instance Ownership (instances in session vs agent)
- Option A: Instances in Session (current proposal)
- Option B: Instances in Agent, State in Session
- B1: Simple dict state with optional return
- B2: SessionState object with mutable wrapper
- Updated examples to use Hooks pattern (before_run/after_run)
- Added open discussion on hook factories in Option B model
* Update ADR: Choose ContextPlugin with before_run/after_run and Option B1
Decision outcomes:
- Option 3 (Hooks pattern) with ContextPlugin class name
- Methods: before_run/after_run
- Option B1: Instances in Agent, State in Session (simple dict)
- Whole state dict passed to plugins (mutable, no return needed)
- Added trust note: plugins reason over messages, so they're trusted by default
Status changed from proposed to accepted.
* Add agent and session params to before_run/after_run methods
Signature now: before_run(agent, session, context, state)
* Remove ContextPluginRunner, store plugins directly on agent
Simpler design: agent stores Sequence[ContextPlugin] and calls
before_run/after_run directly in the run method.
* Update workplan to 2 PRs for simpler review
* updated doc
* Refine ADR: serialization, ownership, decorators, session methods, exports
- Add to_dict()/from_dict() on AgentSession with 'type' discriminator
- Present serialization as Option A (direct) vs Option B (through agent)
- Rewrite ownership section as 2x2 matrix (orthogonal decision)
- Move Instance Ownership Options before Decision Outcome
- Fix get_session to use service_session_id, split from create_session
- Add decorator-based provider convenience API (@before_run/@after_run)
- Add _ prefix naming strategy for all PR1 types (core + external)
- Constructor compatibility table for existing providers
- Add load_messages=False skip logic to all agent run loops
- Clarify abstract vs non-abstract in execution pattern samples
- Update auto-provision: trigger on conversation_id or store=True
- Document root package exports (ContextProvider, HistoryProvider, etc.)
- Rename section heading to 'Key Design Considerations'
* Rename ADR to 0016-python-context-middleware.md
* Fix broken link: #3-unified-storage-middleware → #3-unified-storage
* feat(workflows): Make telemetry opt-in via WithOpenTelemetry()
- Add WorkflowTelemetryOptions class with EnableSensitiveData property
- Add WorkflowTelemetryContext to manage ActivitySource lifecycle
- Add WithOpenTelemetry() extension method on WorkflowBuilder
- Update all workflow components to use telemetry context:
- WorkflowBuilder, Workflow, Executor
- InProcessRunnerContext, InProcessRunner
- LockstepRunEventStream, StreamingRunEventStream
- All edge runners (Direct, FanIn, FanOut, Response)
- Telemetry is now disabled by default
- Users must call WithOpenTelemetry() to enable spans/activities
BREAKING CHANGE: Workflow telemetry is now opt-in. Users who relied on
automatic telemetry must add .WithOpenTelemetry() to their workflow builder.
* refactor: Pass telemetry context as parameter instead of via interface
- Remove IWorkflowContextWithTelemetry interface
- Add internal ExecuteAsync overload that accepts WorkflowTelemetryContext
- Public ExecuteAsync delegates with WorkflowTelemetryContext.Disabled
- InProcessRunner passes TelemetryContext when calling ExecuteAsync
- BoundContext now implements IWorkflowContext (not the removed interface)
* Add optional ActivitySource parameter to WithOpenTelemetry
Allow users to provide their own ActivitySource when enabling telemetry,
giving them better control over the ActivitySource lifecycle. When not
provided, the framework creates one internally (existing behavior).
Changes:
- Add optional activitySource parameter to WithOpenTelemetry() extension
- Update WorkflowTelemetryContext to accept external ActivitySource
- Add unit test for user-provided ActivitySource scenario
* Add component-level telemetry control with disable flags
Allow users to selectively disable specific activity types via
WorkflowTelemetryOptions. All activities are enabled by default.
New disable flags:
- DisableWorkflowBuild: Disables workflow.build activities
- DisableWorkflowRun: Disables workflow_invoke activities
- DisableExecutorProcess: Disables executor.process activities
- DisableEdgeGroupProcess: Disables edge_group.process activities
- DisableMessageSend: Disables message.send activities
Added helper methods to WorkflowTelemetryContext for each activity type
and updated all activity creation sites to use them.
* Implement EnableSensitiveData to log executor input/output
When EnableSensitiveData is true in WorkflowTelemetryOptions, executor
input and output are logged as JSON-serialized attributes in the
executor.process activity.
New activity tags:
- executor.input: JSON serialized input message
- executor.output: JSON serialized output result (non-void only)
Added suppression attributes for AOT/trimming warnings since this is
an opt-in feature for debugging/diagnostics.
* Refactor activity start methods to centralize tagging logic
Move tagging logic into WorkflowTelemetryContext methods:
- StartExecutorProcessActivity now accepts executorId, executorType,
messageType, and message; sets all tags including executor.input
when EnableSensitiveData is true
- Added SetExecutorOutput method to set executor.output after execution
- StartMessageSendActivity now accepts sourceId, targetId, and message;
sets all tags including message.content when EnableSensitiveData is true
Simplified Executor.cs and InProcessRunnerContext.cs by removing
inline tagging code. Added message.content tag constant.
* Revert Python changes
* Update samples and code cleanup
* Fix file formatting
* Add comment
* Add telemetry configuration to declarative workflow
* Remove delays in tests
* Address comments
* python: replace pre-commit with prek, add PEP 723 script deps, clean up dev dependencies
- Replace pre-commit with prek (Rust-native, faster pre-commit alternative)
- Move supported hooks to repo: builtin for zero-clone speed
- Add new builtin hooks: trailing-whitespace, check-merge-conflict, detect-private-key, check-added-large-files
- Update all hook versions to latest (pre-commit-hooks v6, pyupgrade v3.21.2, bandit 1.9.3, uv-pre-commit 0.10.0)
- Add PEP 723 inline script metadata to 34 samples with external deps
- Remove autogen-agentchat/autogen-ext from dev deps (now declared per-sample)
- Remove unused dev deps: pytest-env, tomli-w
- Add agent-framework-core>=1.0.0b260130 lower bound to all 21 packages
- Update CI workflow to use j178/prek-action
- Update docs: DEV_SETUP.md, AGENTS.md, CODING_STANDARD.md, SAMPLE_GUIDELINES.md
* updated lock
* python: fix prek config paths for local execution and CI workflow
Remove global 'files: ^python/' filter and strip python/ prefix from all path patterns in .pre-commit-config.yaml so prek finds files when run from the python/ directory. Update CI workflow to use --cd python instead of --config path. Include trailing whitespace fixes and dev dependency cleanup.
* python: move helper scripts to scripts/ folder and exclude from checks
* python: exclude AGENTS.md from prek markdown code lint
* python: exclude AGENTS.md and azure_ai_search sample from markdown lint
* fix m365 sample
* python: ignore CPY rule for samples with PEP 723 headers
* fix in dev_setup
* python: replace aiofiles with regular open in samples
* python: suppress reportUnusedImport in markdown code block checker
* python: use samples pyright config for markdown code block checker
Write a temp pyrightconfig.json matching pyrightconfig.samples.json rules (typeCheckingMode=off, only reportMissingImports and reportAttributeAccessIssue). Filter output to only fail on these rules since syntax-level errors (top-level await, undefined vars) are expected in README documentation snippets.
* python: use markdown-code-lint with fixed globs instead of prek file list
The prek-markdown-code-lint task received all changed files including non-README markdown and files with pre-existing broken imports. Replace with the standard markdown-code-lint task which uses the correct glob patterns (README.md, packages/**/README.md, samples/**/*.md).
* python: exclude READMEs with pre-existing broken imports from markdown lint
* python: fix broken README code snippets instead of excluding them
- ag-ui: replace TextContent (removed) with content.type == 'text'
- durabletask: fix import path to durabletask.worker.TaskHubGrpcWorker
- orchestrations: use constructor params instead of .participants() method
- observability: mark deprecated code blocks as plain text, filter
reportMissingImports to agent_framework modules only
- remove README excludes from markdown-code-lint task
* add revision to gaia download
* feat(python): parallelize checks across packages
Run (package × task) cross-product in parallel using ThreadPoolExecutor
and subprocesses. Key changes:
- Add scripts/task_runner.py with shared parallel execution engine
- Update run_tasks_in_packages_if_exists.py to accept multiple tasks
- Update run_tasks_in_changed_packages.py with --files flag and parallel support
- Add check-packages poe task (fmt+lint+pyright+mypy in parallel)
- Add prek-markdown-code-lint and prek-samples-check with change detection
- Split CI code quality workflow into parallel prek and mypy jobs
- Update DEV_SETUP.md to document new parallel behavior
Core package changes still trigger checks on all packages.
* feat(ci): split code quality into 4 parallel jobs
Split the single prek job into parallel jobs:
- pre-commit-hooks: lightweight hooks (SKIP=poe-check)
- package-checks: fmt/lint/pyright/mypy via check-packages
- samples-markdown: samples-lint, samples-syntax, markdown-code-lint
- mypy: change-detected mypy checks
All 4 jobs run concurrently (×2 Python versions = 8 runners).
* feat(ci): use only Python 3.10 for code quality checks
* refactor(python): add future annotations and remove quoted types
Add `from __future__ import annotations` to 93 package files that
used quoted string annotations, then run pyupgrade --py310-plus to
remove the now-unnecessary quotes.
Fixes https://github.com/microsoft/agent-framework/issues/3578
* Add ability to mark the source of Agent request messages and use that for filtering
* Add support for source, in addition to source type, and add unit tests for automatic stamping
* Address PR comments.
* Add merge fixes
* Address PR comments
* Add samples syntax checking with pyright
- Add pyrightconfig.samples.json with relaxed type checking but import validation
- Add samples-syntax poe task to check samples for syntax and import errors
- Add samples-syntax to check and pre-commit-check tasks
- Fix 78 sample errors:
- Update workflow builder imports to use agent_framework_orchestrations
- Change content type isinstance checks to content.type comparisons
- Use Content factory methods instead of removed content type classes
- Fix TypedDict access patterns for Annotation
- Fix various API mismatches (normalize_messages, ChatMessage.text, role)
* fixed a bunch of samples and tweaks to pre-commit
* updated lock
* updated lock
* fixes
* added lint to samples
* WIP
* big update to new ResponseStream model
* fixed tests and typing
* fixed tests and typing
* fixed tools typevar import
* fix
* mypy fix
* mypy fixes and some cleanup
* fix missing quoted names
* and client
* fix imports agui
* fix anthropic override
* fix agui
* fix ag ui
* fix import
* fix anthropic types
* fix mypy
* refactoring
* updated typing
* fix 3.11
* fixes
* redid layering of chat clients and agents
* redid layering of chat clients and agents
* Fix lint, type, and test issues after rebase
- Add @overload decorators to AgentProtocol.run() for type compatibility
- Add missing docstring params (middleware, function_invocation_configuration)
- Fix TODO format (TD002) by adding author tags
- Fix broken observability tests from upstream:
- Replace non-existent use_instrumentation with direct instantiation
- Replace non-existent use_agent_instrumentation with AgentTelemetryLayer mixin
- Fix get_streaming_response to use get_response(stream=True)
- Add AgentInitializationError import
- Update streaming exception tests to match actual behavior
* Fix AgentExecutionException import error in test_agents.py
- Replace non-existent AgentExecutionException with AgentRunException
* Fix test import and asyncio deprecation issues
- Add 'tests' to pythonpath in ag-ui pyproject.toml for utils_test_ag_ui import
- Replace deprecated asyncio.get_event_loop().run_until_complete with asyncio.run
* Fix azure-ai test failures
- Update _prepare_options patching to use correct class path
- Fix test_to_azure_ai_agent_tools_web_search_missing_connection to clear env vars
* Convert ag-ui utils_test_ag_ui.py to conftest.py
- Move test utilities to conftest.py for proper pytest discovery
- Update all test imports to use conftest instead of utils_test_ag_ui
- Remove old utils_test_ag_ui.py file
- Revert pythonpath change in pyproject.toml
* fix: use relative imports for ag-ui test utilities
* fix agui
* Rename Bare*Client to Raw*Client and BaseChatClient
- Renamed BareChatClient to BaseChatClient (abstract base class)
- Renamed BareOpenAIChatClient to RawOpenAIChatClient
- Renamed BareOpenAIResponsesClient to RawOpenAIResponsesClient
- Renamed BareAzureAIClient to RawAzureAIClient
- Added warning docstrings to Raw* classes about layer ordering
- Updated README in samples/getting_started/agents/custom with layer docs
- Added test for span ordering with function calling
* Fix layer ordering: FunctionInvocationLayer before ChatTelemetryLayer
This ensures each inner LLM call gets its own telemetry span, resulting in
the correct span sequence: chat -> execute_tool -> chat
Updated all production clients and test mocks to use correct ordering:
- ChatMiddlewareLayer (first)
- FunctionInvocationLayer (second)
- ChatTelemetryLayer (third)
- BaseChatClient/Raw...Client (fourth)
* Remove run_stream usage
* Fix conversation_id propagation
* Python: Add BaseAgent implementation for Claude Agent SDK (#3509)
* Added ClaudeAgent implementation
* Updated streaming logic
* Small updates
* Small update
* Fixes
* Small fix
* Naming improvements
* Updated imports
* Addressed comments
* Updated package versions
* Update Claude agent connector layering
* fix test and plugin
* Store function middleware in invocation layer
* Fix telemetry streaming and ag-ui tests
* Remove legacy ag-ui tests folder
* updates
* Remove terminate flag from FunctionInvocationContext, use MiddlewareTermination instead
- Remove terminate attribute from FunctionInvocationContext
- Add result attribute to MiddlewareTermination to carry function results
- FunctionMiddlewarePipeline.execute() now lets MiddlewareTermination propagate
- _auto_invoke_function captures context.result in exception before re-raising
- _try_execute_function_calls catches MiddlewareTermination and sets should_terminate
- Fix handoff middleware to append to chat_client.function_middleware directly
- Update tests to use raise MiddlewareTermination instead of context.terminate
- Add middleware flow documentation in samples/concepts/tools/README.md
- Fix ag-ui to use FunctionMiddlewarePipeline instead of removed create_function_middleware_pipeline
* fix: remove references to removed terminate flag in purview tests, add type ignore
* fix: move _test_utils.py from package to test folder
* fix: call get_final_response() to trigger context provider notification in streaming test
* fix: correct broken links in tools README
* docs: clarify default middleware behavior in summary table
* fix: ensure inner stream result hooks are called when using map()/from_awaitable()
* Fix mypy type errors
* Address PR review comments on observability.py
- Remove TODO comment about unconsumed streams, add explanatory note instead
- Remove redundant _close_span cleanup hook (already called in _finalize_stream)
- Clarify behavior: cleanup hooks run after stream iteration, if stream is not
consumed the span remains open until garbage collected
* Remove gen_ai.client.operation.duration from span attributes
Duration is a metrics-only attribute per OpenTelemetry semantic conventions.
It should be recorded to the histogram but not set as a span attribute.
* Remove duration from _get_response_attributes, pass directly to _capture_response
Duration is a metrics-only attribute. It's now passed directly to _capture_response
instead of being included in the attributes dict that gets set on the span.
* Remove redundant _close_span cleanup hook in AgentTelemetryLayer
_finalize_stream already calls _close_span() in its finally block,
so adding it as a separate cleanup hook is redundant.
* Use weakref.finalize to close span when stream is garbage collected
If a user creates a streaming response but never consumes it, the cleanup
hooks won't run. Now we register a weak reference finalizer that will close
the span when the stream object is garbage collected, ensuring spans don't
leak in this scenario.
* Fix _get_finalizers_from_stream to use _result_hooks attribute
Renamed function to _get_result_hooks_from_stream and fixed it to
look for the _result_hooks attribute which is the correct name in
ResponseStream class.
* Add missing asyncio import in test_request_info_mixin.py
* Fix leftover merge conflict marker in image_generation sample
* Update integration tests
* Fix integration tests: increase max_iterations from 1 to 2
Tests with tool_choice options require at least 2 iterations:
1. First iteration to get function call and execute the tool
2. Second iteration to get the final text response
With max_iterations=1, streaming tests would return early with only
the function call/result but no final text content.
* Fix duplicate function call error in conversation-based APIs
When using conversation_id (for Responses/Assistants APIs), the server
already has the function call message from the previous response. We
should only send the new function result message, not all messages
including the function call which would cause a duplicate ID error.
Fix: When conversation_id is set, only send the last message (the tool
result) instead of all response.messages.
* Add regression test for conversation_id propagation between tool iterations
Port test from PR #3664 with updates for new streaming API pattern.
Tests that conversation_id is properly updated in options dict during
function invocation loop iterations.
* Fix tool_choice=required to return after tool execution
When tool_choice is 'required', the user's intent is to force exactly one
tool call. After the tool executes, return immediately with the function
call and result - don't continue to call the model again.
This fixes integration tests that were failing with empty text responses
because with tool_choice=required, the model would keep returning function
calls instead of text.
Also adds regression tests for:
- conversation_id propagation between tool iterations (from PR #3664)
- tool_choice=required returns after tool execution
* Document tool_choice behavior in tools README
- Add table explaining tool_choice values (auto, none, required)
- Explain why tool_choice=required returns immediately after tool execution
- Add code example showing the difference between required and auto
- Update flow diagram to show the early return path for tool_choice=required
* Fix tool_choice=None behavior - don't default to 'auto'
Remove the hardcoded default of 'auto' for tool_choice in ChatAgent init.
When tool_choice is not specified (None), it will now not be sent to the
API, allowing the API's default behavior to be used.
Users who want tool_choice='auto' can still explicitly set it either in
default_options or at runtime.
Fixes#3585
* Fix tool_choice=none should not remove tools
In OpenAI Assistants client, tools were not being sent when
tool_choice='none'. This was incorrect - tool_choice='none' means
the model won't call tools, but tools should still be available
in the request (they may be used later in the conversation).
Fixes#3585
* Add test for tool_choice=none preserving tools
Adds a regression test to ensure that when tool_choice='none' is set but
tools are provided, the tools are still sent to the API. This verifies
the fix for #3585.
* Fix tool_choice=none should not remove tools in all clients
Apply the same fix to OpenAI Responses client and Azure AI client:
- OpenAI Responses: Remove else block that popped tool_choice/parallel_tool_calls
- Azure AI: Remove tool_choice != 'none' check when adding tools
When tool_choice='none', the model won't call tools, but tools should
still be sent to the API so they're available for future turns.
Also update README to clarify tool_choice=required supports multiple tools.
Fixes#3585
* Keep tool_choice even when tools is None
Move tool_choice processing outside of the 'if tools' block in OpenAI
Responses client so tool_choice is sent to the API even when no tools
are provided.
* Update test to match new parallel_tool_calls behavior
Changed test_prepare_options_removes_parallel_tool_calls_when_no_tools to
test_prepare_options_preserves_parallel_tool_calls_when_no_tools to reflect
that parallel_tool_calls is now preserved even when no tools are present,
consistent with the tool_choice behavior.
* Fix ChatMessage API and Role enum usage after rebase
- Update ChatMessage instantiation to use keyword args (role=, text=, contents=)
- Fix Role enum comparisons to use .value for string comparison
- Add created_at to AgentResponse in error handling
- Fix AgentResponse.from_updates -> from_agent_run_response_updates
- Fix DurableAgentStateMessage.from_chat_message to convert Role enum to string
- Add Role import where needed
* Fix additional ChatMessage API and method name changes
- Fix ChatMessage usage in workflow files (use text= instead of contents= for strings)
- Fix AgentResponse.from_updates -> from_agent_run_response_updates in workflow files
- Fix test files for ChatMessage and Role enum usage
* Fix remaining ChatMessage API usage in test files
* Fix more ChatMessage and Role API changes in source and test files
- Fix ChatMessage in _magentic.py replan method
- Fix Role enum comparison in test assertions
- Fix remaining test files with old ChatMessage syntax
* Fix ChatMessage and Role API changes across packages
- Add Role import where missing
- Fix ChatMessage signature: positional args to keyword args (role=, text=, contents=)
- Fix Role enum comparisons: .role.value instead of .role string
- Fix FinishReason enum usage in ag-ui event converters
- Rename AgentResponse.from_updates to from_agent_run_response_updates in ag-ui
Fixes API compatibility after Types API Review improvements merge
* Fix ChatMessage and Role API changes in github_copilot tests
* Fix ChatMessage and Role API changes in redis and github_copilot packages
- Fix redis provider: Role enum comparison using .value
- Fix redis tests: ChatMessage signature and Role comparisons
- Fix github_copilot tests: ChatMessage signature and Role comparisons
- Update docstring examples in redis chat message store
* Fix ChatMessage and Role API changes in devui package
- Fix executor: ChatMessage signature change
- Fix conversations: Role enum to string conversion in two places
- Fix tests: ChatMessage signatures and Role comparisons
* Fix ChatMessage and Role API changes in a2a and lab packages
- Fix a2a tests: Role comparisons and ChatMessage signatures
- Fix lab tau2 source: Role enum comparison in flip_messages, log_messages, sliding_window
- Fix lab tau2 tests: ChatMessage signatures and Role comparisons
* Remove duplicate test files from ag-ui/tests (tests are in ag_ui_tests)
* Fix ChatMessage and Role API changes across packages
After rebasing on upstream/main which merged PR #3647 (Types API Review
improvements), fix all packages to use the new API:
- ChatMessage: Use keyword args (role=, text=, contents=) instead of
positional args
- Role: Compare using .value attribute since it's now an enum
Packages fixed:
- ag-ui: Fixed Role value extraction bugs in _message_adapters.py
- anthropic: Fixed ChatMessage and Role comparisons in tests
- azure-ai: Fixed Role comparison in _client.py
- azure-ai-search: Fixed ChatMessage and Role in source/tests
- bedrock: Fixed ChatMessage signatures in tests
- chatkit: Fixed ChatMessage and Role in source/tests
- copilotstudio: Fixed ChatMessage and Role in tests
- declarative: Fixed ChatMessage in _executors_agents.py
- mem0: Fixed ChatMessage and Role in source/tests
- purview: Fixed ChatMessage in source/tests
* Fix mypy errors for ChatMessage and Role API changes
- durabletask: Use str() fallback in role value extraction
- core: Fix ChatMessage in _orchestrator_helpers.py to use keyword args
- core: Add type ignore for _conversation_state.py contents deserialization
- ag-ui: Fix type ignore comments (call-overload instead of arg-type)
- azure-ai-search: Fix get_role_value type hint to accept Any
- lab: Move get_role_value to module level with Any type hint
* Improve CI test timeout configuration
- Increase job timeout from 10 to 15 minutes
- Reduce per-test timeout to 60s (was 900s/300s)
- Add --timeout_method thread for better timeout handling
- Add --timeout-verbose to see which tests are slow
- Reduce retries from 3 to 2 and delay from 10s to 5s
This ensures individual test timeouts are shorter than the job
timeout, providing better visibility when tests hang.
With 60s timeout and 2 retries, worst case per test is ~180s.
* Fix ChatMessage API usage in docstrings and source
- Fix ChatMessage positional args in docstrings: _serialization.py, _threads.py, _middleware.py
- Fix ChatMessage in tau2 runner.py
- Fix role comparison in _orchestrator_helpers.py to use .value
- Fix role comparison in _group_chat.py docstring example
- Fix role assertions in test_durable_entities.py to use .value
* Revert tool_choice/parallel_tool_calls changes - must be removed when no tools
OpenAI API requires tool_choice and parallel_tool_calls to only be
present when tools are specified. Restored the logic that removes
these options when there are no tools.
- Restored check in _chat_client.py to remove tool_choice and
parallel_tool_calls when no tools present
- Restored same logic in _responses_client.py
- Reverted test to expect the correct behavior
* fixed issue in tests
* fix: resolve merge conflict markers in ag-ui tests
* fix: restructure ag-ui tests and fix Role/FinishReason to use string types
* fix: streaming function invocation and middleware termination
- Refactor streaming function invocation to use get_final_response() on inner streams
- Fix MiddlewareTermination to accept result parameter for passing results
- Fix _AutoHandoffMiddleware to use MiddlewareTermination instead of context.terminate
- Fix AgentMiddlewareLayer.run() to properly forward function/chat middleware
- Remove duplicate middleware registration in AgentMiddlewareLayer.__init__
- Fix exception handling in _auto_invoke_function to properly capture termination
- Fix mypy errors in core package
- Update tests to use stream=True parameter for unified run API
* fix all tests command
* Refactor integration tests to use pytest fixtures
- Merge testutils.py into conftest.py for azurefunctions integration tests
- Merge dt_testutils.py into conftest.py for durabletask integration tests
- Convert all integration tests to use fixtures instead of direct imports
(fixes ModuleNotFoundError with --import-mode=importlib)
- Add sample_helper fixture for azurefunctions tests
- Add agent_client_factory and orchestration_helper fixtures for durabletask
- Integration tests now skip with descriptive messages when services unavailable
- Restructure devui tests into tests/devui/ with proper conftest.py
- Add test organization guidelines to CODING_STANDARD.md
- Remove __init__.py from test directories per pytest best practices
* Fix pytest_collection_modifyitems to only skip integration tests
The hook was skipping all tests in the test session, not just
integration tests. Now it only skips items in the integration_tests
directory.
* Fix mem0 tests failing on Python 3.13
Use patch.object on the imported module instead of @patch with string
path to ensure the mock takes effect regardless of import timing.
* fix mem0
* another attempt for mem0
* fix for mem0
* fix mem0
* Increase worker initialization wait time in durabletask tests
Increase from 2 to 8 seconds to allow time for:
- Python startup and module imports
- Azure OpenAI client creation
- Agent registration with DTS worker
- Worker connection to DTS
This helps prevent test failures in CI where the first tests may run
before the worker is fully ready to process requests.
* Fix streaming test to use ResponseStream with finalizer
The _consume_stream method now expects a ResponseStream that can provide
a final AgentResponse via get_final_response(). Update the test to use
ResponseStream with AgentResponse.from_updates as the finalizer.
* Fix MockToolCallingAgent to use new ResponseStream API and update samples
* small updates to run_stream to run
* fix sub workflow
* temp fix for az func test
---------
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
* Add a StateBag to AgentSession and pass Agent and AgentSession to AIContextProvider and ChatHistoryProviders
* Remove statebag code from this branch, to get the refactoring out of the way first
* Apply suggestion from @rogerbarreto
Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>
* Apply suggestion from @westey-m
* Apply suggestion from @westey-m
---------
Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>
2026-02-05 15:58:41 +00:00
Roger BarretoGitHubcopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
* Initial plan
* Fix issue #3195: Handle empty Version and ID in Azure AI agent responses
This fix addresses the issue where hosted MCP agents (like AgentWithHostedMCP)
fail with "ID cannot be null or empty (Parameter 'id')" error when deployed
to Azure AI Foundry.
Changes:
- Add CreateAgentReference helper method in AzureAIProjectChatClient that defaults
empty version to "latest"
- Update CreateChatClientAgentOptions to generate a fallback ID from name and version
when AgentVersion.Id is null or empty
- Add GetAgentVersionResponseJsonWithEmptyVersion and GetAgentResponseJsonWithEmptyVersion
test data methods
- Add unit tests for empty version handling scenarios
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Address code review feedback: improve documentation and test comments
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Address PR review: Use IsNullOrWhiteSpace and add whitespace unit tests
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
* Add an AsyncLocal AgentRunContext
* Update AgentRunContext session naming
* Make AgentRunContext readonly and add ADR
* Make session nullable and add unit tests
* Add unit tests for setting the context in AIAgent
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Fix sample in ADR
* Fix broken unit test
* Add unit test for checking if middleware can access AgentRunContext
* Fix build error after merge.
* Fix AgentRunContextTests after merge from main
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* WIP: with_output_from
* Add with_output_from to other modules; next: workflow as agent
* WIP: remove agent run events
* orchestrations
* WIP: update samples; next start at guessing_game_With_human_input.py
* Update all samples
* WIP: consolidate workflow as agent streaming vs non-streaming
* Consolidate workflow as agent streaming vs non-streaming
* Move request info event processing to a share method
* Final pass on the samples
* Fix mypy
* Fix mypy
* Comments
---------
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
* Initial working version with tests.
* Updates to validate class data once instead of for each handler method. Also updated Diagnostics Ids to format of MAFGENWF{NUM}
* Formatting and trying to fix generation project pack.
* Another atempt at getting the genrators project to build.
* More attempts to fix generator build and pack.
* Fixing file encodings.
* Initail round of cleanup.
* Trying to fix packing.
* Still trying to fix pipeline pack.
* Remove obsolescence markers, sample updates, and docs from generator branch.
This commit separates the generator core functionality from the
deprecation of ReflectingExecutor. The removed changes will be
re-added in a dependent branch (wf-obsolete-reflector).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Mark ReflectingExecutor and IMessageHandler as obsolete.
This commit deprecates the reflection-based handler discovery approach
in favor of the new [MessageHandler] attribute with source generation.
Changes:
- Add [Obsolete] to ReflectingExecutor<T>, IMessageHandler<T>, IMessageHandler<T,R>
- Add #pragma to suppress warnings in internal reflection code
- Update Concurrent sample to use new [MessageHandler] pattern
- Add Directory.Build.props for samples to include generator
- Add documentation files explaining the migration
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Obsoleteing Reflector-based workflow code generation in favor of Source Generators and updating some samples to use new pattern.
This commit deprecates the reflection-based handler discovery approach
in favor of the new [MessageHandler] attribute with source generation.
Changes:
- Add [Obsolete] to ReflectingExecutor<T>, IMessageHandler<T>, IMessageHandler<T,R>
- Add #pragma to suppress warnings in internal reflection code
- Update Concurrent sample to use new [MessageHandler] pattern
- Add Directory.Build.props for samples to include generator
- Add documentation files explaining the migration
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Cleaning up temporary design and progress files.
---------
Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Initial plan
* Add unit tests to improve coverage for Microsoft.Agents.AI.Abstractions
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Fix file encoding and naming rule violation in new test files
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Remove ChatMessageStoreExtensionsTests.cs to avoid duplication with Wesley's work
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Fix AgentThread to AgentSession rename in unit tests
Update MockAgentWithName in AIAgentTests.cs and DelegatingAIAgentTests.cs
to use the renamed AgentSession class and corresponding methods:
- AgentThread -> AgentSession
- GetNewThreadAsync -> GetNewSessionAsync
- DeserializeThreadAsync -> DeserializeSessionAsync
- thread parameter -> session parameter
* Fix: Rename GetNewSessionAsync to CreateSessionAsync to match API changes
* Fix: Add SerializeSession override and remove async from DeserializeSessionAsync
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Move AgentSession.Serialize to AIAgent
* Address PR comments.
* Improve code and fix unit test
* Update test agents to return a default json element instead of throwing where the the result of the serialization is never used.
* Update further tests to actually serialize the session
* Replace Role and FinishReason classes with NewType + Literal
- Remove EnumLike metaclass from _types.py
- Replace Role class with NewType('Role', str) + RoleLiteral
- Replace FinishReason class with NewType('FinishReason', str) + FinishReasonLiteral
- Update all usages across codebase to use string literals
- Remove .value access patterns (direct string comparison now works)
- Add backward compatibility for legacy dict serialization format
- Update tests to reflect new string-based types
Addresses #3591, #3615
* Simplify ChatResponse and AgentResponse type hints (#3592)
- Remove overloads from ChatResponse.__init__
- Remove text parameter from ChatResponse.__init__
- Remove | dict[str, Any] from finish_reason and usage_details params
- Remove **kwargs from AgentResponse.__init__
- Both now accept ChatMessage | Sequence[ChatMessage] | None for messages
- Update docstrings and examples to reflect changes
- Fix tests that were using removed kwargs
- Fix Role type hint usage in ag-ui utils
* Remove text parameter from ChatResponseUpdate and AgentResponseUpdate (#3597)
- Remove text parameter from ChatResponseUpdate.__init__
- Remove text parameter from AgentResponseUpdate.__init__
- Remove **kwargs from both update classes
- Simplify contents parameter type to Sequence[Content] | None
- Update all usages to use contents=[Content.from_text(...)] pattern
- Fix imports in test files
- Update docstrings and examples
* Rename from_chat_response_updates to from_updates (#3593)
- ChatResponse.from_chat_response_updates → ChatResponse.from_updates
- ChatResponse.from_chat_response_generator → ChatResponse.from_update_generator
- AgentResponse.from_agent_run_response_updates → AgentResponse.from_updates
* Remove try_parse_value method from ChatResponse and AgentResponse (#3595)
- Remove try_parse_value method from ChatResponse
- Remove try_parse_value method from AgentResponse
- Remove try_parse_value calls from from_updates and from_update_generator methods
- Update samples to use try/except with response.value instead
- Update tests to use response.value pattern
- Users should now use response.value with try/except for safe parsing
* Add agent_id to AgentResponse and clarify author_name documentation (#3596)
- Add agent_id parameter to AgentResponse class
- Document that author_name is on ChatMessage objects, not responses
- Update ChatResponse docstring with author_name note
- Update AgentResponse docstring with author_name note
* Simplify ChatMessage.__init__ signature (#3618)
- Make contents a positional argument accepting Sequence[Content | str]
- Auto-convert strings in contents to TextContent
- Remove overloads, keep text kwarg for backward compatibility with serialization
- Update _parse_content_list to handle string items
- Update all usages across codebase to use new format: ChatMessage("role", ["text"])
* Allow Content as input on run and get_response
- Update prepare_messages and normalize_messages to accept Content
- Update type signatures in _agents.py and _clients.py
- Add tests for Content input handling
* Fix ChatMessage usage across packages and samples
Update all remaining ChatMessage(role=..., text=...) to use new
ChatMessage('role', ['text']) signature.
* Fix Role string usage and response format parsing
- Fix redis provider: remove .value access on string literals
- Fix durabletask ensure_response_format: set _response_format before accessing .value
* Fix ollama .value and ai_model_id issues, handle None in content list
- Fix ollama _chat_client: remove .value on string literals
- Fix ollama _chat_client: rename ai_model_id to model_id
- Fix _parse_content_list: skip None values gracefully
* Fix A2AAgent type signature to include Content
* Fix Role/FinishReason NewType dict annotations and improve test coverage to 95%
* Fix mypy errors for Role/FinishReason NewType usage
* Fix Role.TOOL and Role.ASSISTANT usage in _orchestrator_helpers.py
* Fix Role NewType usage in durabletask _models.py
2026-02-04 10:13:23 +00:00
Evan MattsonGitHubCopilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
* fix(claude): preserve $defs in JSON schema for nested Pydantic models
- Preserve $defs section from Pydantic JSON schema when converting FunctionTool to SDK MCP tool
- This fixes tools with nested Pydantic models that use $ref references
- Add test for nested type schema preservation
Fixes#3654
* Adjust shared state import
* Fix MCP tool kwargs serialization bug
---------
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
* Support specifying types via handler and executor decorators
* Add handling for string types
* Fix typing
* Address PR feedback
* All or nothing for handler typing approach
* Fix mypy issues
* type support for request info
* Fix naming issue
* Fix mypy
In _prepare_options(), the 'instructions' key was excluded from run_options
but never re-added. This caused instructions passed via as_agent(instructions=...)
to be silently dropped, making agents in sequential workflows ignore their
configured instructions.
Fixes#3507
* Builds locally and tests pass
* Fix typo
* Updated
* Updated
* Fixed tests failing on net472 but not on dotnet10
---------
Co-authored-by: Chris Rickman <crickman@microsoft.com>
* Python: Add coverage threshold gate for PR checks (#3392)
- Add python-check-coverage.py script to enforce coverage threshold on specific modules
- Modify python-test-coverage.yml to run coverage check after tests
- Initial enforced module: agent_framework_azure_ai at 85% threshold
- Other modules are reported for visibility but don't block merges
* Fail if module not found
* Force unit test job to run
* Comment 1
* Fix coverage check to use full package paths for submodule support
* Update report format
* Add core utilities unit tests to improve coverage (#3356)
* Address PR comments: remove redundant imports and fix misleading test
* Refactor tests to use module-level mock class instead of inline classes
* Remove unnecessary tests for trivial base class implementations
* Restore base class tests with module-level helper class
* Builds locally and tests pass
* Fix typo
* Reverted nuget config change to remove internal feed and map to new public object model package with renames.
* Renaming Bot object model in additional sample.
---------
Co-authored-by: Peter Ibekwe <peibekwe@microsoft.com>
* changed AIFunction to FunctionTool and @ai_function to @tool
* test and mypy fixes
* mypy fix
* switch function tool to always_require
* fix noop
* fix github copilot imports
* test fixes
* fix ollama test
* fixes for tests
* fix tests
* reverted change to always_require and extended timeout
* fix test
Adds tests documenting current shared state behavior in subworkflows:
- State works correctly within a subworkflow
- State is isolated across parent/subworkflow boundaries
Related to #2419
* Python: Add initial scaffold for `durabletask` package (#2761)
* Add initial scaffold
* Update design
* Fix mypy and update design
* add additional style considered
* Address comments
* Fix test
* Update readmes
* Python: Rebase durable task feature branch with main (#2806)
* Python: Add Entity State Providers for DurableTask Package (#2981)
* Add Entity State Providers
* address comments
* Fix tests
* Fix tests
* Revert unrelated changes and remove thread_id
* Revert unrelated files
* Python: [Durabletask] Update `feature-durabletask-python` branch with `main` (#3068)
* Python: Add factory pattern to concurrent orchestration builder (#2738)
* Add factory pattern to concurrent orchestration builder
* Update readme
* Address AI comments
* Fix unit tests
* Fix import
* Prevent multiple calls to set participants or factories
* Add comments
* Mitigate warnings
* Fix mypy
* Address comments
* Address Copilot comments
* Fix tests
* Python: fix: GroupChat ManagerSelectionResponse JSON Schema for OpenAI Structured Outpu… (#2750)
* fix: ManagerSelectionResponse JSON Schema for OpenAI Structured Output Strict Mode
* refactor: install pre-commit then commit again
* Capture file IDs from code interpreter in streaming responses (#2741)
* .NET: [BREAKING] Prevent nulls in AIAgent property (#2719)
* prevent nulls in AIAgent property
* address feedback
* code ql sm04598 (#2723)
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
* .NET: Add Conversation State Sample (Step05) (#2697)
* Initial plan
* Add Agent_OpenAI_Step05_Conversation sample for conversation state management
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Update Program.cs comment to accurately describe the sample
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Update the code to use the ConversationClient more in line with the samples in OpenAI
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Changing sample to use ChatClientAgent and conversationId in GetNewThread
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.7 to 4.0.4.11 (#2777)
---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
dependency-version: 4.0.4.11
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump Azure.Identity from 1.17.0 to 1.17.1 (#2780)
---
updated-dependencies:
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2778)
---
updated-dependencies:
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Python: added more complete parsing for mcp tool arguments (#2756)
* added more complete parsing for mcp tool arguments
* fixed mypy
* added nonlocal model counter, and some fixes
* fixes in naming logic
* extracted json parsing function, added parametrized test and checked coverage
* Python: Updated package versions (#2784)
* Updated package versions
* Small fix
* Bump actions/checkout from 5 to 6 (#2404)
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)
---
updated-dependencies:
- dependency-name: actions/checkout
dependency-version: '6'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* .NET: adds support for labels in edges, fixes rendering of labels in dot a… (#1507)
* adds support for labels in edges, fixes rendering of labels in dot and mermaid, adds rendering of labels in edges
* Update dotnet/src/Microsoft.Agents.AI.Workflows/Visualization/WorkflowVisualizer.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* escaping edge labels, adding tests for labels containing strange characters that would break the diagram and enabling the previous signature so the API has backwards compatibility.
* Unify label in EdgeData
* Edge API adjustments, removed useless "sanitizer"
* fixed test
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Python: Added custom args and thread object to ai_function kwargs (#2769)
* Added an example of using kwargs in ai_function
* Added thread object to ai_function kwargs
* Updated docs
* Small fix
* Added thread parameter filtering
* Fix WorkflowAgent to include thread convo history. Enable checkpointing. (#2774)
* Update OpenAIResponses.yaml to match AgentSchema (#2598)
1. Update `connection` child types -- `kind: ApiKey` to `kind: key` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/apikeyconnection/
2. Update `outputSchema`'s `PropertySchema` to be `kind` instead of `type` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/propertyschema/
* Python: Remove warnings from workflow builder on not using factories (#2808)
* Revert concurrent
* Fix comments
* Python: Filter framework kwargs from MCP tool invocations (#2870)
* Filter framework kwargs from MCP tool invocations
* Fixes
* Python: Fix WorkflowAgent to emit yield_output as agent response (#2866)
* Fix WorkflowAgent to emit yield_output as agent response
* use raw_representation
* Raw representation handling
* Python: Use agent description in HandoffBuilder auto-generated tools (#2713) (#2714)
## Summary
Enhanced `HandoffBuilder._apply_auto_tools` to use the target agent's
description when creating handoff tools, providing more informative tool
descriptions for LLMs.
## Changes
- Modified `_apply_auto_tools` to extract `description` from
`AgentExecutor._agent` when available
- Updated iteration to use `.items()` for more efficient dict traversal
- Handoff tools now use agent descriptions instead of generic placeholders
## Example
Before: "Handoff to the refund_agent agent."
After: "You handle refund requests. Ask for order details and process refunds."
## Testing
- All handoff tests pass (20/20)
- No breaking changes to existing API
Fixes#2713
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
* Python: [BREAKING] Observability updates (#2782)
* fixes Python: Add env_file_path parameter to setup_observability() similar to AzureOpenAIChatClient
Fixes#2186
* WIP on updates using configure_azure_monitor
* improved setup and clarity
* fixed root .env.example
* revert changes
* updated files
* updated sample
* updated zero code
* test fixes and fixed links
* fix devui
* removed planning docs
* added enable method and updated readme and samples
* clarified docstring
* add return annotation
* updated naming
* update capatilized version
* updated readme and some fixes
* updated decorator name inline with the rest
* feedback from comments addressed
* Python: Fix middleware terminate flag to exit function calling loop immediately (#2868)
* Fix middleware terminate flag to exit function calling loop immediately
* Eliminating duck typing
* Improve function exec result handling
* Fix race condition
* Fix mypy issues
* Python: Fix context duplication in handoff workflows when restoring from checkpoint (#2867)
* Fix context duplication in handoff workflows when restoring from checkpoint
* Address Copilot PR review
* .NET: Update to latest Azure.AI.*, OpenAI, and M.E.AI* (#2850)
* Update to latest Azure.AI.*, OpenAI, and M.E.AI*
Absorb breaking changes in Responses surface area
* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs
* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs
* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs
* Update dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/Program.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Using patch to remove the model is necessary, updated the response client to actually use the the ForAgent
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>
* Bump actions/download-artifact from 6 to 7 (#2862)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v6...v7)
---
updated-dependencies:
- dependency-name: actions/download-artifact
dependency-version: '7'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump actions/cache from 4 to 5 (#2861)
Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v4...v5)
---
updated-dependencies:
- dependency-name: actions/cache
dependency-version: '5'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump actions/upload-artifact from 5 to 6 (#2860)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v5...v6)
---
updated-dependencies:
- dependency-name: actions/upload-artifact
dependency-version: '6'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Python : Ollama Connector for Agent Framework (#1104)
* Initial Commit for Olama Connector
* Added Olama Sample
* Add Sample & Fixed Open Telemetry
* Fixed Spelling from Olama to Ollama
* remove"opentelemetry-semantic-conventions-ai ~=0.4.13" since its handled in a different pr
* Added Tool Calling
* Finalizing test cases
* Adjust samples to be more reliable
* Update python/packages/ollama/agent_framework_ollama/_chat_client.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/ollama/pyproject.toml
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/ollama/tests/test_ollama_chat_client.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/ollama/agent_framework_ollama/_chat_client.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Improved Docstrings & Sample
* Update python/packages/ollama/agent_framework_ollama/_chat_client.py
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
* Integrate PR Feedback
- Divided Streaming and Non-Streaming into independent Methods
- Catch Ollama Validation Error
- Add OTEL Provider Name
- Checked Ollama Messages
- Add Usage Statistics
* Revert setting, so it can be none
* Validate Message formatting between AF and Ollama
* Catch Ollama Error and raise a ServiceResponse Error
* Fix mypy error
* remove .vscode comma
* Add Reasoning support & adjust to new structure
* Add Ollama Multimodality and Reasoning
* Add test cases for reasoning
* Add Tests for Error Handling in Ollama Client
* Update python/samples/getting_started/multimodal_input/ollama_chat_multimodal.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Integrated Copilot Feedback
* Implement first PR Feedback
* Adjust Readme files for examples
* Adjust argument passing via additional chat options
* Implemented PR Feedback
* Removing Ollama Package from Core and moving samples
* Fix Link & Adding Samples to Main Sample Readme
* Fixing Links in Readme
* Moved Multimodal and Chat Example
* Fixed Link in ChatClient to Ollama
* Fix AgentFramework Links in Ollama Project
* Fix observability breaking change
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
* Skip failing IT (#2904)
* .NET: Cosmos DB UT Fast Skip (For Non-Configured Local envs) (#2906)
* Cosmos DB UT Fast Skip (Non-Configured Local envs) + Long running UT skip in pipeline when no CosmosDB changes happened
* Force a CosmosDB source code change to trigger the pipeline
* Address possible string boolean mismatch
* Add debug
* Enabling emulator always when running IT
* .NET: Add TTLs to durable agent sessions (#2679)
* .NET: Add TTLs to durable agent sessions
* Remove unnecessary async
* PR feedback: clarify UTC
* PR feedback: limit minimum signal delay to <= 5 minutes
* PR feedback: Fix TTL disablement
* Linter: use auto-property
* Fix build break from OpenAI SDK change
* Updated CHANGELOG.md
* PR feedback
* Reduce default TTL to 14 days to work around DTS bug
* Python: Update Mem0Provider to use v2 search API `filters` parameter (#2766)
* short fix to move id parameters to filters object
* added tests
* small fix
* mem0 dependency update
* Updated package versions (#2913)
* .NET: Switch to new "Run" method name. (#2843)
* Switch to new "RunAgent" method name.
* Try to disable false positive naming warning.
* Add comment about disabled warnings.
* Rename `RunAgent` to just `Run`.
* Update CHANGELOG.
* Python: Switch to new "run" method name. (#2890)
* Switch to `run` method.
* Add support for deprecated `run_agent`.
* Fix entity method name.
* Fix method name and improve tests.
* Update comment.
* Update Python CHANGELOG.
* [BREAKING] Python: Add factory pattern to handoff orchestration builder (#2844)
* WIP: Factory pattern to handoff
* Add factory pattern to concurrent orchestration builder; Next: tests and sample verification
* Add tests and improve comments
* Fix mypy
* Simplify handoff_simple.py
* Simplify handoff_autonoumous.py and bug fix
* Update readme
* Address Copilot comments
* Python: Flow custom kwargs to agents via Workflow SharedState (#2894)
* Flow custom kwargs to agents via SharedState
* Address Copilot feedback
* Improve sample typing
* Fix test
* Fix Pydantic error when using Literal type for tool params (#2893)
* Updated Ollama package version (#2920)
* Python: Azure AI Agent with Bing Grounding Citations Sample (#2892)
* bing grounding sample with citations
* small fix
* fix
* .NET: Make DelegatingAIAgent abstract (#2797)
* Initial plan
* Make DelegatingAIAgent abstract
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Added additional arguments for Azure AI agent (#2922)
* Python: Correction of MCP image type conversion in _mcp.py (#2901)
* Correction of MCP image type conversion in _mcp.py
* Added a new overload to the init function of the DataContent() type of the Agent Framework, edited the test case to correctly test the usage of the data and uri fields while using DataContent()
* Fixed tests related to the changes of the DataContent type, added testing for both string and byte representations
* Pass kwargs into subworkflows (#2923)
* Python: Move ollama samples to samples getting started dir (#2921)
* Move ollama samples to samples getting started dir
* Address feedback
* Python: fix: correct BadRequestError when using Pydantic model in response_fo… (#1843)
* fix: correct BadRequestError when using Pydantic model in response_format
* Fix lint
---------
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
* .NET: [Breaking] Delete display name property (#2758)
* delete the AIAgent.DisplayName property
* use agent name as a first value for activity display name
* Update dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Python: cleanup and refactoring of chat clients (#2937)
* refactoring and unifying naming schemes of internal methods of chat clients
* set tool_choice to auto
* fix for mypy
* added note on naming and fix#2951
* fix responses
* fixes in azure ai agents client
* Python: Workflow add option to visualize internal executors (#2917)
* Workflow add option to visualize internal executors
* Address Copilot comments
* Python: Fixes Run ID and Thread ID casing to align with AG-UI Typescript SDK (#2948)
* added camelCase input to run id and thread id aligning with @ag-ui/core
* fixed per copilot suggestions
* Python: Add workflow cancellation sample (#2732)
* Add workflow cancellation sample
Add sample demonstrating how to cancel a running workflow using asyncio
tasks. Shows both cancellation mid-execution and normal completion paths.
Useful for implementing timeouts, graceful shutdown, or A2A executors.
* update docstring
* .NET: Update Anthropic package to version 12.0.0 (#2914)
* Initial plan
* Update Anthropic package to version 12.0.0
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
* Python: Add Azure Managed Redis Support with Credential Provider (#2887)
* azure redis support
* small fixes
* azure managed redis sample
* fixes
* Bump CommunityToolkit.Aspire.OllamaSharp from 13.0.0-beta.440 to 13.0.0 (#2856)
---
updated-dependencies:
- dependency-name: CommunityToolkit.Aspire.OllamaSharp
dependency-version: 13.0.0
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.11 to 4.0.5 (#2853)
---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
dependency-version: 4.0.5
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
* Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2854)
---
updated-dependencies:
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Python: Fix WorkflowAgent event handling and kwargs forwarding (#2946)
* Fix kwargs propagation through workflow.as_agent()
* Fix WorkflowAgent to respect AgentExecutor output_response setting
* .NET: Use GrpcEntityRunner instead of TaskEntityDispatcher (#2759)
* Use GrpcEntityRunner instead of TaskEntityDispatcher
* Pin to Durable worker 1.11.0
* Set the invocation result
* Update all Durable packages
* Update changelog, rename dispatcher to encondedEntityRequest
* Python: Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG (#2968)
* Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG
* update lock
* Fix formatting
* Fix ChatKit typing
* Python: Introducing Foundry Local Chat Clients (#2915)
* redo foundry local chat client
* fix mypy and spelling
* better docstring, updated sample
* fixed tests and added tests
* small sample update
* Updated package versions (#2978)
* Python: Added GitHub MCP sample with PAT (#2967)
* added github mcp sample with PAT
* addressed copilot fixes
* env fix
* Python: Preserve reasoning blocks with OpenRouter (#2950)
* Preserve reasoning blocks with OpenRouter
* Put encrypted reasoning in TextReasoningContent
* Remove unneccessary change
* Fix docs
* Support streaming
* Fix handling None in TextReasoningContent.text
* Python: Added response.created and response.in_progress event process to OpenAIBaseResponseClient (#2975)
* added response.created and response.in_progress to include response.id
* better doc string
* added tests for the new streaming event types
* Python: Introducing support for Bedrock-hosted models (Anthropic, Cohere, etc.) (#2610)
* Pushing the bedrock related changes to the new branch after addressing the review comments
* 2524 Addressed the second round review comments
* 2524 Addressed few more minor comments on the PR
* resolving the merge conflict
* 2524 resolved the uv.lock conflicts
* 2524 addressed more comments
* 2524 removed the print statement to fix the checks failure
* 2524 resolved the CI failure issues
* 2524 fixing the CI breaks
* 2524 Addressed the review comment
* 2524 resolved conflict
---------
Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>
* .NET: [Durable Agents] Reliable streaming sample (#2942)
* .NET: [Durable Agents] Reliable streaming sample
* Add automated validation for new sample
* Address Copilot PR feedback
* Fix typo in README.md about agent definitions (#2634)
* Fix typo in README.md about agent definitions
* Update agent-samples/README.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Python: latency improvements (#3014)
* latency improvements
* fixed mypy, added coding standards and instructions
* slight logic improvement
* Python: Updated package versions (#3024)
* Updated package versions
* Updated changelog
* Python: add powerfx safe mode (#3028)
* add powerfx safe mode
* improved docstring and aligned env_file loading
* ensured test uses reset
* .NET: [Breaking] Introduce RunCoreAsync/RunCoreStreamingAsync delegation pattern in AIAgent (#2749)
* Initial plan
* Refactor AIAgent: Make RunAsync and RunStreamingAsync non-abstract, add RunCoreAsync and RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix infinite recursion in test implementations
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Make RunAsync and RunStreamingAsync non-virtual as requested
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix DelegatingAIAgent subclasses to use RunCoreAsync/RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix XML documentation references in AnonymousDelegatingAIAgent
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Restore <see cref> tags with proper qualified signatures in AnonymousDelegatingAIAgent
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Rollback unnecessary XML documentation changes in AnonymousDelegatingAIAgent
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Remove pragma and update crefs to RunCoreAsync/RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix EntityAgentWrapper to call base.RunCoreAsync/RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* fix compilation issues
* fix compilatio issue
* fix tests
* fix unit tests
* fix unit test
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Remove from feature branch
* Remove ollama changes
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Tao Chen <taochen@microsoft.com>
Co-authored-by: Kurt <65111699+q33566@users.noreply.github.com>
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: Korolev Dmitry <deagle.gross@gmail.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: Jose Luis Latorre Millas <joslat@gmail.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Richard Ortega <richardjortega@gmail.com>
Co-authored-by: 刘邦学AI <lbbniu@gmail.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Nico Möller <nkm-moeller@mail.de>
Co-authored-by: Chris Gillum <cgillum@microsoft.com>
Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com>
Co-authored-by: Phillip Hoff <phillip.hoff@gmail.com>
Co-authored-by: Ege Ozan Özyedek <36128615+egeozanozyedek@users.noreply.github.com>
Co-authored-by: samueljohnsiby <66901393+samueljohnsiby@users.noreply.github.com>
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
Co-authored-by: Hao Luo <338265+howlowck@users.noreply.github.com>
Co-authored-by: Victor Dibia <chuvidi2003@gmail.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: Jacob Viau <javia@microsoft.com>
Co-authored-by: SuperKenVery <39673849+SuperKenVery@users.noreply.github.com>
Co-authored-by: Sunil Dutta <dutta.2003@gmail.com>
Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>
Co-authored-by: Syrine Chelly <62653967+SyChell@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
* Python: Complete durableagent package (#3058)
* Add worker and clients
* Clean code and refactor common code
* Implement sample
* Add sample
* Update readmes
* Fix tests
* Fix tests
* Update requirements
* Fix typo
* Address comments
* use response.text
* .NET: Python: Merge main into feature-durabletask-python branch (#3160)
* 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
* Revert to match main
* revert file to main
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Tao Chen <taochen@microsoft.com>
Co-authored-by: Kurt <65111699+q33566@users.noreply.github.com>
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: Korolev Dmitry <deagle.gross@gmail.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: Jose Luis Latorre Millas <joslat@gmail.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Richard Ortega <richardjortega@gmail.com>
Co-authored-by: 刘邦学AI <lbbniu@gmail.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Nico Möller <nkm-moeller@mail.de>
Co-authored-by: Chris Gillum <cgillum@microsoft.com>
Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com>
Co-authored-by: Phillip Hoff <phillip.hoff@gmail.com>
Co-authored-by: Ege Ozan Özyedek <36128615+egeozanozyedek@users.noreply.github.com>
Co-authored-by: samueljohnsiby <66901393+samueljohnsiby@users.noreply.github.com>
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
Co-authored-by: Hao Luo <338265+howlowck@users.noreply.github.com>
Co-authored-by: Victor Dibia <chuvidi2003@gmail.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: Jacob Viau <javia@microsoft.com>
Co-authored-by: SuperKenVery <39673849+SuperKenVery@users.noreply.github.com>
Co-authored-by: Sunil Dutta <dutta.2003@gmail.com>
Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>
Co-authored-by: Syrine Chelly <62653967+SyChell@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
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>
* Python: Add Durabletask samples and minor fixes (#3157)
* Add samples and minor fixes
* Add redis sample and wait-for-completion
* Add wait-for-completion support
* ADd missing docs
* 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>
* Python: Add integration tests for durabletask package (#3317)
* Add integration tests
* Fix flaky test
* Fix env viz
* Fix tests and address feedback
* Fix imports for durabletask (#3345)
* .NET: Python: Merge `main` into `feature-durabletask` branch (#3385)
* Python: Add factory pattern to concurrent orchestration builder (#2738)
* Add factory pattern to concurrent orchestration builder
* Update readme
* Address AI comments
* Fix unit tests
* Fix import
* Prevent multiple calls to set participants or factories
* Add comments
* Mitigate warnings
* Fix mypy
* Address comments
* Address Copilot comments
* Fix tests
* Python: fix: GroupChat ManagerSelectionResponse JSON Schema for OpenAI Structured Outpu… (#2750)
* fix: ManagerSelectionResponse JSON Schema for OpenAI Structured Output Strict Mode
* refactor: install pre-commit then commit again
* Capture file IDs from code interpreter in streaming responses (#2741)
* .NET: [BREAKING] Prevent nulls in AIAgent property (#2719)
* prevent nulls in AIAgent property
* address feedback
* code ql sm04598 (#2723)
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
* .NET: Add Conversation State Sample (Step05) (#2697)
* Initial plan
* Add Agent_OpenAI_Step05_Conversation sample for conversation state management
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Update Program.cs comment to accurately describe the sample
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* Update the code to use the ConversationClient more in line with the samples in OpenAI
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Changing sample to use ChatClientAgent and conversationId in GetNewThread
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.7 to 4.0.4.11 (#2777)
---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
dependency-version: 4.0.4.11
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump Azure.Identity from 1.17.0 to 1.17.1 (#2780)
---
updated-dependencies:
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.Identity
dependency-version: 1.17.1
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2778)
---
updated-dependencies:
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Python: added more complete parsing for mcp tool arguments (#2756)
* added more complete parsing for mcp tool arguments
* fixed mypy
* added nonlocal model counter, and some fixes
* fixes in naming logic
* extracted json parsing function, added parametrized test and checked coverage
* Python: Updated package versions (#2784)
* Updated package versions
* Small fix
* Bump actions/checkout from 5 to 6 (#2404)
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)
---
updated-dependencies:
- dependency-name: actions/checkout
dependency-version: '6'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* .NET: adds support for labels in edges, fixes rendering of labels in dot a… (#1507)
* adds support for labels in edges, fixes rendering of labels in dot and mermaid, adds rendering of labels in edges
* Update dotnet/src/Microsoft.Agents.AI.Workflows/Visualization/WorkflowVisualizer.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* escaping edge labels, adding tests for labels containing strange characters that would break the diagram and enabling the previous signature so the API has backwards compatibility.
* Unify label in EdgeData
* Edge API adjustments, removed useless "sanitizer"
* fixed test
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Python: Added custom args and thread object to ai_function kwargs (#2769)
* Added an example of using kwargs in ai_function
* Added thread object to ai_function kwargs
* Updated docs
* Small fix
* Added thread parameter filtering
* Fix WorkflowAgent to include thread convo history. Enable checkpointing. (#2774)
* Update OpenAIResponses.yaml to match AgentSchema (#2598)
1. Update `connection` child types -- `kind: ApiKey` to `kind: key` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/apikeyconnection/
2. Update `outputSchema`'s `PropertySchema` to be `kind` instead of `type` otherwise schema will fail: https://microsoft.github.io/AgentSchema/reference/propertyschema/
* Python: Remove warnings from workflow builder on not using factories (#2808)
* Revert concurrent
* Fix comments
* Python: Filter framework kwargs from MCP tool invocations (#2870)
* Filter framework kwargs from MCP tool invocations
* Fixes
* Python: Fix WorkflowAgent to emit yield_output as agent response (#2866)
* Fix WorkflowAgent to emit yield_output as agent response
* use raw_representation
* Raw representation handling
* Python: Use agent description in HandoffBuilder auto-generated tools (#2713) (#2714)
## Summary
Enhanced `HandoffBuilder._apply_auto_tools` to use the target agent's
description when creating handoff tools, providing more informative tool
descriptions for LLMs.
## Changes
- Modified `_apply_auto_tools` to extract `description` from
`AgentExecutor._agent` when available
- Updated iteration to use `.items()` for more efficient dict traversal
- Handoff tools now use agent descriptions instead of generic placeholders
## Example
Before: "Handoff to the refund_agent agent."
After: "You handle refund requests. Ask for order details and process refunds."
## Testing
- All handoff tests pass (20/20)
- No breaking changes to existing API
Fixes#2713
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
* Python: [BREAKING] Observability updates (#2782)
* fixes Python: Add env_file_path parameter to setup_observability() similar to AzureOpenAIChatClient
Fixes#2186
* WIP on updates using configure_azure_monitor
* improved setup and clarity
* fixed root .env.example
* revert changes
* updated files
* updated sample
* updated zero code
* test fixes and fixed links
* fix devui
* removed planning docs
* added enable method and updated readme and samples
* clarified docstring
* add return annotation
* updated naming
* update capatilized version
* updated readme and some fixes
* updated decorator name inline with the rest
* feedback from comments addressed
* Python: Fix middleware terminate flag to exit function calling loop immediately (#2868)
* Fix middleware terminate flag to exit function calling loop immediately
* Eliminating duck typing
* Improve function exec result handling
* Fix race condition
* Fix mypy issues
* Python: Fix context duplication in handoff workflows when restoring from checkpoint (#2867)
* Fix context duplication in handoff workflows when restoring from checkpoint
* Address Copilot PR review
* .NET: Update to latest Azure.AI.*, OpenAI, and M.E.AI* (#2850)
* Update to latest Azure.AI.*, OpenAI, and M.E.AI*
Absorb breaking changes in Responses surface area
* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs
* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs
* Update dotnet/samples/AgentWebChat/AgentWebChat.AgentHost/Utilities/ChatClientExtensions.cs
* Update dotnet/samples/GettingStarted/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/Program.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Using patch to remove the model is necessary, updated the response client to actually use the the ForAgent
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com>
* Bump actions/download-artifact from 6 to 7 (#2862)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v6...v7)
---
updated-dependencies:
- dependency-name: actions/download-artifact
dependency-version: '7'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump actions/cache from 4 to 5 (#2861)
Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v4...v5)
---
updated-dependencies:
- dependency-name: actions/cache
dependency-version: '5'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump actions/upload-artifact from 5 to 6 (#2860)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v5...v6)
---
updated-dependencies:
- dependency-name: actions/upload-artifact
dependency-version: '6'
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Python : Ollama Connector for Agent Framework (#1104)
* Initial Commit for Olama Connector
* Added Olama Sample
* Add Sample & Fixed Open Telemetry
* Fixed Spelling from Olama to Ollama
* remove"opentelemetry-semantic-conventions-ai ~=0.4.13" since its handled in a different pr
* Added Tool Calling
* Finalizing test cases
* Adjust samples to be more reliable
* Update python/packages/ollama/agent_framework_ollama/_chat_client.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/ollama/pyproject.toml
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/ollama/tests/test_ollama_chat_client.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/packages/ollama/agent_framework_ollama/_chat_client.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Improved Docstrings & Sample
* Update python/packages/ollama/agent_framework_ollama/_chat_client.py
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
* Integrate PR Feedback
- Divided Streaming and Non-Streaming into independent Methods
- Catch Ollama Validation Error
- Add OTEL Provider Name
- Checked Ollama Messages
- Add Usage Statistics
* Revert setting, so it can be none
* Validate Message formatting between AF and Ollama
* Catch Ollama Error and raise a ServiceResponse Error
* Fix mypy error
* remove .vscode comma
* Add Reasoning support & adjust to new structure
* Add Ollama Multimodality and Reasoning
* Add test cases for reasoning
* Add Tests for Error Handling in Ollama Client
* Update python/samples/getting_started/multimodal_input/ollama_chat_multimodal.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Integrated Copilot Feedback
* Implement first PR Feedback
* Adjust Readme files for examples
* Adjust argument passing via additional chat options
* Implemented PR Feedback
* Removing Ollama Package from Core and moving samples
* Fix Link & Adding Samples to Main Sample Readme
* Fixing Links in Readme
* Moved Multimodal and Chat Example
* Fixed Link in ChatClient to Ollama
* Fix AgentFramework Links in Ollama Project
* Fix observability breaking change
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
* Skip failing IT (#2904)
* .NET: Cosmos DB UT Fast Skip (For Non-Configured Local envs) (#2906)
* Cosmos DB UT Fast Skip (Non-Configured Local envs) + Long running UT skip in pipeline when no CosmosDB changes happened
* Force a CosmosDB source code change to trigger the pipeline
* Address possible string boolean mismatch
* Add debug
* Enabling emulator always when running IT
* .NET: Add TTLs to durable agent sessions (#2679)
* .NET: Add TTLs to durable agent sessions
* Remove unnecessary async
* PR feedback: clarify UTC
* PR feedback: limit minimum signal delay to <= 5 minutes
* PR feedback: Fix TTL disablement
* Linter: use auto-property
* Fix build break from OpenAI SDK change
* Updated CHANGELOG.md
* PR feedback
* Reduce default TTL to 14 days to work around DTS bug
* Python: Update Mem0Provider to use v2 search API `filters` parameter (#2766)
* short fix to move id parameters to filters object
* added tests
* small fix
* mem0 dependency update
* Updated package versions (#2913)
* .NET: Switch to new "Run" method name. (#2843)
* Switch to new "RunAgent" method name.
* Try to disable false positive naming warning.
* Add comment about disabled warnings.
* Rename `RunAgent` to just `Run`.
* Update CHANGELOG.
* Python: Switch to new "run" method name. (#2890)
* Switch to `run` method.
* Add support for deprecated `run_agent`.
* Fix entity method name.
* Fix method name and improve tests.
* Update comment.
* Update Python CHANGELOG.
* [BREAKING] Python: Add factory pattern to handoff orchestration builder (#2844)
* WIP: Factory pattern to handoff
* Add factory pattern to concurrent orchestration builder; Next: tests and sample verification
* Add tests and improve comments
* Fix mypy
* Simplify handoff_simple.py
* Simplify handoff_autonoumous.py and bug fix
* Update readme
* Address Copilot comments
* Python: Flow custom kwargs to agents via Workflow SharedState (#2894)
* Flow custom kwargs to agents via SharedState
* Address Copilot feedback
* Improve sample typing
* Fix test
* Fix Pydantic error when using Literal type for tool params (#2893)
* Updated Ollama package version (#2920)
* Python: Azure AI Agent with Bing Grounding Citations Sample (#2892)
* bing grounding sample with citations
* small fix
* fix
* .NET: Make DelegatingAIAgent abstract (#2797)
* Initial plan
* Make DelegatingAIAgent abstract
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Added additional arguments for Azure AI agent (#2922)
* Python: Correction of MCP image type conversion in _mcp.py (#2901)
* Correction of MCP image type conversion in _mcp.py
* Added a new overload to the init function of the DataContent() type of the Agent Framework, edited the test case to correctly test the usage of the data and uri fields while using DataContent()
* Fixed tests related to the changes of the DataContent type, added testing for both string and byte representations
* Pass kwargs into subworkflows (#2923)
* Python: Move ollama samples to samples getting started dir (#2921)
* Move ollama samples to samples getting started dir
* Address feedback
* Python: fix: correct BadRequestError when using Pydantic model in response_fo… (#1843)
* fix: correct BadRequestError when using Pydantic model in response_format
* Fix lint
---------
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
* .NET: [Breaking] Delete display name property (#2758)
* delete the AIAgent.DisplayName property
* use agent name as a first value for activity display name
* Update dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/HandoffAgentExecutor.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Python: cleanup and refactoring of chat clients (#2937)
* refactoring and unifying naming schemes of internal methods of chat clients
* set tool_choice to auto
* fix for mypy
* added note on naming and fix#2951
* fix responses
* fixes in azure ai agents client
* Python: Workflow add option to visualize internal executors (#2917)
* Workflow add option to visualize internal executors
* Address Copilot comments
* Python: Fixes Run ID and Thread ID casing to align with AG-UI Typescript SDK (#2948)
* added camelCase input to run id and thread id aligning with @ag-ui/core
* fixed per copilot suggestions
* Python: Add workflow cancellation sample (#2732)
* Add workflow cancellation sample
Add sample demonstrating how to cancel a running workflow using asyncio
tasks. Shows both cancellation mid-execution and normal completion paths.
Useful for implementing timeouts, graceful shutdown, or A2A executors.
* update docstring
* .NET: Update Anthropic package to version 12.0.0 (#2914)
* Initial plan
* Update Anthropic package to version 12.0.0
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
* Python: Add Azure Managed Redis Support with Credential Provider (#2887)
* azure redis support
* small fixes
* azure managed redis sample
* fixes
* Bump CommunityToolkit.Aspire.OllamaSharp from 13.0.0-beta.440 to 13.0.0 (#2856)
---
updated-dependencies:
- dependency-name: CommunityToolkit.Aspire.OllamaSharp
dependency-version: 13.0.0
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.11 to 4.0.5 (#2853)
---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
dependency-version: 4.0.5
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
* Bump Azure.AI.AgentServer.AgentFramework from 1.0.0-beta.4 to 1.0.0-beta.5 (#2854)
---
updated-dependencies:
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Azure.AI.AgentServer.AgentFramework
dependency-version: 1.0.0-beta.5
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Python: Fix WorkflowAgent event handling and kwargs forwarding (#2946)
* Fix kwargs propagation through workflow.as_agent()
* Fix WorkflowAgent to respect AgentExecutor output_response setting
* .NET: Use GrpcEntityRunner instead of TaskEntityDispatcher (#2759)
* Use GrpcEntityRunner instead of TaskEntityDispatcher
* Pin to Durable worker 1.11.0
* Set the invocation result
* Update all Durable packages
* Update changelog, rename dispatcher to encondedEntityRequest
* Python: Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG (#2968)
* Bump Py version to 1.0.0b251218 for a release. Update CHANGELOG
* update lock
* Fix formatting
* Fix ChatKit typing
* Python: Introducing Foundry Local Chat Clients (#2915)
* redo foundry local chat client
* fix mypy and spelling
* better docstring, updated sample
* fixed tests and added tests
* small sample update
* Updated package versions (#2978)
* Python: Added GitHub MCP sample with PAT (#2967)
* added github mcp sample with PAT
* addressed copilot fixes
* env fix
* Python: Preserve reasoning blocks with OpenRouter (#2950)
* Preserve reasoning blocks with OpenRouter
* Put encrypted reasoning in TextReasoningContent
* Remove unneccessary change
* Fix docs
* Support streaming
* Fix handling None in TextReasoningContent.text
* Python: Added response.created and response.in_progress event process to OpenAIBaseResponseClient (#2975)
* added response.created and response.in_progress to include response.id
* better doc string
* added tests for the new streaming event types
* Python: Introducing support for Bedrock-hosted models (Anthropic, Cohere, etc.) (#2610)
* Pushing the bedrock related changes to the new branch after addressing the review comments
* 2524 Addressed the second round review comments
* 2524 Addressed few more minor comments on the PR
* resolving the merge conflict
* 2524 resolved the uv.lock conflicts
* 2524 addressed more comments
* 2524 removed the print statement to fix the checks failure
* 2524 resolved the CI failure issues
* 2524 fixing the CI breaks
* 2524 Addressed the review comment
* 2524 resolved conflict
---------
Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>
* .NET: [Durable Agents] Reliable streaming sample (#2942)
* .NET: [Durable Agents] Reliable streaming sample
* Add automated validation for new sample
* Address Copilot PR feedback
* Fix typo in README.md about agent definitions (#2634)
* Fix typo in README.md about agent definitions
* Update agent-samples/README.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Python: latency improvements (#3014)
* latency improvements
* fixed mypy, added coding standards and instructions
* slight logic improvement
* Python: Updated package versions (#3024)
* Updated package versions
* Updated changelog
* Python: add powerfx safe mode (#3028)
* add powerfx safe mode
* improved docstring and aligned env_file loading
* ensured test uses reset
* .NET: [Breaking] Introduce RunCoreAsync/RunCoreStreamingAsync delegation pattern in AIAgent (#2749)
* Initial plan
* Refactor AIAgent: Make RunAsync and RunStreamingAsync non-abstract, add RunCoreAsync and RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix infinite recursion in test implementations
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Make RunAsync and RunStreamingAsync non-virtual as requested
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix DelegatingAIAgent subclasses to use RunCoreAsync/RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix XML documentation references in AnonymousDelegatingAIAgent
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Restore <see cref> tags with proper qualified signatures in AnonymousDelegatingAIAgent
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Rollback unnecessary XML documentation changes in AnonymousDelegatingAIAgent
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Remove pragma and update crefs to RunCoreAsync/RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix EntityAgentWrapper to call base.RunCoreAsync/RunCoreStreamingAsync
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* fix compilation issues
* fix compilatio issue
* fix tests
* fix unit tests
* fix unit test
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* add issue template and additional labeling (#3006)
* fix and extra int test (#3037)
* .NET: [BREAKING] Refactor ChatMessageStore methods to be similar to AIContextProvider and add filtering support (#2604)
* Refactor ChatMessageStore methods to be similar to AIContextProvider
* Fix file encoding
* Ensure that AIContextProvider messages area also persisted.
* Update formatting and seal context classes
* Improve formatting
* Remove optional messages from constructor and add unit test
* Add ChatMessageStore filtering via a decorator
* Update sample and cosmos message store to store AIContextProvider messages in right order. Fix unit tests.
* Update Workflowmessage store to use aicontext provider messages.
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Apply suggestions from code review
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Improve xml docs messaging
* Address code review comments.
* Also notify message store on failure
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* [BREAKING] Remove unused AgentThreadMetadata (#3067)
* Remove unused AgentThreadMetadata
* Update DurableTask Changelog
* Python: Fix AzureAIClient failure when conversation history contains assistant messages (#3076)
* Fix AzureAIClient failure when conversation history contains assistant messages
* Address PR review feedback: improve docstring and test assertions
* Remove redundant cast
* Fix: Update OTLP exporter protocol conditions (#3070)
* Python: Fix ExecutorInvokedEvent and ExecutorCompletedEvent observability data (#3090)
* Fix ExecutorInvokedEvent.data mutation bug
* Fix bug related to not yielding output type
* .NET: Seal ChatClientAgentThread (#2842)
* Initial plan
* Seal ChatClientAgentThread class
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* Fix broken strands urls. (#3102)
* Fix broken strands urls.
* Fix typos
* .NET: Fix message ordering inconsistency when using AIContextProvider (#2659)
* Initial plan
* Fix message ordering inconsistency when using AIContextProvider
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
* Revert to original message ordering: Input, AIContextProvider, Response
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
* Reorder messages to ChatClient to match MessageStore order: Existing, Input, AIContextProvider
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
* Remove redundant test methods as existing tests already verify the behavior
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* fix: tool_choice parameter not being honored when passed to agent.run() (#3095)
* sharepoint sample fix (#3108)
* Bump versions to 1.0.0b260106 for a release. Update CHANGELOG.md (#3109)
* Bump Bedrock version to latest (#3110)
* Python: Fix MCP tool result serialization for list[TextContent] (#2523)
* Fix MCP tool result serialization for list[TextContent]
When MCP tools return results containing list[TextContent], they were
incorrectly serialized to object repr strings like:
'[<agent_framework._types.TextContent object at 0x...>]'
This fix properly extracts text content from list items by:
1. Checking if items have a 'text' attribute (TextContent)
2. Using model_dump() for items that support it
3. Falling back to str() for other types
4. Joining single items as plain text, multiple items as JSON array
Fixes#2509
* Address PR review feedback for MCP tool result serialization
- Extract serialize_content_result() to shared _utils.py
- Fix logic: use texts[0] instead of join for single item
- Add type annotation: texts: list[str] = []
- Return empty string for empty list instead of '[]'
- Move import json to file top level
- Add comprehensive unit tests for serialization
* Address PR review feedback: fix type checking and double serialization
- Add isinstance(item.text, str) check to ensure text attribute is a string
- Fix double-serialization issue by keeping model_dump results as dicts
until final json.dumps (removes escaped JSON strings in arrays)
- Improve docstring with detailed return value documentation
- Add test for non-string text attribute handling
- Add tests for list type tool results in _events.py path
* Simplify PR: minimal changes to fix MCP tool result serialization
Addresses reviewer feedback about excessive refactoring:
- Reset _events.py to original structure
- Only add import and use serialize_content_result in one location
- All review comments addressed in serialize_content_result():
- Added isinstance(item.text, str) check
- Use model_dump(mode="json") to avoid double-serialization
- Improved docstring with explicit return value documentation
- Empty list returns "" instead of "[]"
* Refactor: Move MCP TextContent serialization to core prepare_function_call_results
Per reviewer feedback, moved the TextContent serialization logic from
ag-ui's serialize_content_result to the core package's
prepare_function_call_results function.
Changes:
- Added handling for objects with 'text' attribute (like MCP TextContent)
in _prepare_function_call_results_as_dumpable
- Removed serialize_content_result from ag-ui/_utils.py
- Updated _events.py and _message_adapters.py to use
prepare_function_call_results from core package
- Updated tests to match the core function's behavior
* Fix failing tests for prepare_function_call_results behavior
- test_tool_result_with_none: Update expected value to 'null' (JSON serialization of None)
- test_tool_result_with_model_dump_objects: Use Pydantic BaseModel instead of plain class
* Fix B903 linter error: Convert MockTextContent to dataclass
The ruff linter was reporting B903 (class could be dataclass or namedtuple)
for the MockTextContent test helper classes. This commit converts them to
dataclasses to satisfy the linter check.
* Python: Improve DevUI, add Context Inspector view as new tab under traces (#2742)
* Improve DevUI, add Context Inspector view as new tab under traces
* fix mypy errors
* fix: Handle stale MCP connections in DevUI executor
MCP tools can become stale when HTTP streaming responses end - the underlying
stdio streams close but `is_connected` remains True. This causes subsequent
requests to fail with `ClosedResourceError`.
Add `_ensure_mcp_connections()` to detect and reconnect stale MCP tools before
agent execution. This is a workaround for an upstream Agent Framework issue
where connection state isn't properly tracked.
Fixes MCP tools failing on second HTTP request in DevUI.
fixes #1476#1515#2865
* fix#1572 report import dependency errors more clearly
* Ensure there is streaming toggle where users can select streaming vs non streaming mode in devui . Fixes .NET: [Python] DevUI tool call rendering in non-streaming mode?
* remove unused dead code
* improve ux - workflows with agents show a chat component in execution timelien, also ensure magentic final output shows correctly
* update ui build
* update devui to use instrumentation instead of tracing, other instrumentation and type/instance check fixes
* .NET: Seal factory contexts and add non JSO deserialize overloads (#3066)
* Seal factory contexts and add non JSO deserialize overloads
* Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Enable blank issues in issue template configuration
Need to re-enable creating blank issues
* updated templates (#3106)
* updated templates
* enabled blank and fixed triage
* made language optional and moved to the bottom for features
* Python: Streaming sample for azurefunctions (#3057)
* Streaming sample for azurefunctions
* Fixed links and sample name
* Addressed feedback
* Addressed feedback
* Fixed integration tests
* Updated test
* Python: fix(azure-ai): Fix response_format handling for structured outputs (#3114)
* fix(azure-ai): read response_format from chat_options instead of run_options
* refactor: use explicit None checks for response_format
* Fix mypy error
* Mypy fix
* Python: Bump python version to 1.0.0b260107 for a release (#3128)
* Bump python version to 1.0.0b260107 for a release
* Update changelog
* Make A2AAgent public, so that it's concrete implementation methods can be used. (#3119)
* .NET: Map additional props <-> A2A metadata (#3137)
* map additional props from agent run options to a2a request metadata
* small touches
* add unit tests for new extension methods
* Sort using
* add unit test
* add additiona unit tests
* special case json element to avoid unnecessary serialization
* Python: Fix Anthropic streaming response bugs (#3141)
* test commit identity
* fix(anthropic): fix raw_representation and finish_reason in streaming
* lint fix
* Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.5 to 4.0.5.1 (#2994)
---
updated-dependencies:
- dependency-name: AWSSDK.Extensions.Bedrock.MEAI
dependency-version: 4.0.5.1
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Bump Anthropic from 12.0.0 to 12.0.1 (#2993)
---
updated-dependencies:
- dependency-name: Anthropic
dependency-version: 12.0.1
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* .NET: [Breaking] Prevent loss of input messages & streamed updates when resuming streaming (#2748)
* save input messages and stream updates to the continuation token to be able to use them in the last successful stream resumption call.
* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update dotnet/tests/Microsoft.Agents.AI.UnitTests/ChatClient/ChatClientAgent_BackgroundResponsesTests.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgentContinuationToken.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix typo
* init continuation token from chat response
* remove unnecessary types for source generation
* remove check for continuation token passed at initial run
* remove check for continuation token pass at initial run
* centralize continuation token parsing
* update xml comments
* use readonly collection instead of enumerable
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* .NET: fix: Expose WorkflowErrorEvent as ErrorContent (#2762)
* fix: Expose WorkflowErrorEvent as ErrorContent
When hosted using .AsAgent(), Workflows were not exposing inner errors coming as Exceptions (through the WorkflowErrorEvent)
The fix is to convert their message to an ErrorContent on the way out, rather than rely on the default "empty update" to collect the raw event.
* feat: Add a way to show/suppress exception information
* Bump Microsoft.Agents.AI.Workflows from 1.0.0-preview.251125.1 to 1.0.0-preview.251219.1 (#2997)
---
updated-dependencies:
- dependency-name: Microsoft.Agents.AI.Workflows
dependency-version: 1.0.0-preview.251219.1
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
* .NET: Add Run overloads to expose ChatClientAgentRunOptions in IntelliSense (#3115)
* Initial plan
* Add ChatClientAgentExtensions for improved discoverability of ChatClientAgentRunOptions
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
* Address code review feedback - use collection expression syntax
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
* Apply suggestion from @westey-m
* Fix issues with Copilot implementation
* Add additional tests for structured output overloads.
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: westey-m <164392973+westey-m@users.noreply.github.com>
* Python: Add tool call/result content types and update connectors and samples (#2971)
* Add new AI content types and image tool support
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Add Python content types for tool calls/results and image generation tool support
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Address review feedback for tool content and samples
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Tighten image generation typing and sample tools list
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Align image generation output typing
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Handle MCP naming, image options mapping, and connector tool content
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Allow MCP call in function approval request
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Remove raw image_generation tool remapping
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Restore Anthropic tool_use to function calls unless code execution
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Fix lint issues for hosted file docstring and MCP parsing
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Import ChatResponse types in Anthropic client
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Fix Anthropics citation type imports and MCP typing for handoff/tools
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Skip lightning tests without agentlightning and fix function call import
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* fix lint on lab package
* rebuilt anthropic parsing
* redid anthropic parsing
* typo
* updated parsing and added missing docstrings
* fix tests
* mypy fixes
* second mypy fix
* add new class to other samples
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu>
* Bump Google.GenAI from 0.6.0 to 0.9.0 (#2995)
---
updated-dependencies:
- dependency-name: Google.GenAI
dependency-version: 0.9.0
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Bump js-yaml from 4.1.0 to 4.1.1 in /python/packages/devui/frontend (#3123)
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.0 to 4.1.1.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1)
---
updated-dependencies:
- dependency-name: js-yaml
dependency-version: 4.1.1
dependency-type: indirect
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Updated package versions (#3144)
* .NET: Bump Microsoft.Agents.AI.OpenAI and Microsoft.Extensions.AI.OpenAI (#2996)
* Bump Microsoft.Agents.AI.OpenAI and Microsoft.Extensions.AI.OpenAI
Bumps Microsoft.Agents.AI.OpenAI from 1.0.0-preview.251125.1 to 1.0.0-preview.251219.1
Bumps Microsoft.Extensions.AI.OpenAI from 10.1.0-preview.1.25608.1 to 10.1.1-preview.1.25612.2
---
updated-dependencies:
- dependency-name: Microsoft.Agents.AI.OpenAI
dependency-version: 1.0.0-preview.251219.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Microsoft.Extensions.AI.OpenAI
dependency-version: 10.1.1-preview.1.25612.2
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Microsoft.Agents.AI.OpenAI
dependency-version: 1.0.0-preview.251219.1
dependency-type: direct:production
update-type: version-update:semver-patch
- dependency-name: Microsoft.Extensions.AI.OpenAI
dependency-version: 10.1.1-preview.1.25612.2
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
* Fixed samples
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
* Python: fix(ag-ui): Execute tools with approval_mode, fix shared state, code cleanup (#3079)
* fix(ag-ui): execute tools after approval in human-in-the-loop flow
* Fix shared state bug
* Bug fix finalized
* Refactoring to clean up code
* Code cleanup
* More fixes
* More code cleanup
* Add version detection in __init__.py to ruff ignore list
* Track agent name with updates for workflow agent (#3146)
* Python: Fix AzureAIClient tool call bug for AG-UI use (#3148)
* Fiz AzureAIClient tool call bug
* Address copilot feedback
* Python: multiple bug fixes (#3150)
* fix Python: kwargs are not passed to _prepare_thread_and_messages in ChatAgent.run
Fixes#3118
* fix Python: [Bug]: model_id versus model_deployment_name is confusing in Azure AI Agents
Fixes#3147
* add types
* fixed type and docstring
* fix(anthropic): fix duplicate ToolCallStartEvent in streaming tool calls (#3051)
When processing `input_json_delta` events, the Anthropic client was
passing the tool name from the previous `tool_use` event. This caused
ag-ui's `_handle_function_call_content` to emit a `ToolCallStartEvent`
for every streaming chunk (since it triggers on `if content.name:`).
This fix changes the behavior to pass an empty string for `name` in
`input_json_delta` events, matching OpenAI's behavior where streaming
argument chunks have `name=""`. The initial `tool_use` event still
provides the tool name, so only one `ToolCallStartEvent` is emitted.
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
* .NET: [BREAKING] Change GetNewThread and DeserializeThread to async (#3152)
* Change GetNewThread and DeserializeThread plus ChatMessageStore and AIContextProvider Factories to async
* Merge fixes
* Fix Ollama model env var in documentation (#3156)
Signed-off-by: Dina Suehiro Jones <dina.s.jones@intel.com>
* Python: Add Pydantic request model and OpenAPI tags support to AG-UI FastAPI endpoint (#2522)
* feat(ag-ui): Add Pydantic request model and OpenAPI tags support
- Add AGUIRequest Pydantic model in _types.py with field descriptions
- Update add_agent_framework_fastapi_endpoint() to accept tags parameter
- Use AGUIRequest model for automatic validation and OpenAPI schema generation
- Export AGUIRequest and DEFAULT_TAGS in __init__.py
- Update test_endpoint.py to expect 422 for invalid requests
- Add tests for OpenAPI schema, default tags, custom tags, and validation
Benefits:
- Better API documentation with complete request schema in Swagger UI
- Automatic request validation with Pydantic
- Organized endpoints under 'AG-UI' tag instead of 'default'
- Improved developer experience and type safety
Fixes #<issue-number>
* test(ag-ui): Add test for internal error handling to achieve 100% coverage
- Add test_endpoint_internal_error_handling() to cover exception handling code
- Mock copy.deepcopy to simulate internal error during default_state processing
- Add type: ignore for FastAPI tags parameter (known pyright compatibility issue)
- Achieves 100% test coverage for _endpoint.py (previously missing lines 103-105)
* .NET: Improve resolving `AITool` from DI (#3175)
* remove localagenttoolregistry
* also give the factory method API
* Python: Fix MCPStreamableHTTPTool to use new streamable_http_client API (#3088)
* Fix MCPStreamableHTTPTool to use new streamable_http_client API with proper httpx client cleanup
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Update docstring to reflect new streamable_http_client API usage
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Refactor MCPStreamableHTTPTool to accept optional http_client parameter and delegate client creation to streamable_http_client
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Update mcp package minimum version to 1.24.0 for streamable_http_client API support
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Fix critical bugs: apply headers/timeout/sse_read_timeout when creating httpx client, add version constraint <2, and properly manage client lifecycle
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Simplify implementation: remove headers/timeout/sse_read_timeout params, remove kwargs, remove close() override per feedback
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Add back **kwargs parameter for backward compatibility (accepted but not used)
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* Remove unused httpx import from test file
Note: The uv.lock file needs to be updated with 'uv sync' to reflect the mcp version constraint change (>=1.24.0,<2)
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
* cicd fixes
* udpated samples with headers examples
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu>
* azureai direct a2a endpoint support (#3127)
* Python: [BREAKING]: removed display_name, renamed context_providers, middleware and AggregateContextProvider (#3139)
* removed display_name, renamed context_providers, middleware and AggregateContextProvider
* fixes
* fixed test
* testfix
* removed mistakenly put back test
* updated new test
* rename middlewares to middleware
* middleware fixes
* Python: MCP Improvements: improved connection loss behavior, pagination for loading and a param to control representation (#3154)
* pagination support (#2848) added a parse_tool_result param and connection loss (#2884)
* fix#3153
* improved connection handling
* improved logic
* Python: Add declarative workflow runtime (#2815)
* Further support for declarative python workflows
* Add tests. Clean up for typing and formatting
* Improvements and cleanup
* Typing cleanup. Improve docstrings
* Proper code in docstrings
* Fix malformed code-block directive in docstring
* Remove dead links
* PR feedback
* Address PR feedback
* Address PR feedback
* Remove sl
* Update devui frontend
* More cleanup
* Fix uv lock
* Skip Py 3.14 tests as powerfx doesn't support it
* Fix mypy error
* Fix for tool calls
* Removed stale docstring
* Fix lint
* Standardize on .NET namespaces. Revert DevUI changes (bring in later)
* Implement remaining items for Python declarative support to match dotnet
* point URL to agent, not to agentcard (#3176)
* Python: [BREAKING]: Introducing Options as TypedDict and Generic (#3140)
* WIP typeddict for options
* updated all clients and ChatAgents
* updated everything
* added ADR
* fix mypy
* proper typevar imports
* fixed import
* fixed other imports
* slight update in the sample
* updated from feedback
* fixes
* fixed missing covariants and test fixes
* fixed typing
* updated anthropic thinking config
* ruff fixes
* fixed int tests
* fix tests and mypy
* updated integration tests
* updated docstring and test fix
* improved options handling in obser
* mypy fix
* updated a host of integration tests
* fix tests
* bedrock fix
* [BREAKING] Python: Refactor orchestrations (#3023)
* Group chat refactoring Part 1; Next: HIL and handoff
* Add agent approval flow; next samples
* WIP: samples
* WIP: HIL samples
* Group chat HIL working; next: handoff
* Fix group chat tool approval sample
* WIP: refactor handoff; next handoff handling
* Handoff done; next handoff samples and concurrent and sequential
* Handoff samples, concurrent, and sequential done; next Magentic
* WIP: magentic; next test with samples + HIL
* Magentic Working; next fix all samples and tests
* Fix handoff samples; next tests
* WIP: fixing tests; some orchestration as agent samples are failing
* Group chat unit tests done
* Handoff unit tests done
* Remove old orchestration_request_info and fix related tests
* Magentic unit tests done
* Fix samples
* Fix test
* Fix test 2
* mypy
* Address comments
* Update readme
* Address comments
* Address comments 2
* Replace display name
* Python: ADR for create/get agent API (#2618)
* ADR for create/get agent API
* Updated ADR with implementation options
* Small updates
* Updated decision outcome section
* Updated broken links
* Small updates
* Fixed merge conflicts
* Small fix
* Updated decision outcome section
* Small fixes
* Updated provider naming based on client SDK
* Add ignored parameter for CodeQL in workflow (#3204)
* Implement IReadOnlyList on InMemoryChatMessageStore (#3205)
* .NET: Make ChatMessageStore and AIContextProvider context props settable (#3196)
* Make ChatMessageStore and AIContextProvider context props setable
* Add validation to preserve non-null requirement of certain properties.
* Fix broken tests.
* Python: Add dependencies param to ag-ui FastAPI endpoint (#3191)
* Add dependencies param to ag-ui FastAPI endpoint
* Address Copilot feedback
* renamed all (#3207)
* Python: ADR for simplified get response (#3098)
* ADR for simplified get response
* updated some language, added agent option and code comparison
* small update in sample
* added workflows and expanded some points
* changed decision and number
* updated with stream=False default
* .NET: [Breaking] Rename`AgentRunResponse` and `AgentRunResponseUpdate` classes (#3197)
* rename AgentRunResponse and AgentRunResponseUpdate classes - part1
* rename varialbles, parameters, methods and tests
* rollback unnecessary changes
* .NET: [Breaking] Rename AgentRunResponseEvent and AgentRunUpdateEvent classes (#3214)
* rename AgentRunResponseEvent and AgentRunUpdateEvent classes
* rollback unnecessary changes
* Python: Create/Get Agent API for Azure V2 (#3059)
* Added get_agent method to Azure AI V2
* Small fixes
* Small fix
* Removed AzureAIAgentProvider
* Added create_agent method
* Small fixes
* Fixed code interpreter tool mapping
* Added agent provider for V2 client
* Updated response format handling
* Added provider example
* Fixed errors
* Update python/samples/getting_started/agents/azure_ai/README.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Small fix
* Updates from merge
* Resolved comments
* Resolved comments
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Python: Add more specific exceptions to Workflow (#3188)
* Add more specifc workflow exceptions
* Fix tests
* AI comments
* Misc
* Python: Added AzureAI sample for downloading code interpreter generated files (#3189)
* added azure ai code interpreter file download sample
* copilot fix suggestions
* function name fixes + readme update
* small fix
* update package versions (#3223)
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
* Python: fix(core): correct FunctionResultContent ordering in WorkflowAgent.merge_updates (#3168)
* fix(core): simplify FunctionResultContent ordering in WorkflowAgent.merge_updates
* improve comment
* Fix name
* fix(workflows): rename WorkflowOutputEvent.source_executor_id to executor_id for API consistency (#3166)
* Python: fix(ag-ui): add MCP tool support for AG-UI approval flows (#3212)
* add MCP tool support for AG-UI approval flows
* use attribute in place of property
* Python: Properly configure structured outputs based on new options dict (#3213)
* Properly configure structured outputs based on new options dict
* Fix mypy
* .NET: Merge AgentRunOptions.AdditionalProperties into ChatOptions.AdditionalProperties (#3184)
* Merge AgentRunOptions.AdditionalProperties into ChatOptions.AdditionalProperties
* Fix namespace and typo.
* .NET: Update Google.GenAI to 0.11.0 and remove polyfill implementations (#3232)
* Initial plan
* Update Google.GenAI to 0.11.0 and remove polyfill files
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
* .NET: [BREAKING] Renamed CreateAIAgent/GetAIAgent to AsAIAgent (#3222)
* Renamed chat client extension method
* Additional renaming
* Updated documentation
* Fixed tests
* Small fix
* Small fix
* Updated DurableAIAgent and fixed integration tests (#3241)
* Python: Create/Get Agent API for Azure V1 (#3192)
* Added provider implementation for Azure AI V1
* Small fixes
* Fixed OpenAPI example
* Fixed local MCP example
* Fixed hosted MCP example
* Fixed file search sample
* Small fixes
* Resolved comments
* Doc updates
* Bump azure-core from 1.37.0 to 1.38.0 in /python (#3209)
Bumps [azure-core](https://github.com/Azure/azure-sdk-for-python) from 1.37.0 to 1.38.0.
- [Release notes](https://github.com/Azure/azure-sdk-for-python/releases)
- [Commits](https://github.com/Azure/azure-sdk-for-python/compare/azure-core_1.37.0...azure-core_1.38.0)
---
updated-dependencies:
- dependency-name: azure-core
dependency-version: 1.38.0
dependency-type: indirect
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Python: Create/Get Agent API for OpenAI Assistants (#3208)
* Added provider implementation
* Added example with response format
* Small improvements
* Python: (AG-UI) Support service-managed thread on AG-UI (#3136)
* added service thread support
* set service_thread_id to only supplied_thread_id
* uses raw_representation to extract the conversation_id
* removed accidental edit
* updated test to use raw_representation
* resolves copilot review feedback
* revert back StubAgent, since not used
* removed relative module import
* removed hasattr check per PR feedback
* Create/Get Agent API - fixes and example improvements (#3246)
* .NET Purview Middleware: Improve Background Job Runner Injection (#3256)
* Clean up background job dependency injection
* Fix xml documentation grammar
* Python: [BREAKING] Renamed create_agent to as_agent (#3249)
* Renamed create_agent to as_agent
* Override for as_agent
* Added override
* Python: Update package version (#3258)
* package version 260116
* removed name tags
* Python: Fixed Azure chat client for asynchronous filtering (#3260)
* Fixed Azure chat client for asynchronous filtering
* Updated test
* Python: Fixed use_agent_middleware calling private _normalize_messages (#3264)
* Fix use_agent_middleware calling private _normalize_messages
* Fixed A2A and Copilot Studio agent
* Python: Added rai_config to Azure AI agent creation (#3265)
* Add kwargs to create_agent method
* Added test for kwargs
* Addressed comment
* Added doc string
* Python: Filter conversation_id when passing kwargs to agent as tool (#3266)
* Filter conversation_id when passing kwargs to agent as tool
* Small fix
* Update python/samples/getting_started/agents/azure_ai/README.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/samples/getting_started/agents/openai/openai_responses_client_with_agent_as_tool.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update python/samples/getting_started/agents/azure_ai/azure_ai_with_agent_as_tool.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Bump actions/setup-dotnet from 5.0.1 to 5.1.0 (#3273)
Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 5.0.1 to 5.1.0.
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/v5.0.1...v5.1.0)
---
updated-dependencies:
- dependency-name: actions/setup-dotnet
dependency-version: 5.1.0
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Update ignored checks in merge-gatekeeper workflow
* Python: [BREAKING] Make response_format validation errors visible to users (#3274)
* Make response_format validation errors visible to users
* Small fix
* Addressed comments
* Python: fix(declarative): Fix MCP tool connection not passed from YAML to Azure AI agent creation API (#3248)
* fix(declarative): Fix MCP tool connection not passed from YAML
* Add samples to README
* Fix mypy
* Fix mypy again
* Address PR comments
* fix#3171, ensure proper form rendering for int (#3201)
* Bump uv from 0.9.25 to 0.9.26 in /python (#3288)
Bumps [uv](https://github.com/astral-sh/uv) from 0.9.25 to 0.9.26.
- [Release notes](https://github.com/astral-sh/uv/releases)
- [Changelog](https://github.com/astral-sh/uv/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/uv/compare/0.9.25...0.9.26)
---
updated-dependencies:
- dependency-name: uv
dependency-version: 0.9.26
dependency-type: direct:development
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump ruff from 0.14.11 to 0.14.13 in /python (#3287)
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.14.11 to 0.14.13.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.14.11...0.14.13)
---
updated-dependencies:
- dependency-name: ruff
dependency-version: 0.14.13
dependency-type: direct:development
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Bump tar from 7.4.3 to 7.5.3 in /python/packages/devui/frontend (#3267)
Bumps [tar](https://github.com/isaacs/node-tar) from 7.4.3 to 7.5.3.
- [Release notes](https://github.com/isaacs/node-tar/releases)
- [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-tar/compare/v7.4.3...v7.5.3)
---
updated-dependencies:
- dependency-name: tar
dependency-version: 7.5.3
dependency-type: indirect
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* .NET: Delete sync extension methods for agent (#3291)
* Delete sync extension methods for agent
* Fix comments and obsolete attribute
* Remove more sync methods.
* Fix naming and comments.
* Fix unit tests
* Python: Fix: Add system_instructions to ChatClient LLM span tracing (#3164)
* Fix: Add system_instructions to ChatClient LLM span tracing
- Add system_instructions parameter to _capture_messages() calls in
_trace_get_response() and _trace_get_streaming_response()
- Extract instructions from chat_options in kwargs
- Add unit tests to verify system_instructions are captured correctly
When using ChatClient with ChatOptions.instructions, the OpenTelemetry
LLM span was missing system messages in gen_ai.input.messages and the
gen_ai.system_instructions attribute was not being set.
This fix aligns the ChatClient-level tracing with the Agent-level
tracing which already correctly passes system_instructions.
Fixes#3163
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add edge case tests for system_instructions
- Add test for empty string instructions (should not set attribute)
- Add test for list-type instructions (verify multiple items captured)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Simplify: use options.get('instructions') directly instead of kwargs.get('chat_options')
Addresses reviewer feedback:
- Removed unnecessary chat_options variable from kwargs
- Directly access instructions from the options parameter
- Updated tests to use dict syntax for options (TypedDict convention)
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Improve PR number handling in workflow (#3302)
* Improve PR number handling in workflow
Refine PR number extraction and validation method.
* Update .github/workflows/python-test-coverage-report.yml
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Fix error message for invalid PR number
---------
Co-authored-by: Copilot <175728472+Copilot@…
* Modify failures
* Fix mypy errors
* Address comments
* Update durabletask version
* Remove event loops
* Add comment
* Fix typing for apps
---------
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Dina Suehiro Jones <dina.s.jones@intel.com>
Co-authored-by: Tao Chen <taochen@microsoft.com>
Co-authored-by: Kurt <65111699+q33566@users.noreply.github.com>
Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com>
Co-authored-by: Korolev Dmitry <deagle.gross@gmail.com>
Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
Co-authored-by: Jose Luis Latorre Millas <joslat@gmail.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Richard Ortega <richardjortega@gmail.com>
Co-authored-by: 刘邦学AI <lbbniu@gmail.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Nico Möller <nkm-moeller@mail.de>
Co-authored-by: Chris Gillum <cgillum@microsoft.com>
Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com>
Co-authored-by: Phillip Hoff <phillip.hoff@gmail.com>
Co-authored-by: Ege Ozan Özyedek <36128615+egeozanozyedek@users.noreply.github.com>
Co-authored-by: samueljohnsiby <66901393+samueljohnsiby@users.noreply.github.com>
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
Co-authored-by: Hao Luo <338265+howlowck@users.noreply.github.com>
Co-authored-by: Victor Dibia <chuvidi2003@gmail.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: Jacob Viau <javia@microsoft.com>
Co-authored-by: SuperKenVery <39673849+SuperKenVery@users.noreply.github.com>
Co-authored-by: Sunil Dutta <dutta.2003@gmail.com>
Co-authored-by: Sunil Dutta <sunil.dutta@penske.com>
Co-authored-by: budgetboardingai <apurva.sharma31@gmail.com>
Co-authored-by: Syrine Chelly <62653967+SyChell@users.noreply.github.com>
Co-authored-by: SergeyMenshykh <sergemenshikh@gmail.com>
Co-authored-by: westey <164392973+westey-m@users.noreply.github.com>
Co-authored-by: takanori-terai <123897708+takanori-terai@users.noreply.github.com>
Co-authored-by: claude89757 <138977524+claude89757@users.noreply.github.com>
Co-authored-by: Gavin Aguiar <80794152+gavin-aguiar@users.noreply.github.com>
Co-authored-by: Sukeesh <vsukeeshbabu@gmail.com>
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu>
Co-authored-by: Ao Chen <chenao3220@gmail.com>
Co-authored-by: Dina Suehiro Jones <dina.s.jones@intel.com>
Co-authored-by: eoindoherty1 <eoindoherty@microsoft.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Darren Cohen <39422044+dargilco@users.noreply.github.com>
Co-authored-by: Ben Thomas <ben.thomas@microsoft.com>
Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: Shyju Krishnankutty <connectshyju@gmail.com>
* Update devcontainer versions for .net
* Fix version number
* Remove docker in docker
* bring back docker in docker
* Try bookworm version of container
* Try the trixie image
* Try noble container
* Try preview image
* Try 2-10.0
* Add docker file to work around devcontainer bug
* refactor: Rename AggregateTurnMessagesExecutor
* feat: Rework Agent Hosting for Configurability and HIL support
* Adds support for selecting whether updates and/or full responses are
emitted to events
* Adds support for HIL/FunctionCalls (including interception)
* Implements internal support for ExternalRequests from any executor
(not just RequestPort)
* test: Add tests for new AIAgentHostExecutor functionality
* feat: Unify non-Handoff Agent Hosting
* doc: More explicit documentation for `overwrite` in RouteBuilder
* adds support for labels in edges, fixes rendering of labels in dot and mermaid, adds rendering of labels in edges
* Update dotnet/src/Microsoft.Agents.AI.Workflows/Visualization/WorkflowVisualizer.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* escaping edge labels, adding tests for labels containing strange characters that would break the diagram and enabling the previous signature so the API has backwards compatibility.
* Unify label in EdgeData
* Edge API adjustments, removed useless "sanitizer"
* fixed test
* Fix in Sample
* update
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Jacob Alber <jaalber@microsoft.com>
Co-authored-by: Chris <66376200+crickman@users.noreply.github.com>
* Roslyn Source Generators for Workflow Executor Routing.
* Update dotnet/src/Microsoft.Agents.AI.Workflows.Generators/ExecutorRouteGenerator.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* WIP.
* All fixed up except dangling sends/yields attriutes, working on that next.
* Add protocol-only generation for SendsMessage/YieldsOutput attributes
* Ensuring collections that can change order are sorted to enable pipeline caching.
* Improvents per PR feedback.
---------
Co-authored-by: alliscode <bentho@microsoft.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Subworkflows run into issues with Checkpointing and the Chat Protocol:
* The concurrency rework made subtle changes in behaviour that introduced a hang when using subworkflows with ChatProtocol and streaming execution.
* The ResetAsync() implementation in WorkflowHostExecutor was improperly resetting the joinContext - this was happening on restore checkpoint _after_ the join context was attached when
* Subworkflows cannot be used as the start node when hosted AsAgent due to inability to treat Catch-All as a Chat Protocol
* Subworkflow ownership issue when used in non-concurrent mode after finishing a run
Also fixes:
* When ChatMessages are output by executors that are not agents, there is no corresponding AgentResponseUpdate/AgentResponse event
Breaking Changes
* [BREAKING CHANGE] It is possible to provide the wrong RunId when resuming from CheckpointInfo (even though the data already exists on CheckpointInfo)
* fix(anthropic): Add response_format support for structured outputs
* only use from options
* use native way of response format
* ruff lint fix
* address comment; handle dict
* Fix: Add system_instructions to ChatClient LLM span tracing
- Add system_instructions parameter to _capture_messages() calls in
_trace_get_response() and _trace_get_streaming_response()
- Extract instructions from chat_options in kwargs
- Add unit tests to verify system_instructions are captured correctly
When using ChatClient with ChatOptions.instructions, the OpenTelemetry
LLM span was missing system messages in gen_ai.input.messages and the
gen_ai.system_instructions attribute was not being set.
This fix aligns the ChatClient-level tracing with the Agent-level
tracing which already correctly passes system_instructions.
Fixes#3163
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add edge case tests for system_instructions
- Add test for empty string instructions (should not set attribute)
- Add test for list-type instructions (verify multiple items captured)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Simplify: use options.get('instructions') directly instead of kwargs.get('chat_options')
Addresses reviewer feedback:
- Removed unnecessary chat_options variable from kwargs
- Directly access instructions from the options parameter
- Updated tests to use dict syntax for options (TypedDict convention)
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* 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
* 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
* 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
* Make ChatMessageStore and AIContextProvider context props setable
* Add validation to preserve non-null requirement of certain properties.
* Fix broken tests.
* 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
* 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
* 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)
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>
* 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(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
* 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
* 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>
* 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
* 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
* 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.
* 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>
* 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>
* 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
* 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
* 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
* fix: correct BadRequestError when using Pydantic model in response_format
* Fix lint
---------
Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
* 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
* 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.
* 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
* 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>
## 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>
* Added an example of using kwargs in ai_function
* Added thread object to ai_function kwargs
* Updated docs
* Small fix
* Added thread parameter filtering
* 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>
* 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
* Add factory pattern to sequential orchestration builder
* Use temp list to avoid override
* Add sample and some other fixes
* Fix comments
* Small fix
* Update readme
* Support HITL for orchestration patterns
* Cleanup around naming
* Fix typing issues
* Clean up
* Naming clean up
* Updates to HITL to make it cleaner
* Rename human input hook to orchestration request info
* Clean up per PR feedback
- Replace OPENAI_APIKEY with OPENAI_API_KEY across all samples
- Replace AZURE_FOUNDRY_OPENAI_APIKEY with AZURE_FOUNDRY_OPENAI_API_KEY
- Ensures consistency with OpenAI's standard naming convention
- Applies to .NET and Python samples
Fixes#1001
Co-authored-by: Alexander Zarei <alzarei@users.noreply.github.com>
* .NET: [Durable Agents] Update CHANGELOG with release notes for past releases
Backfills the CHANGELOG.md files with the last several updates.
* Update dotnet/src/Microsoft.Agents.AI.DurableTask/CHANGELOG.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update the Azure Functions changelog and add GHCP changelog instructions for these projects
* Tweak instructions
* Remove the timestamp requirement
* Rename instructions file
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* change namespaces for agents and extension methods of the Microsoft.Agents.AI.OpenAI package
* remove unnecessary namespace
* remove unused namespaces
* fix compilation issues and rrolled back removed run methods
* sort usings
* add extension methods for AIAgent to work with OpenAI Responses primitives
* Move OpenAIChatClientAgent and OpenAIResponseClientAgent to samples
* sort usings
* sort usings
* Title: Fix WorkflowFailedEvent error extraction to use details instead of error Body:
Summary
Fixed WorkflowFailedEvent mapping to extract error message from details.message instead of non-existent error attribute
Added support for including details.extra context in error messages when present
Problem
The WorkflowFailedEvent handler in _mapper.py was reading event.error, but WorkflowFailedEvent uses a details attribute (of type WorkflowErrorDetails), not error. This caused all workflow failures to display "Unknown error" in the UI instead of the actual error message.
Fix
Updated the handler to match the pattern already used by ExecutorFailedEvent:
Read from event.details instead of event.error
Extract details.message for the error text
Include details.extra context when available
* improve error handling consistency
All python code resides under the `python/` directory.
All C# code resides under the `dotnet/` directory.
Microsoft Agent Framework - a multi-language framework for building, orchestrating, and deploying AI agents.
The purpose of the code is to provide a framework for building AI agents.
## Repository Structure
When contributing to this repository, please follow these guidelines:
-`python/` - Python implementation → see [python/AGENTS.md](../python/AGENTS.md)
-`dotnet/` - C#/.NET implementation → see [dotnet/AGENTS.md](../dotnet/AGENTS.md)
-`docs/` - Design documents and architectural decision records
## C# Code Guidelines
## Architectural Decision Records (ADRs)
Here are some general guidelines that apply to all code.
ADRs in `docs/decisions/` capture significant design decisions and their rationale. They document considered alternatives, trade-offs, and the reasoning behind choices.
- The top of all *.cs files should have a copyright notice: `// Copyright (c) Microsoft. All rights reserved.`
-All public methods and classes should have XML documentation comments.
**Templates:**
-`adr-template.md` - Full template with detailed sections
-`adr-short-template.md` - Abbreviated template for simpler decisions
### C# Sample Code Guidelines
Sample code is located in the `dotnet/samples` directory.
When adding a new sample, follow these steps:
- The sample should be a standalone .net project in one of the subdirectories of the samples directory.
- The directory name should be the same as the project name.
- The directory should contain a README.md file that explains what the sample does and how to run it.
- The README.md file should follow the same format as other samples.
- The csproj file should match the directory name.
- The csproj file should be configured in the same way as other samples.
- The project should preferably contain a single Program.cs file that contains all the sample code.
- The sample should be added to the solution file in the samples directory.
- The sample should be tested to ensure it works as expected.
- A reference to the new samples should be added to the README.md file in the parent directory of the new sample.
The sample code should follow these guidelines:
- Configuration settings should be read from environment variables, e.g. `var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");`.
- Environment variables should use upper snake_case naming convention.
- Secrets should not be hardcoded in the code or committed to the repository.
- The code should be well-documented with comments explaining the purpose of each step.
- The code should be simple and to the point, avoiding unnecessary complexity.
- Prefer inline literals over constants for values that are not reused. For example, use `new ChatClientAgent(chatClient, instructions: "You are a helpful assistant.")` instead of defining a constant for "instructions".
- Ensure that all private classes are sealed
- Use the Async suffix on the name of all async methods that return a Task or ValueTask.
- Prefer defining variables using types rather than var, to help users understand the types involved.
- Follow the patterns in the samples in the same directories where new samples are being added.
- The structure of the sample should be as follows:
- The top of the Program.cs should have a copyright notice: `// Copyright (c) Microsoft. All rights reserved.`
- Then add a comment describing what the sample is demonstrating.
- Then add the necessary using statements.
- Then add the main code logic.
- Finally, add any helper methods or classes at the bottom of the file.
### C# Unit Test Guidelines
Unit tests are located in the `dotnet/tests` directory in projects with a `.UnitTests.csproj` suffix.
Unit tests should follow these guidelines:
- Use `this.` for accessing class members
- Add Arrange, Act and Assert comments for each test
- Ensure that all private classes, that are not subclassed, are sealed
- Use the Async suffix on the name of all async methods
- Use the Moq library for mocking objects where possible
- Validate that each test actually tests the target behavior, e.g. we should not have tests that creates a mock, calls the mock and then verifies that the mock was called, without the target code being involved. We also shouldn't have tests that test language features, e.g. something that the compiler would catch anyway.
- Avoid adding excessive comments to tests. Instead favour clear easy to understand code.
- Follow the patterns in the unit tests in the same project or classes to which new tests are being added
When proposing architectural changes, create an ADR to capture options considered and the decision rationale. See [docs/decisions/README.md](../docs/decisions/README.md) for the full process.
- Each pull request that modifies code should add just one bulleted entry to the `CHANGELOG.md` file containing a change title (usually the PR title) and a link to the PR itself.
- New PRs should be added to the top of the `CHANGELOG.md` file under a "## [Unreleased]" heading.
- If the PR is the first since the last release, the existing "## [Unreleased]" heading should be replaced with a "## v[X.Y.Z]" heading and the PRs since the last release should be added to the new "## [Unreleased]" heading.
- The style of new `CHANGELOG.md` entries should match the style of the other entries in the file.
- If the PR introduces a breaking change, the changelog entry should be prefixed with "[BREAKING]".
@@ -980,6 +1016,8 @@ AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential(
### 3. OpenAI Assistants Migration
> ⚠️ **DEPRECATION WARNING**: The OpenAI Assistants API has been deprecated. The Agent Framework extension methods for Assistants are marked as `[Obsolete]`. **Please use the Responses API instead** (see Section 6: OpenAI Responses Migration).
<configuration_changes>
**Remove Semantic Kernel Packages:**
```xml
@@ -1291,52 +1329,7 @@ var result = await agent.RunAsync(userInput, thread);
@@ -53,7 +53,7 @@ Still have questions? Join our [weekly office hours](./COMMUNITY.md#public-commu
### ✨ **Highlights**
- **Graph-based Workflows**: Connect agents and deterministic functions using data flows with streaming, checkpointing, human-in-the-loop, and time-travel capabilities
This folder contains sample agent definitions than be ran using the declarative agent support, for python see the [declarative agent python sample folder](../python/samples/getting_started/declarative/).
This folder contains sample agent definitions that can be run using the declarative agent support, for python see the [declarative agent python sample folder](../python/samples/02-agents/declarative/).
@@ -64,7 +64,7 @@ Approaches observed from the compared SDKs:
| AutoGen | **Approach 1** Separates messages into Agent-Agent (maps to Primary) and Internal (maps to Secondary) and these are returned as separate properties on the agent response object. See [types of messages](https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/messages.html#types-of-messages) and [Response](https://microsoft.github.io/autogen/stable/reference/python/autogen_agentchat.base.html#autogen_agentchat.base.Response) | **Approach 2** Returns a stream of internal events and the last item is a Response object. See [ChatAgent.on_messages_stream](https://microsoft.github.io/autogen/stable/reference/python/autogen_agentchat.base.html#autogen_agentchat.base.ChatAgent.on_messages_stream) |
| OpenAI Agent SDK | **Approach 1** Separates new_items (Primary+Secondary) from final output (Primary) as separate properties on the [RunResult](https://github.com/openai/openai-agents-python/blob/main/src/agents/result.py#L39) | **Approach 1** Similar to non-streaming, has a way of streaming updates via a method on the response object which includes all data, and then a separate final output property on the response object which is populated only when the run is complete. See [RunResultStreaming](https://github.com/openai/openai-agents-python/blob/main/src/agents/result.py#L136) |
| Google ADK | **Approach 2** [Emits events](https://google.github.io/adk-docs/runtime/#step-by-step-breakdown) with [FinalResponse](https://github.com/google/adk-java/blob/main/core/src/main/java/com/google/adk/events/Event.java#L232) true (Primary) / false (Secondary) and callers have to filter out those with false to get just the final response message | **Approach 2** Similar to non-streaming except [events](https://google.github.io/adk-docs/runtime/#streaming-vs-non-streaming-output-partialtrue) are emitted with [Partial](https://github.com/google/adk-java/blob/main/core/src/main/java/com/google/adk/events/Event.java#L133) true to indicate that they are streaming messages. A final non partial event is also emitted. |
| AWS (Strands) | **Approach 3** Returns an [AgentResult](https://strandsagents.com/latest/api-reference/agent/#strands.agent.agent_result.AgentResult) (Primary) with messages and a reason for the run's completion. | **Approach 2** [Streams events](https://strandsagents.com/latest/api-reference/agent/#strands.agent.agent.Agent.stream_async) (Primary+Secondary) including, response text, current_tool_use, even data from "callbacks" (strands plugins) |
| AWS (Strands) | **Approach 3** Returns an [AgentResult](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent_result/) (Primary) with messages and a reason for the run's completion. | **Approach 2** [Streams events](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent/#strands.agent.agent.Agent.stream_async) (Primary+Secondary) including, response text, current_tool_use, even data from "callbacks" (strands plugins) |
| LangGraph | **Approach 2** A mixed list of all [messages](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) | **Approach 2** A mixed list of all [messages](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) |
| Agno | **Combination of various approaches** Returns a [RunResponse](https://docs.agno.com/reference/agents/run-response) object with text content, messages (essentially chat history including inputs and instructions), reasoning and thinking text properties. Secondary events could potentially be extracted from messages. | **Approach 2** Returns [RunResponseEvent](https://docs.agno.com/reference/agents/run-response#runresponseevent-types-and-attributes) objects including tool call, memory update, etc, information, where the [RunResponseCompletedEvent](https://docs.agno.com/reference/agents/run-response#runresponsecompletedevent) has similar properties to RunResponse|
| A2A | **Approach 3** Returns a [Task or Message](https://a2aproject.github.io/A2A/latest/specification/#71-messagesend) where the message is the final result (Primary) and task is a reference to a long running process. | **Approach 2** Returns a [stream](https://a2aproject.github.io/A2A/latest/specification/#72-messagestream) that contains task updates (Secondary) and a final message (Primary) |
@@ -163,8 +163,8 @@ foreach (var update in response.Messages)
### Option 2 Run: Container with Primary and Secondary Properties, RunStreaming: Stream of Primary + Secondary
Run returns a new response type that has separate properties for the Primary Content and the Secondary Updates leading up to it.
The Primary content is available in the `AgentRunResponse.Messages` property while Secondary updates are in a new `AgentRunResponse.Updates` property.
`AgentRunResponse.Text` returns the Primary content text.
The Primary content is available in the `AgentResponse.Messages` property while Secondary updates are in a new `AgentResponse.Updates` property.
`AgentResponse.Text` returns the Primary content text.
Since streaming would still need to return an `IAsyncEnumerable` of updates, the design would differ from non-streaming.
With non-streaming Primary and Secondary content is split into separate lists, while with streaming it's combined in one stream.
@@ -232,24 +232,24 @@ await foreach (var update in responses)
@@ -463,7 +463,7 @@ Option 2 chosen so that we can vary Agent responses independently of Chat Client
### StructuredOutputs Decision
We will not support structured output per run request, but individual agents are free to allow this on the concrete implementation or at construction time.
We will however add support for easily extracting a structured output type from the `AgentRunResponse`.
We will however add support for easily extracting a structured output type from the `AgentResponse`.
## Addendum 1: AIContext Derived Types for different response types / Gap Analysis (Work in progress)
@@ -495,8 +495,8 @@ We need to decide what AIContent types, each agent response type will be mapped
| SDK | Structured Outputs support |
|-|-|
| AutoGen | **Approach 1** Supports [configuring an agent](https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/agents.html#structured-output) at agent creation. |
| Google ADK | **Approach 1** Both [input and output shemas can be specified for LLM Agents](https://google.github.io/adk-docs/agents/llm-agents/#structuring-data-input_schema-output_schema-output_key) at construction time. This option is specific to this agent type and other agent types do not necessarily support |
| AWS (Strands) | **Approach 2** Supports a special invocation method called [structured_output](https://strandsagents.com/latest/api-reference/agent/#strands.agent.agent.Agent.structured_output) |
| Google ADK | **Approach 1** Both [input and output schemas can be specified for LLM Agents](https://google.github.io/adk-docs/agents/llm-agents/#structuring-data-input_schema-output_schema-output_key) at construction time. This option is specific to this agent type and other agent types do not necessarily support |
| AWS (Strands) | **Approach 2** Supports a special invocation method called [structured_output](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent/#strands.agent.agent.Agent.structured_output) |
| LangGraph | **Approach 1** Supports [configuring an agent](https://langchain-ai.github.io/langgraph/agents/agents/?h=structured#6-configure-structured-output) at agent construction time, and a [structured response](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) can be retrieved as a special property on the agent response |
| Agno | **Approach 1** Supports [configuring an agent](https://docs.agno.com/examples/getting-started/structured-output) at agent construction time |
| A2A | **Informal Approach 2** Doesn't formally support schema negotiation, but [hints can be provided via metadata](https://a2a-protocol.org/latest/specification/#97-structured-data-exchange-requesting-and-providing-json) at invocation time |
@@ -508,7 +508,7 @@ We need to decide what AIContent types, each agent response type will be mapped
|-|-|
| AutoGen | Supports a [stop reason](https://microsoft.github.io/autogen/stable/reference/python/autogen_agentchat.base.html#autogen_agentchat.base.TaskResult.stop_reason) which is a freeform text string |
| Google ADK | [No equivalent present](https://github.com/google/adk-python/blob/main/src/google/adk/events/event.py) |
| AWS (Strands) | Exposes a [stop_reason](https://strandsagents.com/latest/api-reference/types/#strands.types.event_loop.StopReason) property on the [AgentResult](https://strandsagents.com/latest/api-reference/agent/#strands.agent.agent_result.AgentResult) class with options that are tied closely to LLM operations. |
| AWS (Strands) | Exposes a [stop_reason](https://strandsagents.com/latest/documentation/docs/api-reference/python/types/event_loop/#strands.types.event_loop.StopReason) property on the [AgentResult](https://strandsagents.com/latest/documentation/docs/api-reference/python/agent/agent_result/) class with options that are tied closely to LLM operations. |
| LangGraph | No equivalent present, output contains only [messages](https://langchain-ai.github.io/langgraph/agents/run_agents/#output-format) |
| A2A | No equivalent present, response only contains a [message](https://a2a-protocol.org/latest/specification/#64-message-object) or [task](https://a2a-protocol.org/latest/specification/#61-task-object). |
@@ -54,7 +54,7 @@ The table below represents the majority of the naming changes discussed in issue
| *Mcp* & *Http* | *MCP* & *HTTP* | accepted | Acronyms should be uppercased in class names, according to PEP 8. | None |
| `agent.run_streaming` | `agent.run_stream` | accepted | Shorter and more closely aligns with AutoGen and Semantic Kernel names for the same methods. | None |
| `workflow.run_streaming` | `workflow.run_stream` | accepted | In sync with `agent.run_stream` and shorter and more closely aligns with AutoGen and Semantic Kernel names for the same methods. | None |
| AgentRunResponse & AgentRunResponseUpdate | AgentResponse & AgentResponseUpdate | rejected | Rejected, because it is the response to a run invocation and AgentResponse is too generic. | None |
| AgentResponse & AgentResponseUpdate | AgentResponse & AgentResponseUpdate | rejected | Rejected, because it is the response to a run invocation and AgentResponse is too generic. | None |
| *Content | * | rejected | Rejected other content type renames (removing `Content` suffix) because it would reduce clarity and discoverability. | Item was also considered, but rejected as it is very similar to Content, but would be inconsistent with dotnet. |
| ChatResponse & ChatResponseUpdate | Response & ResponseUpdate | rejected | Rejected, because Response is too generic. | None |
@@ -1279,7 +1279,7 @@ Below are the details of the option selected for chat clients that is also selec
#### 3.1 Continuation Token of a Custom Type
This option suggests using `ContinuationToken` to encapsulate all properties representing a long-running operation. The continuation token will be returned by agents in the
`ContinuationToken` property of the `AgentRunResponse` and `AgentRunResponseUpdate` responses to indicate that the response is part of a long-running operation. A null value
`ContinuationToken` property of the `AgentResponse` and `AgentResponseUpdate` responses to indicate that the response is part of a long-running operation. A null value
of the property will indicate that the response is not part of a long-running operation or the long-running operation has been completed. Callers will set the token in the
`ContinuationToken` property of the `AgentRunOptions` class in follow-up calls to the `Run{Streaming}Async` methods to indicate that they want to "continue" the long-running
operation identified by the token.
@@ -1313,18 +1313,18 @@ public class AgentRunOptions
- Provides bidirectional client and server support
@@ -69,7 +69,7 @@ Chosen option: "Current approach with internal event types and framework-native
3.**Agent Factory Pattern** - `MapAGUIAgent` uses factory function `(messages) => AIAgent` to allow request-specific agent configuration supporting multi-tenancy
4.**Bidirectional Conversion Architecture** - Symmetric conversion logic in shared namespace compiled into both packages for server (`AgentRunResponseUpdate` → AG-UI events) and client (AG-UI events → `AgentRunResponseUpdate`)
4.**Bidirectional Conversion Architecture** - Symmetric conversion logic in shared namespace compiled into both packages for server (`AgentResponseUpdate` → AG-UI events) and client (AG-UI events → `AgentResponseUpdate`)
5.**Thread Management** - `AGUIAgentThread` stores only `ThreadId` with thread ID communicated via `ConversationId`; applications manage persistence for parity with other implementations and to be compliant with the protocol. Future extensions will support having the server manage the conversation.
There is a misalignment between the create/get agent API in the .NET and Python implementations.
In .NET, the `CreateAIAgent` method can create either a local instance of an agent or a remote instance if the backend provider supports it. For remote agents, once the agent is created, you can retrieve an existing remote agent by using the `GetAIAgent` method. If a backend provider doesn't support remote agents, `CreateAIAgent` just initializes a new local agent instance and `GetAIAgent` is not available. There is also a `BuildAIAgent` method, which is an extension for the `ChatClientBuilder` class from `Microsoft.Extensions.AI`. It builds pipelines of `IChatClient` instances with an `IServiceProvider`. This functionality does not exist in Python, so `BuildAIAgent` is out of scope.
In Python, there is only one `create_agent` method, which always creates a local instance of the agent. If the backend provider supports remote agents, the remote agent is created only on the first `agent.run()` invocation.
Below is a short summary of different providers and their APIs in .NET:
| Package | Method | Behavior | Python support |
|---|---|---|---|
| Microsoft.Agents.AI | `CreateAIAgent` (based on `IChatClient`) | Creates a local instance of `ChatClientAgent`. | Yes (`create_agent` in `BaseChatClient`). |
| Microsoft.Agents.AI.Anthropic | `CreateAIAgent` (based on `IBetaService` and `IAnthropicClient`) | Creates a local instance of `ChatClientAgent`. | Yes (`AnthropicClient` inherits `BaseChatClient`, which exposes `create_agent`). |
| Microsoft.Agents.AI.AzureAI (V2) | `GetAIAgent` (based on `AIProjectClient` with `AgentReference`) | Creates a local instance of `ChatClientAgent`. | Partial (Python uses `create_agent` from `BaseChatClient`). |
| Microsoft.Agents.AI.AzureAI (V2) | `GetAIAgent`/`GetAIAgentAsync` (with `Name`/`ChatClientAgentOptions`) | Fetches `AgentRecord` via HTTP, then creates a local `ChatClientAgent` instance. | No |
| Microsoft.Agents.AI.AzureAI (V2) | `CreateAIAgent`/`CreateAIAgentAsync` (based on `AIProjectClient`) | Creates a remote agent first, then wraps it into a local `ChatClientAgent` instance. | No |
| Microsoft.Agents.AI.AzureAI.Persistent (V1) | `GetAIAgent` (based on `PersistentAgentsClient` with `PersistentAgent`) | Creates a local instance of `ChatClientAgent`. | Partial (Python uses `create_agent` from `BaseChatClient`). |
| Microsoft.Agents.AI.AzureAI.Persistent (V1) | `GetAIAgent`/`GetAIAgentAsync` (with `AgentId`) | Fetches `PersistentAgent` via HTTP, then creates a local `ChatClientAgent` instance. | No |
| Microsoft.Agents.AI.AzureAI.Persistent (V1) | `CreateAIAgent`/`CreateAIAgentAsync` | Creates a remote agent first, then wraps it into a local `ChatClientAgent` instance. | No |
| Microsoft.Agents.AI.OpenAI | `GetAIAgent` (based on `AssistantClient` with `Assistant`) | Creates a local instance of `ChatClientAgent`. | Partial (Python uses `create_agent` from `BaseChatClient`). |
| Microsoft.Agents.AI.OpenAI | `GetAIAgent`/`GetAIAgentAsync` (with `AgentId`) | Fetches `Assistant` via HTTP, then creates a local `ChatClientAgent` instance. | No |
| Microsoft.Agents.AI.OpenAI | `CreateAIAgent`/`CreateAIAgentAsync` (based on `AssistantClient`) | Creates a remote agent first, then wraps it into a local `ChatClientAgent` instance. | No |
| Microsoft.Agents.AI.OpenAI | `CreateAIAgent` (based on `ChatClient`) | Creates a local instance of `ChatClientAgent`. | Yes (`create_agent` in `BaseChatClient`). |
| Microsoft.Agents.AI.OpenAI | `CreateAIAgent` (based on `OpenAIResponseClient`) | Creates a local instance of `ChatClientAgent`. | Yes (`create_agent` in `BaseChatClient`). |
Another difference between Python and .NET implementation is that in .NET `CreateAIAgent`/`GetAIAgent` methods are implemented as extension methods based on underlying SDK client, like `AIProjectClient` from Azure AI or `AssistantClient` from OpenAI:
```csharp
// Definition
publicstaticChatClientAgentCreateAIAgent(
thisAIProjectClientaiProjectClient,
stringname,
stringmodel,
stringinstructions,
string?description=null,
IList<AITool>?tools=null,
Func<IChatClient,IChatClient>?clientFactory=null,
IServiceProvider?services=null,
CancellationTokencancellationToken=default)
{}
// Usage
AIProjectClientaiProjectClient=new(newUri(endpoint),newAzureCliCredential());// Initialization of underlying SDK client
varnewAgent=awaitaiProjectClient.CreateAIAgentAsync(name:AgentName,model:deploymentName,instructions:AgentInstructions,tools:[tool]);// ChatClientAgent creation from underlying SDK client
// Alternative usage (same as extension method, just explicit syntax)
Python doesn't support extension methods. Currently `create_agent` method is defined on `BaseChatClient`, but this method only creates a local instance of `ChatAgent` and it can't create remote agents for providers that support it for a couple of reasons:
- It's defined as non-async.
-`BaseChatClient` implementation is stateful for providers like Azure AI or OpenAI Assistants. The implementation stores agent/assistant metadata like `AgentId` and `AgentName`, so currently it's not possible to create different instances of `ChatAgent` from a single `BaseChatClient` in case if the implementation is stateful.
## Decision Drivers
- API should be aligned between .NET and Python.
- API should be intuitive and consistent between backend providers in .NET and Python.
## Considered Options
Add missing implementations on the Python side. This should include the following:
### agent-framework-azure-ai (both V1 and V2)
- Add a `get_agent` method that accepts an underlying SDK agent instance and creates a local instance of `ChatAgent`.
- Add a `get_agent` method that accepts an agent identifier, performs an additional HTTP request to fetch agent data, and then creates a local instance of `ChatAgent`.
- Override the `create_agent` method from `BaseChatClient` to create a remote agent instance and wrap it into a local `ChatAgent`.
.NET:
```csharp
varagent1=newAIProjectClient(...).GetAIAgent(agentInstanceFromSdkType);// Creates a local ChatClientAgent instance from Azure.AI.Projects.OpenAI.AgentReference
varagent2=newAIProjectClient(...).GetAIAgent(agentName);// Fetches agent data, creates a local ChatClientAgent instance
varagent3=newAIProjectClient(...).CreateAIAgent(...);// Creates a remote agent, returns a local ChatClientAgent instance
```
### agent-framework-core (OpenAI Assistants)
- Add a `get_agent` method that accepts an underlying SDK agent instance and creates a local instance of `ChatAgent`.
- Add a `get_agent` method that accepts an agent name, performs an additional HTTP request to fetch agent data, and then creates a local instance of `ChatAgent`.
- Override the `create_agent` method from `BaseChatClient` to create a remote agent instance and wrap it into a local `ChatAgent`.
.NET:
```csharp
varagent1=newAssistantClient(...).GetAIAgent(agentInstanceFromSdkType);// Creates a local ChatClientAgent instance from OpenAI.Assistants.Assistant
varagent2=newAssistantClient(...).GetAIAgent(agentId);// Fetches agent data, creates a local ChatClientAgent instance
varagent3=newAssistantClient(...).CreateAIAgent(...);// Creates a remote agent, returns a local ChatClientAgent instance
```
### Possible Python implementations
Methods like `create_agent` and `get_agent` should be implemented separately or defined on some stateless component that will allow to create multiple agents from the same instance/place.
Possible options:
#### Option 1: Module-level functions
Implement free functions in the provider package that accept the underlying SDK client as the first argument (similar to .NET extension methods, but expressed in Python).
| Multiple implementations | One package may contain V1, V2, and other agent types. Function names like `create_agent` become ambiguous - which agent type does it create? | Each provider class is explicit: `AzureAIAgentsProvider` vs `AzureAIProjectAgentProvider` |
| Discoverability | Users must know to import specific functions from the package | IDE autocomplete on provider instance shows all available methods |
| Client reuse | SDK client must be passed to every function call: `create_agent(client, ...)`, `get_agent(client, ...)` | SDK client passed once at construction: `provider = Provider(client)` |
**Option 1 example:**
```python
from agent_framework.azure import create_agent, get_agent
agent1 = await create_agent(client, name="Agent1", ...) # Which agent type, V1 or V2?
The method names (`create_agent`, `get_agent`) do not explicitly mention "service" or "remote" because:
- In Python, the provider class name explicitly identifies the service (`AzureAIAgentsProvider`, `OpenAIAssistantProvider`), making additional qualifiers in method names redundant.
- In .NET, these are extension methods on `AIProjectClient` or `AssistantClient`, which already imply service operations.
### Provider Class Naming
| Package | Provider Class | SDK Client | Service |
Current method `create_agent` (python) / `CreateAIAgent` (.NET) can be renamed to `as_agent` (python) / `AsAIAgent` (.NET) to emphasize the conversion logic rather than creation/initialization logic and to avoid collision with `create_agent` method for remote calls.
```python
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIChatClient
# Convert chat client to ChatAgent (no remote service involved)
client = OpenAIChatClient(model="gpt-4")
agent = client.as_agent(name="LocalAgent", instructions="...") # instead of create_agent
```
### Adding New Agent Types
Python:
1. Create provider class in appropriate package.
2. Implement `create_agent`, `get_agent`, `as_agent` as applicable.
.NET:
1. Create static class for extension methods.
2. Implement `CreateAIAgentAsync`, `GetAIAgentAsync`, `AsAIAgent` as applicable.
# Leveraging TypedDict and Generic Options in Python Chat Clients
## Context and Problem Statement
The Agent Framework Python SDK provides multiple chat client implementations for different providers (OpenAI, Anthropic, Azure AI, Bedrock, Ollama, etc.). Each provider has unique configuration options beyond the common parameters defined in `ChatOptions`. Currently, developers using these clients lack type safety and IDE autocompletion for provider-specific options, leading to runtime errors and a poor developer experience.
How can we provide type-safe, discoverable options for each chat client while maintaining a consistent API across all implementations?
## Decision Drivers
- **Type Safety**: Developers should get compile-time/static analysis errors when using invalid options
- **IDE Support**: Full autocompletion and inline documentation for all available options
- **Extensibility**: Users should be able to define custom options that extend provider-specific options
- **Consistency**: All chat clients should follow the same pattern for options handling
- **Provider Flexibility**: Each provider can expose its unique options without affecting the common interface
## Considered Options
- **Option 1: Status Quo - Class `ChatOptions` with `**kwargs`**
- **Option 2: TypedDict with Generic Type Parameters**
### Option 1: Status Quo - Class `ChatOptions` with `**kwargs`
The current approach uses a base `ChatOptions` Class with common parameters, and provider-specific options are passed via `**kwargs` or loosely typed dictionaries.
```python
# Current usage - no type safety for provider-specific options
response=awaitclient.get_response(
messages=messages,
temperature=0.7,
top_k=40,
random=42,# No validation
)
```
**Pros:**
- Simple implementation
- Maximum flexibility
**Cons:**
- No type checking for provider-specific options
- No IDE autocompletion for available options
- Runtime errors for typos or invalid options
- Documentation must be consulted for each provider
### Option 2: TypedDict with Generic Type Parameters (Chosen)
Each chat client is parameterized with a TypeVar bound to a provider-specific `TypedDict` that extends `ChatOptions`. This enables full type safety and IDE support.
- Users can extend options for their specific needs or advances in models
**Cons:**
- More complex implementation
- Some type: ignore comments needed for TypedDict field overrides
- Minor: Requires TypeVar with default (Python 3.13+ or typing_extensions)
> [NOTE!]
> In .NET this is already achieved through overloads on the `GetResponseAsync` method for each provider-specific options class, e.g., `AnthropicChatOptions`, `OpenAIChatOptions`, etc. So this does not apply to .NET.
### Implementation Details
1.**Base Protocol**: `ChatClientProtocol[TOptions]` is generic over options type, with default set to `ChatOptions` (the new TypedDict)
2.**Provider TypedDicts**: Each provider defines its options extending `ChatOptions`
They can even override fields with type=None to indicate they are not supported.
4.**Option Translation**: Common options are kept in place,and explicitly documented in the Options class how they are used. (e.g., `user` → `metadata.user_id`) in `_prepare_options` (for Anthropic) to preserve easy use of common options.
## Decision Outcome
Chosen option: **"Option 2: TypedDict with Generic Type Parameters"**, because it provides full type safety, excellent IDE support with autocompletion, and allows users to extend provider-specific options for their use cases. Extended this Generic to ChatAgents in order to also properly type the options used in agent construction and run methods.
See [typed_options.py](../../python/samples/02-agents/typed_options.py) for a complete example demonstrating the usage of typed options with custom extensions.
# Simplify Python Get Response API into a single method
## Context and Problem Statement
Currently chat clients must implement two separate methods to get responses, one for streaming and one for non-streaming. This adds complexity to the client implementations and increases the maintenance burden. This was likely done because the .NET version cannot do proper typing with a single method, in Python this is possible and this for instance is also how the OpenAI python client works, this would then also make it simpler to work with the Python version because there is only one method to learn about instead of two.
## Implications of this change
### Current Architecture Overview
The current design has **two separate methods** at each layer:
These are parallel methods on the agent, so consolidating the client methods would **not break** the agent API. You could keep `agent.run()` and `agent.run_stream()` unchanged while internally calling `get_response(stream=True/False)`.
All subclasses implement both `_inner_*` methods, except:
- OpenAI Assistants Client (and similar clients, such as Foundry Agents V1) - it implements `_inner_get_response` by calling `_inner_get_streaming_response`
### Implications of Consolidation
| Aspect | Impact |
|--------|--------|
| **Type Safety** | Overloads work well: `@overload` with `Literal[True]` → `AsyncIterable`, `Literal[False]` → `ChatResponse`. Runtime return type based on `stream` param. |
| **Breaking Change** | **Major breaking change** for anyone implementing custom chat clients. They'd need to update from 2 methods to 1 (or 2 inner methods to 1). |
| **Decorator Complexity** | All 3 decorator systems (function invocation, middleware, observability) would need refactoring to handle both paths in one wrapper. |
| **Code Reduction** | Significant reduction in _tools.py (~200 lines of near-duplicate code) and other decorators. |
| **Samples/Tests** | Many samples call `get_streaming_response()` directly - would need updates. |
| **Protocol Simplification** | `ChatClientProtocol` goes from 2 methods + 1 property to 1 method + 1 property. |
### Recommendation
The consolidation makes sense architecturally, but consider:
1.**The overload pattern with `stream: bool`** works well in Python typing:
2. **The decorator complexity** is the biggest concern. The current approach of separate decorators for separate methods is cleaner than conditional logic inside one wrapper.
## Decision Drivers
- Reduce code needed to implement a Chat Client, simplify the public API for chat clients
- Reduce code duplication in decorators and middleware
- Maintain type safety and clarity in method signatures
## Considered Options
1. Status quo: Keep separate methods for streaming and non-streaming
2. Consolidate into a single `get_response` method with a `stream` parameter
3. Option 2 plus merging `agent.run` and `agent.run_stream` into a single method with a `stream` parameter as well
## Option 1: Status Quo
- Good: Clear separation of streaming vs non-streaming logic
- Good: Aligned with .NET design, although it is already `run` for Python and `RunAsync` for .NET
- Bad: Code duplication in decorators and middleware
- Bad: More complex client implementations
## Option 2: Consolidate into Single Method
- Good: Simplified public API for chat clients
- Good: Reduced code duplication in decorators
- Good: Smaller API footprint for users to get familiar with
- Good: People using OpenAI directly already expect this pattern
- Bad: Increased complexity in decorators and middleware
- Bad: Less alignment with .NET design (`get_response(stream=True)` vs `GetStreamingResponseAsync`)
## Option 3: Consolidate + Merge Agent and Workflow Methods
- Good: Further simplifies agent and workflow implementation
- Good: Single method for all chat interactions
- Good: Smaller API footprint for users to get familiar with
- Good: People using OpenAI directly already expect this pattern
- Good: Workflows internally already use a single method (_run_workflow_with_tracing), so would eliminate public API duplication as well, with hardly any code changes
- Bad: More breaking changes for agent users
- Bad: Increased complexity in agent implementation
- Bad: More extensive misalignment with .NET design (`run(stream=True)` vs `RunStreamingAsync` in addition to `get_response` change)
## Misc
Smaller questions to consider:
- Should default be `stream=False` or `stream=True`? (Current is False)
- Default to `False` makes it simpler for new users, as non-streaming is easier to handle.
- Default to `False` aligns with existing behavior.
- Streaming tends to be faster, so defaulting to `True` could improve performance for common use cases.
- Should this differ between ChatClient, Agent and Workflows? (e.g., Agent and Workflow defaults to streaming, ChatClient to non-streaming)
When using agents, we often have cases where we want to pass some arbitrary services or data to an agent or some component in the agent execution stack.
These services or data are not necessarily known at compile time and can vary by the agent stack that the user has built.
E.g., there may be an agent decorator or chat client decorator that was added to the stack by the user, and an arbitrary payload needs to be passed to that decorator.
Since these payloads are related to components that are not integral parts of the agent framework, they cannot be added as strongly typed settings to the agent run options.
However, the payloads could be added to the agent run options as loosely typed 'features', that can be retrieved as needed.
In some cases certain classes of agents may support the same capability, but not all agents do.
Having the configuration for such a capability on the main abstraction would advertise the functionality to all users, even if their chosen agent does not support it.
The user may type test for certain agent types, and call overloads on the appropriate agent types, with the strongly typed configuration.
Having a feature collection though, would be an alternative way of passing such configuration, without needing to type check the agent type.
All agents that support the functionality would be able to check for the configuration and use it, simplifying the user code.
If the agent does not support the capability, that configuration would be ignored.
### Sample Scenario 1 - Per Run ChatMessageStore Override for hosting Libraries
We are building an agent hosting library, that can host any agent built using the agent framework.
Where an agent is not built on a service that uses in-service chat history storage, the hosting library wants to force the agent to use
the hosting library's chat history storage implementation.
This chat history storage implementation may be specifically tailored to the type of protocol that the hosting library uses, e.g. conversation id based storage or response id based storage.
The hosting library does not know what type of agent it is hosting, so it cannot provide a strongly typed parameter on the agent.
Instead, it adds the chat history storage implementation to a feature collection, and if the agent supports custom chat history storage, it retrieves the implementation from the feature collection and uses it.
```csharp
// Pseudo-code for an agent hosting library that supports conversation id based hosting.
Currently our base abstraction does not support structured output, since the capability is not supported by all agents.
For those agents that don't support structured output, we could add an agent decorator that takes the response from the underlying agent, and applies structured output parsing on top of it via an additional LLM call.
If we add structured output configuration as a feature, then any agent that supports structured output could retrieve the configuration from the feature collection and apply it, and where it is not supported, the configuration would simply be ignored.
We could add a simple StructuredOutputAgentFeature that can be added to the list of features and also be used to return the generated structured output.
Finally, we can add an extension method on `AIAgent` that can add the feature to the run options and check the feature for the structured output result and add the deserialized result to the response.
|Ability to modify registered options when progressing down the stack|✅ Supported|✅ Supported|❌ Not-Supported (IServiceProvider is read-only)|
|Already available in MEAI stack|❌ No|✅ Yes|❌ No|
|Ambiguity with existing AdditionalProperties|❌ Yes|✅ No|❌ Yes|
## IServiceProvider
Service Collections and Service Providers provide a very popular way to register and retrieve services by type and could be used as a way to pass features to agents and chat clients.
However, since IServiceProvider is read-only, it is not possible to modify the registered services when progressing down the execution stack.
E.g. an agent decorator cannot add additional services to the IServiceProvider passed to it when calling into the inner agent.
IServiceProvider also does not expose a way to list all services contained in it, making it difficult to copy services from one provider to another.
This lack of mutability makes IServiceProvider unsuitable for our use case, since we will not be able to use it to build sample scenario 2.
## AdditionalProperties dictionary
The AdditionalProperties dictionary is already available on various options classes in the agent framework as well as in the MEAI stack and
allows storing arbitrary key/value pairs, where the key is a string and the value is an object.
While FeatureCollection uses Type as a key, AdditionalProperties uses string keys.
This means that users need to agree on string keys to use for specific features, however it is also possible to use Type.FullName as a key by convention
to avoid key collisions, which is an easy convention to follow.
Since the value of AdditionalProperties is of type object, users need to cast the value to the expected type when retrieving it, which is also
a drawback, but when using the convention of using Type.FullName as a key, there is at least a clear expectation of what type to cast to.
If we choose the feature collection option, we need to decide on the design of the feature collection itself.
### Feature Collections extension points
We need to decide the set of actions that feature collections would be supported for. Here is the suggested list of actions:
**MAAI.AIAgent:**
1. GetNewThread
1. E.g. this would allow passing an already existing storage id for the thread to use, or an initialized custom chat message store to use.
1. DeserializeThread
1. E.g. this would allow passing an already existing storage id for the thread to use, or an initialized custom chat message store to use.
1. Run / RunStreaming
1. E.g. this would allow passing an override chat message store just for that run, or a desired schema for a structured output middleware component.
**MEAI.ChatClient:**
1. GetResponse / GetStreamingResponse
### Reconciling with existing AdditionalProperties
If we decide to add feature collections, separately from the existing AdditionalProperties dictionaries, we need to consider how to explain to users when to use each one.
One possible approach though is to have the one use the other under the hood.
AdditionalProperties could be stored as a feature in the feature collection.
Users would be able to retrieve additional properties from the feature collection, in addition to retrieving it via a dedicated AdditionalProperties property.
E.g. `features.Get<AdditionalPropertiesDictionary>()`
One challenge with this approach is that when setting a value in the AdditionalProperties dictionary, the feature collection would need to be created first if it does not already exist.
Since IAgentFeatureCollection is an interface, AgentRunOptions would need to have a concrete implementation of the interface to create, meaning that the user cannot decide.
It also means that if the user doesn't realise that AdditionalProperties is implemented using feature collections, they may set a value on AdditionalProperties, and then later overwrite the entire feature collection, losing the AdditionalProperties feature.
Options to avoid these issues:
1. Make `Features` readonly.
1. This would prevent the user from overwriting the feature collection after setting AdditionalProperties.
1. Since the user cannot set their own implementation of IAgentFeatureCollection, having an interface for it may not be necessary.
### Feature Collection Implementation
We have two options for implementing feature collections:
1. Create our own [IAgentFeatureCollection interface](https://github.com/microsoft/agent-framework/pull/2354/files#diff-9c42f3e60d70a791af9841d9214e038c6de3eebfc10e3997cb4cdffeb2f1246d) and [implementation](https://github.com/microsoft/agent-framework/pull/2354/files#diff-a435cc738baec500b8799f7f58c1538e3bb06c772a208afc2615ff90ada3f4ca).
2. Reuse the asp.net [IFeatureCollection interface](https://github.com/dotnet/aspnetcore/blob/main/src/Extensions/Features/src/IFeatureCollection.cs) and [implementation](https://github.com/dotnet/aspnetcore/blob/main/src/Extensions/Features/src/FeatureCollection.cs).
#### Roll our own
Advantages:
Creating our own IAgentFeatureCollection interface and implementation has the advantage of being more clearly associated with the agent framework and allows us to
improve on some of the design decisions made in asp.net core's IFeatureCollection.
Drawbacks:
It would mean a different implementation to maintain and test.
#### Reuse asp.net IFeatureCollection
Advantages:
Reusing the asp.net IFeatureCollection has the advantage of being able to reuse the well-established and tested implementation from asp.net
core. Users who are using agents in an asp.net core application may be able to pass feature collections from asp.net core to the agent framework directly.
Drawbacks:
While the package name is `Microsoft.Extensions.Features`, the namespaces of the types are `Microsoft.AspNetCore.Http.Features`, which may create confusion for users of agent framework who are not building web applications or services.
Users may rightly ask: Why do I need to use a class from asp.net core when I'm not building a web application / service?
The current design has some design issues that would be good to avoid. E.g. it does not distinguish between a feature being "not set" and "null". Get returns both as null and there is no tryget method.
Since the [default implementation](https://github.com/dotnet/aspnetcore/blob/main/src/Extensions/Features/src/FeatureCollection.cs) also supports value types, it throws for null values of value types.
A TryGet method would be more appropriate.
## Feature Layering
One possible scenario when adding support for feature collections is to allow layering of features by scope.
The following levels of scope could be supported:
1. Application - Application wide features that apply to all agents / chat clients
2. Artifact (Agent / ChatClient) - Features that apply to all runs of a specific agent or chat client instance
3. Action (GetNewThread / Run / GetResponse) - Feature that apply to a single action only
When retrieving a feature from the collection, the search would start from the most specific scope (Action) and progress to the least specific scope (Application), returning the first matching feature found.
Introducing layering adds some challenges:
- There may be multiple feature collections at the same scope level, e.g. an Agent that uses a ChatClient where both have their own feature collections.
- Do we layer the agent feature collection over the chat client feature collection (Application -> ChatClient -> Agent -> Run), or only use the agent feature collection in the agent (Application -> Agent -> Run), and the chat client feature collection in the chat client (Application -> ChatClient -> Run)?
- The appropriate base feature collection may change when progressing down the stack, e.g. when an Agent calls a ChatClient, the action feature collection stays the same, but the artifact feature collection changes.
- Who creates the feature collection hierarchy?
- Since the hierarchy changes as it progresses down the execution stack, and the caller can only pass in the action level feature collection, the callee needs to combine it with its own artifact level feature collection and the application level feature collection. Each action will need to build the appropriate feature collection hierarchy, at the start of its execution.
- For Artifact level features, it seems odd to pass them in as a bag of untyped features, when we are constructing a known artifact type and therefore can have typed settings.
- E.g. today we have a strongly typed setting on ChatClientAgentOptions to configure a ChatMessageStore for the agent.
- To avoid global statics for application level features, the user would need to pass in the application level feature collection to each artifact that they create.
- This would be very odd if the user also already has to strongly typed settings for each feature that they want to set at the artifact level.
### Layering Options
1. No layering - only a single feature collection is supported per action (the caller can still create a layered collection if desired, but the callee does not do any layering automatically).
1. Fallback is to any features configured on the artifact via strongly typed settings.
1. Full layering - support layering at all levels (Application -> Artifact -> Action).
1. Only apply applicable artifact level features when calling into that artifact.
1. Apply upstream artifact features when calling into downstream artifacts, e.g. Feature hierarchy in ChatClientAgent would be `Application -> Agent -> Run` and in ChatClient would be `Application -> ChatClient -> Agent -> Run` or `Application -> Agent -> ChatClient -> Run`
1. The user needs to provide the application level feature collection to each artifact that they create and artifact features are passed via strongly typed settings.
### Accessing application level features Options
We need to consider how application level features would be accessed if supported.
1. The user provides the application level feature collection to each artifact that the user constructs
1. Passing the application level feature collection to each artifact is tedious for the user.
1. There is a static application level feature collection that can be accessed globally.
1. Statics create issues with testing and isolation.
## Decisions
- Feature Collections Container: Use AdditionalProperties
- Feature Layering: No layering - only a single collection/dictionary is supported per action. Application layers can be added later if needed.
During an agent run, various components involved in the execution (middleware, filters, tools, nested agents, etc.) may need access to contextual information about the current run, such as:
1. The agent that is executing the run
2. The session associated with the run
3. The request messages passed to the agent
4. The run options controlling the agent's behavior
Additionally, some components may need to modify this context during execution, for example:
- Replacing the session with a different one
- Modifying the request messages before they reach the agent core
- Updating or replacing the run options entirely
Currently, there is no standardized way to access or modify this context from arbitrary code that executes during an agent run, especially from deeply nested call stacks where the context is not explicitly passed.
## Sample Scenario
When using an Agent as an AIFunction developers may want to pass context from the parent agent run to the child agent run. For example, the developer may want to copy chat history to the child agent, or share the same session across both agents.
To enable these scenarios, we need a way to access the parent agent run context, including e.g. the parent agent itself, the parent agent session, and the parent run options from function tool calls.
- Components executing during an agent run need access to run context without explicit parameter passing through every layer
- Context should flow naturally across async calls without manual propagation
- The design should allow modification of context properties by agent decorators (e.g., replacing options or session)
- Solution should be consistent with patterns used in similar frameworks (e.g., `FunctionInvokingChatClient.CurrentContext``HttpContext.Current`, `Activity.Current`)
## Considered Options
- **Option 1**: Pass context explicitly through all method signatures
- **Option 2**: Use `AsyncLocal<T>` to provide ambient context accessible anywhere during the run
- **Option 3**: Use a combination of explicit parameters for `RunCoreAsync` and `AsyncLocal<T>` for ambient access
## Decision Outcome
Chosen option: **Option 3** - Combination of explicit parameters and AsyncLocal ambient access.
This approach provides the best of both worlds:
1.**Explicit parameters are passed to `RunCoreAsync`**: The core agent implementation receives the parameters explicitly, making it clear what data is available and enabling easy unit testing. Any modification of these in a decorator will require calling `RunAsync` on the inner agent with the updated parameters, which would result in the inner agent creating a new `AgentRunContext` instance.
```csharp
public async Task<AgentResponse> RunAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
AgentRunOptions? options = null,
CancellationToken cancellationToken = default)
{
CurrentRunContext = new(this, session, messages as IReadOnlyCollection<ChatMessage> ?? messages.ToList(), options);
2. **`AsyncLocal<AgentRunContext?>` for ambient access**: The context is stored in an `AsyncLocal<T>` field, making it accessible from any code executing during the agent run via a static property.
The main scenario for this is to allow deeply nested components (e.g., tools, chat client middleware) to access the context without needing to pass it through every method signature. These are external components that cannot easily be modified to accept additional parameters. For internal components, we prefer passing any parameters explicitly.
```csharp
public static AgentRunContext? CurrentRunContext
{
get => s_currentContext.Value;
protected set => s_currentContext.Value = value;
}
```
### AgentRunContext Design
The `AgentRunContext` class encapsulates all run-related state:
```csharp
public class AgentRunContext
{
public AgentRunContext(
AIAgent agent,
AgentSession? session,
IReadOnlyCollection<ChatMessage> requestMessages,
AgentRunOptions? agentRunOptions)
public AIAgent Agent { get; }
public AgentSession? Session { get; }
public IReadOnlyCollection<ChatMessage> RequestMessages { get; }
public AgentRunOptions? RunOptions { get; }
}
```
Key design decisions:
- **All properties are read-only**: While some of the sub-properties on the provided properties (like `AgentRunOptions.AllowBackgroundResponses`) may be mutable, the `AgentRunContext` itself is immutable and we want to discourage anyone modifying the values in the context. Modifying the context is unlikely to result in the desired behavior, as the values will typically already have been used by the time any custom code accesses them.
### Benefits
1. **Ambient Access**: Any code executing during the run can access context via `AIAgent.CurrentRunContext` without needing explicit parameters
2. **Async Flow**: `AsyncLocal<T>` automatically flows across async/await boundaries
3. **Modifiability**: Components can modify or replace session, messages, or options as needed
4. **Testability**: The explicit parameter to `RunCoreAsync` makes unit testing straightforward
Structured output is a valuable aspect of any agent system, since it forces an agent to produce output in a required format that may include required fields.
This allows easily turning unstructured data into structured data using a general-purpose language model.
## Context and Problem Statement
Structured output is currently supported only by `ChatClientAgent` and can be configured in two ways:
**Approach 1: ResponseFormat + Deserialize**
Specify the SO type schema via the `ChatClientAgent{Run}Options.ChatOptions.ResponseFormat` property at agent creation or invocation time, then use `JsonSerializer.Deserialize<T>` to extract the structured data from the response text.
Note: `RunAsync<T>` is an instance method of `ChatClientAgent` and not part of the `AIAgent` base class since not all agents support structured output.
Approach 1 is perceived as cumbersome by the community, as it requires additional effort when using primitive or collection types - the SO schema may need to be wrapped in an artificial JSON object. Otherwise, the caller will encounter an error like _Invalid schema for response_format 'Movie': schema must be a JSON Schema of 'type: "object"', got 'type: "array"'_.
This occurs because OpenAI and compatible APIs require a JSON object as the root schema.
Approach 1 is also necessary in scenarios where (a) agents can only be configured with SO at creation time (such as with `AIProjectClient`), (b) the SO type is not known at compile time, or (c) the JSON schema is represented as text (for declarative agents) or as a `JsonElement`.
Approach 2 is more convenient and works seamlessly with primitives and collections. However, it requires the SO type to be known at compile time, making it less flexible.
Additionally, since the `RunAsync<T>` methods are instance methods of `ChatClientAgent` and are not part of the `AIAgent` base class, applying decorators like `OpenTelemetryAgent` on top of `ChatClientAgent` prevents users from accessing `RunAsync<T>`, meaning structured output is not available with decorated agents.
Given the different scenarios above in which structured output can be used, there is no one-size-fits-all solution. Each approach has its own advantages and limitations,
and the two can complement each other to provide a comprehensive structured output experience across various use cases.
## Approaches Overview
1. SO usage via `ResponseFormat` property
2. SO usage via `RunAsync<T>` generic method
## 1. SO usage via `ResponseFormat` property
This approach should be used in the following scenarios:
- 1.1 SO result as text is sufficient as is, and deserialization is not required
- 1.2 SO for inter-agent collaboration
- 1.3 SO can only be configured at agent creation time (such as with `AIProjectClient`)
- 1.4 SO type is not known at compile time and represented by System.Type
- 1.5 SO is represented by JSON schema and there's no corresponding .NET type either at compile time or at runtime
- 1.6 SO in streaming scenarios, where the SO response is produced in parts
**Note: Primitives and arrays are not supported by this approach.**
When a caller provides a schema via `ResponseFormat`, they are explicitly telling the framework what schema to use. The framework passes that schema through as-is and
is not responsible for transforming it. Because the framework does not own the schema, it cannot wrap primitives or arrays into a JSON object to satisfy API requirements,
nor can it unwrap the response afterward - the caller controls the schema and is responsible for ensuring it is compatible with the underlying API.
This is in contrast to the `RunAsync<T>` approach (section 2), where the caller provides a type `T` and says "make it work." In that case, the caller does not
dictate the schema - the framework infers the schema from `T`, owns the end-to-end pipeline (schema generation, API invocation, and deserialization), and can
therefore wrap and unwrap primitives and arrays transparently.
Additionally, in streaming scenarios (1.6), the framework cannot reliably unwrap a response it did not wrap, since it has no way of knowing whether the caller wrapped the schema.Wrapping and unwrapping can only be done safely when the framework owns the entire lifecycle - from schema creation through deserialization — which is only the case with `RunAsync<T>`.
If a caller needs to work with primitives or arrays via the `ResponseFormat` approach, they can easily create a wrapper type around them:
```csharp
public class MovieListWrapper
{
public List<string> Movies { get; set; }
}
```
### 1.1 SO result as text is sufficient as is, and deserialization is not required
In this scenario, the caller only needs the raw JSON text returned by the model and does not need to deserialize it into a .NET type.
The SO schema is specified via `ResponseFormat` at agent creation or invocation time, and the response text is consumed directly from the `AgentResponse`.
In this scenario, the SO schema can only be configured at agent creation time (such as with `AIProjectClient`) and cannot be changed on a per-run basis.
The caller specifies the `ResponseFormat` when creating the agent, and all subsequent invocations use the same schema.
```csharp
AIProjectClient client = ...;
AIAgent agent = await client.CreateAIAgentAsync(model: "<model>", new ChatClientAgentOptions()
### 1.4 SO type not known at compile time and represented by System.Type
In this scenario, the SO type is not known at compile time and is provided as a `System.Type` at runtime. This is useful for dynamic scenarios where the schema is determined programmatically,
such as when building tooling or frameworks that work with user-defined types.
```csharp
Type soType = GetStructuredOutputTypeFromConfiguration(); // e.g., typeof(PersonInfo)
### 1.5 SO represented by JSON schema with no corresponding .NET type
In this scenario, the SO schema is represented as raw JSON schema text or a `JsonElement`, and there is no corresponding .NET type available at compile time or runtime.
This is typical for declarative agents or scenarios where schemas are loaded from external configuration.
```csharp
// JSON schema provided as a string, e.g., loaded from a configuration file
// Consume the SO result as text since there's no .NET type to deserialize into
Console.WriteLine(response.Text);
```
### 1.6 SO in streaming scenarios
In this scenario, the SO response is produced incrementally in parts via streaming. The caller specifies the `ResponseFormat` and consumes the response chunks as they arrive.
Deserialization is performed after all chunks have been received.
IAsyncEnumerable<AgentResponseUpdate> updates = agent.RunStreamingAsync("Please provide information about John Smith, who is a 35-year-old software engineer.");
This approach provides a convenient way to work with structured output on a per-run basis when the target type is known at compile time and a typed instance of the result
is required.
### Decision Drivers
1. Support arrays and primitives as SO types
2. Support complex types as SO types
3. Work with `AIAgent` decorators (e.g., `OpenTelemetryAgent`)
4. Enable SO for all AI agents, regardless of whether they natively support it
### Considered Options
1. `RunAsync<T>` as an instance method of `AIAgent` class delegating to virtual `RunCoreAsync<T>`
2. `RunAsync<T>` as an extension method using feature collection
3. `RunAsync<T>` as a method of the new `ITypedAIAgent` interface
4. `RunAsync<T>` as an instance method of `AIAgent` class working via the new `AgentRunOptions.ResponseFormat` property
### 1. `RunAsync<T>` as an instance method of `AIAgent` class delegating to virtual `RunCoreAsync<T>`
This option adds the `RunAsync<T>` method directly to the `AIAgent` base class.
throw new NotSupportedException($"The agent of type '{this.GetType().FullName}' does not support typed responses.");
}
}
```
Agents with native SO support override the `RunCoreAsync<T>` method to provide their implementation. If not overridden, the method throws a `NotSupportedException`.
Users will call the generic `RunAsync<T>` method directly on the agent:
```csharp
AIAgent agent = chatClient.AsAIAgent(name: "HelpfulAssistant", instructions: "You are a helpful assistant.");
AgentResponse<PersonInfo> response = await agent.RunAsync<PersonInfo>("Please provide information about John Smith, who is a 35-year-old software engineer.");
```
Decision drivers satisfied:
1. Support arrays and primitives as SO types
2. Support complex types as SO types
3. Work with `AIAgent` decorators (e.g., `OpenTelemetryAgent`)
4. Enable SO for all AI agents, regardless of whether they natively support it
Pros:
- The `AIAgent.RunAsync<T>` method is easily discoverable.
- Both the SO decorator and `ChatClientAgent` have compile-time access to the type `T`, allowing them to use the native `IChatClient.GetResponseAsync<T>` API, which handles primitives and collections seamlessly.
Cons:
- Agents without native SO support will still expose `RunAsync<T>`, which may be misleading.
- `ChatClientAgent` exposing `RunAsync<T>` may be misleading when the underlying chat client does not support SO.
- All `AIAgent` decorators must override `RunCoreAsync<T>` to properly handle `RunAsync<T>` calls.
### 2. `RunAsync<T>` as an extension method using feature collection
This option uses the Agent Framework feature collection (implemented via `AgentRunOptions.AdditionalProperties`) to pass a `StructuredOutputFeature` to agents, signaling that SO is requested.
Agents with native SO support check for this feature. If present, they read the target type, build the schema, invoke the underlying API, and store the response back in the feature.
```csharp
public class StructuredOutputFeature
{
public StructuredOutputFeature(Type outputType)
{
this.OutputType = outputType;
}
[JsonIgnore]
public Type OutputType { get; set; }
public JsonSerializerOptions? SerializerOptions { get; set; }
public AgentResponse? Response { get; set; }
}
```
The `RunAsync<T>` extension method for `AIAgent` adds this feature to the collection.
```csharp
public static async Task<AgentResponse<T>> RunAsync<T>(
((options ??= new AgentRunOptions()).AdditionalProperties ??= []).Add(typeof(StructuredOutputFeature).FullName!, structuredOutputFeature);
var response = await agent.RunAsync(messages, session, options, cancellationToken).ConfigureAwait(false);
if (structuredOutputFeature.Response is not null)
{
return new StructuredOutputResponse<T>(structuredOutputFeature.Response, response, serializerOptions);
}
throw new InvalidOperationException("No structured output response was generated by the agent.");
}
```
Users will call the `RunAsync<T>` extension method directly on the agent:
```csharp
AIAgent agent = chatClient.AsAIAgent(name: "HelpfulAssistant", instructions: "You are a helpful assistant.");
AgentResponse<PersonInfo> response = await agent.RunAsync<PersonInfo>("Please provide information about John Smith, who is a 35-year-old software engineer.");
```
Decision drivers satisfied:
1. Support arrays and primitives as SO types
2. Support complex types as SO types
3. Work with `AIAgent` decorators (e.g., `OpenTelemetryAgent`)
4. Enable SO for all AI agents, regardless of whether they natively support it
Pros:
- The `RunAsync<T>` extension method is easily discoverable.
- The `AIAgent` public API surface remains unchanged.
- No changes required to `AIAgent` decorators.
Cons:
- Agents without native SO support will still expose `RunAsync<T>`, which may be misleading.
- `ChatClientAgent` exposing `RunAsync<T>` may be misleading when the underlying chat client does not support SO.
### 3. `RunAsync<T>` as a method of the new `ITypedAIAgent` interface
This option defines a new `ITypedAIAgent` interface that agents with SO support implement. Agents without SO support do not implement it, allowing users to check for SO capability via interface detection.
The interface:
```csharp
public interface ITypedAIAgent
{
Task<AgentResponse<T>> RunAsync<T>(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
JsonSerializerOptions? serializerOptions = null,
AgentRunOptions? options = null,
CancellationToken cancellationToken = default);
...
}
```
Agents with SO support implement this interface:
```csharp
public sealed partial class ChatClientAgent : AIAgent, ITypedAIAgent
{
public async Task<AgentResponse<T>> RunAsync<T>(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
JsonSerializerOptions? serializerOptions = null,
AgentRunOptions? options = null,
CancellationToken cancellationToken = default)
{
...
}
}
```
However, `ChatClientAgent` presents a challenge: it can work with chat clients that either support or do not support SO. Implementing the interface does not guarantee
the underlying chat client supports SO, which undermines the core idea of using interface detection to determine SO capability.
Additionally, to allow users to access interface methods on decorated agents, all decorators must implement `ITypedAIAgent`. This makes it difficult for users to
determine whether the underlying agent actually supports SO, further weakening the purpose of this approach.
Furthermore, users would have to probe the agent type to check if it implements the `ITypedAIAgent` interface and cast it accordingly to access the `RunAsync<T>` methods.
This adds friction to the user experience. A `RunAsync<T>` extension method for `AIAgent` could be provided to alleviate that.
Given these drawbacks, this option is more complex to implement than the others without providing clear benefits.
Decision drivers satisfied:
1. Support arrays and primitives as SO types
2. Support complex types as SO types
3. Work with `AIAgent` decorators (e.g., `OpenTelemetryAgent`)
4. Enable SO for all AI agents, regardless of whether they natively support it
Pros:
- Both the SO decorator and `ChatClientAgent` have compile-time access to the type `T`, allowing them to use the native `IChatClient.GetResponseAsync<T>` API, which handles primitives and collections seamlessly.
Cons:
- `ChatClientAgent` implementing `ITypedAIAgent` may be misleading when the underlying chat client does not support SO.
- All `AIAgent` decorators must implement `ITypedAIAgent` to handle `RunAsync<T>` calls.
- Decorators implementing the interface may mislead users into thinking the underlying agent natively supports SO.
- Agents must implement all members of `ITypedAIAgent`, not just a core method.
- Users must check the agent type and cast to `ITypedAIAgent` to access `RunAsync<T>`.
### 4. `RunAsync<T>` as an instance method of `AIAgent` class working via the new `AgentRunOptions.ResponseFormat` property
This option adds a `ResponseFormat` property of type `ChatResponseFormat` to `AgentRunOptions`. Agents that support SO check for the presence of
this property in the options passed to `RunAsync` to determine whether structured output is requested. If present, they use the schema from `ResponseFormat`
to invoke the underlying API and obtain the SO response.
```csharp
public class AgentRunOptions
{
public ChatResponseFormat? ResponseFormat { get; set; }
}
```
Additionally, a generic `RunAsync<T>` method is added to `AIAgent` that initializes the `ResponseFormat` based on the type `T` and delegates to the non-generic `RunAsync`.
return new AgentResponse<T>(response, serializerOptions);
}
}
```
Users call the generic `RunAsync<T>` method directly on the agent:
```csharp
AIAgent agent = chatClient.AsAIAgent(name: "HelpfulAssistant", instructions: "You are a helpful assistant.");
AgentResponse<PersonInfo> response = await agent.RunAsync<PersonInfo>("Please provide information about John Smith, who is a 35-year-old software engineer.");
```
Decision drivers satisfied:
1. Support arrays and primitives as SO types
2. Support complex types as SO types
3. Work with `AIAgent` decorators (e.g., `OpenTelemetryAgent`)
4. Enable SO for all AI agents, regardless of whether they natively support it
Pros:
- The `AIAgent.RunAsync<T>` method is easily discoverable.
- No changes required to `AIAgent` decorators
Cons:
- Agents without native SO support will still expose `RunAsync<T>`, which may be misleading.
- `ChatClientAgent` exposing `RunAsync<T>` may be misleading when the underlying chat client does not support SO.
| Decorator changes | ❌ All decorators must override `RunCoreAsync<T>` | ✅ No changes required | ❌ All decorators must implement `ITypedAIAgent` | ✅ No changes required to decorators |
| Primitives/collections handling | ✅ Native support via `IChatClient.GetResponseAsync<T>` | ❌ Must wrap/unwrap internally | ✅ Native support via `IChatClient.GetResponseAsync<T>` | ❌ Must wrap/unwrap internally |
| Misleading API exposure | ❌ Agents without SO still expose `RunAsync<T>` | ❌ Agents without SO still expose `RunAsync<T>` | ❌ Interface on `ChatClientAgent` may be misleading | ❌ Agents without SO still expose `RunAsync<T>` |
| Implementation burden | ❌ Decorators must override method | ❌ Must handle schema wrapping | ❌ Agents must implement all interface members | ✅ Delegates to existing `RunAsync` via `ResponseFormat` |
## Cross-Cutting Aspects
1. **The `useJsonSchemaResponseFormat` parameter**: The `ChatClientAgent.RunAsync<T>` method has this parameter to enable structured output on LLMs that do not natively support it.
It works by adding a user message like "Respond with a JSON value conforming to the following schema:" along with the JSON schema. However, this approach has not been reliable historically. The recommendation is not to carry this parameter forward, regardless of which option is chosen.
2. **Primitives and array types handling**: There are a few options for how primitive and array types can be handled in the Agent Framework:
1. **Never wrap**, regardless of whether the schema is provided via `ResponseFormat` or `RunAsync<T>`.
- Pro: No changes needed; user has full control.
- Pro: No issues with unwrapping in streaming scenarios.
- Con: User must wrap manually.
2. **Always wrap**, regardless of whether the schema is provided via `ResponseFormat` or `RunAsync<T>`.
- Pro: Consistent wrapping behavior; no manual wrapping needed.
- Con: Inconsistent unwrapping behavior; it may be unexpected to have SO result wrapped when schema is provided via `ResponseFormat`.
- Con: Impossible to know if SO result is wrapped to unwrap it in streaming scenarios.
3. **Wrap only for `RunAsync<T>`** and do not wrap the schema provided via `ResponseFormat`.
- Pro: No unexpectedly wrapped result when schema is provided via `ResponseFormat`.
- Pro: Solves the problem with unwrapping in streaming scenarios.
4. **User decides** whether to wrap schema provided via `ResponseFormat` using a new `wrapPrimitivesAndArrays` property of `ChatResponseFormatJson`. For SO provided via `RunAsync<T>`, AF always wraps.
- Pro: No manual wrapping needed; just flip a switch.
- Pro: Solves the problem with unwrapping in streaming scenarios.
- Con: Extends the public API surface.
3. **Structured output for agents without native SO support**: Some AI agents in AF do not support structured output natively. This is either because it is not part of the protocol (e.g., A2A agent) or because the agents use LLMs without structured output capabilities.
To address this gap, AF can provide the `StructuredOutputAgent` decorator. This decorator wraps any `AIAgent` and adds structured output support by obtaining the text response from the decorated agent and delegating it to a configured chat client for JSON transformation.
```csharp
public class StructuredOutputAgent : DelegatingAIAgent
{
private readonly IChatClient _chatClient;
public StructuredOutputAgent(AIAgent innerAgent, IChatClient chatClient)
return new StructuredOutputAgentResponse(soResponse, textResponse);
}
}
```
The decorator preserves the original response from the decorated agent and surfaces it via the `OriginalResponse` property on the returned `StructuredOutputAgentResponse`.
This allows users to access both the original unstructured response and the new structured response when using this decorator.
```csharp
public class StructuredOutputAgentResponse : AgentResponse
AIAgent baseAgent = meaiChatClient.AsAIAgent(name: "HelpfulAssistant", instructions: "You are a helpful assistant.");
// Register the StructuredOutputAgent decorator during agent building
AIAgent agent = baseAgent
.AsBuilder()
.UseStructuredOutput(meaiChatClient)
.Build();
AgentResponse<PersonInfo> response = await agent.RunAsync<PersonInfo>("Please provide information about John Smith, who is a 35-year-old software engineer.");
It was decided to keep both approaches for structured output - via `ResponseFormat` and via `RunAsync<T>` since they serve different scenarios and use cases.
For the `RunAsync<T>` approach, option 4 was selected, which adds a generic `RunAsync<T>` method to `AIAgent` that works via the new `AgentRunOptions.ResponseFormat` property.
This was chosen for its simplicity and because no changes are required to existing `AIAgent` decorators.
For cross-cutting aspects, the `useJsonSchemaResponseFormat` parameter will not be carried forward due to reliability issues.
For handling primitives and array types, option 3 was selected: wrap only for `RunAsync<T>` and do not wrap the schema provided via `ResponseFormat`.
This avoids the issues described in the Approach 1 section note.
Finally, it was decided not to include the `StructuredOutputAgent` decorator in the framework, since the reliability of producing structured output via an additional
LLM call may not be sufficient for all scenarios. Instead, this pattern is provided as a sample to demonstrate how structured output can be achieved for agents without native support,
giving users a reference implementation they can adapt to their own requirements.
# AdditionalProperties for AIAgent and AgentSession
## Context and Problem Statement
The `AIAgent` base class currently exposes `Id`, `Name`, and `Description` as its core metadata properties, and `AgentSession` exposes only a `StateBag` property.
Neither type has a mechanism for attaching arbitrary metadata, such as protocol-specific descriptors (e.g., A2A agent cards), hosting attributes, session-level tags, or custom user-defined metadata for discovery and routing.
Other types in the framework already carry `AdditionalProperties` — notably `AgentRunOptions`, `AgentResponse`, and `AgentResponseUpdate` — all using `AdditionalPropertiesDictionary` from `Microsoft.Extensions.AI`.
Adding a similar property to `AIAgent` and `AgentSession` would give both types a consistent, extensible metadata surface.
- **Consistency**: Other core types (`AgentRunOptions`, `AgentResponse`, `AgentResponseUpdate`) already expose `AdditionalProperties`. `AIAgent` and `AgentSession` are the major abstractions that lack this.
- **Extensibility**: Hosting libraries, protocol adapters (A2A, AG-UI), and discovery mechanisms need a place to attach agent-level and session-level metadata without subclassing.
- **Simplicity**: The solution should be easy to understand and use; avoid over-engineering.
- **Minimal breaking change**: The addition should not require changes to existing agent implementations.
- **Clear semantics**: Users should understand what `AdditionalProperties` on an agent or session means and how it differs from `AdditionalProperties` on `AgentRunOptions`.
## Considered Options
### Surface Area
- **Option A**: Public get-only property, auto-initialized (`AdditionalPropertiesDictionary AdditionalProperties { get; } = new()`) on both `AIAgent` and `AgentSession`
- **Option B**: Public get/set nullable property (`AdditionalPropertiesDictionary? AdditionalProperties { get; set; }`) on both `AIAgent` and `AgentSession`
- **Option C**: Constructor-injected dictionary with public get-only accessor on both `AIAgent` and `AgentSession`
- **Option D**: External container/wrapper object — metadata lives outside `AIAgent` and `AgentSession`; no changes to the base classes
### Semantics
- **Option 1**: Metadata only — describes the agent or session; not propagated when calling `IChatClient`
- **Option 2**: Passed down the stack — merged into `ChatOptions.AdditionalProperties` during `ChatClientAgent` runs
## Decision Outcome
The chosen option is **Option D + Option 1**: an external container/wrapper object, used purely as metadata.
### Consequences
- Good, because `AIAgent` and `AgentSession` remain unchanged, avoiding any increase to the core framework surface area while still enabling extensible metadata.
- Good, because an external wrapper (owned by hosting/protocol libraries or user code, not the `AIAgent` / `AgentSession` base classes) can internally use `AdditionalPropertiesDictionary` to stay consistent with existing patterns on `AgentRunOptions`, `AgentResponse`, and `AgentResponseUpdate`.
- Good, because metadata-only semantics keep a clean separation from per-run extensibility (`AgentRunOptions.AdditionalProperties`) and avoid unexpected side effects during agent execution.
- Good, because no additional allocation occurs on `AIAgent` or `AgentSession` when no metadata is needed; external wrappers can be created only when metadata is required.
- Bad, because callers and libraries must manage and pass around both the agent/session instance and its associated metadata wrapper, keeping them correctly associated.
- Bad, because different hosting or protocol layers may define their own wrapper types, which can fragment the ecosystem unless conventions are agreed upon.
## Pros and Cons of the Options
### Option A — Public get-only property, auto-initialized
The property is always non-null and ready to use. Users add metadata after construction.
```csharp
public abstract partial class AIAgent
{
public AdditionalPropertiesDictionary AdditionalProperties { get; } = new();
}
public abstract partial class AgentSession
{
public AdditionalPropertiesDictionary AdditionalProperties { get; } = new();
- Good, because it is consistent with the existing `AdditionalProperties` pattern on `AgentRunOptions` and `AgentResponse`.
- Good, because it avoids allocation when no metadata is needed.
- Bad, because every consumer must null-check before reading or writing.
- Bad, because the entire dictionary can be replaced, risking accidental loss of metadata set by other components (e.g., a hosting library sets metadata, then user code replaces the dictionary).
### Option C — Constructor-injected with public get
The dictionary is provided at construction time and exposed as get-only.
```csharp
public abstract partial class AIAgent
{
public AdditionalPropertiesDictionary AdditionalProperties { get; }
- Good, because an agent's metadata can be established before any code runs against it.
- Bad, because `AdditionalPropertiesDictionary` has no read-only variant, so the constructor-injection pattern gives a false sense of immutability — callers can still mutate the dictionary contents after construction.
- Bad, because it requires adding a constructor parameter to the abstract base classes, which is a source-breaking change for all existing `AIAgent` and `AgentSession` subclasses (even with a default value, it changes the constructor signature that derived classes chain to).
- Bad, because it is more complex with little practical benefit over Option A, since post-construction mutation is equally possible.
### Option D — External container/wrapper object
Rather than adding `AdditionalProperties` to `AIAgent` or `AgentSession`, users wrap the agent or session in a container object that carries both the instance and any associated metadata. No changes to the base classes are required.
```csharp
public class AgentWithMetadata
{
public required AIAgent Agent { get; init; }
public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }
}
public class SessionWithMetadata
{
public required AgentSession Session { get; init; }
public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }
- Good, because it requires no changes to `AIAgent` or `AgentSession`, avoiding any risk of breaking existing implementations.
- Good, because metadata is clearly external to the agent and session, eliminating any ambiguity about whether it might be passed down the execution stack.
- Good, because the container pattern gives the user full control over the metadata lifecycle and serialization.
- Bad, because it is not discoverable — users must know about the container convention; there is no built-in API surface guiding them.
### Option 1 — Metadata only
`AdditionalProperties` on `AIAgent` and `AgentSession` is descriptive metadata. It is **not** automatically propagated when the agent calls downstream services such as `IChatClient`.
- Good, because it keeps a clean separation of concerns: agent/session-level metadata vs. per-run options.
- Good, because it avoids unintended side effects — metadata added for discovery or hosting won't leak into LLM requests.
- Good, because per-run extensibility is already served by `AgentRunOptions.AdditionalProperties` (see [ADR 0014](0014-feature-collections.md)), so there is no gap.
- Neutral, because users who want to pass agent metadata to the chat client can still do so manually via `AgentRunOptions`.
### Option 2 — Passed down the stack
`AdditionalProperties` on `AIAgent` and `AgentSession` are automatically merged into `ChatOptions.AdditionalProperties` (or similar) when `ChatClientAgent` invokes the underlying `IChatClient`.
- Good, because it provides an automatic way to send agent-level configuration to the LLM provider.
- Bad, because it conflates metadata (describing the agent) with operational parameters (controlling LLM behavior), leading to potential confusion.
- Bad, because it risks leaking unrelated metadata into LLM calls (e.g., hosting tags, discovery URLs).
- Bad, because it would be `ChatClientAgent`-specific behavior on a base-class property, creating inconsistency for non-`ChatClientAgent` implementations.
- Bad, because it duplicates the purpose of `AgentRunOptions.AdditionalProperties`, which already serves as the per-run extensibility point for passing data down the stack.
## Serialization Considerations
`AIAgent` instances are not typically serialized, so `AdditionalProperties` on `AIAgent` does not raise serialization concerns.
`AgentSession` instances, however, are routinely serialized and deserialized — for example, to persist conversation state across application restarts. Adding `AdditionalProperties` to `AgentSession` introduces a serialization challenge: `AdditionalPropertiesDictionary` is a `Dictionary<string, object?>`, and `object?` values do not carry enough type information for the JSON deserializer to reconstruct the original CLR types.
### Default behavior — JsonElement round-tripping
By default, when an `AgentSession` with `AdditionalProperties` is serialized and later deserialized, any complex objects stored as values in the dictionary will be deserialized as `JsonElement` rather than their original types. This is the same behavior exhibited by `ChatMessage.AdditionalProperties` and other `AdditionalPropertiesDictionary` usages in `Microsoft.Extensions.AI`, and is the approach we will follow.
### Custom serialization via JsonSerializerOptions
`AIAgent.SerializeSessionAsync` and `AIAgent.DeserializeSessionAsync` already accept an optional `JsonSerializerOptions` parameter. Users who need strongly-typed round-tripping of `AdditionalProperties` values can supply custom options with appropriate converters or type info resolvers. This is non-trivial to implement but provides full control over deserialization behavior when needed.
## More Information
- [ADR 0014 — Feature Collections](0014-feature-collections.md) established that `AdditionalProperties` on `AgentRunOptions` serves as the per-run extensibility mechanism. The proposed agent-level and session-level properties serve a complementary, distinct purpose: static metadata describing the agent or session itself.
- `AdditionalPropertiesDictionary` is defined in `Microsoft.Extensions.AI` and is already a dependency of `Microsoft.Agents.AI.Abstractions`. No new package references are needed.
- Type-safe access is available via the existing `AdditionalPropertiesExtensions` helper methods (`Add<T>`, `TryGetValue<T>`, `Contains<T>`, `Remove<T>`), which use `typeof(T).FullName` as the dictionary key.
- Official docs (Microsoft Learn): <https://learn.microsoft.com/agent-framework/integrations/azure-functions>
## Document structure
| File | Purpose |
| --- | --- |
| `README.md` | Main technical overview: architecture, hosting models, orchestration patterns, and links to samples. |
| `durable-agents-ttl.md` | Deep-dive on session Time-To-Live (TTL) configuration and behavior. |
Add new sibling documents when a topic is too detailed for the README (e.g., a new feature like reliable streaming or MCP tool exposure). Keep the README focused on orientation and link out to siblings for depth.
## Writing guidelines
- **Audience**: Developers already familiar with the Microsoft Agent Framework who want to understand what durability adds and how to use it.
- **Host-agnostic first**: Durable agents work in console apps, Azure Functions, and any Durable Task–compatible host. Show host-agnostic patterns (plain orchestration functions, `IServiceCollection` registration) before Azure Functions–specific patterns. Avoid giving the impression that Azure Functions is the only hosting option.
- **Both languages**: Always include C# and Python examples side by side. Keep them equivalent in functionality.
- **Callout syntax**: Use GitHub-flavored callouts (`> [!NOTE]`, `> [!IMPORTANT]`, `> [!WARNING]`) rather than bold-text callouts (`> **Note:** ...`).
- **Line length**: Do not wrap long lines. Rely on text viewers / renderers for line wrapping.
- **Tables**: Use spaces around pipes in separator rows (`| --- |` not `|---|`).
- **Code snippets**: Keep them minimal and self-contained. Omit boilerplate (using statements, environment variable reads) unless the snippet is specifically about setup.
- **Cross-references**: Link to Microsoft Learn for conceptual background (Durable Entities, Durable Task Scheduler, Azure Functions). Link to sibling docs within this directory for feature deep-dives.
## Linting
Run markdownlint on all documents before committing, with line-length checks disabled:
Durable agents extend the standard Microsoft Agent Framework with **durable state management** powered by the Durable Task framework. An ordinary Agent Framework agent runs in-process: its conversation history lives in memory and is lost when the process ends. A durable agent persists conversation history and execution state in external storage so that sessions survive process restarts, failures, and scale-out events.
| Capability | Ordinary agent | Durable agent |
| --- | --- | --- |
| Conversation history | In-memory only | Durably persisted |
| Failure recovery | State lost on crash | Automatically resumed |
| Multi-instance scale-out | Not supported | Any worker can resume a session |
| Human-in-the-loop | Must keep process alive | Can wait days/weeks with zero compute |
| Hosting | Any process | Console app, Azure Functions, or any Durable Task–compatible host |
> [!NOTE]
> For a step-by-step tutorial and deployment guidance, see [Azure Functions (Durable)](https://learn.microsoft.com/agent-framework/integrations/azure-functions) on Microsoft Learn.
## How durable agents work
Durable agents are implemented on top of [Durable Entities](https://learn.microsoft.com/azure/azure-functions/durable/durable-functions-entities) (also called "virtual actors"). Each **agent session** maps to one entity instance whose state contains the full conversation history. When you send a message to a durable agent, the following happens:
1. The message is dispatched to the entity identified by an `AgentSessionId` (a composite of the agent name and a unique session key).
2. The entity loads its persisted `DurableAgentState`, which includes the complete conversation history.
3. The entity invokes the underlying `AIAgent` with the full conversation history, collects the response, and appends both the request and the response to the state.
4. The updated state is persisted back to durable storage automatically.
Because the entity framework serializes access to each entity instance, concurrent messages to the same session are processed one at a time, eliminating race conditions.
### Agent session identity
Every durable agent session is identified by an `AgentSessionId`, which has two components:
- **Name**– the registered name of the agent (case-insensitive).
- **Key**– a unique session key (case-sensitive), typically a GUID.
The session ID is mapped to an underlying Durable Task entity ID with a `dafx-` prefix (e.g., `dafx-joker`). This naming convention is consistent across both .NET and Python implementations.
## Architecture
### .NET
The .NET implementation consists of two NuGet packages:
| Package | Purpose |
| --- | --- |
| `Microsoft.Agents.AI.DurableTask` | Core durable agent types: `DurableAIAgent`, `AgentEntity`, `DurableAgentSession`, `AgentSessionId`, `DurableAgentsOptions`, and the state model. |
| `Microsoft.Agents.AI.Hosting.AzureFunctions` | Azure Functions hosting integration: auto-generated HTTP endpoints, MCP tool triggers, entity function triggers, and the `ConfigureDurableAgents` extension method on `FunctionsApplicationBuilder`. |
Key types:
- **`DurableAIAgent`** – A subclass of `AIAgent` used *inside orchestrations*. Obtained via `context.GetAgent("agentName")`, it routes `RunAsync` calls through the orchestration's entity APIs so that each call is checkpointed.
- **`DurableAIAgentProxy`** – A subclass of `AIAgent` used *outside orchestrations* (e.g., from HTTP triggers or console apps). It signals the entity via `DurableTaskClient` and polls for the response.
- **`AgentEntity`** – The `TaskEntity<DurableAgentState>` that hosts the real agent. It loads the registered `AIAgent` by name, wraps it in an `EntityAgentWrapper`, feeds it the full conversation history, and persists the result.
- **`DurableAgentSession`** – An `AgentSession` subclass that carries the `AgentSessionId`.
- **`DurableAgentsOptions`** – Builder for registering agents and configuring TTL.
### Python
The core Python implementation is in the `agent-framework-durabletask` package (`python/packages/durabletask`). Azure Functions hosting (including `AgentFunctionApp`) is in the separate `agent-framework-azurefunctions` package (`python/packages/azurefunctions`).
Key types:
- **`DurableAIAgent`** – A generic proxy (`DurableAIAgent[TaskT]`) implementing `SupportsAgentRun`. Returns a `TaskT` from `run()` — either an `AgentResponse` (client context) or a `DurableAgentTask` (orchestration context, must be `yield`ed).
- **`DurableAIAgentWorker`** – Wraps a `TaskHubGrpcWorker` and registers agents as durable entities via `add_agent()`.
- **`DurableAIAgentClient`** – Wraps a `TaskHubGrpcClient` for external callers. `get_agent()` returns a `DurableAIAgent[AgentResponse]`.
- **`DurableAIAgentOrchestrationContext`** – Wraps an `OrchestrationContext` for use inside orchestrations. `get_agent()` returns a `DurableAIAgent[DurableAgentTask]`.
- **`AgentEntity`** – Platform-agnostic agent execution logic that manages state, invokes the agent, handles streaming, and calls response callbacks.
## Hosting models
### Azure Functions
The recommended production hosting model. A single call to `ConfigureDurableAgents` (C#) or `AgentFunctionApp` (Python) automatically:
- Registers agent entities with the Durable Task worker.
- Generates HTTP endpoints at `/api/agents/{agentName}/run` for each registered agent.
- Supports `thread_id` query parameter / JSON field and the `x-ms-thread-id` response header for session continuity.
- Supports fire-and-forget via the `x-ms-wait-for-response: false` header (returns HTTP 202).
For self-hosted or non-serverless scenarios, register durable agents via `IServiceCollection.ConfigureDurableAgents` (.NET) or `DurableAIAgentWorker` (Python) with explicit Durable Task worker and client configuration.
**C# example:**
```csharp
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.ConfigureDurableAgents(
options => options.AddAIAgent(agent),
workerBuilder: b => b.UseDurableTaskScheduler(connectionString),
clientBuilder: b => b.UseDurableTaskScheduler(connectionString));
Durable agents can be composed into deterministic, checkpointed workflows using Durable Task orchestrations. The orchestration framework replays orchestrator code on failure, so completed agent calls are not re-executed.
### Patterns
| Pattern | Description |
| --- | --- |
| **Sequential (chaining)** | Call agents one after another, passing outputs forward. |
| **Parallel (fan-out/fan-in)** | Run multiple agents concurrently and aggregate results. |
| **Conditional** | Branch orchestration logic based on structured agent output. |
| **Human-in-the-loop** | Pause for external events (approvals, feedback) with optional timeouts. |
### Using agents in orchestrations
Inside an orchestration function, obtain a `DurableAIAgent` via the orchestration context. Each agent gets its own session (created with `CreateSessionAsync` / `create_session`), and you can call the same agent multiple times on the same session to maintain conversation context across sequential invocations.
# Get a durable agent reference — works in any host (standalone worker, Azure Functions, etc.)
writer = agent_ctx.get_agent("WriterAgent")
# Create a session to maintain conversation context across multiple calls
session = writer.create_session()
# First call: generate an initial draft
draft = yield writer.run(
messages="Write a concise inspirational sentence about learning.",
session=session,
)
# Second call: refine the draft — the agent sees the full conversation history
refined = yield writer.run(
messages=f"Improve this further while keeping it under 25 words: {draft.text}",
session=session,
)
return refined.text
```
> [!IMPORTANT]
> In .NET, `DurableAIAgent.RunAsync<T>` deliberately avoids `ConfigureAwait(false)` because the Durable Task Framework uses a custom synchronization context — all continuations must run on the orchestration thread.
## Streaming and response callbacks
Durable agents do not support true end-to-end streaming because entity operations are request/response. However, **reliable streaming** is supported via response callbacks:
- **`IAgentResponseHandler`** (.NET) or **`AgentResponseCallbackProtocol`** (Python) – Implement this interface to receive streaming updates as the underlying agent generates them (e.g., push tokens to a Redis Stream for client consumption).
- The entity still returns the complete `AgentResponse` after the stream is fully consumed.
- Clients can reconnect and resume reading from a cursor-based stream (e.g., Redis Streams) without losing messages.
See the **Reliable Streaming** samples for a complete implementation using Redis Streams.
## Session TTL (Time-To-Live)
Durable agent sessions support automatic cleanup via configurable TTL. See [Session TTL](durable-agents-ttl.md) for details on configuration, behavior, and best practices.
## Observability
When using the [Durable Task Scheduler](https://learn.microsoft.com/azure/azure-functions/durable/durable-task-scheduler/durable-task-scheduler) as the durable backend, you get built-in observability through its dashboard:
- **Conversation history**– View complete chat history for each agent session.
- **Orchestration visualization**– See multi-agent execution flows, including parallel branches and conditional logic.
The durable agents automatically maintain conversation history and state for each session. Without automatic cleanup, this state can accumulate indefinitely, consuming storage resources and increasing costs. The Time-To-Live (TTL) feature provides automatic cleanup of idle agent sessions, ensuring that sessions are automatically deleted after a period of inactivity.
## What is TTL?
Time-To-Live (TTL) is a configurable duration that determines how long an agent session state will be retained after its last interaction. When an agent session is idle (no messages sent to it) for longer than the TTL period, the session state is automatically deleted. Each new interaction with an agent resets the TTL timer, extending the session's lifetime.
## Benefits
- **Automatic cleanup**: No manual intervention required to clean up idle agent sessions
- **Cost optimization**: Reduces storage costs by automatically removing unused session state
- **Resource management**: Prevents unbounded growth of agent session state in storage
- **Configurable**: Set TTL globally or per-agent type to match your application's needs
## Configuration
TTL can be configured at two levels:
1. **Global default TTL**: Applies to all agent sessions unless overridden
2. **Per-agent type TTL**: Overrides the global default for specific agent types
Additionally, you can configure a **minimum deletion delay** that controls how frequently deletion operations are scheduled. The default value is 5 minutes, and the maximum allowed value is also 5 minutes.
> [!NOTE]
> Reducing the minimum deletion delay below 5 minutes can be useful for testing or for ensuring rapid cleanup of short-lived agent sessions. However, this can also increase the load on the system and should be used with caution.
### Default values
- **Default TTL**: 14 days
- **Minimum TTL deletion delay**: 5 minutes (maximum allowed value, subject to change in future releases)
### Configuration examples
#### .NET
```csharp
// Configure global default TTL and minimum signal delay
services.ConfigureDurableAgents(
options =>
{
// Set global default TTL to 7 days
options.DefaultTimeToLive = TimeSpan.FromDays(7);
// Add agents (will use global default TTL)
options.AddAIAgent(myAgent);
});
// Configure per-agent TTL
services.ConfigureDurableAgents(
options =>
{
options.DefaultTimeToLive = TimeSpan.FromDays(14); // Global default
The following sections describe how TTL works in detail.
### Expiration tracking
Each agent session maintains an expiration timestamp in its internally managed state that is updated whenever the session processes a message:
1. When a message is sent to an agent session, the expiration time is set to `current time + TTL`
2. The runtime schedules a delete operation for the expiration time (subject to minimum delay constraints)
3. When the delete operation runs, if the current time is past the expiration time, the session state is deleted. Otherwise, the delete operation is rescheduled for the next expiration time.
### State deletion
When an agent session expires, its entire state is deleted, including:
- Conversation history
- Any custom state data
- Expiration timestamps
After deletion, if a message is sent to the same agent session, a new session is created with a fresh conversation history.
## Behavior examples
The following examples illustrate how TTL works in different scenarios.
### Example 1: Agent session expires after TTL
1. Agent configured with 30-day TTL
2. User sends message at Day 0 → agent session created, expiration set to Day 30
3. No further messages sent
4. At Day 30 → Agent session is deleted
5. User sends message at Day 31 → New agent session created with fresh conversation history
### Example 2: TTL reset on interaction
1. Agent configured with 30-day TTL
2. User sends message at Day 0 → agent session created, expiration set to Day 30
3. User sends message at Day 15 → Expiration reset to Day 45
4. User sends message at Day 40 → Expiration reset to Day 70
5. Agent session remains active as long as there are regular interactions
## Logging
The TTL feature includes comprehensive logging to track state changes:
- **Expiration time updated**: Logged when TTL expiration time is set or updated
- **Deletion scheduled**: Logged when a deletion check signal is scheduled
- **Deletion check**: Logged when a deletion check operation runs
- **Session expired**: Logged when an agent session is deleted due to expiration
- **TTL rescheduled**: Logged when a deletion signal is rescheduled
These logs help monitor TTL behavior and troubleshoot any issues.
## Best practices
1. **Choose appropriate TTL values**: Balance between storage costs and user experience. Too short TTLs may delete active sessions, while too long TTLs may accumulate unnecessary state.
2. **Use per-agent TTLs**: Different agents may have different usage patterns. Configure TTLs per-agent based on expected session lifetimes.
3. **Monitor expiration logs**: Review logs to understand TTL behavior and adjust configuration as needed.
4. **Test with short TTLs**: During development, use short TTLs (e.g., minutes) to verify TTL behavior without waiting for long periods.
## Limitations
- TTL is based on wall-clock time, not activity time. The expiration timer starts from the last message timestamp.
- Deletion checks are durably scheduled operations and may have slight delays depending on system load.
- Once an agent session is deleted, its conversation history cannot be recovered.
- TTL deletion requires at least one worker to be available to process the deletion operation message.
This feature ports the vector store abstractions, embedding generator abstractions, and their implementations from Semantic Kernel into Agent Framework. The ported code follows AF's coding standards, feels native to AF, and is structured to allow data models/schemas to be reusable across both frameworks. The embedding abstraction combines the best of SK's `EmbeddingGeneratorBase` and MEAI's `IEmbeddingGenerator<TInput, TEmbedding>`.
- **Both Protocol and Base class** (matching AF's `SupportsChatGetResponse` + `BaseChatClient` pattern):
- `SupportsGetEmbeddings` — Protocol for duck-typing
- `BaseEmbeddingClient` — ABC base class for implementations (similar to `BaseChatClient`)
- **Generic input type** (`EmbeddingInputT`, default `str`) from MEAI — allows image/audio embeddings in the future
- **Generic output type** (`EmbeddingT`, default `list[float]`) from MEAI — supports `list[float]`, `list[int]`, `bytes`, etc.
- **Generic order**: `[EmbeddingInputT, EmbeddingT, EmbeddingOptionsT]` — options last, matching MEAI's `IEmbeddingGenerator<TInput, TEmbedding>` with options appended
- **TypeVar naming convention**: Use `SuffixT` per AF standard (e.g., `EmbeddingInputT`, `EmbeddingT`, `ModelT`, `KeyT`)
- `EmbeddingGenerationOptions` TypedDict (inspired by MEAI, matching AF's `ChatOptions` pattern) — `total=False`, includes `dimensions`, `model_id`. No `additional_properties` since each implementation extends with its own fields.
- Protocol and base class are generic over input, output, and options: `SupportsGetEmbeddings[EmbeddingInputT, EmbeddingT, OptionsContraT]`, `BaseEmbeddingClient[EmbeddingInputT, EmbeddingT, OptionsCoT]`
- **`Embedding[EmbeddingT]` type** in `_types.py` — a lightweight generic class (not Pydantic) with `vector: EmbeddingT`, `model_id: str | None`, `dimensions: int | None` (explicit or computed from vector), `created_at: datetime | None`, `additional_properties: dict[str, Any]`
- **`GeneratedEmbeddings[EmbeddingT, EmbeddingOptionsT]` type** — a list-like container of `Embedding[EmbeddingT]` objects with `options: EmbeddingOptionsT | None` (stores the options used to generate), `usage: dict[str, Any] | None`, `additional_properties: dict[str, Any]`
- **No numpy dependency** — return `list[float]` by default; users cast as needed
### Vector Store Abstractions
- **Port core abstractions without Pydantic for internal classes** — use plain classes
- **Both Protocol and Base class** for vector store operations (matching AF pattern):
- `BaseVectorCollection` / `BaseVectorSearch` — ABC base classes for implementations
- `BaseVectorStore` — ABC base class for store operations (factory for collections, no protocol needed)
- **TypeVar naming convention**: `ModelT`, `KeyT`, `FilterT` (suffix T, per AF standard)
- **Support Pydantic for user-facing data models** — the `@vectorstoremodel` decorator and `VectorStoreCollectionDefinition` should work with Pydantic models, dataclasses, plain classes, and dicts
- `Embedding[EmbeddingT]` generic class: `vector: EmbeddingT`, `model_id: str | None`, `dimensions: int | None` (explicit param or computed from vector length), `created_at: datetime | None`, `additional_properties: dict[str, Any]`
- `GeneratedEmbeddings[EmbeddingT, EmbeddingOptionsT]` generic class: list-like container of `Embedding[EmbeddingT]` objects with `options: EmbeddingOptionsT | None` (the options used to generate), `usage: dict[str, Any] | None`, `additional_properties: dict[str, Any]`
- `EmbeddingGenerationOptions` TypedDict (`total=False`): `dimensions: int`, `model_id: str` — follows the same pattern as `ChatOptions`. No `additional_properties` needed since it's a TypedDict and each implementation can extend with its own fields.
#### 1.2 — Embedding generator protocol + base class in `_clients.py`
- `SupportsGetEmbeddings(Protocol[EmbeddingInputT, EmbeddingT, OptionsContraT])`: generic over input, output, and options (all with defaults), `get_embeddings(values: Sequence[EmbeddingInputT], *, options: OptionsContraT | None = None) -> Awaitable[GeneratedEmbeddings[EmbeddingT]]`
- `BaseEmbeddingClient(ABC, Generic[EmbeddingInputT, EmbeddingT, OptionsCoT])`: ABC base class mirroring `BaseChatClient` pattern
- `__init__` with `additional_properties`, etc.
- Abstract `get_embeddings(...)` for subclasses to implement directly (no `_inner_*` indirection — simpler than chat, no middleware needed)
- `EmbeddingTelemetryLayer` in `observability.py` — MRO-based telemetry (no closure), `gen_ai.operation.name = "embeddings"`
#### 1.3 — OpenAI embedding generator in `agent_framework/openai/` and `agent_framework/azure/`
- `RawOpenAIEmbeddingClient` — implements `get_embeddings` via `_ensure_client()` factory
- `OpenAIEmbeddingClient(OpenAIConfigMixin, EmbeddingTelemetryLayer[str, list[float], OptionsT], RawOpenAIEmbeddingClient[OptionsT])` — full client with config + telemetry layers
- `OpenAIEmbeddingOptions(EmbeddingGenerationOptions)` — extends with `encoding_format`, `user`
- `AzureOpenAIEmbeddingClient` in `agent_framework/azure/` — follows `AzureOpenAIChatClient` pattern with `AzureOpenAIConfigMixin`, `load_settings`, Entra ID credential support
- `AzureOpenAISettings` extended with `embedding_deployment_name` (env var: `AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME`)
#### 1.4 — Tests and samples
- Unit tests for types, protocol, base class, OpenAI client, Azure OpenAI client
- Integration tests for OpenAI and Azure OpenAI (gated behind credentials check, `@pytest.mark.flaky`)
- Samples in `samples/02-agents/embeddings/` — `openai_embeddings.py`, `azure_openai_embeddings.py`
---
### Phase 2: Embedding Generators for Existing Providers
**Goal:** Add embedding generators to all existing AF provider packages that have chat clients.
**Mergeable:** Yes — each is independent, added to existing provider packages.
#### 2.1 — Azure AI Inference embedding (in `packages/azure-ai/`)
#### 2.2 — Ollama embedding (in `packages/ollama/`)
#### 2.3 — Anthropic embedding (in `packages/anthropic/`)
#### 2.4 — Bedrock embedding (in `packages/bedrock/`)
---
### Phase 3: Core Vector Store Abstractions
**Goal:** Establish all vector store types, enums, the decorator, collection definition, and base classes.
**Mergeable:** Yes — adds new abstractions, no breaking changes.
#### 3.1 — Vector store enums and field types in `_vectors.py`
- `SerializeMethodProtocol`, `ToDictFunctionProtocol`, `FromDictFunctionProtocol`, etc.
- Port the record handler logic but without Pydantic base class — use plain class or ABC
#### 3.4 — Vector store base classes in `_vectors.py`
- `VectorStoreRecordHandler` — internal base class that handles serialization/deserialization between user data models and store-specific formats, plus embedding generation for vector fields. Both `BaseVectorCollection` and `BaseVectorSearch` extend this.
- `BaseVectorCollection(VectorStoreRecordHandler)` — base for collections
- Uses `SupportsGetEmbeddings` instead of `EmbeddingGeneratorBase`
- Not a Pydantic model — use `__init__` with explicit params
**Mergeable:** Yes — each connector is independent.
#### 6.1 — MongoDB Atlas (`packages/mongodb/`)
#### 6.2 — Azure Cosmos DB (`packages/azure-cosmos-db/`)
- Cosmos Mongo + Cosmos NoSQL
#### 6.3 — Pinecone (`packages/pinecone/`)
#### 6.4 — Chroma (`packages/chroma/`)
#### 6.5 — Weaviate (`packages/weaviate/`)
---
### Phase 7: Vector Store Connectors — Tier 3
**Goal:** Ship niche or less common connectors.
**Mergeable:** Yes — each connector is independent.
#### 7.1 — Oracle (`packages/oracle/`)
#### 7.2 — SQL Server (`packages/sql-server/`)
#### 7.3 — FAISS (`packages/faiss/` or in core extending InMemory)
> **Note:** When implementing any SQL-based connector (PostgreSQL, SQL Server, SQLite, Cosmos DB), review the .NET MEVD changes made by @roji (Shay Rojansky) in SK for design patterns, query building, filter translation, and feature parity: https://github.com/microsoft/semantic-kernel/pulls?q=is%3Apr+author%3Aroji+is%3Aclosed
---
### Phase 8: Vector Store CRUD Tools
**Goal:** Provide a full set of agent-usable tools for CRUD operations on vector store collections.
**Mergeable:** Yes — adds tools without changing existing APIs.
#### 8.1 — `create_upsert_tool` — tool for upserting records into a collection
#### 8.2 — `create_get_tool` — tool for retrieving records by key
- Key-based lookup only (by primary key), not a search tool
- Documentation must clearly distinguish this from `create_search_tool`: get_tool retrieves specific records by their known key, while search_tool performs similarity/filtered search across the collection
- Consider if this overlaps with filtered search and document when to use which
#### 8.3 — `create_delete_tool` — tool for deleting records by key
#### 8.4 — Tests and samples for CRUD tools
---
### Phase 9: Additional Embedding Implementations (New Providers)
**Goal:** Provide embedding generators for providers that don't yet have AF packages.
**Mergeable:** Yes — each is independent, new packages.
#### 9.1 — HuggingFace/ONNX embedding (new package or lab)
#### 9.2 — Mistral AI embedding (new package)
#### 9.3 — Google AI / Vertex AI embedding (new package)
- `create_search_function()` for kernel integration (may need AF equivalent)
#### 10.2 — Brave Search implementation
#### 10.3 — Google Search implementation
#### 10.4 — Vector store text search bridge (connecting VectorSearch to TextSearch interface)
---
## Key Considerations
1. **No Pydantic for internal classes**: All AF internal classes should use plain classes. Pydantic is only used for user-facing input validation (e.g., vector store data models).
2. **Protocol + Base class**: Follow AF's pattern of both a `Protocol` for duck-typing and a `Base` ABC for implementation, matching how `SupportsChatGetResponse` + `BaseChatClient` works.
3. **Exception hierarchy**: Use AF's `IntegrationException` branch for vector store operations, since vector stores are external dependencies.
4. **`from __future__ import annotations`**: Required in all files per AF coding standard.
5. **No `**kwargs` escape hatches in public APIs**: For user-facing interfaces, use explicit named parameters per AF coding standard. Internal implementation details (e.g., cooperative multiple inheritance / MRO patterns) may use `**kwargs` where necessary, as long as they are not exposed in public signatures.
6. **Lazy loading**: Connector packages use `__getattr__` lazy loading in core provider folders.
7. **Reusable data models**: The `@vectorstoremodel` decorator and `VectorStoreCollectionDefinition` should be agnostic enough to work with both SK and AF. The core types (`FieldTypes`, `IndexKind`, `DistanceFunction`, `VectorStoreField`) should be identical or easily mapped.
8. **`create_search_tool`**: The AF-native equivalent of SK's `create_search_function`. Instead of creating a `KernelFunction`, this creates an AF `FunctionTool` (via the `@tool` decorator pattern) from a vector search. This allows agents to use vector search as a tool during conversations. Design:
- `create_search_tool(name, description, search_type, ...)` → returns a `FunctionTool` that wraps `VectorSearch.search(search_type=...)`
- The tool accepts a query string, performs embedding + vector search, and returns results as strings
- Lives in `_vectors.py` as a method on `BaseVectorSearch` and/or as a standalone factory function
9. **CRUD tools**: A full set of create/read/update/delete tools for vector store collections, allowing agents to manage data in vector stores. Design:
- `create_upsert_tool(...)` → tool for upserting records
- `create_get_tool(...)` → tool for retrieving records by key
- `create_delete_tool(...)` → tool for deleting records
- These are separate from search and are placed in a later phase
10. **Score threshold filtering**: `SearchOptions` includes `score_threshold: float | None` to filter search results by relevance score (ref: [SK .NET PR #13501](https://github.com/microsoft/semantic-kernel/pull/13501)). The semantics depend on the distance function: for similarity functions (cosine similarity, dot product), results *below* the threshold are filtered out; for distance functions (cosine distance, euclidean), results *above* the threshold are filtered out. Use `DISTANCE_FUNCTION_DIRECTION_HELPER` to determine direction. Connectors should implement this natively where the database supports it, falling back to client-side post-filtering otherwise.
dotnet test tests/Microsoft.Agents.AI.<Package>.UnitTests
dotnet format src/Microsoft.Agents.AI.<Package>
# Run a single test
dotnet test --filter "FullyQualifiedName~Namespace.TestClassName.TestMethodName"
# Run unit tests only
dotnet test --filter FullyQualifiedName\~UnitTests
```
Use `--tl:off` when building to avoid flickering when running commands in the agent.
## Speeding Up Builds and Testing
The full solution is large. Use these shortcuts:
| Change type | What to do |
|-------------|------------|
| Isolated/Internal logic | Build only the affected project and its `*.UnitTests` project. Fix issues, then build the full solution and run all unit tests. |
| Public API surface | Build the full solution and run all unit tests immediately. |
Example: Building a single code project for all target frameworks
Example: Running tests for a single project using .NET 10.
```bash
# From dotnet/ directory
dotnet test ./tests/Microsoft.Agents.AI.Abstractions.UnitTests -f net10.0
```
Example: Running a single test in a specific project using .NET 10.
Provide the full namespace, class name, and method name for the test you want to run:
```bash
# From dotnet/ directory
dotnet test ./tests/Microsoft.Agents.AI.Abstractions.UnitTests -f net10.0 --filter "FullyQualifiedName~Microsoft.Agents.AI.Abstractions.UnitTests.AgentRunOptionsTests.CloningConstructorCopiesProperties"
```
### Multi-target framework tip
Most projects target multiple .NET frameworks. If the affected code does **not** use `#if` directives for framework-specific logic, pass `-f net10.0` to speed up building and testing.
### Package Restore tip
`dotnet build` will try and restore packages for all projects on each build, which can be slow.
Unless packages have been changed, or it's the first time building the solution, add `--no-restore` to the build command to skip this step and speed up builds.
Just remember to run `dotnet restore` after pulling changes, making changes to project references, or when building for the first time.
### Testing on Linux tip
Unit tests target both .NET Framework as well as .NET Core. When running on Linux, only the .NET Core tests can be run, as .NET Framework is not supported on Linux.
To run only the .NET Core tests, use the `-f net10.0` option with `dotnet test`.
| `tests/` | Test projects — named `<Source-Code-Project>.UnitTests` or `<Source-Code-Project>.IntegrationTests` |
| `samples/` | Sample projects |
| `src/Shared`, `src/LegacySupport` | Shared code files included by multiple source code projects (see README.md files in these folders or their subdirectories for instructions on how to include them in a project) |
description: How to build, run and verify the .NET sample projects in the Agent Framework repository. Use this when a user wants to verify that the samples still function as expected.
---
# Verifying .NET Sample Projects
## Sample Pre-requisites
We should only support verifying samples that:
1. Use environment variables for configuration.
2. Have no complex setup requirements, e.g., where multiple applications need to be run together, or where we need to launch a browser, etc.
Always report to the user which samples were run and which were not, and why.
## Verifying a sample
Samples should be verified to ensure that they actually work as intended and that their output matches what is expected.
For each sample that is run, output should be produced that shows the result and explains the reasoning about what output
was expected, what was produced, and why it didn't match what the sample was expected to produce.
Steps to verify a sample:
1. Read the code for the sample
1. Check what environment variables are required for the sample
1. Check if each environment variable has been set
1. If there are any missing, give the user a list of missing environment variables to set and terminate
1. Summarize what the expected output of the sample should be
1. Run the sample
1. Show the user any output from the sample run as it gets produced, so that they can see the run progress
1. Check the output of the run against expectations
1. After running all requested samples, produce output for each sample that was verified:
1. If expectations were matched, output the following:
```text
[Sample Name] Succeeded
```
1. If expectations were not matched, output the following:
```text
[Sample Name] Failed
Actual Output:
[What the sample produced]
Expected Output:
[Explanation of what was expected and why the actual output didn't match expectations]
```
## Environment Variables
Most samples use environment variables to configure settings.
```csharp
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
```
To run a sample, the environment variables should be set first.
Before running a sample, check whether each environment variable in the sample has a value and
then give the user a list of environment variables to set.
You can provide the user some examples of how to set the variables like this:
Instructions for AI coding agents working in the .NET codebase.
## Build, Test, and Lint Commands
See `./.github/skills/build-and-test/SKILL.md` for detailed instructions on building, testing, and linting projects.
## Project Structure
See `./.github/skills/project-structure/SKILL.md` for an overview of the project structure.
### Core types
- `AIAgent`: The abstract base class that all agents derive from, providing common methods for interacting with an agent.
- `AgentSession`: The abstract base class that all agent sessions derive from, representing a conversation with an agent.
- `ChatClientAgent`: An `AIAgent` implementation that uses an `IChatClient` to send messages to an AI provider and receive responses.
- `IChatClient`: Interface for sending messages to an AI provider and receiving responses. Used by `ChatClientAgent` and implemented by provider-specific packages.
- `FunctionInvokingChatClient`: Decorator for `IChatClient` that adds function invocation capabilities.
- `AITool`: Represents a tool that an agent/AI provider can use, with metadata and an execution delegate.
- `AIFunction`: A specific type of `AITool` that represents a local function the agent/AI provider can call, with parameters and return types defined.
- `ChatMessage`: Represents a message in a conversation.
- `AIContent`: Represents content in a message, which can be text, a function call, tool output and more.
### External Dependencies
The framework integrates with `Microsoft.Extensions.AI` and `Microsoft.Extensions.AI.Abstractions` (external NuGet packages)
using types like `IChatClient`, `FunctionInvokingChatClient`, `AITool`, `AIFunction`, `ChatMessage`, and `AIContent`.
## Key Conventions
- **Encoding**: All new files must be saved with UTF-8 encoding with BOM (Byte Order Mark). This is required for `dotnet format` to work correctly.
- **Copyright header**: `// Copyright (c) Microsoft. All rights reserved.` at top of all `.cs` files
- **XML docs**: Required for all public methods and classes
- **Async**: Use `Async` suffix for methods returning `Task`/`ValueTask`
- **Private classes**: Should be `sealed` unless subclassed
- **Config**: Read from environment variables with `UPPER_SNAKE_CASE` naming
- **Tests**: Add Arrange/Act/Assert comments; use Moq for mocking
## Key Design Principles
When developing or reviewing code, verify adherence to these key design principles:
- **DRY**: Avoid code duplication by moving common logic into helper methods or helper classes.
- **Single Responsibility**: Each class should have one clear responsibility.
- **Encapsulation**: Keep implementation details private and expose only necessary public APIs.
- **Strong Typing**: Use strong typing to ensure that code is self-documenting and to catch errors at compile time.
## Sample Structure
Samples (in `./samples/` folder) should follow this structure:
1. Copyright header: `// Copyright (c) Microsoft. All rights reserved.`
2. Description comment explaining what the sample demonstrates
3. Using statements
4. Main code logic
5. Helper methods at bottom
Configuration via environment variables (never hardcode secrets). Keep samples simple and focused.
When adding a new sample:
- Create a standalone project in `samples/` with matching directory and project names
- Include a README.md explaining what the sample does and how to run it
- Add the project to the solution file
- Reference the sample in the parent directory's README.md
@@ -19,11 +19,14 @@ string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"] ?? throw new In
stringdeploymentName=builder.Configuration["AZURE_OPENAI_DEPLOYMENT_NAME"]??thrownewInvalidOperationException("AZURE_OPENAI_DEPLOYMENT_NAME is not set.");
// Create the AI agent with tools
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.