* refactor(foundry_hosting): build FoundryHostedAgentHistoryProvider on azure.ai.agentserver SDK
Rebuilds the Foundry hosted-agent history provider on top of
``azure.ai.agentserver``'s ``FoundryStorageProvider`` instead of the
in-house ``_HttpStorageBackend``. Splits the monolithic ``_responses.py``
into focused modules:
- ``_history_provider.py`` — new ``FoundryHostedAgentHistoryProvider``
that talks to the SDK's ``FoundryStorageProvider``, threads
``response_id`` / ``previous_response_id`` through ``ContextVar``s via
``bind_request_context``, and lifts host-bound isolation keys
(``x-agent-{user,chat}-isolation-key``) from the optional
``agent_framework_hosting`` package into a provider-local
``IsolationContext`` so the storage layer carries the correct
partition keys without channels having to know about them.
- ``_shared.py`` — extracts all SDK ``Item`` / ``OutputItem`` ↔
framework ``Message`` conversion helpers into one place so both
``_responses.py`` and the new history provider can share them.
Restores ``_convert_file_data`` for inline ``input_file`` payloads,
and the hosted-MCP routing for ``custom_tool_call_output`` items
whose ``call_id`` carries the ``mcp_*`` prefix.
- ``_ids.py`` — shared id helpers.
- ``_responses.py`` — shrinks ~700 lines, re-exports converters for
back-compat with existing tests.
- ``tests/test_history_provider.py`` — exercises the new provider
against a fake SDK backend; the host-isolation test is gated on the
optional ``agent_framework_hosting`` import.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* feat(foundry_hosting): add local_storage_root for file-based dev history
Adds an optional `local_storage_root: str | Path | None` parameter to
`FoundryHostedAgentHistoryProvider`. When set and the provider is
running outside a Foundry Hosted Agent container, conversations are
persisted to JSONL files via `agent_framework.FileHistoryProvider`
laid out as:
{root}/{user_key or '~none'}/{chat_key or '~none'}/{session_id}.jsonl
Hosted mode (FOUNDRY_HOSTING_ENVIRONMENT set) ignores the option with a
one-time INFO log so Foundry storage always wins on the platform. The
in-memory fallback is unchanged when the option is omitted.
Path safety: isolation segments are validated against the same character
allowlist FileHistoryProvider uses for session-id stems and
base64-url-encoded with a reserved "~iso-" prefix when unsafe. "~none"
sentinel for missing keys can never collide with a real isolation key
(real keys starting with "~" are encoded). The resolved target dir is
also re-checked to be inside the configured root.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix(foundry_hosting): address PR-1 review comments
- _shared.py:_capture_raw narrows `except Exception` to `except TypeError`
and emits a WARNING with traceback so the lossy fallback to a
synthesized round-trip is observable. Mirrors the reviewer suggestion.
- _history_provider.py:save_messages narrows `except Exception` to
`except FoundryStorageError` so only storage-validation failures
(4xx/5xx, opaque server errors) are swallowed. Network / TLS / auth
/ payload-builder bugs propagate so the caller can retry / alert.
Adds an instance-level `failed_writes` counter operators can poll
for silent-drop visibility.
- _history_provider.py id-stamping loop: drops the
`contextlib.suppress(AttributeError, TypeError)` around
`item.id = new_id` so SDK contract changes surface in the test
suite instead of silently corrupting the chain (the storage backend
rejects the entire `create_response` with HTTP 500 when synthetic
prefix-based ids leak through). `import contextlib` removed.
- tests:
* Unit-cover `foundry_response_id` / `foundry_response_id_factory` /
`foundry_item_id` so SDK `IdGenerator` contract changes are caught
locally.
* Cover the `save_messages` wire payload: required-by-storage fields
(`background`, `parallel_tool_calls`, `instructions`,
`agent_reference`), env-var-driven stamping (`FOUNDRY_AGENT_NAME` /
`FOUNDRY_AGENT_VERSION` / `FOUNDRY_AGENT_SESSION_ID` /
`MODEL_DEPLOYMENT_NAME` with `AZURE_AI_MODEL_DEPLOYMENT_NAME`
fallback), and the rule that `model` / `agent_session_id` /
`agent_reference.version` are omitted (not stamped to `None`) when
their env vars are unset.
* Cover the `FOUNDRY_AGENT_SESSION_ID` last-resort chain anchor on
both the get and save paths, including the prefix gate that blocks
non-`caresp_*`/`resp_*` values from reaching storage, and the
precedence rule that a host binding wins over the env.
* Replace the old `test_save_messages_swallows_backend_errors` with
two tests asserting the new contract: storage errors are swallowed
and bump `failed_writes`; everything else propagates and leaves the
counter at zero.
141 unit tests pass; mypy + pyright + ruff clean.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* fix(foundry_hosting): address PR-1 round-2 review comments
- Hosted detection now delegates to AgentConfig.from_env().is_hosted so
a future Foundry SDK rename of FOUNDRY_HOSTING_ENVIRONMENT propagates
automatically; drop the local _ENV_FOUNDRY_HOSTING_ENVIRONMENT
constant.
- Drop the FOUNDRY_AGENT_SESSION_ID fallback in both get_messages and
save_messages: per the SDK it identifies the *container instance*,
not the conversation, so chaining off it would silently merge
unrelated conversations across container restarts. The host-bound
previous_response_id (set by ResponsesChannel) is the only
authoritative anchor; the env value is still stamped into the
persisted envelope's agent_session_id for operator correlation.
- Update module docstring + replace TestFoundryAgentSessionIdAnchor
with assertions for the new contract (env var ignored as anchor,
still stamped onto persisted envelope, host binding wins).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* refactor(foundry_hosting): reconcile with upstream main (#5851, #5666)
Brings the FoundryHostedAgentHistoryProvider refactor branch back into
sync with the foundry_hosting changes that have landed on upstream
main since PR-1 was opened:
* #5851 (path traversal in checkpoint storage, CWE-22).
The workflow-host code in ``_responses.py`` builds a
``FileCheckpointStorage`` from a caller-controlled ``context_id``
(``previous_response_id`` / ``conversation_id`` / ``response_id``).
Switch both call sites to route through
``_checkpoint_storage_for_context``, which rejects separators,
NUL bytes, drive letters, absolute paths, and all-dot segments,
and enforces ``is_relative_to(root)`` before any directory is
created.
* #5666 (function approval flow).
Make the SDK-Item → AF-Message conversion helpers in ``_shared.py``
async and accept an optional ``approval_storage`` keyword:
- ``_items_to_messages`` / ``_item_to_message`` /
``_item_to_message_inner``
- ``_output_items_to_messages`` / ``_output_item_to_message`` /
``_output_item_to_message_inner``
For ``mcp_approval_request`` / ``mcp_approval_response`` items the
helpers now load the original function-call Content from the
approval storage (via ``ApprovalStorage.load_approval_request``)
instead of synthesising a placeholder. This matches upstream
semantics and lets approval round-trips reconstruct the real
payload.
The ``ApprovalStorage`` Protocol moves to ``_shared.py`` so the
conversion helpers can reference it without pulling in
``_responses.py`` (which would create a circular import). The
concrete ``InMemoryFunctionApprovalStorage`` and
``FileBasedFunctionApprovalStorage`` stay in ``_responses.py``
next to the host that owns them, and re-export
``ApprovalStorage`` from ``_shared`` for compatibility.
The workflow-host streaming path passes its own
``self._approval_storage`` into ``_to_outputs`` so approval
requests are saved at emit time.
* Bump ``_history_provider.FoundryHostedAgentHistoryProvider.get_messages``
to ``await`` the now-async ``_output_items_to_messages`` call.
No public API change beyond the new keyword-only ``approval_storage``
parameter on the four conversion entry points.
Validation:
- uv run poe check-packages -P foundry_hosting (lint + pyright clean)
- uv run poe mypy -P foundry_hosting (clean)
- uv run poe test -P foundry_hosting (183 passed, 1 skipped)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Get Started with Microsoft Agent Framework for Python Developers
Quick Install
We recommend two common installation paths depending on your use case.
1. Development mode
If you are exploring or developing locally, install the entire framework with all sub-packages:
pip install agent-framework
This installs the core and every integration package, making sure that all features are available without additional steps. This is the simplest way to get started.
2. Selective install
If you only need specific integrations, you can install at a more granular level. This keeps dependencies lighter and focuses on what you actually plan to use. Some examples:
# Core only
# includes Azure OpenAI and OpenAI support by default
# also includes workflows and orchestrations
pip install agent-framework-core
# Core + Azure AI Foundry integration
pip install agent-framework-foundry
# Core + Microsoft Copilot Studio integration (preview package)
pip install agent-framework-copilotstudio --pre
# Core + both Microsoft Copilot Studio and Azure AI Foundry integration
pip install --pre agent-framework-copilotstudio agent-framework-foundry
This selective approach is useful when you know which integrations you need, and it is the recommended way to set up lightweight environments. Released packages such as agent-framework, agent-framework-core, and agent-framework-foundry no longer require --pre, while preview connectors such as agent-framework-copilotstudio still do.
Supported Platforms:
- Python: 3.10+
- OS: Windows, macOS, Linux
1. Setup API Keys
Set as environment variables, or create a .env file at your project root:
OPENAI_API_KEY=sk-...
OPENAI_MODEL=...
...
AZURE_OPENAI_API_KEY=...
AZURE_OPENAI_ENDPOINT=...
AZURE_OPENAI_MODEL=...
...
FOUNDRY_PROJECT_ENDPOINT=...
FOUNDRY_MODEL=...
For the generic OpenAI clients (OpenAIChatClient and OpenAIChatCompletionClient), configuration
resolves in this order:
- Explicit Azure inputs such as
credentialorazure_endpoint OPENAI_API_KEY/ explicit OpenAI API-key parameters- Azure environment fallback such as
AZURE_OPENAI_ENDPOINTandAZURE_OPENAI_API_KEY
This means mixed shells default to OpenAI when OPENAI_API_KEY is present. To force Azure routing,
pass an explicit Azure input such as credential=AzureCliCredential().
You can also override environment variables by explicitly passing configuration parameters to the chat client constructor:
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient(
api_key='',
azure_endpoint='',
model='',
api_version='',
)
See the following setup guide for more information.
2. Create a Simple Agent
Create agents and invoke them directly:
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
agent = Agent(
client=OpenAIChatClient(),
instructions="""
1) A robot may not injure a human being...
2) A robot must obey orders given it by human beings...
3) A robot must protect its own existence...
Give me the TLDR in exactly 5 words.
"""
)
result = await agent.run("Summarize the Three Laws of Robotics")
print(result)
asyncio.run(main())
# Output: Protect humans, obey, self-preserve, prioritized.
3. Directly Use Chat Clients (No Agent Required)
You can use the chat client classes directly for advanced workflows:
import asyncio
from agent_framework import Message
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient()
messages = [
Message("system", ["You are a helpful assistant."]),
Message("user", ["Write a haiku about Agent Framework."])
]
response = await client.get_response(messages)
print(response.messages[0].text)
"""
Output:
Agents work in sync,
Framework threads through each task—
Code sparks collaboration.
"""
asyncio.run(main())
4. Build an Agent with Tools and Functions
Enhance your agent with custom tools and function calling:
import asyncio
from typing import Annotated
from random import randint
from pydantic import Field
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
def get_menu_specials() -> str:
"""Get today's menu specials."""
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
async def main():
agent = Agent(
client=OpenAIChatClient(),
instructions="You are a helpful assistant that can provide weather and restaurant information.",
tools=[get_weather, get_menu_specials]
)
response = await agent.run("What's the weather in Amsterdam and what are today's specials?")
print(response)
"""
Output:
The weather in Amsterdam is sunny with a high of 22°C. Today's specials include
Clam Chowder soup, Cobb Salad, and Chai Tea as the special drink.
"""
if __name__ == "__main__":
asyncio.run(main())
You can explore additional agent samples here.
5. Multi-Agent Orchestration
Coordinate multiple agents to collaborate on complex tasks using orchestration patterns:
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
# Create specialized agents
writer = Agent(
client=OpenAIChatClient(),
name="Writer",
instructions="You are a creative content writer. Generate and refine slogans based on feedback."
)
reviewer = Agent(
client=OpenAIChatClient(),
name="Reviewer",
instructions="You are a critical reviewer. Provide detailed feedback on proposed slogans."
)
# Sequential workflow: Writer creates, Reviewer provides feedback
task = "Create a slogan for a new electric SUV that is affordable and fun to drive."
# Step 1: Writer creates initial slogan
initial_result = await writer.run(task)
print(f"Writer: {initial_result}")
# Step 2: Reviewer provides feedback
feedback_request = f"Please review this slogan: {initial_result}"
feedback = await reviewer.run(feedback_request)
print(f"Reviewer: {feedback}")
# Step 3: Writer refines based on feedback
refinement_request = f"Please refine this slogan based on the feedback: {initial_result}\nFeedback: {feedback}"
final_result = await writer.run(refinement_request)
print(f"Final Slogan: {final_result}")
# Example Output:
# Writer: "Charge Forward: Affordable Adventure Awaits!"
# Reviewer: "Good energy, but 'Charge Forward' is overused in EV marketing..."
# Final Slogan: "Power Up Your Adventure: Premium Feel, Smart Price!"
if __name__ == "__main__":
asyncio.run(main())
For more advanced orchestration patterns including Sequential, Concurrent, Group Chat, Handoff, and Magentic orchestrations, see the orchestration samples.
More Examples & Samples
- Getting Started with Agents: Basic agent creation and tool usage
- Chat Client Examples: Direct chat client usage patterns
- Foundry Integration: Microsoft Foundry integration
- Workflow Samples: Advanced multi-agent patterns
Agent Framework Documentation
- Agent Framework Repository
- Python Package Documentation
- .NET Package Documentation
- Design Documents
- Learn docs are coming soon.