ユースケース
Structured Outputs 機能により、モデルは提供された JSON Schema に準拠したレスポンスを生成できるため、生成結果をより制御しやすく、解析しやすくなります。この機能は、後続ロジックでの解析や処理を容易にするだけでなく、結果をビジネスシステムへ統合する際にも役立ち、さまざまな自動化やデータ処理のシナリオに適しています。対応モデル
以下のモデルは構造化出力をサポートしています。使用方法
リクエストに以下の情報を追加します。- パラメータの設定:
response_formatパラメータを使用して、定義した JSON Schema を指定します。 - プロンプトによる指示:プロンプト内で、モデルに構造化出力を行うよう指示します。
使用例
以下では、Structured Outputs 機能を使用して、提供した JSON Schema に準拠する JSON レスポンスを生成する完全な Python コード例を示します。1. クライアントの初期化
JieKou AI API キーを使用してクライアントを初期化する必要があります。from openai import OpenAI
client = OpenAI(
base_url="https://api.highwayapi.ai/openai",
api_key="<Your API Key>",
)
model = "qwen/qwen-2.5-72b-instruct"
2. JSON Schema の定義
JSON Schema を定義する必要があります。以下の例では、ユーザー入力から費用情報を抽出する JSON Schema を作成します。# 費用追跡用のシステムプロンプトを定義します。
system_prompt = """You are an expense tracking assistant.
Extract expense information from the user's input and format it according to the provided schema."""
# 構造化レスポンス用の JSON Schema を定義します。
response_format = {
"type": "json_schema",
"json_schema": {
"name": "expense_tracking_schema",
"schema": {
"type": "object",
"properties": {
"expenses": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "Description of the expense"
},
"amount": {
"type": "number",
"description": "Amount spent in dollars"
},
"date": {
"type": "string",
"description": "When the expense occurred"
},
"category": {
"type": "string",
"description": "Category of expense (e.g., food, office, travel)"
}
},
"required": [
"description",
"amount"
]
}
},
"total": {
"type": "number",
"description": "Total amount of all expenses"
}
},
"required": [
"expenses",
"total"
],
},
},
}
3. API リクエストの実行
API リクエストを作成します。このリクエストにはresponse_format パラメータが含まれており、前のステップで定義した JSON schema を指定します。
chat_completion = client.chat.completions.create(
model=model,
messages=[
{
"role": "system",
"content": system_prompt,
},
{
"role": "user",
"content": """I spent $120 on dinner at an Italian restaurant last Friday with my colleagues.
Also bought office supplies for $45 on Monday.""",
},
],
max_tokens=1024,
temperature=0.8,
stream=False,
response_format=response_format,
)
response_content = chat_completion.choices[0].message.content
# JSON を解析して整形します
try:
json_response = json.loads(response_content)
prettified_json = json.dumps(json_response, indent=2)
print(prettified_json)
except json.JSONDecodeError:
print("Could not parse response as JSON. Raw response:")
print(response_content)
{
"expenses": [
{
"date": "2023-03-17",
"description": "Dinner at Italian restaurant",
"amount": 120,
"category": "Food & Dining"
},
{
"date": "2023-03-13",
"description": "Office supplies",
"amount": 45,
"category": "Office Supplies"
}
],
"total": 165
}
完全なコード
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.highwayapi.ai/openai",
api_key="<Your API Key>",
)
model = "qwen/qwen-2.5-72b-instruct"
# JSON Schema を使用した構造化出力の例
# この例では、費用情報を抽出するための schema を作成します
# 費用追跡用のシステムプロンプトを定義します
system_prompt = """You are an expense tracking assistant.
Extract expense information from the user's input and format it according to the provided schema."""
# 構造化レスポンス用の JSON schema を定義します
response_format = {
"type": "json_schema",
"json_schema": {
"name": "expense_tracking_schema",
"schema": {
"type": "object",
"properties": {
"expenses": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "Description of the expense"
},
"amount": {
"type": "number",
"description": "Amount spent in dollars"
},
"date": {
"type": "string",
"description": "When the expense occurred"
},
"category": {
"type": "string",
"description": "Category of expense (e.g., food, office, travel)"
}
},
"required": [
"description",
"amount"
]
}
},
"total": {
"type": "number",
"description": "Total amount of all expenses"
}
},
"required": [
"expenses",
"total"
],
},
},
}
chat_completion = client.chat.completions.create(
model=model,
messages=[
{
"role": "system",
"content": system_prompt,
},
{
"role": "user",
"content": """I spent $120 on dinner at an Italian restaurant last Friday with my colleagues.
Also bought office supplies for $45 on Monday.""",
},
],
max_tokens=1024,
temperature=0.8,
stream=False,
response_format=response_format,
)
response_content = chat_completion.choices[0].message.content
# JSON を解析して整形します
try:
json_response = json.loads(response_content)
prettified_json = json.dumps(json_response, indent=2)
print(prettified_json)
except json.JSONDecodeError:
print("Could not parse response as JSON. Raw response:")
print(response_content)