Skip to content

Instantly share code, notes, and snippets.

@cedricvidal
Last active May 28, 2025 20:40
Show Gist options
  • Save cedricvidal/511b0c53a17f1a9b2c8d76f473158dc1 to your computer and use it in GitHub Desktop.
Save cedricvidal/511b0c53a17f1a9b2c8d76f473158dc1 to your computer and use it in GitHub Desktop.
OpenAI Agents SDK with Azure AI Foundry and Keyless authentication
# uv add asyncio azure-identity dotenv-azd openai-agents
from openai import AsyncAzureOpenAI
from agents import Agent, Runner, set_default_openai_client, set_tracing_export_api_key
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from dotenv import load_dotenv
from dotenv_azd import load_azd_env
import asyncio
import os
# Load environment variables
load_dotenv()
load_azd_env(quiet=True)
async def main():
# Keyless connection to Azure OpenAI
# https://learn.microsoft.com/en-us/azure/developer/ai/keyless-connections?tabs=python%2Cazure-cli
token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")
# Create OpenAI client using Azure OpenAI
# https://techcommunity.microsoft.com/blog/azure-ai-services-blog/use-azure-openai-and-apim-with-the-openai-agents-sdk/4392537
openai_client = AsyncAzureOpenAI(
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT"),
azure_ad_token_provider=token_provider
)
# Set the default OpenAI client for the Agents SDK
set_default_openai_client(openai_client)
set_tracing_export_api_key(os.getenv("OPENAI_API_KEY"))
agent = Agent(
name="Assistant",
instructions="You only respond in haikus.",
)
result = await Runner.run(agent, "Tell me about recursion in programming.")
print(result.final_output)
# Function calls itself,
# Looping in smaller pieces,
# Endless by design.
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment