> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lyzr.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Utilities

> Context compaction helpers and cost tracking for programmatic use.

## Context Compaction

```ts theme={null}
import {
  estimateTokens,
  estimateMessageTokens,
  needsCompaction,
  truncateToolResults,
  buildCompactPrompt
} from "@open-gitagent/gitagent";

// Estimate tokens in a string
const tokens = estimateTokens("Hello world");  // ~3

// Check if compaction needed (triggers at 75% of context window)
// tokenEstimate is also returned and useful for logging
const { needed, ratio, tokenEstimate } = needsCompaction(messages, 200000);
if (needed) console.log(`Context at ${(ratio * 100).toFixed(0)}% — compaction needed`);

// Truncate oversized tool results (keeps first + last half)
const trimmed = truncateToolResults(messages, 10000);

// Build a summarization prompt for the LLM
const prompt = buildCompactPrompt(messages);
```

| Utility               | Description                                                     |
| --------------------- | --------------------------------------------------------------- |
| `estimateTokens`      | Fast approximation: chars/4                                     |
| `needsCompaction`     | Triggers at 75% of model context window                         |
| `truncateToolResults` | Keeps first and last half of large results                      |
| `buildCompactPrompt`  | Generates a prompt asking the LLM to summarize the conversation |

<Tip>
  Call `needsCompaction` before each turn in a long-running session and feed the output of `buildCompactPrompt` back into `query()` to keep token usage under control.
</Tip>

## Cost Tracking

```ts theme={null}
import { query } from "@open-gitagent/gitagent";

const result = query({ prompt: "...", dir: "..." });

for await (const msg of result) { /* ... */ }

const costs = result.costs();
// {
//   startTime: 1716825600000,
//   totalCostUsd: 0.05,
//   totalInputTokens: 5000,
//   totalOutputTokens: 2000,
//   totalRequests: 3,
//   modelUsage: {
//     "anthropic:claude-sonnet-4-6": {
//       inputTokens: 5000,
//       outputTokens: 2000,
//       cacheReadTokens: 0,
//       cacheWriteTokens: 0,
//       totalTokens: 7000,
//       requests: 3,
//       costUsd: 0.05
//     }
//   }
// }
console.log(`Session cost: $${costs.totalCostUsd.toFixed(4)}`);
```

<CardGroup cols={2}>
  <Card title="SDK Reference" icon="code" href="/open-source/gitagent/sdk/overview">
    Full API reference for query(), tool(), buildTool(), and hooks
  </Card>

  <Card title="SDK Quickstart" icon="rocket" href="/open-source/gitagent/sdk/quickstart">
    Install the SDK and run your first query()
  </Card>

  <Card title="Telemetry" icon="chart-line" href="/open-source/gitagent/sdk/telemetry">
    Emit session cost and token usage as OpenTelemetry metrics
  </Card>

  <Card title="Models & Providers" icon="cpu" href="/open-source/gitagent/configuration/models">
    Configure per-model pricing used in cost calculations
  </Card>
</CardGroup>
