# OpenAI Agent SDKの便利で実践的な使い方
🌍 エージェントの「お財布事情」を可視化しましょう。トークン使用量の追跡で、テナント別課金もステップ別モニタリングも実現できます。
Usage API を使えば、実行全体のトークン消費量から、ツール呼び出し・ハンドオフごとの内訳まで、きめ細かくコストを把握できます。
📌 タイトル:Usage
🔗 URL:
🧩 概要
OpenAI Agent SDK の Usage 機能は、エージェント実行のトークン消費を追跡するための仕組みです。`result.context_wrapper.usage` で実行全体の合計トークン数を取得でき、`result.context_wrapper.usage.request_usage_entries` でステップごと(ツール呼び出し・ハンドオフ・ガードレール)の内訳を確認できます。さらに RunHooks の `on_agent_end` でリアルタイムにログを記録したり、サードパーティモデル使用時に `ModelSettings(include_usage=True)` で使用量レポートを有効化したりできます。
🛠 使い方
`Agent(name="Assistant", instructions="ユーザーの質問に回答してください。")` でエージェントを作り、`result = await "量子コンピュータについて教えてください")` を実行します。` で合計・入力・出力トークン数を取得できます。`result.context_wrapper.usage.request_usage_entries` をループすれば、各リクエストの `entry.input_tokens` と `entry.output_tokens` でステップごとの内訳も確認できます。
🏗 実践的な使い方
**テナント/ユーザー別コスト計算**
SaaS で「テナントごとにいくら使ったか」を記録し、課金や予算管理に活用するパターンです。
`handle_request(tenant_id, user_id, message)` のような関数で `result = await message)` を実行し、`calculate_cost(model="gpt-4.1", input_tokens=result.context_wrapper.usage.input_tokens, output_tokens=result.context_wrapper.usage.output_tokens)` でコストを算出、`await billing_db.record(tenant_id=tenant_id, user_id=user_id, total_tokens= cost_usd=cost, timestamp= でテナント別に記録します。
**ステップ別モニタリング**
`request_usage_entries` で、どのツール呼び出しやハンドオフがトークンを消費しているかを特定します。
`result = await "売上レポートを作成して")` の後、`result.context_wrapper.usage.request_usage_entries` を `enumerate` でループし、各ステップの `entry.input_tokens` と `entry.output_tokens` を確認します。`entry.input_tokens > 5000` のような閾値で警告を出せば、トークン消費の多いステップを特定できます。
**RunHooks でリアルタイムログ**
`on_agent_end` フックでエージェント終了時に使用量をログに記録します。
`RunHooks` を継承した `UsageLoggingHooks` クラスを作り、`on_agent_end(self, context: RunContextWrapper, agent: Agent, output)` メソッドで `context.usage` からトークン使用量を取得し、`"agent_completed", agent_name= total_tokens= ...)` で構造化ログに記録します。`await "質問", hooks=UsageLoggingHooks())` のように `hooks` パラメータで渡します。
**サードパーティモデルでの使用量レポート有効化**
OpenAI 以外のモデルアダプタを使う場合、明示的に使用量レポートを有効にする必要があります。
サードパーティモデルでは `Agent(name="ThirdPartyAgent", instructions="...", model=my_custom_model_adapter, model_settings=ModelSettings(include_usage=True))` のように `ModelSettings(include_usage=True)` を明示的に設定して、使用量レポートを有効化します。
💡 ユースケース
💰 テナント別・ユーザー別のトークン消費をDBに記録し、従量課金の基盤を構築
📊 request_usage_entries でステップ別のトークン消費を可視化し、コスト最適化のボトルネックを特定
🔔 RunHooks の on_agent_end で使用量を構造化ログに記録し、リアルタイムでダッシュボード監視
🔌 サードパーティモデル利用時に ModelSettings(include_usage=True) で使用量追跡を漏れなく有効化
⚠️ 注意点
- ` はリトライやガードレール再実行分も含まれるため、表示上のステップ数より多くなる場合があります。
- サードパーティモデルでは `include_usage=True` を設定しないと使用量がゼロで返ることがあります。アダプタのドキュメントを確認してください。
- コスト計算はモデルの料金体系に依存します。モデルごとの入力/出力トークン単価を正確に反映させましょう。
✨ トークン使用量を3つのレベル(合計・ステップ別・フック)で追跡すれば、コスト管理も品質監視も万全です。まずは result.context_wrapper.usage から始めて、必要に応じてステップ別やフックでの追跡を追加していきましょう!
#
OpenAIAgentSDK# #
AIAgent#
もっと見る
Breaking down TSMC's glass core substrate slide
On June 11, at JPCA Show 2026 in Japan, TSMC gave a roughly 40-slide presentation titled "Advanced Packaging Technology Essential to the Evolution of AI" (AIの進化に不可欠な先端パッケージング技術). One slide from the deck, titled "Glass Substrate Development for CoWoS," has since leaked online and widespread attention.
Here's a closer read of that slide (see attached image). I'll skip the technical background that is already widely available. One thing to flag: the "COP" on the slide does not stand for Chip-on-Package. It means Coplanarity.
▌ Key conclusions:
1. TSMC has officially announced a partnership with Ibiden and Innolux to develop a glass core substrate. The structure is a three-layer design, a glass core sandwiched between two ABF build-up layers. This is the "oS" in CoPoS.
2. The market underestimates how important the glass core substrate is. It's a must-have capability for TSMC. In other words, within CoPoS the "oS" matters more than the "CoP", which is also why, when it was tested, it was paired with the existing CoW rather than with CoP.
3. The glass core substrate costs several times more per unit than existing ABF substrates. The glass processed by Innolux is very expensive per unit and is the single most critical material. Besides Nvidia, two US-based customers have also expressed strong interest.
▌ Industry checks tied to this slide:
1. The glass core substrate shown on the slide is cut from a full-size 250×250mm one. The ABF build-up layers mainly use Ajinomoto's GL107, mixed with ABF-GCP, and were tested at 24–28 layers, which is the mainstream ABF spec for AI chips in 2027–2028.
2. The CoW used in TSMC's experiment is a test vehicle. It is sufficient to validate the most challenging mechanical-structure issues that arise when working with composite materials. Good results mean TSMC, Ibiden, and Innolux have together broken through the critical technical bottleneck.
3. Ibiden currently handles cutting the 250×250mm glass core substrate. When the 510×515mm format is used for pre-mass-production simulation in 2H27, if Ibiden still wants to reduce production complexity to protect its ultra-high gross margins, it may hand the cutting over to Innolux, which is more familiar with the properties of glass.
▌ The leaked slide shows the validation results of pairing CoW with the "oS" in CoPoS, i.e., the glass core substrate (labeled "glass-SBT" on the slide). This addresses the "Substrate mechanical and electrical Dilemma" raised on the previous slide, and it strongly underscores how important the "oS" is within CoPoS.
1. Within CoPoS, what CoP solves is production efficiency / cutting economics, which ties to cost and price. What the oS solves is warpage and durability, which determines whether the chip can be made at all, and whether it can work.
2. CoP and oS complement each other well when integrated, but looking out over the next few years their technical roles still differ. CoP is a very-nice-to-have optimization, and going without it simply means a more expensive chip. But the oS is a must-have. Without it, even being able to make a usable chip is in doubt.
3. Comparing their roles isn't about elevating oS at the expense of CoP. It comes down to the practical question of which technical piece customers are willing to pay for. Details below.
▌ The real gold here is the power integrity (PI) improvement shown on the slide. This matters a great deal to customers, and it means that once glass core substrate production stabilizes, TSMC's profitability and competitive edge should rise in tandem.
1. How it works: the glass core substrate is thin → the vertical conduction path through TGV (through-glass vias) is short → conduction-path resistance (R) and loop inductance (L) both drop → PI improves.
2. Why it matters to customers: better PI → more stable power delivery → frees up power headroom → room to integrate more transistors, or to push clock speeds higher → more AI compute.
3. For customers, production efficiency is TSMC's basic responsibility, so they won't pay extra for it. But gains in AI compute translate directly into the customer's own competitiveness and profit, so customers are willing to pay for that. This is why Nvidia is so positive on the glass core substrate.
4. For TSMC, the glass core substrate raises yield and lowers cost while also boosting both the compute and the selling price of AI chips. It's both a cost-cutting tool and a pricing lever, a plus for profitability and competitiveness alike.
5. Substrate cost currently accounts for a low single-digit percentage of an AI chip's BOM, while losses from packaging yield run roughly 5–10× the substrate cost. So even if the glass core substrate ends up costing several times more than today's, its share of the BOM stays low, and it can cut the losses from packaging yield. The high unit price is therefore not expected to dampen customers' willingness to adopt it.
▌ In the Q&A after the presentation, an audience member asked about TGV details for the glass core substrate. TSMC declined to answer on the spot, because TGV is the key technology behind the glass core substrate, and the core know-how currently sits with TSMC and Innolux. By contrast, when another attendee asked about integrating IVR, eDTC, and LSI, TSMC answered at length.
▌ According to industry checks, if all goes well, TSMC is aiming to start mass production of the glass core substrate in 4Q28–1Q29, to match the cadence of Nvidia's AI chip iterations. As a side note: the Ibiden earnings presentation slide that many people have been circulating lists the glass core substrate timeline as CY30. My read is this: Ibiden, which has always been conservative and cautious in public, has now formally put the glass core substrate on its roadmap, which further confirms the long-term trend for this technology. That said, some other details on Ibiden's slide don't fully line up with what's known in the market. For example, its reticle timeline is off from TSMC's public claims by about a generation, and the Rubin Ultra substrate size is clearly larger than the 90×90 it marked for CY26–27. It's a reminder to always cross-check across multiple sources when forecasting the future.
もっと見る