Skip to content

追蹤 (Tracing)

Agents SDK 內建追蹤功能,能在代理 (agent) 執行期間收集完整的事件紀錄,包括大型語言模型 (LLM) 產生內容、工具呼叫、交接、保護機制 (guardrails),甚至是自訂事件。透過 Traces dashboard,您可以在開發與正式環境中除錯、視覺化並監控您的工作流程。

Note

Tracing is enabled by default. There are two ways to disable tracing:

  1. You can globally disable tracing by setting the env var OPENAI_AGENTS_DISABLE_TRACING=1
  2. You can disable tracing for a single run by setting [agents.run.RunConfig.tracing_disabled][] to True

對於採用零資料保留(Zero Data Retention, ZDR)政策並使用 OpenAI API 的組織,將無法使用追蹤(tracing)功能。

Trace(追蹤)與 Span(區段)

  • Trace(追蹤) 代表單一端到端的「工作流程」操作。它們由多個 Span(區段)組成。Trace 具有以下屬性:
    • workflow_name:這是邏輯上的工作流程或應用程式。例如「程式碼產生」或「客戶服務」。
    • trace_id:追蹤的唯一 ID。如果未提供,系統會自動產生。必須符合格式 trace_<32_alphanumeric>
    • group_id:可選的群組 ID,用於連結同一對話中的多個追蹤。例如,你可以使用聊天串的 ID。
    • disabled:若為 True,則該追蹤不會被記錄。
    • metadata:可選的追蹤中繼資料(metadata)。
  • Span(區段) 代表具有開始與結束時間的操作。Span 具有:
    • started_atended_at 時間戳記
    • trace_id,表示其所屬的 Trace
    • parent_id,指向此 Span 的父 Span(若有)
    • span_data,包含 Span 的相關資訊。例如,AgentSpanData 包含有關 Agent 的資訊,GenerationSpanData 則包含大型語言模型 (LLM) 產生的相關資訊等。

預設追蹤(Default tracing)

預設情況下,SDK 會追蹤以下內容:

  • 整個 Runner.{run, run_sync, run_streamed}() 會被包裝在 trace() 中。
  • 每次執行 agent 時,都會包裝在 agent_span()
  • 大型語言模型 (LLM) 產生的內容會包裝在 generation_span()
  • 每個 Function 工具呼叫都會包裝在 function_span()
  • Guardrails 會包裝在 guardrail_span()
  • Handoffs 會包裝在 handoff_span()
  • 音訊輸入(語音轉文字)會包裝在 transcription_span()
  • 音訊輸出(文字轉語音)會包裝在 speech_span()
  • 相關的音訊 span 可能會被歸屬於 speech_group_span() 之下

預設情況下,trace 的名稱為 "Agent workflow"。如果你使用 trace,可以自行設定名稱;或者你也可以透過 [RunConfig][agents.run.RunConfig] 設定名稱及其他屬性。

此外,你可以設定 自訂 trace 處理器,將 trace 推送到其他目的地(作為替代或輔助目的地)。

更高層級的追蹤(Higher level traces)

有時,你可能希望多次呼叫 run() 都屬於同一個 trace。你可以將整段程式碼包裝在 trace() 中來達成。

from agents import Agent, Runner, trace

async def main():
    agent = Agent(name="Joke generator", instructions="Tell funny jokes.")

    with trace("Joke workflow"): # (1)!
        first_result = await Runner.run(agent, "Tell me a joke")
        second_result = await Runner.run(agent, f"Rate this joke: {first_result.final_output}")
        print(f"Joke: {first_result.final_output}")
        print(f"Rating: {second_result.final_output}")
  1. 因為兩次對 Runner.run 的呼叫都包裹在 with trace() 中,所以這兩次執行會被視為同一個追蹤(trace)的一部分,而不會產生兩個獨立的追蹤。

建立追蹤(Traces)

