mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b70bacceb6 | ||
|
|
b3ea1dee0c | ||
|
|
8b48604a28 | ||
|
|
8bc7c3a7a8 | ||
|
|
0fcd71dbeb | ||
|
|
55e0705923 | ||
|
|
892d88df28 | ||
|
|
3225a59fd3 | ||
|
|
9e3983e547 | ||
|
|
383a2afca2 | ||
|
|
0402b1aac4 | ||
|
|
448f46aff2 | ||
|
|
9ce2aafff7 | ||
|
|
a98a585afb | ||
|
|
615ef9049f |
@@ -131,7 +131,7 @@ jobs:
|
||||
--timeout=120 --session-timeout=900 --timeout_method thread
|
||||
--retries 2 --retry-delay 5
|
||||
|
||||
# Misc integration tests (Anthropic, Hyperlight, Ollama, MCP)
|
||||
# Misc integration tests (Anthropic, Ollama, MCP)
|
||||
python-tests-misc-integration:
|
||||
name: Python Integration Tests - Misc
|
||||
runs-on: ubuntu-latest
|
||||
@@ -162,11 +162,10 @@ jobs:
|
||||
fallback_url: ${{ env.LOCAL_MCP_URL }}
|
||||
- name: Prefer local MCP URL when available
|
||||
run: echo "LOCAL_MCP_URL=${{ steps.local-mcp.outputs.effective_url }}" >> "$GITHUB_ENV"
|
||||
- name: Test with pytest (Anthropic, Hyperlight, Ollama, MCP integration)
|
||||
- name: Test with pytest (Anthropic, Ollama, MCP integration)
|
||||
run: >
|
||||
uv run pytest --import-mode=importlib
|
||||
packages/anthropic/tests
|
||||
packages/hyperlight/tests
|
||||
packages/ollama/tests
|
||||
packages/core/tests/core/test_mcp.py
|
||||
-m integration
|
||||
|
||||
@@ -65,7 +65,6 @@ jobs:
|
||||
- 'python/samples/**/providers/azure/**'
|
||||
misc:
|
||||
- 'python/packages/anthropic/**'
|
||||
- 'python/packages/hyperlight/**'
|
||||
- 'python/packages/ollama/**'
|
||||
- 'python/packages/core/agent_framework/_mcp.py'
|
||||
- 'python/packages/core/tests/core/test_mcp.py'
|
||||
@@ -279,11 +278,10 @@ jobs:
|
||||
fallback_url: ${{ env.LOCAL_MCP_URL }}
|
||||
- name: Prefer local MCP URL when available
|
||||
run: echo "LOCAL_MCP_URL=${{ steps.local-mcp.outputs.effective_url }}" >> "$GITHUB_ENV"
|
||||
- name: Test with pytest (Anthropic, Hyperlight, Ollama, MCP integration)
|
||||
- name: Test with pytest (Anthropic, Ollama, MCP integration)
|
||||
run: >
|
||||
uv run pytest --import-mode=importlib
|
||||
packages/anthropic/tests
|
||||
packages/hyperlight/tests
|
||||
packages/ollama/tests
|
||||
packages/core/tests/core/test_mcp.py
|
||||
-m integration
|
||||
|
||||
@@ -203,8 +203,6 @@ temp*/
|
||||
|
||||
# AI
|
||||
.claude/
|
||||
.omc/
|
||||
.omx/
|
||||
WARP.md
|
||||
**/memory-bank/
|
||||
**/projectBrief.md
|
||||
@@ -237,4 +235,3 @@ python/dotnet-ref
|
||||
|
||||
# Generated filtered solution files (created by eng/scripts/New-FilteredSolution.ps1)
|
||||
dotnet/filtered-*.slnx
|
||||
**/*.lscache
|
||||
|
||||
@@ -1,233 +0,0 @@
|
||||
---
|
||||
status: proposed
|
||||
contact: eavanvalkenburg
|
||||
date: 2026-04-07
|
||||
deciders: TBD
|
||||
consulted:
|
||||
informed:
|
||||
---
|
||||
|
||||
# CodeAct integration through backend-specific context providers and an `execute_code` tool
|
||||
|
||||
## Introduction
|
||||
|
||||
**CodeAct** is a pattern in which the model writes executable code — rather than emitting a fixed function-call JSON schema — to plan, transform data, and orchestrate tool calls inside a single sandbox invocation. Instead of requiring a separate model round-trip for every tool call, conditional branch, or data transformation, the model produces a short program that runs in a controlled runtime, calls host-provided tools through a `call_tool(...)` bridge, and returns structured results. This reduces latency, lowers token cost, and lets the model express richer multi-step logic that is difficult to capture in a flat tool-call sequence.
|
||||
|
||||
Throughout this ADR, **CodeAct** is the primary term. **Code mode** and **programmatic tool calling** refer to the same capability.
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
We need an architecture design that supports CodeAct in both Python and .NET. This is a necessary capability for the current generation of long-running agents, which need to plan, iterate, transform tool outputs, and execute bounded code inside a controlled runtime — for example, filtering a large result set, computing derived values, or chaining several tool calls with conditional logic — instead of requiring a separate model round-trip for each of those steps. The design should preserve the same behavioral contract across SDKs, but it does not need to use the same internal extension point in each runtime. We also want to standardize on Hyperlight as the initial backend, using the existing Python package and an anticipated .NET binding package once it is available.
|
||||
|
||||
Throughout this ADR, **CodeAct** is the primary term. **Code mode** and **programmatic tool calling** refer to the same capability. This ADR uses **CodeAct** consistently.
|
||||
|
||||
Model-generated code is treated as untrusted relative to the host process. This ADR assumes the selected backend provides the primary isolation boundary, while the framework is responsible for configuring approvals and capabilities, integrating telemetry, and translating outputs and failures into framework-native shapes. If a backend cannot provide isolation appropriate for its trust model, it is not a suitable CodeAct backend.
|
||||
|
||||
The core design question is: **where should CodeAct integrate into the agent pipeline so that both SDKs can offer the same functionality without invasive changes to their core function-calling loops?**
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
- CodeAct must shape the model-facing surface before model invocation, not only after the model has already chosen tools.
|
||||
- The design should let users control which tools are available through CodeAct and which remain regular tools only.
|
||||
- The design must preserve existing session, approval, telemetry, and tool invocation behavior as much as possible.
|
||||
- The design should define the minimum cross-SDK telemetry and failure semantics for `execute_code`, so Python and .NET do not diverge on basic observability or error handling.
|
||||
- The design must fit naturally into the extension points that already exist in each SDK.
|
||||
- The design must be safe for concurrent runs and must not rely on mutating shared agent configuration during invocation.
|
||||
- The chosen structure should allow multiple backend-specific providers to fit under the same conceptual design over time, even though Hyperlight is the initial target.
|
||||
- The abstraction should not assume that every backend is a VM-style sandbox; alternative execution models such as Pydantic's Monty should also fit.
|
||||
- The design should allow `execute_code` to be reused both as a tool-enabled CodeAct runtime and as a standard code interpreter tool implementation.
|
||||
- The design should remain open to alternative language/runtime modes, such as JavaScript on Hyperlight, rather than baking the abstraction to Python only.
|
||||
- The design should provide a portable way to configure sandbox capabilities such as file access and network access, including allow-listed outbound domains.
|
||||
- Using CodeAct should be optional, and installing its runtime or backend dependencies should also be optional.
|
||||
- Backend-specific dependencies should be isolated behind a small adapter so SDK code is not tightly coupled to an unstable package surface.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Option 1**: Standardize on context provider-based CodeAct with a shared cross-SDK contract and backend-specific public types
|
||||
- **Option 2**: Implement CodeAct as a dedicated chat-client decorator/wrapper
|
||||
- **Option 3**: Integrate CodeAct directly into the function invocation layer/FunctionInvokingChatClient
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Standardize on context provider-based CodeAct with a shared cross-SDK contract and backend-specific public types
|
||||
|
||||
This option uses `ContextProvider` in Python and `AIContextProvider` in .NET, but standardizes the public concept and behavior.
|
||||
In this option, the CodeAct tool set is provider-owned: only tools explicitly configured on the concrete CodeAct provider instance are available inside CodeAct, and the provider exposes direct CRUD-style management for tools, file mounts, and outbound network allow-list configuration rather than requiring a separate runtime setup object.
|
||||
The agent's direct tool surface remains separate. If a tool should be available both through CodeAct and as a normal direct tool, it is configured in both places.
|
||||
|
||||
- Good, because both SDKs already have first-class provider concepts intended for per-invocation context shaping.
|
||||
- Good, because providers operate before model invocation, which is where CodeAct must add instructions and reshape tools.
|
||||
- Good, because this lets us preserve existing function invocation behavior rather than rewriting it.
|
||||
- Good, because slightly different internals are acceptable while the public behavior remains aligned.
|
||||
- Good, because convenience builder/decorator helpers can still be added later on top of the provider model without changing the core design.
|
||||
- Good, because backend-specific runtime logic can stay inside concrete provider implementations or internal helpers instead of being forced into a lowest-common-denominator public abstraction.
|
||||
- Good, because the same provider structure can support either an all-or-nothing tool surface or a mixed side-by-side tool surface.
|
||||
- Good, because users can keep some tools direct-only while allowing other tools to be used from inside CodeAct.
|
||||
- Good, because a provider-owned CodeAct tool registry avoids mutating or inferring the agent's direct tool surface and can work consistently in both SDKs.
|
||||
- Good, because the same conceptual design can remain open to `HyperlightCodeActProvider`, a future `MontyCodeActProvider`, and other backend-specific providers over time.
|
||||
- Good, because `execute_code` can evolve into multiple backend-specific runtime modes rather than being hard-wired to one Python-plus-tools mode.
|
||||
- Bad, because the provider indirection adds per-run overhead — snapshotting the tool registry, dispatching lifecycle hooks, and building instructions — that a deeper integration point could skip. In practice this overhead is negligible relative to model inference latency and sandbox startup cost.
|
||||
|
||||
### Option 2: Implement CodeAct as a dedicated chat-client decorator/wrapper
|
||||
|
||||
This option would introduce a CodeAct-specific chat-client decorator that injects instructions and tools directly into the chat request pipeline.
|
||||
|
||||
- Good, because this is a natural fit for .NET's `DelegatingChatClient` pipeline.
|
||||
- Good, because it can also support advanced custom chat-client stacks.
|
||||
- Good, because backend-specific runtime selection could be hidden inside the decorator implementation.
|
||||
- Good, because the decorator could also encapsulate mode-specific instruction shaping for tool-enabled versus standalone interpreter behavior.
|
||||
- Good, because the decorator can decide per request whether the tool surface is exclusive or mixed.
|
||||
- Bad, because Python can support this by building a custom layering stack on top of a `Raw...Client` and swapping in a different `FunctionInvocationLayer`, but that composition path is more manual than the .NET `DelegatingChatClient` pipeline.
|
||||
- Bad, because it duplicates responsibilities already handled by provider abstractions.
|
||||
- Bad, because it makes CodeAct look more transport-specific than it really is.
|
||||
- Bad, because swappable backends and reusable interpreter or language modes become coupled to chat-client composition rather than modeled as first-class CodeAct concepts.
|
||||
|
||||
### Option 3: Integrate CodeAct directly into the function invocation layer/FunctionInvokingChatClient
|
||||
|
||||
This option would push CodeAct into Python's `FunctionInvocationLayer` and .NET's `FunctionInvokingChatClient` or related middleware.
|
||||
|
||||
- Good, because it is close to tool execution and can observe concrete tool invocation behavior.
|
||||
- Good, because function middleware may still be useful later for auxiliary auditing or policy around sandbox-originated tool calls.
|
||||
- Bad, because this is the wrong layer for constructing the model-facing tool surface and prompt instructions.
|
||||
- Bad, because it does not naturally control whether the model sees an exclusive CodeAct tool surface or a mixed side-by-side tool surface.
|
||||
- Bad, because it would still require a second mechanism for hiding normal tools and advertising `execute_code`.
|
||||
- Bad, because it is a weak fit for standalone interpreter modes where no tool-calling loop is needed.
|
||||
- Bad, because backend selection and CodeAct mode behavior are orthogonal concerns that do not belong in the function invocation layer.
|
||||
- Bad, because `.NET` would become more tightly coupled to `FunctionInvokingChatClient`, which sits below the agent framework abstraction and is not the natural cross-SDK design seam.
|
||||
|
||||
## Approval Model Options
|
||||
|
||||
- **Option A**: Bundled approval for the `execute_code` invocation
|
||||
- **Option B**: Pre-execution inspection of `call_tool(...)` references before approving `execute_code`
|
||||
- **Option C**: Nested per-tool approvals during `execute_code`
|
||||
|
||||
## Pros and Cons of the Approval Options
|
||||
|
||||
### Option A: Bundled approval for the `execute_code` invocation
|
||||
|
||||
This option grants approval once, before `execute_code` starts. Provider-owned tool calls made from inside that execution run under the same approval. The effective approval of `execute_code` is determined up front from the provider configuration rather than from inspecting which tools are actually called during execution.
|
||||
|
||||
- Good, because it is the simplest model to explain and implement consistently in both SDKs.
|
||||
- Good, because it fits naturally with long-running CodeAct loops where repeated approval interruptions would be disruptive.
|
||||
- Good, because it does not require static code analysis before execution begins.
|
||||
- Good, because it keeps the first release focused on the provider integration rather than a more complex approval engine.
|
||||
- Bad, because approval is coarse-grained and may cover more activity than the user expected.
|
||||
- Bad, because it provides less visibility into which provider-owned tools or capabilities will be exercised during the run.
|
||||
|
||||
### Option B: Pre-execution inspection of `call_tool(...)` references before approving `execute_code`
|
||||
|
||||
This option inspects submitted code for statically discoverable `call_tool("tool_name", ...)` references before execution starts and uses that information to shape the approval request.
|
||||
|
||||
- Good, because it can show users more detail up front while still keeping approval at a single pre-execution moment.
|
||||
- Good, because it matches the common case where tool names are spelled out directly in the generated code.
|
||||
- Good, because it can coexist with bundled approval as a more informative variant of the same UX.
|
||||
- Bad, because the analysis is inherently best-effort and cannot reliably predict dynamic behavior.
|
||||
- Bad, because it requires duplicated parsing or inspection logic that does not replace runtime enforcement.
|
||||
|
||||
### Option C: Nested per-tool approvals during `execute_code`
|
||||
|
||||
This option requests approval when sandboxed code actually attempts to invoke a provider-owned tool that requires approval.
|
||||
|
||||
- Good, because it aligns approval with real behavior rather than predicted behavior.
|
||||
- Good, because it gives precise visibility into which provider-owned tools are being used.
|
||||
- Good, because it can allow some tool calls while rejecting others within the same execution.
|
||||
- Bad, because it interrupts long-running CodeAct flows and can degrade the user experience significantly.
|
||||
- Bad, because it requires more complex runtime plumbing and approval UX in both SDKs.
|
||||
- Bad, because repeated approval pauses may make CodeAct less useful for the exact long-running scenarios that motivate this feature.
|
||||
|
||||
## Decision Outcomes
|
||||
|
||||
### Decision 1: Integration seam and public structure
|
||||
|
||||
Chosen option: **Option 1: Standardize on provider-based CodeAct with a shared cross-SDK contract and backend-specific public types**, because it is the only option that maps cleanly to both SDKs, lets us reshape instructions and tools before model invocation, and avoids invasive changes to the existing function invocation loops while still allowing multiple backend-specific providers and multiple runtime modes to fit under the same structure later.
|
||||
|
||||
### Decision 2: Initial approval model
|
||||
|
||||
Chosen option: **Option A: Bundled approval for the `execute_code` invocation**, because it is the smallest approval model that fits both SDKs, works well for long-running CodeAct flows, and does not force us to standardize a more complex inspection or policy engine in the first release.
|
||||
|
||||
This follows the spirit of the current Python tool approval flow, where `FunctionTool` uses `approval_mode="always_require" | "never_require"` and the auto-invocation loop escalates the whole batch when any called tool requires approval.
|
||||
|
||||
### Design summary
|
||||
|
||||
We standardize the **public concept** of CodeAct across SDKs while allowing each SDK to use the extension point that fits it best.
|
||||
|
||||
- Python uses a `ContextProvider`.
|
||||
- .NET uses an `AIContextProvider`.
|
||||
- The term **CodeAct context provider** is used throughout this ADR as a design concept, not as a required public base type. Public SDK APIs should prefer concrete backend-specific types such as `HyperlightCodeActProvider` rather than a public abstract `CodeActContextProvider` or a public `CodeActExecutor` parameter.
|
||||
- CodeAct support should ship as an optional package in each SDK rather than as part of the core package, so users who do not need CodeAct do not take on its installation and dependency footprint. That optional package may still depend on a few small, backward-compatible hooks in the host SDK's core agent pipeline.
|
||||
- There is no separate runtime setup object in the chosen design. Concrete providers manage their provider-owned CodeAct tool registry, file mounts, and outbound network allow-list configuration directly through CRUD-style methods on the provider itself.
|
||||
- At a high level, CodeAct is exposed through backend-specific context providers that contribute an `execute_code` tool, own the CodeAct-specific tool registry, and carry backend capability configuration such as filesystem and network access.
|
||||
- The initial approval model is bundled approval for `execute_code`, using the same `approval_mode="always_require" | "never_require"` vocabulary as regular tools.
|
||||
- The CodeAct provider exposes a default `approval_mode` for `execute_code`. If the provider default is `always_require`, `execute_code` is always treated as `always_require` regardless of the provider-owned tool registry. If the provider default is `never_require`, the effective approval for `execute_code` is derived from the provider-owned CodeAct tool registry captured for the run.
|
||||
- If every provider-owned CodeAct tool in that registry has `approval_mode="never_require"`, `execute_code` is treated as `never_require`. If any provider-owned CodeAct tool in that registry has `approval_mode="always_require"`, `execute_code` is treated as `always_require`, even if the generated code may not end up calling that tool.
|
||||
- Approval is granted before `execute_code` starts, and provider-owned tool calls made from inside that execution run under the same approval.
|
||||
- Direct-only agent tools do not affect the approval of `execute_code`; only the provider-owned CodeAct tool registry participates in that calculation.
|
||||
- This approval model is intentionally conservative. If one sensitive provider-owned tool forces `execute_code` to require approval more often than desired, the mitigation is to keep that tool direct-only or split it into a different provider/tool surface rather than trying to infer per-run tool usage up front.
|
||||
- Configuring filesystem and network capability state on the provider, including adding file mounts or outbound network allow-list entries, is itself the approval for those capabilities in the initial model.
|
||||
- Each `execute_code` invocation must start from a clean execution state; in-memory variables and other ephemeral interpreter/runtime state must not persist across separate calls. When a provider exposes a workspace, mounted files, or a writable artifact/output area, those files are the supported persistence mechanism across calls and are treated as external state rather than interpreter state.
|
||||
- Mutating the provider's tool registry or capability configuration while a run is in flight is allowed, but it only affects subsequent runs. Provider implementations must snapshot the effective state for each run and synchronize concurrent access so shared provider instances remain safe across concurrent runs.
|
||||
- The minimum cross-SDK telemetry contract is that `execute_code` is traced as a normal tool invocation nested inside the surrounding agent run, and provider-owned tool calls made from inside CodeAct continue to emit ordinary tool-invocation telemetry. Backend-specific resource metrics are optional extensions, not a required new top-level cross-SDK event model.
|
||||
- Timeout, out-of-memory, backend crash, and similar sandbox failures are all execution failures of `execute_code` and should surface as structured error results rather than backend-specific public DTOs. Partial textual or file outputs may be returned only when the backend can report them unambiguously; callers must not rely on partial-output recovery as a portable guarantee.
|
||||
- The provider-based structure preserves room for future pre-execution inspection and nested per-tool approvals if later experience shows they are needed.
|
||||
- Concrete backend-specific providers may still use small SDK-local helpers or adapters internally, but that split is an implementation detail rather than a public API requirement.
|
||||
|
||||
Detailed language-specific implementation notes are specified in:
|
||||
|
||||
- [Python implementation](../features/code_act/python-implementation.md)
|
||||
- [.NET implementation](../features/code_act/dotnet-implementation.md)
|
||||
|
||||
### Minimal core hooks required by the optional package
|
||||
|
||||
CodeAct remains optional at the package level, but the optional package depends on a small number of hooks that must live in the host SDK because the agent pipeline owns model invocation and per-run tool resolution.
|
||||
|
||||
- Python depends on the existing `ContextProvider` lifecycle, `SessionContext.extend_instructions(...)`, `SessionContext.extend_tools(...)`, per-run runtime tool access via `SessionContext.options["tools"]`, and the shared `ApprovalMode` vocabulary used by `FunctionTool`.
|
||||
- .NET depends on the existing `AIContextProvider` seam, agent/runtime support for applying providers before model invocation, and the existing chat-client or function-invocation seams that concrete implementations use to contribute `execute_code`.
|
||||
|
||||
These hooks are backward-compatible because they only expose or forward per-run state that core already owns. Behavior changes only when a concrete CodeAct provider opts in and uses them.
|
||||
|
||||
### Concrete provider implementation contract
|
||||
|
||||
The design does not require a public abstract `CodeActContextProvider` base class, but it does require a stable implementation contract for concrete providers.
|
||||
|
||||
- Concrete providers should expose a standard capability surface at construction time, with SDK-appropriate naming for:
|
||||
- approval mode
|
||||
- workspace root
|
||||
- file mounts
|
||||
- allowed outbound targets plus any per-target method or policy restrictions needed by the backend
|
||||
- Separate public `filesystem_mode` / `network_mode` flags are not required by the cross-SDK contract. Filesystem access may be disabled implicitly until a workspace or file mounts are configured, and outbound network may be disabled implicitly until an allow-list or equivalent outbound policy entry is configured.
|
||||
- Concrete providers should expose direct CRUD-style methods for managing the provider-owned CodeAct tool registry, file mounts, and outbound network allow-list configuration, rather than requiring callers to construct a separate runtime setup object.
|
||||
- Concrete providers should implement their host SDK's provider lifecycle hooks to:
|
||||
- build CodeAct instructions,
|
||||
- add `execute_code`,
|
||||
- snapshot the effective CodeAct tool registry and capability settings for the run,
|
||||
- compute the effective approval requirement for `execute_code`,
|
||||
- configure file access and network access for the backend,
|
||||
- prepare or restore execution state,
|
||||
- execute code,
|
||||
- and translate backend output into framework-native content.
|
||||
- Any internal abstract/helper surface shared by multiple concrete providers should standardize responsibilities for:
|
||||
- instruction construction,
|
||||
- file-access configuration,
|
||||
- network-access configuration,
|
||||
- environment preparation/restoration,
|
||||
- code execution,
|
||||
- and output-to-content conversion.
|
||||
- Backend execution output should reuse existing framework-native content/message primitives rather than introducing backend-specific public result DTOs.
|
||||
|
||||
## More Information
|
||||
|
||||
### Related artifacts
|
||||
|
||||
- Python implementation: [`docs/features/code_act/python-implementation.md`](../features/code_act/python-implementation.md)
|
||||
- .NET implementation: [`docs/features/code_act/dotnet-implementation.md`](../features/code_act/dotnet-implementation.md)
|
||||
- Python provider/session APIs: [`python/packages/core/agent_framework/_sessions.py`](../../python/packages/core/agent_framework/_sessions.py)
|
||||
- Python function invocation loop: [`python/packages/core/agent_framework/_tools.py`](../../python/packages/core/agent_framework/_tools.py)
|
||||
- .NET context provider abstraction: [`dotnet/src/Microsoft.Agents.AI.Abstractions/AIContextProvider.cs`](../../dotnet/src/Microsoft.Agents.AI.Abstractions/AIContextProvider.cs)
|
||||
- .NET agent integration for context providers: [`dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs`](../../dotnet/src/Microsoft.Agents.AI/ChatClient/ChatClientAgent.cs)
|
||||
- Optional .NET chat-client provider decorator: [`dotnet/src/Microsoft.Agents.AI/AIContextProviderDecorators/AIContextProviderChatClient.cs`](../../dotnet/src/Microsoft.Agents.AI/AIContextProviderDecorators/AIContextProviderChatClient.cs)
|
||||
- .NET function invocation middleware seam: [`dotnet/src/Microsoft.Agents.AI/FunctionInvocationDelegatingAgentBuilderExtensions.cs`](../../dotnet/src/Microsoft.Agents.AI/FunctionInvocationDelegatingAgentBuilderExtensions.cs)
|
||||
|
||||
### Related decisions
|
||||
|
||||
- [0015-agent-run-context](0015-agent-run-context.md)
|
||||
- [0016-python-context-middleware](0016-python-context-middleware.md)
|
||||
@@ -1,454 +0,0 @@
|
||||
---
|
||||
status: proposed
|
||||
contact: evmattso
|
||||
date: 2026-04-10
|
||||
deciders: evmattso
|
||||
---
|
||||
|
||||
# Foundry Toolbox Support in FoundryChatClient
|
||||
|
||||
## What is the goal of this feature?
|
||||
|
||||
Enable Agent Framework users to consume Foundry **toolboxes** — named, versioned bundles of tool definitions stored server-side in an Azure AI Foundry project — directly from `FoundryChatClient`, without dropping to the raw `azure-ai-projects` SDK.
|
||||
|
||||
A user who has configured a toolbox in the Foundry portal (or via the raw SDK) should be able to load it into an agent with a single call:
|
||||
|
||||
```python
|
||||
toolbox = await client.get_toolbox("research_tools")
|
||||
agent = Agent(client=client, instructions="...", tools=toolbox)
|
||||
```
|
||||
|
||||
**Success metric:** an agent can consume a toolbox with no manual handling of version-resolution logic on the user's side.
|
||||
|
||||
## What is the problem being solved?
|
||||
|
||||
`azure-ai-projects==2.1.0a20260409002` ships a new `BetaToolboxesOperations` surface, reachable as `AIProjectClient.beta.toolboxes` on the raw SDK client (and therefore as `FoundryChatClient.project_client.beta.toolboxes` through our wrapper), that lets teams:
|
||||
- Group related hosted tools (code interpreter, file search, MCP, web search, etc.) under a named toolbox
|
||||
- Version toolboxes immutably, so agents can pin to a specific configuration for production stability
|
||||
- Share toolboxes across multiple agents in a project
|
||||
|
||||
However, consuming a toolbox from the framework today requires:
|
||||
1. Knowing the raw SDK accessor path (`client.project_client.beta.toolboxes`)
|
||||
2. Making two calls for the common case — `.get(name)` to find the default version, then `.get_version(name, version)` to actually retrieve tools
|
||||
3. Manually unpacking `toolbox.tools` before passing them to `Agent(tools=...)`
|
||||
|
||||
None of this is hard, but it's the kind of boilerplate that should live in the client. Every other hosted tool in `FoundryChatClient` (code interpreter, file search, web search, image generation, MCP) already has a factory method (`get_code_interpreter_tool()`, etc.). Toolbox support should fit the same shape on the chat-client composition surface.
|
||||
|
||||
## API Changes
|
||||
|
||||
### One new method on the FoundryChatClient surface
|
||||
|
||||
The public toolbox-consumption surface lands on:
|
||||
|
||||
- `RawFoundryChatClient` (inherited by `FoundryChatClient`) in `_chat_client.py`
|
||||
|
||||
The implementation delegates to shared helper functions in `_tools.py` so there is a single source of truth for the SDK calls.
|
||||
|
||||
**Scope note:** `FoundryAgent` is intentionally not part of this design. `FoundryAgent` is the runtime surface for invoking an already-configured server-side Foundry agent; if that agent should use a toolbox, the toolbox/tools should already be configured on the Foundry side (UI or `azure-ai-projects` authoring flow) before MAF connects to it.
|
||||
|
||||
**Scope note:** Authoring a server-side agent whose definition references a toolbox (via `PromptAgentDefinition(tools=toolbox.tools, ...)` + `client.agents.create_version(...)`) is deliberately outside MAF scope. That is an `azure-ai-projects` / service-resource authoring concern, not a future MAF feature. Users who need it should use the raw Azure SDK directly.
|
||||
|
||||
```python
|
||||
async def get_toolbox(
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
version: str | None = None,
|
||||
) -> ToolboxVersionObject:
|
||||
"""Fetch a Foundry toolbox by name.
|
||||
|
||||
If ``version`` is ``None``, resolves the toolbox's current default version
|
||||
(two requests). If ``version`` is specified, fetches that version directly
|
||||
(single request).
|
||||
|
||||
:param name: The name of the toolbox.
|
||||
:param version: Optional immutable version identifier to pin to.
|
||||
:return: A ``ToolboxVersionObject``. Pass its ``tools`` attribute to
|
||||
``Agent(tools=toolbox.tools)``.
|
||||
:raises azure.core.exceptions.ResourceNotFoundError: If the toolbox or
|
||||
version does not exist.
|
||||
"""
|
||||
|
||||
```
|
||||
|
||||
### Return types: raw SDK models, no custom wrappers
|
||||
|
||||
Methods return the `azure.ai.projects.models` types directly:
|
||||
|
||||
- `get_toolbox()` → `ToolboxVersionObject` (has `.name`, `.version`, `.tools`, `.id`, `.created_at`, `.description`, `.metadata`, `.policies`)
|
||||
|
||||
No custom wrapper classes are defined. Returning the SDK types directly:
|
||||
- Eliminates maintenance overhead of keeping a custom wrapper aligned with SDK changes
|
||||
- Matches the existing convention — `get_code_interpreter_tool()` returns the raw `CodeInterpreterTool` SDK type
|
||||
- Means any new fields the SDK adds to these types flow through automatically
|
||||
|
||||
`Agent(..., tools=...)` will accept the fetched toolbox object directly by flattening to `toolbox.tools` internally.
|
||||
|
||||
### Design decisions
|
||||
|
||||
**Instance methods, not `@staticmethod` factories.** Existing `get_code_interpreter_tool()` / `get_mcp_tool()` / etc. are `@staticmethod` because they're pure factories with no network I/O. Toolbox fetching requires the project client, so these new methods must be instance methods. This is a deliberate departure from the existing-factory pattern, justified by the async-with-I/O nature of the operation.
|
||||
|
||||
**Raw SDK type passthrough (no custom wrappers).** There is only one toolbox type in the Foundry SDK and maintaining a shadow wrapper would create alignment risk as the SDK evolves. The raw `ToolboxVersionObject` and `ToolboxObject` carry all the fields users need. Individual tools inside `toolbox.tools` are the same `azure.ai.projects.models.Tool` subclasses returned by other factory methods.
|
||||
|
||||
**Two-request default-version path.** When `version=None`, implementation calls `.get(name)` to find `default_version`, then `.get_version(name, default_version)` for the tools. Caching the default-version mapping was considered and rejected — default versions can change server-side via `update(default_version=...)`, and a stale cache would silently give callers the wrong tools. Two requests at agent setup is acceptable.
|
||||
|
||||
**No discovery/listing surface in MAF.** Discovery is intentionally left to the raw `azure-ai-projects` client. MAF does not currently expose project-resource listing surfaces for many other Foundry resources (deployments, vector stores, agents, etc.), so the toolbox design stays narrowly focused on explicit retrieval by name/version.
|
||||
|
||||
**Shared helpers in `_tools.py`.** The SDK-call helper function (`fetch_toolbox`) lives in a shared module so the chat-client surface stays thin and the request logic remains centralized.
|
||||
|
||||
**`tools=toolbox` convenience, not a new wrapper type.** Although `get_toolbox()` returns the raw `ToolboxVersionObject`, Agent Framework can still support `tools=toolbox` / `tools=[toolbox]` by flattening the toolbox's `.tools` internally. That matches existing SDK ergonomics where some higher-level objects can be placed directly in `tools=` and unpacked underneath, without introducing a public `FoundryToolbox` wrapper.
|
||||
|
||||
**Errors pass through unchanged.** `ResourceNotFoundError`, `HttpResponseError`, etc. from the SDK propagate as-is. No framework-specific exception hierarchy.
|
||||
|
||||
## E2E Code Samples
|
||||
|
||||
### Primary sample
|
||||
|
||||
New file: `samples/02-agents/providers/foundry/foundry_chat_client_with_toolbox.py`
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
client = FoundryChatClient(credential=AzureCliCredential())
|
||||
|
||||
toolbox = await client.get_toolbox("research_tools")
|
||||
print(f"Loaded toolbox {toolbox.name}@{toolbox.version} ({len(toolbox.tools)} tools)")
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a research assistant.",
|
||||
tools=toolbox,
|
||||
)
|
||||
|
||||
result = await agent.run("What are the latest developments in quantum error correction?")
|
||||
print(f"Result: {result}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### Version pinning
|
||||
|
||||
```python
|
||||
toolbox = await client.get_toolbox("research_tools", version="v3")
|
||||
```
|
||||
|
||||
### Combining multiple toolboxes
|
||||
|
||||
```python
|
||||
toolbox_a = await client.get_toolbox("research_tools")
|
||||
toolbox_b = await client.get_toolbox("some_other_tools", version="v3")
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="...",
|
||||
tools=[toolbox_a, toolbox_b],
|
||||
)
|
||||
```
|
||||
|
||||
### Combining toolbox tools with locally defined tools
|
||||
|
||||
```python
|
||||
toolbox = await client.get_toolbox("research_tools")
|
||||
|
||||
def get_internal_metrics(metric_name: str) -> dict:
|
||||
"""Custom tool that reads from an internal dashboard."""
|
||||
...
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="...",
|
||||
tools=[get_internal_metrics, toolbox],
|
||||
)
|
||||
```
|
||||
|
||||
### Selecting only some tools from a toolbox
|
||||
|
||||
Developers will not always want to pass the entire toolbox through unchanged. A
|
||||
small helper in the Foundry package provides local post-fetch selection without
|
||||
changing the raw return type of `get_toolbox()`.
|
||||
|
||||
```python
|
||||
from agent_framework.foundry import select_toolbox_tools
|
||||
|
||||
toolbox = await client.get_toolbox("research_tools")
|
||||
|
||||
selected_tools = select_toolbox_tools(
|
||||
toolbox,
|
||||
include_names=["githubmcp", "code_interpreter"],
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="Use only the selected toolbox tools.",
|
||||
tools=selected_tools,
|
||||
)
|
||||
```
|
||||
|
||||
Supported filters:
|
||||
|
||||
```python
|
||||
from agent_framework.foundry import FoundryHostedToolType, select_toolbox_tools
|
||||
|
||||
selected_tools = select_toolbox_tools(
|
||||
toolbox,
|
||||
include_types=["mcp", "code_interpreter"], # type: Collection[FoundryHostedToolType]
|
||||
exclude_names=["internal_admin_tool"],
|
||||
)
|
||||
```
|
||||
|
||||
Helper signature:
|
||||
|
||||
```python
|
||||
type FoundryHostedToolType = Literal[
|
||||
"code_interpreter",
|
||||
"file_search",
|
||||
"image_generation",
|
||||
"mcp",
|
||||
"web_search",
|
||||
] | str
|
||||
|
||||
def select_toolbox_tools(
|
||||
tools: ToolboxVersionObject | Sequence[Tool | dict[str, Any]],
|
||||
*,
|
||||
include_names: Collection[str] | None = None,
|
||||
exclude_names: Collection[str] | None = None,
|
||||
include_types: Collection[FoundryHostedToolType] | None = None,
|
||||
exclude_types: Collection[FoundryHostedToolType] | None = None,
|
||||
predicate: Callable[[Tool | dict[str, Any]], bool] | None = None,
|
||||
) -> list[Tool | dict[str, Any]]:
|
||||
...
|
||||
```
|
||||
|
||||
Normalized name precedence for `include_names` / `exclude_names`:
|
||||
|
||||
1. MCP `server_label`
|
||||
2. generic tool `name`
|
||||
3. fallback tool `type`
|
||||
|
||||
This keeps `get_toolbox()` as a thin fetch API and makes selection an explicit,
|
||||
local post-processing step, while still allowing the ergonomic
|
||||
`select_toolbox_tools(toolbox, ...)` call shape.
|
||||
|
||||
## Native vs MCP consumption of a Foundry toolbox
|
||||
|
||||
A Foundry toolbox can be consumed two ways. This design adds new implementation work only for the first:
|
||||
|
||||
1. **Native consumption (in scope).** Tools execute inside Foundry's agent runtime. `get_toolbox()` returns the `ToolboxVersionObject` whose `.tools` attribute carries typed tool configs that the runtime interprets server-side. This design is specifically for `FoundryChatClient`-backed local agent composition.
|
||||
|
||||
2. **MCP consumption (already supported through existing MCP abstractions).** A Foundry toolbox can also be exposed as an MCP server. In that case, use the existing `MCPStreamableHTTPTool(name=..., url=...)` — it already handles this path with any chat client (Foundry, OpenAI, Anthropic, etc.). No new Foundry-specific API is needed for MCP-exposed toolboxes in this design.
|
||||
|
||||
### MCPStreamableHTTPTool example for a Foundry toolbox endpoint
|
||||
|
||||
If Foundry gives you an MCP endpoint for the toolbox (for example from the
|
||||
toolbox details UI / endpoint surface), the existing MCP client path is:
|
||||
|
||||
```python
|
||||
from agent_framework import Agent, MCPStreamableHTTPTool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
|
||||
toolbox_mcp = MCPStreamableHTTPTool(
|
||||
name="research_tools",
|
||||
url="https://<foundry-toolbox-mcp-endpoint>",
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a research assistant.",
|
||||
tools=[toolbox_mcp],
|
||||
)
|
||||
```
|
||||
|
||||
This is a different integration shape than `get_toolbox(...).tools`:
|
||||
|
||||
- `get_toolbox(...).tools` = **native Foundry hosted-tool configs** interpreted by the
|
||||
Foundry runtime
|
||||
- `MCPStreamableHTTPTool(name=..., url=...)` = **live MCP server connection** to a
|
||||
toolbox endpoint
|
||||
|
||||
The design in this spec adds first-class support only for the native hosted-tool
|
||||
path. The MCP path is already served by the framework's existing MCP abstractions.
|
||||
|
||||
These paths are not unified because they have fundamentally different execution models. Native toolbox tools are declarative configs the Foundry runtime executes; MCP consumption is a live wire protocol to a running server.
|
||||
|
||||
**MCP authentication inside a toolbox** is handled server-side via `project_connection_id` on individual `MCPTool` entries (OAuth connection objects configured in the Foundry project). The client never holds bearer tokens. Consent flow handling (`CONSENT_REQUIRED` → user-visible consent URL) happens during `agent.run()`, not during toolbox fetching — see Non-goals.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Unit tests in `packages/foundry/tests/test_toolbox.py` with mocked `project_client.beta.toolboxes`. A single opt-in live round-trip, `test_integration_get_toolbox_round_trip_against_real_project`, is marked `@pytest.mark.integration`; it is skipped by default and only runs when the required Foundry credentials are available.
|
||||
|
||||
Coverage:
|
||||
|
||||
- `get_toolbox(name, version="v3")` — explicit version, single request. Assert `.get` not called, `.get_version` awaited once, returns `ToolboxVersionObject`.
|
||||
- `get_toolbox(name)` — default-version resolution. Assert `.get` then `.get_version` called in order with correct args.
|
||||
- Error propagation — `ResourceNotFoundError` from `.get` propagates unchanged.
|
||||
- Tool passthrough — heterogeneous tool list (`CodeInterpreterTool`, `MCPTool(project_connection_id=...)`) passes through unchanged. Asserts `project_connection_id` survives.
|
||||
- Agent integration smoke — `tools=toolbox` / `tools=[toolbox]` flatten to the underlying toolbox tools.
|
||||
- Multiple toolbox composition smoke — `tools=[toolbox_a, toolbox_b]` flattens into a single agent tool list.
|
||||
- `get_toolbox_tool_name()` — selection-name precedence is MCP `server_label`, then `name`, then `type`.
|
||||
- `select_toolbox_tools(toolbox, include_names=...)` — selects by normalized tool names directly from a fetched toolbox object.
|
||||
- `select_toolbox_tools(toolbox, include_types=...)` — selects by tool types with `Literal`-guided IDE completion.
|
||||
- `select_toolbox_tools(..., exclude_names=..., predicate=...)` — supports exclusion + custom predicates.
|
||||
|
||||
Deliberately **not** covered:
|
||||
- Runtime consent-flow handling for OAuth MCP tools (see Non-goals).
|
||||
- Toolbox discovery/listing (`list_toolboxes`, `list_toolbox_versions`) — deliberately left to the raw Azure SDK.
|
||||
- Full CRUD (`create_version`, `update`, `delete`) and server-side agent authoring — see Non-goals.
|
||||
|
||||
Live Foundry API integration is exercised only through the opt-in `@pytest.mark.integration` round-trip noted above; it is not part of the default test run.
|
||||
|
||||
## Framework dependency: `normalize_tools` flattening
|
||||
|
||||
The core `normalize_tools` function in `packages/core/agent_framework/_tools.py` already supports flattening composite tool inputs. Toolbox support extends that behavior so a fetched `ToolboxVersionObject` is treated as a composite tool source and flattened to its `.tools`.
|
||||
|
||||
That enables:
|
||||
|
||||
- `tools=toolbox`
|
||||
- `tools=[toolbox]`
|
||||
- `tools=[local_tool, toolbox]`
|
||||
- `tools=[toolbox_a, toolbox_b]`
|
||||
|
||||
while still keeping `select_toolbox_tools(toolbox.tools, ...)` available for partial selection before the final agent construction step.
|
||||
|
||||
## Telemetry
|
||||
|
||||
Telemetry for toolbox support has two separate goals:
|
||||
|
||||
1. **Observe toolbox API access** — `get_toolbox()`
|
||||
2. **Observe toolbox usage during agent runs** — when users pass toolbox-derived tools into `Agent(..., tools=...)`
|
||||
|
||||
### Request telemetry for toolbox API access
|
||||
|
||||
When Agent Framework constructs the `AIProjectClient` internally for `FoundryChatClient`, it already sets:
|
||||
|
||||
```python
|
||||
user_agent=AGENT_FRAMEWORK_USER_AGENT
|
||||
```
|
||||
|
||||
That means toolbox API requests made through:
|
||||
|
||||
- `project_client.beta.toolboxes.get(...)`
|
||||
- `project_client.beta.toolboxes.get_version(...)`
|
||||
|
||||
carry the standard MAF user-agent marker and can be queried in backend request logs the same way as other Foundry SDK calls made through framework-owned clients.
|
||||
|
||||
Important constraint: if the caller passes an already-constructed `project_client`, Agent Framework does **not** mutate it to inject the MAF user-agent. In that case, toolbox API request telemetry reflects whatever user-agent behavior that external client was configured with.
|
||||
|
||||
### Runtime telemetry for toolbox usage on agent runs
|
||||
|
||||
Tool-level telemetry already captures which hosted Foundry tools are available / invoked during agent execution. The remaining gap is **toolbox provenance**: once the user writes `tools=toolbox` (or otherwise flattens the toolbox into tool configs), the framework sees only raw tool configs and no longer knows which toolbox name/version supplied them.
|
||||
|
||||
The design for closing the **client-side** observability gap is **internal provenance tracking**, not user-supplied metadata and not a new public wrapper type.
|
||||
|
||||
#### Provenance model
|
||||
|
||||
Note: this section is still under investigation.
|
||||
|
||||
When `get_toolbox()` or `list_toolbox_versions()` returns a `ToolboxVersionObject`, Agent Framework will attach private provenance metadata to:
|
||||
|
||||
- the returned toolbox object
|
||||
- each tool inside `toolbox.tools`
|
||||
|
||||
Recommended shape (private, internal-only):
|
||||
|
||||
```python
|
||||
tool._maf_toolbox_sources = [
|
||||
{
|
||||
"id": toolbox.id,
|
||||
"name": toolbox.name,
|
||||
"version": toolbox.version,
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Key properties of this approach:
|
||||
|
||||
- **No new public API surface** — users still work with raw `ToolboxVersionObject` / `ToolboxObject`
|
||||
- **No user burden** — callers do not need to stamp metadata manually
|
||||
- **Provenance follows the tool objects** — works with:
|
||||
- `tools=toolbox.tools`
|
||||
- `tools=[toolbox_a.tools, toolbox_b.tools]`
|
||||
- `tools=[*toolbox_a.tools, *toolbox_b.tools]`
|
||||
- **Private attributes are not serialized** into the actual request payload sent to the model/service, so this metadata does not leak into the tool definition body
|
||||
|
||||
This is intentionally preferred over introducing a new public `FoundryToolbox` wrapper purely for telemetry, and preferred over a separate global provenance registry. The provenance lives on the existing tool objects so list-copying and chat-option merging naturally preserve it.
|
||||
|
||||
#### Span enrichment
|
||||
|
||||
When Agent / chat telemetry computes span attributes for a run, it should inspect the final tool list and aggregate the private toolbox provenance from any tool objects that carry it. The aggregated values are then emitted as attributes on the existing run/chat spans.
|
||||
|
||||
Suggested custom attributes:
|
||||
|
||||
- `agent_framework.foundry.toolbox.ids`
|
||||
- `agent_framework.foundry.toolbox.names`
|
||||
- `agent_framework.foundry.toolbox.versions`
|
||||
- or a single compact attribute such as `agent_framework.foundry.toolbox.sources=["research_tools@1","some_other_tools@3"]`
|
||||
|
||||
The single compact `toolbox.sources` form is preferred for initial implementation because it is easy to query and easy to render from combined tool lists.
|
||||
|
||||
#### Scope of telemetry changes
|
||||
|
||||
This design does **not** require new spans. It enriches existing telemetry:
|
||||
|
||||
- toolbox API access continues to rely on request logs + Azure SDK distributed tracing + MAF user-agent
|
||||
- agent/chat execution spans gain toolbox provenance attributes when toolbox-derived tools are present
|
||||
|
||||
Implementation-wise, this design most likely touches:
|
||||
|
||||
- `packages/foundry/agent_framework_foundry/_tools.py` — to stamp provenance on fetched toolbox objects / tools
|
||||
- `packages/core/agent_framework/observability.py` — to aggregate provenance into span attributes
|
||||
|
||||
#### Important limitation: no server-side toolbox telemetry solution yet
|
||||
|
||||
Private provenance attached to tool objects is only useful on the client side. It
|
||||
does **not** go over the wire to the Foundry service because those private fields
|
||||
are intentionally not serialized into the request payload.
|
||||
|
||||
That means this design can support:
|
||||
|
||||
- local OpenTelemetry / exporter spans emitted by Agent Framework
|
||||
- local attribution of a run to one or more fetched toolboxes
|
||||
|
||||
but it does **not** solve:
|
||||
|
||||
- server-side request-log attribution of a model/tool run back to a toolbox
|
||||
- backend/database queries that need the service itself to know "this tool came from toolbox X"
|
||||
|
||||
At the moment, we do not have a satisfactory design for server-side toolbox
|
||||
telemetry. The service would require additional structured information on the
|
||||
request, and there is no accepted mechanism in this design yet for projecting
|
||||
toolbox provenance into a server-visible field/header/metadata shape.
|
||||
|
||||
So the telemetry story in this spec is explicitly limited to **client-side
|
||||
toolbox telemetry**. Server-side toolbox attribution remains an open question and
|
||||
requires either:
|
||||
|
||||
- new service/API support, or
|
||||
- a later framework design for emitting additional server-visible request metadata.
|
||||
|
||||
#### Deliberate non-goals for telemetry
|
||||
|
||||
- No requirement for users to pass explicit toolbox metadata in `default_options["metadata"]` or `run(..., options=...)`
|
||||
- No new public `FoundryToolbox` wrapper type just to preserve attribution
|
||||
- No attempted server-side attribution mechanism in this design (for example a custom request header or request metadata field) until there is a validated end-to-end contract for it
|
||||
|
||||
## Non-goals / Future Work
|
||||
|
||||
Explicitly out of scope for this design. Each is a separate design and PR when needed.
|
||||
|
||||
1. **Create/update/delete toolboxes from code.** CRUD is rare in agent consumption flows. Users who need it drop to `client.project_client.beta.toolboxes.create_version(...)`, `.update(...)`, `.delete(...)` directly.
|
||||
|
||||
2. **Server-side agent authoring from toolbox.** Creating a `PromptAgentDefinition(tools=toolbox.tools)` + `client.agents.create_version(...)` is a future feature covering agent authoring from code. The toolbox read API provides the building blocks; the authoring helpers are a separate design.
|
||||
|
||||
3. **OAuth consent-flow runtime handling.** When a toolbox contains MCP tools with `project_connection_id` pointing to an OAuth connection, the runtime may return `CONSENT_REQUIRED` mid-run. This is a runtime concern separate from toolbox fetching.
|
||||
|
||||
4. **Live integration tests.** This PR ships unit tests only.
|
||||
|
||||
5. **Toolbox caching or refresh APIs.** Each `get_toolbox()` call hits the network. Users who want caching wrap the call themselves.
|
||||
@@ -1,625 +0,0 @@
|
||||
# CodeAct .NET implementation
|
||||
|
||||
This document describes the .NET realization of the CodeAct design in
|
||||
[`docs/decisions/0024-codeact-integration.md`](../../decisions/0024-codeact-integration.md).
|
||||
|
||||
This document is intentionally focused on the .NET design and public API surface.
|
||||
The initial public .NET type described here is `HyperlightCodeActProvider`. Future .NET backends, such as Monty, should follow the same conceptual model with their own concrete provider types rather than through a public abstract base class or a public executor parameter.
|
||||
|
||||
## What is the goal of this feature?
|
||||
|
||||
Goals:
|
||||
- .NET developers can enable CodeAct through an `AIContextProvider`-based integration.
|
||||
- Developers can configure a provider-owned CodeAct tool set that is separate from the agent's direct tool surface.
|
||||
- Developers can use the same `execute_code` concept for both tool-enabled CodeAct and a standard code interpreter tool implementation.
|
||||
- Developers can swap execution backends over time, starting with Hyperlight while keeping room for alternatives.
|
||||
- Developers can configure execution capabilities such as workspace mounts and outbound network allow lists in a portable way.
|
||||
|
||||
Success Metric:
|
||||
- .NET samples exist for both a tool-enabled CodeAct mode and a standard interpreter mode.
|
||||
|
||||
Implementation-free outcome:
|
||||
- A .NET developer can attach a backend-specific CodeAct provider, choose which tools are available inside CodeAct, and configure execution capabilities without rewriting the function invocation loop or ChatClient pipeline.
|
||||
|
||||
## What is the problem being solved?
|
||||
|
||||
The cross-SDK problem statement and decision rationale live in the [ADR](../../decisions/0024-codeact-integration.md). The items below narrow that statement to .NET-specific design concerns:
|
||||
|
||||
- Today, the easiest way to prototype CodeAct in .NET is to manually configure an `AIFunction` and wire instructions — this is fragile and requires understanding internal sandbox lifecycle details.
|
||||
- There is no first-class .NET design that simultaneously covers Hyperlight-backed CodeAct now, future backend-specific providers, and both tool-enabled and interpreter modes.
|
||||
- Sandbox capabilities such as mounted file access and outbound network access need a portable configuration model instead of ad hoc backend-specific wiring.
|
||||
- Approval behavior needs to be explicit and configurable, mapping to .NET's existing `ApprovalRequiredAIFunction` wrapper mechanism.
|
||||
|
||||
## API Changes
|
||||
|
||||
### CodeAct contract
|
||||
|
||||
#### Terminology
|
||||
|
||||
- **CodeAct** is the primary term.
|
||||
- `execute_code` is the model-facing tool name used by the initial .NET provider in this spec.
|
||||
- Tool-enabled versus interpreter behavior is derived from the presence of CodeAct-managed tools, not from a separate public profile object.
|
||||
|
||||
#### Provider-owned CodeAct tool registry
|
||||
|
||||
A concrete .NET CodeAct provider owns the set of tools available through `call_tool(...)` inside CodeAct.
|
||||
|
||||
Rules:
|
||||
- Only tools explicitly configured on the concrete provider instance are available inside CodeAct.
|
||||
- The provider must not infer its CodeAct-managed tool set from the agent's direct tool configuration (`ChatClientAgentOptions.Tools` or `AIContext.Tools`).
|
||||
- Exclusive versus mixed behavior is achieved by where tools are configured, not by rewriting the agent's direct tool list.
|
||||
|
||||
Implications:
|
||||
- **CodeAct-only tool**: configured on the concrete CodeAct provider only.
|
||||
- **Direct-only tool**: configured on the agent only.
|
||||
- **Tool available both ways**: configured on both the agent and the concrete CodeAct provider.
|
||||
|
||||
#### Managing tools and capabilities after provider construction
|
||||
|
||||
There is no separate runtime setup object in the .NET design. CodeAct tools, file mounts, and outbound network allow-list state are managed directly on the provider through CRUD-style registry methods.
|
||||
|
||||
Preferred pattern:
|
||||
- `AddTools(params AIFunction[] tools) -> void`
|
||||
- `GetTools() -> IReadOnlyList<AIFunction>`
|
||||
- `RemoveTools(params string[] names) -> void`
|
||||
- `ClearTools() -> void`
|
||||
- `AddFileMounts(params FileMount[] mounts) -> void`
|
||||
- `GetFileMounts() -> IReadOnlyList<FileMount>`
|
||||
- `RemoveFileMounts(params string[] mountPaths) -> void`
|
||||
- `ClearFileMounts() -> void`
|
||||
- `AddAllowedDomains(params AllowedDomain[] domains) -> void`
|
||||
- `GetAllowedDomains() -> IReadOnlyList<AllowedDomain>`
|
||||
- `RemoveAllowedDomains(params string[] targets) -> void`
|
||||
- `ClearAllowedDomains() -> void`
|
||||
|
||||
Requirements:
|
||||
- The provider-owned CodeAct tool registry is keyed by tool name (from `AIFunction.Name`).
|
||||
- `AddTools(...)` adds new tools and replaces an existing provider-owned registration when the same tool name is added again.
|
||||
- `GetTools()` returns the provider's current configured CodeAct tool registry.
|
||||
- `RemoveTools(...)` removes provider-owned CodeAct tools by name.
|
||||
- `ClearTools()` removes all provider-owned CodeAct tools.
|
||||
- File mounts are keyed by sandbox mount path.
|
||||
- `AddFileMounts(...)` adds new file mounts and replaces an existing mount when the same mount path is added again.
|
||||
- `GetFileMounts()` returns the provider's current configured file mounts.
|
||||
- `RemoveFileMounts(...)` removes file mounts by mount path.
|
||||
- `ClearFileMounts()` removes all configured file mounts.
|
||||
- Allowed domains are keyed by normalized target string.
|
||||
- `AddAllowedDomains(...)` adds allow-list entries and replaces an existing entry when the same target is added again.
|
||||
- `GetAllowedDomains()` returns the current outbound allow-list entries.
|
||||
- `RemoveAllowedDomains(...)` removes allow-list entries by target.
|
||||
- `ClearAllowedDomains()` removes all configured allow-list entries.
|
||||
- Tool, file-mount, and network-allow-list mutations affect subsequent runs only; runs already in progress keep the snapshot captured at run start.
|
||||
- The provider must snapshot its effective tool registry and capability state at the start of each run so concurrent execution remains deterministic.
|
||||
|
||||
#### Approval model
|
||||
|
||||
The initial .NET design follows the ADR's bundled approval decision and maps to the existing `ApprovalRequiredAIFunction` wrapper from `Microsoft.Extensions.AI.Abstractions`:
|
||||
|
||||
- The provider exposes a default `ApprovalMode` for `execute_code` (enum: `CodeActApprovalMode.AlwaysRequire` / `CodeActApprovalMode.NeverRequire`).
|
||||
|
||||
Effective `execute_code` approval is computed as follows:
|
||||
|
||||
- If the provider default is `AlwaysRequire`, `execute_code` requires approval.
|
||||
- If the provider default is `NeverRequire`, the provider evaluates the provider-owned CodeAct tool registry snapshot for that run.
|
||||
- If every provider-owned CodeAct tool in that snapshot is not an `ApprovalRequiredAIFunction`, `execute_code` does not require approval.
|
||||
- If any provider-owned CodeAct tool in that snapshot is an `ApprovalRequiredAIFunction`, `execute_code` requires approval, even if the generated code may not call that tool.
|
||||
- When the effective approval resolves to `AlwaysRequire`, the generated `execute_code` function is wrapped in `ApprovalRequiredAIFunction` before being added to the `AIContext.Tools`.
|
||||
- Provider-owned tool calls made through `call_tool(...)` during that execution run use the approval already determined for `execute_code`.
|
||||
- Direct-only agent tools are excluded from this calculation.
|
||||
- File and network capabilities do not create a separate runtime approval check in the initial model; configuring them on the provider is itself the approval for those capabilities.
|
||||
|
||||
This is intentionally conservative and matches the shape of the existing .NET function-tool approval flow, where `ApprovalRequiredAIFunction` signals to the `ChatClientAgent` that user approval is needed before invocation.
|
||||
|
||||
#### Shared execution flow
|
||||
|
||||
On each run:
|
||||
1. `ProvideAIContextAsync(...)` snapshots the current CodeAct-managed tool registry and capability settings.
|
||||
2. Computes the effective approval requirement for `execute_code` from the provider default plus the snapshotted tool registry.
|
||||
3. Builds provider-defined instructions.
|
||||
4. Builds a run-scoped `execute_code` `AIFunction` from the snapshot (optionally wrapped in `ApprovalRequiredAIFunction`).
|
||||
5. Returns an `AIContext` containing the instructions and `execute_code` tool.
|
||||
6. When `execute_code` is invoked by the model, the run-scoped function creates or reuses an execution environment.
|
||||
7. If the current provider mode exposes host tools, `call_tool(...)` is bound only to the provider-owned tool registry snapshot.
|
||||
8. Code is executed and results converted to a JSON result string.
|
||||
|
||||
Caching rules:
|
||||
- The Hyperlight backend supports snapshots: the provider caches a reusable clean snapshot after the first sandbox initialization.
|
||||
- No mutable per-run execution state may be shared across concurrent runs.
|
||||
- In-memory interpreter state does not persist across separate `execute_code` calls.
|
||||
- Configured workspace files, mounted files, and any writable artifact/output area are the supported persistence mechanism across calls when the backend exposes them.
|
||||
|
||||
### .NET public API
|
||||
|
||||
#### Core types
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Represents a host-to-sandbox file mount configuration.
|
||||
/// </summary>
|
||||
/// <param name="HostPath">Absolute or relative path on the host filesystem.</param>
|
||||
/// <param name="MountPath">Path inside the sandbox (e.g. "/input/data.csv").</param>
|
||||
public sealed record FileMount(string HostPath, string MountPath);
|
||||
|
||||
/// <summary>
|
||||
/// Represents an outbound network allow-list entry.
|
||||
/// </summary>
|
||||
/// <param name="Target">URL or domain (e.g. "https://api.github.com").</param>
|
||||
/// <param name="Methods">
|
||||
/// Optional HTTP methods to allow (e.g. ["GET", "POST"]).
|
||||
/// Null allows all methods supported by the backend.
|
||||
/// </param>
|
||||
public sealed record AllowedDomain(string Target, IReadOnlyList<string>? Methods = null);
|
||||
|
||||
/// <summary>
|
||||
/// Controls the approval behavior for execute_code invocations.
|
||||
/// </summary>
|
||||
public enum CodeActApprovalMode
|
||||
{
|
||||
/// <summary>execute_code always requires user approval.</summary>
|
||||
AlwaysRequire,
|
||||
|
||||
/// <summary>
|
||||
/// Approval is derived from the provider-owned tool registry:
|
||||
/// if any tool is an ApprovalRequiredAIFunction, execute_code requires approval.
|
||||
/// </summary>
|
||||
NeverRequire,
|
||||
}
|
||||
```
|
||||
|
||||
#### HyperlightCodeActProvider
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// An AIContextProvider that enables CodeAct execution through the
|
||||
/// Hyperlight sandbox backend.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This provider injects an <c>execute_code</c> tool into the model-facing
|
||||
/// tool surface and builds CodeAct guidance instructions. Guest code executed
|
||||
/// through <c>execute_code</c> runs in an isolated Hyperlight sandbox with
|
||||
/// snapshot/restore for clean state per invocation.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If no CodeAct-managed tools are configured, the provider uses
|
||||
/// interpreter-style behavior. If one or more CodeAct-managed tools are
|
||||
/// configured, the provider uses tool-enabled behavior and exposes
|
||||
/// <c>call_tool(...)</c> inside the sandbox bound to the configured tools.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class HyperlightCodeActProvider : AIContextProvider, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new HyperlightCodeActProvider.
|
||||
/// </summary>
|
||||
/// <param name="options">Configuration options for the provider.</param>
|
||||
public HyperlightCodeActProvider(HyperlightCodeActProviderOptions options);
|
||||
|
||||
// ----- Tool registry -----
|
||||
|
||||
/// <summary>Adds tools to the provider-owned CodeAct tool registry.</summary>
|
||||
public void AddTools(params AIFunction[] tools);
|
||||
|
||||
/// <summary>Returns the current CodeAct-managed tools.</summary>
|
||||
public IReadOnlyList<AIFunction> GetTools();
|
||||
|
||||
/// <summary>Removes tools by name from the CodeAct tool registry.</summary>
|
||||
public void RemoveTools(params string[] names);
|
||||
|
||||
/// <summary>Removes all CodeAct-managed tools.</summary>
|
||||
public void ClearTools();
|
||||
|
||||
// ----- File mounts -----
|
||||
|
||||
/// <summary>Adds file mount configurations.</summary>
|
||||
public void AddFileMounts(params FileMount[] mounts);
|
||||
|
||||
/// <summary>Returns the current file mount configurations.</summary>
|
||||
public IReadOnlyList<FileMount> GetFileMounts();
|
||||
|
||||
/// <summary>Removes file mounts by sandbox mount path.</summary>
|
||||
public void RemoveFileMounts(params string[] mountPaths);
|
||||
|
||||
/// <summary>Removes all file mount configurations.</summary>
|
||||
public void ClearFileMounts();
|
||||
|
||||
// ----- Network allow-list -----
|
||||
|
||||
/// <summary>Adds outbound network allow-list entries.</summary>
|
||||
public void AddAllowedDomains(params AllowedDomain[] domains);
|
||||
|
||||
/// <summary>Returns the current outbound allow-list entries.</summary>
|
||||
public IReadOnlyList<AllowedDomain> GetAllowedDomains();
|
||||
|
||||
/// <summary>Removes allow-list entries by target.</summary>
|
||||
public void RemoveAllowedDomains(params string[] targets);
|
||||
|
||||
/// <summary>Removes all outbound allow-list entries.</summary>
|
||||
public void ClearAllowedDomains();
|
||||
|
||||
// ----- Lifecycle -----
|
||||
|
||||
/// <summary>Releases the sandbox and all associated native resources.</summary>
|
||||
public void Dispose();
|
||||
}
|
||||
```
|
||||
|
||||
#### HyperlightCodeActProviderOptions
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Configuration options for <see cref="HyperlightCodeActProvider"/>.
|
||||
/// </summary>
|
||||
public sealed class HyperlightCodeActProviderOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// The sandbox backend to use. Default is <c>Wasm</c>.
|
||||
/// </summary>
|
||||
public SandboxBackend Backend { get; set; } = SandboxBackend.Wasm;
|
||||
|
||||
/// <summary>
|
||||
/// Path to the guest module (.wasm or .aot file).
|
||||
/// Required for the Wasm backend; not needed for JavaScript.
|
||||
/// When null, the provider attempts to locate the default packaged
|
||||
/// Python guest module.
|
||||
/// </summary>
|
||||
public string? ModulePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Guest heap size. Accepts human-readable strings ("50Mi", "2Gi")
|
||||
/// or raw byte values. Null uses the backend default.
|
||||
/// </summary>
|
||||
public string? HeapSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Guest stack size. Accepts human-readable strings ("35Mi")
|
||||
/// or raw byte values. Null uses the backend default.
|
||||
/// </summary>
|
||||
public string? StackSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initial set of CodeAct-managed tools available inside the sandbox.
|
||||
/// </summary>
|
||||
public IEnumerable<AIFunction>? Tools { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default approval mode for the execute_code tool.
|
||||
/// Default is <see cref="CodeActApprovalMode.NeverRequire"/>.
|
||||
/// </summary>
|
||||
public CodeActApprovalMode ApprovalMode { get; set; } = CodeActApprovalMode.NeverRequire;
|
||||
|
||||
/// <summary>
|
||||
/// Optional workspace root directory on the host.
|
||||
/// When set, it is exposed as the sandbox's input directory.
|
||||
/// </summary>
|
||||
public string? WorkspaceRoot { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initial file mount configurations.
|
||||
/// </summary>
|
||||
public IEnumerable<FileMount>? FileMounts { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initial outbound network allow-list entries.
|
||||
/// </summary>
|
||||
public IEnumerable<AllowedDomain>? AllowedDomains { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// State key used to store provider state in AgentSession.StateBag.
|
||||
/// Defaults to "HyperlightCodeActProvider". Override when using
|
||||
/// multiple provider instances on the same agent.
|
||||
/// </summary>
|
||||
public string? StateKey { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
#### Provider implementation contract
|
||||
|
||||
The concrete provider plugs into the existing .NET `AIContextProvider` surface from `Microsoft.Agents.AI.Abstractions`.
|
||||
|
||||
Required override:
|
||||
- `ProvideAIContextAsync(InvokingContext, CancellationToken) -> ValueTask<AIContext>`
|
||||
|
||||
`ProvideAIContextAsync(...)` is responsible for:
|
||||
- snapshotting the current CodeAct-managed tool registry and capability settings for the run,
|
||||
- computing the effective approval requirement for `execute_code` from the provider default and the snapshotted tool registry,
|
||||
- building a short CodeAct guidance instruction string,
|
||||
- building a run-scoped `execute_code` `AIFunction` from the snapshot,
|
||||
- optionally wrapping it in `ApprovalRequiredAIFunction` when approval is required,
|
||||
- and returning an `AIContext` with `Instructions` and `Tools` set.
|
||||
|
||||
These steps run on every invocation rather than once at construction time because the provider supports CRUD mutations between runs, concurrent runs need independent snapshots, and the effective approval and instructions depend on the tool registry state captured at run start.
|
||||
|
||||
The provider overrides `StateKeys` to return the configured `StateKey` from options, enabling multiple provider instances on the same agent without key collisions.
|
||||
|
||||
Mutating the provider after `ProvideAIContextAsync(...)` has captured a run-scoped snapshot is allowed, but it affects subsequent runs only. Provider implementations synchronize state capture and CRUD operations so shared provider instances remain safe across concurrent runs.
|
||||
|
||||
#### AIFunction-to-sandbox tool bridging
|
||||
|
||||
The Hyperlight sandbox's `RegisterTool(name, Func<string, string>)` accepts a synchronous JSON-in / JSON-out delegate. Provider-owned CodeAct tools are `AIFunction` instances that are async and cancellation-aware.
|
||||
|
||||
Bridging strategy:
|
||||
- At sandbox initialization time, the provider registers each CodeAct-managed tool with the sandbox using the raw JSON overload: `RegisterTool(name, Func<string, string>)`.
|
||||
- When the sandbox guest calls `call_tool("name", ...)`, the bridge delegate:
|
||||
1. Deserializes the JSON arguments.
|
||||
2. Invokes `AIFunction.InvokeAsync(...)` synchronously (via `GetAwaiter().GetResult()`) since the sandbox FFI callback is inherently synchronous.
|
||||
3. Serializes the result back to JSON.
|
||||
- This sync-over-async bridge is a known pragmatic trade-off constrained by the Hyperlight FFI boundary. It is safe because:
|
||||
- Sandbox execution already runs on the thread pool (via `Task.Run`).
|
||||
- The FFI callback runs on a worker thread with no synchronization context.
|
||||
- If the Hyperlight .NET SDK later adds async tool registration, the bridge should migrate to that.
|
||||
|
||||
#### Runtime behavior
|
||||
|
||||
- `ProvideAIContextAsync(...)` adds a short CodeAct guidance block through `AIContext.Instructions`.
|
||||
- `ProvideAIContextAsync(...)` adds `execute_code` through `AIContext.Tools`.
|
||||
- The detailed `call_tool(...)`, sandbox-tool, and capability guidance is carried by the `execute_code` function's `Description`.
|
||||
- `execute_code` invokes the configured Hyperlight sandbox guest.
|
||||
- If the current CodeAct tool registry snapshot is non-empty, the runtime injects `call_tool(...)` bound to the provider-owned tool registry.
|
||||
- The provider does not inspect or mutate the agent's `ChatClientAgentOptions.Tools` or the incoming `AIContext.Tools` to determine its CodeAct tool set.
|
||||
- The provider snapshots the current CodeAct tool registry and capability state at run start, so later registry and allow-list mutations only affect future runs.
|
||||
- Interpreter versus tool-enabled behavior is derived from the presence of CodeAct-managed tools.
|
||||
- `execute_code` is traced like a normal tool invocation within the surrounding agent run.
|
||||
|
||||
#### Backend integration
|
||||
|
||||
Initial public provider:
|
||||
- `HyperlightCodeActProvider`
|
||||
|
||||
Backend-specific notes:
|
||||
- **Hyperlight**
|
||||
- The provider internally creates a `SandboxBuilder` from the options and uses the `Sandbox` API from `HyperlightSandbox.Api`.
|
||||
- The provider uses snapshot/restore to ensure clean execution state per `execute_code` invocation: a "warm" snapshot is taken after the first no-op initialization run, and restored before each subsequent execution.
|
||||
- File access maps to Hyperlight Sandbox's `WithInputDir()` / `WithOutputDir()` / `WithTempOutput()` capability model.
|
||||
- Network access is denied by default and is enabled through `Sandbox.AllowDomain(...)` per-target allow-list entries.
|
||||
- Guest module resolution: if `ModulePath` is null for the Wasm backend, the provider attempts to locate a packaged Python guest module (equivalent to the Python SDK's `python_guest.path` resolution).
|
||||
|
||||
#### Capability handling
|
||||
|
||||
Capabilities are first-class `HyperlightCodeActProviderOptions` properties and provider-managed CRUD surfaces:
|
||||
- `WorkspaceRoot`
|
||||
- `FileMounts`
|
||||
- `AllowedDomains`
|
||||
|
||||
Enabling access means:
|
||||
- Configuring `WorkspaceRoot` or any `FileMounts` enables the sandbox filesystem surface exposed through `/input` and `/output`.
|
||||
- Leaving both `WorkspaceRoot` and `FileMounts` unset means no filesystem surface is configured.
|
||||
- Adding any `AllowedDomains` entry enables outbound access only for the configured targets; leaving it empty means network access is disabled without a separate network mode flag.
|
||||
|
||||
Backends may implement stricter semantics than these top-level settings.
|
||||
|
||||
#### Execution output representation
|
||||
|
||||
Backend execution output maps to a JSON result string returned from the `execute_code` `AIFunction`:
|
||||
|
||||
```json
|
||||
{
|
||||
"stdout": "Hello world\n",
|
||||
"stderr": "",
|
||||
"exit_code": 0,
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
Execution failures should surface readable error text in the `stderr` field and a non-zero `exit_code`. Timeouts, out-of-memory conditions, backend crashes, and similar sandbox failures are all `execute_code` failures and should surface as structured error results. Partial textual or file outputs may be returned only when the backend can report them unambiguously.
|
||||
|
||||
#### `execute_code` input contract
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"description": "Code to execute using the provider's configured backend/runtime behavior."
|
||||
}
|
||||
},
|
||||
"required": ["code"]
|
||||
}
|
||||
```
|
||||
|
||||
#### Thread safety and concurrency
|
||||
|
||||
- All CRUD methods (`AddTools`, `RemoveTools`, `AddFileMounts`, etc.) are synchronized via an internal lock.
|
||||
- `ProvideAIContextAsync(...)` acquires the lock to snapshot current state, then releases it before building the run-scoped function. The run-scoped function closes over the immutable snapshot, not mutable provider state.
|
||||
- Concurrent `execute_code` invocations from different runs use independent sandbox instances or synchronized access to a shared sandbox with snapshot/restore.
|
||||
- Workspace directories (`WorkspaceRoot`, `FileMounts`) are external shared state: concurrent runs against the same workspace can race on files. This is the user's responsibility to manage (e.g., by using per-run output directories or separate provider instances).
|
||||
|
||||
### HyperlightExecuteCodeFunction
|
||||
|
||||
The provider package also exports a standalone `HyperlightExecuteCodeFunction` for direct-tool scenarios where a provider lifecycle is not needed. This is the .NET equivalent of the Python `HyperlightExecuteCodeTool`.
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// A standalone execute_code AIFunction backed by a Hyperlight sandbox.
|
||||
/// Use this for manual/static wiring when the AIContextProvider lifecycle
|
||||
/// is not needed.
|
||||
/// </summary>
|
||||
public sealed class HyperlightExecuteCodeFunction : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new standalone code execution function.
|
||||
/// </summary>
|
||||
/// <param name="options">Configuration options.</param>
|
||||
public HyperlightExecuteCodeFunction(HyperlightCodeActProviderOptions options);
|
||||
|
||||
/// <summary>
|
||||
/// Returns this as an AIFunction for direct registration on an agent.
|
||||
/// When approval is required, the returned function is wrapped in
|
||||
/// ApprovalRequiredAIFunction.
|
||||
/// </summary>
|
||||
public AIFunction AsAIFunction();
|
||||
|
||||
/// <summary>
|
||||
/// Builds a CodeAct instruction string describing the available
|
||||
/// tools and capabilities.
|
||||
/// </summary>
|
||||
/// <param name="toolsVisibleToModel">
|
||||
/// When false, the instructions include full tool descriptions
|
||||
/// (for use when tools are only accessible through CodeAct).
|
||||
/// When true, instructions are abbreviated (tools are already
|
||||
/// visible to the model as direct tools).
|
||||
/// </param>
|
||||
public string BuildInstructions(bool toolsVisibleToModel = false);
|
||||
|
||||
/// <summary>Releases sandbox resources.</summary>
|
||||
public void Dispose();
|
||||
}
|
||||
```
|
||||
|
||||
### Internal implementation structure
|
||||
|
||||
The provider and standalone function share internal helpers:
|
||||
|
||||
```
|
||||
Microsoft.Agents.AI.Hyperlight/
|
||||
├── HyperlightCodeActProvider.cs // AIContextProvider implementation
|
||||
├── HyperlightCodeActProviderOptions.cs // Options record
|
||||
├── HyperlightExecuteCodeFunction.cs // Standalone AIFunction for manual wiring
|
||||
├── FileMount.cs // File mount record
|
||||
├── AllowedDomain.cs // Network allow-list record
|
||||
├── CodeActApprovalMode.cs // Approval enum
|
||||
├── Internal/
|
||||
│ ├── SandboxExecutor.cs // Manages sandbox lifecycle, snapshot/restore
|
||||
│ ├── InstructionBuilder.cs // Builds CodeAct instruction strings
|
||||
│ └── ToolBridge.cs // AIFunction ↔ Sandbox.RegisterTool adapter
|
||||
```
|
||||
|
||||
`SandboxExecutor` encapsulates:
|
||||
- Creating and configuring a `Sandbox` from options.
|
||||
- Performing the initial no-op warm-up and snapshot.
|
||||
- Registering bridged tools via `ToolBridge`.
|
||||
- Restoring to the clean snapshot before each execution.
|
||||
- Translating `ExecutionResult` to a JSON string.
|
||||
|
||||
`InstructionBuilder` generates:
|
||||
- A short CodeAct guidance block for `AIContext.Instructions`.
|
||||
- A detailed `execute_code` description including `call_tool(...)` signatures and capability documentation.
|
||||
|
||||
`ToolBridge` handles:
|
||||
- Reflecting `AIFunction` metadata to build the sandbox tool registration.
|
||||
- The sync-over-async invocation bridge.
|
||||
|
||||
## E2E Code Samples
|
||||
|
||||
### Tool-enabled CodeAct mode
|
||||
|
||||
```csharp
|
||||
var fetchDocs = AIFunctionFactory.Create(FetchDocs, name: "fetch_docs");
|
||||
var queryData = AIFunctionFactory.Create(QueryData, name: "query_data");
|
||||
var lookupUser = AIFunctionFactory.Create(LookupUser, name: "lookup_user");
|
||||
|
||||
var codeact = new HyperlightCodeActProvider(new HyperlightCodeActProviderOptions
|
||||
{
|
||||
Tools = [fetchDocs, queryData],
|
||||
WorkspaceRoot = "./workdir",
|
||||
AllowedDomains = [new AllowedDomain("api.github.com", ["GET"])],
|
||||
});
|
||||
codeact.AddTools(lookupUser);
|
||||
|
||||
var sendEmail = AIFunctionFactory.Create(SendEmail, name: "send_email");
|
||||
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "You are a helpful assistant.",
|
||||
options: new ChatClientAgentOptions
|
||||
{
|
||||
Tools = [sendEmail], // direct-only tool
|
||||
AIContextProviders = [codeact],
|
||||
});
|
||||
|
||||
await using var session = await agent.CreateSessionAsync();
|
||||
var response = await agent.InvokeAsync("Analyze the latest docs", session);
|
||||
```
|
||||
|
||||
### Standard code interpreter mode
|
||||
|
||||
```csharp
|
||||
var codeact = new HyperlightCodeActProvider(new HyperlightCodeActProviderOptions
|
||||
{
|
||||
WorkspaceRoot = "./data",
|
||||
});
|
||||
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "You are a code interpreter.",
|
||||
options: new ChatClientAgentOptions
|
||||
{
|
||||
AIContextProviders = [codeact],
|
||||
});
|
||||
```
|
||||
|
||||
### Manual static wiring (no provider lifecycle)
|
||||
|
||||
When the tool registry and capability configuration are fixed, the provider lifecycle can be skipped entirely. Build the `execute_code` function and instructions once and pass them directly to the agent:
|
||||
|
||||
```csharp
|
||||
using var executeCode = new HyperlightExecuteCodeFunction(
|
||||
new HyperlightCodeActProviderOptions
|
||||
{
|
||||
Tools = [fetchDocs, queryData],
|
||||
WorkspaceRoot = "./workdir",
|
||||
AllowedDomains = [new AllowedDomain("api.github.com", ["GET"])],
|
||||
});
|
||||
|
||||
var codeactInstructions = executeCode.BuildInstructions(toolsVisibleToModel: false);
|
||||
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: $"You are a helpful assistant.\n\n{codeactInstructions}",
|
||||
options: new ChatClientAgentOptions
|
||||
{
|
||||
Tools = [sendEmail, executeCode.AsAIFunction()],
|
||||
});
|
||||
```
|
||||
|
||||
### With approval required
|
||||
|
||||
```csharp
|
||||
var sensitiveAction = new ApprovalRequiredAIFunction(
|
||||
AIFunctionFactory.Create(DeleteRecords, name: "delete_records"));
|
||||
|
||||
var codeact = new HyperlightCodeActProvider(new HyperlightCodeActProviderOptions
|
||||
{
|
||||
Tools = [fetchDocs, sensitiveAction], // sensitiveAction triggers approval
|
||||
});
|
||||
|
||||
// execute_code will be wrapped in ApprovalRequiredAIFunction because
|
||||
// at least one managed tool (delete_records) requires approval.
|
||||
var agent = chatClient.AsAIAgent(
|
||||
instructions: "You are a helpful assistant.",
|
||||
options: new ChatClientAgentOptions
|
||||
{
|
||||
AIContextProviders = [codeact],
|
||||
});
|
||||
```
|
||||
|
||||
## Relationship to hyperlight-sandbox .NET SDK
|
||||
|
||||
This design depends on the .NET SDK being added in [hyperlight-dev/hyperlight-sandbox#46](https://github.com/hyperlight-dev/hyperlight-sandbox/pull/46). Key types consumed from that SDK:
|
||||
|
||||
| hyperlight-sandbox type | Used for |
|
||||
|---|---|
|
||||
| `Sandbox` | Core sandbox lifecycle: `Run()`, `RegisterTool()`, `AllowDomain()`, `Snapshot()`, `Restore()` |
|
||||
| `SandboxBuilder` | Fluent sandbox construction from provider options |
|
||||
| `SandboxBackend` | Backend selection (Wasm, JavaScript) |
|
||||
| `ExecutionResult` | Capturing stdout, stderr, exit code from guest execution |
|
||||
| `SandboxSnapshot` | Checkpoint/restore for clean state per execution |
|
||||
|
||||
The provider package (`Microsoft.Agents.AI.Hyperlight`) takes a NuGet dependency on `Hyperlight.HyperlightSandbox.Api` and `Microsoft.Extensions.AI.Abstractions`. It does **not** depend on `HyperlightSandbox.Extensions.AI` (`CodeExecutionTool`) — the provider implements its own sandbox lifecycle management with run-scoped snapshots to support concurrent invocations safely.
|
||||
|
||||
## Package structure
|
||||
|
||||
The CodeAct Hyperlight provider ships as an optional NuGet package:
|
||||
- **Package**: `Microsoft.Agents.AI.Hyperlight`
|
||||
- **Dependencies**:
|
||||
- `Microsoft.Agents.AI.Abstractions` (for `AIContextProvider`, `AIContext`)
|
||||
- `Microsoft.Extensions.AI.Abstractions` (for `AIFunction`, `ApprovalRequiredAIFunction`)
|
||||
- `Hyperlight.HyperlightSandbox.Api` (for sandbox API)
|
||||
- **Target framework**: `net8.0`
|
||||
|
||||
This keeps CodeAct and its native sandbox dependencies optional — users who do not need CodeAct do not take on the Hyperlight installation and dependency footprint.
|
||||
|
||||
## Open questions
|
||||
|
||||
1. **Guest module distribution**: How should the default Python guest module (`.aot` file) be distributed for .NET consumers? Options include a separate NuGet package with native assets, a runtime download, or requiring users to build/provide their own.
|
||||
2. **Async tool registration**: If the Hyperlight .NET SDK adds async tool callback support in a future release, the sync-over-async bridge should be replaced. This is tracked as a known technical debt item.
|
||||
3. **Output file access**: The Hyperlight sandbox exposes `GetOutputFiles()` and `OutputPath` for retrieving files written by guest code. The initial design returns these as part of the JSON result. A future iteration could surface output files as framework-native content (e.g., `DataContent` or URI references).
|
||||
4. **Multiple sandbox instances for concurrency**: The current design uses synchronized access to a single sandbox with snapshot/restore. An alternative pooling strategy (one sandbox per concurrent run) could improve throughput at the cost of memory. This is deferred to implementation time.
|
||||
@@ -1,385 +0,0 @@
|
||||
# CodeAct Python implementation
|
||||
|
||||
This document describes the Python realization of the CodeAct design in
|
||||
[`docs/decisions/0024-codeact-integration.md`](../../decisions/0024-codeact-integration.md).
|
||||
|
||||
This document is intentionally focused on the Python design and public API surface.
|
||||
The initial public Python type described here is `HyperlightCodeActProvider`. Future Python backends, such as Monty, should follow the same conceptual model with their own concrete provider types rather than through a public abstract base class or a public executor parameter.
|
||||
|
||||
## What is the goal of this feature?
|
||||
|
||||
Goals:
|
||||
- Python developers can enable CodeAct through a `ContextProvider`-based integration.
|
||||
- Developers can configure a provider-owned CodeAct tool set that is separate from the agent's direct `tools=` surface.
|
||||
- Developers can use the same `execute_code` concept for both tool-enabled CodeAct and a standard code interpreter tool implementation.
|
||||
- Developers can swap execution backends over time, starting with Hyperlight while keeping room for alternatives such as Pydantic's Monty.
|
||||
- Developers can configure execution capabilities such as workspace mounts and outbound network allow lists in a portable way.
|
||||
|
||||
Success Metric:
|
||||
- Python samples exist for both a tool-enabled CodeAct mode and a standard interpreter mode.
|
||||
|
||||
Implementation-free outcome:
|
||||
- A Python developer can attach a backend-specific CodeAct provider, choose which tools are available inside CodeAct, and configure execution capabilities without rewriting the function invocation loop.
|
||||
|
||||
## What is the problem being solved?
|
||||
|
||||
The cross-SDK problem statement and decision rationale live in the [ADR](../../decisions/0024-codeact-integration.md). The items below narrow that statement to Python-specific design concerns:
|
||||
|
||||
- Today, the easiest way to prototype CodeAct is to infer or reshape the agent's direct tool surface, which is fragile and hard to reason about.
|
||||
- In Python, inferring a CodeAct tool surface from generic agent tool configuration is fragile and hard to reason about.
|
||||
- There is no first-class Python design that simultaneously covers Hyperlight-backed CodeAct now, future backend-specific providers such as Monty, and both tool-enabled and interpreter modes.
|
||||
- Sandbox capabilities such as mounted file access and outbound network access need a portable configuration model instead of ad hoc backend-specific wiring.
|
||||
- Approval behavior needs to be explicit and configurable, especially when CodeAct and direct tool calling may both be available.
|
||||
|
||||
## API Changes
|
||||
|
||||
### CodeAct contract
|
||||
|
||||
#### Terminology
|
||||
|
||||
- **CodeAct** is the primary term.
|
||||
- **Code mode**, **codemode**, and **programmatic tool calling** refer to the same concept in this document.
|
||||
- `execute_code` is the model-facing tool name used by the initial Python providers in this spec.
|
||||
|
||||
#### Provider-owned CodeAct tool registry
|
||||
|
||||
A concrete Python CodeAct provider owns the set of tools available through `call_tool(...)` inside CodeAct.
|
||||
|
||||
Rules:
|
||||
- Only tools explicitly configured on the concrete provider instance are available inside CodeAct.
|
||||
- The provider must not infer its CodeAct-managed tool set from the agent's direct `tools=` configuration.
|
||||
- Exclusive versus mixed behavior is achieved by where tools are configured, not by rewriting the agent's direct tool list.
|
||||
|
||||
Implications:
|
||||
- **CodeAct-only tool**: configured on the concrete CodeAct provider only.
|
||||
- **Direct-only tool**: configured on the agent only.
|
||||
- **Tool available both ways**: configured on both the agent and the concrete CodeAct provider.
|
||||
|
||||
#### Managing tools and capabilities after provider construction
|
||||
|
||||
There is no separate runtime setup object in the Python design. CodeAct tools, file mounts, and outbound network allow-list state are managed directly on the provider through CRUD-style registry methods.
|
||||
|
||||
Preferred pattern:
|
||||
- `add_tools(...) -> None`
|
||||
- `get_tools() -> Sequence[ToolTypes]`
|
||||
- `remove_tool(...) -> None`
|
||||
- `clear_tools() -> None`
|
||||
- `add_file_mounts(...) -> None`
|
||||
- `get_file_mounts() -> Sequence[FileMount]`
|
||||
- `remove_file_mount(...) -> None`
|
||||
- `clear_file_mounts() -> None`
|
||||
- `add_allowed_domains(...) -> None`
|
||||
- `get_allowed_domains() -> Sequence[AllowedDomain]`
|
||||
- `remove_allowed_domain(...) -> None`
|
||||
- `clear_allowed_domains() -> None`
|
||||
|
||||
Requirements:
|
||||
- The provider-owned CodeAct tool registry is keyed by tool name.
|
||||
- `add_tools(...)` adds new tools and replaces an existing provider-owned registration when the same tool name is added again.
|
||||
- `get_tools()` returns the provider's current configured CodeAct tool registry.
|
||||
- `remove_tool(...)` removes provider-owned CodeAct tools by name.
|
||||
- `clear_tools()` removes all provider-owned CodeAct tools.
|
||||
- File mounts are keyed by sandbox mount path.
|
||||
- `add_file_mounts(...)` adds new file mounts and replaces an existing mount when the same mount path is added again.
|
||||
- `get_file_mounts()` returns the provider's current configured file mounts.
|
||||
- `remove_file_mount(...)` removes file mounts by mount path.
|
||||
- `clear_file_mounts()` removes all configured file mounts.
|
||||
- Allowed domains are keyed by normalized target string.
|
||||
- `add_allowed_domains(...)` adds allow-list entries and replaces an existing entry when the same target is added again.
|
||||
- `get_allowed_domains()` returns the current outbound allow-list entries.
|
||||
- `remove_allowed_domain(...)` removes allow-list entries by target.
|
||||
- `clear_allowed_domains()` removes all configured allow-list entries.
|
||||
- Tool, file-mount, and network-allow-list mutations affect subsequent runs only; runs already in progress keep the snapshot captured at run start.
|
||||
- The provider must snapshot its effective tool registry and capability state at the start of each run so concurrent execution remains deterministic.
|
||||
|
||||
#### Approval model
|
||||
|
||||
The initial Python design follows the ADR's initial approval decision and reuses the existing tool approval vocabulary from `agent_framework._tools`:
|
||||
|
||||
- `approval_mode="always_require"`
|
||||
- `approval_mode="never_require"`
|
||||
|
||||
The provider exposes a default `approval_mode` for `execute_code`.
|
||||
|
||||
Effective `execute_code` approval is computed as follows:
|
||||
|
||||
- If the provider default is `always_require`, `execute_code` requires approval.
|
||||
- If the provider default is `never_require`, the provider evaluates the provider-owned CodeAct tool registry snapshot for that run.
|
||||
- If every provider-owned CodeAct tool in that snapshot is `never_require`, `execute_code` is `never_require`.
|
||||
- If any provider-owned CodeAct tool in that snapshot is `always_require`, `execute_code` is `always_require`, even if the generated code may not call that tool.
|
||||
- Provider-owned tool calls made through `call_tool(...)` during that execution run use the approval already determined for `execute_code`.
|
||||
- Direct-only agent tools are excluded from this calculation.
|
||||
- File and network capabilities do not create a separate runtime approval check in the initial model; configuring them on the provider, including adding file mounts or outbound network allow-list entries, is itself the approval for those capabilities.
|
||||
|
||||
This is intentionally conservative and matches the shape of the current function-tool approval flow, where `FunctionTool` uses `always_require` / `never_require` and the auto-invocation loop escalates the whole batch if any called tool requires approval.
|
||||
|
||||
If one sensitive provider-owned tool causes `execute_code` to require approval more often than desired, the mitigation is to keep that tool direct-only or expose it through a different CodeAct provider/tool surface. The initial model does not try to infer whether generated code will actually call that tool before approval.
|
||||
|
||||
If the framework later standardizes pre-execution inspection or nested per-tool approvals, the Python provider surface can grow to expose that explicitly. The initial design does not assume that those extra modes are required.
|
||||
|
||||
#### Shared execution flow
|
||||
|
||||
On each run:
|
||||
1. Resolve the provider's backend/runtime behavior, capabilities, provider default `approval_mode`, and provider-owned tool registry.
|
||||
2. Compute the effective approval requirement for `execute_code` from the provider default plus the provider-owned tool registry snapshot.
|
||||
3. Build provider-defined instructions.
|
||||
4. Add `execute_code` to the model-facing tool surface.
|
||||
5. Invoke the underlying model.
|
||||
6. When `execute_code` is called, create or reuse an execution environment keyed by provider type, backend setup identity, capability configuration, and provider-owned tool signature.
|
||||
7. If the current provider mode exposes host tools, expose `call_tool(...)` bound only to the provider-owned tool registry.
|
||||
8. Execute code and convert results to framework-native content objects.
|
||||
|
||||
Caching rules:
|
||||
- Backends that support snapshots may cache a reusable clean snapshot.
|
||||
- Backends that do not support snapshots may still cache warm initialization artifacts.
|
||||
- No mutable per-run execution state may be shared across concurrent runs.
|
||||
- In-memory interpreter state does not persist across separate `execute_code` calls.
|
||||
- Configured workspace files, mounted files, and any writable artifact/output area are the supported persistence mechanism across calls when the backend exposes them.
|
||||
|
||||
### Python public API
|
||||
|
||||
#### Core types
|
||||
|
||||
```python
|
||||
class FileMount(NamedTuple):
|
||||
host_path: str | Path
|
||||
mount_path: str
|
||||
|
||||
FileMountInput = str | tuple[str | Path, str] | FileMount
|
||||
|
||||
|
||||
class AllowedDomain(NamedTuple):
|
||||
target: str
|
||||
methods: tuple[str, ...] | None = None
|
||||
|
||||
|
||||
AllowedDomainInput = str | tuple[str, str | Sequence[str]] | AllowedDomain
|
||||
|
||||
|
||||
class HyperlightCodeActProvider(ContextProvider):
|
||||
def __init__(
|
||||
self,
|
||||
source_id: str = "hyperlight_codeact",
|
||||
*,
|
||||
backend: str = "wasm",
|
||||
module: str | None = "python_guest.path",
|
||||
module_path: str | None = None,
|
||||
tools: ToolTypes | None = None,
|
||||
approval_mode: Literal["always_require", "never_require"] = "never_require",
|
||||
workspace_root: Path | None = None,
|
||||
file_mounts: Sequence[FileMountInput] = (),
|
||||
allowed_domains: Sequence[AllowedDomainInput] = (),
|
||||
) -> None: ...
|
||||
|
||||
def add_tools(self, tools: ToolTypes | Sequence[ToolTypes]) -> None: ...
|
||||
def get_tools(self) -> Sequence[ToolTypes]: ...
|
||||
def remove_tool(self, name: str) -> None: ...
|
||||
def clear_tools(self) -> None: ...
|
||||
def add_file_mounts(self, mounts: FileMountInput | Sequence[FileMountInput]) -> None: ...
|
||||
def get_file_mounts(self) -> Sequence[FileMount]: ...
|
||||
def remove_file_mount(self, mount_path: str) -> None: ...
|
||||
def clear_file_mounts(self) -> None: ...
|
||||
def add_allowed_domains(self, domains: AllowedDomainInput | Sequence[AllowedDomainInput]) -> None: ...
|
||||
def get_allowed_domains(self) -> Sequence[AllowedDomain]: ...
|
||||
def remove_allowed_domain(self, domain: str) -> None: ...
|
||||
def clear_allowed_domains(self) -> None: ...
|
||||
```
|
||||
|
||||
`file_mounts` accepts three equivalent input forms:
|
||||
- `"data/report.csv"` uses the same relative path on the host and in the sandbox.
|
||||
- `("fixtures/users.json", "data/users.json")` or `(Path("fixtures/users.json"), "data/users.json")` uses distinct host and sandbox paths.
|
||||
- `FileMount(Path("fixtures/users.json"), "data/users.json")` is the named-tuple form of the explicit pair.
|
||||
|
||||
`allowed_domains` accepts three equivalent input forms:
|
||||
- `"github.com"` allows that target with all backend-supported methods.
|
||||
- `("github.com", "GET")` or `("github.com", ["GET", "HEAD"])` uses an explicit per-target method list.
|
||||
- `AllowedDomain("github.com", ("GET", "HEAD"))` is the named-tuple form of the explicit entry.
|
||||
|
||||
No public abstract `CodeActContextProvider` base or public `executor=` parameter is required for the initial Python API.
|
||||
|
||||
The initial alpha package also exports a standalone `HyperlightExecuteCodeTool`
|
||||
for direct-tool scenarios where a provider is not needed. That standalone tool
|
||||
should advertise `call_tool(...)`, the registered sandbox tools, and capability
|
||||
state through its own `description` rather than requiring separate agent
|
||||
instructions.
|
||||
|
||||
Provider modes:
|
||||
- If no CodeAct-managed tools are configured, `HyperlightCodeActProvider` uses interpreter-style behavior.
|
||||
- If one or more CodeAct-managed tools are configured, `HyperlightCodeActProvider` uses tool-enabled behavior.
|
||||
|
||||
#### Python provider implementation contract
|
||||
|
||||
The concrete provider plugs into the existing Python `ContextProvider` surface from `agent_framework._sessions`.
|
||||
|
||||
The Hyperlight package also depends on a small set of core hooks that must remain available from `agent-framework-core`:
|
||||
- `ContextProvider.before_run(...)`
|
||||
- `SessionContext.extend_instructions(...)`
|
||||
- `SessionContext.extend_tools(...)`
|
||||
- per-run runtime tool access via `SessionContext.options["tools"]`
|
||||
- the shared `ApprovalMode` vocabulary used by `FunctionTool`
|
||||
|
||||
Required lifecycle hook:
|
||||
- `before_run(*, agent, session, context, state) -> None`
|
||||
|
||||
Optional lifecycle hook:
|
||||
- `after_run(*, agent, session, context, state) -> None`
|
||||
|
||||
`before_run(...)` is responsible for:
|
||||
- snapshotting the current CodeAct-managed tool registry and capability settings for the run,
|
||||
- computing the effective approval requirement for `execute_code` from the provider default and the snapshotted tool registry,
|
||||
- adding a short CodeAct guidance block,
|
||||
- adding `execute_code` to the run through `SessionContext.extend_tools(...)`,
|
||||
- and wiring any backend-specific execution state needed for the run.
|
||||
|
||||
These steps run on every invocation rather than once at construction time because the provider supports CRUD mutations between runs, concurrent runs need independent snapshots, and the effective approval and instructions depend on the tool registry state captured at run start. When the tool registry and capability configuration are fixed for the lifetime of the agent, the manual wiring pattern (see `codeact_manual_wiring.py`) can be used instead, which passes the tool and instructions directly to the `Agent` constructor and avoids the per-run provider lifecycle entirely.
|
||||
|
||||
If the provider stores anything in `state`, that value must stay JSON-serializable.
|
||||
|
||||
Mutating the provider after `before_run(...)` has captured a run-scoped snapshot is allowed, but it affects subsequent runs only. Provider implementations should synchronize state capture and CRUD operations so shared provider instances remain safe across concurrent runs.
|
||||
|
||||
`after_run(...)` is responsible for any backend-specific cleanup or post-processing that must happen after the model invocation completes.
|
||||
|
||||
If shared internal helpers are introduced later for multiple concrete providers, they should standardize responsibilities for:
|
||||
- building instructions,
|
||||
- computing effective approval,
|
||||
- configuring file access,
|
||||
- configuring network access,
|
||||
- preparing or restoring execution state,
|
||||
- executing code,
|
||||
- and converting backend output into framework-native `Content`.
|
||||
|
||||
#### Runtime behavior
|
||||
|
||||
- `before_run(...)` adds a short CodeAct guidance block through `SessionContext.extend_instructions(...)`.
|
||||
- `before_run(...)` adds `execute_code` through `SessionContext.extend_tools(...)`.
|
||||
- The detailed `call_tool(...)`, sandbox-tool, and capability guidance is carried by `execute_code.description`.
|
||||
- `execute_code` invokes the configured Hyperlight sandbox guest.
|
||||
- If the current CodeAct tool registry is non-empty, the runtime injects `call_tool(...)` bound to the provider-owned tool registry.
|
||||
- The provider does not inspect or mutate `Agent.default_options["tools"]` or `context.options["tools"]` to determine its CodeAct tool set.
|
||||
- The provider snapshots the current CodeAct tool registry and capability state at run start, so later registry and allow-list mutations only affect future runs.
|
||||
- Interpreter versus tool-enabled behavior is derived from the concrete provider and the presence of CodeAct-managed tools, not from a separate public profile object.
|
||||
- `execute_code` should be traced like a normal tool invocation within the surrounding agent run, and provider-owned tool calls executed through `call_tool(...)` should continue to emit ordinary tool invocation telemetry.
|
||||
|
||||
#### Backend integration
|
||||
|
||||
Initial public provider:
|
||||
- `HyperlightCodeActProvider`
|
||||
|
||||
Backend-specific notes:
|
||||
- **Hyperlight**
|
||||
- Provider construction needs a guest artifact via `module`, which may be a packaged guest module name or a path to a compiled guest artifact.
|
||||
- File access maps naturally to Hyperlight Sandbox's read-only `/input` and writable `/output` capability model.
|
||||
- Network access is denied by default and is enabled through per-target allow-list entries.
|
||||
- **Monty**
|
||||
- A future `MontyCodeActProvider` should be a separate public type rather than a `HyperlightCodeActProvider` mode.
|
||||
- Monty does not expose built-in filesystem or network access directly inside the interpreter.
|
||||
- File and URL access are mediated through host-provided external functions, so a Monty provider would need to translate provider settings into virtual files and allow-checked callbacks.
|
||||
- Monty setup may also include backend-specific inputs such as `script_name`, optional type-check stubs, or restored snapshots.
|
||||
|
||||
#### Capability handling
|
||||
|
||||
Capabilities are first-class `HyperlightCodeActProvider` init parameters and provider-managed CRUD surfaces:
|
||||
- `workspace_root`
|
||||
- `file_mounts`
|
||||
- `allowed_domains`
|
||||
|
||||
Concrete providers should normalize these settings internally. Hyperlight can map them directly to sandbox capabilities, while Monty must enforce them through host-mediated file and network functions and may apply stricter URL-level checks than the public provider surface expresses.
|
||||
|
||||
Expected management split:
|
||||
- `workspace_root` remains a direct configuration value on the provider,
|
||||
- file mounts are managed through provider CRUD methods,
|
||||
- outbound allow-list entries are managed through provider CRUD methods.
|
||||
|
||||
Enabling access means:
|
||||
- Configuring `workspace_root` or any `file_mounts` enables the sandbox filesystem surface exposed through `/input` and `/output`.
|
||||
- Leaving both `workspace_root` and `file_mounts` unset means no filesystem surface is configured.
|
||||
- Adding any `allowed_domains` entry enables outbound access only for the configured targets; leaving it empty means network access is disabled without a separate `network_mode` flag.
|
||||
- A string target allows all backend-supported methods for that target; an explicit tuple or `AllowedDomain` entry narrows the methods for that target.
|
||||
|
||||
Backends may implement stricter semantics than these top-level settings. For example, Hyperlight naturally maps file access to `/input` and `/output`, while Monty would enforce equivalent policy through host-provided callbacks rather than direct interpreter I/O.
|
||||
|
||||
#### Execution output representation
|
||||
|
||||
Backend execution output should be translated into existing AF `Content` values rather than a custom `CodeActExecutionResult` type.
|
||||
|
||||
Use the existing content model from `agent_framework._types`, for example:
|
||||
- `Content.from_code_interpreter_tool_result(outputs=[...])` to surface the overall result of sandboxed code execution,
|
||||
- `Content.from_text(...)` for plain textual output,
|
||||
- `Content.from_data(...)` or `Content.from_uri(...)` for generated files or binary artifacts,
|
||||
- `Content.from_error(...)` for execution failures,
|
||||
- and `Content.from_function_result(..., result=list[Content])` when surfacing the final result of `execute_code` through the normal tool result path.
|
||||
|
||||
#### `execute_code` input contract
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"description": "Code to execute using the provider's configured backend/runtime behavior."
|
||||
}
|
||||
},
|
||||
"required": ["code"]
|
||||
}
|
||||
```
|
||||
|
||||
Execution failures should surface readable error text and structured error `Content`, not a custom backend result object.
|
||||
|
||||
Timeouts, out-of-memory conditions, backend crashes, and similar sandbox failures are all `execute_code` failures and should surface as structured error content. Partial textual or file outputs may be returned only when the backend can report them unambiguously; callers should not rely on partial-output recovery as a portable contract.
|
||||
|
||||
## E2E Code Samples
|
||||
|
||||
### Tool-enabled CodeAct mode
|
||||
|
||||
```python
|
||||
codeact = HyperlightCodeActProvider(
|
||||
tools=[fetch_docs, query_data],
|
||||
workspace_root="./workdir",
|
||||
allowed_domains=[("api.github.com", "GET")],
|
||||
)
|
||||
codeact.add_tools([lookup_user])
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="assistant",
|
||||
tools=[send_email], # direct-only tool
|
||||
context_providers=[codeact],
|
||||
)
|
||||
```
|
||||
|
||||
### Standard code interpreter mode
|
||||
|
||||
```python
|
||||
codeact = HyperlightCodeActProvider(
|
||||
workspace_root="./data",
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="interpreter",
|
||||
context_providers=[codeact],
|
||||
)
|
||||
```
|
||||
|
||||
### Manual static wiring (no per-run provider lifecycle)
|
||||
|
||||
When the tool registry and capability configuration are fixed, the provider lifecycle can be skipped entirely. Build the `execute_code` tool and instructions once and pass them directly to the agent:
|
||||
|
||||
```python
|
||||
execute_code = HyperlightExecuteCodeTool(
|
||||
tools=[fetch_docs, query_data],
|
||||
workspace_root="./workdir",
|
||||
allowed_domains=[("api.github.com", "GET")],
|
||||
approval_mode="never_require",
|
||||
)
|
||||
|
||||
codeact_instructions = execute_code.build_instructions(tools_visible_to_model=False)
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="assistant",
|
||||
instructions=f"You are a helpful assistant.\n\n{codeact_instructions}",
|
||||
tools=[send_email, execute_code],
|
||||
)
|
||||
```
|
||||
@@ -7,16 +7,13 @@
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<!-- Aspire -->
|
||||
<AspireAppHostSdkVersion>13.1.0</AspireAppHostSdkVersion>
|
||||
<AspireAppHostSdkVersion>13.0.2</AspireAppHostSdkVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Aspire.* -->
|
||||
<PackageVersion Include="Anthropic" Version="12.13.0" />
|
||||
<PackageVersion Include="Anthropic.Foundry" Version="0.5.0" />
|
||||
<PackageVersion Include="Aspire.Hosting" Version="$(AspireAppHostSdkVersion)" />
|
||||
<PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="13.0.0-preview.1.25560.3" />
|
||||
<PackageVersion Include="Aspire.Azure.AI.Inference" Version="13.1.0-preview.1.25616.3" />
|
||||
<PackageVersion Include="Aspire.Hosting.Azure.AIFoundry" Version="13.1.0-preview.1.25616.3" />
|
||||
<PackageVersion Include="Aspire.Hosting.AppHost" Version="$(AspireAppHostSdkVersion)" />
|
||||
<PackageVersion Include="Aspire.Hosting.Azure.CognitiveServices" Version="$(AspireAppHostSdkVersion)" />
|
||||
<PackageVersion Include="Aspire.Microsoft.Azure.Cosmos" Version="$(AspireAppHostSdkVersion)" />
|
||||
@@ -51,12 +48,12 @@
|
||||
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.6.3" />
|
||||
<PackageVersion Include="System.Net.Security" Version="4.3.2" />
|
||||
<!-- OpenTelemetry -->
|
||||
<PackageVersion Include="OpenTelemetry" Version="1.14.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Api" Version="1.14.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Exporter.Console" Version="1.14.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Exporter.InMemory" Version="1.14.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.14.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.14.0" />
|
||||
<PackageVersion Include="OpenTelemetry" Version="1.13.1" />
|
||||
<PackageVersion Include="OpenTelemetry.Api" Version="1.13.1" />
|
||||
<PackageVersion Include="OpenTelemetry.Exporter.Console" Version="1.13.1" />
|
||||
<PackageVersion Include="OpenTelemetry.Exporter.InMemory" Version="1.13.1" />
|
||||
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.13.1" />
|
||||
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.13.1" />
|
||||
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.13.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.13.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.13.0" />
|
||||
@@ -74,18 +71,18 @@
|
||||
<PackageVersion Include="Microsoft.Extensions.AI.OpenAI" Version="10.5.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Compliance.Abstractions" Version="10.5.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.UserSecrets" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.UserSecrets" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.6" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.6" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="10.0.1" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.VectorData.Abstractions" Version="9.7.0" />
|
||||
<!-- Vector Stores -->
|
||||
|
||||
@@ -4,9 +4,6 @@
|
||||
<BuildType Name="Publish" />
|
||||
<BuildType Name="Release" />
|
||||
</Configurations>
|
||||
<Folder Name="/src/Aspire.Hosting.AgentFramework.DevUI/">
|
||||
<Project Path="src/Aspire.Hosting.AgentFramework.DevUI/Aspire.Hosting.AgentFramework.DevUI.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/">
|
||||
<File Path="samples/AGENTS.md" />
|
||||
<File Path="samples/README.md" />
|
||||
@@ -40,12 +37,6 @@
|
||||
<Project Path="samples/02-agents/AgentProviders/Agent_With_OpenAIChatCompletion/Agent_With_OpenAIChatCompletion.csproj" />
|
||||
<Project Path="samples/02-agents/AgentProviders/Agent_With_OpenAIResponses/Agent_With_OpenAIResponses.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/05-end-to-end/DevUIAspireIntegration/">
|
||||
<Project Path="samples/05-end-to-end/DevUIAspireIntegration/DevUIIntegration.AppHost/DevUIIntegration.AppHost.csproj" />
|
||||
<Project Path="samples/05-end-to-end/DevUIAspireIntegration/DevUIIntegration.ServiceDefaults/DevUIIntegration.ServiceDefaults.csproj" />
|
||||
<Project Path="samples/05-end-to-end/DevUIAspireIntegration/EditorAgent/EditorAgent.csproj" />
|
||||
<Project Path="samples/05-end-to-end/DevUIAspireIntegration/WriterAgent/WriterAgent.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/02-agents/Agents/">
|
||||
<File Path="samples/02-agents/Agents/README.md" />
|
||||
<Project Path="samples/02-agents/Agents/Agent_Step01_UsingFunctionToolsWithApprovals/Agent_Step01_UsingFunctionToolsWithApprovals.csproj" />
|
||||
@@ -161,7 +152,6 @@
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step21_WebSearch/Agent_Step21_WebSearch.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step22_MemorySearch/Agent_Step22_MemorySearch.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step23_LocalMCP/Agent_Step23_LocalMCP.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step24_CodeInterpreterFileDownload/Agent_Step24_CodeInterpreterFileDownload.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/02-agents/Evaluation/">
|
||||
<Project Path="samples/02-agents/Evaluation/Evaluation_SimpleEval/Evaluation_SimpleEval.csproj" />
|
||||
@@ -183,7 +173,6 @@
|
||||
<Project Path="samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step03_CreateFromChatClient/Agent_OpenAI_Step03_CreateFromChatClient.csproj" />
|
||||
<Project Path="samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/Agent_OpenAI_Step04_CreateFromOpenAIResponseClient.csproj" />
|
||||
<Project Path="samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step05_Conversation/Agent_OpenAI_Step05_Conversation.csproj" />
|
||||
<Project Path="samples/02-agents/AgentWithOpenAI/Agent_OpenAI_Step06_CodeInterpreterFileDownload/Agent_OpenAI_Step06_CodeInterpreterFileDownload.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/02-agents/AgentWithRAG/">
|
||||
<File Path="samples/02-agents/AgentWithRAG/README.md" />
|
||||
@@ -551,7 +540,6 @@
|
||||
<Project Path="tests/OpenAIResponse.IntegrationTests/OpenAIResponse.IntegrationTests.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Tests/UnitTests/">
|
||||
<Project Path="tests/Aspire.Hosting.AgentFramework.DevUI.UnitTests/Aspire.Hosting.AgentFramework.DevUI.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.A2A.UnitTests/Microsoft.Agents.AI.A2A.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Abstractions.UnitTests/Microsoft.Agents.AI.Abstractions.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.AGUI.UnitTests/Microsoft.Agents.AI.AGUI.UnitTests.csproj" />
|
||||
|
||||
@@ -28,8 +28,7 @@
|
||||
"src\\Microsoft.Agents.AI.Workflows.Declarative\\Microsoft.Agents.AI.Workflows.Declarative.csproj",
|
||||
"src\\Microsoft.Agents.AI.Workflows.Generators\\Microsoft.Agents.AI.Workflows.Generators.csproj",
|
||||
"src\\Microsoft.Agents.AI.Workflows\\Microsoft.Agents.AI.Workflows.csproj",
|
||||
"src\\Microsoft.Agents.AI\\Microsoft.Agents.AI.csproj",
|
||||
"src\\Aspire.Hosting.AgentFramework.DevUI\\Aspire.Hosting.AgentFramework.DevUI.csproj"
|
||||
"src\\Microsoft.Agents.AI\\Microsoft.Agents.AI.csproj"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample shows how to download files generated by Code Interpreter using the Containers API.
|
||||
// Code Interpreter generates files inside containers (cfile_ / cntr_ IDs) which cannot be
|
||||
// downloaded via the standard Files API. Use ContainerClient instead.
|
||||
|
||||
#pragma warning disable OPENAI001
|
||||
|
||||
using System.ClientModel;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
using OpenAI;
|
||||
using OpenAI.Containers;
|
||||
using OpenAI.Responses;
|
||||
|
||||
string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");
|
||||
string model = Environment.GetEnvironmentVariable("OPENAI_CHAT_MODEL_NAME") ?? "gpt-4o-mini";
|
||||
|
||||
var openAIClient = new OpenAIClient(new ApiKeyCredential(apiKey));
|
||||
|
||||
// Create an agent with Code Interpreter tool enabled
|
||||
AIAgent agent = openAIClient
|
||||
.GetResponsesClient()
|
||||
.AsAIAgent(
|
||||
model: model,
|
||||
instructions: "You are a helpful assistant that can generate files using code.",
|
||||
name: "CodeInterpreterAgent",
|
||||
tools: [new HostedCodeInterpreterTool()]);
|
||||
|
||||
// Ask the agent to generate a file
|
||||
AgentResponse response = await agent.RunAsync(
|
||||
"Create a CSV file with the multiplication times tables from 1 to 12. Include headers.");
|
||||
|
||||
// Display the text response
|
||||
foreach (TextContent textContent in response.Messages.SelectMany(x => x.Contents).OfType<TextContent>())
|
||||
{
|
||||
Console.WriteLine(textContent.Text);
|
||||
}
|
||||
|
||||
// Extract container file citations from response annotations and download
|
||||
ContainerClient containerClient = openAIClient.GetContainerClient();
|
||||
|
||||
HashSet<string> downloadedFiles = [];
|
||||
bool foundContainerFiles = false;
|
||||
|
||||
foreach (AIContent content in response.Messages.SelectMany(x => x.Contents))
|
||||
{
|
||||
if (content.Annotations is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (AIAnnotation annotation in content.Annotations)
|
||||
{
|
||||
// Container files from Code Interpreter have ContainerFileCitationMessageAnnotation as raw representation
|
||||
if (annotation is CitationAnnotation citation
|
||||
&& citation.RawRepresentation is ContainerFileCitationMessageAnnotation containerCitation)
|
||||
{
|
||||
foundContainerFiles = true;
|
||||
|
||||
// Deduplicate by container+file ID in case the same file is cited multiple times
|
||||
string key = $"{containerCitation.ContainerId}/{containerCitation.FileId}";
|
||||
if (!downloadedFiles.Add(key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Console.WriteLine($"\nDownloading container file: {containerCitation.Filename}");
|
||||
Console.WriteLine($" Container ID: {containerCitation.ContainerId}");
|
||||
Console.WriteLine($" File ID: {containerCitation.FileId}");
|
||||
|
||||
BinaryData fileData = await containerClient.DownloadContainerFileAsync(
|
||||
containerCitation.ContainerId,
|
||||
containerCitation.FileId);
|
||||
|
||||
// Sanitize filename to prevent path traversal
|
||||
string safeFilename = Path.GetFileName(containerCitation.Filename);
|
||||
string outputPath = Path.Combine(Directory.GetCurrentDirectory(), safeFilename);
|
||||
await File.WriteAllBytesAsync(outputPath, fileData.ToArray());
|
||||
Console.WriteLine($" Saved to: {outputPath}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundContainerFiles)
|
||||
{
|
||||
Console.WriteLine("\nNo container file citations found in the response.");
|
||||
Console.WriteLine("The model may not have generated a downloadable file for this prompt.");
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
# Code Interpreter File Download (OpenAI)
|
||||
|
||||
This sample demonstrates how to download files generated by Code Interpreter when using the OpenAI Responses API.
|
||||
|
||||
## What this sample demonstrates
|
||||
|
||||
- Creating an agent with Code Interpreter tool using `ResponsesClient.AsAIAgent()`
|
||||
- Generating files through Code Interpreter (e.g., CSV, Excel, images)
|
||||
- Extracting container file citations from agent response annotations
|
||||
- Downloading container files using the `ContainerClient` API
|
||||
|
||||
## Container files vs regular files
|
||||
|
||||
When Code Interpreter generates a file, the file is stored inside a **container** with a `cntr_` prefixed ID. The file itself gets a `cfile_` prefixed ID.
|
||||
|
||||
These container files **cannot** be downloaded using the standard Files API (`GetOpenAIFileClient`), which returns 404 for `cfile_` IDs. Instead, you must use the **Containers API** (`GetContainerClient`) to download them:
|
||||
|
||||
```csharp
|
||||
// ❌ This does NOT work for container files
|
||||
var filesClient = openAIClient.GetOpenAIFileClient();
|
||||
await filesClient.DownloadFileAsync("cfile_..."); // Returns 404
|
||||
|
||||
// âś… Use ContainerClient instead
|
||||
var containerClient = openAIClient.GetContainerClient();
|
||||
await containerClient.DownloadContainerFileAsync("cntr_...", "cfile_...");
|
||||
```
|
||||
|
||||
The container ID and file ID are available from the `ContainerFileCitationMessageAnnotation` annotation in the response, accessible via `CitationAnnotation.RawRepresentation`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- .NET 10 SDK or later
|
||||
- OpenAI API key with access to a model that supports Code Interpreter
|
||||
|
||||
Set the following environment variables:
|
||||
|
||||
```powershell
|
||||
$env:OPENAI_API_KEY="sk-..."
|
||||
$env:OPENAI_CHAT_MODEL_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini
|
||||
```
|
||||
|
||||
## Run the sample
|
||||
|
||||
```powershell
|
||||
dotnet run
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [Code Interpreter File Download with Foundry](../../../02-agents/AgentsWithFoundry/Agent_Step24_CodeInterpreterFileDownload/) — same scenario using Microsoft Foundry
|
||||
- [Code Interpreter](../../../02-agents/AgentsWithFoundry/Agent_Step14_CodeInterpreter/) — Code Interpreter without file download
|
||||
@@ -14,5 +14,4 @@ Agent Framework provides additional support to allow OpenAI developers to use th
|
||||
|[Using Reasoning Capabilities](./Agent_OpenAI_Step02_Reasoning/)|This sample demonstrates how to create an AI agent with reasoning capabilities using OpenAI's reasoning models and response types.|
|
||||
|[Creating an Agent from a ChatClient](./Agent_OpenAI_Step03_CreateFromChatClient/)|This sample demonstrates how to create an AI agent directly from an OpenAI.Chat.ChatClient instance using OpenAIChatClientAgent.|
|
||||
|[Creating an Agent from an OpenAIResponseClient](./Agent_OpenAI_Step04_CreateFromOpenAIResponseClient/)|This sample demonstrates how to create an AI agent directly from an OpenAI.Responses.OpenAIResponseClient instance using OpenAIResponseClientAgent.|
|
||||
|[Managing Conversation State](./Agent_OpenAI_Step05_Conversation/)|This sample demonstrates how to maintain conversation state across multiple turns using the AgentSession for context continuity.|
|
||||
|[Code Interpreter File Download](./Agent_OpenAI_Step06_CodeInterpreterFileDownload/)|This sample demonstrates how to download files generated by Code Interpreter using the Containers API (`cfile_`/`cntr_` IDs).|
|
||||
|[Managing Conversation State](./Agent_OpenAI_Step05_Conversation/)|This sample demonstrates how to maintain conversation state across multiple turns using the AgentSession for context continuity.|
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample shows how to download files generated by Code Interpreter using Microsoft Foundry.
|
||||
// Code Interpreter generates files inside containers (cfile_ / cntr_ IDs) which cannot be
|
||||
// downloaded via the standard Files API. Use ContainerClient from the project's OpenAI client instead.
|
||||
|
||||
#pragma warning disable OPENAI001
|
||||
|
||||
using Azure.AI.Projects;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
using OpenAI.Responses;
|
||||
|
||||
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
|
||||
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
|
||||
|
||||
// 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.
|
||||
AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential());
|
||||
|
||||
// Create an agent with Code Interpreter tool enabled
|
||||
AIAgent agent = aiProjectClient.AsAIAgent(
|
||||
deploymentName,
|
||||
instructions: "You are a helpful assistant that can generate files using code.",
|
||||
name: "CodeInterpreterAgent",
|
||||
tools: [new HostedCodeInterpreterTool()]);
|
||||
|
||||
// Ask the agent to generate a file
|
||||
AgentResponse response = await agent.RunAsync(
|
||||
"Create a CSV file with the multiplication times tables from 1 to 12. Include headers.");
|
||||
|
||||
// Display the text response
|
||||
foreach (TextContent textContent in response.Messages.SelectMany(x => x.Contents).OfType<TextContent>())
|
||||
{
|
||||
Console.WriteLine(textContent.Text);
|
||||
}
|
||||
|
||||
// Extract container file citations from response annotations and download.
|
||||
// AIProjectClient.GetProjectOpenAIClient() returns a ProjectOpenAIClient (inherits from OpenAI.OpenAIClient)
|
||||
// which supports GetContainerClient(), unlike AzureOpenAIClient which does not.
|
||||
var containerClient = aiProjectClient.GetProjectOpenAIClient().GetContainerClient();
|
||||
|
||||
HashSet<string> downloadedFiles = [];
|
||||
bool foundContainerFiles = false;
|
||||
|
||||
foreach (AIContent content in response.Messages.SelectMany(x => x.Contents))
|
||||
{
|
||||
if (content.Annotations is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (AIAnnotation annotation in content.Annotations)
|
||||
{
|
||||
// Container files from Code Interpreter have ContainerFileCitationMessageAnnotation as raw representation
|
||||
if (annotation is CitationAnnotation citation
|
||||
&& citation.RawRepresentation is ContainerFileCitationMessageAnnotation containerCitation)
|
||||
{
|
||||
foundContainerFiles = true;
|
||||
|
||||
// Deduplicate by container+file ID in case the same file is cited multiple times
|
||||
string key = $"{containerCitation.ContainerId}/{containerCitation.FileId}";
|
||||
if (!downloadedFiles.Add(key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Console.WriteLine($"\nDownloading container file: {containerCitation.Filename}");
|
||||
Console.WriteLine($" Container ID: {containerCitation.ContainerId}");
|
||||
Console.WriteLine($" File ID: {containerCitation.FileId}");
|
||||
|
||||
BinaryData fileData = await containerClient.DownloadContainerFileAsync(
|
||||
containerCitation.ContainerId,
|
||||
containerCitation.FileId);
|
||||
|
||||
// Sanitize filename to prevent path traversal
|
||||
string safeFilename = Path.GetFileName(containerCitation.Filename);
|
||||
string outputPath = Path.Combine(Directory.GetCurrentDirectory(), safeFilename);
|
||||
await File.WriteAllBytesAsync(outputPath, fileData.ToArray());
|
||||
Console.WriteLine($" Saved to: {outputPath}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundContainerFiles)
|
||||
{
|
||||
Console.WriteLine("\nNo container file citations found in the response.");
|
||||
Console.WriteLine("The model may not have generated a downloadable file for this prompt.");
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
# Code Interpreter File Download (Microsoft Foundry)
|
||||
|
||||
This sample demonstrates how to download files generated by Code Interpreter when using Microsoft Foundry.
|
||||
|
||||
## What this sample demonstrates
|
||||
|
||||
- Creating an agent with Code Interpreter tool using `AIProjectClient.AsAIAgent()`
|
||||
- Generating files through Code Interpreter (e.g., CSV, Excel, images)
|
||||
- Extracting container file citations from agent response annotations
|
||||
- Downloading container files using the `ContainerClient` via `AIProjectClient.GetProjectOpenAIClient()`
|
||||
|
||||
## Container files vs regular files
|
||||
|
||||
When Code Interpreter generates a file, the file is stored inside a **container** with a `cntr_` prefixed ID. The file itself gets a `cfile_` prefixed ID.
|
||||
|
||||
These container files **cannot** be downloaded using the standard Files API (`GetOpenAIFileClient`), which returns 404 for `cfile_` IDs. Instead, you must use the **Containers API** to download them.
|
||||
|
||||
### Getting the ContainerClient with Foundry
|
||||
|
||||
`AzureOpenAIClient.GetContainerClient()` is not supported and throws `InvalidOperationException`. Instead, use the project's OpenAI client which inherits directly from `OpenAI.OpenAIClient`:
|
||||
|
||||
```csharp
|
||||
// ❌ AzureOpenAIClient does not support ContainerClient
|
||||
var azureClient = new AzureOpenAIClient(endpoint, credential);
|
||||
azureClient.GetContainerClient(); // Throws InvalidOperationException
|
||||
|
||||
// âś… Use AIProjectClient's project OpenAI client
|
||||
var containerClient = aiProjectClient.GetProjectOpenAIClient().GetContainerClient();
|
||||
await containerClient.DownloadContainerFileAsync("cntr_...", "cfile_...");
|
||||
```
|
||||
|
||||
The container ID and file ID are available from the `ContainerFileCitationMessageAnnotation` annotation in the response, accessible via `CitationAnnotation.RawRepresentation`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- .NET 10 SDK or later
|
||||
- Microsoft Foundry service endpoint and deployment configured
|
||||
- Azure CLI installed and authenticated (`az login`)
|
||||
|
||||
Set the following environment variables:
|
||||
|
||||
```powershell
|
||||
$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project"
|
||||
$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini
|
||||
```
|
||||
|
||||
## Run the sample
|
||||
|
||||
```powershell
|
||||
dotnet run
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [Code Interpreter File Download with OpenAI](../../../02-agents/AgentWithOpenAI/Agent_OpenAI_Step06_CodeInterpreterFileDownload/) — same scenario using Public OpenAI
|
||||
- [Code Interpreter](../Agent_Step14_CodeInterpreter/) — Code Interpreter without file download
|
||||
@@ -72,7 +72,6 @@ Some samples require extra tool-specific environment variables. See each sample
|
||||
| [Web search](./Agent_Step21_WebSearch/) | Web search tool |
|
||||
| [Memory search](./Agent_Step22_MemorySearch/) | Memory search tool |
|
||||
| [Local MCP](./Agent_Step23_LocalMCP/) | Local MCP client with HTTP transport |
|
||||
| [Code interpreter file download](./Agent_Step24_CodeInterpreterFileDownload/) | Download container files generated by code interpreter |
|
||||
|
||||
## Running the samples
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"appHostPath": "../DevUIIntegration.AppHost/DevUIIntegration.AppHost.csproj"
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
**/**/*.Development.json
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<Sdk Name="Aspire.AppHost.Sdk" Version="$(AspireAppHostSdkVersion)" />
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Hosting.AppHost" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Hosting.Azure.AIFoundry" />
|
||||
<PackageReference Include="OpenAI" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" IsAspireProjectResource="false" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.DevUI\Microsoft.Agents.AI.DevUI.csproj" IsAspireProjectResource="false" />
|
||||
<ProjectReference Include="..\..\..\..\src\Aspire.Hosting.AgentFramework.DevUI\Aspire.Hosting.AgentFramework.DevUI.csproj" IsAspireProjectResource="false" />
|
||||
<ProjectReference Include="..\WriterAgent\WriterAgent.csproj" />
|
||||
<ProjectReference Include="..\EditorAgent\EditorAgent.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
var builder = DistributedApplication.CreateBuilder(args);
|
||||
|
||||
var foundry = builder.AddAzureAIFoundry("foundry");
|
||||
|
||||
// Comment the following lines to create a new Foundry instance instead of connecting to an existing one. If creating a new instance, the DevUI resource will wait for the Foundry to be ready before starting, ensuring the DevUI frontend is available as soon as the app starts.
|
||||
var existingFoundryName = builder.AddParameter("existingFoundryName")
|
||||
.WithDescription("The name of the existing Azure Foundry resource.");
|
||||
var existingFoundryResourceGroup = builder.AddParameter("existingFoundryResourceGroup")
|
||||
.WithDescription("The resource group of the existing Azure Foundry resource.");
|
||||
foundry.AsExisting(existingFoundryName, existingFoundryResourceGroup);
|
||||
|
||||
// Add the writer agent service
|
||||
var writerAgent = builder.AddProject<Projects.WriterAgent>("writer-agent")
|
||||
.WithHttpHealthCheck("/health")
|
||||
.WithReference(foundry).WaitFor(foundry);
|
||||
|
||||
// Add the editor agent service
|
||||
var editorAgent = builder.AddProject<Projects.EditorAgent>("editor-agent")
|
||||
.WithHttpHealthCheck("/health")
|
||||
.WithReference(foundry).WaitFor(foundry);
|
||||
|
||||
// Add DevUI integration that aggregates agents from all agent services.
|
||||
// Agent metadata is declared here so backends don't need a /v1/entities endpoint.
|
||||
_ = builder.AddDevUI("devui")
|
||||
.WithAgentService(writerAgent, agents: [new("writer")]) // the name of the agent should match the agent declaration in WriterAgent/Program.cs
|
||||
.WithAgentService(editorAgent, agents: [new("editor")]) // the name of the agent should match the agent declaration in EditorAgent/Program.cs
|
||||
.WaitFor(writerAgent)
|
||||
.WaitFor(editorAgent);
|
||||
|
||||
builder.Build().Run();
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:16500;http://localhost:16501",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"DOTNET_ENVIRONMENT": "Development",
|
||||
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:17250",
|
||||
"ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:18100",
|
||||
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:17250",
|
||||
"ASPIRE_SHOW_DASHBOARD_RESOURCES": "true"
|
||||
}
|
||||
},
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:16501",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"DOTNET_ENVIRONMENT": "Development",
|
||||
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:17251",
|
||||
"ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18101",
|
||||
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:17251",
|
||||
"ASPIRE_SHOW_DASHBOARD_RESOURCES": "true",
|
||||
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"Azure": {
|
||||
"TenantId": "",
|
||||
"SubscriptionId": "",
|
||||
"AllowResourceGroupCreation": true,
|
||||
"ResourceGroup": "",
|
||||
"Location": "",
|
||||
"CredentialSource": "AzureCli"
|
||||
},
|
||||
"Parameters": {
|
||||
"existingFoundryName": "",
|
||||
"existingFoundryResourceGroup": ""
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsAspireSharedProject>true</IsAspireSharedProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
|
||||
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Http" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenTelemetry;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Trace;
|
||||
|
||||
namespace Microsoft.Extensions.Hosting;
|
||||
|
||||
// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry.
|
||||
// This project should be referenced by each service project in your solution.
|
||||
// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults
|
||||
#pragma warning disable CA1724 // Type name 'Extensions' conflicts with namespace - acceptable for Aspire pattern
|
||||
public static class Extensions
|
||||
#pragma warning restore CA1724
|
||||
{
|
||||
private const string HealthEndpointPath = "/health";
|
||||
private const string AlivenessEndpointPath = "/alive";
|
||||
|
||||
public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
|
||||
{
|
||||
builder.ConfigureOpenTelemetry();
|
||||
|
||||
builder.AddDefaultHealthChecks();
|
||||
|
||||
builder.Services.AddServiceDiscovery();
|
||||
|
||||
builder.Services.ConfigureHttpClientDefaults(http =>
|
||||
{
|
||||
// Turn on resilience by default
|
||||
http.AddStandardResilienceHandler();
|
||||
|
||||
// Turn on service discovery by default
|
||||
http.AddServiceDiscovery();
|
||||
});
|
||||
|
||||
// Uncomment the following to restrict the allowed schemes for service discovery.
|
||||
// builder.Services.Configure<ServiceDiscoveryOptions>(options =>
|
||||
// {
|
||||
// options.AllowedSchemes = ["https"];
|
||||
// });
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
|
||||
{
|
||||
builder.Logging.AddOpenTelemetry(logging =>
|
||||
{
|
||||
logging.IncludeFormattedMessage = true;
|
||||
logging.IncludeScopes = true;
|
||||
});
|
||||
|
||||
builder.Services.AddOpenTelemetry()
|
||||
.WithMetrics(metrics =>
|
||||
{
|
||||
metrics.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddRuntimeInstrumentation();
|
||||
})
|
||||
.WithTracing(tracing =>
|
||||
{
|
||||
tracing.AddSource(builder.Environment.ApplicationName)
|
||||
.AddAspNetCoreInstrumentation(tracing =>
|
||||
// Exclude health check requests from tracing
|
||||
tracing.Filter = context =>
|
||||
!context.Request.Path.StartsWithSegments(HealthEndpointPath)
|
||||
&& !context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
|
||||
)
|
||||
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
|
||||
//.AddGrpcClientInstrumentation()
|
||||
.AddHttpClientInstrumentation();
|
||||
});
|
||||
|
||||
builder.AddOpenTelemetryExporters();
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
|
||||
{
|
||||
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
|
||||
|
||||
if (useOtlpExporter)
|
||||
{
|
||||
builder.Services.AddOpenTelemetry().UseOtlpExporter();
|
||||
}
|
||||
|
||||
// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
|
||||
//if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
|
||||
//{
|
||||
// builder.Services.AddOpenTelemetry()
|
||||
// .UseAzureMonitor();
|
||||
//}
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
|
||||
{
|
||||
builder.Services.AddHealthChecks()
|
||||
// Add a default liveness check to ensure app is responsive
|
||||
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static WebApplication MapDefaultEndpoints(this WebApplication app)
|
||||
{
|
||||
// Adding health checks endpoints to applications in non-development environments has security implications.
|
||||
// See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
// All health checks must pass for app to be considered ready to accept traffic after starting
|
||||
app.MapHealthChecks(HealthEndpointPath);
|
||||
|
||||
// Only health checks tagged with the "live" tag must pass for app to be considered alive
|
||||
app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
|
||||
{
|
||||
Predicate = r => r.Tags.Contains("live")
|
||||
});
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>b2c3d4e5-f6a7-8901-bcde-f12345678901</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Azure.AI.Inference" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting\Microsoft.Agents.AI.Hosting.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting.OpenAI\Microsoft.Agents.AI.Hosting.OpenAI.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
<ProjectReference Include="..\DevUIIntegration.ServiceDefaults\DevUIIntegration.ServiceDefaults.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,51 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.ComponentModel;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Hosting;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
builder.AddAzureChatCompletionsClient(connectionName: "foundry",
|
||||
configureSettings: settings =>
|
||||
{
|
||||
settings.TokenCredential = new DefaultAzureCredential();
|
||||
settings.EnableSensitiveTelemetryData = builder.Environment.IsDevelopment();
|
||||
})
|
||||
.AddChatClient("gpt41");
|
||||
|
||||
builder.AddAIAgent("editor", (sp, key) =>
|
||||
{
|
||||
var chatClient = sp.GetRequiredService<IChatClient>();
|
||||
return new ChatClientAgent(
|
||||
chatClient,
|
||||
name: key,
|
||||
instructions: "You edit short stories to improve grammar and style, ensuring the stories are less than 300 words. Once finished editing, you select a title and format the story for publishing.",
|
||||
tools: [AIFunctionFactory.Create(FormatStory)]
|
||||
);
|
||||
});
|
||||
|
||||
// Register services for OpenAI responses and conversations
|
||||
builder.Services.AddOpenAIResponses();
|
||||
builder.Services.AddOpenAIConversations();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Map OpenAI API endpoints — DevUI aggregator routes requests here
|
||||
app.MapOpenAIResponses();
|
||||
app.MapOpenAIConversations();
|
||||
|
||||
app.MapDefaultEndpoints();
|
||||
|
||||
app.Run();
|
||||
|
||||
[Description("Formats the story for publication, revealing its title.")]
|
||||
static string FormatStory(string title, string story) => $"""
|
||||
**Title**: {title}
|
||||
|
||||
{story}
|
||||
""";
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5281",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
# DevUI Integration Sample
|
||||
|
||||
This sample demonstrates how to use the **Aspire.Hosting.AgentFramework.DevUI** library to test and debug multiple AI agents through a unified DevUI web interface, orchestrated by an Aspire AppHost.
|
||||
|
||||
The solution contains two agent services:
|
||||
|
||||
- **WriterAgent** — a simple agent that writes short stories (≤ 300 words) about a given topic.
|
||||
- **EditorAgent** — an agent that edits stories for grammar and style, selects a title, and formats the result for publishing. It also demonstrates tool use via `AIFunctionFactory`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [.NET 10 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)
|
||||
- [Aspire CLI](https://learn.microsoft.com/dotnet/aspire/fundamentals/setup-tooling)
|
||||
- An Azure subscription with access to [Azure AI Foundry](https://learn.microsoft.com/azure/ai-studio/)
|
||||
- Azure CLI authenticated (`az login`)
|
||||
|
||||
## Azure AI Foundry configuration
|
||||
|
||||
The sample requires an Azure AI Foundry resource with a deployed `gpt-4.1` model. You have two options:
|
||||
|
||||
### Option 1: Connect to an existing Foundry resource
|
||||
|
||||
Fill in the parameters in `DevUIIntegration.AppHost/appsettings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"Azure": {
|
||||
"TenantId": "<your-tenant-id>",
|
||||
"SubscriptionId": "<your-subscription-id>",
|
||||
"AllowResourceGroupCreation": true,
|
||||
"ResourceGroup": "<your-resource-group>",
|
||||
"Location": "<your-azure-region>",
|
||||
"CredentialSource": "AzureCli"
|
||||
},
|
||||
"Parameters": {
|
||||
"existingFoundryName": "<your-foundry-resource-name>",
|
||||
"existingFoundryResourceGroup": "<resource-group-containing-your-foundry>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The AppHost calls `foundry.AsExisting(...)` with these parameters, so Aspire connects to the existing resource instead of provisioning a new one.
|
||||
|
||||
### Option 2: Let Aspire provision a new Foundry resource
|
||||
|
||||
Remove or comment out the `AsExisting` block in `DevUIIntegration.AppHost/Program.cs`:
|
||||
|
||||
```csharp
|
||||
// Comment the following lines to create a new Foundry instance
|
||||
// _ = builder.AddParameterFromConfiguration("tenant", "Azure:TenantId");
|
||||
// var existingFoundryName = builder.AddParameter("existingFoundryName") ...
|
||||
// foundry.AsExisting(existingFoundryName, existingFoundryResourceGroup);
|
||||
```
|
||||
|
||||
Aspire will provision a new Azure AI Foundry resource on startup. The DevUI resource uses `.WaitFor(foundry)` transitively through the agent services, so the frontend won't become available until provisioning completes. This can take several minutes on first run.
|
||||
|
||||
You still need to fill in the `Azure` section of `appsettings.json` (subscription, location, etc.) so Aspire knows where to create the resource.
|
||||
|
||||
## Agent name matching with `WithAgentService`
|
||||
|
||||
When connecting agent services to DevUI in the AppHost, you must pass the correct agent name via the `agents:` parameter. **This name must match the name used in `AddAIAgent(...)` inside each agent service's `Program.cs` — not the Aspire resource name.**
|
||||
|
||||
For example, the WriterAgent Aspire resource is named `"writer-agent"`, but the agent is registered as `"writer"`:
|
||||
|
||||
```csharp
|
||||
// WriterAgent/Program.cs
|
||||
builder.AddAIAgent("writer", "You write short stories ...");
|
||||
// ^^^^^^^^ this is the agent name
|
||||
```
|
||||
|
||||
```csharp
|
||||
// EditorAgent/Program.cs
|
||||
builder.AddAIAgent("editor", (sp, key) => { ... });
|
||||
// ^^^^^^^^ this is the agent name
|
||||
```
|
||||
|
||||
The AppHost must use these exact names:
|
||||
|
||||
```csharp
|
||||
// DevUIIntegration.AppHost/Program.cs
|
||||
builder.AddDevUI("devui")
|
||||
.WithAgentService(writerAgent, agents: [new("writer")]) // âś… matches AddAIAgent("writer", ...)
|
||||
.WithAgentService(editorAgent, agents: [new("editor")]) // âś… matches AddAIAgent("editor", ...)
|
||||
.WaitFor(writerAgent)
|
||||
.WaitFor(editorAgent);
|
||||
```
|
||||
|
||||
Using the wrong name (e.g., `new("writer-agent")` instead of `new("writer")`) will cause the aggregator to send an entity ID the backend doesn't recognize, resulting in 404 errors when interacting with the agent.
|
||||
|
||||
If you omit the `agents:` parameter entirely, the aggregator defaults to a single agent named after the Aspire resource (e.g., `"writer-agent"`). Since agent services don't expose a `/v1/entities` discovery endpoint, **the Aspire resource name must exactly match the agent name registered via `AddAIAgent(...)` in the service's `Program.cs`**.
|
||||
|
||||
## Running the sample
|
||||
|
||||
```bash
|
||||
cd dotnet/samples/05-end-to-end/DevUIAspireIntegration
|
||||
aspire run
|
||||
```
|
||||
|
||||
Once all services are running, open the **DevUI** URL shown in the Aspire dashboard. You should see both the writer and editor agents listed — select one and start a conversation.
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI.Hosting;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
builder.AddAzureChatCompletionsClient(connectionName: "foundry",
|
||||
configureSettings: settings =>
|
||||
{
|
||||
settings.TokenCredential = new DefaultAzureCredential();
|
||||
settings.EnableSensitiveTelemetryData = builder.Environment.IsDevelopment();
|
||||
})
|
||||
.AddChatClient("gpt41");
|
||||
|
||||
builder.AddAIAgent("writer", "You write short stories (300 words or less) about the specified topic.");
|
||||
|
||||
// Register services for OpenAI responses and conversations
|
||||
builder.Services.AddOpenAIResponses();
|
||||
builder.Services.AddOpenAIConversations();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Map OpenAI API endpoints — DevUI aggregator routes requests here
|
||||
app.MapOpenAIResponses();
|
||||
app.MapOpenAIConversations();
|
||||
|
||||
app.MapDefaultEndpoints();
|
||||
|
||||
app.Run();
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5280",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>a1b2c3d4-e5f6-7890-abcd-ef1234567890</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Azure.AI.Inference" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting\Microsoft.Agents.AI.Hosting.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Hosting.OpenAI\Microsoft.Agents.AI.Hosting.OpenAI.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
<ProjectReference Include="..\DevUIIntegration.ServiceDefaults\DevUIIntegration.ServiceDefaults.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"appHost": {
|
||||
"path": "DevUIIntegration.AppHost/DevUIIntegration.AppHost.csproj"
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework;
|
||||
|
||||
/// <summary>
|
||||
/// Describes an AI agent exposed by an agent service backend, used for entity discovery in DevUI.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// When added via <see cref="AgentFrameworkBuilderExtensions.WithAgentService{TSource}"/>,
|
||||
/// agent metadata is declared at the AppHost level so that the DevUI aggregator can build the
|
||||
/// entity listing without querying each backend's <c>/v1/entities</c> endpoint.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Agent services only need to expose the standard OpenAI Responses and Conversations API endpoints
|
||||
/// (<c>MapOpenAIResponses</c> and <c>MapOpenAIConversations</c>), not a custom discovery endpoint.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="Id">The unique identifier for the agent, typically matching the name passed to <c>AddAIAgent</c>.</param>
|
||||
/// <param name="Description">A short description of the agent's capabilities.</param>
|
||||
public record AgentEntityInfo(string Id, string? Description = null)
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the display name for the agent. Defaults to <see cref="Id"/> if not specified.
|
||||
/// </summary>
|
||||
public string Name { get; init; } = Id;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entity type. Defaults to <c>"agent"</c>.
|
||||
/// </summary>
|
||||
public string Type { get; init; } = "agent";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the framework identifier. Defaults to <c>"agent_framework"</c>.
|
||||
/// </summary>
|
||||
public string Framework { get; init; } = "agent_framework";
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Aspire.Hosting.AgentFramework;
|
||||
using Aspire.Hosting.ApplicationModel;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Aspire.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for adding Agent Framework DevUI resources to the application model.
|
||||
/// </summary>
|
||||
public static class AgentFrameworkBuilderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds a DevUI resource for testing AI agents in a distributed application.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// DevUI is a web-based interface for testing and debugging AI agents using the OpenAI Responses protocol.
|
||||
/// When configured with <see cref="WithAgentService{TSource}"/>, it aggregates agents from multiple backend services
|
||||
/// and provides a unified testing interface.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The aggregator runs as an in-process reverse proxy within the AppHost, requiring no external container image.
|
||||
/// It serves the DevUI frontend from embedded resources in Microsoft.Agents.AI.DevUI when available, and
|
||||
/// falls back to proxying from the first configured backend. It aggregates entity listings from all backends.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This resource is excluded from the deployment manifest as it is intended for development use only.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
|
||||
/// <param name="name">The name to give the resource.</param>
|
||||
/// <param name="port">The host port for the DevUI web interface. If not specified, a random port will be assigned.</param>
|
||||
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for chaining.</returns>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// var devui = builder.AddDevUI("devui")
|
||||
/// .WithAgentService(dotnetAgent)
|
||||
/// .WithAgentService(pythonAgent);
|
||||
/// </code>
|
||||
/// </example>
|
||||
public static IResourceBuilder<DevUIResource> AddDevUI(
|
||||
this IDistributedApplicationBuilder builder,
|
||||
string name,
|
||||
int? port = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(builder);
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
|
||||
var resource = new DevUIResource(name, port);
|
||||
|
||||
var resourceBuilder = builder.AddResource(resource)
|
||||
.ExcludeFromManifest(); // DevUI is a dev-only tool
|
||||
|
||||
// Initialize the in-process aggregator when the resource is initialized by the orchestrator
|
||||
builder.Eventing.Subscribe<InitializeResourceEvent>(resource, async (e, ct) =>
|
||||
{
|
||||
var logger = e.Logger;
|
||||
var aggregator = new DevUIAggregatorHostedService(resource, e.Services.GetRequiredService<ILoggerFactory>().CreateLogger<DevUIAggregatorHostedService>());
|
||||
|
||||
try
|
||||
{
|
||||
// Wait for dependencies (e.g. agent service backends) before starting.
|
||||
// Custom resources must manually publish BeforeResourceStartedEvent to trigger
|
||||
// the orchestrator's WaitFor mechanism.
|
||||
await e.Eventing.PublishAsync(new BeforeResourceStartedEvent(resource, e.Services), ct).ConfigureAwait(false);
|
||||
|
||||
await e.Notifications.PublishUpdateAsync(resource, snapshot => snapshot with
|
||||
{
|
||||
State = KnownResourceStates.Starting
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
await aggregator.StartAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// Allocate the endpoint so the URL appears in the Aspire dashboard
|
||||
var endpointAnnotation = resource.Annotations
|
||||
.OfType<EndpointAnnotation>()
|
||||
.First(ea => ea.Name == DevUIResource.PrimaryEndpointName);
|
||||
|
||||
endpointAnnotation.AllocatedEndpoint = new AllocatedEndpoint(
|
||||
endpointAnnotation, "localhost", aggregator.AllocatedPort);
|
||||
|
||||
var devuiUrl = $"http://localhost:{aggregator.AllocatedPort}/devui/";
|
||||
|
||||
await e.Notifications.PublishUpdateAsync(resource, snapshot => snapshot with
|
||||
{
|
||||
State = KnownResourceStates.Running,
|
||||
Urls = [new UrlSnapshot("DevUI", devuiUrl, IsInternal: false)]
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
// Shut down the aggregator when the app stops
|
||||
var lifetime = e.Services.GetRequiredService<IHostApplicationLifetime>();
|
||||
lifetime.ApplicationStopping.Register(() =>
|
||||
{
|
||||
e.Notifications.PublishUpdateAsync(resource, snapshot => snapshot with
|
||||
{
|
||||
State = KnownResourceStates.Finished
|
||||
}).GetAwaiter().GetResult();
|
||||
|
||||
aggregator.StopAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
aggregator.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to start DevUI aggregator");
|
||||
|
||||
await aggregator.DisposeAsync().ConfigureAwait(false);
|
||||
|
||||
await e.Notifications.PublishUpdateAsync(resource, snapshot => snapshot with
|
||||
{
|
||||
State = KnownResourceStates.FailedToStart
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
});
|
||||
|
||||
return resourceBuilder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures DevUI to connect to an agent service backend.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Each agent service should expose the OpenAI Responses and Conversations API endpoints
|
||||
/// (via <c>MapOpenAIResponses</c> and <c>MapOpenAIConversations</c>).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// When <paramref name="agents"/> is provided, the aggregator builds the entity listing from
|
||||
/// these declarations without querying the backend. When not provided, a single agent named
|
||||
/// after the service resource is assumed. Agent services don't need a <c>/v1/entities</c> endpoint.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <typeparam name="TSource">The type of the agent service resource.</typeparam>
|
||||
/// <param name="builder">The DevUI resource builder.</param>
|
||||
/// <param name="agentService">The agent service resource to connect to.</param>
|
||||
/// <param name="agents">
|
||||
/// Optional list of agents declared by this backend. When provided, the aggregator uses these
|
||||
/// declarations directly. When not provided, defaults to a single agent named after the
|
||||
/// <paramref name="agentService"/> resource. The backend doesn't need to expose a
|
||||
/// <c>/v1/entities</c> endpoint in either case.
|
||||
/// </param>
|
||||
/// <param name="entityIdPrefix">
|
||||
/// An optional prefix to add to entity IDs from this backend.
|
||||
/// If not specified, the resource name will be used as the prefix.
|
||||
/// </param>
|
||||
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/> for chaining.</returns>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// var writerAgent = builder.AddProject<Projects.WriterAgent>("writer-agent");
|
||||
/// var editorAgent = builder.AddProject<Projects.EditorAgent>("editor-agent");
|
||||
///
|
||||
/// builder.AddDevUI("devui")
|
||||
/// .WithAgentService(writerAgent, agents: [new("writer", "Writes short stories")])
|
||||
/// .WithAgentService(editorAgent, agents: [new("editor", "Edits and formats stories")])
|
||||
/// .WaitFor(writerAgent)
|
||||
/// .WaitFor(editorAgent);
|
||||
/// </code>
|
||||
/// </example>
|
||||
public static IResourceBuilder<DevUIResource> WithAgentService<TSource>(
|
||||
this IResourceBuilder<DevUIResource> builder,
|
||||
IResourceBuilder<TSource> agentService,
|
||||
IReadOnlyList<AgentEntityInfo>? agents = null,
|
||||
string? entityIdPrefix = null)
|
||||
where TSource : IResourceWithEndpoints
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(builder);
|
||||
ArgumentNullException.ThrowIfNull(agentService);
|
||||
|
||||
// Default to a single agent named after the service resource
|
||||
agents ??= [new AgentEntityInfo(agentService.Resource.Name)];
|
||||
|
||||
builder.WithAnnotation(new AgentServiceAnnotation(agentService.Resource, entityIdPrefix, agents));
|
||||
builder.WithRelationship(agentService.Resource, "agent-backend");
|
||||
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Aspire.Hosting.AgentFramework;
|
||||
|
||||
namespace Aspire.Hosting.ApplicationModel;
|
||||
|
||||
/// <summary>
|
||||
/// An annotation that tracks an agent service backend referenced by a DevUI resource.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This annotation is used to configure DevUI to aggregate entities from multiple
|
||||
/// agent service backends. Each annotation represents one backend that DevUI should
|
||||
/// connect to for entity discovery and request routing.
|
||||
/// </remarks>
|
||||
public class AgentServiceAnnotation : IResourceAnnotation
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AgentServiceAnnotation"/> class.
|
||||
/// </summary>
|
||||
/// <param name="agentService">The agent service resource.</param>
|
||||
/// <param name="entityIdPrefix">
|
||||
/// An optional prefix to add to entity IDs from this backend to avoid conflicts.
|
||||
/// If not specified, the resource name will be used as the prefix.
|
||||
/// </param>
|
||||
/// <param name="agents">
|
||||
/// Optional list of agents declared by this backend. When provided, the aggregator builds the entity
|
||||
/// listing directly from these declarations instead of querying the backend's <c>/v1/entities</c> endpoint.
|
||||
/// </param>
|
||||
public AgentServiceAnnotation(IResource agentService, string? entityIdPrefix = null, IReadOnlyList<AgentEntityInfo>? agents = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(agentService);
|
||||
|
||||
this.AgentService = agentService;
|
||||
this.EntityIdPrefix = entityIdPrefix;
|
||||
this.Agents = agents ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the agent service resource that exposes AI agents.
|
||||
/// </summary>
|
||||
public IResource AgentService { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the prefix to use for entity IDs from this backend.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When <c>null</c>, the resource name will be used as the prefix.
|
||||
/// Entity IDs will be formatted as "{prefix}/{entityId}" to ensure uniqueness
|
||||
/// across multiple agent backends.
|
||||
/// </remarks>
|
||||
public string? EntityIdPrefix { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of agents declared by this backend.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When non-empty, the DevUI aggregator uses these declarations to build the entity listing
|
||||
/// without querying the backend. When empty, the aggregator falls back to calling
|
||||
/// <c>GET /v1/entities</c> on the backend for discovery.
|
||||
/// </remarks>
|
||||
public IReadOnlyList<AgentEntityInfo> Agents { get; }
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>$(TargetFrameworksCore)</TargetFrameworks>
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageTags>aspire integration hosting agent-framework devui ai agents</PackageTags>
|
||||
<Description>Microsoft Agent Framework DevUI support for Aspire.</Description>
|
||||
<!-- Suppress analyzer warnings for Aspire integration code -->
|
||||
<!-- IL2026/IL3050: Suppress trimming/AOT warnings - DevUI is a dev-only tool not intended for AOT -->
|
||||
<NoWarn>$(NoWarn);CA1873;RCS1061;VSTHRD002;IL2026;IL3050</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Aspire.Hosting.AgentFramework.DevUI.UnitTests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Hosting" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,779 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Aspire.Hosting.ApplicationModel;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework;
|
||||
|
||||
/// <summary>
|
||||
/// Hosts an in-process reverse proxy that aggregates DevUI entities from multiple agent backends.
|
||||
/// Serves the DevUI frontend directly from the <c>Microsoft.Agents.AI.DevUI</c> assembly's embedded
|
||||
/// resources and intercepts API calls to provide multi-backend entity aggregation and request routing.
|
||||
/// </summary>
|
||||
internal sealed class DevUIAggregatorHostedService : IAsyncDisposable
|
||||
{
|
||||
private static readonly FileExtensionContentTypeProvider s_contentTypeProvider = new();
|
||||
|
||||
private WebApplication? _app;
|
||||
private readonly DevUIResource _resource;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
// Frontend resources loaded from the Microsoft.Agents.AI.DevUI assembly (null if unavailable)
|
||||
private readonly Dictionary<string, (string ResourceName, string ContentType)>? _frontendResources;
|
||||
|
||||
// Maps conversation IDs to backend URLs for routing GET requests that lack agent_id context.
|
||||
// Populated when the aggregator routes conversation requests to a positively-resolved backend.
|
||||
private readonly ConcurrentDictionary<string, string> _conversationBackendMap = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public DevUIAggregatorHostedService(
|
||||
DevUIResource resource,
|
||||
ILogger logger)
|
||||
{
|
||||
this._resource = resource;
|
||||
this._logger = logger;
|
||||
this._frontendResources = LoadFrontendResources(logger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the port the aggregator is listening on, available after <see cref="StartAsync"/>.
|
||||
/// </summary>
|
||||
internal int AllocatedPort { get; private set; }
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var builder = WebApplication.CreateSlimBuilder();
|
||||
builder.Logging.ClearProviders();
|
||||
|
||||
builder.Services.AddHttpClient("devui-proxy")
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
|
||||
{
|
||||
AllowAutoRedirect = false
|
||||
});
|
||||
|
||||
this._app = builder.Build();
|
||||
|
||||
// Bind to a fixed port if one was specified on the DevUI resource; otherwise use 0 for dynamic allocation.
|
||||
var port = this._resource.Port ?? 0;
|
||||
this._app.Urls.Add($"http://127.0.0.1:{port}");
|
||||
this.MapRoutes(this._app);
|
||||
|
||||
await this._app.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var serverAddresses = this._app.Services.GetRequiredService<IServer>()
|
||||
.Features.Get<IServerAddressesFeature>();
|
||||
|
||||
if (serverAddresses is not null)
|
||||
{
|
||||
var address = serverAddresses.Addresses.First();
|
||||
var uri = new Uri(address);
|
||||
this.AllocatedPort = uri.Port;
|
||||
this._logger.LogInformation("DevUI aggregator started on port {Port}", this.AllocatedPort);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (this._app is not null)
|
||||
{
|
||||
await this._app.StopAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (this._app is not null)
|
||||
{
|
||||
await this._app.DisposeAsync().ConfigureAwait(false);
|
||||
this._app = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the DevUI frontend resources from the <c>Microsoft.Agents.AI.DevUI</c> assembly.
|
||||
/// The assembly embeds the Vite SPA build output as manifest resources.
|
||||
/// Returns null if the assembly is not available.
|
||||
/// </summary>
|
||||
private static Dictionary<string, (string ResourceName, string ContentType)>? LoadFrontendResources(ILogger logger)
|
||||
{
|
||||
Assembly assembly;
|
||||
try
|
||||
{
|
||||
assembly = Assembly.Load("Microsoft.Agents.AI.DevUI");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogDebug(ex, "Microsoft.Agents.AI.DevUI assembly not found. Frontend will be proxied from backends.");
|
||||
return null;
|
||||
}
|
||||
|
||||
var prefix = $"{assembly.GetName().Name}.resources.";
|
||||
var resources = new Dictionary<string, (string, string)>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var name in assembly.GetManifestResourceNames())
|
||||
{
|
||||
if (!name.StartsWith(prefix, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The DevUI middleware maps resource names by replacing dots with slashes.
|
||||
// Both the key and lookup use the same transform, so they match.
|
||||
var key = name[prefix.Length..].Replace('.', '/');
|
||||
s_contentTypeProvider.TryGetContentType(name, out var contentType);
|
||||
resources[key] = (name, contentType ?? "application/octet-stream");
|
||||
}
|
||||
|
||||
if (resources.Count == 0)
|
||||
{
|
||||
logger.LogWarning("Microsoft.Agents.AI.DevUI assembly loaded but contains no frontend resources");
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.LogDebug("Loaded {Count} DevUI frontend resources from assembly", resources.Count);
|
||||
return resources;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serves the DevUI frontend. Uses embedded assembly resources if available,
|
||||
/// otherwise falls back to proxying from the first backend agent service.
|
||||
/// </summary>
|
||||
private async Task ServeDevUIFrontendAsync(HttpContext context, string? path)
|
||||
{
|
||||
// Redirect /devui to /devui/ so relative URLs in the SPA resolve correctly
|
||||
if (string.IsNullOrEmpty(path) && context.Request.Path.Value is { } reqPath && !reqPath.EndsWith('/'))
|
||||
{
|
||||
var redirect = reqPath + "/";
|
||||
if (context.Request.QueryString.HasValue)
|
||||
{
|
||||
redirect += context.Request.QueryString.Value;
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status301MovedPermanently;
|
||||
context.Response.Headers.Location = redirect;
|
||||
return;
|
||||
}
|
||||
|
||||
// Try embedded resources first
|
||||
if (this._frontendResources is not null)
|
||||
{
|
||||
var resourcePath = string.IsNullOrEmpty(path) ? "index.html" : path;
|
||||
|
||||
if (await this.TryServeResourceAsync(context, resourcePath).ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// SPA fallback: serve index.html for paths without a file extension (client-side routing)
|
||||
if (!resourcePath.Contains('.', StringComparison.Ordinal) &&
|
||||
await this.TryServeResourceAsync(context, "index.html").ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback: proxy from the first backend that serves /devui
|
||||
var backends = this.ResolveBackends();
|
||||
var firstBackendUrl = backends.Values.FirstOrDefault();
|
||||
|
||||
if (firstBackendUrl is null)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
context.Response.ContentType = "text/plain";
|
||||
await context.Response.WriteAsync(
|
||||
"DevUI: No agent service backends are available yet.", context.RequestAborted).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var targetPath = string.IsNullOrEmpty(path) ? "/devui/" : $"/devui/{path}";
|
||||
await ProxyRequestAsync(
|
||||
context, firstBackendUrl, targetPath + context.Request.QueryString, bodyBytes: null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<bool> TryServeResourceAsync(HttpContext context, string resourcePath)
|
||||
{
|
||||
if (this._frontendResources is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var key = resourcePath.Replace('.', '/');
|
||||
|
||||
if (!this._frontendResources.TryGetValue(key, out var entry))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Assembly assembly;
|
||||
try
|
||||
{
|
||||
assembly = Assembly.Load("Microsoft.Agents.AI.DevUI");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using var stream = assembly.GetManifestResourceStream(entry.ResourceName);
|
||||
|
||||
if (stream is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
context.Response.ContentType = entry.ContentType;
|
||||
context.Response.Headers.CacheControl = "no-cache, no-store";
|
||||
await stream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IResult GetMeta()
|
||||
{
|
||||
return Results.Json(new
|
||||
{
|
||||
ui_mode = "developer",
|
||||
version = "0.1.0",
|
||||
framework = "agent_framework",
|
||||
runtime = "dotnet",
|
||||
capabilities = new Dictionary<string, bool>
|
||||
{
|
||||
["tracing"] = false,
|
||||
["openai_proxy"] = false,
|
||||
["deployment"] = false
|
||||
},
|
||||
auth_required = false
|
||||
});
|
||||
}
|
||||
|
||||
private void MapRoutes(WebApplication app)
|
||||
{
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "healthy" }));
|
||||
|
||||
// Intercept API calls for multi-backend aggregation and routing
|
||||
app.MapGet("/v1/entities", (Delegate)this.AggregateEntitiesAsync);
|
||||
app.MapGet("/v1/entities/{**entityPath}", this.RouteEntityInfoAsync);
|
||||
app.MapPost("/v1/responses", this.RouteResponsesAsync);
|
||||
app.Map("/v1/conversations/{**path}", this.ProxyConversationsAsync);
|
||||
app.MapGet("/meta", GetMeta);
|
||||
|
||||
// Serve the DevUI frontend from embedded assembly resources
|
||||
app.Map("/devui/{**path}", this.ServeDevUIFrontendAsync);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves backend URLs from the resource's <see cref="AgentServiceAnnotation"/> annotations.
|
||||
/// This method does not cache results to ensure late-allocated backends are always discovered.
|
||||
/// </summary>
|
||||
private Dictionary<string, string> ResolveBackends()
|
||||
{
|
||||
var result = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var annotation in this._resource.Annotations.OfType<AgentServiceAnnotation>())
|
||||
{
|
||||
if (annotation.AgentService is not IResourceWithEndpoints rwe)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var prefix = annotation.EntityIdPrefix ?? annotation.AgentService.Name;
|
||||
|
||||
try
|
||||
{
|
||||
var endpoint = rwe.GetEndpoint("http");
|
||||
if (endpoint.IsAllocated)
|
||||
{
|
||||
result[prefix] = endpoint.Url;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogDebug(ex, "Backend '{Prefix}' endpoint not yet available", prefix);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<IResult> AggregateEntitiesAsync(HttpContext context)
|
||||
{
|
||||
var backends = this.ResolveBackends();
|
||||
var allEntities = new JsonArray();
|
||||
|
||||
foreach (var annotation in this._resource.Annotations.OfType<AgentServiceAnnotation>())
|
||||
{
|
||||
var prefix = annotation.EntityIdPrefix ?? annotation.AgentService.Name;
|
||||
|
||||
if (annotation.Agents.Count > 0)
|
||||
{
|
||||
// Build entities from AppHost-declared metadata — no backend call needed
|
||||
foreach (var agent in annotation.Agents)
|
||||
{
|
||||
allEntities.Add(new JsonObject
|
||||
{
|
||||
["id"] = $"{prefix}/{agent.Id}",
|
||||
["type"] = agent.Type,
|
||||
["name"] = agent.Name,
|
||||
["description"] = agent.Description,
|
||||
["framework"] = agent.Framework,
|
||||
["_original_id"] = agent.Id,
|
||||
["_backend"] = prefix
|
||||
});
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Fallback: query backend /v1/entities for discovery
|
||||
if (!backends.TryGetValue(prefix, out var baseUrl))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var httpClientFactory = context.RequestServices.GetRequiredService<IHttpClientFactory>();
|
||||
using var client = httpClientFactory.CreateClient("devui-proxy");
|
||||
var response = await client.GetAsync(
|
||||
new Uri(new Uri(baseUrl), "/v1/entities"),
|
||||
context.RequestAborted).ConfigureAwait(false);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
this._logger.LogWarning(
|
||||
"Failed to fetch entities from backend '{Prefix}' at {Url}: {Status}",
|
||||
prefix, baseUrl, response.StatusCode);
|
||||
continue;
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync(context.RequestAborted).ConfigureAwait(false);
|
||||
var doc = JsonNode.Parse(json);
|
||||
var entities = doc?["entities"]?.AsArray();
|
||||
|
||||
if (entities is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var entity in entities)
|
||||
{
|
||||
if (entity is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var cloned = entity.DeepClone();
|
||||
var id = cloned["id"]?.GetValue<string>() ?? cloned["name"]?.GetValue<string>();
|
||||
|
||||
if (id is not null)
|
||||
{
|
||||
cloned["id"] = $"{prefix}/{id}";
|
||||
cloned["_original_id"] = id;
|
||||
cloned["_backend"] = prefix;
|
||||
}
|
||||
|
||||
allEntities.Add(cloned);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
this._logger.LogWarning(ex, "Error fetching entities from backend '{Prefix}' at {Url}", prefix, baseUrl);
|
||||
}
|
||||
}
|
||||
|
||||
return Results.Json(new { entities = allEntities });
|
||||
}
|
||||
|
||||
private async Task RouteEntityInfoAsync(HttpContext context, string entityPath)
|
||||
{
|
||||
var (backendUrl, actualPath) = this.ResolveBackend(entityPath);
|
||||
|
||||
if (backendUrl is null)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return;
|
||||
}
|
||||
|
||||
var httpClientFactory = context.RequestServices.GetRequiredService<IHttpClientFactory>();
|
||||
using var client = httpClientFactory.CreateClient("devui-proxy");
|
||||
var targetUrl = new Uri(new Uri(backendUrl), $"/v1/entities/{actualPath}");
|
||||
|
||||
using var response = await client.GetAsync(targetUrl, context.RequestAborted).ConfigureAwait(false);
|
||||
await CopyResponseAsync(response, context).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task RouteResponsesAsync(HttpContext context)
|
||||
{
|
||||
var bodyBytes = await ReadRequestBodyAsync(context.Request).ConfigureAwait(false);
|
||||
var json = JsonNode.Parse(bodyBytes);
|
||||
var entityId = json?["metadata"]?["entity_id"]?.GetValue<string>();
|
||||
|
||||
if (entityId is null)
|
||||
{
|
||||
var firstBackend = this.ResolveBackends().Values.FirstOrDefault();
|
||||
if (firstBackend is null)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status502BadGateway;
|
||||
return;
|
||||
}
|
||||
|
||||
await ProxyRequestAsync(context, firstBackend, "/v1/responses", bodyBytes).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var (backendUrl, actualEntityId) = this.ResolveBackend(entityId);
|
||||
|
||||
if (backendUrl is null)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
await context.Response.WriteAsJsonAsync(
|
||||
new { error = $"No backend found for entity '{entityId}'" },
|
||||
context.RequestAborted).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Rewrite entity_id to the un-prefixed original value
|
||||
json!["metadata"]!["entity_id"] = actualEntityId;
|
||||
var rewrittenBody = JsonSerializer.SerializeToUtf8Bytes(json);
|
||||
|
||||
await ProxyRequestAsync(context, backendUrl, "/v1/responses", rewrittenBody, streaming: true).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ProxyConversationsAsync(HttpContext context, string? path)
|
||||
{
|
||||
// Try to determine the backend from agent_id query param or request body
|
||||
string? backendUrl = null;
|
||||
string? actualAgentId = null;
|
||||
|
||||
var agentId = context.Request.Query["agent_id"].FirstOrDefault();
|
||||
if (agentId is not null)
|
||||
{
|
||||
(backendUrl, actualAgentId) = this.ResolveBackend(agentId);
|
||||
}
|
||||
|
||||
// Build query string with rewritten agent_id if we resolved from query param
|
||||
var queryString = (agentId is not null && actualAgentId is not null)
|
||||
? RewriteAgentIdInQueryString(context.Request.QueryString, actualAgentId)
|
||||
: context.Request.QueryString.ToString();
|
||||
|
||||
// Try conversation→backend map for previously-seen conversations
|
||||
if (backendUrl is null)
|
||||
{
|
||||
var conversationId = ExtractConversationId(path);
|
||||
if (conversationId is not null && this._conversationBackendMap.TryGetValue(conversationId, out var mappedUrl))
|
||||
{
|
||||
backendUrl = mappedUrl;
|
||||
}
|
||||
}
|
||||
|
||||
// Always read the request body when present so it isn't dropped during proxying
|
||||
byte[]? bodyBytes = null;
|
||||
if (context.Request.ContentLength > 0)
|
||||
{
|
||||
bodyBytes = await ReadRequestBodyAsync(context.Request).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Try to resolve backend from request body metadata when not yet determined
|
||||
if (backendUrl is null && bodyBytes is not null)
|
||||
{
|
||||
var json = JsonNode.Parse(bodyBytes);
|
||||
var entityId = json?["metadata"]?["entity_id"]?.GetValue<string>()
|
||||
?? json?["metadata"]?["agent_id"]?.GetValue<string>();
|
||||
|
||||
if (entityId is not null)
|
||||
{
|
||||
string actualId;
|
||||
(backendUrl, actualId) = this.ResolveBackend(entityId);
|
||||
|
||||
if (backendUrl is not null)
|
||||
{
|
||||
// Rewrite the entity/agent id to the un-prefixed value
|
||||
if (json?["metadata"]?["entity_id"] is not null)
|
||||
{
|
||||
json!["metadata"]!["entity_id"] = actualId;
|
||||
}
|
||||
|
||||
if (json?["metadata"]?["agent_id"] is not null)
|
||||
{
|
||||
json!["metadata"]!["agent_id"] = actualId;
|
||||
}
|
||||
|
||||
bodyBytes = JsonSerializer.SerializeToUtf8Bytes(json);
|
||||
var targetPath = string.IsNullOrEmpty(path) ? "/v1/conversations" : $"/v1/conversations/{path}";
|
||||
|
||||
// Also rewrite query string agent_id if present
|
||||
var bodyQueryString = (agentId is not null)
|
||||
? RewriteAgentIdInQueryString(context.Request.QueryString, actualId)
|
||||
: context.Request.QueryString.ToString();
|
||||
|
||||
await this.ProxyAndRecordConversationAsync(
|
||||
context, backendUrl, path, targetPath + bodyQueryString, bodyBytes).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Couldn't determine backend from body; proxy raw bytes to first backend
|
||||
backendUrl = this.ResolveBackends().Values.FirstOrDefault();
|
||||
if (backendUrl is null)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status502BadGateway;
|
||||
return;
|
||||
}
|
||||
|
||||
var targetPathFallback = string.IsNullOrEmpty(path) ? "/v1/conversations" : $"/v1/conversations/{path}";
|
||||
await ProxyRequestAsync(
|
||||
context, backendUrl, targetPathFallback + queryString, bodyBytes).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Route to resolved backend (from query or conversation map), or fall back to first backend
|
||||
var backendKnown = backendUrl is not null;
|
||||
backendUrl ??= this.ResolveBackends().Values.FirstOrDefault();
|
||||
if (backendUrl is null)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status502BadGateway;
|
||||
return;
|
||||
}
|
||||
|
||||
var convPath = string.IsNullOrEmpty(path) ? "/v1/conversations" : $"/v1/conversations/{path}";
|
||||
if (backendKnown)
|
||||
{
|
||||
await this.ProxyAndRecordConversationAsync(
|
||||
context, backendUrl, path, convPath + queryString, bodyBytes).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ProxyRequestAsync(
|
||||
context, backendUrl, convPath + queryString, bodyBytes).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites the agent_id query parameter to the un-prefixed value for backend routing.
|
||||
/// </summary>
|
||||
internal static string RewriteAgentIdInQueryString(QueryString queryString, string actualAgentId)
|
||||
{
|
||||
if (!queryString.HasValue)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(queryString.Value);
|
||||
query["agent_id"] = actualAgentId;
|
||||
|
||||
return QueryString.Create(query).ToString();
|
||||
}
|
||||
|
||||
private static string? ExtractConversationId(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var slashIndex = path.IndexOf('/');
|
||||
return slashIndex > 0 ? path[..slashIndex] : path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the conversation→backend mapping and proxies the request.
|
||||
/// For creation POSTs (no conversation ID in path), intercepts the response to capture the new ID.
|
||||
/// </summary>
|
||||
private async Task ProxyAndRecordConversationAsync(
|
||||
HttpContext context,
|
||||
string backendUrl,
|
||||
string? conversationPath,
|
||||
string targetUrl,
|
||||
byte[]? bodyBytes)
|
||||
{
|
||||
var conversationId = ExtractConversationId(conversationPath);
|
||||
if (conversationId is not null)
|
||||
{
|
||||
// We already know the conversation ID — record and proxy normally
|
||||
this._conversationBackendMap[conversationId] = backendUrl;
|
||||
await ProxyRequestAsync(context, backendUrl, targetUrl, bodyBytes).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Creation POST: intercept response to capture the new conversation ID
|
||||
if (!context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await ProxyRequestAsync(context, backendUrl, targetUrl, bodyBytes).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var originalBody = context.Response.Body;
|
||||
using var buffer = new MemoryStream();
|
||||
context.Response.Body = buffer;
|
||||
|
||||
try
|
||||
{
|
||||
await ProxyRequestAsync(context, backendUrl, targetUrl, bodyBytes).ConfigureAwait(false);
|
||||
|
||||
if (context.Response.StatusCode is >= 200 and < 300)
|
||||
{
|
||||
buffer.Position = 0;
|
||||
try
|
||||
{
|
||||
using var doc = await JsonDocument.ParseAsync(
|
||||
buffer, cancellationToken: context.RequestAborted).ConfigureAwait(false);
|
||||
if (doc.RootElement.TryGetProperty("id", out var idProp) &&
|
||||
idProp.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
var createdId = idProp.GetString();
|
||||
if (createdId is not null)
|
||||
{
|
||||
this._conversationBackendMap[createdId] = backendUrl;
|
||||
this._logger.LogDebug(
|
||||
"Recorded conversation '{ConversationId}' → backend '{BackendUrl}'",
|
||||
createdId, backendUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort: response may not be parseable JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
context.Response.Body = originalBody;
|
||||
buffer.Position = 0;
|
||||
await buffer.CopyToAsync(originalBody, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ProxyRequestAsync(
|
||||
HttpContext context,
|
||||
string backendUrl,
|
||||
string path,
|
||||
byte[]? bodyBytes,
|
||||
bool streaming = false)
|
||||
{
|
||||
var httpClientFactory = context.RequestServices.GetRequiredService<IHttpClientFactory>();
|
||||
using var client = httpClientFactory.CreateClient("devui-proxy");
|
||||
|
||||
var targetUri = new Uri(new Uri(backendUrl), path);
|
||||
using var request = new HttpRequestMessage(new HttpMethod(context.Request.Method), targetUri);
|
||||
|
||||
foreach (var header in context.Request.Headers)
|
||||
{
|
||||
if (IsHopByHopHeader(header.Key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
request.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
|
||||
}
|
||||
|
||||
if (bodyBytes is not null)
|
||||
{
|
||||
request.Content = new ByteArrayContent(bodyBytes);
|
||||
if (context.Request.ContentType is not null)
|
||||
{
|
||||
request.Content.Headers.ContentType =
|
||||
System.Net.Http.Headers.MediaTypeHeaderValue.Parse(context.Request.ContentType);
|
||||
}
|
||||
}
|
||||
|
||||
var completionOption = streaming
|
||||
? HttpCompletionOption.ResponseHeadersRead
|
||||
: HttpCompletionOption.ResponseContentRead;
|
||||
|
||||
using var response = await client.SendAsync(
|
||||
request, completionOption, context.RequestAborted).ConfigureAwait(false);
|
||||
|
||||
if (streaming && response.Content.Headers.ContentType?.MediaType == "text/event-stream")
|
||||
{
|
||||
context.Response.StatusCode = (int)response.StatusCode;
|
||||
context.Response.ContentType = "text/event-stream";
|
||||
context.Response.Headers.CacheControl = "no-cache";
|
||||
|
||||
using var stream = await response.Content.ReadAsStreamAsync(context.RequestAborted).ConfigureAwait(false);
|
||||
await stream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await CopyResponseAsync(response, context).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private (string? BackendUrl, string ActualPath) ResolveBackend(string prefixedId)
|
||||
{
|
||||
var backends = this.ResolveBackends();
|
||||
var slashIndex = prefixedId.IndexOf('/');
|
||||
|
||||
if (slashIndex > 0)
|
||||
{
|
||||
var prefix = prefixedId[..slashIndex];
|
||||
var rest = prefixedId[(slashIndex + 1)..];
|
||||
|
||||
if (backends.TryGetValue(prefix, out var url))
|
||||
{
|
||||
return (url, rest);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: check all prefixes
|
||||
foreach (var (prefix, url) in backends)
|
||||
{
|
||||
if (prefixedId.StartsWith(prefix + "/", StringComparison.Ordinal))
|
||||
{
|
||||
return (url, prefixedId[(prefix.Length + 1)..]);
|
||||
}
|
||||
}
|
||||
|
||||
return (null, prefixedId);
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadRequestBodyAsync(HttpRequest request)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
await request.Body.CopyToAsync(ms).ConfigureAwait(false);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private static async Task CopyResponseAsync(HttpResponseMessage response, HttpContext context)
|
||||
{
|
||||
context.Response.StatusCode = (int)response.StatusCode;
|
||||
|
||||
foreach (var header in response.Headers.Where(h => !IsHopByHopHeader(h.Key)))
|
||||
{
|
||||
context.Response.Headers[header.Key] = header.Value.ToArray();
|
||||
}
|
||||
|
||||
foreach (var header in response.Content.Headers)
|
||||
{
|
||||
context.Response.Headers[header.Key] = header.Value.ToArray();
|
||||
}
|
||||
|
||||
await response.Content.CopyToAsync(context.Response.Body).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static bool IsHopByHopHeader(string headerName)
|
||||
{
|
||||
return headerName.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase)
|
||||
|| headerName.Equals("Connection", StringComparison.OrdinalIgnoreCase)
|
||||
|| headerName.Equals("Keep-Alive", StringComparison.OrdinalIgnoreCase)
|
||||
|| headerName.Equals("Host", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Aspire.Hosting.ApplicationModel;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a DevUI resource for testing AI agents in a distributed application.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// DevUI aggregates agents from multiple backend services and provides a unified
|
||||
/// web interface for testing and debugging AI agents using the OpenAI Responses protocol.
|
||||
/// The aggregator runs as an in-process reverse proxy within the AppHost, requiring no
|
||||
/// external container image.
|
||||
/// </remarks>
|
||||
/// <param name="name">The name of the DevUI resource.</param>
|
||||
public class DevUIResource(string name) : Resource(name), IResourceWithEndpoints, IResourceWithWaitSupport
|
||||
{
|
||||
internal const string PrimaryEndpointName = "http";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DevUIResource"/> class with endpoint annotations.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the resource.</param>
|
||||
/// <param name="port">An optional fixed port. If <c>null</c>, a dynamic port is assigned.</param>
|
||||
internal DevUIResource(string name, int? port) : this(name)
|
||||
{
|
||||
this.Port = port;
|
||||
this.Annotations.Add(new EndpointAnnotation(
|
||||
ProtocolType.Tcp,
|
||||
uriScheme: "http",
|
||||
name: PrimaryEndpointName,
|
||||
port: port,
|
||||
isProxied: false)
|
||||
{
|
||||
TargetHost = "localhost"
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional fixed port for the DevUI web interface.
|
||||
/// </summary>
|
||||
internal int? Port { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the primary HTTP endpoint for the DevUI web interface.
|
||||
/// </summary>
|
||||
public EndpointReference PrimaryEndpoint => field ??= new(this, PrimaryEndpointName);
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
# Aspire.Hosting.AgentFramework.DevUI library
|
||||
|
||||
Provides extension methods and resource definitions for an Aspire AppHost to configure a DevUI resource for testing and debugging AI agents built with [Microsoft Agent Framework](https://github.com/microsoft/agent-framework).
|
||||
|
||||
## Getting started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Agent services must expose the OpenAI Responses and Conversations API endpoints. This is compatible with services using [Microsoft Agent Framework](https://github.com/microsoft/agent-framework) with `MapOpenAIResponses()` and `MapOpenAIConversations()` mapped.
|
||||
|
||||
### Install the package
|
||||
|
||||
In your AppHost project, install the Aspire Agent Framework DevUI Hosting library with [NuGet](https://www.nuget.org):
|
||||
|
||||
```dotnetcli
|
||||
dotnet add package Aspire.Hosting.AgentFramework.DevUI
|
||||
```
|
||||
|
||||
## Usage example
|
||||
|
||||
Then, in the _AppHost.cs_ file of `AppHost`, add a DevUI resource and connect it to your agent services using the following methods:
|
||||
|
||||
```csharp
|
||||
var writerAgent = builder.AddProject<Projects.WriterAgent>("writer-agent")
|
||||
.WithHttpHealthCheck("/health");
|
||||
|
||||
var editorAgent = builder.AddProject<Projects.EditorAgent>("editor-agent")
|
||||
.WithHttpHealthCheck("/health");
|
||||
|
||||
var devui = builder.AddDevUI("devui")
|
||||
.WithAgentService(writerAgent)
|
||||
.WithAgentService(editorAgent)
|
||||
.WaitFor(writerAgent)
|
||||
.WaitFor(editorAgent);
|
||||
```
|
||||
|
||||
Each agent service only needs to map the standard OpenAI API endpoints — no custom discovery endpoints are required:
|
||||
|
||||
```csharp
|
||||
// In the agent service's Program.cs
|
||||
builder.AddAIAgent("writer", "You write short stories.");
|
||||
builder.Services.AddOpenAIResponses();
|
||||
builder.Services.AddOpenAIConversations();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapOpenAIResponses();
|
||||
app.MapOpenAIConversations();
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
`AddDevUI` starts an **in-process aggregator** inside the AppHost — no external container image is needed. The aggregator is a lightweight Kestrel server that:
|
||||
|
||||
1. **Serves the DevUI frontend** from the `Microsoft.Agents.AI.DevUI` assembly's embedded resources (loaded at runtime). If the assembly is not available, it falls back to proxying the frontend from the first backend.
|
||||
2. **Aggregates entities** from all configured agent service backends into a single `/v1/entities` listing. Each entity ID is prefixed with the backend name to ensure uniqueness across services (e.g., `writer-agent/writer`, `editor-agent/editor`).
|
||||
3. **Routes requests** to the correct backend based on the entity ID prefix. When DevUI sends a `POST /v1/responses` or `/v1/conversations` request, the aggregator strips the prefix and forwards it to the appropriate service.
|
||||
4. **Streams SSE responses** for the `/v1/responses` endpoint, so agent responses stream back to the DevUI frontend in real time.
|
||||
|
||||
The aggregator publishes its URL to the Aspire dashboard, where it appears as a clickable link.
|
||||
|
||||
## Agent discovery
|
||||
|
||||
By default, `WithAgentService` declares a single agent named after the Aspire resource. You can provide explicit agent metadata when the agent name differs from the resource name, or when a service hosts multiple agents:
|
||||
|
||||
```csharp
|
||||
builder.AddDevUI("devui")
|
||||
.WithAgentService(writerAgent, agents: [new("writer", "Writes short stories")])
|
||||
.WithAgentService(editorAgent, agents: [new("editor", "Edits and formats stories")]);
|
||||
```
|
||||
|
||||
Agent metadata is declared at the AppHost level so the aggregator builds the entity listing directly — agent services don't need a `/v1/entities` endpoint.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Custom entity ID prefix
|
||||
|
||||
By default, entity IDs are prefixed with the Aspire resource name. You can specify a custom prefix:
|
||||
|
||||
```csharp
|
||||
builder.AddDevUI("devui")
|
||||
.WithAgentService(myService, entityIdPrefix: "custom-prefix");
|
||||
```
|
||||
|
||||
### Custom port
|
||||
|
||||
You can specify a fixed host port for the DevUI web interface:
|
||||
|
||||
```csharp
|
||||
builder.AddDevUI("devui", port: 8090);
|
||||
```
|
||||
|
||||
### DevUI frontend assembly
|
||||
|
||||
To serve the DevUI frontend directly from the aggregator (instead of proxying from a backend), add the `Microsoft.Agents.AI.DevUI` NuGet package to your AppHost project. The aggregator loads its embedded resources at runtime via `Assembly.Load`.
|
||||
|
||||
## Additional documentation
|
||||
|
||||
* https://github.com/microsoft/agent-framework
|
||||
* https://github.com/microsoft/agent-framework/tree/main/dotnet/src/Microsoft.Agents.AI.DevUI
|
||||
|
||||
## Feedback & contributing
|
||||
|
||||
https://github.com/dotnet/aspire
|
||||
@@ -1,7 +1,5 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
|
||||
|
||||
/// <summary>
|
||||
@@ -27,11 +25,6 @@ public sealed record class ActionExecutorResult
|
||||
|
||||
internal static ActionExecutorResult ThrowIfNot(object? message)
|
||||
{
|
||||
if (message is PortableValue portableValue && portableValue.IsType(out ActionExecutorResult? unwrapped))
|
||||
{
|
||||
return unwrapped;
|
||||
}
|
||||
|
||||
if (message is not ActionExecutorResult executorMessage)
|
||||
{
|
||||
throw new DeclarativeActionException($"Unexpected message type: {message?.GetType().Name ?? "(null)"} (Expected: {nameof(ActionExecutorResult)})");
|
||||
|
||||
+2
-4
@@ -27,11 +27,9 @@ internal sealed class InvokeAzureAgentExecutor(InvokeAzureAgent model, ResponseA
|
||||
public static string Resume(string id) => $"{id}_{nameof(Resume)}";
|
||||
}
|
||||
|
||||
public static bool RequiresInput(object? message) =>
|
||||
message is ExternalInputRequest || (message is PortableValue pv && pv.IsType(out ExternalInputRequest? _));
|
||||
public static bool RequiresInput(object? message) => message is ExternalInputRequest;
|
||||
|
||||
public static bool RequiresNothing(object? message) =>
|
||||
message is ActionExecutorResult || (message is PortableValue pv && pv.IsType(out ActionExecutorResult? _));
|
||||
public static bool RequiresNothing(object? message) => message is ActionExecutorResult;
|
||||
|
||||
private AzureAgentUsage AgentUsage => Throw.IfNull(this.Model.Agent, $"{nameof(this.Model)}.{nameof(this.Model.Agent)}");
|
||||
private AzureAgentInput? AgentInput => this.Model.Input;
|
||||
|
||||
+2
-4
@@ -46,14 +46,12 @@ internal sealed class InvokeMcpToolExecutor(
|
||||
/// <summary>
|
||||
/// Determines if the message indicates external input is required.
|
||||
/// </summary>
|
||||
public static bool RequiresInput(object? message) =>
|
||||
message is ExternalInputRequest || (message is PortableValue pv && pv.IsType(out ExternalInputRequest? _));
|
||||
public static bool RequiresInput(object? message) => message is ExternalInputRequest;
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the message indicates no external input is required.
|
||||
/// </summary>
|
||||
public static bool RequiresNothing(object? message) =>
|
||||
message is ActionExecutorResult || (message is PortableValue pv && pv.IsType(out ActionExecutorResult? _));
|
||||
public static bool RequiresNothing(object? message) => message is ActionExecutorResult;
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override bool EmitResultEvent => false;
|
||||
|
||||
@@ -48,7 +48,7 @@ internal static class AIAgentsAbstractionsExtensions
|
||||
/// any that have a different <see cref="ChatMessage.AuthorName"/> from <paramref name="targetAgentName"/> to
|
||||
/// <see cref="ChatRole.User"/>.
|
||||
/// </summary>
|
||||
public static List<ChatMessage>? ChangeAssistantToUserForOtherParticipants(this IEnumerable<ChatMessage> messages, string targetAgentName)
|
||||
public static List<ChatMessage>? ChangeAssistantToUserForOtherParticipants(this List<ChatMessage> messages, string targetAgentName)
|
||||
{
|
||||
List<ChatMessage>? roleChanged = null;
|
||||
foreach (var m in messages)
|
||||
|
||||
@@ -219,17 +219,13 @@ public class HandoffWorkflowBuilderCore<TBuilder> where TBuilder : HandoffWorkfl
|
||||
|
||||
if (string.IsNullOrWhiteSpace(handoffReason))
|
||||
{
|
||||
handoffReason = (string.IsNullOrWhiteSpace(to.Description) ? null : to.Description)
|
||||
?? (string.IsNullOrWhiteSpace(to.Name) ? null : $"handoff to {to.Name}")
|
||||
?? to.GetService<ChatClientAgent>()?.Instructions;
|
||||
|
||||
handoffReason = to.Description ?? to.Name ?? (to as ChatClientAgent)?.Instructions;
|
||||
if (string.IsNullOrWhiteSpace(handoffReason))
|
||||
{
|
||||
Throw.ArgumentException(
|
||||
nameof(to),
|
||||
$"The provided target agent '{(string.IsNullOrWhiteSpace(to.Name) ? to.Id : to.Name)}' has no description, name, or instructions, and no " +
|
||||
"handoff description has been provided. At least one of these is required to register a handoff so that the appropriate target agent can " +
|
||||
"be chosen.");
|
||||
$"The provided target agent '{to.Name ?? to.Id}' has no description, name, or instructions, and no handoff description has been provided. " +
|
||||
"At least one of these is required to register a handoff so that the appropriate target agent can be chosen.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ using System.ComponentModel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
@@ -32,6 +31,140 @@ internal sealed class HandoffAgentExecutorOptions
|
||||
public HandoffToolCallFilteringBehavior ToolCallFilteringBehavior { get; set; } = HandoffToolCallFilteringBehavior.HandoffOnly;
|
||||
}
|
||||
|
||||
[Experimental(DiagnosticConstants.ExperimentalFeatureDiagnostic)]
|
||||
internal sealed class HandoffMessagesFilter
|
||||
{
|
||||
private readonly HandoffToolCallFilteringBehavior _filteringBehavior;
|
||||
|
||||
public HandoffMessagesFilter(HandoffToolCallFilteringBehavior filteringBehavior)
|
||||
{
|
||||
this._filteringBehavior = filteringBehavior;
|
||||
}
|
||||
|
||||
[Experimental(DiagnosticConstants.ExperimentalFeatureDiagnostic)]
|
||||
internal static bool IsHandoffFunctionName(string name)
|
||||
{
|
||||
return name.StartsWith(HandoffWorkflowBuilder.FunctionPrefix, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public IEnumerable<ChatMessage> FilterMessages(List<ChatMessage> messages)
|
||||
{
|
||||
if (this._filteringBehavior == HandoffToolCallFilteringBehavior.None)
|
||||
{
|
||||
return messages;
|
||||
}
|
||||
|
||||
Dictionary<string, FilterCandidateState> filteringCandidates = new();
|
||||
List<ChatMessage> filteredMessages = [];
|
||||
HashSet<int> messagesToRemove = [];
|
||||
|
||||
bool filterHandoffOnly = this._filteringBehavior == HandoffToolCallFilteringBehavior.HandoffOnly;
|
||||
foreach (ChatMessage unfilteredMessage in messages)
|
||||
{
|
||||
ChatMessage filteredMessage = unfilteredMessage.Clone();
|
||||
|
||||
// .Clone() is shallow, so we cannot modify the contents of the cloned message in place.
|
||||
List<AIContent> contents = [];
|
||||
contents.Capacity = unfilteredMessage.Contents?.Count ?? 0;
|
||||
filteredMessage.Contents = contents;
|
||||
|
||||
// Because this runs after the role changes from assistant to user for the target agent, we cannot rely on tool calls
|
||||
// originating only from messages with the Assistant role. Instead, we need to inspect the contents of all non-Tool (result)
|
||||
// FunctionCallContent.
|
||||
if (unfilteredMessage.Role != ChatRole.Tool)
|
||||
{
|
||||
for (int i = 0; i < unfilteredMessage.Contents!.Count; i++)
|
||||
{
|
||||
AIContent content = unfilteredMessage.Contents[i];
|
||||
if (content is not FunctionCallContent fcc || (filterHandoffOnly && !IsHandoffFunctionName(fcc.Name)))
|
||||
{
|
||||
filteredMessage.Contents.Add(content);
|
||||
|
||||
// Track non-handoff function calls so their tool results are preserved in HandoffOnly mode
|
||||
if (filterHandoffOnly && content is FunctionCallContent nonHandoffFcc)
|
||||
{
|
||||
filteringCandidates[nonHandoffFcc.CallId] = new FilterCandidateState(nonHandoffFcc.CallId)
|
||||
{
|
||||
IsHandoffFunction = false,
|
||||
};
|
||||
}
|
||||
}
|
||||
else if (filterHandoffOnly)
|
||||
{
|
||||
if (!filteringCandidates.TryGetValue(fcc.CallId, out FilterCandidateState? candidateState))
|
||||
{
|
||||
filteringCandidates[fcc.CallId] = new FilterCandidateState(fcc.CallId)
|
||||
{
|
||||
IsHandoffFunction = true,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
candidateState.IsHandoffFunction = true;
|
||||
(int messageIndex, int contentIndex) = candidateState.FunctionCallResultLocation!.Value;
|
||||
ChatMessage messageToFilter = filteredMessages[messageIndex];
|
||||
messageToFilter.Contents.RemoveAt(contentIndex);
|
||||
if (messageToFilter.Contents.Count == 0)
|
||||
{
|
||||
messagesToRemove.Add(messageIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// All mode: strip all FunctionCallContent
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!filterHandoffOnly)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int i = 0; i < unfilteredMessage.Contents!.Count; i++)
|
||||
{
|
||||
AIContent content = unfilteredMessage.Contents[i];
|
||||
if (content is not FunctionResultContent frc
|
||||
|| (filteringCandidates.TryGetValue(frc.CallId, out FilterCandidateState? candidateState)
|
||||
&& candidateState.IsHandoffFunction is false))
|
||||
{
|
||||
// Either this is not a function result content, so we should let it through, or it is a FRC that
|
||||
// we know is not related to a handoff call. In either case, we should include it.
|
||||
filteredMessage.Contents.Add(content);
|
||||
}
|
||||
else if (candidateState is null)
|
||||
{
|
||||
// We haven't seen the corresponding function call yet, so add it as a candidate to be filtered later
|
||||
filteringCandidates[frc.CallId] = new FilterCandidateState(frc.CallId)
|
||||
{
|
||||
FunctionCallResultLocation = (filteredMessages.Count, filteredMessage.Contents.Count),
|
||||
};
|
||||
}
|
||||
// else we have seen the corresponding function call and it is a handoff, so we should filter it out.
|
||||
}
|
||||
}
|
||||
|
||||
if (filteredMessage.Contents.Count > 0)
|
||||
{
|
||||
filteredMessages.Add(filteredMessage);
|
||||
}
|
||||
}
|
||||
|
||||
return filteredMessages.Where((_, index) => !messagesToRemove.Contains(index));
|
||||
}
|
||||
|
||||
private class FilterCandidateState(string callId)
|
||||
{
|
||||
public (int MessageIndex, int ContentIndex)? FunctionCallResultLocation { get; set; }
|
||||
|
||||
public string CallId => callId;
|
||||
|
||||
public bool? IsHandoffFunction { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
internal struct AgentInvocationResult(AgentResponse agentResponse, string? handoffTargetId)
|
||||
{
|
||||
public AgentResponse Response => agentResponse;
|
||||
@@ -42,31 +175,19 @@ internal struct AgentInvocationResult(AgentResponse agentResponse, string? hando
|
||||
public bool IsHandoffRequested => this.HandoffTargetId != null;
|
||||
}
|
||||
|
||||
internal record HandoffAgentHostState(
|
||||
HandoffState? IncomingState,
|
||||
int ConversationBookmark)
|
||||
internal record HandoffAgentHostState(HandoffState? CurrentTurnState, List<ChatMessage> FilteredIncomingMessages, List<ChatMessage> TurnMessages)
|
||||
{
|
||||
[MemberNotNullWhen(true, nameof(IncomingState))]
|
||||
[JsonIgnore]
|
||||
public bool IsTakingTurn => this.IncomingState != null;
|
||||
}
|
||||
public HandoffState PrepareHandoff(AgentInvocationResult invocationResult, string currentAgentId)
|
||||
{
|
||||
if (this.CurrentTurnState == null)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot create a handoff request: Out of turn.");
|
||||
}
|
||||
|
||||
internal sealed record StateRef<TState>(string Key, string? ScopeName)
|
||||
{
|
||||
public ValueTask InvokeWithStateAsync(Func<TState?, IWorkflowContext, CancellationToken, ValueTask<TState?>> invocation,
|
||||
IWorkflowContext context,
|
||||
CancellationToken cancellationToken)
|
||||
=> context.InvokeWithStateAsync(invocation, this.Key, this.ScopeName, cancellationToken);
|
||||
IEnumerable<ChatMessage> allMessages = [.. this.CurrentTurnState.Messages, .. this.TurnMessages, .. invocationResult.Response.Messages];
|
||||
|
||||
public ValueTask InvokeWithStateAsync(Func<TState?, IWorkflowContext, CancellationToken, ValueTask> invocation,
|
||||
IWorkflowContext context,
|
||||
CancellationToken cancellationToken)
|
||||
=> context.InvokeWithStateAsync<TState>(
|
||||
async (state, ctx, ct) =>
|
||||
{
|
||||
await invocation(state, ctx, ct).ConfigureAwait(false);
|
||||
return state;
|
||||
}, this.Key, this.ScopeName, cancellationToken);
|
||||
return new(this.CurrentTurnState.TurnToken, invocationResult.HandoffTargetId, allMessages.ToList(), currentAgentId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executor used to represent an agent in a handoffs workflow, responding to <see cref="HandoffState"/> events.</summary>
|
||||
@@ -87,13 +208,7 @@ internal sealed class HandoffAgentExecutor :
|
||||
private readonly HashSet<string> _handoffFunctionNames = [];
|
||||
private readonly Dictionary<string, string> _handoffFunctionToAgentId = [];
|
||||
|
||||
private readonly StateRef<HandoffSharedState> _sharedStateRef = new(HandoffConstants.HandoffSharedStateKey,
|
||||
HandoffConstants.HandoffSharedStateScope);
|
||||
|
||||
internal const string AgentSessionKey = nameof(AgentSession);
|
||||
private AgentSession? _session;
|
||||
|
||||
private static HandoffAgentHostState InitialStateFactory() => new(null, 0);
|
||||
private static HandoffAgentHostState InitialStateFactory() => new(null, [], []);
|
||||
|
||||
public HandoffAgentExecutor(AIAgent agent, HashSet<HandoffTarget> handoffs, HandoffAgentExecutorOptions options)
|
||||
: base(IdFor(agent), InitialStateFactory)
|
||||
@@ -176,18 +291,13 @@ internal sealed class HandoffAgentExecutor :
|
||||
// resumes can be processed in one invocation.
|
||||
return this.InvokeWithStateAsync((state, ctx, ct) =>
|
||||
{
|
||||
if (!state.IsTakingTurn)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot process user responses when not taking a turn in Handoff Orchestration.");
|
||||
}
|
||||
|
||||
ChatMessage userMessage = new(ChatRole.User, [response])
|
||||
state.TurnMessages.Add(new ChatMessage(ChatRole.User, [response])
|
||||
{
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
};
|
||||
});
|
||||
|
||||
return this.ContinueTurnAsync(state, [userMessage], ctx, ct);
|
||||
return this.ContinueTurnAsync(state, ctx, ct);
|
||||
}, context, skipCache: false, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -205,44 +315,24 @@ internal sealed class HandoffAgentExecutor :
|
||||
// resumes can be processed in one invocation.
|
||||
return this.InvokeWithStateAsync((state, ctx, ct) =>
|
||||
{
|
||||
if (!state.IsTakingTurn)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot process user responses in when not taking a turn in Handoff Orchestration.");
|
||||
}
|
||||
state.TurnMessages.Add(
|
||||
new ChatMessage(ChatRole.Tool, [result])
|
||||
{
|
||||
AuthorName = this._agent.Name ?? this._agent.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
});
|
||||
|
||||
ChatMessage toolMessage = new(ChatRole.Tool, [result])
|
||||
{
|
||||
AuthorName = this._agent.Name ?? this._agent.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
};
|
||||
|
||||
return this.ContinueTurnAsync(state, [toolMessage], ctx, ct);
|
||||
return this.ContinueTurnAsync(state, ctx, ct);
|
||||
}, context, skipCache: false, cancellationToken);
|
||||
}
|
||||
|
||||
private async ValueTask<HandoffAgentHostState?> ContinueTurnAsync(HandoffAgentHostState state, List<ChatMessage> incomingMessages, IWorkflowContext context, CancellationToken cancellationToken, bool skipAddIncoming = false)
|
||||
private async ValueTask<HandoffAgentHostState?> ContinueTurnAsync(HandoffAgentHostState state, IWorkflowContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!state.IsTakingTurn)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot process user responses in when not taking a turn in Handoff Orchestration.");
|
||||
}
|
||||
List<ChatMessage>? roleChanges = state.FilteredIncomingMessages.ChangeAssistantToUserForOtherParticipants(this._agent.Name ?? this._agent.Id);
|
||||
|
||||
// If a handoff was invoked by a previous agent, filter out the handoff function call and tool result messages
|
||||
// before sending to the underlying agent. These are internal workflow mechanics that confuse the target model
|
||||
// into ignoring the original user question.
|
||||
//
|
||||
// This will not filter out tool responses and approval responses that are part of this agent's turn, which is
|
||||
// the expected behavior since those are part of the agent's reasoning process.
|
||||
HandoffMessagesFilter handoffMessagesFilter = new(this._options.ToolCallFilteringBehavior);
|
||||
IEnumerable<ChatMessage> messagesForAgent = state.IncomingState.RequestedHandoffTargetAgentId is not null
|
||||
? handoffMessagesFilter.FilterMessages(incomingMessages)
|
||||
: incomingMessages;
|
||||
|
||||
List<ChatMessage>? roleChanges = messagesForAgent.ChangeAssistantToUserForOtherParticipants(this._agent.Name ?? this._agent.Id);
|
||||
|
||||
bool emitUpdateEvents = state.IncomingState!.ShouldEmitStreamingEvents(this._options.EmitAgentResponseUpdateEvents);
|
||||
AgentInvocationResult result = await this.InvokeAgentAsync(messagesForAgent, context, emitUpdateEvents, cancellationToken)
|
||||
bool emitUpdateEvents = state.CurrentTurnState!.ShouldEmitStreamingEvents(this._options.EmitAgentResponseUpdateEvents);
|
||||
AgentInvocationResult result = await this.InvokeAgentAsync([.. state.FilteredIncomingMessages, .. state.TurnMessages], context, emitUpdateEvents, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (this.HasOutstandingRequests && result.IsHandoffRequested)
|
||||
@@ -252,40 +342,20 @@ internal sealed class HandoffAgentExecutor :
|
||||
|
||||
roleChanges.ResetUserToAssistantForChangedRoles();
|
||||
|
||||
int newConversationBookmark = state.ConversationBookmark;
|
||||
await this._sharedStateRef.InvokeWithStateAsync(
|
||||
(sharedState, ctx, ct) =>
|
||||
{
|
||||
if (sharedState == null)
|
||||
{
|
||||
throw new InvalidOperationException("Handoff Orchestration shared state was not properly initialized.");
|
||||
}
|
||||
|
||||
if (!skipAddIncoming)
|
||||
{
|
||||
sharedState.Conversation.AddMessages(incomingMessages);
|
||||
}
|
||||
|
||||
newConversationBookmark = sharedState.Conversation.AddMessages(result.Response.Messages);
|
||||
|
||||
return new ValueTask();
|
||||
},
|
||||
context,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// We send on the HandoffState even if handoff is not requested because we might be terminating the processing, but this only
|
||||
// happens if we have no outstanding requests.
|
||||
if (!this.HasOutstandingRequests)
|
||||
{
|
||||
HandoffState outgoingState = new(state.IncomingState.TurnToken, result.HandoffTargetId, this._agent.Id);
|
||||
HandoffState outgoingState = state.PrepareHandoff(result, this._agent.Id);
|
||||
|
||||
await context.SendMessageAsync(outgoingState, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// reset the state for the next handoff, making sure to keep track of the conversation bookmark, and avoid resetting the
|
||||
// agent session. (return-to-current is modeled as a new handoff turn, as opposed to "HITL", which can be a bit confusing.)
|
||||
return state with { IncomingState = null, ConversationBookmark = newConversationBookmark };
|
||||
// reset the state for the next handoff (return-to-current is modeled as a new handoff turn, as opposed to "HITL", which
|
||||
// can be a bit confusing.)
|
||||
return null;
|
||||
}
|
||||
|
||||
state.TurnMessages.AddRange(result.Response.Messages);
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -293,36 +363,28 @@ internal sealed class HandoffAgentExecutor :
|
||||
{
|
||||
return this.InvokeWithStateAsync(InvokeContinueTurnAsync, context, skipCache: false, cancellationToken);
|
||||
|
||||
async ValueTask<HandoffAgentHostState?> InvokeContinueTurnAsync(HandoffAgentHostState state, IWorkflowContext context, CancellationToken cancellationToken)
|
||||
ValueTask<HandoffAgentHostState?> InvokeContinueTurnAsync(HandoffAgentHostState state, IWorkflowContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
// Check that we are not getting this message while in the middle of a turn
|
||||
if (state.IsTakingTurn)
|
||||
if (state.CurrentTurnState != null)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot have multiple simultaneous conversations in Handoff Orchestration.");
|
||||
}
|
||||
|
||||
IEnumerable<ChatMessage> newConversationMessages = [];
|
||||
int newConversationBookmark = 0;
|
||||
// If a handoff was invoked by a previous agent, filter out the handoff function
|
||||
// call and tool result messages before sending to the underlying agent. These
|
||||
// are internal workflow mechanics that confuse the target model into ignoring the
|
||||
// original user question.
|
||||
HandoffMessagesFilter handoffMessagesFilter = new(this._options.ToolCallFilteringBehavior);
|
||||
IEnumerable<ChatMessage> messagesForAgent = message.RequestedHandoffTargetAgentId is not null
|
||||
? handoffMessagesFilter.FilterMessages(message.Messages)
|
||||
: message.Messages;
|
||||
|
||||
await this._sharedStateRef.InvokeWithStateAsync(
|
||||
(sharedState, ctx, ct) =>
|
||||
{
|
||||
if (sharedState == null)
|
||||
{
|
||||
throw new InvalidOperationException("Handoff Orchestration shared state was not properly initialized.");
|
||||
}
|
||||
// This works because the runtime guarantees that a given executor instance will process messages serially,
|
||||
// though there is no global cross-executor ordering guarantee (and in turn, no canonical message delivery order)
|
||||
state = new(message, messagesForAgent.ToList(), []);
|
||||
|
||||
(newConversationMessages, newConversationBookmark) = sharedState.Conversation.CollectNewMessages(state.ConversationBookmark);
|
||||
|
||||
return new ValueTask();
|
||||
},
|
||||
context,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
state = state with { IncomingState = message, ConversationBookmark = newConversationBookmark };
|
||||
|
||||
return await this.ContinueTurnAsync(state, newConversationMessages.ToList(), context, cancellationToken, skipAddIncoming: true)
|
||||
.ConfigureAwait(false);
|
||||
return this.ContinueTurnAsync(state, context, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,35 +395,18 @@ internal sealed class HandoffAgentExecutor :
|
||||
{
|
||||
Task userInputRequestsTask = this._userInputHandler?.OnCheckpointingAsync(UserInputRequestStateKey, context, cancellationToken).AsTask() ?? Task.CompletedTask;
|
||||
Task functionCallRequestsTask = this._functionCallHandler?.OnCheckpointingAsync(FunctionCallRequestStateKey, context, cancellationToken).AsTask() ?? Task.CompletedTask;
|
||||
Task agentSessionTask = CheckpointAgentSessionAsync();
|
||||
|
||||
Task baseTask = base.OnCheckpointingAsync(context, cancellationToken).AsTask();
|
||||
await Task.WhenAll(userInputRequestsTask, functionCallRequestsTask, agentSessionTask, baseTask).ConfigureAwait(false);
|
||||
|
||||
async Task CheckpointAgentSessionAsync()
|
||||
{
|
||||
JsonElement? sessionState = this._session is not null ? await this._agent.SerializeSessionAsync(this._session, cancellationToken: cancellationToken).ConfigureAwait(false) : null;
|
||||
await context.QueueStateUpdateAsync(AgentSessionKey, sessionState, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await Task.WhenAll(userInputRequestsTask, functionCallRequestsTask, baseTask).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
protected internal override async ValueTask OnCheckpointRestoredAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Task userInputRestoreTask = this._userInputHandler?.OnCheckpointRestoredAsync(UserInputRequestStateKey, context, cancellationToken).AsTask() ?? Task.CompletedTask;
|
||||
Task functionCallRestoreTask = this._functionCallHandler?.OnCheckpointRestoredAsync(FunctionCallRequestStateKey, context, cancellationToken).AsTask() ?? Task.CompletedTask;
|
||||
Task agentSessionTask = RestoreAgentSessionAsync();
|
||||
|
||||
await Task.WhenAll(userInputRestoreTask, functionCallRestoreTask, agentSessionTask).ConfigureAwait(false);
|
||||
await Task.WhenAll(userInputRestoreTask, functionCallRestoreTask).ConfigureAwait(false);
|
||||
await base.OnCheckpointRestoredAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
async Task RestoreAgentSessionAsync()
|
||||
{
|
||||
JsonElement? sessionState = await context.ReadStateAsync<JsonElement?>(AgentSessionKey, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (sessionState.HasValue)
|
||||
{
|
||||
this._session = await this._agent.DeserializeSessionAsync(sessionState.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
private bool HasOutstandingRequests => (this._userInputHandler?.HasPendingRequests == true)
|
||||
|| (this._functionCallHandler?.HasPendingRequests == true);
|
||||
@@ -372,43 +417,31 @@ internal sealed class HandoffAgentExecutor :
|
||||
|
||||
AIAgentUnservicedRequestsCollector collector = new(this._userInputHandler, this._functionCallHandler);
|
||||
|
||||
IAsyncEnumerable<AgentResponseUpdate> agentStream = this._agent.RunStreamingAsync(
|
||||
messages,
|
||||
options: this._agentOptions,
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
string? requestedHandoff = null;
|
||||
List<AgentResponseUpdate> updates = [];
|
||||
List<FunctionCallContent> candidateRequests = [];
|
||||
await foreach (AgentResponseUpdate update in agentStream.ConfigureAwait(false))
|
||||
{
|
||||
await AddUpdateAsync(update, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await this.InvokeWithStateAsync(
|
||||
async (state, ctx, ct) =>
|
||||
collector.ProcessAgentResponseUpdate(update, CollectHandoffRequestsFilter);
|
||||
|
||||
bool CollectHandoffRequestsFilter(FunctionCallContent candidateHandoffRequest)
|
||||
{
|
||||
this._session ??= await this._agent.CreateSessionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
IAsyncEnumerable<AgentResponseUpdate> agentStream =
|
||||
this._agent.RunStreamingAsync(messages,
|
||||
this._session,
|
||||
options: this._agentOptions,
|
||||
cancellationToken: ct);
|
||||
|
||||
await foreach (AgentResponseUpdate update in agentStream.ConfigureAwait(false))
|
||||
bool isHandoffRequest = this._handoffFunctionNames.Contains(candidateHandoffRequest.Name);
|
||||
if (isHandoffRequest)
|
||||
{
|
||||
await AddUpdateAsync(update, ct).ConfigureAwait(false);
|
||||
|
||||
collector.ProcessAgentResponseUpdate(update, CollectHandoffRequestsFilter);
|
||||
|
||||
bool CollectHandoffRequestsFilter(FunctionCallContent candidateHandoffRequest)
|
||||
{
|
||||
bool isHandoffRequest = this._handoffFunctionNames.Contains(candidateHandoffRequest.Name);
|
||||
if (isHandoffRequest)
|
||||
{
|
||||
candidateRequests.Add(candidateHandoffRequest);
|
||||
}
|
||||
|
||||
return !isHandoffRequest;
|
||||
}
|
||||
candidateRequests.Add(candidateHandoffRequest);
|
||||
}
|
||||
|
||||
return state;
|
||||
},
|
||||
context,
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
return !isHandoffRequest;
|
||||
}
|
||||
}
|
||||
|
||||
if (candidateRequests.Count > 1)
|
||||
{
|
||||
@@ -426,7 +459,7 @@ internal sealed class HandoffAgentExecutor :
|
||||
{
|
||||
AgentId = this._agent.Id,
|
||||
AuthorName = this._agent.Name ?? this._agent.Id,
|
||||
Contents = [CreateHandoffResult(handoffRequest.CallId)],
|
||||
Contents = [new FunctionResultContent(handoffRequest.CallId, "Transferred.")],
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
Role = ChatRole.Tool,
|
||||
@@ -459,6 +492,4 @@ internal sealed class HandoffAgentExecutor :
|
||||
? this._handoffFunctionToAgentId.TryGetValue(requestedHandoff, out string? targetId) ? targetId : null
|
||||
: null;
|
||||
}
|
||||
|
||||
internal static FunctionResultContent CreateHandoffResult(string requestCallId) => new(requestCallId, "Transferred.");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -13,33 +12,23 @@ internal sealed class HandoffEndExecutor(bool returnToPrevious) : Executor(Execu
|
||||
{
|
||||
public const string ExecutorId = "HandoffEnd";
|
||||
|
||||
private readonly StateRef<HandoffSharedState> _sharedStateRef = new(HandoffConstants.HandoffSharedStateKey,
|
||||
HandoffConstants.HandoffSharedStateScope);
|
||||
|
||||
protected override ProtocolBuilder ConfigureProtocol(ProtocolBuilder protocolBuilder) =>
|
||||
protocolBuilder.ConfigureRoutes(routeBuilder => routeBuilder.AddHandler<HandoffState>(
|
||||
(handoff, context, cancellationToken) => this.HandleAsync(handoff, context, cancellationToken)))
|
||||
protocolBuilder.ConfigureRoutes(routeBuilder => routeBuilder.AddHandler<HandoffState>((handoff, context, cancellationToken) =>
|
||||
this.HandleAsync(handoff, context, cancellationToken)))
|
||||
.YieldsOutput<List<ChatMessage>>();
|
||||
|
||||
private async ValueTask HandleAsync(HandoffState handoff, IWorkflowContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
await this._sharedStateRef.InvokeWithStateAsync(
|
||||
async (HandoffSharedState? sharedState, IWorkflowContext context, CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (sharedState == null)
|
||||
{
|
||||
throw new InvalidOperationException("Handoff Orchestration shared state was not properly initialized.");
|
||||
}
|
||||
if (returnToPrevious)
|
||||
{
|
||||
await context.QueueStateUpdateAsync<string?>(HandoffConstants.PreviousAgentTrackerKey,
|
||||
handoff.PreviousAgentId,
|
||||
HandoffConstants.PreviousAgentTrackerScope,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (returnToPrevious)
|
||||
{
|
||||
sharedState.PreviousAgentId = handoff.PreviousAgentId;
|
||||
}
|
||||
|
||||
await context.YieldOutputAsync(sharedState.Conversation.CloneAllMessages(), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return sharedState;
|
||||
}, context, cancellationToken).ConfigureAwait(false);
|
||||
await context.YieldOutputAsync(handoff.Messages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public ValueTask ResetAsync() => default;
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Specialized;
|
||||
|
||||
[Experimental(DiagnosticConstants.ExperimentalFeatureDiagnostic)]
|
||||
internal sealed class HandoffMessagesFilter
|
||||
{
|
||||
private readonly HandoffToolCallFilteringBehavior _filteringBehavior;
|
||||
|
||||
public HandoffMessagesFilter(HandoffToolCallFilteringBehavior filteringBehavior)
|
||||
{
|
||||
this._filteringBehavior = filteringBehavior;
|
||||
}
|
||||
|
||||
[Experimental(DiagnosticConstants.ExperimentalFeatureDiagnostic)]
|
||||
internal static bool IsHandoffFunctionName(string name)
|
||||
{
|
||||
return name.StartsWith(HandoffWorkflowBuilder.FunctionPrefix, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public IEnumerable<ChatMessage> FilterMessages(IEnumerable<ChatMessage> messages)
|
||||
{
|
||||
if (this._filteringBehavior == HandoffToolCallFilteringBehavior.None)
|
||||
{
|
||||
return messages;
|
||||
}
|
||||
|
||||
HashSet<string> filteredCallsWithoutResponses = new();
|
||||
List<ChatMessage> retainedMessages = [];
|
||||
|
||||
bool filterAllToolCalls = this._filteringBehavior == HandoffToolCallFilteringBehavior.All;
|
||||
|
||||
// The logic of filtering is fairly straightforward: We are only interested in FunctionCallContent and FunctionResponseContent.
|
||||
// We are going to assume that Handoff operates as follows:
|
||||
// * Each agent is only taking one turn at a time
|
||||
// * Each agent is taking a turn alone
|
||||
//
|
||||
// In the case of certain providers, like Gemini (see microsoft/agent-framework #5244), we will see the function call name as the
|
||||
// call id as well, so we may see multiple calls with the same call id, and assume that the call is terminated before another
|
||||
// "CallId-less" FCC is issued. We also need to rely on the idea that FRC follows their corresponding FCC in the message stream.
|
||||
// (This changes the previous behaviour where FRC could arrive earlier, and relies on strict ordering).
|
||||
//
|
||||
// The benefit of expecting all the AIContent to be strictly ordered is that we never need to reach back into a post-filtered
|
||||
// content to retroactively remove it, or to try to inject it back into the middle of a Message that has already been processed.
|
||||
|
||||
foreach (ChatMessage unfilteredMessage in messages)
|
||||
{
|
||||
if (unfilteredMessage.Contents is null || unfilteredMessage.Contents.Count == 0)
|
||||
{
|
||||
retainedMessages.Add(unfilteredMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
// We may need to filter out a subset of the message's content, but we won't know until we iterate through it. Create a new list
|
||||
// of AIContent which we will stuff into a clone of the message if we need to filter out any content.
|
||||
List<AIContent> retainedContents = new(capacity: unfilteredMessage.Contents.Count);
|
||||
|
||||
foreach (AIContent content in unfilteredMessage.Contents)
|
||||
{
|
||||
if (content is FunctionCallContent fcc
|
||||
&& (filterAllToolCalls || IsHandoffFunctionName(fcc.Name)))
|
||||
{
|
||||
// If we already have an unmatched candidate with the same CallId, that means we have two FCCs in a row without an FRC,
|
||||
// which violates our assumption of strict ordering.
|
||||
if (!filteredCallsWithoutResponses.Add(fcc.CallId))
|
||||
{
|
||||
throw new InvalidOperationException($"Duplicate FunctionCallContent with CallId '{fcc.CallId}' without corresponding FunctionResultContent.");
|
||||
}
|
||||
|
||||
// If we are filtering all tool calls, or this is a handoff call (and we are not filtering None, already checked), then
|
||||
// filter this FCC
|
||||
continue;
|
||||
}
|
||||
else if (content is FunctionResultContent frc)
|
||||
{
|
||||
// We rely on the corresponding FCC to have already been processed, so check if it is in the candidate dictionary.
|
||||
// If it is, we can filter out the FRC, but we need to remove the candidate from the dictionary, since a future FCC can
|
||||
// come in with the same CallId, and should be considered a new call that may need to be filtered.
|
||||
if (filteredCallsWithoutResponses.Remove(frc.CallId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// FCC/FRC, but not filtered, or neither FCC nor FRC: this should not be filtered out
|
||||
retainedContents.Add(content);
|
||||
}
|
||||
|
||||
if (retainedContents.Count == 0)
|
||||
{
|
||||
// message was fully filtered, skip it
|
||||
continue;
|
||||
}
|
||||
|
||||
ChatMessage filteredMessage = unfilteredMessage.Clone();
|
||||
filteredMessage.Contents = retainedContents;
|
||||
retainedMessages.Add(filteredMessage);
|
||||
}
|
||||
|
||||
return retainedMessages;
|
||||
}
|
||||
}
|
||||
@@ -9,23 +9,8 @@ namespace Microsoft.Agents.AI.Workflows.Specialized;
|
||||
|
||||
internal static class HandoffConstants
|
||||
{
|
||||
internal const string HandoffOrchestrationSharedScope = "HandoffOrchestration";
|
||||
|
||||
internal const string PreviousAgentTrackerKey = "LastAgentId";
|
||||
internal const string PreviousAgentTrackerScope = HandoffOrchestrationSharedScope;
|
||||
|
||||
internal const string MultiPartyConversationKey = "MultiPartyConversation";
|
||||
internal const string MultiPartyConversationScope = HandoffOrchestrationSharedScope;
|
||||
|
||||
internal const string HandoffSharedStateKey = "SharedState";
|
||||
internal const string HandoffSharedStateScope = HandoffOrchestrationSharedScope;
|
||||
}
|
||||
|
||||
internal sealed class HandoffSharedState
|
||||
{
|
||||
public MultiPartyConversation Conversation { get; } = new();
|
||||
|
||||
public string? PreviousAgentId { get; set; }
|
||||
internal const string PreviousAgentTrackerScope = "HandoffOrchestration";
|
||||
}
|
||||
|
||||
/// <summary>Executor used at the start of a handoffs workflow to accumulate messages and emit them as HandoffState upon receiving a turn token.</summary>
|
||||
@@ -44,25 +29,23 @@ internal sealed class HandoffStartExecutor(bool returnToPrevious) : ChatProtocol
|
||||
|
||||
protected override ValueTask TakeTurnAsync(List<ChatMessage> messages, IWorkflowContext context, bool? emitEvents, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.InvokeWithStateAsync(
|
||||
async (HandoffSharedState? sharedState, IWorkflowContext context, CancellationToken cancellationToken) =>
|
||||
{
|
||||
sharedState ??= new HandoffSharedState();
|
||||
sharedState.Conversation.AddMessages(messages);
|
||||
if (returnToPrevious)
|
||||
{
|
||||
return context.InvokeWithStateAsync(
|
||||
async (string? previousAgentId, IWorkflowContext context, CancellationToken cancellationToken) =>
|
||||
{
|
||||
HandoffState handoffState = new(new(emitEvents), null, messages, previousAgentId);
|
||||
await context.SendMessageAsync(handoffState, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
string? previousAgentId = sharedState.PreviousAgentId;
|
||||
return previousAgentId;
|
||||
},
|
||||
HandoffConstants.PreviousAgentTrackerKey,
|
||||
HandoffConstants.PreviousAgentTrackerScope,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
// If we are configured to return to the previous agent, include the previous agent id in the handoff state.
|
||||
// If there was no previousAgent, it will still be null.
|
||||
HandoffState turnState = new(new(emitEvents), null, returnToPrevious ? previousAgentId : null);
|
||||
|
||||
await context.SendMessageAsync(turnState, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return sharedState;
|
||||
},
|
||||
HandoffConstants.HandoffSharedStateKey,
|
||||
HandoffConstants.HandoffSharedStateScope,
|
||||
cancellationToken);
|
||||
HandoffState handoff = new(new(emitEvents), null, messages);
|
||||
return context.SendMessageAsync(handoff, cancellationToken);
|
||||
}
|
||||
|
||||
public new ValueTask ResetAsync() => base.ResetAsync();
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Specialized;
|
||||
|
||||
internal sealed record class HandoffState(
|
||||
TurnToken TurnToken,
|
||||
string? RequestedHandoffTargetAgentId,
|
||||
List<ChatMessage> Messages,
|
||||
string? PreviousAgentId = null);
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Specialized;
|
||||
|
||||
internal sealed class MultiPartyConversation
|
||||
{
|
||||
private readonly List<ChatMessage> _history = [];
|
||||
private readonly object _mutex = new();
|
||||
|
||||
public List<ChatMessage> CloneAllMessages()
|
||||
{
|
||||
lock (this._mutex)
|
||||
{
|
||||
return this._history.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public (ChatMessage[], int) CollectNewMessages(int bookmark)
|
||||
{
|
||||
lock (this._mutex)
|
||||
{
|
||||
int count = this._history.Count - bookmark;
|
||||
if (count < 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Bookmark value too large: {bookmark} vs count={count}");
|
||||
}
|
||||
|
||||
return (this._history.Skip(bookmark).ToArray(), this.CurrentBookmark);
|
||||
}
|
||||
}
|
||||
|
||||
private int CurrentBookmark => this._history.Count;
|
||||
|
||||
public int AddMessages(IEnumerable<ChatMessage> messages)
|
||||
{
|
||||
lock (this._mutex)
|
||||
{
|
||||
this._history.AddRange(messages);
|
||||
return this.CurrentBookmark;
|
||||
}
|
||||
}
|
||||
|
||||
public int AddMessage(ChatMessage message)
|
||||
{
|
||||
lock (this._mutex)
|
||||
{
|
||||
this._history.Add(message);
|
||||
return this.CurrentBookmark;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ public static class WorkflowHostingExtensions
|
||||
{
|
||||
Dictionary<string, object?> parameters = new()
|
||||
{
|
||||
{ "data", request.Data }
|
||||
{ "data", request.Data}
|
||||
};
|
||||
|
||||
return new FunctionCallContent(request.RequestId, request.PortInfo.PortId, parameters);
|
||||
|
||||
@@ -247,7 +247,7 @@ internal sealed class WorkflowSession : AgentSession
|
||||
hasMatchedResponseForStartExecutor |= string.Equals(responseExecutorId, this._workflow.StartExecutorId, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
object normalizedResponseContent = NormalizeResponseContentForDelivery(content, pendingRequest);
|
||||
AIContent normalizedResponseContent = NormalizeResponseContentForDelivery(content, pendingRequest);
|
||||
externalResponses.Add((pendingRequest.CreateResponse(normalizedResponseContent), pendingRequest.RequestId));
|
||||
(matchedContentIds ??= new(StringComparer.Ordinal)).Add(contentId);
|
||||
}
|
||||
@@ -303,35 +303,14 @@ internal sealed class WorkflowSession : AgentSession
|
||||
/// <summary>
|
||||
/// Rewrites workflow-facing response content back to the original agent-owned content ID.
|
||||
/// </summary>
|
||||
private static object NormalizeResponseContentForDelivery(AIContent content, ExternalRequest request)
|
||||
private static AIContent NormalizeResponseContentForDelivery(AIContent content, ExternalRequest request) => content switch
|
||||
{
|
||||
switch (content)
|
||||
{
|
||||
// If we got a FRC, and were expecting a FRC (because the request started out as a FCC, rather than getting converted to
|
||||
// on at the WorkflowSession boundary), clone it and send it in.
|
||||
case FunctionResultContent functionResultContent when request.TryGetDataAs(out FunctionCallContent? functionCallContent):
|
||||
return CloneFunctionResultContent(functionResultContent, functionCallContent.CallId);
|
||||
case FunctionResultContent functionResultContent when !request.PortInfo.ResponseType.IsMatchPolymorphic(typeof(FunctionResultContent)):
|
||||
{
|
||||
object? result = functionResultContent.Result;
|
||||
if (result != null)
|
||||
{
|
||||
if (request.PortInfo.ResponseType.IsMatchPolymorphic(result.GetType()) || result is PortableValue)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"Unexpected result type in FunctionResultContent {result.GetType()}; expecting {request.PortInfo.ResponseType}");
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"Null result is not supported when using RequestPort with non-AIContent-typed requests. {functionResultContent}");
|
||||
}
|
||||
case ToolApprovalResponseContent toolApprovalResponseContent when request.TryGetDataAs(out ToolApprovalRequestContent? toolApprovalRequestContent):
|
||||
return CloneToolApprovalResponseContent(toolApprovalResponseContent, toolApprovalRequestContent.RequestId);
|
||||
default:
|
||||
return content;
|
||||
}
|
||||
}
|
||||
FunctionResultContent functionResultContent when request.TryGetDataAs(out FunctionCallContent? functionCallContent)
|
||||
=> CloneFunctionResultContent(functionResultContent, functionCallContent.CallId),
|
||||
ToolApprovalResponseContent toolApprovalResponseContent when request.TryGetDataAs(out ToolApprovalRequestContent? toolApprovalRequestContent)
|
||||
=> CloneToolApprovalResponseContent(toolApprovalResponseContent, toolApprovalRequestContent.RequestId),
|
||||
_ => content,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workflow-facing request ID from response content types.
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework.DevUI.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for the <see cref="AgentEntityInfo"/> record.
|
||||
/// </summary>
|
||||
public class AgentEntityInfoTests
|
||||
{
|
||||
#region Constructor Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the Id property is set from the constructor parameter.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_WithId_SetsIdProperty()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("test-agent", info.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the Description property is set when provided.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_WithDescription_SetsDescriptionProperty()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent", "A test agent");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("A test agent", info.Description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the Description property is null when not provided.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_WithoutDescription_DescriptionIsNull()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent");
|
||||
|
||||
// Assert
|
||||
Assert.Null(info.Description);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Default Value Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Name defaults to the Id value when not explicitly set.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Name_NotSet_DefaultsToId()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("test-agent", info.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Name can be overridden with a custom value.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Name_Set_ReturnsCustomValue()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent") { Name = "Custom Name" };
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Custom Name", info.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Type defaults to "agent".
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Type_NotSet_DefaultsToAgent()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("agent", info.Type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Type can be overridden with a custom value.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Type_Set_ReturnsCustomValue()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent") { Type = "workflow" };
|
||||
|
||||
// Assert
|
||||
Assert.Equal("workflow", info.Type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Framework defaults to "agent_framework".
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Framework_NotSet_DefaultsToAgentFramework()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("agent_framework", info.Framework);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Framework can be overridden with a custom value.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Framework_Set_ReturnsCustomValue()
|
||||
{
|
||||
// Arrange & Act
|
||||
var info = new AgentEntityInfo("test-agent") { Framework = "custom_framework" };
|
||||
|
||||
// Assert
|
||||
Assert.Equal("custom_framework", info.Framework);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Record Equality Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that two AgentEntityInfo records with identical values are equal.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Equality_SameValues_AreEqual()
|
||||
{
|
||||
// Arrange
|
||||
var info1 = new AgentEntityInfo("agent", "description");
|
||||
var info2 = new AgentEntityInfo("agent", "description");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(info1, info2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that two AgentEntityInfo records with different Ids are not equal.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Equality_DifferentIds_AreNotEqual()
|
||||
{
|
||||
// Arrange
|
||||
var info1 = new AgentEntityInfo("agent1");
|
||||
var info2 = new AgentEntityInfo("agent2");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(info1, info2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that with-expression creates a modified copy.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithExpression_ModifiesProperty_CreatesNewInstance()
|
||||
{
|
||||
// Arrange
|
||||
var original = new AgentEntityInfo("agent", "Original description");
|
||||
|
||||
// Act
|
||||
var modified = original with { Description = "Modified description" };
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Original description", original.Description);
|
||||
Assert.Equal("Modified description", modified.Description);
|
||||
Assert.Equal(original.Id, modified.Id);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
-567
@@ -1,567 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Aspire.Hosting.ApplicationModel;
|
||||
using Moq;
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework.DevUI.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for the <see cref="AgentFrameworkBuilderExtensions"/> class.
|
||||
/// </summary>
|
||||
public class AgentFrameworkBuilderExtensionsTests
|
||||
{
|
||||
#region AddDevUI Validation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI throws ArgumentNullException when builder is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_NullBuilder_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(
|
||||
() => AgentFrameworkBuilderExtensions.AddDevUI(null!, "devui"));
|
||||
Assert.Equal("builder", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI throws ArgumentNullException when name is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_NullName_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(
|
||||
() => builder.AddDevUI(null!));
|
||||
Assert.Equal("name", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI creates a resource with the specified name.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_ValidName_CreatesResourceWithName()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
|
||||
// Act
|
||||
var resourceBuilder = builder.AddDevUI("my-devui");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("my-devui", resourceBuilder.Resource.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI creates a DevUIResource.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_ReturnsDevUIResourceBuilder()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
|
||||
// Act
|
||||
var resourceBuilder = builder.AddDevUI("devui");
|
||||
|
||||
// Assert
|
||||
Assert.IsType<DevUIResource>(resourceBuilder.Resource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI with port configures the endpoint.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_WithPort_ConfiguresEndpointWithPort()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
|
||||
// Act
|
||||
var resourceBuilder = builder.AddDevUI("devui", port: 8090);
|
||||
|
||||
// Assert
|
||||
var endpoint = resourceBuilder.Resource.Annotations
|
||||
.OfType<EndpointAnnotation>()
|
||||
.FirstOrDefault(e => e.Name == "http");
|
||||
Assert.NotNull(endpoint);
|
||||
Assert.Equal(8090, endpoint.Port);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI without port leaves port as null for dynamic allocation.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_WithoutPort_EndpointHasDynamicPort()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
|
||||
// Act
|
||||
var resourceBuilder = builder.AddDevUI("devui");
|
||||
|
||||
// Assert
|
||||
var endpoint = resourceBuilder.Resource.Annotations
|
||||
.OfType<EndpointAnnotation>()
|
||||
.FirstOrDefault(e => e.Name == "http");
|
||||
Assert.NotNull(endpoint);
|
||||
Assert.Null(endpoint.Port);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region WithAgentService Validation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService throws ArgumentNullException when builder is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_NullBuilder_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var mockAgentService = CreateMockAgentServiceBuilder(appBuilder, "agent-service");
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(
|
||||
() => AgentFrameworkBuilderExtensions.WithAgentService(null!, mockAgentService));
|
||||
Assert.Equal("builder", exception.ParamName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService throws ArgumentNullException when agentService is null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_NullAgentService_ThrowsArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<ArgumentNullException>(
|
||||
() => devuiBuilder.WithAgentService<IResourceWithEndpoints>(null!));
|
||||
Assert.Equal("agentService", exception.ParamName);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region WithAgentService Annotation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService adds an AgentServiceAnnotation to the resource.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_ValidService_AddsAnnotation()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.FirstOrDefault();
|
||||
Assert.NotNull(annotation);
|
||||
Assert.Same(agentService.Resource, annotation.AgentService);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService defaults to agent name being the resource name.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_NoAgents_DefaultsToResourceNameAsAgent()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
Assert.Single(annotation.Agents);
|
||||
Assert.Equal("writer-agent", annotation.Agents[0].Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService with explicit agents uses those agents.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_WithAgents_UsesProvidedAgents()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "multi-agent-service");
|
||||
var agents = new[]
|
||||
{
|
||||
new AgentEntityInfo("agent1", "First agent"),
|
||||
new AgentEntityInfo("agent2", "Second agent")
|
||||
};
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService, agents: agents);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
Assert.Equal(2, annotation.Agents.Count);
|
||||
Assert.Equal("agent1", annotation.Agents[0].Id);
|
||||
Assert.Equal("agent2", annotation.Agents[1].Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService with custom prefix uses that prefix.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_WithEntityIdPrefix_UsesProvidedPrefix()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService, entityIdPrefix: "custom-prefix");
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
Assert.Equal("custom-prefix", annotation.EntityIdPrefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService without prefix leaves EntityIdPrefix null.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_NoEntityIdPrefix_PrefixIsNull()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
Assert.Null(annotation.EntityIdPrefix);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Chaining Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService returns the builder for chaining.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_ReturnsSameBuilder_ForChaining()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
var result = devuiBuilder.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
Assert.Same(devuiBuilder, result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that multiple WithAgentService calls can be chained.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_MultipleCalls_AddsMultipleAnnotations()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var writerService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
var editorService = CreateMockAgentServiceBuilder(appBuilder, "editor-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder
|
||||
.WithAgentService(writerService)
|
||||
.WithAgentService(editorService);
|
||||
|
||||
// Assert
|
||||
var annotations = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.ToList();
|
||||
Assert.Equal(2, annotations.Count);
|
||||
Assert.Contains(annotations, a => a.AgentService.Name == "writer-agent");
|
||||
Assert.Contains(annotations, a => a.AgentService.Name == "editor-agent");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI returns a builder that can be chained with WithAgentService.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_CanChainWithAgentService()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act - Chain AddDevUI with WithAgentService
|
||||
var result = appBuilder.AddDevUI("devui").WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
var annotation = result.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.FirstOrDefault();
|
||||
Assert.NotNull(annotation);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Relationship Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService creates a relationship annotation.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_CreatesRelationshipAnnotation()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
var relationship = devuiBuilder.Resource.Annotations
|
||||
.OfType<ResourceRelationshipAnnotation>()
|
||||
.FirstOrDefault();
|
||||
Assert.NotNull(relationship);
|
||||
Assert.Equal("agent-backend", relationship.Type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that multiple WithAgentService calls create multiple relationship annotations.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_MultipleCalls_CreatesMultipleRelationships()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var writerService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
var editorService = CreateMockAgentServiceBuilder(appBuilder, "editor-agent");
|
||||
|
||||
// Act
|
||||
devuiBuilder
|
||||
.WithAgentService(writerService)
|
||||
.WithAgentService(editorService);
|
||||
|
||||
// Assert
|
||||
var relationships = devuiBuilder.Resource.Annotations
|
||||
.OfType<ResourceRelationshipAnnotation>()
|
||||
.ToList();
|
||||
Assert.Equal(2, relationships.Count);
|
||||
Assert.All(relationships, r => Assert.Equal("agent-backend", r.Type));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Agent Metadata Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that agent description is preserved when specified.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_AgentWithDescription_PreservesDescription()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
var agents = new[] { new AgentEntityInfo("writer", "Writes creative stories") };
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService, agents: agents);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
Assert.Equal("Writes creative stories", annotation.Agents[0].Description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that custom agent properties are preserved.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_CustomAgentProperties_ArePreserved()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "custom-service");
|
||||
var agents = new[]
|
||||
{
|
||||
new AgentEntityInfo("custom-agent")
|
||||
{
|
||||
Name = "Custom Display Name",
|
||||
Type = "workflow",
|
||||
Framework = "custom_framework"
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService, agents: agents);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
var agent = annotation.Agents[0];
|
||||
Assert.Equal("custom-agent", agent.Id);
|
||||
Assert.Equal("Custom Display Name", agent.Name);
|
||||
Assert.Equal("workflow", agent.Type);
|
||||
Assert.Equal("custom_framework", agent.Framework);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that empty agents array can be explicitly provided and is respected.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_EmptyAgentsArray_UsesEmptyArray()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devuiBuilder = appBuilder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
var emptyAgents = Array.Empty<AgentEntityInfo>();
|
||||
|
||||
// Act
|
||||
devuiBuilder.WithAgentService(agentService, agents: emptyAgents);
|
||||
|
||||
// Assert
|
||||
var annotation = devuiBuilder.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
// When explicitly passing an empty array, the extension method respects it
|
||||
// This is the expected behavior - explicit empty means "discover at runtime"
|
||||
Assert.Empty(annotation.Agents);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Edge Case Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AddDevUI can be called multiple times with different names.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AddDevUI_MultipleCalls_CreatesSeparateResources()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
|
||||
// Act
|
||||
var devui1 = appBuilder.AddDevUI("devui1");
|
||||
var devui2 = appBuilder.AddDevUI("devui2");
|
||||
|
||||
// Assert
|
||||
Assert.NotSame(devui1.Resource, devui2.Resource);
|
||||
Assert.Equal("devui1", devui1.Resource.Name);
|
||||
Assert.Equal("devui2", devui2.Resource.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that same agent service can be added to multiple DevUI resources.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_SameServiceToMultipleDevUI_Works()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devui1 = appBuilder.AddDevUI("devui1");
|
||||
var devui2 = appBuilder.AddDevUI("devui2");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "shared-agent");
|
||||
|
||||
// Act
|
||||
devui1.WithAgentService(agentService);
|
||||
devui2.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
var annotation1 = devui1.Resource.Annotations.OfType<AgentServiceAnnotation>().Single();
|
||||
var annotation2 = devui2.Resource.Annotations.OfType<AgentServiceAnnotation>().Single();
|
||||
Assert.Same(annotation1.AgentService, annotation2.AgentService);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService works with different entity ID prefixes for the same service.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_DifferentPrefixesToDifferentDevUI_Works()
|
||||
{
|
||||
// Arrange
|
||||
var appBuilder = DistributedApplication.CreateBuilder();
|
||||
var devui1 = appBuilder.AddDevUI("devui1");
|
||||
var devui2 = appBuilder.AddDevUI("devui2");
|
||||
var agentService = CreateMockAgentServiceBuilder(appBuilder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devui1.WithAgentService(agentService, entityIdPrefix: "prefix1");
|
||||
devui2.WithAgentService(agentService, entityIdPrefix: "prefix2");
|
||||
|
||||
// Assert
|
||||
var annotation1 = devui1.Resource.Annotations.OfType<AgentServiceAnnotation>().Single();
|
||||
var annotation2 = devui2.Resource.Annotations.OfType<AgentServiceAnnotation>().Single();
|
||||
Assert.Equal("prefix1", annotation1.EntityIdPrefix);
|
||||
Assert.Equal("prefix2", annotation2.EntityIdPrefix);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helper Methods
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mock agent service builder for testing.
|
||||
/// Uses a minimal resource implementation that satisfies IResourceWithEndpoints.
|
||||
/// </summary>
|
||||
private static IResourceBuilder<IResourceWithEndpoints> CreateMockAgentServiceBuilder(
|
||||
IDistributedApplicationBuilder appBuilder,
|
||||
string name)
|
||||
{
|
||||
// Create a mock resource that implements IResourceWithEndpoints
|
||||
var mockResource = new Mock<IResourceWithEndpoints>();
|
||||
mockResource.Setup(r => r.Name).Returns(name);
|
||||
mockResource.Setup(r => r.Annotations).Returns(new ResourceAnnotationCollection());
|
||||
|
||||
var mockBuilder = new Mock<IResourceBuilder<IResourceWithEndpoints>>();
|
||||
mockBuilder.Setup(b => b.Resource).Returns(mockResource.Object);
|
||||
mockBuilder.Setup(b => b.ApplicationBuilder).Returns(appBuilder);
|
||||
|
||||
return mockBuilder.Object;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using Aspire.Hosting.ApplicationModel;
|
||||
using Moq;
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework.DevUI.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for the <see cref="AgentServiceAnnotation"/> class.
|
||||
/// </summary>
|
||||
public class AgentServiceAnnotationTests
|
||||
{
|
||||
#region Constructor Validation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that passing null for agentService throws ArgumentNullException.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_NullAgentService_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentNullException>(() => new AgentServiceAnnotation(null!));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a valid agentService can be used to create the annotation.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_ValidAgentService_CreatesAnnotation()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("test-service");
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(mockResource.Object);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(annotation);
|
||||
Assert.Same(mockResource.Object, annotation.AgentService);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Property Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AgentService property returns the value passed to constructor.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AgentService_ReturnsConstructorValue()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("my-service");
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(mockResource.Object);
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockResource.Object, annotation.AgentService);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that EntityIdPrefix returns null when not specified.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EntityIdPrefix_NotSpecified_ReturnsNull()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("test-service");
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(mockResource.Object);
|
||||
|
||||
// Assert
|
||||
Assert.Null(annotation.EntityIdPrefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that EntityIdPrefix returns the value passed to constructor.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EntityIdPrefix_Specified_ReturnsValue()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("test-service");
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(mockResource.Object, entityIdPrefix: "custom-prefix");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("custom-prefix", annotation.EntityIdPrefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Agents returns empty collection when not specified.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Agents_NotSpecified_ReturnsEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("test-service");
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(mockResource.Object);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(annotation.Agents);
|
||||
Assert.Empty(annotation.Agents);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that Agents returns the list passed to constructor.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Agents_Specified_ReturnsValue()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("test-service");
|
||||
var agents = new[] { new AgentEntityInfo("agent1"), new AgentEntityInfo("agent2") };
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(mockResource.Object, agents: agents);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, annotation.Agents.Count);
|
||||
Assert.Equal("agent1", annotation.Agents[0].Id);
|
||||
Assert.Equal("agent2", annotation.Agents[1].Id);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Full Constructor Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that all constructor parameters are correctly stored.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_AllParameters_SetsAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
var mockResource = new Mock<IResource>();
|
||||
mockResource.Setup(r => r.Name).Returns("full-service");
|
||||
var agents = new[] { new AgentEntityInfo("writer", "Writes stories") };
|
||||
|
||||
// Act
|
||||
var annotation = new AgentServiceAnnotation(
|
||||
mockResource.Object,
|
||||
entityIdPrefix: "writer-backend",
|
||||
agents: agents);
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockResource.Object, annotation.AgentService);
|
||||
Assert.Equal("writer-backend", annotation.EntityIdPrefix);
|
||||
Assert.Single(annotation.Agents);
|
||||
Assert.Equal("writer", annotation.Agents[0].Id);
|
||||
Assert.Equal("Writes stories", annotation.Agents[0].Description);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>$(TargetFrameworksCore)</TargetFrameworks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Hosting" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Aspire.Hosting.AgentFramework.DevUI\Aspire.Hosting.AgentFramework.DevUI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
-298
@@ -1,298 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Linq;
|
||||
using Aspire.Hosting.ApplicationModel;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework.DevUI.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for the <see cref="DevUIAggregatorHostedService"/> class.
|
||||
/// </summary>
|
||||
public class DevUIAggregatorHostedServiceTests
|
||||
{
|
||||
#region RewriteAgentIdInQueryString Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString returns empty string when query string has no value.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_EmptyQueryString_ReturnsEmptyString()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = QueryString.Empty;
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "writer");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString rewrites agent_id to the un-prefixed value.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_WithPrefixedAgentId_RewritesToUnprefixed()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?agent_id=writer-agent%2Fwriter");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "writer");
|
||||
|
||||
// Assert
|
||||
Assert.Contains("agent_id=writer", result);
|
||||
Assert.DoesNotContain("writer-agent", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString preserves other query parameters.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_WithOtherParams_PreservesOtherParams()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?agent_id=writer-agent%2Fwriter&conversation_id=123&page=5");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "writer");
|
||||
|
||||
// Assert
|
||||
Assert.Contains("agent_id=writer", result);
|
||||
Assert.Contains("conversation_id=123", result);
|
||||
Assert.Contains("page=5", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString works when agent_id is not the first parameter.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_AgentIdNotFirst_StillRewrites()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?page=1&agent_id=editor-agent%2Feditor&limit=10");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "editor");
|
||||
|
||||
// Assert
|
||||
Assert.Contains("agent_id=editor", result);
|
||||
Assert.DoesNotContain("editor-agent", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString handles special characters in actual agent ID.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_SpecialCharsInAgentId_UrlEncodesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?agent_id=prefix%2Fmy-agent");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "my-agent");
|
||||
|
||||
// Assert
|
||||
// The result should contain the agent_id with the value properly encoded if needed
|
||||
Assert.Contains("agent_id=my-agent", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString handles an agent_id with no prefix.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_NoPrefix_SetsDirectly()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?agent_id=simple");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "new-value");
|
||||
|
||||
// Assert
|
||||
Assert.Contains("agent_id=new-value", result);
|
||||
Assert.DoesNotContain("simple", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString adds agent_id even if not originally present.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_NoAgentId_AddsAgentId()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?page=1&limit=10");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "writer");
|
||||
|
||||
// Assert
|
||||
Assert.Contains("agent_id=writer", result);
|
||||
Assert.Contains("page=1", result);
|
||||
Assert.Contains("limit=10", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that RewriteAgentIdInQueryString returns proper format starting with ?.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RewriteAgentIdInQueryString_ValidQuery_ReturnsQueryStringFormat()
|
||||
{
|
||||
// Arrange
|
||||
var queryString = new QueryString("?agent_id=test");
|
||||
|
||||
// Act
|
||||
var result = DevUIAggregatorHostedService.RewriteAgentIdInQueryString(queryString, "writer");
|
||||
|
||||
// Assert
|
||||
Assert.StartsWith("?", result);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Backend Resolution Behavior Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that ResolveBackends returns empty dictionary when no annotations are present.
|
||||
/// These tests verify the expected behavior of the aggregator via the DevUI resource annotations.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void DevUIResource_NoAnnotations_ResolveBackendsReturnsEmpty()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
var devui = builder.AddDevUI("devui");
|
||||
|
||||
// Assert - no AgentServiceAnnotation means no backends
|
||||
var annotations = devui.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.ToList();
|
||||
|
||||
Assert.Empty(annotations);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that WithAgentService adds proper annotations for backend resolution.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_AddsAnnotation_ForBackendResolution()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
var devui = builder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(builder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devui.WithAgentService(agentService);
|
||||
|
||||
// Assert
|
||||
var annotation = devui.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.FirstOrDefault();
|
||||
|
||||
Assert.NotNull(annotation);
|
||||
Assert.Equal("writer-agent", annotation.AgentService.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that custom EntityIdPrefix is properly stored in the annotation.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_CustomPrefix_StoresInAnnotation()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
var devui = builder.AddDevUI("devui");
|
||||
var agentService = CreateMockAgentServiceBuilder(builder, "writer-agent");
|
||||
|
||||
// Act
|
||||
devui.WithAgentService(agentService, entityIdPrefix: "custom-writer");
|
||||
|
||||
// Assert
|
||||
var annotation = devui.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.First();
|
||||
|
||||
Assert.Equal("custom-writer", annotation.EntityIdPrefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that multiple agent services create multiple annotations for backend resolution.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void WithAgentService_MultipleServices_CreatesMultipleAnnotations()
|
||||
{
|
||||
// Arrange
|
||||
var builder = DistributedApplication.CreateBuilder();
|
||||
var devui = builder.AddDevUI("devui");
|
||||
var writerService = CreateMockAgentServiceBuilder(builder, "writer-agent");
|
||||
var editorService = CreateMockAgentServiceBuilder(builder, "editor-agent");
|
||||
|
||||
// Act
|
||||
devui.WithAgentService(writerService);
|
||||
devui.WithAgentService(editorService);
|
||||
|
||||
// Assert
|
||||
var annotations = devui.Resource.Annotations
|
||||
.OfType<AgentServiceAnnotation>()
|
||||
.ToList();
|
||||
|
||||
Assert.Equal(2, annotations.Count);
|
||||
Assert.Contains(annotations, a => a.AgentService.Name == "writer-agent");
|
||||
Assert.Contains(annotations, a => a.AgentService.Name == "editor-agent");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Entity ID Parsing Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies the expected format for prefixed entity IDs in the aggregator.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("writer-agent/writer", "writer-agent", "writer")]
|
||||
[InlineData("editor-agent/editor", "editor-agent", "editor")]
|
||||
[InlineData("custom/my-agent", "custom", "my-agent")]
|
||||
[InlineData("prefix/sub/path", "prefix", "sub/path")]
|
||||
public void PrefixedEntityId_Format_ExtractsCorrectly(string prefixedId, string expectedPrefix, string expectedRest)
|
||||
{
|
||||
// This test documents the expected format for prefixed entity IDs
|
||||
// The aggregator uses "prefix/entityId" format where:
|
||||
// - prefix is typically the resource name or custom prefix
|
||||
// - entityId is the original entity identifier from the backend
|
||||
|
||||
var slashIndex = prefixedId.IndexOf('/');
|
||||
var prefix = prefixedId[..slashIndex];
|
||||
var rest = prefixedId[(slashIndex + 1)..];
|
||||
|
||||
Assert.Equal(expectedPrefix, prefix);
|
||||
Assert.Equal(expectedRest, rest);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helper Methods
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mock agent service builder for testing.
|
||||
/// Uses a minimal resource implementation that satisfies IResourceWithEndpoints.
|
||||
/// </summary>
|
||||
private static IResourceBuilder<IResourceWithEndpoints> CreateMockAgentServiceBuilder(
|
||||
IDistributedApplicationBuilder appBuilder,
|
||||
string name)
|
||||
{
|
||||
// Create a mock resource that implements IResourceWithEndpoints
|
||||
var mockResource = new Moq.Mock<IResourceWithEndpoints>();
|
||||
mockResource.Setup(r => r.Name).Returns(name);
|
||||
mockResource.Setup(r => r.Annotations).Returns(new ResourceAnnotationCollection());
|
||||
|
||||
var mockBuilder = new Moq.Mock<IResourceBuilder<IResourceWithEndpoints>>();
|
||||
mockBuilder.Setup(b => b.Resource).Returns(mockResource.Object);
|
||||
mockBuilder.Setup(b => b.ApplicationBuilder).Returns(appBuilder);
|
||||
|
||||
return mockBuilder.Object;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using Aspire.Hosting.ApplicationModel;
|
||||
|
||||
namespace Aspire.Hosting.AgentFramework.DevUI.UnitTests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for the <see cref="DevUIResource"/> class.
|
||||
/// </summary>
|
||||
public class DevUIResourceTests
|
||||
{
|
||||
#region Constructor Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the resource name is correctly set.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_WithName_SetsName()
|
||||
{
|
||||
// Arrange & Act
|
||||
var resource = new DevUIResource("test-devui");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("test-devui", resource.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the resource implements IResourceWithEndpoints.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Resource_ImplementsIResourceWithEndpoints()
|
||||
{
|
||||
// Arrange & Act
|
||||
var resource = new DevUIResource("test-devui");
|
||||
|
||||
// Assert
|
||||
Assert.IsAssignableFrom<IResourceWithEndpoints>(resource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the resource implements IResourceWithWaitSupport.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Resource_ImplementsIResourceWithWaitSupport()
|
||||
{
|
||||
// Arrange & Act
|
||||
var resource = new DevUIResource("test-devui");
|
||||
|
||||
// Assert
|
||||
Assert.IsAssignableFrom<IResourceWithWaitSupport>(resource);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Endpoint Annotation Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the resource has an HTTP endpoint annotation when port is specified.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_WithPort_AddsEndpointAnnotation()
|
||||
{
|
||||
// Arrange & Act
|
||||
var resource = CreateResourceWithPort(8090);
|
||||
|
||||
// Assert
|
||||
var endpoint = resource.Annotations.OfType<EndpointAnnotation>().FirstOrDefault();
|
||||
Assert.NotNull(endpoint);
|
||||
Assert.Equal("http", endpoint.Name);
|
||||
Assert.Equal(8090, endpoint.Port);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the endpoint annotation has correct protocol type.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EndpointAnnotation_HasTcpProtocol()
|
||||
{
|
||||
// Arrange
|
||||
var resource = CreateResourceWithPort(8080);
|
||||
|
||||
// Act
|
||||
var endpoint = resource.Annotations.OfType<EndpointAnnotation>().First();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ProtocolType.Tcp, endpoint.Protocol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the endpoint annotation has HTTP URI scheme.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EndpointAnnotation_HasHttpUriScheme()
|
||||
{
|
||||
// Arrange
|
||||
var resource = CreateResourceWithPort(8080);
|
||||
|
||||
// Act
|
||||
var endpoint = resource.Annotations.OfType<EndpointAnnotation>().First();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http", endpoint.UriScheme);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the endpoint is not proxied.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EndpointAnnotation_IsNotProxied()
|
||||
{
|
||||
// Arrange
|
||||
var resource = CreateResourceWithPort(8080);
|
||||
|
||||
// Act
|
||||
var endpoint = resource.Annotations.OfType<EndpointAnnotation>().First();
|
||||
|
||||
// Assert
|
||||
Assert.False(endpoint.IsProxied);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the endpoint target host is localhost.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EndpointAnnotation_TargetHostIsLocalhost()
|
||||
{
|
||||
// Arrange
|
||||
var resource = CreateResourceWithPort(8080);
|
||||
|
||||
// Act
|
||||
var endpoint = resource.Annotations.OfType<EndpointAnnotation>().First();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("localhost", endpoint.TargetHost);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the endpoint has no fixed port when null is passed.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Constructor_WithNullPort_EndpointHasNullPort()
|
||||
{
|
||||
// Arrange & Act
|
||||
var resource = CreateResourceWithPort(null);
|
||||
|
||||
// Assert
|
||||
var endpoint = resource.Annotations.OfType<EndpointAnnotation>().FirstOrDefault();
|
||||
Assert.NotNull(endpoint);
|
||||
Assert.Null(endpoint.Port);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region PrimaryEndpoint Tests
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that PrimaryEndpoint returns an endpoint reference.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PrimaryEndpoint_ReturnsEndpointReference()
|
||||
{
|
||||
// Arrange
|
||||
var resource = CreateResourceWithPort(8080);
|
||||
|
||||
// Act
|
||||
var endpoint = resource.PrimaryEndpoint;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(endpoint);
|
||||
Assert.Same(resource, endpoint.Resource);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that PrimaryEndpoint returns the same instance on multiple calls.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PrimaryEndpoint_MultipleCalls_ReturnsSameInstance()
|
||||
{
|
||||
// Arrange
|
||||
var resource = CreateResourceWithPort(8080);
|
||||
|
||||
// Act
|
||||
var endpoint1 = resource.PrimaryEndpoint;
|
||||
var endpoint2 = resource.PrimaryEndpoint;
|
||||
|
||||
// Assert
|
||||
Assert.Same(endpoint1, endpoint2);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static DevUIResource CreateResourceWithPort(int? port) => new("test-devui", port);
|
||||
}
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using FluentAssertions;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.Events;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.Kit;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests.Kit;
|
||||
|
||||
/// <summary>
|
||||
/// Tests that edge predicates correctly handle PortableValue-wrapped messages,
|
||||
/// which occur after checkpoint restore (JSON round-trip).
|
||||
/// </summary>
|
||||
public sealed class PortableValuePredicateTests
|
||||
{
|
||||
#region ActionExecutorResult.ThrowIfNot
|
||||
|
||||
[Fact]
|
||||
public void ActionExecutorResult_ThrowIfNot_WithDirectActionExecutorResult_ReturnsResult()
|
||||
{
|
||||
// Arrange
|
||||
ActionExecutorResult result = new("test-executor");
|
||||
|
||||
// Act
|
||||
ActionExecutorResult actual = ActionExecutorResult.ThrowIfNot(result);
|
||||
|
||||
// Assert
|
||||
actual.Should().BeSameAs(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ActionExecutorResult_ThrowIfNot_WithPortableValueWrappedActionExecutorResult_Unwraps()
|
||||
{
|
||||
// Arrange
|
||||
ActionExecutorResult result = new("test-executor");
|
||||
PortableValue wrapped = new(result);
|
||||
|
||||
// Act
|
||||
ActionExecutorResult actual = ActionExecutorResult.ThrowIfNot(wrapped);
|
||||
|
||||
// Assert
|
||||
actual.ExecutorId.Should().Be("test-executor");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ActionExecutorResult_ThrowIfNot_WithNonActionExecutorResult_Throws()
|
||||
{
|
||||
// Arrange
|
||||
object message = "not an ActionExecutorResult";
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<DeclarativeActionException>(() => ActionExecutorResult.ThrowIfNot(message));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ActionExecutorResult_ThrowIfNot_WithNull_Throws()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.Throws<DeclarativeActionException>(() => ActionExecutorResult.ThrowIfNot(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ActionExecutorResult_ThrowIfNot_WithPortableValueWrappedNonResult_Throws()
|
||||
{
|
||||
// Arrange
|
||||
PortableValue wrapped = new("not an ActionExecutorResult");
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<DeclarativeActionException>(() => ActionExecutorResult.ThrowIfNot(wrapped));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region InvokeAzureAgentExecutor Predicates
|
||||
|
||||
[Fact]
|
||||
public void InvokeAzureAgentExecutor_RequiresInput_WithDirectExternalInputRequest_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
ExternalInputRequest request = new("test prompt");
|
||||
|
||||
// Act & Assert
|
||||
InvokeAzureAgentExecutor.RequiresInput(request).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvokeAzureAgentExecutor_RequiresInput_WithPortableValueWrappedRequest_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
ExternalInputRequest request = new("test prompt");
|
||||
PortableValue wrapped = new(request);
|
||||
|
||||
// Act & Assert
|
||||
InvokeAzureAgentExecutor.RequiresInput(wrapped).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvokeAzureAgentExecutor_RequiresInput_WithActionExecutorResult_ReturnsFalse()
|
||||
{
|
||||
// Arrange
|
||||
ActionExecutorResult result = new("test");
|
||||
|
||||
// Act & Assert
|
||||
InvokeAzureAgentExecutor.RequiresInput(result).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvokeAzureAgentExecutor_RequiresNothing_WithDirectActionExecutorResult_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
ActionExecutorResult result = new("test");
|
||||
|
||||
// Act & Assert
|
||||
InvokeAzureAgentExecutor.RequiresNothing(result).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvokeAzureAgentExecutor_RequiresNothing_WithPortableValueWrappedResult_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
ActionExecutorResult result = new("test");
|
||||
PortableValue wrapped = new(result);
|
||||
|
||||
// Act & Assert
|
||||
InvokeAzureAgentExecutor.RequiresNothing(wrapped).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvokeAzureAgentExecutor_RequiresNothing_WithExternalInputRequest_ReturnsFalse()
|
||||
{
|
||||
// Arrange
|
||||
ExternalInputRequest request = new("test prompt");
|
||||
|
||||
// Act & Assert
|
||||
InvokeAzureAgentExecutor.RequiresNothing(request).Should().BeFalse();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region InvokeMcpToolExecutor Predicates
|
||||
|
||||
[Fact]
|
||||
public void InvokeMcpToolExecutor_RequiresInput_WithPortableValueWrappedRequest_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
ExternalInputRequest request = new("test prompt");
|
||||
PortableValue wrapped = new(request);
|
||||
|
||||
// Act & Assert
|
||||
InvokeMcpToolExecutor.RequiresInput(wrapped).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvokeMcpToolExecutor_RequiresNothing_WithPortableValueWrappedResult_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
ActionExecutorResult result = new("test");
|
||||
PortableValue wrapped = new(result);
|
||||
|
||||
// Act & Assert
|
||||
InvokeMcpToolExecutor.RequiresNothing(wrapped).Should().BeTrue();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region QuestionExecutor.IsComplete
|
||||
|
||||
[Fact]
|
||||
public void QuestionExecutor_IsComplete_WithPortableValueWrappedResult_NullResult_ReturnsTrue()
|
||||
{
|
||||
// Arrange - result with null Result property means "complete"
|
||||
ActionExecutorResult result = new("test", result: null);
|
||||
PortableValue wrapped = new(result);
|
||||
|
||||
// Act & Assert
|
||||
QuestionExecutor.IsComplete(wrapped).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QuestionExecutor_IsComplete_WithPortableValueWrappedResult_NonNullResult_ReturnsFalse()
|
||||
{
|
||||
// Arrange - result with non-null Result property means "not complete"
|
||||
ActionExecutorResult result = new("test", result: true);
|
||||
PortableValue wrapped = new(result);
|
||||
|
||||
// Act & Assert
|
||||
QuestionExecutor.IsComplete(wrapped).Should().BeFalse();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
@@ -12,9 +11,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Agents.AI.Workflows.InProc;
|
||||
using Microsoft.Agents.AI.Workflows.Specialized;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
#pragma warning disable SYSLIB1045 // Use GeneratedRegex
|
||||
#pragma warning disable RCS1186 // Use Regex instance instead of static method
|
||||
@@ -55,51 +52,6 @@ public class AgentWorkflowBuilderTests
|
||||
|
||||
var noDescriptionAgent = new ChatClientAgent(new MockChatClient(delegate { return new(); }));
|
||||
Assert.Throws<ArgumentException>("to", () => handoffs.WithHandoff(agent, noDescriptionAgent));
|
||||
|
||||
var emptyDescriptionAgent = new MockChatClient(delegate { return new(); }).AsAIAgent(description: "");
|
||||
Assert.Throws<ArgumentException>("to", () => handoffs.WithHandoff(agent, emptyDescriptionAgent));
|
||||
|
||||
var emptyNameAgent = new MockChatClient(delegate { return new(); }).AsAIAgent(name: "");
|
||||
Assert.Throws<ArgumentException>("to", () => handoffs.WithHandoff(agent, emptyNameAgent));
|
||||
}
|
||||
|
||||
private sealed class NullLogger : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildHandoffs_DelegatingAIAgent_DoesNotThrow()
|
||||
{
|
||||
DoubleEchoAgent agent = new("agent");
|
||||
HandoffWorkflowBuilder handoffs = AgentWorkflowBuilder.CreateHandoffBuilderWith(agent);
|
||||
Assert.NotNull(handoffs);
|
||||
|
||||
ChatClientAgent instructionsOnlyAgent = new MockChatClient(delegate { return new(); }).AsAIAgent(instructions: "instructions");
|
||||
LoggingAgent delegatingAgent = new(instructionsOnlyAgent, new NullLogger());
|
||||
|
||||
handoffs.WithHandoff(agent, delegatingAgent);
|
||||
|
||||
// get the _targets field from the HandoffWorkflowBuilder (need to use the base type)
|
||||
FieldInfo field = typeof(HandoffWorkflowBuilder).BaseType!.GetField("_targets", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
Dictionary<AIAgent, HashSet<HandoffTarget>>? targets = field.GetValue(handoffs) as Dictionary<AIAgent, HashSet<HandoffTarget>>;
|
||||
|
||||
targets.Should().NotBeNull();
|
||||
|
||||
HandoffTarget target = targets[agent].Single();
|
||||
target.Reason.Should().Be("instructions");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+55
-189
@@ -7,10 +7,6 @@ using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Agents.AI.Workflows.Checkpointing;
|
||||
using Microsoft.Agents.AI.Workflows.Execution;
|
||||
using Microsoft.Agents.AI.Workflows.InProc;
|
||||
using Microsoft.Agents.AI.Workflows.Sample;
|
||||
using Microsoft.Agents.AI.Workflows.Specialized;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
@@ -18,27 +14,6 @@ namespace Microsoft.Agents.AI.Workflows.UnitTests;
|
||||
|
||||
public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
{
|
||||
private static async ValueTask<TestRunContext> PrepareHandoffSharedStateAsync(TestRunContext? runContext = null, IEnumerable<ChatMessage>? messages = null)
|
||||
{
|
||||
runContext ??= new();
|
||||
|
||||
HandoffSharedState sharedState = new();
|
||||
|
||||
if (messages != null)
|
||||
{
|
||||
sharedState.Conversation.AddMessages(messages);
|
||||
}
|
||||
|
||||
await runContext.BindWorkflowContext(nameof(HandoffStartExecutor))
|
||||
.QueueStateUpdateAsync(HandoffConstants.HandoffSharedStateKey,
|
||||
sharedState,
|
||||
HandoffConstants.HandoffSharedStateScope);
|
||||
|
||||
await runContext.StateManager.PublishUpdatesAsync(null);
|
||||
|
||||
return runContext;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)]
|
||||
[InlineData(null, true)]
|
||||
@@ -52,7 +27,7 @@ public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
public async Task Test_HandoffAgentExecutor_EmitsStreamingUpdatesIFFConfiguredAsync(bool? executorSetting, bool? turnSetting)
|
||||
{
|
||||
// Arrange
|
||||
TestRunContext testContext = await PrepareHandoffSharedStateAsync();
|
||||
TestRunContext testContext = new();
|
||||
TestReplayAgent agent = new(TestMessages, TestAgentId, TestAgentName);
|
||||
|
||||
HandoffAgentExecutorOptions options = new("",
|
||||
@@ -64,7 +39,7 @@ public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
testContext.ConfigureExecutor(executor);
|
||||
|
||||
// Act
|
||||
HandoffState message = new(new(turnSetting), null, null);
|
||||
HandoffState message = new(new(turnSetting), null, []);
|
||||
await executor.HandleAsync(message, testContext.BindWorkflowContext(executor.Id));
|
||||
|
||||
// Assert
|
||||
@@ -80,7 +55,7 @@ public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
public async Task Test_HandoffAgentExecutor_EmitsResponseIFFConfiguredAsync(bool executorSetting)
|
||||
{
|
||||
// Arrange
|
||||
TestRunContext testContext = await PrepareHandoffSharedStateAsync();
|
||||
TestRunContext testContext = new();
|
||||
TestReplayAgent agent = new(TestMessages, TestAgentId, TestAgentName);
|
||||
|
||||
HandoffAgentExecutorOptions options = new("",
|
||||
@@ -92,7 +67,7 @@ public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
testContext.ConfigureExecutor(executor);
|
||||
|
||||
// Act
|
||||
HandoffState message = new(new(false), null, null);
|
||||
HandoffState message = new(new(false), null, []);
|
||||
await executor.HandleAsync(message, testContext.BindWorkflowContext(executor.Id));
|
||||
|
||||
// Assert
|
||||
@@ -100,82 +75,6 @@ public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
CheckResponseEventsAgainstTestMessages(updates, expectingResponse: executorSetting, agent.GetDescriptiveId());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Test_HandoffAgentExecutor_ComposesWithHITLSubworkflowAsync()
|
||||
{
|
||||
// Arrange
|
||||
TestRunContext testContext = await PrepareHandoffSharedStateAsync();
|
||||
|
||||
SendsRequestExecutor challengeSender = new();
|
||||
Workflow subworkflow = new WorkflowBuilder(challengeSender)
|
||||
.AddExternalRequest<Challenge, Response>(challengeSender, "SendChallengeToUser")
|
||||
.WithOutputFrom(challengeSender)
|
||||
.Build();
|
||||
|
||||
InProcessExecutionEnvironment environment = InProcessExecution.Lockstep.WithCheckpointing(CheckpointManager.CreateInMemory());
|
||||
AIAgent subworkflowAgent = subworkflow.AsAIAgent(includeWorkflowOutputsInResponse: true, name: "Subworkflow", executionEnvironment: environment);
|
||||
HandoffAgentExecutorOptions options = new("",
|
||||
emitAgentResponseEvents: true,
|
||||
emitAgentResponseUpdateEvents: true,
|
||||
HandoffToolCallFilteringBehavior.None);
|
||||
|
||||
HandoffAgentExecutor executor = new(subworkflowAgent, [], options);
|
||||
Workflow fakeWorkflow = new(executor.Id) { ExecutorBindings = { { executor.Id, executor } } };
|
||||
EdgeMap map = new(testContext, fakeWorkflow, null);
|
||||
|
||||
testContext.ConfigureExecutor(executor, map);
|
||||
|
||||
// Validate that our test assumptions hold
|
||||
string functionCallPortId = $"{HandoffAgentExecutor.IdFor(subworkflowAgent)}_FunctionCall";
|
||||
map.TryGetResponsePortExecutorId(functionCallPortId, out string? responsePortExecutorId).Should().BeTrue();
|
||||
responsePortExecutorId.Should().Be(executor.Id);
|
||||
|
||||
// Act
|
||||
HandoffState message = new(new(false), null, null);
|
||||
await executor.HandleAsync(message, testContext.BindWorkflowContext(executor.Id));
|
||||
|
||||
await testContext.StateManager.PublishUpdatesAsync(null);
|
||||
|
||||
// Assert
|
||||
testContext.ExternalRequests.Should().HaveCount(1)
|
||||
.And.ContainSingle(request => request.IsDataOfType<FunctionCallContent>());
|
||||
|
||||
FunctionCallContent functionCallContent = testContext.ExternalRequests.Single().Data.As<FunctionCallContent>()!;
|
||||
object? requestData = functionCallContent.Arguments!["data"];
|
||||
|
||||
Challenge? challenge = null;
|
||||
if (requestData is PortableValue pv)
|
||||
{
|
||||
challenge = pv.As<Challenge>();
|
||||
}
|
||||
else
|
||||
{
|
||||
challenge = requestData as Challenge;
|
||||
}
|
||||
|
||||
if (challenge is null)
|
||||
{
|
||||
Assert.Fail($"Expected request data to be of type {typeof(Challenge).FullName}, but was {requestData?.GetType().FullName ?? "null"}");
|
||||
return; // Unreachable, but analysis cannot infer that Debug.Fail will throw/exit, and UnreachableException is not available on net472
|
||||
}
|
||||
|
||||
// Act 2
|
||||
string challengeResponse = new(challenge.Value.Reverse().ToArray());
|
||||
FunctionResultContent responseContent = new(functionCallContent.CallId, new Response(challengeResponse));
|
||||
|
||||
RequestPortInfo requestPortInfo = new(new(typeof(Challenge)), new(typeof(Response)), functionCallPortId);
|
||||
string requestId = $"{functionCallPortId.Length}:{functionCallPortId}:{functionCallContent.CallId}";
|
||||
DeliveryMapping? mapping = await map.PrepareDeliveryForResponseAsync(new(requestPortInfo, requestId, new(responseContent)));
|
||||
|
||||
mapping!.Deliveries.Should().HaveCount(1);
|
||||
|
||||
MessageDelivery delivery = mapping!.Deliveries.Single();
|
||||
|
||||
object? result = await executor.ExecuteCoreAsync(delivery.Envelope.Message,
|
||||
delivery.Envelope.MessageType,
|
||||
testContext.BindWorkflowContext(executor.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Test_HandoffAgentExecutor_PreservesExistingInstructionsAndToolsAsync()
|
||||
{
|
||||
@@ -193,113 +92,80 @@ public class HandoffAgentExecutorTests : AIAgentHostingExecutorTestsBase
|
||||
HandoffTarget handoff = new(targetAgent);
|
||||
HandoffAgentExecutor executor = new(handoffAgent, [handoff], options);
|
||||
|
||||
TestRunContext runContext = await PrepareHandoffSharedStateAsync();
|
||||
IWorkflowContext testContext = runContext.BindWorkflowContext(executor.Id);
|
||||
HandoffState state = new(new(false), null);
|
||||
TestWorkflowContext testContext = new(executor.Id);
|
||||
HandoffState state = new(new(false), null, [], null);
|
||||
|
||||
// Act / Assert
|
||||
Func<Task> runStreamingAsync = async () => await executor.HandleAsync(state, testContext);
|
||||
await runStreamingAsync.Should().NotThrowAsync();
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record Challenge(string Value);
|
||||
internal sealed record Response(string Value);
|
||||
|
||||
[SendsMessage(typeof(Challenge))]
|
||||
internal sealed partial class SendsRequestExecutor(string? id = null) : ChatProtocolExecutor(id ?? nameof(SendsRequestExecutor), s_chatOptions)
|
||||
{
|
||||
internal const string ChallengeString = "{C7A762AE-7DAA-4D9C-A647-E64E6DBC35AE}";
|
||||
private static string ResponseKey { get; } = new(ChallengeString.Reverse().ToArray());
|
||||
|
||||
private static readonly ChatProtocolExecutorOptions s_chatOptions = new()
|
||||
private sealed class OptionValidatingChatClient(string baseInstructions, string handoffInstructions, AITool baseTool) : IChatClient
|
||||
{
|
||||
AutoSendTurnToken = false
|
||||
};
|
||||
|
||||
protected override ValueTask TakeTurnAsync(List<ChatMessage> messages, IWorkflowContext context, bool? emitEvents, CancellationToken cancellationToken = default)
|
||||
=> context.SendMessageAsync(new Challenge(ChallengeString), cancellationToken);
|
||||
|
||||
[MessageHandler]
|
||||
public async ValueTask HandleChallengeResponseAsync(Response response, IWorkflowContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (response.Value != ResponseKey)
|
||||
public void Dispose()
|
||||
{
|
||||
throw new InvalidOperationException($"Incorrect response received. Expected '{ResponseKey}' but got '{response.Value}'");
|
||||
}
|
||||
|
||||
await context.SendMessageAsync(new ChatMessage(ChatRole.Assistant, "Correct response."), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
private void CheckOptions(ChatOptions? options)
|
||||
{
|
||||
options.Should().NotBeNull();
|
||||
|
||||
await context.SendMessageAsync(new TurnToken(false), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
options.Instructions.Should().NotBeNullOrEmpty("Handoff orchestration should preserve and augment instructions.")
|
||||
.And.Contain(baseInstructions, because: "Handoff orchestration should preserve existing instructions.")
|
||||
.And.Contain(handoffInstructions, because: "Handoff orchestration should inject handoff instructions.");
|
||||
|
||||
internal sealed class OptionValidatingChatClient(string baseInstructions, string handoffInstructions, AITool baseTool) : IChatClient
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
options.Tools.Should().NotBeNullOrEmpty("Handoff orchestration should preserve and augment tools.")
|
||||
.And.Contain(tool => tool.Name == baseTool.Name, "Handoff orchestration should preserve existing tools.")
|
||||
.And.Contain(tool => tool.Name.StartsWith(HandoffWorkflowBuilder.FunctionPrefix, StringComparison.Ordinal),
|
||||
because: "Handoff orchestration should inject handoff tools.");
|
||||
}
|
||||
|
||||
private void CheckOptions(ChatOptions? options)
|
||||
{
|
||||
options.Should().NotBeNull();
|
||||
|
||||
options.Instructions.Should().NotBeNullOrEmpty("Handoff orchestration should preserve and augment instructions.")
|
||||
.And.Contain(baseInstructions, because: "Handoff orchestration should preserve existing instructions.")
|
||||
.And.Contain(handoffInstructions, because: "Handoff orchestration should inject handoff instructions.");
|
||||
|
||||
options.Tools.Should().NotBeNullOrEmpty("Handoff orchestration should preserve and augment tools.")
|
||||
.And.Contain(tool => tool.Name == baseTool.Name, "Handoff orchestration should preserve existing tools.")
|
||||
.And.Contain(tool => tool.Name.StartsWith(HandoffWorkflowBuilder.FunctionPrefix, StringComparison.Ordinal),
|
||||
because: "Handoff orchestration should inject handoff tools.");
|
||||
}
|
||||
|
||||
private List<ChatMessage> ResponseMessages =>
|
||||
[
|
||||
new ChatMessage(ChatRole.Assistant, "Ok")
|
||||
private List<ChatMessage> ResponseMessages =>
|
||||
[
|
||||
new ChatMessage(ChatRole.Assistant, "Ok")
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString(),
|
||||
AuthorName = nameof(OptionValidatingChatClient)
|
||||
}
|
||||
];
|
||||
];
|
||||
|
||||
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
this.CheckOptions(options);
|
||||
|
||||
ChatResponse response = new(this.ResponseMessages)
|
||||
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ResponseId = Guid.NewGuid().ToString("N"),
|
||||
CreatedAt = DateTimeOffset.Now
|
||||
};
|
||||
this.CheckOptions(options);
|
||||
|
||||
return Task.FromResult(response);
|
||||
}
|
||||
|
||||
public object? GetService(Type serviceType, object? serviceKey = null)
|
||||
{
|
||||
if (serviceType == typeof(OptionValidatingChatClient))
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
this.CheckOptions(options);
|
||||
|
||||
string responseId = Guid.NewGuid().ToString("N");
|
||||
foreach (ChatMessage message in this.ResponseMessages)
|
||||
{
|
||||
yield return new(message.Role, message.Contents)
|
||||
ChatResponse response = new(this.ResponseMessages)
|
||||
{
|
||||
ResponseId = responseId,
|
||||
MessageId = message.MessageId,
|
||||
ResponseId = Guid.NewGuid().ToString("N"),
|
||||
CreatedAt = DateTimeOffset.Now
|
||||
};
|
||||
|
||||
return Task.FromResult(response);
|
||||
}
|
||||
|
||||
public object? GetService(Type serviceType, object? serviceKey = null)
|
||||
{
|
||||
if (serviceType == typeof(OptionValidatingChatClient))
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
this.CheckOptions(options);
|
||||
|
||||
string responseId = Guid.NewGuid().ToString("N");
|
||||
foreach (ChatMessage message in this.ResponseMessages)
|
||||
{
|
||||
yield return new(message.Role, message.Contents)
|
||||
{
|
||||
ResponseId = responseId,
|
||||
MessageId = message.MessageId,
|
||||
CreatedAt = DateTimeOffset.Now
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Agents.AI.Workflows.Specialized;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.UnitTests;
|
||||
|
||||
public class HandoffMessageFilterTests
|
||||
{
|
||||
private List<ChatMessage> CreateTestMessages(bool firstAgentUsesCallId, bool secondAgentUsesCallId, HandoffToolCallFilteringBehavior filter = HandoffToolCallFilteringBehavior.None)
|
||||
{
|
||||
FunctionCallContent handoffRequest1 = CreateHandoffCall(1, firstAgentUsesCallId);
|
||||
FunctionResultContent handoffResponse1 = CreateHandoffResponse(handoffRequest1);
|
||||
|
||||
FunctionCallContent toolCall = CreateToolCall(secondAgentUsesCallId);
|
||||
FunctionResultContent toolResponse = CreateToolResponse(toolCall);
|
||||
|
||||
// Approvals come from the function call middleware over ChatClient, so we can expect there to be a RequestId (not that we
|
||||
// care, because we do not filter approval content)
|
||||
ToolApprovalRequestContent toolApproval = new(Guid.NewGuid().ToString("N"), toolCall);
|
||||
ToolApprovalResponseContent toolApprovalResponse = new(toolApproval.RequestId, true, toolCall);
|
||||
|
||||
FunctionCallContent handoffRequest2 = CreateHandoffCall(1, secondAgentUsesCallId);
|
||||
FunctionResultContent handoffResponse2 = CreateHandoffResponse(handoffRequest2);
|
||||
|
||||
List<ChatMessage> result = [new(ChatRole.User, "Hello")];
|
||||
|
||||
// Agent 1 turn
|
||||
result.Add(new(ChatRole.Assistant, "Hello! What do you want help with today?"));
|
||||
result.Add(new(ChatRole.User, "Please explain temperature"));
|
||||
|
||||
// Unless we are filtering none, we expect the handoff call to be filtered out, so we add it conditionally
|
||||
if (filter == HandoffToolCallFilteringBehavior.None)
|
||||
{
|
||||
result.Add(new(ChatRole.Assistant, [handoffRequest1]));
|
||||
result.Add(new(ChatRole.Tool, [handoffResponse1]));
|
||||
}
|
||||
|
||||
// Agent 2 turn
|
||||
|
||||
// Tool approvals are never filtered, so we add them unconditionally
|
||||
result.Add(new(ChatRole.Assistant, [toolApproval]));
|
||||
result.Add(new(ChatRole.User, [toolApprovalResponse]));
|
||||
|
||||
// Unless we are filtering all, we expect the tool call to be retained, so we add it conditionally
|
||||
if (filter != HandoffToolCallFilteringBehavior.All)
|
||||
{
|
||||
result.Add(new(ChatRole.Assistant, [toolCall]));
|
||||
result.Add(new(ChatRole.Tool, [toolResponse]));
|
||||
}
|
||||
|
||||
result.Add(new(ChatRole.Assistant, "Temperature is a measure of the average kinetic energy of the particles in a substance."));
|
||||
|
||||
if (filter == HandoffToolCallFilteringBehavior.None)
|
||||
{
|
||||
result.Add(new(ChatRole.Assistant, [handoffRequest2]));
|
||||
result.Add(new(ChatRole.Tool, [handoffResponse2]));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static FunctionCallContent CreateHandoffCall(int id, bool useCallId)
|
||||
{
|
||||
string callName = $"{HandoffWorkflowBuilder.FunctionPrefix}{id}";
|
||||
string callId = useCallId ? Guid.NewGuid().ToString("N") : callName;
|
||||
|
||||
return new FunctionCallContent(callId, callName);
|
||||
}
|
||||
|
||||
private static FunctionResultContent CreateHandoffResponse(FunctionCallContent call)
|
||||
=> HandoffAgentExecutor.CreateHandoffResult(call.CallId);
|
||||
|
||||
private static FunctionCallContent CreateToolCall(bool useCallId)
|
||||
{
|
||||
const string CallName = "ToolFunction";
|
||||
string callId = useCallId ? Guid.NewGuid().ToString("N") : CallName;
|
||||
|
||||
return new FunctionCallContent(callId, CallName);
|
||||
}
|
||||
|
||||
private static FunctionResultContent CreateToolResponse(FunctionCallContent call)
|
||||
=> new(call.CallId, new object());
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, true, HandoffToolCallFilteringBehavior.None)]
|
||||
[InlineData(true, false, HandoffToolCallFilteringBehavior.None)]
|
||||
[InlineData(false, true, HandoffToolCallFilteringBehavior.None)]
|
||||
[InlineData(false, false, HandoffToolCallFilteringBehavior.None)]
|
||||
[InlineData(true, true, HandoffToolCallFilteringBehavior.HandoffOnly)]
|
||||
[InlineData(true, false, HandoffToolCallFilteringBehavior.HandoffOnly)]
|
||||
[InlineData(false, true, HandoffToolCallFilteringBehavior.HandoffOnly)]
|
||||
[InlineData(false, false, HandoffToolCallFilteringBehavior.HandoffOnly)]
|
||||
[InlineData(true, true, HandoffToolCallFilteringBehavior.All)]
|
||||
[InlineData(true, false, HandoffToolCallFilteringBehavior.All)]
|
||||
[InlineData(false, true, HandoffToolCallFilteringBehavior.All)]
|
||||
[InlineData(false, false, HandoffToolCallFilteringBehavior.All)]
|
||||
public void Test_HandoffMessageFilter_FiltersOnlyExpectedMessages(bool firstAgentUsesCallId, bool secondAgentUsesCallId, HandoffToolCallFilteringBehavior behavior)
|
||||
{
|
||||
// Arrange
|
||||
List<ChatMessage> messages = this.CreateTestMessages(firstAgentUsesCallId, secondAgentUsesCallId);
|
||||
List<ChatMessage> expected = this.CreateTestMessages(firstAgentUsesCallId, secondAgentUsesCallId, behavior);
|
||||
|
||||
HandoffMessagesFilter filter = new(behavior);
|
||||
|
||||
// Act
|
||||
IEnumerable<ChatMessage> filteredMessages = filter.FilterMessages(messages);
|
||||
|
||||
// Assert
|
||||
filteredMessages.Should().BeEquivalentTo(expected);
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,6 @@ internal static class Step12EntryPoint
|
||||
foreach (string input in inputs)
|
||||
{
|
||||
AgentResponse response;
|
||||
|
||||
ResponseContinuationToken? continuationToken = null;
|
||||
do
|
||||
{
|
||||
|
||||
@@ -314,38 +314,6 @@ public class SampleSmokeTest
|
||||
Action<string> CreateValidator(string expected) => actual => actual.Should().Be(expected);
|
||||
}
|
||||
|
||||
public class Step12ExpectedOutputCalculator(int agentCount)
|
||||
{
|
||||
private readonly int[] _bookmarks = new int[agentCount];
|
||||
private readonly List<string> _history = new();
|
||||
private readonly HashSet<int> _skipIndices = new();
|
||||
|
||||
public IEnumerable<string> ExpectedOutputs =>
|
||||
this._history.Where((element, index) => !this._skipIndices.Contains(index));
|
||||
|
||||
public void ProcessInput(string newInput)
|
||||
{
|
||||
this._skipIndices.Add(this._history.Count);
|
||||
this._history.Add(newInput);
|
||||
|
||||
for (int i = 0; i < agentCount; i++)
|
||||
{
|
||||
int agentId = i + 1;
|
||||
int agentBookmark = this._bookmarks[i];
|
||||
int count = this._history.Count - agentBookmark;
|
||||
|
||||
count.Should().BeGreaterThanOrEqualTo(0);
|
||||
|
||||
foreach (string input in this._history.Skip(agentBookmark).ToList())
|
||||
{
|
||||
this._history.Add($"{agentId}:{input}");
|
||||
}
|
||||
|
||||
this._bookmarks[i] = this._history.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ExecutionEnvironment.InProcess_Lockstep)]
|
||||
[InlineData(ExecutionEnvironment.InProcess_OffThread)]
|
||||
@@ -354,10 +322,14 @@ public class SampleSmokeTest
|
||||
{
|
||||
List<string> inputs = ["1", "2", "3"];
|
||||
|
||||
using StringWriter writer = new();
|
||||
await Step12EntryPoint.RunAsync(writer, environment.ToWorkflowExecutionEnvironment(), inputs);
|
||||
|
||||
string[] lines = writer.ToString().Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
// The expectation is that each agent will echo each input along with every echo from previous agents
|
||||
// E.g.:
|
||||
// (user): 1
|
||||
// ----- outputs below
|
||||
// (a1): 1:1
|
||||
// (a2): 2:1
|
||||
// (a2): 2:1:1
|
||||
@@ -368,35 +340,7 @@ public class SampleSmokeTest
|
||||
// (a3): 3:2:1
|
||||
// (a3): 3:2:1:1
|
||||
|
||||
// If there are multiple inputs (there are), then each successive input adds to the depth of the previous
|
||||
// ones, so, for example, once we do input = "1", "2":
|
||||
|
||||
// (user): 1
|
||||
// (a1): 1:1 <- a1 "last seen"
|
||||
// (a2): 2:1
|
||||
// (a2): 2:1:1 <- a2 "last seen"
|
||||
// (user): 2
|
||||
// ----- outputs below
|
||||
// (a1): 1:2:1
|
||||
// (a1): 1:2:1:1
|
||||
// (a1): 1:2 <- from user input, a1 "last seen"
|
||||
// (a2): 2:2 <- from user input (note that a2 seems like it is seeing these in a different "order" than a1 - but it is not)
|
||||
// (a2): 2:1:2:1
|
||||
// (a2): 2:1:2:1:1
|
||||
// (a2): 2:1:2 <- from a1's first echo, a2 "last seen"
|
||||
|
||||
Step12ExpectedOutputCalculator outputGenerator = new(Step12EntryPoint.AgentCount);
|
||||
foreach (string input in inputs)
|
||||
{
|
||||
outputGenerator.ProcessInput(input);
|
||||
}
|
||||
|
||||
string[] expected = outputGenerator.ExpectedOutputs.ToArray();
|
||||
|
||||
using StringWriter writer = new();
|
||||
await Step12EntryPoint.RunAsync(writer, environment.ToWorkflowExecutionEnvironment(), inputs);
|
||||
|
||||
string[] lines = writer.ToString().Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] expected = inputs.SelectMany(input => EchoesForInput(input)).ToArray();
|
||||
|
||||
Console.Error.WriteLine("Expected lines: ");
|
||||
foreach (string expectedLine in expected)
|
||||
@@ -413,6 +357,19 @@ public class SampleSmokeTest
|
||||
Assert.Collection(lines,
|
||||
expected.Select(CreateValidator).ToArray());
|
||||
|
||||
IEnumerable<string> EchoesForInput(string input)
|
||||
{
|
||||
List<string> echoes = [$"{Step12EntryPoint.EchoPrefixForAgent(1)}{input}"];
|
||||
for (int i = 2; i <= Step12EntryPoint.AgentCount; i++)
|
||||
{
|
||||
string agentPrefix = Step12EntryPoint.EchoPrefixForAgent(i);
|
||||
List<string> newEchoes = [$"{agentPrefix}{input}", .. echoes.Select(echo => $"{agentPrefix}{echo}")];
|
||||
echoes.AddRange(newEchoes);
|
||||
}
|
||||
|
||||
return echoes;
|
||||
}
|
||||
|
||||
Action<string> CreateValidator(string expected) => actual => actual.Should().Be(expected);
|
||||
}
|
||||
|
||||
|
||||
@@ -27,9 +27,6 @@ public class TestRunContext : IRunnerContext
|
||||
|
||||
internal TestRunContext ConfigureExecutor(Executor executor, EdgeMap? map = null)
|
||||
{
|
||||
// Ensure that we have run the ProtocolBuilder
|
||||
_ = executor.Protocol.Describe();
|
||||
|
||||
executor.AttachRequestContext(new TestExternalRequestContext(this, executor.Id, map));
|
||||
this.Executors.Add(executor.Id, executor);
|
||||
return this;
|
||||
@@ -45,7 +42,6 @@ public class TestRunContext : IRunnerContext
|
||||
return this;
|
||||
}
|
||||
|
||||
internal StateManager StateManager { get; } = new();
|
||||
private sealed class BoundContext(
|
||||
string executorId,
|
||||
TestRunContext runnerContext,
|
||||
@@ -74,16 +70,16 @@ public class TestRunContext : IRunnerContext
|
||||
=> this.AddEventAsync(new RequestHaltEvent());
|
||||
|
||||
public ValueTask QueueClearScopeAsync(string? scopeName = null, CancellationToken cancellationToken = default)
|
||||
=> runnerContext.StateManager.ClearStateAsync(executorId, scopeName);
|
||||
=> default;
|
||||
|
||||
public ValueTask QueueStateUpdateAsync<T>(string key, T? value, string? scopeName = null, CancellationToken cancellationToken = default)
|
||||
=> runnerContext.StateManager.WriteStateAsync(new ScopeId(executorId, scopeName), key, value);
|
||||
=> default;
|
||||
|
||||
public ValueTask<T?> ReadStateAsync<T>(string key, string? scopeName = null, CancellationToken cancellationToken = default)
|
||||
=> runnerContext.StateManager.ReadStateAsync<T>(new ScopeId(executorId, scopeName), key);
|
||||
=> new(default(T?));
|
||||
|
||||
public ValueTask<HashSet<string>> ReadStateKeysAsync(string? scopeName = null, CancellationToken cancellationToken = default)
|
||||
=> runnerContext.StateManager.ReadKeysAsync(new ScopeId(executorId, scopeName));
|
||||
=> new([]);
|
||||
|
||||
public ValueTask SendMessageAsync(object message, string? targetId = null, CancellationToken cancellationToken = default)
|
||||
=> runnerContext.SendMessageAsync(executorId, message, targetId, cancellationToken);
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
"azuredocs",
|
||||
"azurefunctions",
|
||||
"boto",
|
||||
"codeact",
|
||||
"contentvector",
|
||||
"contoso",
|
||||
"datamodel",
|
||||
@@ -47,7 +46,6 @@
|
||||
"hnsw",
|
||||
"httpx",
|
||||
"huggingface",
|
||||
"hyperlight",
|
||||
"Instrumentor",
|
||||
"logit",
|
||||
"logprobs",
|
||||
|
||||
+1
-38
@@ -7,44 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.0] - 2026-04-21
|
||||
|
||||
### Added
|
||||
- **agent-framework-gemini**: Add `GeminiChatClient` ([#4847](https://github.com/microsoft/agent-framework/pull/4847))
|
||||
- **agent-framework-core**: Add `context_providers` and `description` to `workflow.as_agent()` ([#4651](https://github.com/microsoft/agent-framework/pull/4651))
|
||||
- **agent-framework-core**: Add experimental file history provider ([#5248](https://github.com/microsoft/agent-framework/pull/5248))
|
||||
- **agent-framework-core**: Add OpenAI types to the default checkpoint encoding allow list ([#5297](https://github.com/microsoft/agent-framework/pull/5297))
|
||||
- **agent-framework-core**: Add `AgentExecutorResponse.with_text()` to preserve conversation history through custom executors ([#5255](https://github.com/microsoft/agent-framework/pull/5255))
|
||||
- **agent-framework-a2a**: Propagate A2A metadata from `Message`, `Artifact`, `Task`, and event types ([#5256](https://github.com/microsoft/agent-framework/pull/5256))
|
||||
- **agent-framework-core**: Add `finish_reason` support to `AgentResponse` and `AgentResponseUpdate` ([#5211](https://github.com/microsoft/agent-framework/pull/5211))
|
||||
- **agent-framework-hyperlight**: Add Hyperlight CodeAct package and docs ([#5185](https://github.com/microsoft/agent-framework/pull/5185))
|
||||
- **agent-framework-openai**: Add search tool content support for OpenAI responses ([#5302](https://github.com/microsoft/agent-framework/pull/5302))
|
||||
- **agent-framework-foundry**: Add support for Foundry Toolboxes ([#5346](https://github.com/microsoft/agent-framework/pull/5346))
|
||||
- **agent-framework-ag-ui**: Expose `forwardedProps` to agents and tools via session metadata ([#5264](https://github.com/microsoft/agent-framework/pull/5264))
|
||||
- **agent-framework-foundry**: Add hosted agent V2 support ([#5379](https://github.com/microsoft/agent-framework/pull/5379))
|
||||
|
||||
### Changed
|
||||
- **agent-framework-azure-cosmos**: [BREAKING] `CosmosCheckpointStorage` now uses restricted pickle deserialization by default, matching `FileCheckpointStorage` behavior. If your checkpoints contain application-defined types, pass them via `allowed_checkpoint_types=["my_app.models:MyState"]`. ([#5200](https://github.com/microsoft/agent-framework/issues/5200))
|
||||
- **agent-framework-core**: Improve skill name validation ([#4530](https://github.com/microsoft/agent-framework/pull/4530))
|
||||
- **agent-framework-azure-cosmos**: Add `allowed_checkpoint_types` support to `CosmosCheckpointStorage` for parity with `FileCheckpointStorage` ([#5202](https://github.com/microsoft/agent-framework/pull/5202))
|
||||
- **agent-framework-core**: Move `InMemory` history provider injection to first invocation ([#5236](https://github.com/microsoft/agent-framework/pull/5236))
|
||||
- **agent-framework-github-copilot**: Forward provider config to `SessionConfig` in `GitHubCopilotAgent` ([#5195](https://github.com/microsoft/agent-framework/pull/5195))
|
||||
- **agent-framework-hyperlight-codeact**: Flatten `execute_code` output ([#5333](https://github.com/microsoft/agent-framework/pull/5333))
|
||||
- **dependencies**: Bump `pygments` from `2.19.2` to `2.20.0` in `/python` ([#4978](https://github.com/microsoft/agent-framework/pull/4978))
|
||||
- **tests**: Bump misc integration retry delay to 30s ([#5293](https://github.com/microsoft/agent-framework/pull/5293))
|
||||
- **tests**: Improve misc integration test robustness ([#5295](https://github.com/microsoft/agent-framework/pull/5295))
|
||||
- **tests**: Skip hosted tools test on transient upstream MCP errors ([#5296](https://github.com/microsoft/agent-framework/pull/5296))
|
||||
|
||||
### Fixed
|
||||
- **agent-framework-core**: Fix `python-feature-lifecycle` skill YAML frontmatter ([#5226](https://github.com/microsoft/agent-framework/pull/5226))
|
||||
- **agent-framework-core**: Fix `HandoffBuilder` dropping function-level middleware when cloning agents ([#5220](https://github.com/microsoft/agent-framework/pull/5220))
|
||||
- **agent-framework-ag-ui**: Fix deterministic state updates from tool results ([#5201](https://github.com/microsoft/agent-framework/pull/5201))
|
||||
- **agent-framework-devui**: Fix streaming memory growth and add cross-platform regression coverage ([#5221](https://github.com/microsoft/agent-framework/pull/5221))
|
||||
- **agent-framework-core**: Skip `get_final_response` in `_finalize_stream` when the stream has errored ([#5232](https://github.com/microsoft/agent-framework/pull/5232))
|
||||
- **agent-framework-openai**: Fix reasoning replay when `store=False` ([#5250](https://github.com/microsoft/agent-framework/pull/5250))
|
||||
- **agent-framework-foundry**: Handle `url_citation` annotations in `FoundryChatClient` streaming responses ([#5071](https://github.com/microsoft/agent-framework/pull/5071))
|
||||
- **agent-framework-gemini**: Fix Gemini client support for Gemini API and Vertex AI ([#5258](https://github.com/microsoft/agent-framework/pull/5258))
|
||||
- **agent-framework-copilotstudio**: Fix `CopilotStudioAgent` to reuse conversation ID from an existing session ([#5299](https://github.com/microsoft/agent-framework/pull/5299))
|
||||
|
||||
## [devui-1.0.0b260414] - 2026-04-14
|
||||
|
||||
@@ -939,8 +903,7 @@ Release candidate for **agent-framework-core** and **agent-framework-azure-ai**
|
||||
|
||||
For more information, see the [announcement blog post](https://devblogs.microsoft.com/foundry/introducing-microsoft-agent-framework-the-open-source-engine-for-agentic-ai-apps/).
|
||||
|
||||
[Unreleased]: https://github.com/microsoft/agent-framework/compare/python-1.1.0...HEAD
|
||||
[1.1.0]: https://github.com/microsoft/agent-framework/compare/python-1.0.1...python-1.1.0
|
||||
[Unreleased]: https://github.com/microsoft/agent-framework/compare/python-1.0.1...HEAD
|
||||
[1.0.1]: https://github.com/microsoft/agent-framework/compare/python-1.0.0...python-1.0.1
|
||||
[1.0.0]: https://github.com/microsoft/agent-framework/compare/python-1.0.0rc6...python-1.0.0
|
||||
[1.0.0rc6]: https://github.com/microsoft/agent-framework/compare/python-1.0.0rc5...python-1.0.0rc6
|
||||
|
||||
@@ -33,7 +33,6 @@ Status is grouped into these buckets:
|
||||
| `agent-framework-foundry-local` | `python/packages/foundry_local` | `beta` |
|
||||
| `agent-framework-gemini` | `python/packages/gemini` | `alpha` |
|
||||
| `agent-framework-github-copilot` | `python/packages/github_copilot` | `beta` |
|
||||
| `agent-framework-hyperlight` | `python/packages/hyperlight` | `alpha` |
|
||||
| `agent-framework-lab` | `python/packages/lab` | `beta` |
|
||||
| `agent-framework-mem0` | `python/packages/mem0` | `beta` |
|
||||
| `agent-framework-ollama` | `python/packages/ollama` | `beta` |
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "A2A integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"a2a-sdk>=0.3.5,<0.3.24",
|
||||
]
|
||||
|
||||
|
||||
@@ -69,23 +69,19 @@ if TYPE_CHECKING:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Keys that are internal to AG-UI orchestration and should not be passed to chat clients
|
||||
AG_UI_INTERNAL_METADATA_KEYS = {"ag_ui_thread_id", "ag_ui_run_id", "current_state", "forwarded_props"}
|
||||
AG_UI_INTERNAL_METADATA_KEYS = {"ag_ui_thread_id", "ag_ui_run_id", "current_state"}
|
||||
|
||||
|
||||
def _build_safe_metadata(thread_metadata: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""Build metadata dict with string values for Azure compatibility.
|
||||
"""Build metadata dict with truncated string values for Azure compatibility.
|
||||
|
||||
Azure has a 512 character limit per metadata value. String values that
|
||||
already fit are kept as-is. Non-string values are JSON-serialized. If the
|
||||
resulting string exceeds 512 characters the key is **dropped** (with a
|
||||
warning) instead of truncated, because truncation can produce invalid JSON
|
||||
that downstream consumers cannot decode.
|
||||
Azure has a 512 character limit per metadata value.
|
||||
|
||||
Args:
|
||||
thread_metadata: Raw metadata dict
|
||||
|
||||
Returns:
|
||||
Metadata with safe string values (each <= 512 chars)
|
||||
Metadata with string values truncated to 512 chars
|
||||
"""
|
||||
if not thread_metadata:
|
||||
return {}
|
||||
@@ -93,12 +89,7 @@ def _build_safe_metadata(thread_metadata: dict[str, Any] | None) -> dict[str, An
|
||||
for key, value in thread_metadata.items():
|
||||
value_str = value if isinstance(value, str) else json.dumps(value)
|
||||
if len(value_str) > 512:
|
||||
logger.warning(
|
||||
"Dropping metadata key %r: serialized value is %d chars (limit 512)",
|
||||
key,
|
||||
len(value_str),
|
||||
)
|
||||
continue
|
||||
value_str = value_str[:512]
|
||||
safe_metadata[key] = value_str
|
||||
return safe_metadata
|
||||
|
||||
@@ -799,10 +790,6 @@ async def run_agent_stream(
|
||||
"ag_ui_thread_id": thread_id,
|
||||
"ag_ui_run_id": run_id,
|
||||
}
|
||||
if "forwarded_props" in input_data:
|
||||
base_metadata["forwarded_props"] = input_data["forwarded_props"]
|
||||
elif "forwardedProps" in input_data:
|
||||
base_metadata["forwarded_props"] = input_data["forwardedProps"]
|
||||
if flow.current_state:
|
||||
base_metadata["current_state"] = flow.current_state
|
||||
session.metadata = _build_safe_metadata(base_metadata) # type: ignore[attr-defined]
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
@@ -582,33 +581,11 @@ async def run_workflow_stream(
|
||||
flow.accumulated_text = ""
|
||||
return [TextMessageEndEvent(message_id=current_message_id)]
|
||||
|
||||
fwd_kwargs: dict[str, Any] = {}
|
||||
if "forwarded_props" in input_data:
|
||||
forwarded_props = input_data["forwarded_props"]
|
||||
fwd_kwargs["function_invocation_kwargs"] = {"forwarded_props": forwarded_props}
|
||||
elif "forwardedProps" in input_data:
|
||||
forwarded_props = input_data["forwardedProps"]
|
||||
fwd_kwargs["function_invocation_kwargs"] = {"forwarded_props": forwarded_props}
|
||||
|
||||
# Only pass function_invocation_kwargs if the workflow.run signature accepts it
|
||||
if fwd_kwargs:
|
||||
try:
|
||||
sig = inspect.signature(workflow.run)
|
||||
params = sig.parameters
|
||||
accepts_fwd = "function_invocation_kwargs" in params or any(
|
||||
p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
accepts_fwd = False
|
||||
if not accepts_fwd:
|
||||
logger.debug("workflow.run() does not accept function_invocation_kwargs; dropping forwarded_props")
|
||||
fwd_kwargs = {}
|
||||
|
||||
try:
|
||||
if responses:
|
||||
event_stream = workflow.run(responses=responses, stream=True, **fwd_kwargs)
|
||||
event_stream = workflow.run(responses=responses, stream=True)
|
||||
else:
|
||||
event_stream = workflow.run(message=messages, stream=True, **fwd_kwargs)
|
||||
event_stream = workflow.run(message=messages, stream=True)
|
||||
|
||||
async for event in event_stream:
|
||||
event_type = getattr(event, "type", None)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "agent-framework-ag-ui"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
description = "AG-UI protocol integration for Agent Framework"
|
||||
readme = "README.md"
|
||||
license-files = ["LICENSE"]
|
||||
@@ -22,7 +22,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"ag-ui-protocol==0.1.13",
|
||||
"fastapi>=0.115.0,<0.133.1",
|
||||
"uvicorn[standard]>=0.30.0,<0.42.0"
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Tests for forwarded_props inclusion in AG-UI session metadata."""
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from agent_framework_ag_ui._agent_run import AG_UI_INTERNAL_METADATA_KEYS, _build_safe_metadata
|
||||
|
||||
|
||||
class TestForwardedPropsInSessionMetadata:
|
||||
"""Verify that forwarded_props is surfaced in session metadata and filtered from LLM metadata."""
|
||||
|
||||
def test_forwarded_props_in_internal_metadata_keys(self):
|
||||
"""forwarded_props is listed in AG_UI_INTERNAL_METADATA_KEYS to prevent LLM leakage."""
|
||||
assert "forwarded_props" in AG_UI_INTERNAL_METADATA_KEYS
|
||||
|
||||
def test_forwarded_props_filtered_from_client_metadata(self):
|
||||
"""forwarded_props is filtered out when building LLM-bound client metadata."""
|
||||
session_metadata: dict[str, Any] = {
|
||||
"ag_ui_thread_id": "t1",
|
||||
"ag_ui_run_id": "r1",
|
||||
"forwarded_props": '{"custom_flag": true}',
|
||||
}
|
||||
|
||||
client_metadata = {k: v for k, v in session_metadata.items() if k not in AG_UI_INTERNAL_METADATA_KEYS}
|
||||
|
||||
assert "forwarded_props" not in client_metadata
|
||||
assert "ag_ui_thread_id" not in client_metadata
|
||||
|
||||
|
||||
class TestBuildSafeMetadata:
|
||||
"""Verify _build_safe_metadata handles various value types correctly."""
|
||||
|
||||
def test_string_value_unchanged(self):
|
||||
result = _build_safe_metadata({"key": "hello"})
|
||||
assert result == {"key": "hello"}
|
||||
|
||||
def test_dict_value_serialized_to_json(self):
|
||||
result = _build_safe_metadata({"fp": {"flag": True, "source": "frontend"}})
|
||||
assert "fp" in result
|
||||
assert isinstance(result["fp"], str)
|
||||
# Must be valid, decodable JSON
|
||||
decoded = json.loads(result["fp"])
|
||||
assert decoded == {"flag": True, "source": "frontend"}
|
||||
|
||||
def test_empty_dict_serialized_to_json(self):
|
||||
result = _build_safe_metadata({"fp": {}})
|
||||
assert result["fp"] == "{}"
|
||||
assert json.loads(result["fp"]) == {}
|
||||
|
||||
def test_value_within_limit_kept(self):
|
||||
value = "x" * 512
|
||||
result = _build_safe_metadata({"key": value})
|
||||
assert result["key"] == value
|
||||
|
||||
def test_value_exceeding_limit_dropped(self):
|
||||
"""Values exceeding 512 chars are dropped entirely (not truncated)."""
|
||||
value = "x" * 513
|
||||
result = _build_safe_metadata({"key": value})
|
||||
assert "key" not in result
|
||||
|
||||
def test_json_value_exceeding_limit_dropped(self):
|
||||
"""JSON-serialized dict exceeding 512 chars is dropped, not truncated into invalid JSON."""
|
||||
big_dict = {f"key_{i}": "v" * 100 for i in range(50)}
|
||||
result = _build_safe_metadata({"forwarded_props": big_dict})
|
||||
assert "forwarded_props" not in result
|
||||
|
||||
def test_other_keys_preserved_when_one_dropped(self):
|
||||
"""Dropping one oversized key does not affect other keys."""
|
||||
result = _build_safe_metadata(
|
||||
{
|
||||
"small": "ok",
|
||||
"big": "x" * 600,
|
||||
}
|
||||
)
|
||||
assert result == {"small": "ok"}
|
||||
|
||||
def test_none_input_returns_empty(self):
|
||||
assert _build_safe_metadata(None) == {}
|
||||
|
||||
def test_empty_input_returns_empty(self):
|
||||
assert _build_safe_metadata({}) == {}
|
||||
@@ -63,12 +63,12 @@ class TestBuildSafeMetadata:
|
||||
result = _build_safe_metadata(metadata)
|
||||
assert result == metadata
|
||||
|
||||
def test_drops_long_strings(self):
|
||||
"""Drops strings over 512 chars instead of truncating."""
|
||||
def test_truncates_long_strings(self):
|
||||
"""Truncates strings over 512 chars."""
|
||||
long_value = "x" * 1000
|
||||
metadata = {"key": long_value}
|
||||
result = _build_safe_metadata(metadata)
|
||||
assert "key" not in result
|
||||
assert len(result["key"]) == 512
|
||||
|
||||
def test_serializes_non_strings(self):
|
||||
"""Serializes non-string values to JSON."""
|
||||
@@ -77,12 +77,12 @@ class TestBuildSafeMetadata:
|
||||
assert result["count"] == "42"
|
||||
assert result["items"] == "[1, 2, 3]"
|
||||
|
||||
def test_drops_oversized_serialized_values(self):
|
||||
"""Drops serialized values over 512 chars instead of truncating."""
|
||||
def test_truncates_serialized_values(self):
|
||||
"""Truncates serialized values over 512 chars."""
|
||||
long_list = list(range(200))
|
||||
metadata = {"data": long_list}
|
||||
result = _build_safe_metadata(metadata)
|
||||
assert "data" not in result
|
||||
assert len(result["data"]) == 512
|
||||
|
||||
|
||||
class TestHasOnlyToolCalls:
|
||||
|
||||
@@ -1672,210 +1672,3 @@ async def test_workflow_run_non_terminal_status_emits_custom():
|
||||
custom = [e for e in events if e.type == "CUSTOM" and e.name == "status"]
|
||||
assert len(custom) == 1
|
||||
assert custom[0].value == {"state": "running"}
|
||||
|
||||
|
||||
async def test_workflow_run_passes_forwarded_props_as_function_invocation_kwargs() -> None:
|
||||
"""forwarded_props from input_data is forwarded to workflow.run() via function_invocation_kwargs."""
|
||||
|
||||
class CapturingWorkflow:
|
||||
def __init__(self) -> None:
|
||||
self.captured_kwargs: dict[str, Any] = {}
|
||||
|
||||
def run(self, **kwargs: Any):
|
||||
self.captured_kwargs = dict(kwargs)
|
||||
|
||||
async def _stream():
|
||||
yield SimpleNamespace(type="started")
|
||||
|
||||
return _stream()
|
||||
|
||||
workflow = CapturingWorkflow()
|
||||
events = [
|
||||
event
|
||||
async for event in run_workflow_stream(
|
||||
{
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"forwarded_props": {"custom_flag": True, "source": "copilotkit"},
|
||||
},
|
||||
cast(Any, workflow),
|
||||
)
|
||||
]
|
||||
|
||||
event_types = [event.type for event in events]
|
||||
assert "RUN_STARTED" in event_types
|
||||
assert "RUN_FINISHED" in event_types
|
||||
|
||||
assert workflow.captured_kwargs["stream"] is True
|
||||
assert "function_invocation_kwargs" in workflow.captured_kwargs
|
||||
assert workflow.captured_kwargs["function_invocation_kwargs"] == {
|
||||
"forwarded_props": {"custom_flag": True, "source": "copilotkit"},
|
||||
}
|
||||
|
||||
|
||||
async def test_workflow_run_omits_function_invocation_kwargs_when_no_forwarded_props() -> None:
|
||||
"""function_invocation_kwargs is not passed when forwarded_props is absent."""
|
||||
|
||||
class CapturingWorkflow:
|
||||
def __init__(self) -> None:
|
||||
self.captured_kwargs: dict[str, Any] = {}
|
||||
|
||||
def run(self, **kwargs: Any):
|
||||
self.captured_kwargs = dict(kwargs)
|
||||
|
||||
async def _stream():
|
||||
yield SimpleNamespace(type="started")
|
||||
|
||||
return _stream()
|
||||
|
||||
workflow = CapturingWorkflow()
|
||||
events = [
|
||||
event
|
||||
async for event in run_workflow_stream(
|
||||
{"messages": [{"role": "user", "content": "hello"}]},
|
||||
cast(Any, workflow),
|
||||
)
|
||||
]
|
||||
|
||||
event_types = [event.type for event in events]
|
||||
assert "RUN_STARTED" in event_types
|
||||
assert workflow.captured_kwargs["stream"] is True
|
||||
assert "function_invocation_kwargs" not in workflow.captured_kwargs
|
||||
|
||||
|
||||
async def test_workflow_run_accepts_camel_case_forwarded_props() -> None:
|
||||
"""forwardedProps (camelCase) is accepted as an alternative key."""
|
||||
|
||||
class CapturingWorkflow:
|
||||
def __init__(self) -> None:
|
||||
self.captured_kwargs: dict[str, Any] = {}
|
||||
|
||||
def run(self, **kwargs: Any):
|
||||
self.captured_kwargs = dict(kwargs)
|
||||
|
||||
async def _stream():
|
||||
yield SimpleNamespace(type="started")
|
||||
|
||||
return _stream()
|
||||
|
||||
workflow = CapturingWorkflow()
|
||||
events = [
|
||||
event
|
||||
async for event in run_workflow_stream(
|
||||
{
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"forwardedProps": {"source": "frontend"},
|
||||
},
|
||||
cast(Any, workflow),
|
||||
)
|
||||
]
|
||||
|
||||
event_types = [event.type for event in events]
|
||||
assert "RUN_STARTED" in event_types
|
||||
|
||||
assert workflow.captured_kwargs["stream"] is True
|
||||
assert "function_invocation_kwargs" in workflow.captured_kwargs
|
||||
assert workflow.captured_kwargs["function_invocation_kwargs"] == {
|
||||
"forwarded_props": {"source": "frontend"},
|
||||
}
|
||||
|
||||
|
||||
async def test_workflow_run_passes_empty_dict_forwarded_props() -> None:
|
||||
"""An empty dict forwarded_props={} should still be forwarded (not dropped by truthiness)."""
|
||||
|
||||
class CapturingWorkflow:
|
||||
def __init__(self) -> None:
|
||||
self.captured_kwargs: dict[str, Any] = {}
|
||||
|
||||
def run(self, **kwargs: Any):
|
||||
self.captured_kwargs = dict(kwargs)
|
||||
|
||||
async def _stream():
|
||||
yield SimpleNamespace(type="started")
|
||||
|
||||
return _stream()
|
||||
|
||||
workflow = CapturingWorkflow()
|
||||
events = [
|
||||
event
|
||||
async for event in run_workflow_stream(
|
||||
{
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"forwarded_props": {},
|
||||
},
|
||||
cast(Any, workflow),
|
||||
)
|
||||
]
|
||||
|
||||
event_types = [event.type for event in events]
|
||||
assert "RUN_STARTED" in event_types
|
||||
assert "RUN_FINISHED" in event_types
|
||||
|
||||
assert workflow.captured_kwargs["stream"] is True
|
||||
assert "function_invocation_kwargs" in workflow.captured_kwargs
|
||||
assert workflow.captured_kwargs["function_invocation_kwargs"] == {
|
||||
"forwarded_props": {},
|
||||
}
|
||||
|
||||
|
||||
async def test_workflow_run_stream_true_always_passed() -> None:
|
||||
"""stream=True is always passed to workflow.run()."""
|
||||
|
||||
class CapturingWorkflow:
|
||||
def __init__(self) -> None:
|
||||
self.captured_kwargs: dict[str, Any] = {}
|
||||
|
||||
def run(self, **kwargs: Any):
|
||||
self.captured_kwargs = dict(kwargs)
|
||||
|
||||
async def _stream():
|
||||
yield SimpleNamespace(type="started")
|
||||
|
||||
return _stream()
|
||||
|
||||
workflow = CapturingWorkflow()
|
||||
_ = [
|
||||
event
|
||||
async for event in run_workflow_stream(
|
||||
{
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"forwarded_props": {"key": "val"},
|
||||
},
|
||||
cast(Any, workflow),
|
||||
)
|
||||
]
|
||||
|
||||
assert workflow.captured_kwargs["stream"] is True
|
||||
|
||||
|
||||
async def test_workflow_run_drops_fwd_kwargs_when_run_lacks_param() -> None:
|
||||
"""function_invocation_kwargs is silently dropped if workflow.run() does not accept it."""
|
||||
|
||||
class StrictWorkflow:
|
||||
def __init__(self) -> None:
|
||||
self.captured_kwargs: dict[str, Any] = {}
|
||||
|
||||
def run(self, *, message: Any = None, responses: Any = None, stream: bool = False):
|
||||
self.captured_kwargs = {"message": message, "responses": responses, "stream": stream}
|
||||
|
||||
async def _stream():
|
||||
yield SimpleNamespace(type="started")
|
||||
|
||||
return _stream()
|
||||
|
||||
workflow = StrictWorkflow()
|
||||
events = [
|
||||
event
|
||||
async for event in run_workflow_stream(
|
||||
{
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"forwarded_props": {"custom": True},
|
||||
},
|
||||
cast(Any, workflow),
|
||||
)
|
||||
]
|
||||
|
||||
event_types = [event.type for event in events]
|
||||
assert "RUN_STARTED" in event_types
|
||||
assert "RUN_FINISHED" in event_types
|
||||
# No TypeError raised, and function_invocation_kwargs was not passed
|
||||
assert "function_invocation_kwargs" not in workflow.captured_kwargs
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Anthropic integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"anthropic>=0.80.0,<0.80.1",
|
||||
]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Azure AI Search integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"azure-search-documents>=11.7.0b2,<11.7.0b3",
|
||||
]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Azure Cosmos DB history provider integration for Microsoft Agent
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"azure-cosmos>=4.3.0,<5",
|
||||
]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Azure Functions integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -22,7 +22,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"agent-framework-durabletask",
|
||||
"azure-functions>=1.24.0,<2",
|
||||
"azure-functions-durable>=1.3.1,<2",
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Amazon Bedrock integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"boto3>=1.35.0,<2.0.0",
|
||||
"botocore>=1.35.0,<2.0.0",
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "OpenAI ChatKit integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -22,7 +22,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"openai-chatkit>=1.4.1,<2.0.0",
|
||||
]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Claude Agent SDK integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"claude-agent-sdk>=0.1.36,<0.1.49",
|
||||
]
|
||||
|
||||
|
||||
@@ -244,8 +244,7 @@ class CopilotStudioAgent(BaseAgent):
|
||||
"""Non-streaming implementation of run."""
|
||||
if not session:
|
||||
session = self.create_session()
|
||||
if not session.service_session_id:
|
||||
session.service_session_id = await self._start_new_conversation()
|
||||
session.service_session_id = await self._start_new_conversation()
|
||||
|
||||
input_messages = normalize_messages(messages)
|
||||
|
||||
@@ -272,8 +271,7 @@ class CopilotStudioAgent(BaseAgent):
|
||||
nonlocal session
|
||||
if not session:
|
||||
session = self.create_session()
|
||||
if not session.service_session_id:
|
||||
session.service_session_id = await self._start_new_conversation()
|
||||
session.service_session_id = await self._start_new_conversation()
|
||||
|
||||
input_messages = normalize_messages(messages)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Copilot Studio integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"microsoft-agents-copilotstudio-client>=0.3.1,<0.3.2",
|
||||
]
|
||||
|
||||
|
||||
@@ -245,47 +245,6 @@ class TestCopilotStudioAgent:
|
||||
assert response_count == 1
|
||||
assert session.service_session_id == "test-conversation-id"
|
||||
|
||||
async def test_run_reuses_existing_conversation(
|
||||
self, mock_copilot_client: MagicMock, mock_activity: MagicMock
|
||||
) -> None:
|
||||
"""Test run method reuses an existing conversation ID from the session."""
|
||||
agent = CopilotStudioAgent(client=mock_copilot_client)
|
||||
session = AgentSession()
|
||||
session.service_session_id = "existing-conversation-id"
|
||||
|
||||
mock_copilot_client.ask_question.return_value = create_async_generator([mock_activity])
|
||||
|
||||
response = await agent.run("test message", session=session)
|
||||
|
||||
assert isinstance(response, AgentResponse)
|
||||
assert session.service_session_id == "existing-conversation-id"
|
||||
mock_copilot_client.start_conversation.assert_not_called()
|
||||
mock_copilot_client.ask_question.assert_called_once_with("test message", "existing-conversation-id")
|
||||
|
||||
async def test_run_streaming_reuses_existing_conversation(self, mock_copilot_client: MagicMock) -> None:
|
||||
"""Test run(stream=True) method reuses an existing conversation ID from the session."""
|
||||
agent = CopilotStudioAgent(client=mock_copilot_client)
|
||||
session = AgentSession()
|
||||
session.service_session_id = "existing-conversation-id"
|
||||
|
||||
typing_activity = MagicMock()
|
||||
typing_activity.text = "Streaming response"
|
||||
typing_activity.type = "typing"
|
||||
typing_activity.id = "test-typing-id"
|
||||
typing_activity.from_property.name = "Test Bot"
|
||||
|
||||
mock_copilot_client.ask_question.return_value = create_async_generator([typing_activity])
|
||||
|
||||
response_count = 0
|
||||
async for response in agent.run("test message", session=session, stream=True):
|
||||
assert isinstance(response, AgentResponseUpdate)
|
||||
response_count += 1
|
||||
|
||||
assert response_count == 1
|
||||
assert session.service_session_id == "existing-conversation-id"
|
||||
mock_copilot_client.start_conversation.assert_not_called()
|
||||
mock_copilot_client.ask_question.assert_called_once_with("test message", "existing-conversation-id")
|
||||
|
||||
async def test_run_streaming_no_typing_activity(self, mock_copilot_client: MagicMock) -> None:
|
||||
"""Test run(stream=True) method with non-typing activity."""
|
||||
agent = CopilotStudioAgent(client=mock_copilot_client)
|
||||
|
||||
@@ -49,7 +49,6 @@ class ExperimentalFeature(str, Enum):
|
||||
EVALS = "EVALS"
|
||||
FILE_HISTORY = "FILE_HISTORY"
|
||||
SKILLS = "SKILLS"
|
||||
TOOLBOXES = "TOOLBOXES"
|
||||
|
||||
|
||||
class ReleaseCandidateFeature(str, Enum):
|
||||
|
||||
@@ -4,9 +4,6 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from typing import Any, Final
|
||||
|
||||
from . import __version__ as version_info
|
||||
@@ -29,34 +26,27 @@ USER_AGENT_KEY: Final[str] = "User-Agent"
|
||||
HTTP_USER_AGENT: Final[str] = "agent-framework-python"
|
||||
AGENT_FRAMEWORK_USER_AGENT = f"{HTTP_USER_AGENT}/{version_info}" # type: ignore[has-type]
|
||||
|
||||
_user_agent_prefixes: ContextVar[tuple[str, ...]] = ContextVar("_user_agent_prefixes", default=())
|
||||
_user_agent_prefixes: list[str] = []
|
||||
|
||||
|
||||
@contextmanager
|
||||
def user_agent_prefix(prefix: str) -> Generator[None]:
|
||||
"""Context manager that adds a prefix to the user agent string for the current scope.
|
||||
def append_to_user_agent(prefix: str) -> None:
|
||||
"""Prepend a prefix to the agent framework user agent string.
|
||||
|
||||
This is useful for upstream layers that want to identify themselves in telemetry
|
||||
for the duration of a request without permanently mutating global state.
|
||||
This is useful for hosting layers that want to identify themselves in telemetry.
|
||||
Duplicate prefixes are ignored.
|
||||
|
||||
Args:
|
||||
prefix: The prefix to add (e.g. "foundry-hosting").
|
||||
prefix: The prefix to prepend (e.g. "foundry-hosting").
|
||||
"""
|
||||
current = _user_agent_prefixes.get()
|
||||
token = _user_agent_prefixes.set((*current, prefix)) if prefix and prefix not in current else None
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if token is not None:
|
||||
_user_agent_prefixes.reset(token)
|
||||
if prefix and prefix not in _user_agent_prefixes:
|
||||
_user_agent_prefixes.append(prefix)
|
||||
|
||||
|
||||
def _get_user_agent() -> str:
|
||||
"""Return the full user agent string including any context-scoped prefixes."""
|
||||
prefixes = _user_agent_prefixes.get()
|
||||
if not prefixes:
|
||||
"""Return the full user agent string including any prepended prefixes."""
|
||||
if not _user_agent_prefixes:
|
||||
return AGENT_FRAMEWORK_USER_AGENT
|
||||
return f"{'/'.join(prefixes)}/{AGENT_FRAMEWORK_USER_AGENT}"
|
||||
return f"{'/'.join(_user_agent_prefixes)}/{AGENT_FRAMEWORK_USER_AGENT}"
|
||||
|
||||
|
||||
def prepend_agent_framework_to_user_agent(headers: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
|
||||
@@ -12,7 +12,6 @@ from collections.abc import (
|
||||
AsyncIterable,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Iterable,
|
||||
Mapping,
|
||||
Sequence,
|
||||
)
|
||||
@@ -90,7 +89,6 @@ logger = logging.getLogger("agent_framework")
|
||||
DEFAULT_MAX_ITERATIONS: Final[int] = 40
|
||||
DEFAULT_MAX_CONSECUTIVE_ERRORS_PER_REQUEST: Final[int] = 3
|
||||
SHELL_TOOL_KIND_VALUE: Final[str] = "shell"
|
||||
ApprovalMode: TypeAlias = Literal["always_require", "never_require"]
|
||||
ChatClientT = TypeVar("ChatClientT", bound="SupportsChatGetResponse[Any]")
|
||||
ResponseModelBoundT = TypeVar("ResponseModelBoundT", bound=BaseModel)
|
||||
|
||||
@@ -272,7 +270,7 @@ class FunctionTool(SerializationMixin):
|
||||
*,
|
||||
name: str,
|
||||
description: str = "",
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
approval_mode: Literal["always_require", "never_require"] | None = None,
|
||||
kind: str | None = None,
|
||||
max_invocations: int | None = None,
|
||||
max_invocation_exceptions: int | None = None,
|
||||
@@ -860,15 +858,6 @@ def normalize_tools(
|
||||
Returns:
|
||||
A normalized list where callable inputs are converted to ``FunctionTool``
|
||||
using :func:`tool`, and existing tool objects are passed through unchanged.
|
||||
|
||||
Tool-collection wrappers are flattened in two forms:
|
||||
|
||||
- non-tool, non-callable iterables
|
||||
- mapping-like objects that expose a ``.tools`` collection (for example
|
||||
``ToolboxVersionObject`` from azure-ai-projects)
|
||||
|
||||
This lets callers write ``tools=[toolbox, my_func]`` and have the
|
||||
toolbox's contents spread in alongside individual tools.
|
||||
"""
|
||||
if not tools:
|
||||
return []
|
||||
@@ -893,24 +882,6 @@ def normalize_tools(
|
||||
if callable(tool_item): # type: ignore[reportUnknownArgumentType]
|
||||
normalized.append(tool(tool_item))
|
||||
continue
|
||||
# Mapping-like tool collections (for example ToolboxVersionObject) are
|
||||
# not flattened by the generic Iterable branch below because they are
|
||||
# also Mapping instances. If they expose a ``tools`` collection, spread
|
||||
# that collection into the normalized list.
|
||||
collection_tools = getattr(tool_item, "tools", None) # type: ignore[reportUnknownArgumentType]
|
||||
if isinstance(collection_tools, Iterable) and not isinstance(
|
||||
collection_tools, (str, bytes, bytearray, Mapping)
|
||||
):
|
||||
normalized.extend(normalize_tools(list(collection_tools))) # type: ignore[reportUnknownArgumentType]
|
||||
continue
|
||||
# Tool-collection wrapper (e.g. FoundryToolbox): a non-tool, non-callable
|
||||
# iterable. Flatten its contents so ``tools=[toolbox, my_func]`` works.
|
||||
# Strings, mappings, and Pydantic BaseModel are excluded — BaseModel
|
||||
# instances iterate over (field, value) tuples, not tools, so they
|
||||
# should pass through as leaf tool specs (handled below).
|
||||
if isinstance(tool_item, Iterable) and not isinstance(tool_item, (str, bytes, bytearray, Mapping, BaseModel)):
|
||||
normalized.extend(normalize_tools(list(tool_item))) # type: ignore[reportUnknownArgumentType]
|
||||
continue
|
||||
normalized.append(tool_item) # type: ignore[reportUnknownArgumentType]
|
||||
return normalized
|
||||
|
||||
@@ -1062,7 +1033,7 @@ def tool(
|
||||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
schema: type[BaseModel] | Mapping[str, Any] | None = None,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
approval_mode: Literal["always_require", "never_require"] | None = None,
|
||||
kind: str | None = None,
|
||||
max_invocations: int | None = None,
|
||||
max_invocation_exceptions: int | None = None,
|
||||
@@ -1078,7 +1049,7 @@ def tool(
|
||||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
schema: type[BaseModel] | Mapping[str, Any] | None = None,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
approval_mode: Literal["always_require", "never_require"] | None = None,
|
||||
kind: str | None = None,
|
||||
max_invocations: int | None = None,
|
||||
max_invocation_exceptions: int | None = None,
|
||||
@@ -1093,7 +1064,7 @@ def tool(
|
||||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
schema: type[BaseModel] | Mapping[str, Any] | None = None,
|
||||
approval_mode: ApprovalMode | None = None,
|
||||
approval_mode: Literal["always_require", "never_require"] | None = None,
|
||||
kind: str | None = None,
|
||||
max_invocations: int | None = None,
|
||||
max_invocation_exceptions: int | None = None,
|
||||
|
||||
@@ -351,8 +351,6 @@ ContentType = Literal[
|
||||
"image_generation_tool_result",
|
||||
"mcp_server_tool_call",
|
||||
"mcp_server_tool_result",
|
||||
"search_tool_call",
|
||||
"search_tool_result",
|
||||
"shell_tool_call",
|
||||
"shell_tool_result",
|
||||
"shell_command_output",
|
||||
@@ -866,56 +864,6 @@ class Content:
|
||||
raw_representation=raw_representation,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_search_tool_call(
|
||||
cls: type[ContentT],
|
||||
call_id: str,
|
||||
*,
|
||||
tool_name: str,
|
||||
arguments: str | Mapping[str, Any] | None = None,
|
||||
status: str | None = None,
|
||||
annotations: Sequence[Annotation] | None = None,
|
||||
additional_properties: MutableMapping[str, Any] | None = None,
|
||||
raw_representation: Any = None,
|
||||
) -> ContentT:
|
||||
"""Create search tool call content."""
|
||||
return cls(
|
||||
"search_tool_call",
|
||||
call_id=call_id,
|
||||
tool_name=tool_name,
|
||||
arguments=arguments,
|
||||
status=status,
|
||||
annotations=annotations,
|
||||
additional_properties=additional_properties,
|
||||
raw_representation=raw_representation,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_search_tool_result(
|
||||
cls: type[ContentT],
|
||||
call_id: str,
|
||||
*,
|
||||
tool_name: str,
|
||||
result: Any = None,
|
||||
items: Sequence[Content] | None = None,
|
||||
status: str | None = None,
|
||||
annotations: Sequence[Annotation] | None = None,
|
||||
additional_properties: MutableMapping[str, Any] | None = None,
|
||||
raw_representation: Any = None,
|
||||
) -> ContentT:
|
||||
"""Create search tool result content."""
|
||||
return cls(
|
||||
"search_tool_result",
|
||||
call_id=call_id,
|
||||
tool_name=tool_name,
|
||||
result=result,
|
||||
items=list(items) if items is not None else None,
|
||||
status=status,
|
||||
annotations=annotations,
|
||||
additional_properties=additional_properties,
|
||||
raw_representation=raw_representation,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_usage(
|
||||
cls: type[ContentT],
|
||||
@@ -1530,7 +1478,7 @@ class Content:
|
||||
return span.lower() == top_level_media_type.lower()
|
||||
|
||||
def parse_arguments(self) -> dict[str, Any | None] | None:
|
||||
"""Parse arguments from function_call, mcp_server_tool_call, or search_tool_call content.
|
||||
"""Parse arguments from function_call or mcp_server_tool_call content.
|
||||
|
||||
If arguments cannot be parsed as JSON or the result is not a dict,
|
||||
they are returned as a dictionary with a single key "raw".
|
||||
|
||||
@@ -20,7 +20,6 @@ _IMPORTS: dict[str, tuple[str, str]] = {
|
||||
"FoundryEmbeddingOptions": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"FoundryEmbeddingSettings": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"FoundryEvals": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"FoundryHostedToolType": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"FoundryMemoryProvider": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"FoundryLocalChatOptions": ("agent_framework_foundry_local", "agent-framework-foundry-local"),
|
||||
"FoundryLocalClient": ("agent_framework_foundry_local", "agent-framework-foundry-local"),
|
||||
@@ -32,9 +31,6 @@ _IMPORTS: dict[str, tuple[str, str]] = {
|
||||
"RawFoundryEmbeddingClient": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"evaluate_foundry_target": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"evaluate_traces": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"get_toolbox_tool_name": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"get_toolbox_tool_type": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
"select_toolbox_tools": ("agent_framework_foundry", "agent-framework-foundry"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from agent_framework_foundry import (
|
||||
FoundryEmbeddingOptions,
|
||||
FoundryEmbeddingSettings,
|
||||
FoundryEvals,
|
||||
FoundryHostedToolType,
|
||||
FoundryMemoryProvider,
|
||||
RawFoundryAgent,
|
||||
RawFoundryAgentChatClient,
|
||||
@@ -20,9 +19,6 @@ from agent_framework_foundry import (
|
||||
RawFoundryEmbeddingClient,
|
||||
evaluate_foundry_target,
|
||||
evaluate_traces,
|
||||
get_toolbox_tool_name,
|
||||
get_toolbox_tool_type,
|
||||
select_toolbox_tools,
|
||||
)
|
||||
from agent_framework_foundry_local import (
|
||||
FoundryLocalChatOptions,
|
||||
@@ -39,7 +35,6 @@ __all__ = [
|
||||
"FoundryEmbeddingOptions",
|
||||
"FoundryEmbeddingSettings",
|
||||
"FoundryEvals",
|
||||
"FoundryHostedToolType",
|
||||
"FoundryLocalChatOptions",
|
||||
"FoundryLocalClient",
|
||||
"FoundryLocalSettings",
|
||||
@@ -51,7 +46,4 @@ __all__ = [
|
||||
"RawFoundryEmbeddingClient",
|
||||
"evaluate_foundry_target",
|
||||
"evaluate_traces",
|
||||
"get_toolbox_tool_name",
|
||||
"get_toolbox_tool_type",
|
||||
"select_toolbox_tools",
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Microsoft Agent Framework for building AI Agents with Python. Thi
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.1.0"
|
||||
version = "1.0.1"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
|
||||
@@ -8,7 +8,6 @@ from agent_framework import (
|
||||
USER_AGENT_TELEMETRY_DISABLED_ENV_VAR,
|
||||
prepend_agent_framework_to_user_agent,
|
||||
)
|
||||
from agent_framework._telemetry import user_agent_prefix
|
||||
|
||||
# region Test constants
|
||||
|
||||
@@ -97,56 +96,3 @@ def test_modifies_original_dict():
|
||||
|
||||
assert result is headers # Same object
|
||||
assert "User-Agent" in headers
|
||||
|
||||
|
||||
# region Test user_agent_prefix context manager
|
||||
|
||||
|
||||
def test_user_agent_prefix_adds_prefix():
|
||||
"""Test that the context manager adds a prefix within its scope."""
|
||||
with user_agent_prefix("test-host"):
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert result["User-Agent"].startswith("test-host/")
|
||||
assert AGENT_FRAMEWORK_USER_AGENT in result["User-Agent"]
|
||||
|
||||
# Prefix is removed after exiting the context
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert result["User-Agent"] == AGENT_FRAMEWORK_USER_AGENT
|
||||
|
||||
|
||||
def test_user_agent_prefix_ignores_duplicates():
|
||||
"""Test that duplicate prefixes are not added within nested scopes."""
|
||||
with user_agent_prefix("test-host"), user_agent_prefix("test-host"):
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert result["User-Agent"].count("test-host") == 1
|
||||
|
||||
|
||||
def test_user_agent_prefix_ignores_empty():
|
||||
"""Test that empty strings are not added as prefixes."""
|
||||
with user_agent_prefix(""):
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert result["User-Agent"] == AGENT_FRAMEWORK_USER_AGENT
|
||||
|
||||
|
||||
def test_user_agent_prefix_restores_on_exit():
|
||||
"""Test that prefixes are fully restored after the context manager exits."""
|
||||
with user_agent_prefix("test-host"):
|
||||
pass
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert result["User-Agent"] == AGENT_FRAMEWORK_USER_AGENT
|
||||
|
||||
|
||||
def test_user_agent_prefix_nesting():
|
||||
"""Test that nested context managers compose prefixes correctly."""
|
||||
with user_agent_prefix("outer"):
|
||||
with user_agent_prefix("inner"):
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert "outer" in result["User-Agent"]
|
||||
assert "inner" in result["User-Agent"]
|
||||
# Inner prefix removed
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert "outer" in result["User-Agent"]
|
||||
assert "inner" not in result["User-Agent"]
|
||||
# Both removed
|
||||
result = prepend_agent_framework_to_user_agent()
|
||||
assert result["User-Agent"] == AGENT_FRAMEWORK_USER_AGENT
|
||||
|
||||
@@ -1144,160 +1144,3 @@ def test_parse_annotation_with_annotated_and_literal():
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
# region normalize_tools flattening of tool-collection wrappers
|
||||
|
||||
|
||||
def _make_flatten_function_tool(name: str) -> FunctionTool:
|
||||
"""Build a FunctionTool for flattening tests."""
|
||||
|
||||
@tool(name=name, description=f"{name} tool")
|
||||
def _impl(x: int) -> int:
|
||||
return x
|
||||
|
||||
return _impl # type: ignore[return-value]
|
||||
|
||||
|
||||
def test_normalize_tools_flattens_tool_collection_wrapper() -> None:
|
||||
"""A non-tool, non-callable iterable inside the tools list is flattened."""
|
||||
from agent_framework._tools import normalize_tools
|
||||
|
||||
inner_a = _make_flatten_function_tool("inner_a")
|
||||
inner_b = _make_flatten_function_tool("inner_b")
|
||||
|
||||
class ToolBundle:
|
||||
"""Minimal stand-in for a tool-collection wrapper like FoundryToolbox."""
|
||||
|
||||
def __init__(self, tools: list[FunctionTool]) -> None:
|
||||
self._tools = tools
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._tools)
|
||||
|
||||
bundle = ToolBundle([inner_a, inner_b])
|
||||
|
||||
normalized = normalize_tools([bundle])
|
||||
|
||||
assert len(normalized) == 2
|
||||
assert normalized[0] is inner_a
|
||||
assert normalized[1] is inner_b
|
||||
|
||||
|
||||
def test_normalize_tools_combines_bundle_with_individual_tools() -> None:
|
||||
"""The canonical ``tools=[bundle, my_func]`` call site spreads bundle + individual."""
|
||||
from agent_framework._tools import normalize_tools
|
||||
|
||||
bundled = _make_flatten_function_tool("bundled")
|
||||
standalone = _make_flatten_function_tool("standalone")
|
||||
|
||||
class ToolBundle:
|
||||
def __init__(self, tools: list[FunctionTool]) -> None:
|
||||
self._tools = tools
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._tools)
|
||||
|
||||
normalized = normalize_tools([ToolBundle([bundled]), standalone])
|
||||
|
||||
assert len(normalized) == 2
|
||||
assert normalized[0] is bundled
|
||||
assert normalized[1] is standalone
|
||||
|
||||
|
||||
def test_normalize_tools_flattens_nested_bundles() -> None:
|
||||
"""Bundles inside bundles are flattened recursively via the recursive call."""
|
||||
from agent_framework._tools import normalize_tools
|
||||
|
||||
inner = _make_flatten_function_tool("deep")
|
||||
|
||||
class ToolBundle:
|
||||
def __init__(self, tools: list[Any]) -> None:
|
||||
self._tools = tools
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._tools)
|
||||
|
||||
nested = ToolBundle([ToolBundle([inner])])
|
||||
|
||||
normalized = normalize_tools([nested])
|
||||
|
||||
assert len(normalized) == 1
|
||||
assert normalized[0] is inner
|
||||
|
||||
|
||||
def test_normalize_tools_bundle_only_form() -> None:
|
||||
"""Passing a bundle directly (no outer list) also flattens its contents.
|
||||
|
||||
``tools=bundle`` — the outer wrap-in-list happens in the non-Sequence
|
||||
branch, then the flattening logic kicks in on the inner pass.
|
||||
"""
|
||||
from agent_framework._tools import normalize_tools
|
||||
|
||||
a = _make_flatten_function_tool("a")
|
||||
b = _make_flatten_function_tool("b")
|
||||
|
||||
class ToolBundle:
|
||||
def __init__(self, tools: list[FunctionTool]) -> None:
|
||||
self._tools = tools
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._tools)
|
||||
|
||||
normalized = normalize_tools(ToolBundle([a, b])) # type: ignore[arg-type]
|
||||
|
||||
assert len(normalized) == 2
|
||||
assert normalized[0] is a
|
||||
assert normalized[1] is b
|
||||
|
||||
|
||||
def test_normalize_tools_does_not_flatten_known_tool_types() -> None:
|
||||
"""FunctionTool / dict / callable are detected before the flatten branch."""
|
||||
from agent_framework._tools import normalize_tools
|
||||
|
||||
func_tool = _make_flatten_function_tool("ft")
|
||||
dict_tool: dict[str, Any] = {"type": "code_interpreter", "container": {"type": "auto"}}
|
||||
|
||||
def plain_callable(x: int) -> int:
|
||||
return x
|
||||
|
||||
normalized = normalize_tools([func_tool, dict_tool, plain_callable])
|
||||
|
||||
assert len(normalized) == 3
|
||||
assert normalized[0] is func_tool
|
||||
assert normalized[1] is dict_tool
|
||||
# plain_callable was wrapped in a FunctionTool via the @tool helper
|
||||
assert isinstance(normalized[2], FunctionTool)
|
||||
|
||||
|
||||
def test_normalize_tools_flattens_mapping_like_toolbox_with_tools_attr() -> None:
|
||||
"""Mapping-like toolbox objects with ``.tools`` should still flatten."""
|
||||
from collections.abc import Mapping as MappingABC
|
||||
|
||||
from agent_framework._tools import normalize_tools
|
||||
|
||||
bundled = _make_flatten_function_tool("bundled")
|
||||
standalone = _make_flatten_function_tool("standalone")
|
||||
|
||||
class ToolBundleMapping(MappingABC[str, Any]):
|
||||
def __init__(self, tools: list[FunctionTool]) -> None:
|
||||
self.tools = tools
|
||||
self._data = {"name": "research_tools", "version": "v1", "tools": tools}
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
return self._data[key]
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._data)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._data)
|
||||
|
||||
normalized = normalize_tools([ToolBundleMapping([bundled]), standalone])
|
||||
|
||||
assert len(normalized) == 2
|
||||
assert normalized[0] is bundled
|
||||
assert normalized[1] is standalone
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
@@ -664,21 +664,6 @@ def test_function_approval_serialization_roundtrip():
|
||||
# The Content union will need to be handled differently when we fully migrate
|
||||
|
||||
|
||||
def test_function_approval_request_function_call_none_guard():
|
||||
"""Test that accessing function_call attributes is safe when function_call is None."""
|
||||
# Construct a Content with type "function_approval_request" but no function_call.
|
||||
# This verifies the None-guard pattern used in samples to prevent AttributeError.
|
||||
content = Content("function_approval_request", id="req-none")
|
||||
assert content.function_call is None
|
||||
|
||||
# A proper approval request always has function_call set
|
||||
fc = Content.from_function_call(call_id="call-1", name="do_something", arguments={"a": 1})
|
||||
req = Content.from_function_approval_request(id="req-1", function_call=fc)
|
||||
assert req.function_call is not None
|
||||
assert req.function_call.name == "do_something"
|
||||
assert req.function_call.arguments == {"a": 1}
|
||||
|
||||
|
||||
def test_function_approval_accepts_mcp_call():
|
||||
"""Ensure FunctionApprovalRequestContent supports MCP server tool calls."""
|
||||
mcp_call = Content.from_mcp_server_tool_call(
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Declarative specification support for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -22,7 +22,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"powerfx>=0.0.32,<0.0.35; python_version < '3.14'",
|
||||
"pyyaml>=6.0,<7.0",
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Debug UI for Microsoft Agent Framework with OpenAI-compatible API
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260414"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://github.com/microsoft/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -23,7 +23,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"openai>=1.99.0,<3",
|
||||
"opentelemetry-sdk>=1.39.0,<2",
|
||||
"fastapi>=0.115.0,<0.133.1",
|
||||
|
||||
@@ -4,7 +4,7 @@ description = "Durable Task integration for Microsoft Agent Framework."
|
||||
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
version = "1.0.0b260421"
|
||||
version = "1.0.0b260409"
|
||||
license-files = ["LICENSE"]
|
||||
urls.homepage = "https://aka.ms/agent-framework"
|
||||
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
||||
@@ -22,7 +22,7 @@ classifiers = [
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"agent-framework-core>=1.1.0,<2",
|
||||
"agent-framework-core>=1.0.1,<2",
|
||||
"durabletask>=1.3.0,<2",
|
||||
"durabletask-azuremanaged>=1.3.0,<2",
|
||||
"python-dateutil>=2.8.0,<3",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user