Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build and deploy AI applications on Azure AI Foundry using Microsoft's model catalog and AI services
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/sdk/foundry-sdk-py.md
1# Microsoft Foundry - Python SDK Guide23Python-specific implementations for working with Microsoft Foundry.45**Table of Contents:** [Prerequisites](#prerequisites) · [Model Discovery and Deployment](#model-discovery-and-deployment-mcp) · [RAG Agent with Azure AI Search](#rag-agent-with-azure-ai-search) · [Creating Agents](#creating-agents) · [Agent Evaluation](#agent-evaluation) · [Knowledge Index Operations](#knowledge-index-operations-mcp) · [Best Practices](#best-practices) · [Error Handling](#error-handling)67## Prerequisites89```bash10pip install azure-ai-projects azure-identity azure-ai-inference openai azure-ai-evaluation python-dotenv11```1213### Environment Variables1415```bash16PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>17MODEL_DEPLOYMENT_NAME=gpt-4o18AZURE_AI_SEARCH_CONNECTION_NAME=my-search-connection19AI_SEARCH_INDEX_NAME=my-index20AZURE_OPENAI_ENDPOINT=https://<resource>.openai.azure.com21AZURE_OPENAI_DEPLOYMENT=gpt-4o22```2324## Model Discovery and Deployment (MCP)2526```python27foundry_models_list() # All models28foundry_models_list(publisher="OpenAI") # Filter by publisher29foundry_models_list(search_for_free_playground=True) # Free playground models3031foundry_models_deploy(32resource_group="my-rg", deployment="gpt-4o-deployment",33model_name="gpt-4o", model_format="OpenAI",34azure_ai_services="my-foundry-resource",35model_version="2024-05-13", sku_capacity=10, scale_type="Standard"36)37```3839## RAG Agent with Azure AI Search4041> **Auth:** `DefaultAzureCredential` is for local development. See [auth-best-practices.md](../auth-best-practices.md) for production patterns.4243```python44import os45from azure.ai.projects import AIProjectClient46from azure.identity import DefaultAzureCredential47from azure.ai.agents.models import (48AzureAISearchToolDefinition, AzureAISearchToolResource,49AISearchIndexResource, AzureAISearchQueryType,50)5152project_client = AIProjectClient(53endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],54credential=DefaultAzureCredential(),55)5657azs_connection = project_client.connections.get(58os.environ["AZURE_AI_SEARCH_CONNECTION_NAME"]59)6061agent = project_client.agents.create_agent(62model=os.environ["FOUNDRY_MODEL_DEPLOYMENT_NAME"],63name="RAGAgent",64instructions="You are a helpful assistant. Use the knowledge base to answer. "65"Provide citations as: `[message_idx:search_idx†source]`.",66tools=[AzureAISearchToolDefinition(67azure_ai_search=AzureAISearchToolResource(indexes=[68AISearchIndexResource(69index_connection_id=azs_connection.id,70index_name=os.environ["AI_SEARCH_INDEX_NAME"],71query_type=AzureAISearchQueryType.HYBRID,72),73])74)],75)76```7778### Querying a RAG Agent (Streaming)7980```python81openai_client = project_client.get_openai_client()8283stream = openai_client.responses.create(84stream=True, tool_choice="required", input="Your question here",85extra_body={"agent": {"name": agent.name, "type": "agent_reference"}},86)87for event in stream:88if event.type == "response.output_text.delta":89print(event.delta, end="", flush=True)90elif event.type == "response.output_item.done":91if event.item.type == "message" and event.item.content[-1].type == "output_text":92for ann in event.item.content[-1].annotations:93if ann.type == "url_citation":94print(f"\nCitation: {ann.url}")95```9697## Creating Agents9899### Basic Agent100101```python102agent = project_client.agents.create_agent(103model=os.environ["MODEL_DEPLOYMENT_NAME"],104name="my-agent",105instructions="You are a helpful assistant.",106)107```108109### Agent with Custom Function Tools110111```python112from azure.ai.agents.models import FunctionTool, ToolSet113114def get_weather(location: str, unit: str = "celsius") -> str:115"""Get the current weather for a location."""116return f"Sunny and 22°{unit[0].upper()} in {location}"117118functions = FunctionTool([get_weather])119toolset = ToolSet()120toolset.add(functions)121122agent = project_client.agents.create_agent(123model=os.environ["MODEL_DEPLOYMENT_NAME"],124name="function-agent",125instructions="You are a helpful assistant with tool access.",126toolset=toolset,127)128```129130### Agent with Web Search131132```python133from azure.ai.projects.models import (134PromptAgentDefinition, WebSearchPreviewTool, ApproximateLocation,135)136137agent = project_client.agents.create_version(138agent_name="WebSearchAgent",139definition=PromptAgentDefinition(140model=os.environ["MODEL_DEPLOYMENT_NAME"],141instructions="Search the web for current information. Provide sources.",142tools=[143WebSearchPreviewTool(144user_location=ApproximateLocation(145country="US", city="Seattle", region="Washington"146)147)148],149),150)151```152153> 💡 **Tip:** `WebSearchPreviewTool` requires no external resource or connection. For Bing Grounding (which requires a dedicated Bing resource and project connection), see [Bing Grounding reference](../../foundry-agent/create/references/tool-bing-grounding.md).154155### Interacting with Agents156157```python158from azure.ai.agents.models import ListSortOrder159160thread = project_client.agents.threads.create()161project_client.agents.messages.create(thread_id=thread.id, role="user", content="Hello")162163run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)164if run.status == "failed":165print(f"Run failed: {run.last_error}")166167messages = project_client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)168for msg in messages:169if msg.text_messages:170print(f"{msg.role}: {msg.text_messages[-1].text.value}")171172project_client.agents.delete_agent(agent.id)173```174175## Agent Evaluation176177### Single Response Evaluation (MCP)178179```python180foundry_agents_query_and_evaluate(181agent_id="<agent-id>", query="What's the weather?",182endpoint="https://my-foundry.services.ai.azure.com/api/projects/my-project",183azure_openai_endpoint="https://my-openai.openai.azure.com",184azure_openai_deployment="gpt-4o",185evaluators="intent_resolution,task_adherence,tool_call_accuracy"186)187188foundry_agents_evaluate(189query="What's the weather?", response="Sunny and 22°C.",190evaluator="intent_resolution",191azure_openai_endpoint="https://my-openai.openai.azure.com",192azure_openai_deployment="gpt-4o"193)194```195196### Batch Evaluation197198```python199from azure.ai.evaluation import AIAgentConverter, IntentResolutionEvaluator, evaluate200201converter = AIAgentConverter(project_client)202converter.prepare_evaluation_data(thread_ids=["t1", "t2", "t3"], filename="eval_data.jsonl")203204result = evaluate(205data="eval_data.jsonl",206evaluators={207"intent_resolution": IntentResolutionEvaluator(208azure_openai_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],209azure_openai_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT"]210),211},212output_path="./eval_results"213)214print(f"Results: {result['studio_url']}")215```216217> 💡 **Tip:** Continuous evaluation requires project managed identity with **Azure AI User** role and Application Insights connected to the project.218219## Knowledge Index Operations (MCP)220221```python222foundry_knowledge_index_list(endpoint="<project-endpoint>")223foundry_knowledge_index_schema(endpoint="<project-endpoint>", index="my-index")224```225226## Best Practices2272281. **Never hardcode credentials** — use environment variables and `python-dotenv`2292. **Check `run.status`** and handle `HttpResponseError` exceptions2303. **Reuse `AIProjectClient`** instances — don't create new ones per request2314. **Use type hints** in custom functions for better tool integration2325. **Use context managers** for agent cleanup233234## Error Handling235236```python237from azure.core.exceptions import HttpResponseError238239try:240agent = project_client.agents.create_agent(241model=os.environ["MODEL_DEPLOYMENT_NAME"],242name="my-agent", instructions="You are helpful."243)244except HttpResponseError as e:245if e.status_code == 429:246print("Rate limited — wait and retry with exponential backoff.")247elif e.status_code == 401:248print("Authentication failed — check credentials.")249else:250print(f"Error: {e.message}")251```252253### Context Manager for Agent Cleanup254255```python256from contextlib import contextmanager257258@contextmanager259def temporary_agent(project_client, **kwargs):260agent = project_client.agents.create_agent(**kwargs)261try:262yield agent263finally:264project_client.agents.delete_agent(agent.id)265```266