# How Instagit Formats and Displays Token Usage Information in API Responses

> Discover how Instagit formats and displays token usage in API responses. Learn about input, output, and total token counts directly in the footer. Explore the code in src/api.ts and src/index.ts.

- Repository: [Instalabs AI/instagit](https://github.com/instalabsai/instagit)
- Tags: internals
- Published: 2026-02-16

---

**Instagit automatically appends a structured usage footer to every API response that displays input, output, and total token counts alongside subscription tier and remaining credits, parsed from Server-Sent Events in [`src/api.ts`](https://github.com/instalabsAI/instagit/blob/main/src/api.ts) and formatted in [`src/index.ts`](https://github.com/instalabsAI/instagit/blob/main/src/index.ts).**

Instagit, an open-source AI coding assistant from the `instalabsAI/instagit` repository, provides transparent token consumption metrics by formatting and displaying token usage information directly in its responses. This feature helps developers monitor API costs and subscription limits in real-time. The implementation spans three core files that handle data extraction, type definitions, and presentation logic.

## Where Token Usage Data Originates

Instagit captures usage metadata from the Instagit API's Server-Sent Events (SSE) stream. When the model finishes generating a response, the server emits a `response.completed` event containing a `usage` object with detailed consumption statistics.

### Parsing the SSE Stream in src/api.ts

The API client in [`src/api.ts`](https://github.com/instalabsAI/instagit/blob/main/src/api.ts) listens for the completion event and extracts the usage payload. At lines 48-55, the code checks for the `response.completed` event type and assigns the usage data:

```typescript
// src/api.ts – line 48-55
if (eventType === "response.completed") {
  usage = (data.response?.usage as Record<string, unknown>) ?? {};
}

```

After the stream concludes, the function constructs a return object that normalizes the usage fields. Lines 34-42 cast the raw usage values to their appropriate types and provide defaults for missing data:

```typescript
// src/api.ts – line 34-42
return {
  text: collectedText,
  inputTokens: (usage.input_tokens as number) ?? 0,
  outputTokens: (usage.output_tokens as number) ?? 0,
  totalTokens: (usage.total_tokens as number) ?? 0,
  tier: (usage.tier as string) ?? "free",
  tokensRemaining: (usage.tokens_remaining as number) ?? 0,
  upgradeHint: (usage.upgrade_hint as string) ?? null,
};

```

### The UsageData Interface in src/types.ts

The structure of the usage object is formally defined in [`src/types.ts`](https://github.com/instalabsAI/instagit/blob/main/src/types.ts) at lines 25-32. The `UsageData` interface specifies all possible fields returned by the Instagit API:

```typescript
// src/types.ts – line 25-32
export interface UsageData {
  input_tokens?: number;
  output_tokens?: number;
  total_tokens?: number;
  tier?: string;
  tokens_remaining?: number;
  upgrade_hint?: string;
}

```

This interface ensures type safety throughout the codebase when handling consumption metrics.

## How Instagit Builds the Usage Footer

Once the API client returns the structured usage data, the main entry point in [`src/index.ts`](https://github.com/instalabsAI/instagit/blob/main/src/index.ts) formats this information into a human-readable footer appended to every response.

### Assembling Footer Components

At lines 33-55, the code constructs an array of footer parts based on which usage fields contain valid data. The logic builds descriptive strings for tokens, tier, and remaining credits:

```typescript
// src/index.ts – line 33-55
let responseText = result!.text;

const footerParts: string[] = [];
if (result!.totalTokens > 0) {
  footerParts.push(
    `Tokens: ${result!.inputTokens.toLocaleString()} input, ` +
    `${result!.outputTokens.toLocaleString()} output, ` +
    `${result!.totalTokens.toLocaleString()} total`
  );
}
if (result!.tier) {
  footerParts.push(`Tier: ${result!.tier}`);
}
if (result!.tokensRemaining > 0) {
  footerParts.push(`Credits remaining: ${result!.tokensRemaining.toLocaleString()}`);
}

```

### Final Response Formatting

The footer components are joined with pipe separators (`|`) and prefixed with a horizontal rule (`---`). If the API provided an upgrade hint, it appears as a separate paragraph after the footer:

```typescript
// src/index.ts – continuation of line 33-55
if (footerParts.length > 0) {
  responseText += "\n\n---\n" + footerParts.join(" | ");
}
if (result!.upgradeHint) {
  responseText += `\n\n${result!.upgradeHint}`;
}

```

The resulting format appears as:

```

<model-generated answer>

---
Tokens: 1,234 input, 567 output, 1,801 total | Tier: free | Credits remaining: 10,000

```

## Code Examples

### Example 1 – Calling Instagit from a Node Script

The following TypeScript example demonstrates how the usage footer appears in a standard API call:

```typescript
import { InstagitClient } from "instagit";

async function demo() {
  const client = new InstagitClient({ apiUrl: "https://api.instagit.com" });
  const reply = await client.chat({
    prompt: "Explain why the sky is blue.",
    onProgress: (status) => console.log("⏳", status),
  });

  console.log("\n=== Full Reply ===\n");
  console.log(reply.text);   // includes the token-usage footer
}

demo();

```

**Typical output:**

```

The sky appears blue because ... (full explanation)

---
Tokens: 84 input | 212 output | 296 total | Tier: free | Credits remaining: 4,876

```

### Example 2 – Inspecting the Raw AnalysisResult Object

For debugging or logging purposes, you can access the structured usage fields directly before they are formatted into the footer:

```typescript
import { InstagitClient } from "instagit";

(async () => {
  const client = new InstagitClient({ apiUrl: "https://api.instagit.com" });
  const result = await client.chat({ prompt: "list the first 5 prime numbers" });

  console.log("Input tokens:", result.inputTokens);
  console.log("Output tokens:", result.outputTokens);
  console.log("Total tokens:", result.totalTokens);
  console.log("Tier:", result.tier);
  console.log("Credits left:", result.tokensRemaining);
})();

```

### Example 3 – Manually Formatting a Footer

To replicate Instagit's formatting logic in a custom client:

```typescript
function formatFooter(r: AnalysisResult): string {
  const parts: string[] = [];

  if (r.totalTokens > 0) {
    parts.push(
      `Tokens: ${r.inputTokens.toLocaleString()} input, ` +
      `${r.outputTokens.toLocaleString()} output, ` +
      `${r.totalTokens.toLocaleString()} total`
    );
  }
  if (r.tier) parts.push(`Tier: ${r.tier}`);
  if (r.tokensRemaining > 0) parts.push(`Credits remaining: ${r.tokensRemaining.toLocaleString()}`);

  const footer = parts.length ? `\n\n---\n${parts.join(" | ")}` : "";
  const hint   = r.upgradeHint ? `\n\n${r.upgradeHint}` : "";
  return `${r.text}${footer}${hint}`;
}

```

## Key Implementation Files

| File | Role | Link |
|------|------|------|
| [`src/types.ts`](https://github.com/instalabsAI/instagit/blob/main/src/types.ts) | Defines `UsageData` and `AnalysisResult` interfaces that structure token consumption data. | [src/types.ts](https://github.com/instalabsAI/instagit/blob/main/src/types.ts) |
| [`src/api.ts`](https://github.com/instalabsAI/instagit/blob/main/src/api.ts) | Handles SSE streaming, extracts the `usage` object from `response.completed` events, and normalizes token counts. | [src/api.ts](https://github.com/instalabsAI/instagit/blob/main/src/api.ts) |
| [`src/index.ts`](https://github.com/instalabsAI/instagit/blob/main/src/index.ts) | Assembles the human-readable footer from usage fields and appends it to the model's response text. | [src/index.ts](https://github.com/instalabsAI/instagit/blob/main/src/index.ts) |

These three files implement the complete pipeline that transforms raw API usage metadata into the formatted footer displayed to end users.

## Summary

- **Instagit captures token usage** from the `response.completed` SSE event in [`src/api.ts`](https://github.com/instalabsAI/instagit/blob/main/src/api.ts), extracting `input_tokens`, `output_tokens`, `total_tokens`, `tier`, and `tokens_remaining`.
- **Type safety** is enforced through the `UsageData` interface defined in [`src/types.ts`](https://github.com/instalabsAI/instagit/blob/main/src/types.ts), which structures all consumption metrics returned by the Instagit API.
- **Footer construction** occurs in [`src/index.ts`](https://github.com/instalabsAI/instagit/blob/main/src/index.ts), where usage data is formatted into a readable string with token counts, tier information, and remaining credits, separated by pipes and preceded by a horizontal rule.
- **Upgrade hints** appear as separate paragraphs after the footer when the API includes an `upgrade_hint` field, encouraging users to upgrade their subscription tier.

## Frequently Asked Questions

### What information appears in Instagit's token usage footer?

The footer displays three categories of information: **token counts** (input, output, and total), the **subscription tier** (such as "free" or "pro"), and **remaining credits** (the number of tokens left in the user's quota). These values are extracted from the `usage` object returned by the Instagit API and formatted with locale-aware number formatting for readability.

### How does Instagit parse token usage data from the API response?

Instagit receives usage metadata through a Server-Sent Events (SSE) stream. When the `response.completed` event fires in [`src/api.ts`](https://github.com/instalabsAI/instagit/blob/main/src/api.ts), the code extracts the `usage` object from `data.response.usage` and maps its fields—`input_tokens`, `output_tokens`, `total_tokens`, `tier`, `tokens_remaining`, and `upgrade_hint`—to a strongly-typed `AnalysisResult` object that is passed to the formatting layer.

### Can I customize the format of Instagit's token usage display?

While the default formatting logic is hardcoded in [`src/index.ts`](https://github.com/instalabsAI/instagit/blob/main/src/index.ts), you can replicate the behavior in custom clients by manually constructing the footer using the raw fields available on the `AnalysisResult` object. The standard format joins components with pipe separators (`|`) and prefixes the block with a horizontal rule (`---`), but custom implementations can rearrange or omit fields such as `tier` or `upgradeHint` based on specific application needs.

### Where are the token usage types defined in the Instagit codebase?

The TypeScript interfaces governing token usage are defined in [`src/types.ts`](https://github.com/instalabsAI/instagit/blob/main/src/types.ts). The `UsageData` interface specifies optional fields for `input_tokens`, `output_tokens`, `total_tokens`, `tier`, `tokens_remaining`, and `upgrade_hint`. These types ensure that the SSE parsing logic in [`src/api.ts`](https://github.com/instalabsAI/instagit/blob/main/src/api.ts) and the formatting logic in [`src/index.ts`](https://github.com/instalabsAI/instagit/blob/main/src/index.ts) handle consumption data consistently throughout the application.