# Query Usage and Credits

## Project: Query Usage and Credits

### User Intent

"I want to check my project usage and remaining credits"

### Operation

* **SDK Method**: `graphlit.queryProjectUsage()` or `graphlit.queryProjectCredits()`
* **GraphQL**: `queryProjectUsage` or `queryProjectCredits` query
* **Entity Type**: Project
* **Common Use Cases**: Monitor usage, check credits, track API consumption, billing analysis

### TypeScript (Canonical)

```typescript
import { Graphlit } from 'graphlit-client';
import { Types } from 'graphlit-client/dist/generated/graphql-types';

const graphlit = new Graphlit();

// Query usage for date range
const startDate = new Date('2024-01-01');
const endDate = new Date();

const usageResponse = await graphlit.queryProjectUsage(
  startDate,
  endDate
);

console.log('=== PROJECT USAGE ===');
console.log(`Period: ${startDate.toLocaleDateString()} - ${endDate.toLocaleDateString()}`);
console.log(`\nAPI Calls: ${usageResponse.usage?.length || 0} records`);

// Show usage breakdown
usageResponse.usage?.forEach(record => {
  console.log(`\n${record.date}:`);
  console.log(`  Tokens: ${record.tokens || 0}`);
  console.log(`  Storage: ${record.storage || 0} bytes`);
});

// Query remaining credits
const creditsResponse = await graphlit.queryProjectCredits();

console.log('\n=== CREDITS ===');
console.log(`Remaining: $${creditsResponse.credits?.remaining || 0}`);
console.log(`Total: $${creditsResponse.credits?.total || 0}`);
console.log(`Used: $${(creditsResponse.credits?.total || 0) - (creditsResponse.credits?.remaining || 0)}`);
```

## Query usage (snake\_case)

start\_date = datetime(2024, 1, 1) end\_date = datetime.now()

usage\_response = await graphlit.queryProjectUsage( start\_date=start\_date, end\_date=end\_date )

print("=== PROJECT USAGE ===") print(f"API Calls: {len(usage\_response.usage or \[])}")

## Query credits

credits\_response = await graphlit.queryProjectCredits()

print("\n=== CREDITS ===") print(f"Remaining: ${credits\_response.credits.remaining or 0}") print(f"Total: ${credits\_response.credits.total or 0}")

````

**C#**:
```csharp
using Graphlit;

var client = new Graphlit();

// Query usage (PascalCase)
var startDate = new DateTime(2024, 1, 1);
var endDate = DateTime.Now;

var usageResponse = await graphlit.QueryProjectUsage(
    startDate: startDate,
    endDate: endDate
);

Console.WriteLine("=== PROJECT USAGE ===");
Console.WriteLine($"API Calls: {usageResponse.Usage?.Count ?? 0}");

// Query credits
var creditsResponse = await graphlit.QueryProjectCredits();

Console.WriteLine("\n=== CREDITS ===");
Console.WriteLine($"Remaining: ${creditsResponse.Credits?.Remaining ?? 0}");
Console.WriteLine($"Total: ${creditsResponse.Credits?.Total ?? 0}");
````

### Parameters

#### queryProjectUsage

* **`startDate`** (Date): Start of date range
* **`endDate`** (Date): End of date range

#### queryProjectCredits

* No parameters required

### Response

#### queryProjectUsage

```typescript
{
  usage: UsageRecord[];
}

interface UsageRecord {
  date: string;
  tokens: number;
  storage: number;
  // Other usage metrics
}
```

#### queryProjectCredits

```typescript
{
  credits: {
    remaining: number;  // Remaining credits ($)
    total: number;      // Total credits ($)
  }
}
```

### Developer Hints

#### Usage Tracking

**Important**: Usage is tracked by date. Query specific date ranges for analysis.

```typescript
// Current month usage
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

const monthUsage = await graphlit.queryProjectUsage(
  startOfMonth,
  now
);

console.log(`Current month usage: ${monthUsage.usage?.length || 0} records`);
```

#### Credit Monitoring

```typescript
// Check if running low on credits
const credits = await graphlit.queryProjectCredits();
const remaining = credits.credits?.remaining || 0;

if (remaining < 10) {
  console.log(' Low credits! Add more to continue.');
} else {
  console.log(` Credits remaining: $${remaining}`);
}
```

#### Usage Analysis

```typescript
// Analyze usage over time
const usage = await graphlit.queryProjectUsage(
  new Date('2024-01-01'),
  new Date()
);

const totalTokens = usage.usage?.reduce((sum, record) => 
  sum + (record.tokens || 0), 0
) || 0;

const totalStorage = usage.usage?.reduce((sum, record) => 
  sum + (record.storage || 0), 0
) || 0;

console.log(`Total tokens: ${totalTokens.toLocaleString()}`);
console.log(`Total storage: ${(totalStorage / 1024 / 1024).toFixed(2)} MB`);
```

### Variations

#### 1. Check Current Credits

Get credit balance:

```typescript
const credits = await graphlit.queryProjectCredits();

