Muokkaa

Microsoft Foundry Agent Service

FoundryAgent connects Agent Framework to an agent definition managed by Microsoft Foundry Agent Service. The agent's model, instructions, hosted tools, and version are configured in Foundry; your application connects to that definition and uses the standard Agent Framework run, streaming, and session APIs.

Use this integration for:

  • Prompt Agents, which are named and versioned server-side agent definitions.
  • Hosted Agents, which are deployed agent applications reached through an agent-specific endpoint.

For direct model inference where your application owns the agent definition, see Microsoft Foundry model provider. To deploy an Agent Framework application as a Hosted Agent, see Foundry Hosted Agents.

Install the packages

dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.Foundry --prerelease

Connect to a Prompt Agent

Create an AIProjectClient for the Foundry project and wrap an AgentReference as a FoundryAgent. Pin the version when the application must use a specific Prompt Agent definition.

using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using Microsoft.Agents.AI.Foundry;

var projectClient = new AIProjectClient(
    new Uri(Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")!),
    new DefaultAzureCredential());

FoundryAgent agent = projectClient.AsAIAgent(
    new AgentReference(
        Environment.GetEnvironmentVariable("FOUNDRY_AGENT_NAME")!,
        Environment.GetEnvironmentVariable("FOUNDRY_AGENT_VERSION")!));

Console.WriteLine(await agent.RunAsync("What can you help me with?"));

You can also retrieve a ProjectsAgentRecord to use its latest version or a ProjectsAgentVersion to use an explicitly retrieved version, then pass that object to projectClient.AsAIAgent(...).

Retrieve the latest Prompt Agent version

Use AgentAdministrationClient when the application should resolve the latest registered version by name.

ProjectsAgentRecord agentRecord =
    await projectClient.AgentAdministrationClient.GetAgentAsync(
        Environment.GetEnvironmentVariable("FOUNDRY_AGENT_NAME")!);

FoundryAgent latestAgent = projectClient.AsAIAgent(agentRecord);
Console.WriteLine(await latestAgent.RunAsync("What can you help me with?"));

Important

A FoundryAgent uses the model, instructions, and hosted tools stored in its Foundry definition. Configure those capabilities in Foundry; the client can't replace them at run time.

Warning

DefaultAzureCredential is convenient for development. In production, prefer a specific credential such as ManagedIdentityCredential to avoid unintended credential probing.

Connect to a Hosted Agent

Hosted Agents expose an agent-specific OpenAI endpoint. Build the endpoint from the project endpoint and registered agent name, then pass it to AIProjectClient.AsAIAgent(...).

Env.TraversePath().Load();

// Port the Hosted-* samples listen on when run locally with `dotnet run`.
const int LocalAgentPort = 8088;

// AZURE_AI_AGENT_NAME is the registered server-side agent name.
string agentName = Environment.GetEnvironmentVariable("AZURE_AI_AGENT_NAME")
    ?? throw new InvalidOperationException("AZURE_AI_AGENT_NAME is not set.");

// Pick the server to talk to. `--local` and `--remote` mirror the flag `azd ai agent invoke`
// exposes; with neither, ask at startup.
    ══════════════════════════════════════════════════════════
    """);
Console.ResetColor();
Console.WriteLine();

The endpoint's administrator-controlled version selector determines the active Hosted Agent version.

Install the packages

pip install agent-framework-foundry

Configuration

FOUNDRY_PROJECT_ENDPOINT="https://<your-project>.services.ai.azure.com"
FOUNDRY_AGENT_NAME="my-agent"
FOUNDRY_AGENT_VERSION="1.0"

Use FOUNDRY_AGENT_VERSION for Prompt Agents. Hosted Agents can omit it.

Connect to a Prompt Agent

Provide the project endpoint, agent name, and agent version. The service supplies the stored model, instructions, and hosted-tool configuration.

async def main() -> None:
    agent = FoundryAgent(
        project_endpoint="https://your-project.services.ai.azure.com",
        agent_name="my-prompt-agent",
        agent_version="1.0",
        credential=AzureCliCredential(),
    )

    result = await agent.run("What is the capital of France?")
    print(f"Agent: {result}")

    # Streaming
    print("Agent (streaming): ", end="", flush=True)
    async for chunk in agent.run("Tell me a fun fact.", stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

If a Prompt Agent declares a local function tool, pass the matching callable through tools= when constructing FoundryAgent so the client can execute it when requested. See the Prompt Agent publish and connect sample.

Connect to a Hosted Agent

Hosted Agents don't require agent_version. Connect with the project endpoint and registered agent name.

async def main() -> None:
    # HostedAgents don't need agent_version
    agent = FoundryAgent(
        project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
        agent_name=os.getenv("FOUNDRY_AGENT_NAME"),
        credential=AzureCliCredential(),
    )

    result = await agent.run("Summarize the latest news about AI.")
    print(f"Agent: {result}")

What works and what doesn't with FoundryAgent

FoundryAgent connects to an agent definition that already exists in Foundry. The stored instructions and tool configuration are authoritative, so client-side behavior differs from an application-owned Agent(client=FoundryChatClient(...)).

Tools

Tool type passed to FoundryAgent(...) Behavior
FunctionTool with a local Python callable Supported only when the matching function definition already exists on the Foundry agent. The callable runs in the application process when Foundry requests it.
Hosted tools, including web search, code interpreter, file search, MCP, image generation, and Microsoft Foundry Toolbox Configure these on the Foundry agent definition. Passing them client-side doesn't add them to the service-managed agent.

For Toolbox attachment and direct MCP consumption guidance, see Microsoft Foundry Toolbox.

You can't register a new model-visible tool at construction time. Passing a function callable only supplies the local implementation for a function that the Foundry agent already declares.

Context providers

Context provider behavior Works with FoundryAgent?
Adds messages, such as retrieved memory, RAG snippets, or user profile information Yes. The injected context is forwarded with the request.
Persists or observes the conversation Yes. The provider runs locally around the request and response.
Adds tools dynamically No, unless those tools are already declared on the Foundry agent definition.

Use Agent(client=FoundryChatClient(...)) when the application needs dynamic tool selection, skill loading, or any behavior that changes model-visible tools at run time.

Run options

Because the Foundry agent definition is the source of truth, not every option passed through default_options or agent.run(...) is honored.

Option Prompt Agent behavior
model Ignored. The model comes from the Foundry agent definition.
tools, tool_choice, parallel_tool_calls Removed from the request. Tools must be declared on the Foundry agent definition.
instructions and system or developer messages Ignored. The stored Foundry instructions are authoritative.
conversation_id Used and mapped to the Foundry agent session when applicable.
extra_body Forwarded and merged with the framework-provided agent reference.
Sampling parameters, metadata, user, store, and response_format Forwarded, but the Foundry agent or model configuration can override or constrain them.

Hosted Agents receive the same client-side filtering, but the deployed agent can accept, ignore, or reinterpret any forwarded option. Verify behavior against the specific Hosted Agent.

Tip

Use Agent(client=FoundryChatClient(...)) when you need per-run control over instructions, generation options, or tools.

Manage a Hosted Agent service session

Hosted Agents that use service-side sessions require the preview Responses surface:

Create the service session explicitly when the application must bind it to a tenant or user, then wrap its identifier as an Agent Framework session.

    *,
    agent: FoundryAgent,
    project_client: AIProjectClient,
    agent_name: str,
    agent_version: str | None,
) -> AgentSession:
    """Create a hosted-agent service session and wrap it in an AgentSession."""
    resolved_agent_version = agent_version
    if resolved_agent_version is None:
        agent_details = await project_client.agents.get(agent_name)
        resolved_agent_version = agent_details.versions.latest.version

    service_session = await project_client.agents.create_session(
        agent_name,
        version_indicator=VersionRefIndicator(agent_version=resolved_agent_version),
    )
    return agent.get_session(service_session.agent_session_id)


async def delete_hosted_agent_session(
    *,
    project_client: AIProjectClient,
    agent_name: str,
    session: AgentSession,
) -> None:
    """Delete a hosted-agent service session."""
    await project_client.agents.delete_session(
        agent_name,
        cast(str, session.service_session_id),
    )


async def main() -> None:
    credential = AzureCliCredential()
    project_endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
    agent_name = os.environ["FOUNDRY_AGENT_NAME"]
    agent_version = os.getenv("FOUNDRY_AGENT_VERSION")

    project_client = AIProjectClient(
        endpoint=project_endpoint,
        credential=credential,
        allow_preview=True,
    )
    async with (
        project_client,
        FoundryAgent(
            project_client=project_client,
            agent_name=agent_name,
            agent_version=agent_version,
            allow_preview=True,
        ) as agent,
    ):
        session = await create_hosted_agent_session(
            agent=agent,
            project_client=project_client,
            agent_name=agent_name,
            agent_version=agent_version,
        )

        try:
            # 1. Send the first turn.
            query = "Hi!"
            print(f"User: {query}")
            print("Agent: ", end="", flush=True)
            async for chunk in agent.run(query, session=session, stream=True):
                if chunk.text:
                    print(chunk.text, end="", flush=True)

            # 2. Continue the conversation with the same deployed agent session.
            query = "Your name is Javis. What can you do?"

Tip

See the using_deployed_agent.py sample for a complete example.

Set a custom HTTP timeout

FoundryAgent inherits the OpenAI SDK timeout by default. Pass timeout= in seconds when multi-turn conversations or network conditions require a different limit.

from agent_framework.foundry import FoundryAgent
from azure.identity import AzureCliCredential

agent = FoundryAgent(
    project_endpoint="https://your-project.services.ai.azure.com",
    agent_name="my-prompt-agent",
    credential=AzureCliCredential(),
    timeout=120.0,
)

The timeout is applied to a per-agent copy of the HTTP client and doesn't affect other agents that share the same AIProjectClient.

Note

FoundryAgent integration for Prompt and Hosted Agents isn't currently available for Agent Framework Go. See the Agent Framework Go repository for the latest status.

Run, stream, and continue conversations

After connecting, use the same APIs as other Agent Framework agents:

  • Run a request with RunAsync or run.
  • Stream updates with RunStreamingAsync or run(..., stream=True).
  • Reuse an AgentSession to continue a conversation.
  • Use Foundry server-side conversation APIs when the conversation must be visible and persisted in the Foundry project.

Keep Foundry agent names, versions, endpoints, and conversation identifiers in trusted server-side state. Authorize the caller before resuming any existing conversation.

Next steps