# 使用状況と課金のメトリック

このガイドでは、Copilot SDK アプリケーションからトークン数、コンテキスト ウィンドウ使用率、AI クレジット コスト、アカウント クォータを読み取る方法について説明します。 TypeScript、Python、Go、.NET、Java、Rust の例を示します。

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

> \[!TIP]
> 各例は、複数の言語で機能的に同等です。 TypeScript スニペットは既定で展開されます。折りたたみ可能なブロックから言語を選択して、その SDK で同じロジックを表示します。

## 概要

SDK は、次の 2 つの補完的なメカニズムを使用して使用状況データを表示します。

* **セッション イベント**: ターンの実行時にランタイムが出力するエフェメラル イベント。 これらをサブスクライブして、リアルタイムの API 呼び出しごとのデータを取得します。
* **RPC メソッド**: 要求時に行う要求/応答呼び出し。 累積合計のスナップショットを作成したり、アカウント レベルのクォータを検索したりするには、これらを使用します。

次の表は、各シグナルを公開する API にマップします。

| 信号                        | API                            | Scope   | タイプ |
| ------------------------- | ------------------------------ | ------- | --- |
| 呼び出しごとのトークン数              |                                |         |     |
| `assistant.usage` 出来事     | Session                        | Event   |     |
| コンテキスト ウィンドウの使用率          |                                |         |     |
| `session.usage_info` 出来事  | Session                        | Event   |     |
| コンテキストウィンドウの内訳（要求時）       | `session.metadata.contextInfo` | Session | RPC |
| 累積 AI クレジットとトークンの合計       | `session.usage.getMetrics`     | Session | RPC |
| モデルごとの AI クレジットの価格        | `models.list`                  | サーバー    | RPC |
| アカウント クォータと Premium の相互作用 | `account.getQuota`             | サーバー    | RPC |

> \[!NOTE]
> `session.usage.getMetrics`、 `session.metadata.contextInfo`、および `session.metadata.recomputeContextTokens` は、生成された RPC サーフェスで試験段階としてマークされます。 .NET では `GHCP001` の試験的診断メッセージが出力されます。これは `#pragma warning disable GHCP001`、またはプロジェクト レベルの `<NoWarn>GHCP001</NoWarn>` 設定で抑制できます。 アプリケーションがそれらに依存している場合は、SDK と Copilot CLI ランタイムの両方をピン留めします。

次のフィールド テーブルには、このページの例で使用されているフィールドのみが一覧表示されます。 完全で常に最新のフィールド参照は、生成された SDK の種類と [AUTOTITLE です。AUTOTITLE](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events) は、依存関係のバンプごとに CLI スキーマから再生成されます。 それらを真理の源として扱い、このページをタスク指向のガイドとして扱います。

## 呼び出しごとのトークン数

`assistant.usage` イベントは、モデル API 呼び出しごとに 1 回だけ生成されます (サブエージェントによる呼び出しを含む)。 トークン数と、その1回の呼び出しに対する課金乗数が含まれます。

