How to Configure Authentication with Azure AI Foundry and FoundryChatClient in Agent Framework
To configure authentication with Azure AI Foundry in the Agent Framework, instantiate FoundryChatClient with an Azure credential such as AzureCliCredential or DefaultAzureCredential, either explicitly or via environment variables.
The FoundryChatClient in the microsoft/agent-framework repository serves as the primary entry point for connecting agent-based applications to Azure AI Foundry's OpenAI-compatible chat API. When initializing the client, you must provide an Azure credential that implements azure.core.credentials.TokenCredential or azure.core.credentials_async.AsyncTokenCredential, which the underlying AIProjectClient uses to acquire access tokens for the Foundry service.
Authentication Architecture and Configuration Resolution
The FoundryChatClient resolves connection parameters through a specific priority chain defined in python/packages/foundry/agent_framework_foundry/_chat_client.py. Understanding this resolution order ensures you configure authentication correctly without redundant parameters.
Configuration Resolution Order
The client evaluates parameters in the following sequence:
project_endpoint: First checks the constructor argument, then falls back to theFOUNDRY_PROJECT_ENDPOINTenvironment variable (lines 63-66)model: First checks the constructor argument, then falls back to theFOUNDRY_MODELenvironment variable (lines 67-69)credential: Required when providingproject_endpointdirectly without an existingAIProjectClient(lines 90-94)
If you supply only project_endpoint and credential, the client internally constructs an AIProjectClient:
project_client = AIProjectClient(
endpoint=project_endpoint,
credential=credential,
user_agent=AGENT_FRAMEWORK_USER_AGENT,
allow_preview=allow_preview,
)
Critical validation: The source code at lines 91-93 raises a ValueError if you omit the credential parameter when the client needs to create an internal AIProjectClient. However, if you pass a pre-configured project_client instance, the credential argument becomes optional because authentication is already embedded in that client.
Setting Up Environment Variables
Before instantiating the client, export the required environment variables to enable automatic configuration resolution:
export FOUNDRY_PROJECT_ENDPOINT="https://my-project.services.ai.azure.com/api/projects/my-project"
export FOUNDRY_MODEL="gpt-4o"
These variables allow the client to resolve the endpoint and model without explicit constructor arguments, simplifying CI/CD pipelines and containerized deployments.
Authentication Patterns
Explicit Authentication with AzureCliCredential
For local development and samples, use AzureCliCredential to authenticate via the Azure CLI (az login). This approach makes the authentication flow explicit and aligns with the sample guidelines documented in python/samples/SAMPLE_GUIDELINES.md.
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
client = FoundryChatClient(
project_endpoint="https://my-project.services.ai.azure.com/api/projects/my-project",
model="gpt-4o",
credential=AzureCliCredential(),
)
agent = client.as_agent(name="travel-planner", instructions="Help plan trips.")
response = await agent.run("What are the top attractions in Kyoto?")
print(response)
This pattern satisfies the credential requirement at lines 90-94 of _chat_client.py by providing a concrete TokenCredential implementation that obtains access tokens from your local Azure CLI session.
Production Authentication with DefaultAzureCredential
For production environments, Azure-hosted agents, or scenarios requiring automatic credential discovery, use DefaultAzureCredential. This credential probes a chain of identity sources including managed identities, environment variables, Azure CLI, and IDE integrations.
import os
from agent_framework.foundry import FoundryChatClient
from azure.identity import DefaultAzureCredential
client = FoundryChatClient(
credential=DefaultAzureCredential()
)
agent = client.as_agent(name="budget-assistant", instructions="Assist with budgeting tasks.")
print(await agent.run("Create a monthly budget for $3000."))
Assuming you have set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL environment variables, the client resolves these automatically while DefaultAzureCredential handles token acquisition through the most appropriate mechanism available in the execution environment.
Advanced: Reusing an Existing AIProjectClient
When your application requires custom HTTP headers, specific preview flags, or shared connection pooling, instantiate AIProjectClient separately and pass it to FoundryChatClient via the project_client parameter. In this pattern, you do not need to pass the credential parameter again.
from azure.ai.projects.aio import AIProjectClient
from azure.identity import DefaultAzureCredential
from agent_framework.foundry import FoundryChatClient
import os
project_client = AIProjectClient(
endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
credential=DefaultAzureCredential(),
user_agent="my-custom-agent",
allow_preview=True,
)
client = FoundryChatClient(
project_client=project_client,
model=os.getenv("FOUNDRY_MODEL"),
)
agent = client.as_agent(name="research-bot", instructions="Answer research questions.")
print(await agent.run("Summarize the latest research on quantum error correction."))
This approach leverages the existing authenticated client while allowing fine-grained control over the underlying HTTP configuration and preview feature enablement.
Error Handling and Validation
The FoundryChatClient constructor performs strict validation to prevent runtime authentication failures. As implemented in python/packages/foundry/agent_framework_foundry/_chat_client.py at lines 91-93, the client raises a ValueError if:
- You provide a
project_endpointwithout a correspondingcredential, and - You do not provide an existing
project_client
Always ensure you provide either both project_endpoint and credential, or a fully configured project_client to avoid initialization errors.
Summary
- Credential Requirement: The
FoundryChatClientrequires an AzureTokenCredentialimplementation (such asAzureCliCredentialorDefaultAzureCredential) when creating an internalAIProjectClient. - Configuration Priority: Constructor arguments override environment variables;
FOUNDRY_PROJECT_ENDPOINTandFOUNDRY_MODELprovide fallback values when arguments are omitted. - Client Reuse: Passing a pre-configured
AIProjectClientvia theproject_clientparameter eliminates the need to pass credentials separately toFoundryChatClient. - Validation: The source code explicitly validates credential presence at lines 90-94 of
_chat_client.py, raisingValueErrorfor invalid combinations of parameters. - Flexibility: Support for both explicit string arguments and environment variables enables seamless transitions from local development to production deployments.
Frequently Asked Questions
What happens if I forget to provide a credential to FoundryChatClient?
If you provide a project_endpoint argument without a credential and without an existing project_client, the constructor raises a ValueError immediately. According to the implementation in _chat_client.py (lines 91-93), this validation prevents the creation of an unauthenticated AIProjectClient that would fail at runtime when attempting to fetch tokens.
Can I use environment variables instead of passing arguments to the constructor?
Yes. The FoundryChatClient automatically resolves project_endpoint from the FOUNDRY_PROJECT_ENDPOINT environment variable and model from FOUNDRY_MODEL (lines 63-69 in _chat_client.py). You only need to provide the credential parameter explicitly unless you are also passing a pre-configured project_client.
Is AzureCliCredential or DefaultAzureCredential better for production?
DefaultAzureCredential is recommended for production and Azure-hosted environments because it automatically discovers managed identities, environment variables, and other token sources without code changes. AzureCliCredential is preferred for local development and samples because it makes the authentication flow explicit and aligns with the sample guidelines in python/samples/SAMPLE_GUIDELINES.md.
How do I enable preview features when using FoundryChatClient?
When you need preview features or custom headers, do not rely on the internal AIProjectClient creation. Instead, instantiate AIProjectClient manually with allow_preview=True and pass it to FoundryChatClient via the project_client parameter. This bypasses the standard credential validation while giving you full control over the connection configuration.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →