{"meta":{"title":"Usage and billing metrics","intro":"This guide shows how to read token counts, context-window utilization, AI credit cost, and account quota from a Copilot SDK application. Examples are shown for TypeScript, Python, Go, .NET, Java, and Rust.","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/enterprise-cloud@latest/copilot","title":"GitHub Copilot"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos","title":"How-tos"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features","title":"Features"},{"href":"/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/usage-and-billing","title":"Usage and billing"}],"documentType":"article"},"body":"# Usage and billing metrics\n\nThis guide shows how to read token counts, context-window utilization, AI credit cost, and account quota from a Copilot SDK application. Examples are shown for TypeScript, Python, Go, .NET, Java, and Rust.\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n> \\[!TIP]\n> Each example is functionally equivalent across languages. The TypeScript snippet is expanded by default; select your language from the collapsible blocks to see the same logic in that SDK.\n\n## Overview\n\nThe SDK surfaces usage data through two complementary mechanisms:\n\n* **Session events**: ephemeral events the runtime emits as a turn runs. Subscribe to these for real-time, per-API-call data.\n* **RPC methods**: request/response calls you make on demand. Use these to snapshot accumulated totals or look up account-level quota.\n\nThe table below maps each signal to the API that exposes it.\n\n| Signal                                 | API                            | Scope   | Type  |\n| -------------------------------------- | ------------------------------ | ------- | ----- |\n| Per-call token counts                  | `assistant.usage` event        | Session | Event |\n| Context-window utilization             | `session.usage_info` event     | Session | Event |\n| Context-window breakdown (on demand)   | `session.metadata.contextInfo` | Session | RPC   |\n| Accumulated AI credit and token totals | `session.usage.getMetrics`     | Session | RPC   |\n| Per-model AI credit pricing            | `models.list`                  | Server  | RPC   |\n| Account quota and premium interactions | `account.getQuota`             | Server  | RPC   |\n\n> \\[!NOTE]\n> `session.usage.getMetrics`, `session.metadata.contextInfo`, and `session.metadata.recomputeContextTokens` are marked experimental in the generated RPC surface. In .NET they raise the `GHCP001` experimental diagnostic, which you suppress with `#pragma warning disable GHCP001` or a project-level `<NoWarn>GHCP001</NoWarn>`. Pin both the SDK and the Copilot CLI runtime if your application depends on them.\n\nThe field tables below list only the fields used in the examples on this page. The complete, always-current field reference is the generated SDK types plus [Streaming session events](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events), which is regenerated from the CLI schema on every dependency bump. Treat those as the source of truth and this page as a task-oriented guide.\n\n## Per-call token counts\n\nThe `assistant.usage` event is emitted once for every model API call in a turn (including calls made by sub-agents). It carries the token counts and the billing multiplier for that single call.\n\nThe example below uses these fields. See [Streaming session events](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events#assistantusage) for the full list, including cache, reasoning, latency, and tracing fields.\n\n| Field          | Type     | Description                                     |\n| -------------- | -------- | ----------------------------------------------- |\n| `model`        | `string` | Model identifier for this call                  |\n| `inputTokens`  | `number` | Input tokens consumed                           |\n| `outputTokens` | `number` | Output tokens produced                          |\n| `cost`         | `number` | Premium request multiplier applied to this call |\n\n> \\[!TIP]\n> `assistant.usage` is ephemeral, so it is delivered live but not replayed when you resume a session. To read accumulated totals after the fact, call `session.usage.getMetrics` (see [Accumulated AI credit and token totals](#accumulated-ai-credit-and-token-totals)).\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nsession.on(\"assistant.usage\", (event) => {\n    const { model, inputTokens, outputTokens, cost } = event.data;\n    console.log(\n        `${model}: in=${inputTokens ?? 0} out=${outputTokens ?? 0} cost=${cost ?? 0}`,\n    );\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\ndef on_usage(event):\n    if event.type == SessionEventType.ASSISTANT_USAGE:\n        data = event.data\n        print(f\"{data.model}: in={data.input_tokens or 0} out={data.output_tokens or 0} cost={data.cost or 0}\")\n\nsession.on(on_usage)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nsession.On(func(event copilot.SessionEvent) {\n    d, ok := event.Data.(*copilot.AssistantUsageData)\n    if !ok {\n        return\n    }\n    in, out, cost := int64(0), int64(0), float64(0)\n    if d.InputTokens != nil {\n        in = *d.InputTokens\n    }\n    if d.OutputTokens != nil {\n        out = *d.OutputTokens\n    }\n    if d.Cost != nil {\n        cost = *d.Cost\n    }\n    fmt.Printf(\"%s: in=%d out=%d cost=%g\\n\", d.Model, in, out, cost)\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nsession.On<AssistantUsageEvent>(evt =>\n{\n    var data = evt.Data;\n    Console.WriteLine(\n        $\"{data.Model}: in={data.InputTokens ?? 0} out={data.OutputTokens ?? 0} cost={data.Cost ?? 0}\");\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nsession.on(AssistantUsageEvent.class, event -> {\n    var data = event.getData();\n    long in = data.inputTokens() != null ? data.inputTokens() : 0;\n    long out = data.outputTokens() != null ? data.outputTokens() : 0;\n    double cost = data.cost() != null ? data.cost() : 0.0;\n    System.out.printf(\"%s: in=%d out=%d cost=%s%n\", data.model(), in, out, cost);\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n```rust\nuse github_copilot_sdk::session_events::AssistantUsageData;\n\nlet mut events = session.subscribe();\nwhile let Ok(event) = events.recv().await {\n    if event.event_type == \"assistant.usage\" {\n        if let Some(data) = event.typed_data::<AssistantUsageData>() {\n            println!(\n                \"{}: in={} out={} cost={}\",\n                data.model,\n                data.input_tokens.unwrap_or(0),\n                data.output_tokens.unwrap_or(0),\n                data.cost.unwrap_or(0.0),\n            );\n        }\n    }\n}\n```\n\n</div>\n\n</div>\n\n## Context-window utilization\n\nToken counts tell you what each call consumed. Context-window utilization tells you how full the model's prompt window is right now—useful for showing a progress bar or warning the user before automatic compaction kicks in.\n\n### Live updates with `session.usage_info`\n\nThe runtime emits a `session.usage_info` event whenever the context-window size changes. The example uses `currentTokens` and `tokenLimit`; see [Streaming session events](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events#sessionusage_info) for the complete payload.\n\n| Field           | Type     | Description                                   |\n| --------------- | -------- | --------------------------------------------- |\n| `currentTokens` | `number` | Tokens currently in the context window        |\n| `tokenLimit`    | `number` | Maximum tokens for the model's context window |\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nsession.on(\"session.usage_info\", (event) => {\n    const { currentTokens, tokenLimit } = event.data;\n    const pct = Math.round((currentTokens / tokenLimit) * 100);\n    console.log(`Context: ${currentTokens}/${tokenLimit} (${pct}%)`);\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\ndef on_usage_info(event):\n    if event.type == SessionEventType.SESSION_USAGE_INFO:\n        data = event.data\n        pct = round(data.current_tokens / data.token_limit * 100)\n        print(f\"Context: {data.current_tokens}/{data.token_limit} ({pct}%)\")\n\nsession.on(on_usage_info)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nsession.On(func(event copilot.SessionEvent) {\n    d, ok := event.Data.(*copilot.SessionUsageInfoData)\n    if !ok {\n        return\n    }\n    pct := int(float64(d.CurrentTokens) / float64(d.TokenLimit) * 100)\n    fmt.Printf(\"Context: %d/%d (%d%%)\\n\", d.CurrentTokens, d.TokenLimit, pct)\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nsession.On<SessionUsageInfoEvent>(evt =>\n{\n    var pct = (int)Math.Round((double)evt.Data.CurrentTokens / evt.Data.TokenLimit * 100);\n    Console.WriteLine($\"Context: {evt.Data.CurrentTokens}/{evt.Data.TokenLimit} ({pct}%)\");\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nsession.on(SessionUsageInfoEvent.class, event -> {\n    var data = event.getData();\n    long pct = Math.round((double) data.currentTokens() / data.tokenLimit() * 100);\n    System.out.printf(\"Context: %d/%d (%d%%)%n\", data.currentTokens(), data.tokenLimit(), pct);\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n```rust\nuse github_copilot_sdk::session_events::SessionUsageInfoData;\n\nlet mut events = session.subscribe();\nwhile let Ok(event) = events.recv().await {\n    if event.event_type == \"session.usage_info\" {\n        if let Some(data) = event.typed_data::<SessionUsageInfoData>() {\n            let pct = (data.current_tokens as f64 / data.token_limit as f64 * 100.0) as i64;\n            println!(\"Context: {}/{} ({}%)\", data.current_tokens, data.token_limit, pct);\n        }\n    }\n}\n```\n\n</div>\n\n</div>\n\n### On-demand breakdown with `session.metadata.contextInfo`\n\nEvents only fire when the context changes. To read the current breakdown at any moment—for example, right after resuming a session—call `session.metadata.contextInfo`. Pass `0` for `promptTokenLimit` to use the runtime default; pass `0` for `outputTokenLimit` if the value is unknown.\n\nThe result's `contextInfo` is `null` until the session has been initialized (the system prompt and tool metadata have been cached). It breaks the total down into `systemTokens`, `conversationTokens`, and `toolDefinitionsTokens`, alongside the `promptTokenLimit`.\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nconst { contextInfo } = await session.rpc.metadata.contextInfo({\n    promptTokenLimit: 0,\n    outputTokenLimit: 0,\n});\n\nif (contextInfo) {\n    console.log(\n        `Total ${contextInfo.totalTokens}/${contextInfo.promptTokenLimit} ` +\n            `(system=${contextInfo.systemTokens}, conversation=${contextInfo.conversationTokens})`,\n    );\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nresult = await session.rpc.metadata.context_info(\n    MetadataContextInfoRequest(prompt_token_limit=0, output_token_limit=0)\n)\ninfo = result.context_info\n\nif info is not None:\n    print(\n        f\"Total {info.total_tokens}/{info.prompt_token_limit} \"\n        f\"(system={info.system_tokens}, conversation={info.conversation_tokens})\"\n    )\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nresult, _ := session.RPC.Metadata.ContextInfo(ctx, &rpc.MetadataContextInfoRequest{\n    PromptTokenLimit: 0,\n    OutputTokenLimit: 0,\n})\n\nif info := result.ContextInfo; info != nil {\n    fmt.Printf(\"Total %d/%d (system=%d, conversation=%d)\\n\",\n        info.TotalTokens, info.PromptTokenLimit, info.SystemTokens, info.ConversationTokens)\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nvar result = await session.Rpc.Metadata.ContextInfoAsync(promptTokenLimit: 0, outputTokenLimit: 0);\nvar info = result.ContextInfo;\n\nif (info is not null)\n{\n    Console.WriteLine(\n        $\"Total {info.TotalTokens}/{info.PromptTokenLimit} \" +\n        $\"(system={info.SystemTokens}, conversation={info.ConversationTokens})\");\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nvar result = session.getRpc().metadata\n    .contextInfo(new SessionMetadataContextInfoParams(null, 0L, 0L, null))\n    .join();\nvar info = result.contextInfo();\n\nif (info != null) {\n    System.out.printf(\"Total %d/%d (system=%d, conversation=%d)%n\",\n        info.totalTokens(), info.promptTokenLimit(), info.systemTokens(), info.conversationTokens());\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n```rust\nuse github_copilot_sdk::rpc::MetadataContextInfoRequest;\n\nlet result = session\n    .rpc()\n    .metadata()\n    .context_info(MetadataContextInfoRequest {\n        prompt_token_limit: 0,\n        output_token_limit: 0,\n        selected_model: None,\n    })\n    .await?;\n\nif let Some(info) = result.context_info {\n    println!(\n        \"Total {}/{} (system={}, conversation={})\",\n        info.total_tokens, info.prompt_token_limit, info.system_tokens, info.conversation_tokens,\n    );\n}\n```\n\n</div>\n\n</div>\n\n## Accumulated AI credit and token totals\n\n`session.usage.getMetrics` returns the running totals for the whole session in a single call. This is the cleanest way to read AI credit cost, because it aggregates every API call (main agent and sub-agents) for you.\n\nThe example uses the fields below. The generated `UsageGetMetricsResult` type is the full reference.\n\n| Field                     | Type                          | Description                                                                                       |\n| ------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------- |\n| `totalNanoAiu`            | `number`                      | Session-wide AI credit cost, in nano-AI units                                                     |\n| `totalPremiumRequestCost` | `number`                      | Premium request cost across all models, after multipliers                                         |\n| `modelMetrics`            | `Record<string, ModelMetric>` | Per-model breakdown; each entry has `usage.inputTokens`, `usage.outputTokens`, and `totalNanoAiu` |\n\n> \\[!NOTE]\n> Cost is reported in **nano-AI units** (the field is named `totalNanoAiu`). The exact conversion to AI credits and the precise meaning of premium request accounting are defined by GitHub Copilot billing, not by the SDK—treat [GitHub's Copilot billing documentation](/en/enterprise-cloud@latest/copilot/concepts/billing) as the source of truth and verify before surfacing currency-like values to users. The examples divide by `1e9` as a convenience, following the SI `nano` prefix; confirm this matches current billing before relying on it. The `modelMetrics` and `tokenDetails` maps are keyed by runtime strings (model IDs and token-type names) that the SDK type system does not validate.\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nconst metrics = await session.rpc.usage.getMetrics();\n\nconst aiCredits = (metrics.totalNanoAiu ?? 0) / 1e9;\nconsole.log(`AI credits used: ${aiCredits.toFixed(6)}`);\nconsole.log(`Premium requests: ${metrics.totalPremiumRequestCost}`);\n\nfor (const [model, m] of Object.entries(metrics.modelMetrics)) {\n    if (!m) continue;\n    console.log(\n        `${model}: in=${m.usage.inputTokens} out=${m.usage.outputTokens} ` +\n            `nanoAiu=${m.totalNanoAiu ?? 0}`,\n    );\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nmetrics = await session.rpc.usage.get_metrics()\n\nai_credits = (metrics.total_nano_aiu or 0) / 1e9\nprint(f\"AI credits used: {ai_credits:.6f}\")\nprint(f\"Premium requests: {metrics.total_premium_request_cost}\")\n\nfor model, m in metrics.model_metrics.items():\n    print(f\"{model}: in={m.usage.input_tokens} out={m.usage.output_tokens} nanoAiu={m.total_nano_aiu or 0}\")\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nmetrics, _ := session.RPC.Usage.GetMetrics(ctx)\n\naiCredits := float64(0)\nif metrics.TotalNanoAiu != nil {\n    aiCredits = *metrics.TotalNanoAiu / 1e9\n}\nfmt.Printf(\"AI credits used: %.6f\\n\", aiCredits)\nfmt.Printf(\"Premium requests: %v\\n\", metrics.TotalPremiumRequestCost)\n\nfor model, m := range metrics.ModelMetrics {\n    nanoAiu := float64(0)\n    if m.TotalNanoAiu != nil {\n        nanoAiu = *m.TotalNanoAiu\n    }\n    fmt.Printf(\"%s: in=%d out=%d nanoAiu=%v\\n\", model, m.Usage.InputTokens, m.Usage.OutputTokens, nanoAiu)\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nvar metrics = await session.Rpc.Usage.GetMetricsAsync();\n\nvar aiCredits = (metrics.TotalNanoAiu ?? 0) / 1e9;\nConsole.WriteLine($\"AI credits used: {aiCredits:F6}\");\nConsole.WriteLine($\"Premium requests: {metrics.TotalPremiumRequestCost}\");\n\nforeach (var (model, m) in metrics.ModelMetrics)\n{\n    Console.WriteLine(\n        $\"{model}: in={m.Usage.InputTokens} out={m.Usage.OutputTokens} nanoAiu={m.TotalNanoAiu ?? 0}\");\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nvar metrics = session.getRpc().usage.getMetrics().join();\n\ndouble aiCredits = metrics.totalNanoAiu() != null ? metrics.totalNanoAiu() / 1e9 : 0;\nSystem.out.printf(\"AI credits used: %.6f%n\", aiCredits);\nSystem.out.printf(\"Premium requests: %s%n\", metrics.totalPremiumRequestCost());\n\nmetrics.modelMetrics().forEach((model, m) -> {\n    double nanoAiu = m.totalNanoAiu() != null ? m.totalNanoAiu() : 0;\n    System.out.printf(\"%s: in=%d out=%d nanoAiu=%s%n\",\n        model, m.usage().inputTokens(), m.usage().outputTokens(), nanoAiu);\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n```rust\nlet metrics = session.rpc().usage().get_metrics().await?;\n\nlet ai_credits = metrics.total_nano_aiu.unwrap_or(0.0) / 1e9;\nprintln!(\"AI credits used: {ai_credits:.6}\");\nprintln!(\"Premium requests: {}\", metrics.total_premium_request_cost);\n\nfor (model, m) in &metrics.model_metrics {\n    let nano_aiu = m.total_nano_aiu.unwrap_or(0.0);\n    println!(\n        \"{model}: in={} out={} nanoAiu={nano_aiu}\",\n        m.usage.input_tokens, m.usage.output_tokens,\n    );\n}\n```\n\n</div>\n\n</div>\n\n## Per-model AI credit pricing\n\nTo estimate cost before you run a turn, read each model's token prices from `models.list`. This is a server-scoped call on the client, so it does not need a session. Prices are expressed in AI credits per billing batch of tokens. The generated `ModelBillingTokenPrices` type lists every field, including `cachePrice`.\n\n| Field                             | Type     | Description                                               |\n| --------------------------------- | -------- | --------------------------------------------------------- |\n| `billing.multiplier`              | `number` | Premium request cost multiplier relative to the base rate |\n| `billing.tokenPrices.inputPrice`  | `number` | AI credit cost per batch of input tokens                  |\n| `billing.tokenPrices.outputPrice` | `number` | AI credit cost per batch of output tokens                 |\n| `billing.tokenPrices.batchSize`   | `number` | Number of tokens per billing batch                        |\n\n> \\[!NOTE]\n> Price values change as plans and models evolve. Read them at runtime as shown below; never hard-code the numbers into your application.\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nconst { models } = await client.rpc.models.list({});\n\nfor (const model of models) {\n    const prices = model.billing?.tokenPrices;\n    if (!prices) continue;\n    console.log(\n        `${model.id}: input=${prices.inputPrice} output=${prices.outputPrice} ` +\n            `per ${prices.batchSize} tokens (x${model.billing?.multiplier ?? 1})`,\n    );\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nresult = await client.rpc.models.list(ModelsListRequest())\n\nfor model in result.models:\n    prices = model.billing.token_prices if model.billing else None\n    if prices is None:\n        continue\n    multiplier = model.billing.multiplier if model.billing else 1\n    print(\n        f\"{model.id}: input={prices.input_price} output={prices.output_price} \"\n        f\"per {prices.batch_size} tokens (x{multiplier})\"\n    )\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nlist, _ := client.RPC.Models.List(ctx, &rpc.ModelsListRequest{})\n\nfor _, model := range list.Models {\n    if model.Billing == nil || model.Billing.TokenPrices == nil {\n        continue\n    }\n    prices := model.Billing.TokenPrices\n    multiplier := 1.0\n    if model.Billing.Multiplier != nil {\n        multiplier = *model.Billing.Multiplier\n    }\n    in, out := 0.0, 0.0\n    if prices.InputPrice != nil {\n        in = *prices.InputPrice\n    }\n    if prices.OutputPrice != nil {\n        out = *prices.OutputPrice\n    }\n    batch := int64(0)\n    if prices.BatchSize != nil {\n        batch = *prices.BatchSize\n    }\n    fmt.Printf(\"%s: input=%v output=%v per %d tokens (x%v)\\n\", model.ID, in, out, batch, multiplier)\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nvar list = await client.Rpc.Models.ListAsync();\n\nforeach (var model in list.Models)\n{\n    var prices = model.Billing?.TokenPrices;\n    if (prices is null) continue;\n    Console.WriteLine(\n        $\"{model.Id}: input={prices.InputPrice} output={prices.OutputPrice} \" +\n        $\"per {prices.BatchSize} tokens (x{model.Billing?.Multiplier ?? 1})\");\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nvar list = client.getRpc().models.list().join();\n\nfor (var model : list.models()) {\n    var billing = model.billing();\n    if (billing == null || billing.tokenPrices() == null) {\n        continue;\n    }\n    var prices = billing.tokenPrices();\n    double multiplier = billing.multiplier() != null ? billing.multiplier() : 1;\n    System.out.printf(\"%s: input=%s output=%s per %d tokens (x%s)%n\",\n        model.id(), prices.inputPrice(), prices.outputPrice(), prices.batchSize(), multiplier);\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n```rust\nlet list = client.rpc().models().list().await?;\n\nfor model in &list.models {\n    let Some(billing) = &model.billing else { continue };\n    let Some(prices) = &billing.token_prices else { continue };\n    let multiplier = billing.multiplier.unwrap_or(1.0);\n    println!(\n        \"{}: input={} output={} per {} tokens (x{multiplier})\",\n        model.id,\n        prices.input_price.unwrap_or(0.0),\n        prices.output_price.unwrap_or(0.0),\n        prices.batch_size.unwrap_or(0),\n    );\n}\n```\n\n</div>\n\n</div>\n\n## Account quota and premium interactions\n\n`account.getQuota` reports the authenticated user's remaining Copilot entitlement. The result's `quotaSnapshots` map is keyed by quota type—commonly `premium_interactions`, `chat`, and `completions`. Use it to show users how much of their monthly allowance is left, or to gate work before they hit a limit.\n\nThe example uses the fields below; the generated `AccountQuotaSnapshot` type is the full reference. The `quotaSnapshots` keys are runtime strings that the SDK type system does not validate, so guard your lookups.\n\n| Field                 | Type     | Description                                                 |\n| --------------------- | -------- | ----------------------------------------------------------- |\n| `entitlementRequests` | `number` | Requests included in the entitlement, or `-1` for unlimited |\n| `usedRequests`        | `number` | Requests used so far this period                            |\n| `remainingPercentage` | `number` | Percentage of the entitlement remaining                     |\n| `resetDate`           | `string` | ISO 8601 date when the quota resets                         |\n\n> \\[!TIP]\n> To read quota for a specific user rather than the connection's global auth context (for example, in a multi-tenant backend), pass that user's GitHub token to `getQuota`. See [Multi-tenancy and server deployments](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/setup/multi-tenancy).\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nconst { quotaSnapshots } = await client.rpc.account.getQuota({});\nconst premium = quotaSnapshots[\"premium_interactions\"];\n\nif (premium) {\n    console.log(\n        `Premium interactions: ${premium.usedRequests}/${premium.entitlementRequests} ` +\n            `(${premium.remainingPercentage.toFixed(1)}% left, resets ${premium.resetDate ?? \"n/a\"})`,\n    );\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nresult = await client.rpc.account.get_quota(AccountGetQuotaRequest())\npremium = result.quota_snapshots.get(\"premium_interactions\")\n\nif premium is not None:\n    print(\n        f\"Premium interactions: {premium.used_requests}/{premium.entitlement_requests} \"\n        f\"({premium.remaining_percentage:.1f}% left, resets {premium.reset_date or 'n/a'})\"\n    )\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nresult, _ := client.RPC.Account.GetQuota(ctx, &rpc.AccountGetQuotaRequest{})\n\nif premium, ok := result.QuotaSnapshots[\"premium_interactions\"]; ok {\n    resets := \"n/a\"\n    if premium.ResetDate != nil {\n        resets = premium.ResetDate.Format(time.RFC3339)\n    }\n    fmt.Printf(\"Premium interactions: %d/%d (%.1f%% left, resets %s)\\n\",\n        premium.UsedRequests, premium.EntitlementRequests, premium.RemainingPercentage, resets)\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nvar result = await client.Rpc.Account.GetQuotaAsync();\n\nif (result.QuotaSnapshots.TryGetValue(\"premium_interactions\", out var premium))\n{\n    Console.WriteLine(\n        $\"Premium interactions: {premium.UsedRequests}/{premium.EntitlementRequests} \" +\n        $\"({premium.RemainingPercentage:F1}% left, resets {premium.ResetDate?.ToString(\"o\") ?? \"n/a\"})\");\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nvar result = client.getRpc().account.getQuota().join();\nvar premium = result.quotaSnapshots().get(\"premium_interactions\");\n\nif (premium != null) {\n    System.out.printf(\"Premium interactions: %d/%d (%.1f%% left, resets %s)%n\",\n        premium.usedRequests(), premium.entitlementRequests(),\n        premium.remainingPercentage(), premium.resetDate());\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n```rust\nlet result = client.rpc().account().get_quota().await?;\n\nif let Some(premium) = result.quota_snapshots.get(\"premium_interactions\") {\n    let resets = premium.reset_date.as_deref().unwrap_or(\"n/a\");\n    println!(\n        \"Premium interactions: {}/{} ({:.1}% left, resets {resets})\",\n        premium.used_requests, premium.entitlement_requests, premium.remaining_percentage,\n    );\n}\n```\n\n</div>\n\n</div>\n\n## Choosing the right API\n\nUse this summary to decide which API fits your use case:\n\n* **Render a live cost or token meter as a turn runs**: subscribe to `assistant.usage` and `session.usage_info`.\n* **Show a final cost summary after a turn or session**: call `session.usage.getMetrics`.\n* **Display context-window usage on resume, before any new turn**: call `session.metadata.contextInfo`.\n* **Estimate cost before running work**: read `models.list` token prices.\n* **Warn users before they exhaust their plan**: call `account.getQuota`.\n\n## Further reading\n\n* [Streaming session events](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/streaming-events): full field-level reference for `assistant.usage`, `session.usage_info`, and every other session event\n* [Observability](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/observability): export usage data to OpenTelemetry for cost attribution\n* [Multi-tenancy and server deployments](/en/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/setup/multi-tenancy): resolve per-user quota and models with a GitHub token"}