次の例では、これらのフィールドを使用します。 キャッシュ、推論、待機時間、トレース フィールドなど、完全な一覧については [AUTOTITLE を](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events#assistantusage) 参照してください。

| フィールド          | タイプ      | Description               |
| -------------- | -------- | ------------------------- |
| `model`        | `string` | この呼び出しのモデル識別子             |
| `inputTokens`  | `number` | 使用された入力トークン               |
| `outputTokens` | `number` | 生成された出力トークン               |
| `cost`         | `number` | この呼び出しに適用されるプレミアム リクエスト乗数 |

> \[!TIP]
> `assistant.usage` はエフェメラルであるため、ライブ配信されますが、セッションを再開するときに再生されません。 その後の累積合計を読み取るために、 `session.usage.getMetrics` を呼び出します ( [「累積 AI クレジットとトークンの合計](#accumulated-ai-credit-and-token-totals)」を参照)。

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
session.on("assistant.usage", (event) => {
    const { model, inputTokens, outputTokens, cost } = event.data;
    console.log(
        `${model}: in=${inputTokens ?? 0} out=${outputTokens ?? 0} cost=${cost ?? 0}`,
    );
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
def on_usage(event):
    if event.type == SessionEventType.ASSISTANT_USAGE:
        data = event.data
        print(f"{data.model}: in={data.input_tokens or 0} out={data.output_tokens or 0} cost={data.cost or 0}")

session.on(on_usage)
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
session.On(func(event copilot.SessionEvent) {
    d, ok := event.Data.(*copilot.AssistantUsageData)
    if !ok {
        return
    }
    in, out, cost := int64(0), int64(0), float64(0)
    if d.InputTokens != nil {
        in = *d.InputTokens
    }
    if d.OutputTokens != nil {
        out = *d.OutputTokens
    }
    if d.Cost != nil {
        cost = *d.Cost
    }
    fmt.Printf("%s: in=%d out=%d cost=%g\n", d.Model, in, out, cost)
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
session.On<AssistantUsageEvent>(evt =>
{
    var data = evt.Data;
    Console.WriteLine(
        $"{data.Model}: in={data.InputTokens ?? 0} out={data.OutputTokens ?? 0} cost={data.Cost ?? 0}");
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
session.on(AssistantUsageEvent.class, event -> {
    var data = event.getData();
    long in = data.inputTokens() != null ? data.inputTokens() : 0;
    long out = data.outputTokens() != null ? data.outputTokens() : 0;
    double cost = data.cost() != null ? data.cost() : 0.0;
    System.out.printf("%s: in=%d out=%d cost=%s%n", data.model(), in, out, cost);
});
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
use github_copilot_sdk::session_events::AssistantUsageData;

let mut events = session.subscribe();
while let Ok(event) = events.recv().await {
    if event.event_type == "assistant.usage" {
        if let Some(data) = event.typed_data::<AssistantUsageData>() {
            println!(
                "{}: in={} out={} cost={}",
                data.model,
                data.input_tokens.unwrap_or(0),
                data.output_tokens.unwrap_or(0),
                data.cost.unwrap_or(0.0),
            );
        }
    }
}
```

</div>

</div>

## コンテキスト ウィンドウの使用率

トークン数は、各呼び出しで使用された内容を示します。 コンテキスト ウィンドウの使用率は、モデルのプロンプト ウィンドウが現在どの程度満たされているかを示します。これは、自動圧縮が開始される前に進行状況バーを表示したり、ユーザーに警告したりするのに役立ちます。

### `session.usage_info` によるリアルタイム更新

ランタイムは、コンテキスト ウィンドウのサイズが変更されるたびに、 `session.usage_info` イベントを生成します。 この例では、 `currentTokens` と `tokenLimit`を使用しています。完全なペイロードについては [ストリーミング セッション イベント](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events#sessionusage_info) を参照してください。

| フィールド           | タイプ      | Description              |
| --------------- | -------- | ------------------------ |
| `currentTokens` | `number` | 現在コンテキスト ウィンドウ内のトークン     |
| `tokenLimit`    | `number` | モデルのコンテキスト ウィンドウの最大トークン数 |

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
session.on("session.usage_info", (event) => {
    const { currentTokens, tokenLimit } = event.data;
    const pct = Math.round((currentTokens / tokenLimit) * 100);
    console.log(`Context: ${currentTokens}/${tokenLimit} (${pct}%)`);
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
def on_usage_info(event):
    if event.type == SessionEventType.SESSION_USAGE_INFO:
        data = event.data
        pct = round(data.current_tokens / data.token_limit * 100)
        print(f"Context: {data.current_tokens}/{data.token_limit} ({pct}%)")

session.on(on_usage_info)
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
session.On(func(event copilot.SessionEvent) {
    d, ok := event.Data.(*copilot.SessionUsageInfoData)
    if !ok {
        return
    }
    pct := int(float64(d.CurrentTokens) / float64(d.TokenLimit) * 100)
    fmt.Printf("Context: %d/%d (%d%%)\n", d.CurrentTokens, d.TokenLimit, pct)
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
session.On<SessionUsageInfoEvent>(evt =>
{
    var pct = (int)Math.Round((double)evt.Data.CurrentTokens / evt.Data.TokenLimit * 100);
    Console.WriteLine($"Context: {evt.Data.CurrentTokens}/{evt.Data.TokenLimit} ({pct}%)");
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
session.on(SessionUsageInfoEvent.class, event -> {
    var data = event.getData();
    long pct = Math.round((double) data.currentTokens() / data.tokenLimit() * 100);
    System.out.printf("Context: %d/%d (%d%%)%n", data.currentTokens(), data.tokenLimit(), pct);
});
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
use github_copilot_sdk::session_events::SessionUsageInfoData;

let mut events = session.subscribe();
while let Ok(event) = events.recv().await {
    if event.event_type == "session.usage_info" {
        if let Some(data) = event.typed_data::<SessionUsageInfoData>() {
            let pct = (data.current_tokens as f64 / data.token_limit as f64 * 100.0) as i64;
            println!("Context: {}/{} ({}%)", data.current_tokens, data.token_limit, pct);
        }
    }
}
```

</div>

</div>

### `session.metadata.contextInfo` を使用したオンデマンドの内訳

イベントは、コンテキストが変更されたときにのみ発生します。 セッションの再開直後など、いつでも現在の内訳を読み取るために、 `session.metadata.contextInfo`を呼び出します。 ランタイムの既定値を使用する`promptTokenLimit`の`0`を渡します。値が不明な場合は、`outputTokenLimit`に`0`を渡します。

結果の `contextInfo` は、セッションが初期化されるまで `null` されます (システム プロンプトとツールメタデータがキャッシュされています)。 合計は、`promptTokenLimit`と共に`systemTokens`、`conversationTokens`、`toolDefinitionsTokens`に分割されます。

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
const { contextInfo } = await session.rpc.metadata.contextInfo({
    promptTokenLimit: 0,
    outputTokenLimit: 0,
});

if (contextInfo) {
    console.log(
        `Total ${contextInfo.totalTokens}/${contextInfo.promptTokenLimit} ` +
            `(system=${contextInfo.systemTokens}, conversation=${contextInfo.conversationTokens})`,
    );
}
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
result = await session.rpc.metadata.context_info(
    MetadataContextInfoRequest(prompt_token_limit=0, output_token_limit=0)
)
info = result.context_info

if info is not None:
    print(
        f"Total {info.total_tokens}/{info.prompt_token_limit} "
        f"(system={info.system_tokens}, conversation={info.conversation_tokens})"
    )
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
result, _ := session.RPC.Metadata.ContextInfo(ctx, &rpc.MetadataContextInfoRequest{
    PromptTokenLimit: 0,
    OutputTokenLimit: 0,
})

if info := result.ContextInfo; info != nil {
    fmt.Printf("Total %d/%d (system=%d, conversation=%d)\n",
        info.TotalTokens, info.PromptTokenLimit, info.SystemTokens, info.ConversationTokens)
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var result = await session.Rpc.Metadata.ContextInfoAsync(promptTokenLimit: 0, outputTokenLimit: 0);
var info = result.ContextInfo;

if (info is not null)
{
    Console.WriteLine(
        $"Total {info.TotalTokens}/{info.PromptTokenLimit} " +
        $"(system={info.SystemTokens}, conversation={info.ConversationTokens})");
}
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
var result = session.getRpc().metadata
    .contextInfo(new SessionMetadataContextInfoParams(null, 0L, 0L, null))
    .join();
var info = result.contextInfo();

if (info != null) {
    System.out.printf("Total %d/%d (system=%d, conversation=%d)%n",
        info.totalTokens(), info.promptTokenLimit(), info.systemTokens(), info.conversationTokens());
}
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
use github_copilot_sdk::rpc::MetadataContextInfoRequest;

let result = session
    .rpc()
    .metadata()
    .context_info(MetadataContextInfoRequest {
        prompt_token_limit: 0,
        output_token_limit: 0,
        selected_model: None,
    })
    .await?;

if let Some(info) = result.context_info {
    println!(
        "Total {}/{} (system={}, conversation={})",
        info.total_tokens, info.prompt_token_limit, info.system_tokens, info.conversation_tokens,
    );
}
```

</div>

</div>

## 累積 AI クレジットとトークンの合計

`session.usage.getMetrics` は、1 回の呼び出しでセッション全体の実行合計を返します。 これは、すべての API 呼び出し (メイン エージェントとサブエージェント) を集計するため、AI クレジット コストを読み取る最もクリーンな方法です。

この例では、次のフィールドを使用します。 生成された `UsageGetMetricsResult` 型は完全な参照です。

| フィールド                     | タイプ                           | Description                                                                    |
| ------------------------- | ----------------------------- | ------------------------------------------------------------------------------ |
| `totalNanoAiu`            | `number`                      | セッション全体の AI クレジット コスト (nano-AI ユニット単位)                                         |
| `totalPremiumRequestCost` | `number`                      | すべてのモデルにおける、乗数適用後の Premium リクエスト コスト                                           |
| `modelMetrics`            | `Record<string, ModelMetric>` | モデルごとの内訳。各エントリには、 `usage.inputTokens`、 `usage.outputTokens`、および `totalNanoAiu` |

> \[!NOTE]
> コストは **nano-AI ユニット** で報告されます (フィールドの名前は `totalNanoAiu`)。 AI クレジットへの正確な変換と Premium 要求アカウンティングの正確な意味は、SDK ではなくGitHub Copilot課金によって定義されます。[GitHubのCopilot課金ドキュメント](/ja/enterprise-cloud@latest/copilot/concepts/billing)を真実のソースとして扱い、通貨のような値をユーザーに表示する前に検証します。 例では、便宜上、SI の `1e9` 接頭辞に従って `nano` で除算しています。これを当てにする前に、現在の請求と一致していることを確認してください。
> `modelMetrics`マップと`tokenDetails` マップは、SDK 型システムが検証しないランタイム文字列 (モデル ID とトークン型名) によってキー付けされます。

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
const metrics = await session.rpc.usage.getMetrics();

const aiCredits = (metrics.totalNanoAiu ?? 0) / 1e9;
console.log(`AI credits used: ${aiCredits.toFixed(6)}`);
console.log(`Premium requests: ${metrics.totalPremiumRequestCost}`);

for (const [model, m] of Object.entries(metrics.modelMetrics)) {
    if (!m) continue;
    console.log(
        `${model}: in=${m.usage.inputTokens} out=${m.usage.outputTokens} ` +
            `nanoAiu=${m.totalNanoAiu ?? 0}`,
    );
}
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
metrics = await session.rpc.usage.get_metrics()

ai_credits = (metrics.total_nano_aiu or 0) / 1e9
print(f"AI credits used: {ai_credits:.6f}")
print(f"Premium requests: {metrics.total_premium_request_cost}")

for model, m in metrics.model_metrics.items():
    print(f"{model}: in={m.usage.input_tokens} out={m.usage.output_tokens} nanoAiu={m.total_nano_aiu or 0}")
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
metrics, _ := session.RPC.Usage.GetMetrics(ctx)

aiCredits := float64(0)
if metrics.TotalNanoAiu != nil {
    aiCredits = *metrics.TotalNanoAiu / 1e9
}
fmt.Printf("AI credits used: %.6f\n", aiCredits)
fmt.Printf("Premium requests: %v\n", metrics.TotalPremiumRequestCost)

for model, m := range metrics.ModelMetrics {
    nanoAiu := float64(0)
    if m.TotalNanoAiu != nil {
        nanoAiu = *m.TotalNanoAiu
    }
    fmt.Printf("%s: in=%d out=%d nanoAiu=%v\n", model, m.Usage.InputTokens, m.Usage.OutputTokens, nanoAiu)
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var metrics = await session.Rpc.Usage.GetMetricsAsync();

var aiCredits = (metrics.TotalNanoAiu ?? 0) / 1e9;
Console.WriteLine($"AI credits used: {aiCredits:F6}");
Console.WriteLine($"Premium requests: {metrics.TotalPremiumRequestCost}");

foreach (var (model, m) in metrics.ModelMetrics)
{
    Console.WriteLine(
        $"{model}: in={m.Usage.InputTokens} out={m.Usage.OutputTokens} nanoAiu={m.TotalNanoAiu ?? 0}");
}
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
var metrics = session.getRpc().usage.getMetrics().join();

double aiCredits = metrics.totalNanoAiu() != null ? metrics.totalNanoAiu() / 1e9 : 0;
System.out.printf("AI credits used: %.6f%n", aiCredits);
System.out.printf("Premium requests: %s%n", metrics.totalPremiumRequestCost());

metrics.modelMetrics().forEach((model, m) -> {
    double nanoAiu = m.totalNanoAiu() != null ? m.totalNanoAiu() : 0;
    System.out.printf("%s: in=%d out=%d nanoAiu=%s%n",
        model, m.usage().inputTokens(), m.usage().outputTokens(), nanoAiu);
});
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
let metrics = session.rpc().usage().get_metrics().await?;

let ai_credits = metrics.total_nano_aiu.unwrap_or(0.0) / 1e9;
println!("AI credits used: {ai_credits:.6}");
println!("Premium requests: {}", metrics.total_premium_request_cost);

for (model, m) in &metrics.model_metrics {
    let nano_aiu = m.total_nano_aiu.unwrap_or(0.0);
    println!(
        "{model}: in={} out={} nanoAiu={nano_aiu}",
        m.usage.input_tokens, m.usage.output_tokens,
    );
}
```

</div>

</div>

## モデルごとの AI クレジットの価格

ターンを実行する前にコストを見積もるために、各モデルのトークン価格を `models.list`から読み取ってください。 これはクライアントでのサーバー スコープの呼び出しであるため、セッションは必要ありません。 価格は、トークンの課金バッチごとに AI クレジットで表されます。 生成された `ModelBillingTokenPrices` 型には、 `cachePrice`を含むすべてのフィールドが一覧表示されます。

| フィールド                             | タイプ      | Description                 |
| --------------------------------- | -------- | --------------------------- |
| `billing.multiplier`              | `number` | 基本レートに対する Premium 要求コスト乗数   |
| `billing.tokenPrices.inputPrice`  | `number` | 入力トークンのバッチあたりの AI クレジット コスト |
| `billing.tokenPrices.outputPrice` | `number` | 出力トークンのバッチあたりの AI クレジット コスト |
| `billing.tokenPrices.batchSize`   | `number` | 課金バッチあたりのトークン数              |

> \[!NOTE]
> 価格の値は、プランとモデルの進化に伴って変化します。 次に示すように、実行時にそれらを読み取ります。アプリケーションに番号をハードコーディングしないでください。

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
const { models } = await client.rpc.models.list({});

for (const model of models) {
    const prices = model.billing?.tokenPrices;
    if (!prices) continue;
    console.log(
        `${model.id}: input=${prices.inputPrice} output=${prices.outputPrice} ` +
            `per ${prices.batchSize} tokens (x${model.billing?.multiplier ?? 1})`,
    );
}
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
result = await client.rpc.models.list(ModelsListRequest())

for model in result.models:
    prices = model.billing.token_prices if model.billing else None
    if prices is None:
        continue
    multiplier = model.billing.multiplier if model.billing else 1
    print(
        f"{model.id}: input={prices.input_price} output={prices.output_price} "
        f"per {prices.batch_size} tokens (x{multiplier})"
    )
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
list, _ := client.RPC.Models.List(ctx, &rpc.ModelsListRequest{})

for _, model := range list.Models {
    if model.Billing == nil || model.Billing.TokenPrices == nil {
        continue
    }
    prices := model.Billing.TokenPrices
    multiplier := 1.0
    if model.Billing.Multiplier != nil {
        multiplier = *model.Billing.Multiplier
    }
    in, out := 0.0, 0.0
    if prices.InputPrice != nil {
        in = *prices.InputPrice
    }
    if prices.OutputPrice != nil {
        out = *prices.OutputPrice
    }
    batch := int64(0)
    if prices.BatchSize != nil {
        batch = *prices.BatchSize
    }
    fmt.Printf("%s: input=%v output=%v per %d tokens (x%v)\n", model.ID, in, out, batch, multiplier)
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var list = await client.Rpc.Models.ListAsync();

foreach (var model in list.Models)
{
    var prices = model.Billing?.TokenPrices;
    if (prices is null) continue;
    Console.WriteLine(
        $"{model.Id}: input={prices.InputPrice} output={prices.OutputPrice} " +
        $"per {prices.BatchSize} tokens (x{model.Billing?.Multiplier ?? 1})");
}
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
var list = client.getRpc().models.list().join();

for (var model : list.models()) {
    var billing = model.billing();
    if (billing == null || billing.tokenPrices() == null) {
        continue;
    }
    var prices = billing.tokenPrices();
    double multiplier = billing.multiplier() != null ? billing.multiplier() : 1;
    System.out.printf("%s: input=%s output=%s per %d tokens (x%s)%n",
        model.id(), prices.inputPrice(), prices.outputPrice(), prices.batchSize(), multiplier);
}
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
let list = client.rpc().models().list().await?;

for model in &list.models {
    let Some(billing) = &model.billing else { continue };
    let Some(prices) = &billing.token_prices else { continue };
    let multiplier = billing.multiplier.unwrap_or(1.0);
    println!(
        "{}: input={} output={} per {} tokens (x{multiplier})",
        model.id,
        prices.input_price.unwrap_or(0.0),
        prices.output_price.unwrap_or(0.0),
        prices.batch_size.unwrap_or(0),
    );
}
```

</div>

</div>

## アカウント クォータと Premium の相互作用

`account.getQuota`は、認証されたユーザーの残りのCopilot資格を報告します。 結果の `quotaSnapshots` マップは、クォータの種類 (一般的に `premium_interactions`、 `chat`、 `completions`) によってキーが設定されます。 これを使用して、毎月の許容量がどれだけ残っているかをユーザーに示したり、制限に達する前に作業を制限したりします。

この例では、次のフィールドを使用します。生成された `AccountQuotaSnapshot` 型は完全な参照です。
`quotaSnapshots` キーは、SDK 型システムでは検証されないランタイム文字列であるため、参照を保護します。

| フィールド                 | タイプ      | Description                          |
| --------------------- | -------- | ------------------------------------ |
| `entitlementRequests` | `number` | エンタイトルメントに含まれるリクエスト数、または無制限の場合は `-1` |
| `usedRequests`        | `number` | この期間にこれまでに使用された要求                    |
| `remainingPercentage` | `number` | 残りの権利の割合                             |
| `resetDate`           | `string` | クォータがリセットされた ISO 8601 日付             |

> \[!TIP]
> 接続のグローバル認証コンテキスト (マルチテナント バックエンドなど) ではなく、特定のユーザーのクォータを読み取るために、そのユーザーのGitHub トークンを`getQuota`に渡します。 「[マルチテナントとサーバーの展開](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/setup/multi-tenancy)」を参照してください。

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
const { quotaSnapshots } = await client.rpc.account.getQuota({});
const premium = quotaSnapshots["premium_interactions"];

if (premium) {
    console.log(
        `Premium interactions: ${premium.usedRequests}/${premium.entitlementRequests} ` +
            `(${premium.remainingPercentage.toFixed(1)}% left, resets ${premium.resetDate ?? "n/a"})`,
    );
}
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
result = await client.rpc.account.get_quota(AccountGetQuotaRequest())
premium = result.quota_snapshots.get("premium_interactions")

if premium is not None:
    print(
        f"Premium interactions: {premium.used_requests}/{premium.entitlement_requests} "
        f"({premium.remaining_percentage:.1f}% left, resets {premium.reset_date or 'n/a'})"
    )
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
result, _ := client.RPC.Account.GetQuota(ctx, &rpc.AccountGetQuotaRequest{})

if premium, ok := result.QuotaSnapshots["premium_interactions"]; ok {
    resets := "n/a"
    if premium.ResetDate != nil {
        resets = premium.ResetDate.Format(time.RFC3339)
    }
    fmt.Printf("Premium interactions: %d/%d (%.1f%% left, resets %s)\n",
        premium.UsedRequests, premium.EntitlementRequests, premium.RemainingPercentage, resets)
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var result = await client.Rpc.Account.GetQuotaAsync();

if (result.QuotaSnapshots.TryGetValue("premium_interactions", out var premium))
{
    Console.WriteLine(
        $"Premium interactions: {premium.UsedRequests}/{premium.EntitlementRequests} " +
        $"({premium.RemainingPercentage:F1}% left, resets {premium.ResetDate?.ToString("o") ?? "n/a"})");
}
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
var result = client.getRpc().account.getQuota().join();
var premium = result.quotaSnapshots().get("premium_interactions");

if (premium != null) {
    System.out.printf("Premium interactions: %d/%d (%.1f%% left, resets %s)%n",
        premium.usedRequests(), premium.entitlementRequests(),
        premium.remainingPercentage(), premium.resetDate());
}
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
let result = client.rpc().account().get_quota().await?;

if let Some(premium) = result.quota_snapshots.get("premium_interactions") {
    let resets = premium.reset_date.as_deref().unwrap_or("n/a");
    println!(
        "Premium interactions: {}/{} ({:.1}% left, resets {resets})",
        premium.used_requests, premium.entitlement_requests, premium.remaining_percentage,
    );
}
```

</div>

</div>

## 適切な API の選択

この概要を使用して、ユース ケースに適した API を決定します。

* **ターンの実行時にライブ コストまたはトークン メーターをレンダリング**します。 `assistant.usage` と `session.usage_info`をサブスクライブします。
* **ターンまたはセッション後の最終的なコストの概要を表示**する: `session.usage.getMetrics`を呼び出します。
* **新しいターンの前に、再開時にコンテキスト ウィンドウの使用状況を表示**する: `session.metadata.contextInfo`を呼び出します。
* **作業を実行する前にコストを見積も**る: トークンの価格 `models.list` 読み取る。
* **プランを使い果たす前にユーザーに警告**する: `account.getQuota`を呼び出します。

## 詳細については、次を参照してください。

* [ストリーミング セッション イベント](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events): `assistant.usage`、 `session.usage_info`、およびその他のすべてのセッション イベントのフィールド レベルの完全なリファレンス
* [可観測性](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/observability): コスト属性のために使用状況データを OpenTelemetry にエクスポートする
* [マルチテナントとサーバーの展開](/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/setup/multi-tenancy): GitHub トークンを使用してユーザーごとのクォータとモデルを解決する