console.log(`Credits remaining: $${credits.credits?.remaining || 0}`);
```

#### 2. Current Month Usage

This month's usage:

```typescript
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

const usage = await graphlit.queryProjectUsage(startOfMonth, now);

console.log(`This month: ${usage.usage?.length || 0} usage records`);
```

#### 3. Last 30 Days Usage

Recent usage:

```typescript
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - 30);

const usage = await graphlit.queryProjectUsage(startDate, endDate);

console.log(`Last 30 days: ${usage.usage?.length || 0} records`);
```

#### 4. Yearly Usage Report

Full year analysis:

```typescript
const year = 2024;
const startDate = new Date(year, 0, 1);
const endDate = new Date(year, 11, 31);

const usage = await graphlit.queryProjectUsage(startDate, endDate);

console.log(`${year} Usage:`);
console.log(`Records: ${usage.usage?.length || 0}`);
```

#### 5. Usage Alert System

Monitor and alert:

```typescript
async function checkUsageAndCredits() {
  // Check credits
  const credits = await graphlit.queryProjectCredits();
  const remaining = credits.credits?.remaining || 0;
  
  if (remaining < 10) {
    console.log('🚨 ALERT: Low credits!');
    console.log(`Only $${remaining} remaining`);
    // Send alert email/notification
  }
  
  // Check recent usage
  const last7Days = new Date();
  last7Days.setDate(last7Days.getDate() - 7);
  
  const usage = await graphlit.queryProjectUsage(last7Days, new Date());
  const recordCount = usage.usage?.length || 0;
  
  if (recordCount > 1000) {
    console.log(' High usage detected in last 7 days');
    console.log(`Records: ${recordCount}`);
  }
}

await checkUsageAndCredits();
```

#### 6. Monthly Cost Report

Generate cost report:

```typescript
async function generateMonthlyCostReport(year: number, month: number) {
  const startDate = new Date(year, month, 1);
  const endDate = new Date(year, month + 1, 0);
  
  const usage = await graphlit.queryProjectUsage(startDate, endDate);
  const credits = await graphlit.queryProjectCredits();
  
  console.log(`=== COST REPORT: ${startDate.toLocaleString('default', { month: 'long' })} ${year} ===\n`);
  
  const totalTokens = usage.usage?.reduce((sum, r) => sum + (r.tokens || 0), 0) || 0;
  const totalStorage = usage.usage?.reduce((sum, r) => sum + (r.storage || 0), 0) || 0;
  
  console.log(`Tokens Used: ${totalTokens.toLocaleString()}`);
  console.log(`Storage Used: ${(totalStorage / 1024 / 1024).toFixed(2)} MB`);
  console.log(`\nCredits Remaining: $${credits.credits?.remaining || 0}`);
  console.log(`Total Credits: $${credits.credits?.total || 0}`);
}

await generateMonthlyCostReport(2024, 0); // January 2024
```

### Common Issues

**Issue**: No usage data returned\
**Solution**: Check date range is correct. Usage may not be recorded for future dates or very old dates.

**Issue**: Credits show zero\
**Solution**: Add credits to your project in the Graphlit Developer Portal.

**Issue**: Usage seems incomplete\
**Solution**: Usage is recorded periodically. Recent usage may not appear immediately.

### Production Example

**Usage monitoring dashboard**:

```typescript
async function usageDashboard() {
  console.log('=== GRAPHLIT USAGE DASHBOARD ===\n');
  
  // Current credits
  const credits = await graphlit.queryProjectCredits();
  const remaining = credits.credits?.remaining || 0;
  const total = credits.credits?.total || 0;
  const used = total - remaining;
  const percentUsed = total > 0 ? (used / total * 100).toFixed(1) : 0;
  
  console.log(' CREDITS:');
  console.log(`   Total: $${total}`);
  console.log(`   Used: $${used} (${percentUsed}%)`);
  console.log(`   Remaining: $${remaining}\n`);
  
  // This month usage
  const now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthUsage = await graphlit.queryProjectUsage(startOfMonth, now);
  
  const monthTokens = monthUsage.usage?.reduce((sum, r) => 
    sum + (r.tokens || 0), 0
  ) || 0;
  
  console.log(' THIS MONTH:');
  console.log(`   API Calls: ${monthUsage.usage?.length || 0}`);
  console.log(`   Tokens: ${monthTokens.toLocaleString()}\n`);
  
  // Last 7 days
  const last7Days = new Date();
  last7Days.setDate(last7Days.getDate() - 7);
  const weekUsage = await graphlit.queryProjectUsage(last7Days, now);
  
  console.log('📈 LAST 7 DAYS:');
  console.log(`   API Calls: ${weekUsage.usage?.length || 0}`);
  
  // Alerts
  if (remaining < 10) {
    console.log('\n🚨 ALERT: Low credits! Add more to continue.');
  }
  
  if ((weekUsage.usage?.length || 0) > 500) {
    console.log('\n High usage detected this week');
  }
}

await usageDashboard();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.graphlit.dev/api-guides/use-cases/production/project-query-usage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
