> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.withpaygent.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.withpaygent.com/_mcp/server.

# Manual Tracking

Manual tracking gives you full control when you already know the exact token counts. Use manual tracking when:

* ✓ You're calling AI APIs directly and have access to usage data
* ✓ You want maximum control over what's reported
* ✓ You're tracking non-OpenAI models or custom services
* ✓ You have your own token counting logic

## Example: OpenAI Integration

#### Python

**`manual_openai.py`**

```python title="manual_openai.py"
import os
import paygent_sdk
from paygent_sdk import UsageData
from openai import OpenAI

# Initialize Paygent SDK
paygent = paygent_sdk.init(api_key=os.getenv("PAYGENT_API_KEY"))

openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# Make OpenAI API call
response = openai_client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Explain quantum physics"}]
)

# Extract usage data
usage = response.usage
cached_tokens = 0
if hasattr(usage, 'prompt_tokens_details'):
    cached_tokens = usage.prompt_tokens_details.cached_tokens or 0

# Track with Paygent
usage_data = UsageData(
    service_provider="OpenAI",
    model=response.model,
    prompt_tokens=usage.prompt_tokens,
    completion_tokens=usage.completion_tokens,
    cached_tokens=cached_tokens,
    total_tokens=usage.total_tokens
)

paygent.send_usage("qa-agent", "customer-456", "question-answered", usage_data)
```

> **Info**
>
> **Unified SDK Entrypoint:** `paygent_sdk.init(api_key)` enables automatic patching for LLMs (OpenAI, Gemini, Anthropic) AND returns the `paygent` client object for manual tracking calls (`send_usage`, `send_indicator`, etc.).

> **Tip**
>
> **Standalone Scripts:** Paygent sends tracking events asynchronously on background threads so calling threads are never blocked. In short standalone test scripts (unlike web servers), add `time.sleep(1)` at the end to allow background HTTP requests to complete before the process exits.

> **Tip**
>
> **Automate Onboarding.** To simplify your workflow, call `client.create_or_get_customer()` before tracking usage. This ensures the customer exists in Paygent without needing manual setup in the dashboard.

#### Node.js

**`manual-openai.ts`**

```typescript title="manual-openai.ts"
import { PaygentClient } from '@paygent_org/paygent-sdk-node';
import OpenAI from 'openai';

const paygent = PaygentClient.newClient(process.env.PAYGENT_API_KEY);
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

// Make OpenAI API call
const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Explain quantum computing' }]
});

// Extract usage data from OpenAI response
const usage = response.usage;

// Track with Paygent
await paygent.sendUsage(
  'qa-agent',
  'customer-456',
  'question-answered',
  {
    serviceProvider: 'OpenAI',
    model: response.model,
    promptTokens: usage.prompt_tokens,
    completionTokens: usage.completion_tokens,
    totalTokens: usage.total_tokens
  }
);
```

> **Tip**
>
> **Automate Onboarding.** To simplify your workflow, call `client.createOrGetCustomer()` before tracking usage. This ensures the customer exists in Paygent without needing manual setup in the dashboard.

#### Go

**`manual_openai.go`**

```go title="manual_openai.go"
package main

import (
    "context"
    "os"
    
    paygent "github.com/paygent-org/paygent-sdk-go"
    "github.com/sashabaranov/go-openai"
)

func main() {
    paygentClient := paygent.NewClient(os.Getenv("PAYGENT_API_KEY"))
    openaiClient := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
    
    // Make OpenAI API call
    resp, err := openaiClient.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: "gpt-4o",
            Messages: []openai.ChatCompletionMessage{
                {Role: "user", Content: "Explain quantum physics"},
            },
        },
    )
    if err != nil {
        panic(err)
    }
    
    // Extract usage data
    usage := resp.Usage
    
    // Track with Paygent
    usageData := paygent.UsageData{
        ServiceProvider:  "OpenAI",
        Model:            resp.Model,
        PromptTokens:     usage.PromptTokens,
        CompletionTokens: usage.CompletionTokens,
        TotalTokens:      usage.TotalTokens,
    }
    
    paygentClient.SendUsage(
        "qa-agent",
        "customer-456",
        "question-answered",
        usageData,
    )
}
```

## Example: Gemini Integration

#### Python

**`manual_gemini.py`**

```python title="manual_gemini.py"
import os
import paygent_sdk
from paygent_sdk import UsageData
import google.generativeai as genai

paygent = paygent_sdk.init(api_key=os.getenv("PAYGENT_API_KEY"))
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))

# Make Gemini API call
model = genai.GenerativeModel('gemini-2.0-flash-exp')
response = model.generate_content('Write a poem about AI')

# Extract usage data
metadata = response.usage_metadata

# Track with Paygent
usage_data = UsageData(
    service_provider="Google DeepMind",
    model="gemini-2.0-flash-exp",
    prompt_tokens=metadata.prompt_token_count,
    completion_tokens=metadata.candidates_token_count,
    total_tokens=metadata.total_token_count
)

paygent.send_usage("content-gen", "customer-789", "poem-created", usage_data)
```

#### Node.js

**`manual-gemini.ts`**

```typescript title="manual-gemini.ts"
import { PaygentClient } from '@paygent_org/paygent-sdk-node';
import { GoogleGenerativeAI } from '@google/generative-ai';

const paygent = PaygentClient.newClient(process.env.PAYGENT_API_KEY);
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);

// Make Gemini API call
const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash-exp' });
const result = await model.generateContent('Write a story about AI');

// Extract usage data
const usageMetadata = result.response.usageMetadata;

// Track with Paygent
await paygent.sendUsage(
  'content-generator',
  'customer-789',
  'story-generated',
  {
    serviceProvider: 'Google DeepMind',
    model: 'gemini-2.0-flash-exp',
    promptTokens: usageMetadata.promptTokenCount,
    completionTokens: usageMetadata.candidatesTokenCount,
    totalTokens: usageMetadata.totalTokenCount
  }
);
```

#### Go

*Note: Go Gemini tracking is fundamentally similar. Simply make the call to the Gemini API, extract the token usage metadata from the response, and use `SendUsage` to pass those metrics to Paygent.*