可觀測性與資料管理

請求的模型、功能、prompt 版本、token 用量、延遲及停止原因,是成本分析與錯誤追蹤的主要資料。這些欄位須與使用者及工作階段關聯,才能還原截斷、工具失敗或異常用量發生時的執行條件。

文字請求使用 gpt-6-sol 與 reasoning_effort="none",支援相應的取樣、logprobs 及 Chat Completions 工具設定。其他推理程度須移除不相容的取樣參數,推理與工具交替則使用 Responses API;模型及參數限制見GPT-6 Sol 模型文件與部署檢查文件。

儲存、標籤與使用者識別

message.content 只包含回答文字,request log 另記錄內部使用者、session、功能、prompt/Schema 版本、模型、用量、耗時及停止原因,並標示是否串流、是否使用工具或結構化輸出。

參數/資料用途與限制何時採用
storeTrue 啟用支援的 stored completion 管理流程,可 retrieve、list、delete;update 目前只更新 metadata,不能修改生成內容。False 不使用這項儲存功能,自己的資料庫是否保存仍由應用程式決定。測試、評估、除錯、依 completion ID 查詢或搭配 metadata 管理時可考慮儲存;一次性低價值請求、已有完整內部紀錄、敏感內容或嚴格保留政策則應另外評估。設定還須符合專案區域與保留要求。
metadata自訂字串 key-value 標籤,最多 16 組,key 最長 64 字元、value 最長 512 字元;用於功能、環境、版本及實驗查詢,不能當大型內容儲存區。例如客服分類使用 feature=support_ticket_classifier、environment=production,再用 schema、prompt 或實驗版本比較成功率、成本與錯誤率。
舊 user 與新識別欄位舊請求可能有 user="usr_8f3a91"、user_12345 或 hash_9f86d081。新實作將安全識別交給 safety_identifier,快取用途交給 prompt_cache_key;自己的使用者用量仍由內部 log 管理。識別回答的是哪個終端使用者;metadata 則描述這次請求的功能與情境。登入者可用內部 ID,匿名使用者可用 session/visitor ID,避免直接傳姓名或 Email。

store=False 關閉 stored completion 功能,不等於 Zero Data Retention,也不會停用所有濫用監控或必要日誌。資料保留依明確的請求設定、專案設定及資料控制文件決定;產品資料庫與 audit log 仍由應用程式管理。

metadata key可保留的脈絡與示例
feature、request_type功能如 chatbot、receipt_ocr、trip_summary;類型如 chat、extract、classify。
environment、appdevelopment、staging、production;應用如 tallytrip。
version、prompt_version、schema_version功能版本如 2026-06-01;抽取 schema 如 receipt_v2,prompt 如 receipt_extraction_v3。
session_id、internal_user_id內部關聯 ID;對應真實身分的資料留在自己的系統。
experiment、customer_tier例如 ocr_prompt_ab_test;方案如 free、pro、enterprise。

metadata 與日誌的資料保留

metadata 只放功能標籤與內部識別,不放個資、憑證、完整聊天、收據圖片 base64 或帳務內容。對應真實身分的資料留在自己的資料庫,雜湊識別仍按可關聯資料管理存取權限。

輸入遮罩、內容保存範圍、log 保留時間、存取權限與刪除流程各自設定。旅程、收據及分帳資料可連結到成員與消費行為,因此日誌僅保存除錯所需欄位,平台端儲存與應用程式的 audit log 分別管理。

service_tier:請求與實際處理層級

service_tier 指定處理層級,省略時採 auto,依 Project 設定選擇。請求 auto 而回應為 default 是正常解析結果;成本與效能紀錄分別保存 service_tier_requested 及 service_tier_used,可用層級則依帳號、模型、專案及方案而定。

值行為與選擇思路
auto依 Project 設定選擇,未特別配置時通常為 default。
default使用模型標準價格與效能;適合先建立一般產品基準。
flex可接受較高延遲、可用性波動的低優先任務可評估,例如夜間摘要、批次整理、開發測試。
scale依方案或專案設定使用對應處理層級。
priority即時聊天、客服或高價值付費功能可評估延遲與成本。
fast目前 Reference 也列出此請求值,實際回應以 priority 表示;這同樣說明不能只記 request。

互動功能以可接受的等待時間評估服務層級,低優先背景工作可採 Flex。fast 請求的回應值為 priority,其他層級也以實際回傳值為準,欄位定義見Chat Completions Reference。

request log:成功、失敗與用量紀錄

usage 由回應取得,串流請求另設 stream_options={"include_usage": True}。輸入 token、輸出 token 及總用量與功能、版本、耗時和完成狀態一併保存,細項及計費方式由回傳物件的 usage 欄位解讀。

