輸出格式:文字、JSON mode 與 Structured Outputs
文字與圖片請求使用 gpt-6-sol 並關閉推理;音訊使用 gpt-audio-1.5,Predicted Outputs 使用支援該功能的 GPT-4.1。各類請求的模型與參數組合分別設定,不共用不相容的選項。
姓名、日期、金額、文章摘要及客服分類等結果需要交給程式解析時,回覆格式由 response_format 指定。只在 prompt 要求 JSON,仍可能收到說明文字或不符合預期的欄位;JSON mode 與 Structured Outputs 提供的約束也不同。
JSON mode 約束 JSON 語法,Structured Outputs 另約束欄位與型別,適用情境如下。
| 設定 | 提供什麼約束 | 適用情境與限制 |
|---|---|---|
不設定,或 {"type":"text"} | 一般自然語言。 | 聊天、客服、技術解釋、文章、翻譯、改寫與給人看的摘要。格式彈性大,不適合靠固定字串切割來解析 title、summary、tags。 |
{"type":"json_object"} | 舊版 JSON mode,要求有效 JSON。 | 需要簡單可解析 JSON,但不保證欄位名稱與型別。例如要 name、description、features,仍可能得到 product_name、summary、main_features。訊息中必須明確要求 JSON;省略此指令可能持續輸出空白,API 也會檢查上下文是否出現 JSON。 |
{"type":"json_schema","json_schema":{...}} | Structured Outputs,依支援的 JSON Schema 子集限制結構。 | 抽取、分類、表單、收據 OCR、資料庫/API/報表與 UI 所需的固定欄位。模型必須支援,仍需處理拒絕和不完整輸出。 |
strict Schema 與共用函式
strict=True 位於 json_schema 內。object_schema() 將每個欄位列入 required,並設定 additionalProperties=False;巢狀 object 也採相同規則。允許缺值的欄位仍須存在,值的型別則包含 null。
Python 程式依序共用 client、COMMON 及抽取函式,音訊與 prediction 請求另設模型。執行環境需安裝 openai 並設定 OPENAI_API_KEY,安裝方式見第一篇共用設定。
import base64
import json
from pathlib import Path
from openai import OpenAI
client = OpenAI()
CHAT_MODEL = "gpt-6-sol"
COMMON = {"model": CHAT_MODEL, "reasoning_effort": "none", "store": False, "max_completion_tokens": 1600}
def object_schema(properties: dict) -> dict:
return {
"type": "object",
"properties": properties,
"required": list(properties),
"additionalProperties": False,
}
def schema_format(name: str, schema: dict) -> dict:
return {
"type": "json_schema",
"json_schema": {"name": name, "strict": True, "schema": schema},
}
def completed_text(completion) -> str:
if not completion.choices:
raise ValueError("回應沒有候選訊息。")
choice = completion.choices[0]
message = choice.message
if message.refusal:
raise ValueError(message.refusal)
if choice.finish_reason != "stop" or not message.content or not message.content.strip():
raise ValueError("沒有取得完整文字,不能直接當作成功結果。")
return message.content
def extract(instruction: str, source, name: str, schema: dict) -> dict:
completion = client.chat.completions.create(
**COMMON,
messages=[
{"role": "developer", "content": instruction},
{"role": "user", "content": source},
],
response_format=schema_format(name, schema),
)
data = json.loads(completed_text(completion))
if not isinstance(data, dict):
raise ValueError("此流程預期 JSON object。")
return data
completed_text() 檢查拒絕與停止原因,extract() 解析 JSON,日期、幣別及金額等業務值由後端驗證。欄位命名與資料庫、API 保持一致,日期格式可寫在 description,類別可用 enum 限定;Schema 的深度與關鍵字仍受支援子集限制。
收據結果經後端驗證後,建立待確認資料,由使用者確認再寫入帳務。Schema 格式限制見Structured Outputs 官方文件。
產品、收據、摘要與客服分類
四種抽取任務共用 extract(),分別提供 Schema、指令及輸入。cases 保存產品、文字收據、文章摘要與客服分類的設定;圖片收據則以相同函式接收 content parts 及 nullable 欄位。
product_schema = object_schema({
"name": {"type": "string"}, "summary": {"type": "string"},
"features": {"type": "array", "items": {"type": "string"}},
"target_users": {"type": "string"},
})
receipt_schema = object_schema({
"merchant": {"type": ["string", "null"]},
"date": {"type": ["string", "null"], "description": "YYYY-MM-DD"},
"currency": {"type": ["string", "null"], "enum": ["JPY", "TWD", "USD", "KRW", "EUR", None]},
"total": {"type": ["number", "null"]},
"items": {"type": "array", "items": object_schema({
"name": {"type": "string"}, "amount": {"type": "number"},
})},
})
article_schema = object_schema({
"title": {"type": "string"}, "summary": {"type": "string"},
"keywords": {"type": "array", "items": {"type": "string"}},
})
ticket_schema = object_schema({
"category": {"type": "string", "enum": ["billing", "account", "technical", "general"]},
"priority": {"type": "string", "enum": ["low", "medium", "high"]},
"reason": {"type": "string"},
})
cases = {
"product_summary": (
"根據提供的文字抽取產品資訊。",
"TallyTrip 是自由行小團體的旅程協作工具,提供收據 OCR、多人分帳及多幣別結算。",
product_schema,
),
"receipt_expense": (
"根據收據文字抽取消費資料,無法判斷的欄位填 null。",
"店名:Tokyo Coffee\n日期:2026-05-20\n拿鐵 600 JPY\n蛋糕 800 JPY\n總計 1400 JPY",
receipt_schema,
),
"article_summary": (
"使用繁體中文整理文章,不增加原文沒有的資訊。",
"Chat Completions 使用 messages 提供上下文,並以 response_format 控制輸出格式。",
article_schema,
),
"support_ticket_category": (
"根據訊息判斷客服類型與優先級。",
"我昨天付款了,但是帳號還沒有升級。",
ticket_schema,
),
}
# 一次執行一種任務;需要測其他情境時只更換這個 key。
name = "receipt_expense"
instruction, source, schema = cases[name]
data = extract(instruction, source, name, schema)
print(data)
| 情境 | 保留的資料 | 後端接續處理 |
|---|---|---|
| 產品 | name、summary、features、target_users | 核對內容是否來自原始產品資料,再交給頁面或 API。 |
| 文字收據 | merchant、date、currency、total、items | 示例品項合計 600 + 800 = 1400 JPY;驗證日期、幣別與合計後建立待確認草稿。 |
| 文章摘要 | title、summary、keywords | 保留技術名詞,檢查摘要是否增添來源沒有的主張;長文可先分段再作總摘要。 |
| 客服分類 | category、priority、reason | 付款後未升級的訊息可交付款處理流程;分類與優先級另外按業務規則驗證。 |
Pydantic 資料模型與遞迴 UI 的結構定義見第四篇:結構化輸出深入設計。
Tool Calling:定義、驗證、執行與回填
Tool Calling 由模型產生工具名稱與參數,後端負責驗證、執行及回填結果。工具可連接天氣服務、資料庫、訂單、帳號、旅程花費與內部 API,也可執行計算、格式轉換或建立行事曆;存取權限與操作流程由應用程式管理。
tool_calls 是模型提出的呼叫要求,並非執行結果。後端依工具定義驗證輸入、執行查詢,再以 tool 訊息回填,模型才依結果產生回答。GPT-6 Sol 在 Chat Completions 的帶工具請求須使用 reasoning_effort="none";推理與工具交替的流程使用 Responses API,差異見官方差異說明。
tools 定義與 tool_choice 對照
Function 工具的格式為 {"type":"function","function":{...}}:name 指定名稱,description 說明用途,parameters 定義輸入 Schema,strict 位於 function 內。工具描述需包含使用時機及輸入範圍,例如「依城市查詢目前天氣,適用溫度或降雨問題」。
天氣工具可以要求 city(例如 Taipei、Tokyo、Seoul);若增加 unit,可用 enum=["celsius","fahrenheit"] 限定。非 strict schema 可以只把 city 列為 required;strict schema 若要可選單位,仍須列入 required,改用允許 null 的型別表達。
| 選項 | 設定與用途 | 注意事項 |
|---|---|---|
tool_choice | "none" 禁止工具;"auto" 允許模型直接回答或呼叫;"required" 要求一個或多個工具。 | 有 tools 時預設 auto,沒有時預設 none。一般助理用 auto,必須查資料才回答的流程可用 required。 |
| 強制特定工具 | {"type":"function","function":{"name":"get_weather"}} | 適合已按下查詢天氣按鈕、送出訂單表單或後端已決定流程,只讓模型填參數。輸入不適用時仍可能被迫產生不佳參數。 |
| 限制工具集合 | {"type":"allowed_tools","allowed_tools":{"mode":"auto","tools":[{"type":"function","function":{"name":"search_trip"}}]}} | 此例假設 tools 已定義 search_trip。mode 也可設 required;在 get_weather、get_time、search_trip、create_expense、delete_expense 中,只開放此次需要的查詢。 |
parallel_tool_calls | 允許同輪多個呼叫;設 False 可讓每輪最多一個。 | 台北與東京天氣可獨立查詢;先建立旅程、再用產生的 ID 加入花費、最後結算有先後依賴。允許多個呼叫也不代表後端會自動並行,排程與結果回填仍要自己處理。 |
allowed_tools 限制模型本輪可選的工具,後端仍要檢查授權。讀取資料可依相依性安排平行查詢;付款、刪除、發信等有副作用的工具,另做確認、冪等與執行順序控制。
天氣工具呼叫範例
weather_tools 定義城市查詢,tool_turn() 使用共用的 client、CHAT_MODEL、object_schema() 與 completed_text() 執行兩輪請求。weather_handler() 回傳固定示例資料,實際天氣服務可接在 handler 中;呼叫前檢查工具白名單及 city,拒絕或截斷的回應不執行工具。
weather_tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "依城市查詢目前天氣,適用溫度或降雨問題。",
"strict": True,
"parameters": object_schema({
"city": {"type": "string", "description": "城市名稱,如 Taipei、Tokyo、Seoul。"},
}),
},
}]
def weather_handler(arguments: dict) -> dict:
if set(arguments) != {"city"}:
raise ValueError("欄位不符。")
city = arguments["city"]
if not isinstance(city, str) or not city.strip():
raise ValueError("city 必須是非空字串。")
return {"city": city, "forecast": "今天下午有短暫陣雨機率。", "temperature": 28}
def tool_turn(messages: list, tools: list, handlers: dict, parallel=False) -> str:
completion = client.chat.completions.create(
**COMMON,
messages=messages, tools=tools,
tool_choice="auto", parallel_tool_calls=parallel,
)
if not completion.choices:
raise ValueError("回應沒有候選訊息。")
choice = completion.choices[0]
message = choice.message
if message.refusal:
raise ValueError(message.refusal)
if not message.tool_calls:
return completed_text(completion)
if choice.finish_reason != "tool_calls":
raise ValueError("工具輸出不完整,不能執行。")
# 保留原本的 assistant 呼叫訊息,再逐一加入每個呼叫的結果。
following = [*messages, message.model_dump(exclude_none=True)]
for call in message.tool_calls:
if call.type != "function" or not call.id or call.function.name not in handlers:
raise ValueError("未知工具。")
try:
arguments = json.loads(call.function.arguments)
if not isinstance(arguments, dict):
raise ValueError("參數必須是 object。")
result = handlers[call.function.name](arguments)
except (ValueError, PermissionError, TimeoutError):
result = {"error": True, "message": "查詢失敗,請確認輸入與存取權限後重試。"}
following.append({
"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False),
})
final = client.chat.completions.create(
**COMMON,
messages=following, tools=tools, tool_choice="none",
)
return completed_text(final)
weather_messages = [
{"role": "developer", "content": "你是天氣助理,需要即時天氣時請使用工具;依結果回答。"},
{"role": "user", "content": "台北今天會下雨嗎?"},
]
print(tool_turn(weather_messages, weather_tools, {"get_weather": weather_handler}))
例如回應包含 id="call_abc123"、function.name="get_weather" 與 arguments='{"city":"Taipei"}' 時,後端先解析參數,再呼叫 handler。回填的 tool_call_id 使用原呼叫 ID,content 則保存序列化結果;assistant 呼叫訊息與各筆工具結果須一併保留。
tool_turn() 可處理模型直接回答或同輪多個工具呼叫。工具結果回填後,第二次請求使用 tool_choice="none" 取得文字整理;連續多步工具需另設有最大輪數的迴圈。
工具參數與權限驗證
工具輸入仍須檢查型別、ID 是否屬於目前帳號、金額與日期是否合法,以及操作是否需要確認。上例把預期查詢失敗轉成可回填的錯誤;實際服務的 timeout、權限與資料不存在,也在 handler 中轉成明確結果,內部錯誤細節留在後端紀錄。
旅程花費查詢
旅程查詢使用 trip_tools、trip_handler() 與旅程訊息呼叫 tool_turn()。固定金額來自 TallyTrip 的示例資料,授權集合由後端根據登入者取得,不採用模型提供的身分資訊。
trip_tools = [{
"type": "function",
"function": {
"name": "get_trip_expense_summary",
"description": "查詢旅程總花費、幣別與各成員付款及分攤資訊。",
"strict": True,
"parameters": object_schema({
"trip_id": {"type": "string", "description": "旅程 ID。"},
"currency": {"type": "string", "enum": ["TWD", "JPY", "USD", "KRW", "EUR"]},
}),
},
}]
# 示例後端授權與資料;正式系統從目前使用者的權限與資料庫取得。
authorized_trip_ids = {"tokyo_2026"}
def trip_handler(arguments: dict) -> dict:
if set(arguments) != {"trip_id", "currency"}:
raise ValueError("欄位不符。")
trip_id, currency = arguments["trip_id"], arguments["currency"]
if not isinstance(trip_id, str) or not isinstance(currency, str):
raise ValueError("參數型別錯誤。")
if trip_id not in authorized_trip_ids:
raise PermissionError("無存取權。")
if currency not in ["TWD", "JPY", "USD", "KRW", "EUR"]:
raise ValueError("不支援的幣別。")
if currency != "JPY":
raise ValueError("此示例只提供 JPY 統計,未提供匯率換算。")
return {
"trip_id": trip_id, "currency": currency, "total": 128000,
"members": [
{"name": "Alfred", "paid": 60000, "share": 42667},
{"name": "Ben", "paid": 38000, "share": 42667},
{"name": "Cindy", "paid": 30000, "share": 42666},
],
}
print(tool_turn(
[
{"role": "developer", "content": "你是 TallyTrip 旅程助理,花費查詢請用工具並根據結果回答。"},
{"role": "user", "content": "這趟東京旅行目前總共花了多少日圓?trip_id=tokyo_2026"},
],
trip_tools, {"get_trip_expense_summary": trip_handler},
))
以 {"trip_id":"tokyo_2026","currency":"JPY"} 查詢時,後端回傳總計 128,000 JPY,三人分攤 42,667、42,667、42,666,合計與總額一致。對照已付款金額,Alfred 多付 17,333,Ben 少付 4,667,Cindy 少付 12,666 JPY;金額與餘數由後端計算,模型僅整理結果。
舊專案的 functions、function_call 與 role="function",需要一併遷移請求、回傳及結果配對;資料形狀對照見第三篇相容性整理。
文字串流、停止原因與用量
非串流請求完成後一次取得 chat.completion,文字位於 message.content,適用摘要、分類及抽取。串流則逐段回傳 chat.completion.chunk,以 delta.content 提供新增文字,可用於聊天、客服及長回答的即時顯示。
stream 是 boolean 或 null;省略或 False 時為非串流,設 True 才逐段回傳。chunk 可能只有 role、文字、工具參數片段、拒絕或停止原因,也可能沒有 choices;delta 是增量,不是整則訊息。
collect_text_stream() 將單一候選的文字累積到 parts,以 "".join(parts) 組成回答,並同時輸出片段。stream_options={"include_usage":True} 搭配 stream=True,讓串流額外提供用量 chunk,其 choices 是空陣列;多候選請求則須按 choice.index 分開累積。
def collect_text_stream(stream) -> dict:
parts, refusal_parts = [], []
finish_reason, usage = None, None
for chunk in stream:
if chunk.usage is not None:
usage = chunk.usage
if not chunk.choices:
continue
choice = chunk.choices[0]
if choice.delta.content:
parts.append(choice.delta.content)
print(choice.delta.content, end="", flush=True)
if choice.delta.refusal:
refusal_parts.append(choice.delta.refusal)
if choice.finish_reason is not None:
finish_reason = choice.finish_reason
return {
"text": "".join(parts), "refusal": "".join(refusal_parts),
"finish_reason": finish_reason, "usage": usage,
}
stream = client.chat.completions.create(
**COMMON,
messages=[{"role": "user", "content": "請用三句話介紹 Chat Completions API。"}],
stream=True, stream_options={"include_usage": True},
)
try:
result = collect_text_stream(stream)
finally:
stream.close()
print("\n", result["finish_reason"], result["usage"])
if result["refusal"] or result["finish_reason"] != "stop" or not result["text"].strip():
raise ValueError("回覆尚未完整完成,請依原因處理。")
full_text = result["text"]
候選的停止原因與最後用量分屬不同 chunk,因此收到停止原因後仍需繼續讀取。串流中斷時 usage 可能缺省,應保留未知值而非零;候選索引、延遲與錯誤紀錄的完整實作見第三篇串流診斷累積器。
| finish_reason | 代表什麼 | 後續處理 |
|---|---|---|
stop | 自然完成或遇到停止序列。 | 仍檢查拒絕與內容,再保存或解析。 |
length | 到達 token 上限。 | 標記截斷,評估增加 max_completion_tokens;不要執行未完成的工具參數。 |
tool_calls | 完成本輪工具呼叫輸出。 | 組好完整 ID、名稱與參數後,進入驗證和工具流程。 |
content_filter | 內容過濾使輸出停止。 | 走對應的提示或失敗流程。 |
function_call | 舊版函式呼叫。 | 相容程式依舊契約處理。 |
用量 chunk 的固定結構及中斷限制可對照Chat Completions API Reference。
串流工具呼叫的片段累積
工具參數 JSON 可拆成 {"city"、:"Tai、pei"} 等片段,須累積完成才解析與執行。collect_tool_stream() 共用 weather_tools 及天氣訊息,處理單一 choice,並按 tool call index 分別組合多個呼叫。
def collect_tool_stream(stream) -> list:
calls = {}
finish_reason, refused = None, False
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
refused = refused or bool(choice.delta.refusal)
for delta in choice.delta.tool_calls or []:
call = calls.setdefault(delta.index, {"id": "", "type": "", "name": "", "arguments": ""})
if delta.id:
call["id"] = delta.id
if delta.type:
call["type"] = delta.type
function = getattr(delta, "function", None)
if function:
call["name"] += function.name or ""
call["arguments"] += function.arguments or ""
if choice.finish_reason is not None:
finish_reason = choice.finish_reason
if refused or finish_reason != "tool_calls" or not calls:
raise ValueError("工具輸出尚未完整完成。")
result = []
for index in sorted(calls):
call = calls[index]
if call["type"] != "function" or not call["id"] or not call["name"]:
raise ValueError("工具 ID 或名稱不完整。")
arguments = json.loads(call["arguments"])
if not isinstance(arguments, dict):
raise ValueError("工具參數必須是 object。")
result.append({**call, "parsed_arguments": arguments})
return result
stream = client.chat.completions.create(
**COMMON,
messages=weather_messages, tools=weather_tools,
tool_choice="required", parallel_tool_calls=False, stream=True,
)
try:
calls = collect_tool_stream(stream)
finally:
stream.close()
print(calls) # 完整組裝結果;此處尚未執行工具。
組合完成的呼叫仍須經工具名稱、Schema 與權限驗證,再建立含全部 tool_calls 的 assistant 訊息,逐筆回填 tool 結果。這個累積器處理工具分支;採用 auto 的產品另需支援模型直接產生文字的分支。
前端顯示與中斷狀態
後端可透過 HTTP streaming、SSE、WebSocket 或框架的 streaming response 傳送新增文字,前端將內容追加至同一則 assistant 訊息。JavaScript 片段中的 stream 與 renderAssistantMessage 由應用程式提供。
let assistantMessage = "";
for await (const chunk of stream) {
const content = chunk.choices?.[0]?.delta?.content;
if (content) {
assistantMessage += content;
renderAssistantMessage(assistantMessage);
}
}
UI 狀態包括載入中、完成、使用者取消、連線中斷及錯誤,部分文字需依狀態決定是否保存或標記 incomplete。停止生成後,後端可能收不到完整回答及最後用量,因此重試、接續與結果保存不能只根據畫面已有的文字判定。
需要即時顯示時使用串流;後台抽取、分類及完整 JSON 處理可維持非串流,減少狀態管理。
多模態輸入與輸出
純文字 content 可使用字串,同一則 user 訊息混合文字與附件時,使用帶有 type 的 content parts。下表列出輸入片段格式;modalities 則指定輸出型態。
| type | 內容形狀 | 適用範圍 |
|---|---|---|
text | {"type":"text","text":"請分析以下內容。"} | 與其他片段混用;只有文字時用字串更簡單。 |
image_url | {"type":"image_url","image_url":{"url":"圖片網址或 data URL","detail":"high"}} | 圖片描述、UI/商品分析、收據、票券、照片、圖表、表格與訂位或地圖截圖;使用支援視覺的模型。 |
input_audio | {"type":"input_audio","input_audio":{"data":"實際音訊的 base64","format":"mp3"}} | 音訊格式為 mp3 或 wav,搭配支援音訊的模型。 |
file | {"type":"file","file":{"file_id":"已上傳的 ID"}} 或 filename 與 file_data。 | Chat Completions 的 file part 僅接受 PDF,不能當作通用文件格式入口。 |
圖片 URL、base64 與 detail
圖片輸入可提供模型能存取的 URL,或由後端讀檔產生 data:image/jpeg;base64,...。image_part() 使用本機圖片產生 data URL,檔案的 MIME type 須與實際格式一致;URL 與 data URL 的選擇取決於權限、大小及存取方式。
| detail | 用途與限制 |
|---|---|
auto | 採該模型預設的處理方式。 |
low | 粗略理解圖片;尺寸與 token 規則依模型而異,不能一概認定比 high 便宜。 |
high | 一般高細節理解,可用於收據、票券、截圖、表格與細小文字。 |
original | 支援時可用於密集圖片、OCR 或需要精確座標的任務;仍可能按模型限制縮放。使用前確認模型列出的 detail 選項。 |
圖片抽取後要核對文字、金額與日期,再建立待確認資料。不同模型的尺寸與 token 行為可查Images and vision 官方文件。
圖片收據與 nullable Schema
receipt_parts 將文字指令與本機 receipt.jpg 放在同一則輸入中。自然語言描述可將無法辨識的內容標成 unknown;固定 JSON 欄位使用 nullable Schema,以 null 表示缺值。
def image_part(filename: str, mime: str, detail="high") -> dict:
encoded = base64.b64encode(Path(filename).read_bytes()).decode("ascii")
return {
"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{encoded}", "detail": detail},
}
receipt_parts = [
{"type": "text", "text": "請讀取這張收據的 merchant、date、currency、total。"},
image_part("receipt.jpg", "image/jpeg"),
]
image_receipt_schema = object_schema({
"merchant": {"type": ["string", "null"]},
"date": {"type": ["string", "null"], "description": "日期,格式 YYYY-MM-DD"},
"currency": {"type": ["string", "null"]},
"total": {"type": ["number", "null"]},
})
image_receipt = extract(
"你是收據整理助理,請依圖片抽取消費資訊,看不清的欄位填 null。",
receipt_parts, "receipt_summary", image_receipt_schema,
)
print(image_receipt)
收據圖片經抽取及後端驗證後,先建立待確認草稿,由使用者核對金額、幣別及日期後再寫入旅程花費。若結果僅供閱讀,可沿用 receipt_parts 並省略 response_format,取得自然語言描述。
票券與訂位截圖
票券與訂位截圖可包含交通方式、出發地、目的地、出發時間、票價及訂位編號。ticket_parts 讀取本機 ticket.png,將辨識結果整理為待核對的行程草稿。
ticket_parts = [
{"type": "text", "text": "請整理交通方式、出發地、目的地、出發時間、票價與訂位編號。"},
image_part("ticket.png", "image/png"),
]
completion = client.chat.completions.create(
**COMMON,
messages=[
{"role": "developer", "content": "你是旅程資料整理助理,看不清楚的欄位請明確標示 null。"},
{"role": "user", "content": ticket_parts},
],
)
print(completed_text(completion))
如果這些欄位要交給程式處理,再使用相同 extract 流程與 nullable schema;自然語言裡寫 null 並不等於已提供 JSON 結構約束。
PDF 附檔與文件檢索
Chat Completions 的 file part 只接受 PDF,可使用 file_id,或 filename 加上 base64 file_data,不接受外部 file_url。非 PDF 文字檔由應用程式讀取後,以 text 傳入;其他格式可使用 Responses API。PDF 範例讀取本機 document.pdf,附於本輪請求。
pdf_data = base64.b64encode(Path("document.pdf").read_bytes()).decode("ascii")
completion = client.chat.completions.create(
**COMMON,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "請整理這份文件的重點。"},
{"type": "file", "file": {
"filename": "document.pdf",
"file_data": "data:application/pdf;base64," + pdf_data,
}},
],
}],
)
print(completed_text(completion))
已上傳的 PDF 可改用 {"file_id":"實際上傳取得的 ID"}。單次附檔適用 PDF 摘要、合約或報告整理,也能搭配結構化輸出;大量文件查找則使用 file search、retrieval、vector store 或 RAG。格式與限制見File inputs 官方文件。
音訊輸入與語音回應
音訊請求使用 gpt-audio-1.5,GPT-6 Sol 不支援此輸入。recording.mp3 的檔案位元組經 base64 編碼後,直接放入 input_audio.data;此處不加圖片與 PDF 使用的 data URL 前綴。
modalities 指定輸出型態。一般文字可省略或使用 ["text"];語音回答使用 ["audio"] 或 ["text","audio"],並提供 audio 設定。audio.format 可選 wav、mp3、flac、opus、pcm16,voice 決定聲音,例如 alloy。 聲音與格式仍依模型支援選用。
audio_messages = [{
"role": "user",
"content": [
{"type": "text", "text": "請把這段語音整理成三個重點,並用語音回答。"},
{"type": "input_audio", "input_audio": {
"data": base64.b64encode(Path("recording.mp3").read_bytes()).decode("ascii"),
"format": "mp3",
}},
],
}]
completion = client.chat.completions.create(
model="gpt-audio-1.5", messages=audio_messages,
modalities=["text", "audio"], audio={"format": "mp3", "voice": "alloy"},
)
message = completion.choices[0].message
if message.refusal:
raise ValueError(message.refusal)
if completion.choices[0].finish_reason != "stop" or message.audio is None:
raise ValueError("沒有取得完整音訊。")
print(message.audio.transcript)
Path("summary.mp3").write_bytes(base64.b64decode(message.audio.data))
音訊結果包含 id、base64 data、expires_at 與 transcript。語音文字位於 message.audio.transcript,音訊解碼後寫入 summary.mp3 供前端播放。只需要文字摘要時,沿用 audio_messages,設定 modalities=["text"]、移除 audio 參數,再以 completed_text() 讀取;朗讀文字則將 user content 改成文字輸入。
多輪音訊對話可在 assistant 訊息帶入前次音訊 ID,例如 {"role":"assistant","audio":{"id":"audio_abc123"},"content":"上一輪回答的文字"}。實際應使用回傳的 ID 並注意 expires_at;一般文字聊天不需要處理此欄位。
只需要逐字稿可使用 transcription API,即時語音互動則用 Realtime API。模型與音訊格式見 Audio in Chat Completions 官方文件。
prediction:預期輸出與延遲
Predicted Outputs 適用既有程式碼或長文件的小範圍修改,以及接近固定模板的輸出。prediction 提供已知內容以減少生成等待,支援模型有獨立範圍;文件修改範例使用 GPT-4.1,從本機 document.md 讀取預期內容。
original = Path("document.md").read_text(encoding="utf-8")
completion = client.chat.completions.create(
model="gpt-4.1",
messages=[{
"role": "user",
"content": "請只把以下文件中的『舊版名稱』改為『新版名稱』,回傳完整文件:\n" + original,
}],
prediction={"type": "content", "content": original},
)
print(completed_text(completion))
prediction 請求使用 GPT-4.1,與文字及工具的共用模型設定分開。預測未採用的 token 仍依 completion 費率計費,可由 usage 的 rejected_prediction_tokens 查看。此功能不支援 n>1、logprobs、正值 presence_penalty/frequency_penalty、音訊、max_completion_tokens 與 tools,modalities 僅支援 text;模型與計費規則見Predicted Outputs 官方文件。
文字、圖片、音訊與文件分別使用對應的輸入格式,輸出則可選自然語言或 Schema。模型能力與輸入格式共同決定有效的參數組合;單份 PDF 的附檔處理和大量文件檢索也各有不同的資料範圍。
輸出驗證與請求紀錄
圖片可搭配 Schema 抽取欄位,工具查詢須回填結果,長回答可用串流逐段顯示。各類功能都須檢查回應完成狀態、模型相容性及後端業務規則,才能將輸出交給後續程式處理。
請求紀錄包含 token 用量、模型、prompt 版本、工具結果與停止原因,用來追蹤截斷、成本及失敗位置。store、metadata、安全與快取識別、service_tier 及舊參數對照的實作見回傳物件、除錯與實務設定。