你可以使用 [trace()][agents.tracing.trace] 函式來建立一個追蹤(trace)。追蹤需要被啟動並結束。你有兩種方式可以做到:

  1. 推薦方式:將 trace 作為 context manager 使用,例如 with trace(...) as my_trace。這樣會在適當的時機自動啟動與結束追蹤。
  2. 你也可以手動呼叫 [trace.start()][agents.tracing.Trace.start] 和 [trace.finish()][agents.tracing.Trace.finish]。

目前的追蹤是透過 Python 的 contextvar 來追蹤的。這表示它能自動處理並發(concurrency)情境。如果你是手動啟動/結束追蹤,你需要將 mark_as_currentreset_current 傳遞給 start()finish() 來更新目前的追蹤。

建立區段(Spans)

你可以使用各種 [*_span()][agents.tracing.create] 方法來建立區段(span)。一般來說,你不需要手動建立區段。系統也提供 [custom_span()][agents.tracing.custom_span] 函式,用於追蹤自訂的區段資訊。

區段會自動屬於目前的追蹤,並且會巢狀於最近的區段之下,這是透過 Python 的 contextvar 來追蹤的。

敏感資料

某些區段可能會擷取潛在的敏感資料。

generation_span() 會儲存大型語言模型 (LLM) 生成的輸入與輸出資料,function_span() 則會儲存函式呼叫的輸入與輸出。這些內容可能包含敏感資料,因此你可以透過 [RunConfig.trace_include_sensitive_data][agents.run.RunConfig.trace_include_sensitive_data] 來停用這些資料的擷取。

同樣地,Audio 區段預設會包含輸入與輸出音訊的 base64 編碼 PCM 資料。你可以透過設定 [VoicePipelineConfig.trace_include_sensitive_audio_data][agents.voice.pipeline_config.VoicePipelineConfig.trace_include_sensitive_audio_data] 來停用這些音訊資料的擷取。

自訂追蹤處理器(Tracing Processors)

追蹤的高階架構如下:

  • 初始化時,會建立一個全域的 [TraceProvider][agents.tracing.setup.TraceProvider],負責建立追蹤(traces)。
  • 我們會將 TraceProvider 設定為使用 [BatchTraceProcessor][agents.tracing.processors.BatchTraceProcessor],該處理器會將追蹤/區段(traces/spans)以批次方式傳送給 [BackendSpanExporter][agents.tracing.processors.BackendSpanExporter],並將這些區段與追蹤以批次方式匯出到 OpenAI 後端。

若要自訂這個預設設定,例如將追蹤資料傳送到其他或額外的後端,或修改 exporter 行為,你有兩種選擇:

  1. [add_trace_processor()][agents.tracing.add_trace_processor] 允許你新增額外的追蹤處理器,這些處理器會在追蹤與區段就緒時收到資料。這讓你可以在將追蹤資料傳送到 OpenAI 後端的同時,進行自訂處理。
  2. [set_trace_processors()][agents.tracing.set_trace_processors] 允許你取代預設的處理器,改用你自訂的追蹤處理器。這表示除非你包含一個會將資料傳送到 OpenAI 後端的 TracingProcessor,否則追蹤資料將不會傳送到 OpenAI 後端。

與非 OpenAI 模型一起使用追蹤

你可以在非 OpenAI 模型上使用 OpenAI API 金鑰,來啟用 OpenAI Traces 儀表板上的免費追蹤功能,無需停用追蹤。

import os
from agents import set_tracing_export_api_key, Agent, Runner
from agents.extensions.models.litellm_model import LitellmModel

tracing_api_key = os.environ["OPENAI_API_KEY"]
set_tracing_export_api_key(tracing_api_key)

model = LitellmModel(
    model="your-model-name",
    api_key="your-api-key",
)

agent = Agent(
    name="Assistant",
    model=model,
)

注意事項

  • 可在 Openai Traces 儀表板免費查看追蹤紀錄。

外部追蹤處理器清單