資料群組建議欄位
識別與時間內部 id、HTTP request_id、completion_id、user_id、session_id、conversation_id、created_at。
請求設定feature、requested_model、model、service_tier_requested、service_tier_used、prompt_version、schema_version、tool_names、response_format_type、is_streaming、request_metadata。
結果與費用三個 token 總額及可用 details、latency_ms、finish_reason、status、error_code、error_type,以及已遮罩的錯誤摘要。

Django 的 AIRequestLog model 保存必要欄位,並可依需求增加 session、版本及工具名稱。這段定義放入既有 Django app,透過專案的 migration 建立資料表。

from django.db import models

class AIRequestLog(models.Model):
    user_id = models.CharField(max_length=128, null=True, blank=True)
    feature = models.CharField(max_length=128)
    model = models.CharField(max_length=128)
    service_tier_requested = models.CharField(max_length=32, null=True, blank=True)
    service_tier_used = models.CharField(max_length=32, null=True, blank=True)

    prompt_tokens = models.IntegerField(null=True, blank=True)
    completion_tokens = models.IntegerField(null=True, blank=True)
    total_tokens = models.IntegerField(null=True, blank=True)

    latency_ms = models.IntegerField(null=True, blank=True)
    finish_reason = models.CharField(max_length=64, null=True, blank=True)
    status = models.CharField(max_length=32, default="success")
    error_code = models.CharField(max_length=128, null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)

失敗紀錄區分 timeout、rate limit、invalid request、網路錯誤,以及後端的 JSON、Schema 或工具執行錯誤。各類錯誤保留原本型別,產品訊息與診斷資料才能對應實際失敗位置。

tracked_completion() 集中保存成功與失敗的共同紀錄,並回傳完整 completion。received 只表示收到回應,拒絕、截斷、工具呼叫及文字內容由回傳解析器判斷;需要平台儲存時明確傳入 store=True,資料保存政策另由組織設定。

import time
from openai import OpenAI

client = OpenAI()

def tracked_completion(*, messages, user_id, feature,
                       prompt_version="v1", store=False,
                       service_tier="auto", model="gpt-6-sol"):
    started = time.perf_counter()
    record = {
        "user_id": user_id, "feature": feature,
        "requested_model": model, "service_tier_requested": service_tier,
        "prompt_version": prompt_version, "is_streaming": False,
    }
    try:
        completion = client.chat.completions.create(
            model=model, reasoning_effort="none", messages=messages,
            safety_identifier=user_id,
            metadata={"feature": feature, "environment": "production",
                      "prompt_version": prompt_version},
            store=store, service_tier=service_tier,
        )
        choice = completion.choices[0] if completion.choices else None
        usage = completion.usage
        record.update({
            "status": "received", "completion_id": completion.id,
            "request_id": getattr(completion, "_request_id", None),
            "object": completion.object, "created": completion.created,
            "model": completion.model,
            "service_tier_used": getattr(completion, "service_tier", None),
            "system_fingerprint": getattr(completion, "system_fingerprint", None),
            "finish_reason": choice.finish_reason if choice else None,
            "prompt_tokens": usage.prompt_tokens if usage else None,
            "completion_tokens": usage.completion_tokens if usage else None,
            "total_tokens": usage.total_tokens if usage else None,
            "usage": usage.model_dump() if usage else None,
        })
        return completion
    except Exception as exc:
        record.update({
            "status": "error", "error_type": type(exc).__name__,
            "error_code": getattr(exc, "code", None),
            "request_id": getattr(exc, "request_id", None),
        })
        # 若需 error_message,先遮罩;不要直接記錄含原始內容的 str(exc)。
        raise
    finally:
        record["latency_ms"] = int((time.perf_counter() - started) * 1000)
        print(record)  # 示範紀錄邊界;正式產品改接資料庫或 log system。

if __name__ == "__main__":
    result = tracked_completion(
        messages=[{"role": "user", "content": "請用一句話介紹 Chat Completions API。"}],
        user_id="usr_8f3a91", feature="support_chat",
    )
    print("completion id:", result.id)

print 標示日誌提交位置,實際產品可接資料庫、OpenTelemetry、Sentry 或既有日誌系統。回應是否可採用,由解析器依完成狀態與內容判斷。

Token 機率與可重現性

logprobs 與候選 Token 機率

logprobs 是 boolean 或 null,開啟後在每個 choice.logprobs 取得輸出 token 的對數機率,不在最外層 completion。top_logprobs 是 integer 或 null,範圍 0–20,必須搭配 logprobs=True,用來觀察同一位置的有限候選;實際候選數可能少於要求。一般未開啟時,choice.logprobs 通常為 null。

logprob 是自然對數,不是百分比;用 math.exp(logprob) 才轉回該位置的條件機率。越接近 0 表示模型在當下上下文越傾向選擇這個 token:例如 −0.01 約為 0.99、−2 約為 0.135、−5 約為 0.0067;−0.5 還算高,−10 則非常低。yes 的示意紀錄可以是 token="yes"、logprob=-0.02、bytes=[121,101,115],其中 bytes 是 token 的位元組表示。

