Skip to content

Commit 7ab3b50

Browse files
committed
add structured output example script
1 parent 27c20fe commit 7ab3b50

File tree

3 files changed

+188
-99
lines changed

3 files changed

+188
-99
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import argparse
2+
import logging
3+
from os import getenv
4+
5+
from dotenv import load_dotenv
6+
from openai import AzureOpenAI
7+
from pydantic import BaseModel
8+
9+
10+
def init_args() -> argparse.Namespace:
11+
parser = argparse.ArgumentParser(
12+
prog="convert_code",
13+
description="Convert code to a structured format",
14+
)
15+
parser.add_argument("-f", "--file")
16+
parser.add_argument("-s", "--system", default="Extract the event information.")
17+
parser.add_argument("-u", "--user", default="Alice and Bob are going to a science fair on Friday.")
18+
parser.add_argument("-v", "--verbose", action="store_true")
19+
return parser.parse_args()
20+
21+
22+
class ResponseFormat(BaseModel):
23+
# FIXME: Update the ResponseFormat class to match your actual response format
24+
name: str
25+
date: str
26+
participants: list[str]
27+
28+
29+
def print_structured_output(
30+
system: str,
31+
user: str,
32+
):
33+
"""
34+
How to use:
35+
Support for structured outputs was first added in API version 2024-08-01-preview.
36+
It is available in the latest preview APIs as well as the latest GA API: 2024-10-21.
37+
38+
Install dependencies:
39+
$ pip install openai python-dotenv pydantic
40+
41+
References:
42+
- https://learn.microsoft.com/ja-jp/azure/ai-services/openai/how-to/structured-outputs?tabs=python
43+
"""
44+
45+
client = AzureOpenAI(
46+
azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"),
47+
api_key=getenv("AZURE_OPENAI_API_KEY"),
48+
api_version=getenv("AZURE_OPENAI_API_VERSION"),
49+
)
50+
51+
completion = client.beta.chat.completions.parse(
52+
model=getenv("AZURE_OPENAI_GPT_MODEL"),
53+
messages=[
54+
{"role": "system", "content": system},
55+
{"role": "user", "content": user},
56+
],
57+
response_format=ResponseFormat,
58+
)
59+
60+
print(completion.choices[0].message.parsed)
61+
print(completion.model_dump_json(indent=2))
62+
63+
64+
if __name__ == "__main__":
65+
args = init_args()
66+
67+
# Set verbose mode
68+
if args.verbose:
69+
logging.basicConfig(level=logging.DEBUG)
70+
71+
# Parse .env file and set environment variables
72+
load_dotenv()
73+
74+
try:
75+
print_structured_output(
76+
system=args.system,
77+
user=args.user,
78+
)
79+
except Exception as e:
80+
logging.error(e)

0 commit comments

Comments
 (0)