|
| 1 | +# ------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. |
| 3 | +# Licensed under the MIT License. |
| 4 | +# ------------------------------------ |
| 5 | + |
| 6 | +""" |
| 7 | +DESCRIPTION: |
| 8 | + This sample demonstrates how to run a basic responses operation |
| 9 | + using the synchronous AIProject and OpenAI clients, while defining |
| 10 | + a desired JSON schema for the response ("structured output"). |
| 11 | +
|
| 12 | + This sample is inspired by the OpenAI example here: |
| 13 | + https://platform.openai.com/docs/guides/structured-outputs/supported-schemas |
| 14 | +
|
| 15 | +USAGE: |
| 16 | + python sample_responses_structured_output.py |
| 17 | +
|
| 18 | + Before running the sample: |
| 19 | +
|
| 20 | + pip install "azure-ai-projects>=2.0.0b1" openai azure-identity python-dotenv |
| 21 | +
|
| 22 | + Set these environment variables with your own values: |
| 23 | + 1) AZURE_AI_PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview |
| 24 | + page of your Azure AI Foundry portal. |
| 25 | + 2) AZURE_AI_MODEL_DEPLOYMENT_NAME - The deployment name of the AI model, as found under the "Name" column in |
| 26 | + the "Models + endpoints" tab in your Azure AI Foundry project. |
| 27 | +""" |
| 28 | + |
| 29 | +import os |
| 30 | +from dotenv import load_dotenv |
| 31 | +from azure.identity import DefaultAzureCredential |
| 32 | +from azure.ai.projects import AIProjectClient |
| 33 | +from pydantic import BaseModel, Field |
| 34 | + |
| 35 | +load_dotenv() |
| 36 | + |
| 37 | + |
| 38 | +class CalendarEvent(BaseModel): |
| 39 | + model_config = {"extra": "forbid"} |
| 40 | + name: str |
| 41 | + date: str = Field(description="Date in YYYY-MM-DD format") |
| 42 | + participants: list[str] |
| 43 | + |
| 44 | + |
| 45 | +project_client = AIProjectClient( |
| 46 | + endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], |
| 47 | + credential=DefaultAzureCredential(), |
| 48 | +) |
| 49 | + |
| 50 | +with project_client: |
| 51 | + |
| 52 | + openai_client = project_client.get_openai_client() |
| 53 | + |
| 54 | + response = openai_client.responses.create( |
| 55 | + model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], |
| 56 | + instructions=""" |
| 57 | + Extracts calendar event information from the input messages, |
| 58 | + and return it in the desired structured output format. |
| 59 | + """, |
| 60 | + text={ |
| 61 | + "format": { |
| 62 | + "type": "json_schema", |
| 63 | + "name": "CalendarEvent", |
| 64 | + "schema": CalendarEvent.model_json_schema(), |
| 65 | + } |
| 66 | + }, |
| 67 | + input="Alice and Bob are going to a science fair this Friday, November 7, 2025.", |
| 68 | + ) |
| 69 | + print(f"Response output: {response.output_text}") |
0 commit comments