任務/參數用途與界線
分類、yes/no、多選一、短答案輸出短、候選有限時,可分析低機率或混淆結果,搭配人工審核或第二次判斷。
autocomplete、ranking、prompt 調校比較位置上的替代輸出、易混淆類別,觀察 prompt 是否讓選擇更穩定。
聊天、長文章、創意寫作、多段摘要、開放回答資料量大,逐 token 或平均 logprob 無法直接代表正確性、可讀性與整體品質;一般產品通常不優先開。
工具 arguments、JSON 抽取可研究分析,但工具流程通常先做好驗證;JSON Schema 是否需要另加 logprobs 應按任務評估。
temperature、top_p調整生成的隨機性或候選機率範圍;logprobs/top_logprobs 則用來觀察輸出,目的不同。

分類範例同時讀取實際 token、對數機率及候選,使用低 temperature 與較短的輸出預算;完成狀態仍依 finish_reason 判斷。

import math
from openai import OpenAI

client = OpenAI()
completion = client.chat.completions.create(
    model="gpt-6-sol", reasoning_effort="none",
    messages=[
        {"role": "developer", "content": "你是客服分類器。請只輸出 billing、account、technical、general 其中之一,不要加任何解釋。"},
        {"role": "user", "content": "我昨天付款了,但是帳號還沒有升級。"},
    ],
    temperature=0, logprobs=True, top_logprobs=5,
    max_completion_tokens=10, store=False,
)
choice = completion.choices[0]
print("分類結果:", choice.message.content)
if choice.logprobs and choice.logprobs.content:
    for token in choice.logprobs.content:
        print(token.token, token.logprob, math.exp(token.logprob), token.bytes)
        for candidate in token.top_logprobs:
            print("候選:", candidate.token, candidate.logprob)
同一位置的示意候選logprob可觀察的現象
billing−0.05此位置最傾向選擇的 token。
account−3.2若與 billing 越接近,越值得檢查付款和帳號狀態的分類界線。
technical−5.1較低的局部候選。
general−6.8較低的局部候選;未出現的標籤也不能當成零機率。

人工複核可依 token 機率、前兩名差距或分類與關鍵字規則的衝突觸發。例如 logprob < -1.5 可作測試門檻,但實際門檻須用驗證資料與錯誤成本校準。billing、technical 等標籤的切詞不固定為一個 token,比較完整標籤時須合併各 token 的條件機率;分類界線重疊時可調整 Schema 或採多標籤。

seed 與 system_fingerprint 的舊版紀錄

seed 為 integer 或 null,原本用於 best-effort deterministic sampling;system_fingerprint 為回應中的後端設定指紋,並非可指定或鎖定執行環境的版本號。兩者已 deprecated,新系統以模型版本、完整輸入、參數及評估資料追蹤行為,舊 fingerprint 則容許缺值。

相同 seed 與 fingerprint 不保證相同輸出。既有 A/B test 或 regression test 的紀錄需連同模型、輸入及其他設定比對;需要固定文字的功能由模板或程式產生。

seedsystem_fingerprint差異解讀
相同相同較有機會得到相近結果,仍不是保證。
相同不同後端設定可能變動。
不同相同取樣條件不同。
不同不同兩種條件都有差異,結果不同並不意外。

compare_run_settings() 比較已保存的模型、prompt/Schema 版本與參數,不發出 API 請求。歷史 seed 及 fingerprint 只作紀錄差異分析,不加入新的模型請求。

def compare_run_settings(first: dict, second: dict) -> dict:
    fields = (
        "model", "messages", "temperature", "top_p", "seed",
        "system_fingerprint", "max_completion_tokens", "response_format", "tools",
        "prompt_version", "schema_version",
    )
    return {field: (first.get(field), second.get(field))
            for field in fields if first.get(field) != second.get(field)}

# 兩份紀錄是歷史資料的結構示例;此片段不發出 API 請求。
first = {"model": "legacy-model", "seed": 12345, "system_fingerprint": "fp_a",
         "prompt_version": "summary_v1", "temperature": 0.3}
second = {**first, "prompt_version": "summary_v2", "system_fingerprint": "fp_b"}
print(compare_run_settings(first, second))

機率分析與重現性限制

誤判應如何處理
把 logprobs 當正確率它只描述生成 token 的條件機率,模型可以高信心答錯;高風險判斷仍需驗證或人工審核。
用平均 logprob 評估長文章另外評估事實、邏輯、可讀性與任務達成,不能用逐 token 機率取代。
只設 top_logprobs同時設 logprobs=True,並確認模型支援。
把 seed 視為絕對 deterministic只能 best effort;需要固定文字改用模板或程式邏輯。
解讀舊紀錄卻漏存 fingerprint若舊回應提供可一併保存;即使相同也不保證重現,新程式要容許缺值。
所有功能都開 logprobs它增加回傳資料量與解析複雜度,一般聊天或長文未必有價值。

