Skip to content

Commit 33aa908

Browse files
authored
Merge pull request #178 from ks6088ts-labs/feature/issue-177_convert-code-from-string
add structured output example script
2 parents 27c20fe + a03d85b commit 33aa908

File tree

3 files changed

+187
-99
lines changed

3 files changed

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

0 commit comments

Comments
 (0)