GPT 結構化輸出與 PDF
本頁說明 GPT 系列的結構化輸出與 PDF 輸入寫法;模型 ID 與介面設定請見 GPT 系列概覽。
結構化輸出
透過 response_format 傳入 JSON Schema,strict: true 時輸出會嚴格符合 Schema:
gpt_json_schema.py
import json
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.ofox.ai/v1", api_key=os.environ["OFOX_API_KEY"])
resp = client.chat.completions.create(
model="openai/gpt-5.4-mini",
response_format={
"type": "json_schema",
"json_schema": {
"name": "price",
"strict": True,
"schema": {
"type": "object",
"properties": {"price": {"type": "number"}, "currency": {"type": "string"}},
"required": ["price", "currency"],
"additionalProperties": False,
},
},
},
messages=[{"role": "user", "content": "球拍和球共 1.10 美元,球拍比球貴 1 美元,球多少錢?"}],
)
print(json.loads(resp.choices[0].message.content))更多寫法請見結構化輸出。
PDF 輸入
Chat Completions
gpt_pdf.py
import base64
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.ofox.ai/v1", api_key=os.environ["OFOX_API_KEY"])
pdf_b64 = base64.b64encode(open("invoice.pdf", "rb").read()).decode()
resp = client.chat.completions.create(
model="openai/gpt-5.4-mini",
messages=[{"role": "user", "content": [
{"type": "file", "file": {"filename": "invoice.pdf", "file_data": f"data:application/pdf;base64,{pdf_b64}"}},
{"type": "text", "text": "這張發票的總金額是多少?"},
]}],
)
print(resp.choices[0].message.content)其他錯誤請見常見錯誤。
最後更新於