Chat Completion 回傳物件解析

非串流模式在生成完成後一次回傳 chat.completion,包含識別、候選訊息、停止原因及用量。JSON 為欄位結構示意,數字與字串並非 API 實測結果。

{
  "id": "chatcmpl_xxx",
  "object": "chat.completion",
  "created": 1710000000,
  "model": "gpt-6-sol",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Chat Completions API 讓開發者傳入對話訊息並取得模型回覆。",
      "refusal": null,
      "annotations": []
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 120,
    "completion_tokens": 80,
    "total_tokens": 200,
    "prompt_tokens_details": {"cached_tokens": 40},
    "completion_tokens_details": {
      "reasoning_tokens": 20,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": "fp_xxx"
}

回傳欄位與資料路徑

路徑讀法與用途必要注意事項
idcompletion.id 是這次 completion 的識別碼,可關聯內部紀錄與 stored completion 管理。不等於 HTTP request ID;SDK _request_id 對應 x-request-id,支援追查時另外保存。ID 也不能當公開授權依據。
object非串流為 chat.completion,串流為 chat.completion.chunk。SDK 型別通常已足以分辨,手動解析時可用此欄位判別。
createdUnix timestamp,單位秒;可用 datetime.fromtimestamp(completion.created, tz=timezone.utc).isoformat() 轉 UTC 日期。它是模型端建立時間;使用者送出、後端收到、API 開始與結束時間及 latency 仍由自己的系統記錄。
model記錄實際回應模型,並保留 request 的 requested_model。環境、方案、A/B test、模型別名、fallback、路由與不同功能可能讓實際執行條件不同。
choices、choices[].index候選回答列表及候選索引。一般 n=1 常是 index 0;若支援 n=3,可能有 0、1、2,使用迴圈逐一讀取。n 增加生成 token 與成本;只是要五個點子時,可在單一回答要求列出五項。模型是否支援 n 要另查。
choices[].message、message.role模型生成的 assistant message,多輪對話時將回覆加入 messages。有 tools 時保留完整 assistant message,不能只留 content,否則會丟掉呼叫 ID、名稱及 arguments。
message.content一般聊天、摘要、翻譯、改寫與文章生成常用的文字。可能為 null、空字串或缺少一般文字;工具、audio、refusal 等回應需分別處理。
message.tool_calls工具呼叫陣列,包含 id、type、function.name 與 JSON 字串 function.arguments。模型只提出呼叫意圖;程式解析、驗證名稱/schema/權限/業務規則,再執行與回填,完整執行見第二篇工具流程。
choices[].logprobs開啟 logprobs 後才會提供相應 token 資訊。它在每個 choice 下,使用方法與限制見 機率分析章節。
system_fingerprint舊回應可能提供後端設定指紋,可協助解讀舊可重現性紀錄。已 deprecated,非可鎖定的版本號,允許缺省。
service_tier實際處理層級,可與 requested tier 比較。例如 auto → default;費用與效能分析以實際值為依據。
message.refusal、annotations、audio拒絕資訊、引用或其他標註,以及支援模型的音訊資料。依模型、功能與 SDK 版本出現;不要假設 message 只有 role 和 content。

finish_reason:完成與停止原因

finish_reason代表什麼後續處理
stop自然停止,或遇到支援的 stop sequence。再檢查 refusal 與內容型態,才交付一般回答。
length達到生成 token 上限。先看輸出上限與 reasoning 預算,必要時提高 max_completion_tokens、縮短輸入或拆分任務;不能一律歸因於上下文過長。
tool_calls模型要求呼叫工具,尚非最終文字回答。驗證、執行、回填每個工具結果,再繼續模型流程。
content_filter因內容過濾而停止。標記未完整完成並依產品流程處理,不把截斷內容當正常回答。
function_call舊版函式呼叫。用 legacy 相容分支處理,或將整個工具流程一起遷移。

usage:總額、細項與成本

欄位含義示意值/解析方式
prompt_tokensmessages 與相關上下文的輸入用量。120;一般基礎例也可能是 20。
completion_tokenscompletion 用量,可能含推理。80;一般基礎例也可能是 30。
total_tokens輸入與輸出總量。120 + 80 = 200;或 20 + 30 = 50。
prompt_tokens_details.cached_tokensprompt caching 相關輸入細項。40;依模型與功能提供。
completion_tokens_details.reasoning_tokens模型內部推理用量。20;不能只看可見字數估計輸出預算。
accepted_prediction_tokens、rejected_prediction_tokensprediction 功能接受/拒絕的 token 細項。示例均為 0,是否有此功能與欄位依模型而異。

usage 有值時讀取三個總額,細項以 getattr(usage, "prompt_tokens_details", None) 及 getattr(usage, "completion_tokens_details", None) 等方式容許缺省。details 已屬於對應總額,不再加到 total_tokens;費用依實際模型、服務層級及 cached/reasoning/prediction 等用量分別計算。

文字、拒絕與工具回應分類

紀錄中的 received 不代表業務成功。read_completion() 將文字、拒絕、截斷與工具呼叫分成不同狀態,後續解析及執行依分類結果處理。

read_completion() 接收既有 completion,本身不發出 API 請求。一般文字可保存為 {"role":"assistant","content":...};工具回合保存完整 message,例如 message.model_dump(exclude_none=True),再接各筆工具結果。

import json

def read_completion(completion):
    if not completion.choices:
        return {"status": "incomplete", "reason": "missing_choices"}
    choice = completion.choices[0]
    message = choice.message
    if choice.finish_reason in ("length", "content_filter"):
        return {"status": "incomplete", "reason": choice.finish_reason,
                "partial": message.content}
    refusal = getattr(message, "refusal", None)
    if refusal:
        return {"status": "refused", "refusal": refusal}
    if getattr(message, "tool_calls", None):
        if choice.finish_reason != "tool_calls":
            return {"status": "incomplete", "reason": "unfinished_tool_calls"}
        calls = []
        for call in message.tool_calls:
            if call.type != "function" or not call.id or not call.function.name:
                return {"status": "invalid_tool_call"}
            try:
                arguments = json.loads(call.function.arguments)
            except json.JSONDecodeError:
                return {"status": "invalid_tool_arguments", "tool_call_id": call.id}
            if not isinstance(arguments, dict):
                return {"status": "invalid_tool_arguments", "tool_call_id": call.id}
            calls.append({"id": call.id, "name": call.function.name,
                          "arguments": arguments})
        # 僅讀取:執行前仍須允許清單、schema、權限與業務驗證。
        return {"status": "tools", "message": message, "calls": calls}
    if choice.finish_reason == "function_call":
        return {"status": "legacy_function_call", "message": message}
    if choice.finish_reason != "stop":
        return {"status": "incomplete", "reason": choice.finish_reason}
    if message.content and message.content.strip():
        return {"status": "text", "content": message.content,
                "annotations": getattr(message, "annotations", None)}
    return {"status": "no_text", "audio": getattr(message, "audio", None)}

Streaming Chunk 回傳物件解析

非串流取得完整 message;啟用 stream=True 後,收到的是一連串 chat.completion.chunk,每個 delta 只有這次新增的內容。要還原回答,必須累積文字、角色與工具片段,最後根據停止原因決定是否完成。

Chunk 欄位與事件時序

欄位串流中的含義
id、object、created、model同一串流的 completion ID、建立時間及模型通常相同;object 為 chat.completion.chunk。created 是同一 completion 的秒級 Unix timestamp,不是片段抵達時間。可以在第一個 chunk 記錄識別資訊,無須每片都存資料庫。
choices、choice.index本次候選片段列表及所屬候選索引。n>1 要依 index 分開累積;一般聊天 UI 維持 n=1 較容易,也避免多候選成本。
delta.role、delta.content、delta.tool_calls第一片可能只有 assistant 角色或空字串;中間可能有文字、工具或其他型態;最後可能是空 delta。文字缺值與空字串都不能直接當錯誤。
finish_reason中間通常 null,候選結束時才出現;stop、length、tool_calls、content_filter、舊 function_call 的含義與 回傳解析章節相同。
usage設定 stream_options.include_usage=True 才會有額外 final usage chunk;一般內容片段 usage 為 null,最後用量片段 choices 為空。
system_fingerprint、service_tier若回應提供就與 ID、模型、usage、latency 一起保存;舊 fingerprint 仍應容許缺值,tier 記錄實際執行值。

JSON 列出縮減的 chunk 時序及共用欄位,並非完整網路封包。SDK 的迭代器處理 SSE 傳輸層;原始 SSE 另有結束標記。

[
  {"id":"chatcmpl_xxx","object":"chat.completion.chunk","created":1710000000,"model":"gpt-6-sol","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"usage":null},
  {"id":"chatcmpl_xxx","object":"chat.completion.chunk","created":1710000000,"model":"gpt-6-sol","choices":[{"index":0,"delta":{"content":"Chat"},"finish_reason":null}],"usage":null},
  {"id":"chatcmpl_xxx","object":"chat.completion.chunk","created":1710000000,"model":"gpt-6-sol","choices":[{"index":0,"delta":{"content":" Completions"},"finish_reason":null}],"usage":null},
  {"id":"chatcmpl_xxx","object":"chat.completion.chunk","created":1710000000,"model":"gpt-6-sol","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":null},
  {"id":"chatcmpl_xxx","object":"chat.completion.chunk","created":1710000000,"model":"gpt-6-sol","choices":[],"usage":{"prompt_tokens":20,"completion_tokens":30,"total_tokens":50}}
]

created 是 completion 的建立時間,不能用來計算每片抵達延遲。應用程式分別記錄呼叫開始、首段可見文字與串流結束時間,取得 time to first visible text 及總 latency;推理或其他事件發生在可見文字之前時,這個時間不等於模型內部的首個 token 時間。

多候選串流與工具片段累積

工具片段按索引組合:第一片可帶 id="call_abc123"、type="function"、name="get_weather" 及空 arguments,後續的 {"city" 與 :"Taipei"} 才形成完整 JSON。finish_reason="tool_calls" 後才解析及驗證;多候選與平行工具分別按 choice.index 和 tool_call_delta.index 累積。

collect_stream() 收集文字、角色、候選索引、工具片段、usage 與延遲紀錄。工具資料僅組裝及檢查 JSON,不在累積器內執行;帶 tools 的請求使用 reasoning_effort="none"。

import time
import json
from openai import OpenAI

client = OpenAI()

def collect_stream(messages, *, tools=None):
    started = time.perf_counter()
    first_text_at = None
    states = {}
    info = {"completion_id": None, "model": None, "service_tier": None,
            "system_fingerprint": None, "usage": None, "error_type": None}
    request = {
        "model": "gpt-6-sol", "reasoning_effort": "none",
        "messages": messages, "store": False,
        "stream": True, "stream_options": {"include_usage": True},
    }
    if tools is not None:
        request.update(tools=tools, tool_choice="auto", reasoning_effort="none")
    try:
        with client.chat.completions.create(**request) as stream:
            for chunk in stream:
                for key, source in (("completion_id", "id"), ("model", "model"),
                                    ("service_tier", "service_tier"),
                                    ("system_fingerprint", "system_fingerprint")):
                    if info[key] is None:
                        info[key] = getattr(chunk, source, None)
                if chunk.usage is not None:
                    info["usage"] = chunk.usage.model_dump()
                for choice in chunk.choices:  # final usage 的 choices=[] 也安全。
                    state = states.setdefault(choice.index, {
                        "role": "assistant", "parts": [], "refusal": [],
                        "tool_calls": {}, "finish_reason": None,
                    })
                    delta = choice.delta
                    if delta.role:
                        state["role"] = delta.role
                    if delta.content:
                        if first_text_at is None and delta.content.strip():
                            first_text_at = time.perf_counter()
                        state["parts"].append(delta.content)
                        print(delta.content, end="", flush=True)
                    if getattr(delta, "refusal", None):
                        state["refusal"].append(delta.refusal)
                    for fragment in getattr(delta, "tool_calls", None) or []:
                        call = state["tool_calls"].setdefault(fragment.index, {
                            "id": None, "type": None,
                            "function": {"name": "", "arguments": ""},
                        })
                        if fragment.id:
                            call["id"] = fragment.id
                        if fragment.type:
                            call["type"] = fragment.type
                        function = getattr(fragment, "function", None)
                        if function:
                            if function.name:
                                call["function"]["name"] += function.name
                            if function.arguments:
                                call["function"]["arguments"] += function.arguments
                    if choice.finish_reason:
                        state["finish_reason"] = choice.finish_reason
    except Exception as exc:
        info["error_type"] = type(exc).__name__
        # 保存 partial,再由應用程式處理重試或取消;不自動重送工具。
    ended = time.perf_counter()
    info["time_to_first_visible_text_ms"] = (
        int((first_text_at - started) * 1000) if first_text_at is not None else None
    )
    info["latency_ms"] = int((ended - started) * 1000)
    results = {}
    for index, state in states.items():
        calls = [call for _, call in sorted(state["tool_calls"].items())]
        reason = state["finish_reason"]
        text = "".join(state["parts"])
        status = "partial"
        if info["error_type"] is None:
            if state["refusal"]:
                status = "refused"
            elif reason == "stop" and not calls:
                status = "complete" if text.strip() else "no_text"
            elif reason == "tool_calls" and calls:
                status = "tools_pending_validation"
                for call in calls:
                    if call["type"] != "function" or not call["id"] or not call["function"]["name"]:
                        status = "invalid_tool_call"
                        break
                    try:
                        arguments = json.loads(call["function"]["arguments"])
                        if not isinstance(arguments, dict):
                            raise ValueError("工具參數必須是 object。")
                    except (json.JSONDecodeError, ValueError):
                        status = "invalid_tool_arguments"
                        break
        results[index] = {
            "status": status, "finish_reason": reason,
            "message": {"role": state["role"], "content": text,
                        "refusal": "".join(state["refusal"]) or None,
                        "tool_calls": calls or None},
        }
    return {"choices": results, "log": info}

if __name__ == "__main__":
    history = [{"role": "user", "content": "請用三句話介紹 Chat Completions API。"}]
    result = collect_stream(history)
    for item in result["choices"].values():
        if item["status"] == "complete":
            history.append({"role": "assistant", "content": item["message"]["content"]})
    print("\nlog:", result["log"])

只有完成且含非空白文字的回覆加入正式對話,空字串或純空白標記為 no_text。length、content_filter、缺少 finish_reason、取消或網路錯誤保留為 partial/incomplete;工具回合則保存完整 assistant tool_calls 與所有 tool 結果。串流中斷時 final usage 可能缺省,用量維持未知值,不記成零或推定為完整帳單。

多候選資料按 choice.index 分開保存,前端也使用不同訊息容器;終端輸出僅供觀察文字抵達時序。tools_pending_validation 表示工具資料已組裝,執行前的名稱、Schema、授權及業務驗證仍由第二篇的工具流程處理。

前端串流狀態與錯誤矩陣

前端文字追加方式見第二篇前端顯示。後端另傳送候選索引、completion ID、usage、finish_reason 與 error/cancelled,讓 UI 區分完成、等待工具及 partial 狀態。

常見錯誤必須保留的處理
直接讀每片 choices[0]final usage 的 choices=[];先保存 usage,再處理可用的候選片段。
假設每片有 delta.content角色、工具、finish_reason、usage 或空字串都可能沒有可顯示文字。
不看 finish_reasonstop、length、tool_calls、content_filter 需進不同流程。
連線中斷仍存成完整回答標記 partial/incomplete;支援取消、錯誤提示與重新生成。
把工具 arguments 當一次到齊分 index 累積完成後才 parse,驗證通過才執行。

前端另外處理自動滾動、Markdown 增量渲染及未閉合的 code block;取消與中斷不可標記成完成。後台抽取或分類不需要即時顯示時,使用非串流即可。

舊版參數與相容性

2023、2024 年的程式與教學、既有團隊封裝或相容服務中,仍可見 functions、function_call 及 max_tokens。遷移範圍包括請求定義、回傳解析及工具回填,三者使用同一代的資料格式。

新舊格式與工具選擇對照

舊用法新實作遷移時要一起檢查
max_tokensmax_completion_tokens舊例 max_tokens=300/500 對應新的同名預算概念;新上限包含可見輸出與 reasoning。max_tokens 已 deprecated 且不相容 o-series。可先 rg "max_tokens" 搜尋,再按模型與預算逐處確認。
functions=[function_schema]tools=[{"type":"function","function":function_schema}]工具定義增加 type 與 function 外層;schema 的 required/additionalProperties 仍要正確。tools 架構可容納更廣工具類型。
function_calltool_choice不能只換參數名,強制呼叫的物件形狀也改變,見下表。
message.function_callmessage.tool_calls原先單一 function 變成可有多筆工具呼叫的陣列;每筆包含 id、type、function.name 與 JSON arguments。
role="function", name="get_weather"role="tool", tool_call_id="call_abc123"以呼叫 ID 配對結果;回填前保留完整 assistant 工具訊息,每筆呼叫各自有結果。
system 應用指令支援的新模型使用 developersystem 沒有對所有模型全面棄用;舊模型與相容服務按各自文件保留正確角色。user 是使用者輸入、assistant 是模型回覆、tool 是工具結果。
openai.ChatCompletion.create(...)OpenAI() 的 client.chat.completions.create(...)LLM 產生的程式也可能用舊 SDK;檢查版本、模型、角色、預算與工具回填,不只看是否能 import。
工具意圖舊 function_call新 tool_choice
由模型決定"auto""auto":可回答或呼叫一個/多個工具。
禁止呼叫"none""none":例如工具結果回填後,只要最終文字。
指定一個工具{"name":"get_weather"}{"type":"function","function":{"name":"get_weather"}}。
要求使用工具舊介面支援較有限"required":必須呼叫一個或多個工具,仍需驗證。

新版的 tool_calls 是陣列,並可搭配 parallel_tool_calls。即使關閉平行呼叫,解析與回填仍按陣列及呼叫 ID 配對,不能保留只讀單一 function_call 或以名稱回填的舊邏輯。

工具定義與結果回填格式

舊函式流程的變更涉及工具定義、回傳讀取及結果回填。格式片段中的 function_definition、call 與 result 由原流程提供,片段本身不執行工具。

import json

# tools 的定義多了 type/function 外層。
tools = [{"type": "function", "function": function_definition}]
# 指定函式時,tool_choice 的外層也要一起更換。
choice = {"type": "function", "function": {"name": "get_weather"}}
# 每筆結果以原呼叫 ID 配對,不再只用函式名稱。
tool_result_message = {
    "role": "tool", "tool_call_id": call.id,
    "content": json.dumps(result, ensure_ascii=False),
}

assistant 的完整 tool_calls 訊息與每筆工具結果須成對保留。兩輪執行、拒絕與截斷處理、參數白名單及 handler 的實作見第二篇天氣工具主例。

OpenAI-compatible 介面支援範圍

Azure OpenAI、LLM gateway、自架 model server、vLLM、Ollama compatible server、OpenRouter 及其他代理或雲端平台,各有自己的 /chat/completions 支援範圍。接入時確認 developer、tools、parallel_tool_calls、response_format.json_schema、stream_options.include_usage、service_tier、modalities/audio,以及 system、max_tokens 與回傳欄位的契約。OpenAI 官方 API 與相容服務分別依各自文件實作,單一流程使用一致的工具訊息格式。

任務設定與版本紀錄

各類任務的紀錄、版本與執行方式如下。取樣值與 token 預算見第一篇任務設定,請求設定則由共用函式管理。

任務執行與紀錄項目

情境執行方式與獨有紀錄
一般聊天保存 session 與需要的對話歷史;訊息完成才加入正式紀錄。
技術問答記錄問題所依賴的程式與環境版本,讓除錯結論對得上實際條件。
串流聊天室記錄首段可見文字延遲、總耗時、停止原因、取消/中斷及最後用量。
正式產品請求關聯使用者、feature、environment、版本、completion ID、HTTP request ID 與實際模型/tier。
Prompt 版本比較例如 receipt_extraction_v3,另外保存 schema_version,對照抽取成功率、token 用量、無效結果與使用者修正率。
背景整理例如 nightly_summary_job,不開串流,可評估 Flex;這是一般背景呼叫,並不等於使用獨立的 Batch API。

結構化任務的紀錄與驗證

產品、文字收據、圖片收據、客服分類及文章摘要的 Schema 與請求見第二篇結構化輸出及圖片收據章節。請求紀錄另存 feature、prompt_version、schema_version、模型及驗證結果,供資料、prompt、Schema 與程式的版本比較。

工作額外要留下的紀錄驗證位置
文字或圖片收據輸入來源、抽取版本、欄位缺失、使用者修正率。解析後核對日期、幣別、品項與合計;先建立待確認草稿。
客服分類類別分布、轉交結果、誤判與人工修正。對照實際處理流程,必要時調整類別或改用多標籤。
產品或文章摘要來源版本、缺漏重點、額外添加的資訊。比對原始資料;長文先分段時也記錄分段策略。

旅程工具的資料與幣別紀錄

旅程工具的 Schema、授權與執行流程見第二篇旅程花費主例。Request log 保存工具名稱、call ID、旅程內部識別、查詢幣別及狀態,成員帳務資料不重複寫入 metadata。回填幣別須與工具查詢結果一致,換匯則由後端依明確的匯率來源及時間計算。

請求參數與驗證範圍

模型輸出完成、JSON 可解析、Schema 合法及業務操作成功是不同條件。診斷紀錄將輸入、生成、格式、工具及互動狀態分開,才能判斷失敗發生的位置。

控制層參數/資料實作優先順序
模型與上下文model、messages明確能力、成本、速度與應用規則;多輪對話自行保存完整歷史。
生成與格式temperature、top_p、max_completion_tokens、response_format給人閱讀時依風格調整;給程式處理時使用 JSON Schema 與 validation。穩定格式不等於內容正確。
外部資料與工具tools、tool_choice、parallel_tool_calls、tool message解析名稱與參數 → 驗證 → 權限/業務檢查 → 執行 → 依 tool_call_id 回填 → 模型最終回答。
互動體驗stream、stream_options聊天與等待中的互動優先考慮;分類、抽取與背景任務未必需要。分別處理 delta、usage、停止原因與 partial。
多模態content parts、image_url、modalities、audio可用於收據、票券截圖、圖片描述、文件理解、語音摘要或助理。圖片、音訊、檔案及音訊輸出都按模型能力確認,不假設每個模型都支援。
可觀測性store、metadata、識別欄位、usage、request log保存必要的使用者內部 ID、feature、版本、模型、用量、耗時與錯誤,依實際模型/tier 分析成本。
除錯分析logprobs、top_logprobs、舊 seed/fingerprint短答案機率分析與舊紀錄解讀按需使用,避免把它們當正確率或確定性保證。
相容性max_tokens、functions、function_call、舊 SDK維護時看得懂,新實作核對官方建議,遷移整個回傳與回填流程。

Prompt、模型或預算變更以相同測試資料及紀錄比較,分別檢查輸入缺漏、截斷、格式不符、工具失敗及前端中斷。生成品質、資料結構與業務結果各有自己的驗證條件。