# LLM Gateway — Full Documentation
> LLM Gateway is an open-source, OpenAI-compatible API gateway for routing, managing, and analyzing requests across LLM providers. Use one API key, track usage and cost, configure caching and guardrails, and self-host or use the managed cloud. Current models and pricing: https://llmgateway.io/models
API base URL: https://api.llmgateway.io/v1 · Docs: https://docs.llmgateway.ai-stage.zibl.ir · Site: https://llmgateway.io
This file concatenates the full text of every documentation page below.
## Contents
Start with https://docs.llmgateway.ai-stage.zibl.ir/llms.txt for the full page index. Read a linked Markdown page when you need one topic; this complete file may exceed an agent context window.
- [DevPass](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/devpass)
- [Introduction to LLM Gateway](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/index)
- [Overview](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/overview)
- [Quickstart](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/quick-start)
- [Lounge](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/lounge)
- [Airside](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/airside)
- [Coding tool guides](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/guides)
- [Health check](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/health)
- [Create speech](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_audio_speech)
- [Create transcription](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_audio_transcriptions)
- [Cancel batch](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_batches_cancel)
- [Create batch](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_batches_create)
- [List batches](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_batches_list)
- [Retrieve batch](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_batches_retrieve)
- [Chat Completions](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_chat_completions)
- [Decisions](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_decisions)
- [Embeddings](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_embeddings)
- [Retrieve file content](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_files_content)
- [Upload file](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_files_create)
- [Delete file](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_files_delete)
- [List files](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_files_list)
- [Retrieve file](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_files_retrieve)
- [Edit image](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_images_edits)
- [Create image](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_images_generations)
- [Retrieve key status](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_key_retrieve)
- [Anthropic Messages](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_messages)
- [Models](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_models)
- [Moderations](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_moderations)
- [OCR](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_ocr)
- [Create a realtime client secret](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_realtime_client_secrets)
- [Rerank](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_rerank)
- [Search](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_search)
- [System One](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_systemone)
- [Video content](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_videos_content)
- [Create video](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_videos_create)
- [Video log content](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_videos_log_content)
- [Retrieve video](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/v1_videos_retrieve)
- [Introduction](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/learn)
- [Self Host LLM Gateway](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/self-host)
- [LLM Gateway Developer Resources](https://docs.llmgateway.ai-stage.zibl.ir/llms.mdx/developers)
# DevPass
URL: https://docs.llmgateway.ai-stage.zibl.ir/devpass
DevPass is a monthly subscription for developers who code with AI agents. Instead of topping up credits per request, you pay one flat price and get a monthly allowance that covers the models your tools call. Your DevPass key works anywhere an OpenAI- or Anthropic-compatible key does, so you keep the tools you already use.
## Quick start [#quick-start]
### Pick a plan [#pick-a-plan]
Choose a plan on the [DevPass pricing page](https://devpass.llmgateway.io/pricing). Plans come in three tiers, **Lite**, **Pro**, and **Max**. Higher tiers raise the monthly allowance and the weekly cap on [premium models](https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories).
### Copy your key [#copy-your-key]
Open the [DevPass dashboard](https://devpass.llmgateway.io/dashboard). Rotate the key under **API Key** to reveal it once. The **Quick start** panel next to it then shows the exact setup for each supported tool.
### Point your tool at DevPass [#point-your-tool-at-devpass]
For Claude Code, set two environment variables and run `claude` as usual:
```bash
export ANTHROPIC_BASE_URL=https://api.llmgateway.io
export ANTHROPIC_AUTH_TOKEN=your_devpass_key
claude
```
OpenAI-compatible tools use `OPENAI_BASE_URL=https://api.llmgateway.io/v1` and `OPENAI_API_KEY` instead. Every other tool has its own [setup guide](https://docs.llmgateway.ai-stage.zibl.ir/guides).
### Watch your usage [#watch-your-usage]
Requests appear in [Coding Agents](https://docs.llmgateway.ai-stage.zibl.ir/learn/coding-agents), broken down by tool. Allowance meters on the dashboard show what is left this month and this week.
## Provider fallback [#provider-fallback]
Retryable provider failures, including upstream `429` responses, can immediately fail over to another eligible provider of the same model before output reaches your tool. After a successful replacement, later session turns stay on that provider. DevPass eligibility rules and reasoning portability still apply. See [sticky-session fallback](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#falling-back-when-a-provider-is-down).
## Reasoning effort [#reasoning-effort]
When your coding tool requests a reasoning effort, automatic provider selection
excludes deployments whose declared efforts do not support that level. A session
pin does not override this check. See [reasoning-effort compatibility](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#reasoning-effort-compatibility).
## Automatic cache duration [#automatic-cache-duration]
Under **Settings → Automatic cache duration**, choose **5 minutes** (default) or **1 hour**. Available in Automatic cache-write mode, this controls automatically added markers only when your request contains no cache markers of its own. One hour applies only to supported models and providers; otherwise the default duration is used. Longer durations can increase cache-write costs.
Your tool's own markers take precedence, including markers without a TTL. Client-managed and Disabled modes ignore this preference. See [Provider Cache Control](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/provider-cache-control) for details.
## Unused allowance [#unused-allowance]
Part of the allowance you do not use carries over at renewal. Whatever is left when the plan renews is added to the next cycle's full allowance, up to half of your plan's monthly allowance; anything above that expires.
* The amount is worked out again at every renewal from what is left then, so it never builds up past that cap.
* A plan change at renewal uses the cap of the plan you move to.
* Carried-over allowance counts toward the [daily and weekly shares](https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories) like the rest of the cycle's allowance.
* It ends when the plan ends.
The **Usage** page shows what would carry over if the plan renewed now. An immediate upgrade is different: everything left of the cycle being replaced moves to the new plan.
## Cancel your subscription [#cancel-your-subscription]
Cancel from **Billing** in the DevPass dashboard. A paid plan stays active through its current billing period. If a renewal is unpaid or still pending, cancellation ends the plan immediately and attempts to void its pending invoices. Immediate cancellation stops automatic collection, even if invoice cleanup needs to be retried.
If Stripe's invoice lookup is unavailable, cancellation also ends the plan immediately to prevent further renewal attempts. The confirmation tells you whether the plan ended now or remains active until the period ends.
## Take the tour [#take-the-tour]
## Explore DevPass [#explore-devpass]
## Other products [#other-products]
# Introduction to LLM Gateway
URL: https://docs.llmgateway.ai-stage.zibl.ir/
LLM Gateway is an open-source API gateway that sits between your applications and LLM providers like OpenAI, Anthropic, Google AI Studio, and more. It provides a unified, OpenAI-compatible API interface with built-in cost tracking, caching, and intelligent routing.
## Products [#products]
These docs cover four products. Pick one from the menu at the top of the sidebar, or start here:
## How it works [#how-it-works]
Point your existing SDK at `https://api.llmgateway.io/v1` (or your self-hosted instance) and authenticate with an LLM Gateway API key — no code rewrites. The gateway routes each request to the right provider, tracks tokens and cost per model, provider, project, and API key, and fails over to a healthy provider when one errors. Pay per-token with prepaid credits at provider list rates, or bring your own provider keys (BYOK) for free.
## Why use a gateway? [#why-use-a-gateway]
* **One integration** — switch models or providers by changing a model string, not your code.
* **Cost visibility** — usage analytics and cost breakdowns across every provider in one dashboard.
* **Reliability** — automatic provider failover when a provider fails, plus opt-in response caching per project.
* **No lock-in** — open source (AGPLv3), self-hostable, and OpenAI-compatible end to end.
## Take the tour [#take-the-tour]
## Features [#features]
All features are documented under https://docs.llmgateway.ai-stage.zibl.ir/features; each feature page is included in full in this file.
## AI Tooling [#ai-tooling]
LLM Gateway is built to work seamlessly with AI agents and development tools.
AI tooling: https://docs.llmgateway.ai-stage.zibl.ir/llms.txt (docs index for LLMs), https://docs.llmgateway.ai-stage.zibl.ir/llms-full.txt (this file), https://docs.llmgateway.ai-stage.zibl.ir/developers/mcp (MCP server), https://docs.llmgateway.ai-stage.zibl.ir/guides/agent-skills (agent skills), and https://llmgateway.io/templates (templates and agents).
## Next Steps [#next-steps]
* [**Quickstart**](https://docs.llmgateway.ai-stage.zibl.ir/quick-start) — Get up and running in minutes
* [**Overview**](https://docs.llmgateway.ai-stage.zibl.ir/overview) — Learn more about what LLM Gateway offers
* [**Self-Host**](https://docs.llmgateway.ai-stage.zibl.ir/self-host) — Deploy on your own infrastructure
# Overview
URL: https://docs.llmgateway.ai-stage.zibl.ir/overview
LLM Gateway is an open-source API gateway for Large Language Models (LLMs). It acts as a middleware between your applications and various LLM providers, allowing you to:
* Route requests to multiple LLM providers (OpenAI, Anthropic, Google AI Studio, and others)
* Manage API keys for different providers in one place
* Track token usage and costs across all your LLM interactions
* Analyze performance metrics to optimize your LLM usage
## Analyzing Your LLM Requests [#analyzing-your-llm-requests]
LLM Gateway provides detailed insights into your LLM usage:
* **Usage Metrics**: Track the number of requests, tokens used, and response times
* **Cost Analysis**: Monitor spending across different models and providers
* **Performance Tracking**: Identify patterns and optimize your prompts based on actual usage data
* **Breakdown by Model**: Compare different models' performance and cost-effectiveness
All this data is automatically collected and presented in an intuitive dashboard, helping you make informed decisions about your LLM strategy.
## Getting Started [#getting-started]
Using LLM Gateway is simple. Just swap out your current LLM provider URL with the LLM Gateway API endpoint:
```bash
curl -X POST https://api.llmgateway.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}'
```
LLM Gateway maintains compatibility with the OpenAI API format, making migration seamless. Note that unknown or unsupported request parameters (for example `max_completion_tokens`, `stream_options`, `stop`, `seed`, `logprobs`, or `logit_bias`) are accepted and silently ignored rather than rejected, so a request carrying them still succeeds — the parameter just has no effect. Use `max_tokens` to limit completion length.
## Hosted vs. Self-Hosted [#hosted-vs-self-hosted]
You can use LLM Gateway in two ways:
* **Hosted Version**: For immediate use without setup, visit [llmgateway.io](https://llmgateway.io) to create an account and get an API key.
* **Self-Hosted**: Deploy LLM Gateway on your own infrastructure for complete control over your data and configuration.
The self-hosted version offers additional customization options and ensures your LLM traffic never leaves your infrastructure if desired.
# Quickstart
URL: https://docs.llmgateway.ai-stage.zibl.ir/quick-start
Welcome to **LLM Gateway**—a single drop‑in endpoint that lets you call today’s best large‑language models while keeping **your existing code** and development workflow intact.
> **TL;DR** — Point your HTTP requests to `https://api.llmgateway.io/v1/…`, supply your `LLM_GATEWAY_API_KEY`, and you’re done.
***
## 1 · Get an API key [#1--get-an-api-key]
1. Sign in to the dashboard.
2. Create a new Project → *Copy the key*.
3. Export it in your shell (or a `.env` file):
```bash
export LLM_GATEWAY_API_KEY="llmgtwy_XXXXXXXXXXXXXXXX"
```
***
## 2 · Pick your language [#2--pick-your-language]
```bash
curl -X POST https://api.llmgateway.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}'
```
```typescript
const response = await fetch("https://api.llmgateway.io/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.LLM_GATEWAY_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello, how are you?" }],
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data.choices[0].message.content);
```
```tsx
import { useState } from "react";
function ChatComponent() {
const [response, setResponse] = useState("");
const [loading, setLoading] = useState(false);
const sendMessage = async () => {
setLoading(true);
try {
const res = await fetch("https://api.llmgateway.io/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.REACT_APP_LLM_GATEWAY_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello, how are you?" }],
}),
});
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const data = await res.json();
setResponse(data.choices[0].message.content);
} catch (error) {
console.error("Error:", error);
} finally {
setLoading(false);
}
};
return (
{response &&
{response}
}
);
}
export default ChatComponent;
```
The gateway sends no CORS headers by default, so direct browser calls like this only work when the deployment's `GATEWAY_CORS_ORIGINS` allowlist (an environment variable on self-hosted deployments) includes your web app's origin. Prefer calling the gateway from a server route (see the Next.js tab), which also keeps your API key out of the browser bundle.
```typescript
// app/api/chat/route.ts
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
const { message } = await request.json();
const response = await fetch(
"https://api.llmgateway.io/v1/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.LLM_GATEWAY_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4o",
messages: [{ role: "user", content: message }],
}),
},
);
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to get response" },
{ status: response.status },
);
}
const data = await response.json();
return NextResponse.json({
message: data.choices[0].message.content,
});
}
// Usage in component:
// const response = await fetch('/api/chat', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ message: 'Hello, how are you?' })
// });
```
```python
import requests
import os
response = requests.post(
'https://api.llmgateway.io/v1/chat/completions',
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {os.getenv("LLM_GATEWAY_API_KEY")}'
},
json={
'model': 'gpt-4o',
'messages': [
{'role': 'user', 'content': 'Hello, how are you?'}
]
}
)
response.raise_for_status()
print(response.json()['choices'][0]['message']['content'])
```
```java
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
String apiKey = System.getenv("LLM_GATEWAY_API_KEY");
String requestBody = """
{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.llmgateway.io/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
```
```rust
use reqwest::Client;
use serde_json::json;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box> {
let client = Client::new();
let api_key = env::var("LLM_GATEWAY_API_KEY")?;
let response = client
.post("https://api.llmgateway.io/v1/chat/completions")
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", api_key))
.json(&json!({
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}))
.send()
.await?;
let result: serde_json::Value = response.json().await?;
println!("{}", result["choices"][0]["message"]["content"]);
Ok(())
}
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
type ChatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
func main() {
apiKey := os.Getenv("LLM_GATEWAY_API_KEY")
requestBody := ChatRequest{
Model: "gpt-4o",
Messages: []Message{{Role: "user", Content: "Hello, how are you?"}},
}
jsonData, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "https://api.llmgateway.io/v1/chat/completions", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
fmt.Println("Response received")
}
```
```php
'gpt-4o',
'messages' => [
['role' => 'user', 'content' => 'Hello, how are you?']
]
];
$options = [
'http' => [
'header' => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents(
'https://api.llmgateway.io/v1/chat/completions',
false,
$context
);
if ($response === FALSE) {
throw new Exception('Request failed');
}
$result = json_decode($response, true);
echo $result['choices'][0]['message']['content'];
?>
```
```ruby
require 'net/http'
require 'json'
require 'uri'
uri = URI('https://api.llmgateway.io/v1/chat/completions')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request['Authorization'] = "Bearer #{ENV['LLM_GATEWAY_API_KEY']}"
request.body = {
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Hello, how are you?' }
]
}.to_json
response = http.request(request)
if response.code != '200'
raise "HTTP Error: #{response.code}"
end
result = JSON.parse(response.body)
puts result['choices'][0]['message']['content']
```
***
## 3 · SDK integrations [#3--sdk-integrations]
```ts title="ai-sdk.ts"
import { llmgateway } from "@llmgateway/ai-sdk-provider";
import { generateText } from "ai";
const { text } = await generateText({
model: llmgateway("gpt-4o"),
prompt: "Write a vegetarian lasagna recipe for 4 people.",
});
```
```ts title="vercel-ai-sdk.ts"
import { createOpenAI } from "@ai-sdk/openai";
import { generateText } from "ai";
const llmgateway = createOpenAI({
baseURL: "https://api.llmgateway.io/v1",
apiKey: process.env.LLM_GATEWAY_API_KEY!,
});
const { text } = await generateText({
model: llmgateway.chat("gpt-4o"),
messages: [{ role: "user", content: "Hello, how are you?" }],
});
console.log(text);
```
```ts title="openai-sdk.ts"
import OpenAI from "openai";
const openai = new OpenAI({
baseURL: "https://api.llmgateway.io/v1",
apiKey: process.env.LLM_GATEWAY_API_KEY,
});
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello, how are you?" }],
});
console.log(completion.choices[0].message.content);
```
***
## 4 · Going further [#4--going-further]
* **Streaming**: pass `stream: true` to any request—the gateway normalizes every provider's stream into OpenAI-format SSE chunks, with a final chunk carrying `usage` and routing metadata before `data: [DONE]`.
* **Monitoring**: Every call appears in the dashboard with latency, cost & provider breakdown.
***
## 5 · FAQ [#5--faq]
**Which models are supported?**
See the [Models page](https://llmgateway.io/models).
**What makes your service different from OpenRouter?**
Unlike OpenRouter, we offer:
Full self-hosting capabilities, giving you complete control over your
infrastructure
Enhanced analytics with deeper insights into your model usage and
performance
No fees when using your own provider keys, maximizing cost efficiency
Greater flexibility and customization options for enterprise deployments
**How much do you charge for your services?**
Our pricing structure is designed to be flexible and cost-effective: See the
[Pricing section](https://llmgateway.io#pricing).
***
## 6 · Next steps [#6--next-steps]
* Read [Self host docs](https://docs.llmgateway.ai-stage.zibl.ir/self-host) guide.
* Drop into our [GitHub](https://github.com/theopenco/llmgateway) for help or feature requests.
Happy building! ✨
# Lounge
URL: https://docs.llmgateway.ai-stage.zibl.ir/lounge
Lounge is the chat app built on LLM Gateway. Pick any model from the catalogue, switch mid-conversation, and compare answers side by side. The same app includes studios for images, video, speech, and decisions, plus live voice calls, on the web at [lounge.llmgateway.io](https://lounge.llmgateway.io) and on iPhone and iPad.
## Quick start [#quick-start]
### Sign in [#sign-in]
Open [lounge.llmgateway.io](https://lounge.llmgateway.io) and sign in with your LLM Gateway account.
### Choose a model [#choose-a-model]
Use the model picker above the composer. **Auto Route** picks a provider for you based on availability and cost.
### Chat, compare, or create [#chat-compare-or-create]
Send a message, turn on **Comparison mode** to ask several models at once, or pick **Group**, **Image**, **Video**, **Audio**, **Decide**, or **Voice** in the sidebar.
### Get more with a membership [#get-more-with-a-membership]
A [Lounge membership](https://docs.llmgateway.ai-stage.zibl.ir/learn/chat-plans) gives you monthly credits worth more than you pay, so heavy chat usage costs less than pay-as-you-go.
## Take the tour [#take-the-tour]
## Explore Lounge [#explore-lounge]
## Other products [#other-products]
# Airside
URL: https://docs.llmgateway.ai-stage.zibl.ir/airside
Airside is where the companies behind the models run their listing on LLM Gateway. It uses an airport metaphor: LLM Gateway is the airport, developers are passengers, and providers are **carriers**. As a carrier you claim your provider, register your fleet of models, file your fares, and see the traffic that reaches you.
## Quick start [#quick-start]
### Sign up with your company email [#sign-up-with-your-company-email]
Create an account at [airside.llmgateway.io](https://airside.llmgateway.io). The domain of your verified email must match your provider's API endpoint or website to claim it.
### Claim or register your carrier [#claim-or-register-your-carrier]
Claim an existing catalogue provider, or register a new one. The LLM Gateway team reviews every claim before the carrier goes live.
### Register your fleet and file fares [#register-your-fleet-and-file-fares]
Add each model with its context size and capabilities, and file its per-token prices. Every model must pass preflight, which runs on the carrier's saved **provider key**, managed by the carrier or LLM Gateway. A newly registered carrier files this single key with its first preflight; the same key serves live traffic once the model is approved. Replacements under **Settings** are smoke-tested and reviewed by the LLM Gateway team. Once a filing is approved, the model is routable as `/`.
No separate test key is required. Previously saved test keys are ignored; you do not need to remove them or resubmit your provider key. [Airside test usage](https://docs.llmgateway.ai-stage.zibl.ir/features/airside#provider-key-and-test-usage) is included in provider-side usage and gateway accounting.
### Watch your traffic [#watch-your-traffic]
The **Traffic** page shows requests, errors, tokens, and billed traffic per model. Invite teammates under **Crew** so your whole team can manage the listing.
## Take the tour [#take-the-tour]
## Explore Airside [#explore-airside]
## Other products [#other-products]
# DevPass Usage API
URL: https://docs.llmgateway.ai-stage.zibl.ir/developers/devpass-usage
**Plan changes from October 15, 2026**
DevPass subscription prices stay the same, but included usage decreases. Daily
and premium weekly caps and Reset Pass benefits change on October 15; existing
monthly allowances change at the first renewal on or after that date. New
subscriptions from that date start with the new allowance. Review
the [dated plan-change
notice](https://devpass.llmgateway.io/legal/terms#october-2026-plan-changes)
before subscribing.
Use `GET /v1/key` to show DevPass allowance meters in a coding tool or other
trusted application. The endpoint uses the application's existing gateway API
key, so it does not require a dashboard session.
A regular gateway API key is a secret. Do not embed it in public browser code
or distribute it with an application. Read it from the user's secure local
configuration or call the endpoint from a trusted backend.
## Request [#request]
```bash
curl https://api.llmgateway.io/v1/key \
-H "Authorization: Bearer llmgtwy_your_api_key_here"
```
Only regular gateway API keys can use this endpoint. Platform publishable keys
and end-user sessions receive `403 Forbidden` because they cannot read
organization-level plan state.
## Response [#response]
```json
{
"data": {
"label": "My coding tool",
"usage": "31.42",
"limit": null,
"devPlan": "pro",
"devPlanCreditsUsed": "25",
"devPlanCreditsLimit": "158",
"devPlanCreditsRemaining": "133.00",
"devPlanDailyLimit": "14.22",
"devPlanDailyCreditsUsed": "3.10",
"devPlanDayResetsAt": "2026-08-22T09:30:00.000Z",
"devPlanPremiumWeeklyLimit": "18.96",
"devPlanPremiumCreditsUsed": "5.00",
"devPlanPremiumWeekResetsAt": "2026-08-28T12:00:00.000Z"
}
}
```
| Field | Meaning |
| ---------------------------- | -------------------------------------------------------------- |
| `label` | Description of the key |
| `usage` | All-time usage attributed to the key, in USD |
| `limit` | All-time key usage limit in USD, or `null` |
| `devPlan` | `lite`, `pro`, `max`, or `none` |
| `devPlanCreditsUsed` | Plan credits used in the current billing cycle |
| `devPlanCreditsLimit` | Plan credit allowance for the current billing cycle |
| `devPlanCreditsRemaining` | Remaining plan credits, clamped to zero |
| `devPlanDailyLimit` | Daily pacing allowance — plan credits usable per rolling 24h |
| `devPlanDailyCreditsUsed` | Plan credits used in the current 24-hour window |
| `devPlanDayResetsAt` | ISO 8601 reset time, or `null` when no daily window is active |
| `devPlanPremiumWeeklyLimit` | Weekly premium-model allowance |
| `devPlanPremiumCreditsUsed` | Premium-model credits used in the current weekly window |
| `devPlanPremiumWeekResetsAt` | ISO 8601 reset time, or `null` when no weekly window is active |
All USD values are decimal strings. Parse them before calculating percentages
or remaining allowances.
## Daily window behavior [#daily-window-behavior]
The pacing window starts with the first request that draws on the plan
allowance and lasts 24 hours; it covers every model. When it expires, the
endpoint returns `"0.00"` for `devPlanDailyCreditsUsed` and `null` for
`devPlanDayResetsAt`; the full daily share is available again, and the next
request starts a new window.
## Weekly window behavior [#weekly-window-behavior]
The premium window starts with the first premium-model request and lasts seven
days. When it expires, the endpoint returns `"0.00"` for
`devPlanPremiumCreditsUsed` and `null` for `devPlanPremiumWeekResetsAt`; the
full weekly allowance is already available, and the next premium request starts
a new window.
Pay-as-you-go keys return `"none"` for `devPlan` and zero for every DevPass
field. This lets one integration support both key types without a separate
account lookup.
The endpoint remains readable when the key has exceeded its own usage limit,
so an integration can explain why requests stopped. Invalid or inactive keys
receive `401 Unauthorized`.
See [Retrieve key status](https://docs.llmgateway.ai-stage.zibl.ir/v1_key_retrieve) for the generated API reference and
complete response schema.
## Recovering a failed renewal [#recovering-a-failed-renewal]
If your renewal fails, DevPass shows **Payment overdue** with a **Complete payment**
link to the outstanding invoice. Follow the link to pay and complete any bank
verification. Your allowance refreshes after payment succeeds.
Updating your card in **Billing** also retries the failed renewal. Saving a card
alone does not mean the invoice is paid: if payment remains outstanding, the
invoice link stays visible above the card details. Return to DevPass after paying
to refresh the payment status.
# Agent Skills
URL: https://docs.llmgateway.ai-stage.zibl.ir/guides/agent-skills
**Agent Skills** are structured guidelines for AI coding agents, optimized for use with LLM Gateway and the AI SDK. They provide best practices and reusable instructions that help AI agents generate higher-quality code.
## Video walkthrough [#video-walkthrough]
## What Are Agent Skills? [#what-are-agent-skills]
Agent Skills are packaged sets of rules and guidelines that teach AI coding agents how to implement specific features correctly. Each skill covers:
* API integration patterns
* Frontend rendering best practices
* Error handling strategies
* Performance optimization techniques
## Available Skills [#available-skills]
### Image Generation [#image-generation]
The Image Generation skill teaches AI agents how to properly implement image generation features:
* **API Integration** — correctly calling image generation APIs
* **Frontend Rendering** — displaying generated images efficiently
* **Error Handling** — graceful degradation and retry logic
* **Performance** — caching, lazy loading, and optimization
### Changelog Writer [#changelog-writer]
The Changelog Writer skill drafts a polished LLM Gateway changelog entry and its OpenGraph image in one pass:
* **House style** — writes in the established changelog voice: problem first, benefits over features, plain and confident
* **Correct format** — generates the dated Markdown file with valid frontmatter (`id`, `slug`, `date`, `title`, `summary`, `tags`, `image`)
* **OG image prompt** — hands back a ready-to-run `gpt-image-2` prompt at the recommended **1536×1024** OpenGraph resolution
* **Validation** — formats and builds the entry before you commit
It ships as a [Claude Code skill](https://docs.claude.com/en/docs/claude-code/skills) — a single `SKILL.md` file. Trigger it by typing `changelog` (or "write a changelog entry") in Claude Code.
## Claude Code Skills [#claude-code-skills]
Some skills ship as **[Claude Code skills](https://docs.claude.com/en/docs/claude-code/skills)**: a single `SKILL.md` file with YAML frontmatter that Claude Code loads automatically when its description matches what you ask. The **Changelog Writer** above is one of them.
Install one by copying its folder into your project's `.claude/skills/` directory:
```bash
# from the llmgateway-templates repo
git clone https://github.com/theopenco/llmgateway-templates.git
mkdir -p .claude/skills
cp -R llmgateway-templates/skills/changelog .claude/skills/
```
Run these commands from your project directory. Review the installed `.claude/skills/changelog/SKILL.md`, then open Claude Code in that project and trigger it by name:
```
> changelog
```
Place the folder in `~/.claude/skills/` instead to make the skill available across every project. Browse the available Claude Code skills in the [llmgateway-templates repository](https://github.com/theopenco/llmgateway-templates/tree/main/skills).
## Build the image-generation instructions [#build-the-image-generation-instructions]
### Prerequisites [#prerequisites]
Ensure you have Node.js 18+ and pnpm 9+ installed:
```bash
node --version # v18.0.0 or higher
pnpm --version # 9.0.0 or higher
```
### Clone the Repository [#clone-the-repository]
```bash
git clone https://github.com/theopenco/agent-skills.git
cd agent-skills
```
### Install Dependencies [#install-dependencies]
```bash
pnpm install
```
### Build Skills [#build-skills]
Build all skills to generate the documentation:
```bash
pnpm build:all
```
Or build a specific skill:
```bash
pnpm build
```
## Use the generated image-generation instructions [#use-the-generated-image-generation-instructions]
After building, each skill generates an `AGENTS.md` file that can be used with AI coding agents like Claude, Cursor, or Copilot.
### With Claude Code [#with-claude-code]
Add the generated `AGENTS.md` content to your project's `CLAUDE.md` file:
```bash
cat skills/image-generation/AGENTS.md >> CLAUDE.md
```
### With Cursor [#with-cursor]
Add the skill content to your `.cursorrules` file:
```bash
cat skills/image-generation/AGENTS.md >> .cursorrules
```
### With Other AI Agents [#with-other-ai-agents]
Most AI coding tools support custom instructions. Copy the skill content into your tool's configuration.
## Project Structure [#project-structure]
```
agent-skills/
├── packages/
│ └── skills-build/ # Build tooling
├── skills/
│ └── image-generation/ # Individual skill
│ ├── rules/ # Rule files
│ ├── AGENTS.md # Generated documentation
│ └── metadata.json # Skill metadata
└── package.json
```
## Contributing [#contributing]
### Adding New Rules [#adding-new-rules]
### Fork and Clone [#fork-and-clone]
Fork the repository and create a feature branch:
```bash
git checkout -b feat/new-rule
```
### Create a Rule File [#create-a-rule-file]
Rules follow a standardized template with YAML frontmatter containing `title`, `impact` (high/medium/low), and `tags`. The body includes sections for Context, Incorrect examples, and Correct examples with TypeScript code blocks.
See existing rules in `skills/image-generation/rules/` for reference.
### Validate and Build [#validate-and-build]
```bash
pnpm validate
pnpm build:all
```
### Submit a Pull Request [#submit-a-pull-request]
Push your changes and open a PR.
### Impact Levels [#impact-levels]
When creating rules, use these impact levels:
* **high** — Critical for correctness or security
* **medium** — Important for quality and maintainability
* **low** — Nice-to-have improvements
## Development Commands [#development-commands]
| Command | Description |
| ---------------- | --------------------------- |
| `pnpm install` | Install dependencies |
| `pnpm build:all` | Build all skills |
| `pnpm build` | Build a specific skill |
| `pnpm validate` | Validate rule files |
| `pnpm dev` | Development mode with watch |
## More Resources [#more-resources]
* [GitHub Repository](https://github.com/theopenco/agent-skills) — Source code and contributions
* [LLM Gateway CLI](https://docs.llmgateway.ai-stage.zibl.ir/developers/cli) — Project scaffolding tool
* [Templates](https://llmgateway.io/templates) — Production-ready starter projects
Want to contribute a new skill or rule? Check out the [contribution
guidelines](https://github.com/theopenco/agent-skills#contributing) on GitHub.
# Autohand Code Integration
URL: https://llmgateway.io/guides/autohand
[Autohand Code](https://autohand.ai) is a terminal coding agent with a built-in LLM Gateway provider. Use a pay-as-you-go or DevPass API key to connect it to your workspace.
## Video walkthrough [#video-walkthrough]
## Install [#install]
```bash
pnpm add -g autohand-cli
autohand --version
```
See the [Autohand documentation](https://docs.autohand.ai/getting-started/first-session) for installation and onboarding.
## Sign in to Autohand [#sign-in-to-autohand]
The current CLI requires an Autohand account even when inference uses a provider API key. Run `autohand login` and complete the browser sign-in before starting a session. Your LLM Gateway key is a separate credential.
## Connect LLM Gateway [#connect-llm-gateway]
Create a key in your [dashboard](https://llmgateway.io/dashboard), then export it before launching Autohand:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
autohand --provider llmgateway --model MODEL_ID
```
Replace `MODEL_ID` with a text model that supports tools from the [live catalogue](https://llmgateway.io/models?features=tools). With DevPass, choose a canonical model ID supported by your plan; provider-pinned routing is unavailable on coding plans.
## Save the provider configuration [#save-the-provider-configuration]
To keep LLM Gateway as your default, merge these settings into `~/.autohand/config.json`:
```json
{
"provider": "llmgateway",
"llmgateway": {
"apiKey": "${LLMGATEWAY_API_KEY}",
"baseUrl": "https://api.llmgateway.io/v1",
"model": "MODEL_ID"
}
}
```
The provider name is a string, with a separate `llmgateway` settings object. Keep the API key in your environment and replace the model placeholder before running the agent.
## Verify a coding task [#verify-a-coding-task]
Start `autohand` from your project directory. Ask it to read a failing test, fix the implementation, and rerun the test without changing the test file. Review its file changes and command output, then check the request in the workspace that issued your key.
## Troubleshooting [#troubleshooting]
* **Wrong provider:** Pass `--provider llmgateway` explicitly or check the top-level `provider` setting.
* **Authentication failed:** Export `LLMGATEWAY_API_KEY` in the same shell and confirm the key is active.
* **Model unavailable:** Choose a tool-capable model allowed by your workspace or DevPass plan.
See Autohand's [LLM Gateway integration reference](https://docs.autohand.ai/integrations/llmgateway) for additional options.
# Claude Code Integration
URL: https://llmgateway.io/guides/claude-code
Claude Code can use LLM Gateway's Anthropic-compatible endpoint while the gateway routes requests to your selected model. This walkthrough was verified with Claude Code 2.1.263.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Install Claude Code using the [official instructions](https://code.claude.com/docs/en/setup), then check `claude --version`.
## Configure the connection [#configure-the-connection]
Create a key in your [dashboard](https://llmgateway.io/dashboard), then set these variables in the terminal where you launch Claude Code:
```bash
export ANTHROPIC_BASE_URL=https://api.llmgateway.io
export ANTHROPIC_AUTH_TOKEN="your_api_key"
export ANTHROPIC_MODEL=deepseek-v4-flash
claude
```
Use the base URL exactly as shown. Claude Code adds `/v1/messages` itself. If an existing `ANTHROPIC_API_KEY` causes an authentication conflict, unset it in this shell before starting.
The example model supports the tool calls needed to read, edit, and test code. Find other compatible choices in the [live model catalogue](https://llmgateway.io/models?features=tools).
## Choose a model [#choose-a-model]
Set `ANTHROPIC_MODEL` before launch, or override it for one session:
```bash
claude --model deepseek-v4-flash
```
Claude Code's picker and model-discovery behavior vary by version. An explicit `--model` value is useful when your model is absent from the picker.
To add a custom picker option, current Claude Code also supports:
```bash
export ANTHROPIC_CUSTOM_MODEL_OPTION=deepseek-v4-flash
export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="DeepSeek V4 Flash"
```
To discover the gateway models supported by Claude Code's picker, set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` before launch. Discovery is subject to the client's model filtering; it does not guarantee that every gateway model appears.
## Verify the connection [#verify-the-connection]
Open a small project and ask the agent to read a file, make a change, and run its tests. Our recorded example fixes a TypeScript slugifier and passes all three tests with `deepseek-v4-flash` through LLM Gateway.
`Hello, LLM Gateway!` becomes `hello-llm-gateway`; repeated separators collapse into one hyphen; empty and punctuation-only inputs stay empty. The demo uses Node.js 24 to run `node --test slugify.test.ts` directly.
Review the diff and test output, then check the request in your [LLM Gateway dashboard](https://llmgateway.io/dashboard). Choose other compatible models from the [live catalogue](https://llmgateway.io/models?features=tools).
## Prompt cache lifetime [#prompt-cache-lifetime]
For Claude models, the default 5-minute cache refreshes on each hit. If coding pauses or long tool runs regularly exceed five minutes, opt into a 1-hour lifetime before starting Claude Code:
```bash
export CLAUDE_CODE_PROMPT_CACHE_TTL=1h
```
One-hour cache writes cost more, so the default is cheaper for continuous work. `FORCE_PROMPT_CACHING_5M=1` overrides this setting. See [provider cache control](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/provider-cache-control) for pricing and usage fields.
## Auto mode classifier billing [#auto-mode-classifier-billing]
When Claude Code requests server-side auto mode review, routing is restricted to
providers that can forward it. This also applies to DevPass with canonical model
IDs; no provider prefix is needed. An incompatible saved session pin is replaced,
and requests with no compatible provider are rejected instead of silently routing
to one that would drop the review.
Check `/status` for **Auto mode server: Enabled**. Availability still depends on
the upstream model and credentials. Set `CLAUDE_CODE_AUTO_MODE_SERVER=0` before
launch to opt out and allow broader routing with billed client-side classifier
requests. See [auto mode safeguards](https://docs.llmgateway.ai-stage.zibl.ir/features/anthropic-endpoint#auto-mode-safeguard-review).
## Troubleshooting [#troubleshooting]
* **Requests use the wrong endpoint:** check `ANTHROPIC_BASE_URL` in the shell that starts Claude Code and restart the agent after changing it.
* **Authentication fails:** verify the gateway key and resolve conflicting Anthropic authentication variables.
* **A model is missing from the picker:** launch with an explicit `--model` ID from the catalogue.
* **An optional tool is unsupported:** use a model with the required capability, or disable the tool for that session.
A [DevPass](https://devpass.llmgateway.io) plan key can also be used. Use canonical model IDs for plan routing.
# Cline Integration
URL: https://llmgateway.io/guides/cline
[Cline](https://cline.bot) is a coding agent for VS Code. Configure its OpenAI-compatible provider to send model requests through LLM Gateway with a pay-as-you-go or DevPass key.
## Video walkthrough [#video-walkthrough]
## Install Cline [#install-cline]
Open the VS Code Extensions view with **Cmd/Ctrl + Shift + X**, search for **Cline**, and install the extension published by Cline.
## Connect LLM Gateway [#connect-llm-gateway]
On first launch, choose **Bring my own API key** and continue. For an existing installation, open Cline's settings using the gear icon.
Set these fields:
| Field | Value |
| ------------ | ------------------------------------------------ |
| API Provider | `OpenAI Compatible` |
| Base URL | `https://api.llmgateway.io/v1` |
| API Key | A key from your LLM Gateway or DevPass dashboard |
| Model ID | A tool-capable model ID from the live catalogue |
Create a key in your [dashboard](https://llmgateway.io/dashboard). Find model IDs, context limits, and capabilities on the [models page](https://llmgateway.io/models?features=tools).
Cline's model configuration also lets you set context and capability information. Match those settings to your selected model. A default or zero cost shown inside Cline is not the gateway's bill; check actual usage in your dashboard.
> **Using DevPass?** Use a canonical model ID included in your plan, without an upstream provider prefix. The gateway selects the provider. See the [DevPass site](https://devpass.llmgateway.io).
## Verify a small task [#verify-a-small-task]
Open a project and ask Cline to fix one function with an existing test. **Plan** mode can inspect the project and propose a change. Switch to **Act** to apply it.
Review the proposed diff before approving the edit. Approve the test command when prompted, then inspect its output. Keep the scope small until you are comfortable with the tool permissions.
Cline can keep separate models for Plan and Act. If you enable that option, configure both modes to use the intended gateway endpoint and key.
## Troubleshooting [#troubleshooting]
**Authentication fails:** confirm the key is active and the base URL includes `/v1`.
**A model is unavailable:** copy its exact ID from the live catalogue and check that your account can use it.
**Cline plans without editing:** switch to Act mode and approve the proposed edit.
**Terminal output is missing:** check VS Code shell integration. Interactive shell startup prompts can interrupt commands; dismiss them or use a terminal profile with a clean startup, then rerun the test.
**The context limit is wrong:** match Cline's model configuration to the model's documented context window and start a fresh task if the conversation is already too large.
# Codex CLI Integration
URL: https://llmgateway.io/guides/codex-cli
[Codex CLI](https://github.com/openai/codex) can connect to LLM Gateway through a custom provider using the Responses API. This walkthrough was verified with Codex CLI 0.153.4.
## Video walkthrough [#video-walkthrough]
## Install [#install]
```bash
pnpm add -g @openai/codex
codex --version
```
## Configure LLM Gateway [#configure-llm-gateway]
Create a key in your [dashboard](https://llmgateway.io/dashboard) and export it in the terminal where you launch Codex:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Merge these settings into `~/.codex/config.toml`:
```toml
model = "deepseek-v4-flash"
model_provider = "llmgateway"
model_reasoning_effort = "low"
[model_providers.llmgateway]
name = "LLM Gateway"
base_url = "https://api.llmgateway.io/v1"
env_key = "LLMGATEWAY_API_KEY"
wire_api = "responses"
```
The named provider reads your gateway key from the environment. You can keep your existing ChatGPT login. Current Codex versions use `responses`; changing an environment variable cannot switch them to Chat Completions.
Codex's default cached web search works with every model: requests served by OpenAI on a model with native web search search OpenAI's cached index, and everything else answers without searching (see [cache-only search](https://docs.llmgateway.ai-stage.zibl.ir/features/web-search#cache-only-search)). `web_search = "live"` needs a model with native web search from the [catalogue](https://llmgateway.io/models?features=webSearch).
## Start coding [#start-coding]
```bash
cd your-project
codex
```
For a scripted task:
```bash
codex exec --sandbox workspace-write "Fix the failing test and run it again"
```
## Verify the connection [#verify-the-connection]
Open a small project and ask the agent to read a file, make a change, and run its tests. Our recorded example fixes a TypeScript slugifier and passes all three tests with `deepseek-v4-flash` through LLM Gateway.
`Hello, LLM Gateway!` becomes `hello-llm-gateway`; repeated separators collapse into one hyphen; empty and punctuation-only inputs stay empty. The demo uses Node.js 24 to run `node --test slugify.test.ts` directly.
Review the diff and test output, then check the request in your [LLM Gateway dashboard](https://llmgateway.io/dashboard). Choose other compatible models from the [live catalogue](https://llmgateway.io/models?features=tools).
## Troubleshooting [#troubleshooting]
* **Authentication fails:** check that `model_provider` matches the provider table and that `LLMGATEWAY_API_KEY` is exported in the same shell.
* **Native web search is unsupported:** `web_search = "live"` is set for a model without native web search. Remove it or choose a model with that capability, then start a new session.
* **Model metadata or catalogue refresh warning:** Codex 0.153.4 can warn about missing metadata or the gateway's model-list response format. Our configured model still completed the task. Use an explicit model ID and verify the actual request result.
* **Wrong endpoint:** the provider's `base_url` must end in `/v1`.
See OpenAI's [custom-provider configuration](https://developers.openai.com/codex/config-advanced/) for configuration profiles and other options.
# Conductor Integration
URL: https://llmgateway.io/guides/conductor
[Conductor](https://www.conductor.build) runs coding agents in separate workspaces. Its bundled OpenCode agent includes an LLM Gateway provider, so you can connect from Settings without installing a separate CLI or entering a base URL.
Verified with Conductor **0.87.4**.
## Prerequisites [#prerequisites]
* Install Conductor from the [official site](https://www.conductor.build).
* Create an [LLM Gateway API key](https://docs.llmgateway.ai-stage.zibl.ir/learn/api-keys), or use a [DevPass](https://docs.llmgateway.ai-stage.zibl.ir/devpass) plan key.
* Open a repository and workspace in Conductor.
## Connect LLM Gateway [#connect-llm-gateway]
1. Open **Settings → Agents → OpenCode**. Some versions label **Agents** as **Harnesses**.
2. Under **Providers**, click **Configure**.
3. If LLM Gateway is missing, click **View all providers**, then search for **LLM Gateway**.
4. Expand **LLM Gateway**, paste your API key into **LLMGATEWAY\_API\_KEY**, and click **Save**. A checkmark indicates that a key is configured.
The built-in provider supplies the gateway endpoint. Use your pay-as-you-go key for usage-based billing or your DevPass key for your coding plan.
## Choose a model [#choose-a-model]
1. Close the provider dialog and click **Configure** under **Models**.
2. Search for a model and check its entry under **llmgateway**. Choose a model with tool calling from the [live catalogue](https://llmgateway.io/models?features=tools).
For DevPass, choose a model included in your plan under **llmgateway**. The **llmgateway-providers** entries pin an upstream provider and are not supported on coding plans. The model shown in the screenshot is an example; availability changes with the catalogue and your account.
3. Open **Settings → Default models** and add your model from the **OpenCode** column to your **Loadout**. To change an existing slot, open its menu, choose **Agent → OpenCode**, then select your model under **Model**.
4. Return to your workspace, open a new chat, and choose that model from the agent picker below the message box. The picker's **Edit** button takes you back to **Default models**.
## Verify the connection [#verify-the-connection]
Send a small prompt first:
```text
Reply with exactly: Hello from LLM Gateway! Do not use tools or read or change any files.
```
In your [LLM Gateway dashboard](https://llmgateway.io/dashboard), select the project that issued the key and open **Activity** from the sidebar to inspect the request. DevPass users can review usage under [Coding Agents](https://docs.llmgateway.ai-stage.zibl.ir/learn/coding-agents); Conductor runs these requests through OpenCode.
Once connected, ask the agent to make a small change and run the relevant tests. Review the tool output and workspace diff before keeping the change.
## Troubleshooting [#troubleshooting]
**LLM Gateway is missing:** click **View all providers** and search again. If it still does not appear, update Conductor.
**The model is missing from the chat picker:** enable it under **Agents → OpenCode → Models**, then add it to **Default models → Loadout**.
**Authentication fails:** check that the provider key was saved and is active in the matching dashboard.
**Requests use another provider:** select the model under **llmgateway**, then confirm that the chat is using your OpenCode loadout entry.
For executable overrides and other provider configuration options, see Conductor's [OpenCode documentation](https://www.conductor.build/docs/reference/harnesses/opencode).
# Continue CLI Integration
URL: https://llmgateway.io/guides/continue
[Continue CLI](https://docs.continue.dev/cli/quickstart) runs a coding assistant in your terminal. Connect its OpenAI-compatible provider to LLM Gateway with a pay-as-you-go or DevPass API key.
## Video walkthrough [#video-walkthrough]
## Install [#install]
```bash
pnpm add -g @continuedev/cli
cn --version
```
## Configure the model [#configure-the-model]
Create an API key in your [dashboard](https://llmgateway.io/dashboard). Save this configuration in `~/.continue/config.yaml`, merging it with any settings you already use:
```yaml
name: LLM Gateway
version: 1.0.0
schema: v1
models:
- name: Gateway coding model
provider: openai
model: MODEL_ID
apiBase: https://api.llmgateway.io/v1
apiKey: ${{ secrets.LLMGATEWAY_API_KEY }}
capabilities:
- tool_use
```
Replace `MODEL_ID` with a text model that supports tools from the [live catalogue](https://llmgateway.io/models?features=tools), and export your key in the terminal where you launch Continue:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Keep the key private. `capabilities: [tool_use]` tells Continue to enable tool calling; the selected model must actually support it.
`provider: openai` selects the API format. LLM Gateway routes the request to the serving provider. With DevPass, use a canonical model ID supported by your plan, without an upstream provider prefix.
## Start a session [#start-a-session]
Launch Continue from your project with the configuration selected explicitly:
```bash
cd your-project
cn --config ~/.continue/config.yaml
```
Ask it to fix a small failing test, leaving the test itself unchanged. Review requested tool permissions, inspect the diff, and confirm the test output. Requests appear in the dashboard for the workspace that issued your key.
For a one-shot prompt:
```bash
cn --config ~/.continue/config.yaml -p "Explain this project without changing files"
```
## Change models [#change-models]
Add another entry under `models` with a different name and model ID, keeping the gateway endpoint. Select the configured model in Continue. Check the live catalogue for each model's tool and image capabilities.
A separate project configuration works too: pass its path to `--config` when launching the CLI.
## Troubleshooting [#troubleshooting]
* **Configuration rejected:** Include `name`, `version`, and `schema: v1` at the top level, and check YAML indentation.
* **Onboarding appears instead:** Pass the intended file with `--config`.
* **Authentication failed:** Check the key and workspace in the dashboard.
* **Request finishes without visible text:** Continue CLI 1.5.47 drops text chunks that also contain usage, which can affect Gemini responses through the gateway. Choose another tool-capable model and check for a Continue update.
* **Tool calling unavailable:** Choose a model with tool support and include `tool_use` in its capabilities.
* **Connection failed:** Use `https://api.llmgateway.io/v1` as `apiBase`.
See the [Continue configuration reference](https://docs.continue.dev/reference) for additional options.
# Crush Integration
URL: https://llmgateway.io/guides/crush
[Crush](https://github.com/charmbracelet/crush) is a terminal coding agent. Connect its OpenAI-compatible provider to LLM Gateway with a pay-as-you-go or DevPass key.
## Video walkthrough [#video-walkthrough]
## Install [#install]
```bash
pnpm add -g @charmland/crush
crush --version
```
Other installation options are in the [Crush documentation](https://github.com/charmbracelet/crush#installation).
## Connect LLM Gateway [#connect-llm-gateway]
Create an API key in your [dashboard](https://llmgateway.io/dashboard), then export it in the terminal where you run Crush:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Add this provider to your project's `crush.json`, merging it with existing settings:
```json
{
"providers": {
"llmgateway": {
"name": "LLM Gateway",
"type": "openai",
"base_url": "https://api.llmgateway.io/v1",
"api_key": "$LLMGATEWAY_API_KEY"
}
}
}
```
The key stays in your environment. Crush discovers the available models from the gateway when no explicit model list is configured.
## Choose a model and code [#choose-a-model-and-code]
```bash
cd your-project
crush
```
Select **LLM Gateway** and a model with tool support from the [live catalogue](https://llmgateway.io/models?features=tools). With DevPass, choose a canonical model ID supported by your plan, without an upstream provider prefix.
Start with a small task that has a clear test. Review tool permission requests, inspect the changes, and run the tests. Check usage in the workspace that issued your API key.
## Troubleshooting [#troubleshooting]
* **Authentication failed:** Check that `LLMGATEWAY_API_KEY` is exported in the same terminal and the key is active.
* **Models missing:** Restart Crush after editing the provider configuration. Check the endpoint and key before adding a manual model list.
* **Tool calls fail:** Confirm the selected model supports tools.
* **Provider unavailable:** Gateway fallback can route requests to another eligible provider. See the [routing documentation](https://docs.llmgateway.io/features/routing) for pinning and fallback controls.
See the [Crush configuration reference](https://github.com/charmbracelet/crush/tree/main/docs/config) for permissions and additional settings.
# Cursor Integration
URL: https://llmgateway.io/guides/cursor
To route Cursor's chat models through LLM Gateway, open **Cursor Settings → Models → API Keys**, enable **Override OpenAI Base URL**, set it to `https://api.llmgateway.io/v1`, and add a gateway API key. The steps below cover sign-in, model selection, verification, and what the override does not change.
## Video walkthrough [#video-walkthrough]
## Sign in and open model settings [#sign-in-and-open-model-settings]
Install Cursor from its [official site](https://cursor.com/downloads), sign in to your Cursor account, and open **Cursor Settings → Models → API Keys**.
Cursor account access and your gateway API key are separate requirements.
## Add the gateway connection [#add-the-gateway-connection]
1. Enter your workspace key under **OpenAI API Key**.
2. Enable **Override OpenAI Base URL** and set `https://api.llmgateway.io/v1`.
3. Save or verify the key using the controls in your Cursor version.
4. Select a supported chat model. If your version offers custom model entry, use the exact ID from the [live catalogue](https://llmgateway.io/models).
With a [DevPass](https://devpass.llmgateway.io) key, choose a canonical model included in your plan. Upstream provider prefixes pin routing and are not supported on coding plans.
## Verify the request [#verify-the-request]
Open a new chat, select the configured model explicitly, and send a short prompt. Check the request in the workspace that issued the gateway key before relying on the connection for agent tasks.
Compatibility depends on Cursor's model support and the mode you use. A custom endpoint does not guarantee that every catalogue model or agent feature works.
## Scope and billing [#scope-and-billing]
Cursor documents custom keys for chat models; Tab completion continues using Cursor's built-in models. BYOK requests still pass through Cursor's backend for prompt building. Consult Cursor's [API key documentation](https://cursor.com/help/models-and-usage/api-keys) for current plan charges and data handling.
## Troubleshooting [#troubleshooting]
**Sign-in blocks settings:** complete Cursor account sign-in before configuring the provider.
**Authentication fails:** check the active gateway key and the exact base URL, including `/v1`.
**A model is missing or rejected:** confirm Cursor supports it, check its exact catalogue ID, and test a supported chat model first.
**An agent tool fails:** verify tool support and mode compatibility. Check the actual request and error instead of assuming every editor feature uses the override.
**Tab completion uses Cursor's service:** this is expected; custom chat keys do not replace its completion models.
# DevPass Code Integration
URL: https://llmgateway.io/guides/devpass-code
[DevPass Code](https://github.com/theopenco/devpass-code) is a terminal coding agent built for LLM Gateway. This walkthrough was verified with DevPass Code 1.18.11.
## Video walkthrough [#video-walkthrough]
## Install [#install]
```bash
pnpm add -g devpass-code
devpass-code --version
```
See the [project repository](https://github.com/theopenco/devpass-code) for other installation options.
## Connect LLM Gateway [#connect-llm-gateway]
The recorded walkthrough uses an existing gateway API key:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Create your key in the [dashboard](https://llmgateway.io/dashboard). Alternatively, run `devpass-code auth login`, choose **LLM Gateway** or **LLM Gateway DevPass**, and follow the browser-login or key-entry flow.
Browser login creates a credential and returns it to the tool through a local callback. If you have reached your organization's active-key limit, manage your keys in the dashboard before retrying.
## Choose a model [#choose-a-model]
Place a `devpass-code.json` in your project:
```json
{
"model": "llmgateway/deepseek-v4-flash"
}
```
Then launch the agent:
```bash
cd your-project
devpass-code
```
You can also select the model with `--model llmgateway/deepseek-v4-flash` or use the model picker. Browse the [live catalogue](https://llmgateway.io/models?features=tools) for other coding models.
The `llmgateway/` prefix identifies the agent's provider. The remaining model ID is canonical, which is also the form required for [DevPass](https://devpass.llmgateway.io) plan routing.
## Verify the connection [#verify-the-connection]
Open a small project and ask the agent to read a file, make a change, and run its tests. Our recorded example fixes a TypeScript slugifier and passes all three tests with `deepseek-v4-flash` through LLM Gateway.
`Hello, LLM Gateway!` becomes `hello-llm-gateway`; repeated separators collapse into one hyphen; empty and punctuation-only inputs stay empty. The demo uses Node.js 24 to run `node --test slugify.test.ts` directly.
Review the diff and test output, then check the request in your [LLM Gateway dashboard](https://llmgateway.io/dashboard). Choose other compatible models from the [live catalogue](https://llmgateway.io/models?features=tools).
## Troubleshooting [#troubleshooting]
Check that `LLMGATEWAY_API_KEY` is available to the process and that the model ID matches the picker. If a project opens with an unexpected model, check its `devpass-code.json` and pass `--model` explicitly.
DevPass Code tags requests with `x-source: devpass-code` for attribution in your dashboard.
# Empryo Integration
URL: https://llmgateway.io/guides/empryo
[Empryo](https://empryo.com) is a coding agent with a desktop app, terminal UI, and headless CLI. LLM Gateway is built in to both interactive interfaces. Connect with browser login or an existing API key, then choose a model for your project.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Use the [official installer or release downloads](https://empryo.com/download), then verify the installed version:
```bash
empryo --version
```
## Desktop app (GUI) [#desktop-app-gui]
Download the desktop app from the [Empryo downloads page](https://empryo.com/download), then open a project folder from the workspace selector.
### Connect your account [#connect-your-account]
On first launch, the **Connect a model** screen walks through **Provider**, **Account**, and **Model**:
1. Select **LLM Gateway** as the provider.
2. Choose browser login for pay-as-you-go, or the **DevPass** login option for a coding plan. In an already connected profile, these actions appear as **Reconnect** and **Reconnect · DevPass**.
3. Finish authorization in your browser and return to Empryo. Keep the app running until the callback completes.
4. Choose a tool-capable model and click **Start**.
To use a key instead, enter it in **LLM Gateway API key** and click **Connect**. When both a browser connection and a key exist, the **Use** control chooses **Auto**, **Connection**, or **Key**. Select the credential matching the workspace you intend to bill.
### Work in the desktop app [#work-in-the-desktop-app]
Use the model selector in the top bar to change models. Enter your task in the chat composer, inspect the file changes, and check the test output before accepting the result. The workspace tree and diff viewer let you review what the agent changed alongside the conversation.
## Terminal UI (TUI) [#terminal-ui-tui]
### Log in with your browser [#log-in-with-your-browser]
Start Empryo in your project:
```bash
cd your-project
empryo
```
Type `/login` to connect a pay-as-you-go LLM Gateway account. For a [DevPass](https://devpass.llmgateway.io) subscription, use `/login llmgateway-devpass`.
The agent opens the gateway's authorization page in your browser. Check the account and project, then approve the connection. Approval creates an API key and returns it to Empryo through a local callback. If your organization sets spending limits for you, the key carries the strictest of them. Keep the terminal running until the callback finishes.
You can start the same flow directly from the shell:
```bash
empryo --login llmgateway
# For a DevPass subscription:
empryo --login llmgateway-devpass
```
If the browser reports an active-key limit, revoke a key you no longer use on the API Keys page of the [dashboard](https://llmgateway.io/dashboard), then select **Authorize** again. If the local callback expires, restart login to get a fresh authorization link.
### Choose a model [#choose-a-model]
Open `/models` and select a compatible model under LLM Gateway. The picker reads model information from the gateway; use the [live catalogue](https://llmgateway.io/models?features=tools) to check current capabilities.
The leading `llmgateway/` in Empryo's model selector identifies the agent's provider. For DevPass, keep the remaining model ID canonical; do not pin an upstream provider.
### Use an existing API key [#use-an-existing-api-key]
For scripts or an existing gateway credential, export the key before starting Empryo:
```bash
export LLM_GATEWAY_API_KEY="your_api_key"
empryo
```
Empryo uses `LLM_GATEWAY_API_KEY`, including the underscore between `LLM` and `GATEWAY`. You can also enter a key through `/keys`.
A browser login issues a new credential; it does not reuse a key you already copied from the dashboard.
## Verify the connection [#verify-the-connection]
In either interface, ask the agent to read a file, make a small edit, and run the project's tests. Review both the diff and test output; a completed chat response alone does not prove the change works.
For a headless task, replace `MODEL_ID` with a tool-capable model from the live catalogue:
```bash
empryo --headless --model llmgateway/MODEL_ID \
"Fix the failing test and run it again"
```
Review the diff and test output, then check the request in your [dashboard](https://llmgateway.io/dashboard). Empryo tags gateway requests with `x-source: empryo` for attribution.
See the [Empryo documentation](https://empryo.com/docs) for additional desktop and terminal controls.
# GitHub Copilot App Integration
URL: https://llmgateway.io/guides/github-copilot
The [GitHub Copilot app](https://github.com/features/ai/github-app) supports custom model providers for agent sessions. Add LLM Gateway as an OpenAI-compatible endpoint and choose a model available to your workspace.
## Video walkthrough [#video-walkthrough]
## Install and sign in [#install-and-sign-in]
Install the app from GitHub's official download page and sign in with your GitHub account. Review the requested authorization before approving it.
GitHub account sign-in is required even when you supply your own model key. GitHub documents BYOK access without a Copilot subscription; managed accounts may be subject to organization policy. See its [BYOK setup guide](https://docs.github.com/en/copilot/how-tos/github-copilot-app/use-byok-models) for current requirements. The feature is in public preview.
## Add LLM Gateway [#add-llm-gateway]
1. Open app **Settings → Model providers**.
2. Click **Add provider** and choose an **OpenAI-compatible** endpoint.
3. Enter a display name, your gateway workspace key, and the base URL `https://api.llmgateway.io/v1`.
4. Save the provider and open the session's model picker.
Provider credentials are stored in the system credential store. Choose a model with tool calling and streaming support from the [live catalogue](https://llmgateway.io/models?features=tools), then test it in a small local project.
With a [DevPass](https://devpass.llmgateway.io) key, use a canonical model included in your plan. Upstream provider prefixes pin routing and are not supported on coding plans.
## Check reasoning settings [#check-reasoning-settings]
Model discovery may supply only model IDs. If the app does not retain your reasoning selection, edit the model under **Model providers** and configure its supported reasoning effort levels.
Use only levels supported by the selected model and mapping. The model's live catalogue page shows these capabilities; the models API exposes declared levels under `providers[].reasoning_efforts`.
## Verify a session [#verify-a-session]
Choose the connected provider and model explicitly. Ask the agent to inspect a small project, fix one failing test, and run the tests without changing them. Review permissions, the resulting diff, and the actual command output.
Check usage in the workspace that issued your gateway key. A configured provider or successful sign-in alone does not prove that an agent task completed.
## Troubleshooting [#troubleshooting]
**Sign-in expires:** restart the app's sign-in flow and complete the browser authorization before the device code expires.
**The provider or model is missing:** update the app, check the saved base URL and active key, and review managed-account policy.
**Reasoning selection resets:** configure supported levels on the provider's model entry.
**A request is rejected:** inspect the error, model capability, and workspace access. Do not assume every catalogue model supports the app's agent workflow.
For editor-based Copilot setup, see the separate [VS Code guide](https://docs.llmgateway.io/guides/vscode). BYOK works for Copilot Chat and agent mode in VS Code, but Copilot's inline code completions currently do not support BYOK or custom endpoints, including LLM Gateway.
# Hermes Agent Integration
URL: https://llmgateway.io/guides/hermes-agent
[Hermes Agent](https://github.com/NousResearch/hermes-agent) supports custom OpenAI-compatible endpoints. This walkthrough was verified with Hermes Agent 0.21.0.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Follow the [official installation instructions](https://github.com/NousResearch/hermes-agent#installation), then open a new terminal and check:
```bash
hermes --version
```
## Configure the connection [#configure-the-connection]
Run `hermes setup` and choose **Custom OpenAI-compatible endpoint**. Enter:
| Setting | Value |
| ---------------- | ------------------------------------------------------------ |
| Base URL | `https://api.llmgateway.io/v1` |
| API key | A key from your [dashboard](https://llmgateway.io/dashboard) |
| Model | `deepseek-v4-flash` |
| Terminal backend | `local` for this walkthrough |
You can also configure the files directly. Merge the following into `~/.hermes/config.yaml`:
```yaml
model:
provider: custom
default: deepseek-v4-flash
base_url: https://api.llmgateway.io/v1
terminal:
backend: local
```
Store the credentials in `~/.hermes/.env`:
```dotenv
OPENAI_API_KEY=your_api_key
OPENAI_BASE_URL=https://api.llmgateway.io/v1
```
Keep the credentials file private. `HERMES_HOME` can point Hermes at a separate configuration directory.
## Start coding [#start-coding]
```bash
cd your-project
hermes chat
```
For a single task that exits when finished:
```bash
hermes chat --oneshot -q "Fix the failing test and run it again"
```
Use `--toolsets terminal,file` to limit this demo to shell and file tools. You can change the model for a session with `--model`.
## Verify the connection [#verify-the-connection]
Open a small project and ask the agent to read a file, make a change, and run its tests. Our recorded example fixes a TypeScript slugifier and passes all three tests with `deepseek-v4-flash` through LLM Gateway.
`Hello, LLM Gateway!` becomes `hello-llm-gateway`; repeated separators collapse into one hyphen; empty and punctuation-only inputs stay empty. The demo uses Node.js 24 to run `node --test slugify.test.ts` directly.
Review the diff and test output, then check the request in your [LLM Gateway dashboard](https://llmgateway.io/dashboard). Choose other compatible models from the [live catalogue](https://llmgateway.io/models?features=tools).
## Troubleshooting [#troubleshooting]
Run `hermes doctor` to inspect the configuration. Missing credentials for optional providers do not prevent your configured custom endpoint from working.
If requests use another provider, check both `model.provider: custom` and `model.base_url`. If TypeScript tests fail before running, check the Node.js version inside Hermes's terminal tool; it can differ from the version in your outer shell.
# Coding tool guides
URL: https://docs.llmgateway.ai-stage.zibl.ir/guides
Every guide below connects a tool to LLM Gateway and ends with a verified coding task. The same steps work with a [DevPass](https://docs.llmgateway.ai-stage.zibl.ir/devpass) key or a pay-as-you-go [LLM Gateway API key](https://docs.llmgateway.ai-stage.zibl.ir/learn/api-keys). Requests sent through a supported tool show up per agent under [Coding Agents](https://docs.llmgateway.ai-stage.zibl.ir/learn/coding-agents).
## Terminal coding agents [#terminal-coding-agents]
**Claude Code**
Point Claude Code at LLM Gateway with two environment variables, run it on a
compatible tool-capable model, and verify a real file edit and test run.
**Codex CLI**
Configure Codex CLI with an LLM Gateway provider, connect your API key, and
verify file edits and test execution.
**DevPass Code**
Install DevPass Code, connect an LLM Gateway key, select a model, and verify
a real coding task.
**OpenCode**
Connect OpenCode to LLM Gateway and verify a coding task.
**Crush**
Connect Crush to LLM Gateway, discover models, and verify a coding task.
**Continue CLI**
Configure Continue CLI with LLM Gateway, choose a tool-capable model, and
verify a coding task.
**Kimi Code**
Connect Kimi Code to LLM Gateway, discover models, and verify a coding task.
**MiMo Code**
Configure MiMo Code with LLM Gateway, select a compatible model, and verify
a coding task.
**Pi**
Configure Pi with LLM Gateway and verify a coding task.
**Oh My Pi**
Connect Oh My Pi to LLM Gateway or DevPass, discover models, and run a
coding task from your terminal.
**Hermes Agent**
Connect Hermes Agent to LLM Gateway using a custom endpoint, then verify
tool use, file edits, and tests.
**Reasonix**
Configure Reasonix with LLM Gateway and verify a coding task.
**Autohand Code**
Connect Autohand Code’s built-in LLM Gateway provider with an API key,
choose a model, and verify a coding task.
**Mezair**
Connect Mezair to LLM Gateway, choose DevPass or pay-as-you-go billing, and
configure its local coding engine.
**Empryo**
Connect Empryo’s desktop app and terminal UI to LLM Gateway or DevPass,
choose a model, and run a coding task.
**OpenClaw**
Configure OpenClaw with LLM Gateway, verify a local coding task, and
understand provider aliases and tool permissions.
## Editors and desktop apps [#editors-and-desktop-apps]
**Conductor**
Connect Conductor's OpenCode agent to LLM Gateway, choose a model, and
verify your first request.
**T3 Code**
Add an LLM Gateway provider to T3 Code, choose a model, and verify a coding
task with Claude Code, Codex, or OpenCode.
**Cursor**
Override Cursor's OpenAI base URL with LLM Gateway, add your API key, and
pick a supported chat model. Covers compatibility limits and billing scope.
**VS Code**
Install the official LLM Gateway extension and use your PAYG or DevPass key
in VS Code's native chat and agent mode.
**Cline**
Configure Cline's OpenAI-compatible provider, choose a model, and verify a
coding task through LLM Gateway.
**Kilo Code**
Connect Kilo Code to LLM Gateway or DevPass, select a model, and review
agent edits and commands.
**GitHub Copilot**
Configure the GitHub Copilot app with LLM Gateway, review account
prerequisites, and choose a compatible agent model.
**OpenCode Desktop**
Connect OpenCode Desktop to LLM Gateway or DevPass, open a project, and
verify an agent task.
## Automation and agent skills [#automation-and-agent-skills]
**n8n**
Connect n8n chat workflows to LLM Gateway with an OpenAI Chat Model, then
verify a real execution.
**Agent Skills**
Packaged instructions and guidelines for AI coding agents
# Kilo Code Integration
URL: https://llmgateway.io/guides/kilo-code
[Kilo Code](https://kilo.ai/) is a coding agent for VS Code. Its provider settings include separate LLM Gateway and DevPass connections.
## Video walkthrough [#video-walkthrough]
## Install and choose permissions [#install-and-choose-permissions]
Install **Kilo Code** from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=kilocode.kilo-code), then open its sidebar panel.
On first launch, choose how much autonomy to allow. **Review First** lets you inspect edits and shell commands before approving them. Start with a small project and a focused task.
## Connect your workspace [#connect-your-workspace]
1. Open Kilo's **Settings**, then **Providers**.
2. Click **Show more providers** and search for `llm`.
3. Choose **LLM Gateway** for pay-as-you-go usage or **DevPass (LLM Gateway)** for a coding plan.
4. Paste a key from the matching workspace dashboard and submit it.
The built-in provider supplies the endpoint; you do not need to enter a base URL.
## Select the model for this chat [#select-the-model-for-this-chat]
Click the model picker at the bottom of the chat and select a tool-capable model from your connected provider. Check the active model before sending a task: setting a default under **Settings > Models** does not necessarily change an already-open chat.
Use the [live model catalogue](https://llmgateway.io/models?features=tools) to check capabilities. For DevPass, choose a canonical model ID included in your plan; upstream provider prefixes pin routing and are not supported on coding plans.
## Verify a coding task [#verify-a-coding-task]
Ask Kilo to inspect a function, fix a failing test case, and run the existing tests without changing them. In **Review First** mode, inspect the proposed diff and use **Allow once** for the edit and test command when appropriate.
Review the command output and final diff. The key determines which workspace receives the requests; inspect usage in that workspace's dashboard.
## Troubleshooting [#troubleshooting]
**The provider is missing:** expand **Show more providers**, search for `llm`, and check that Kilo is current.
**The chat still uses another provider:** select the model in the chat itself, even if you already changed the default in Settings.
**Authentication fails:** verify that the key is active and matches the selected billing mode.
**A task pauses:** check whether Kilo is waiting for permission to edit a file or run a command.
# Kimi Code Integration
URL: https://llmgateway.io/guides/kimi-code
[Kimi Code](https://github.com/MoonshotAI/kimi-code) is a terminal coding agent. Its provider manager can discover LLM Gateway models and save the connection for future sessions.
## Video walkthrough [#video-walkthrough]
## Install [#install]
```bash
pnpm add -g @moonshot-ai/kimi-code
kimi --version
```
Use the current Kimi Code package. Additional installation options are in the [official documentation](https://github.com/MoonshotAI/kimi-code).
## Connect your account [#connect-your-account]
Create an API key in your LLM Gateway or DevPass dashboard, then launch `kimi` from your project. Review the workspace trust prompt before continuing.
1. Run `/provider`.
2. Select **Add New Platform**, then **Known third-party provider**.
3. Search for **LLM Gateway**.
4. Choose **LLM Gateway** for pay-as-you-go usage or **DevPass (LLM Gateway)** for a coding plan.
5. Enter your key when prompted, then choose a tool-capable model.
The provider registry supplies model metadata. Use the [live catalogue](https://llmgateway.io/models?features=tools) to check capabilities and account availability.
> **Using DevPass?** Choose a canonical model ID included in your plan. An upstream provider prefix pins routing and is not supported by coding plans. A local provider name in Kimi's model alias is separate from the model ID sent to the gateway.
## Verify a small task [#verify-a-small-task]
Ask Kimi to inspect a function, fix one failing test case, and run the existing tests without changing them. Review the diff and command output. Use `/model` to change the selected model for later work.
The key determines which workspace receives the requests. Check usage in that workspace's dashboard.
## Manual configuration [#manual-configuration]
Kimi stores its configuration in `~/.kimi-code/config.toml`. A custom OpenAI-compatible provider uses `type = "openai"` and `base_url = "https://api.llmgateway.io/v1"`. Keep the file private because it can contain your API key.
Model entries refer to the local provider name and specify the gateway model ID. Match their context limits, output limits, and capabilities to the selected model. Prefer the provider manager when you want the registry to populate those values.
## Troubleshooting [#troubleshooting]
**The provider list is unavailable:** check network access to the registry or use a custom provider configuration.
**Authentication fails:** check that the key is active and belongs to the intended workspace.
**A model is unavailable:** verify its exact ID and that your account or plan can use it.
**Tool calls fail:** choose a model with tool support and check the model metadata in your configuration.
# Mezair Integration
URL: https://llmgateway.io/guides/mezair
[Mezair](https://mezair.dev) is a desktop workspace for repository-based agent work. Its built-in LLM Gateway connector supports browser authorization and API keys.
## Install Mezair [#install-mezair]
Follow the [Mezair Desktop installation guide](https://mezair.dev/docs/desktop/installation) to download a release or build from source. Choose **LLMGateway** during first-run setup, or enable it later in **Settings → AI connections & models → AI connections**.
## Connect LLM Gateway [#connect-llm-gateway]
Select **LLMGateway**, then choose the billing mode matching your account:
| Mode | Use it with |
| ------------- | --------------------------------------------------------- |
| DevPass | A coding plan and canonical models supported by that plan |
| Pay as you go | A workspace billed against gateway credits |
Click **Connect in browser**. Review the account and organization on the authorization page, then approve the connection while Mezair stays open. Alternatively, paste an existing key into **API key (alternative)**.
Mezair lists canonical model IDs for DevPass and provider-pinned model IDs for pay-as-you-go.
## Check the coding engine [#check-the-coding-engine]
Mezair uses a local Codex coding engine to edit files and run commands. Your LLM Gateway account provides the models and billing, so you can connect without a ChatGPT account.
If Mezair reports that the engine is missing or unavailable, use its **Install coding engine** or **Repair coding engine** control, then check the status again.
## Select a model and test [#select-a-model-and-test]
Choose **LLMGateway** and a model in the chat model picker. Mezair lists models that support tool calling. Check their capabilities on the [models page](https://llmgateway.io/models?features=tools).
Start a small task in your repository, review the proposed changes, and run the relevant tests. Look for **Mezair** in the **Agents** view of the LLM Gateway workspace you authorized.
## Troubleshooting [#troubleshooting]
**Browser authorization times out:** start the connection again and finish the approval while Mezair remains open.
**No models appear:** check that the key is active and the billing mode matches your LLM Gateway workspace, then reconnect.
**The coding engine is unavailable:** use the install or repair control before starting an agent task.
**Authentication fails:** verify that the key is active, or reconnect in the browser to authorize a new connection.
# MiMo Code Integration
URL: https://llmgateway.io/guides/mimocode
[MiMo Code](https://mimo.xiaomi.com/mimocode) is a terminal coding agent. Its custom provider configuration can route Anthropic-compatible requests through LLM Gateway.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Use the official installer, then check the version:
```bash
curl -fsSL https://mimo.xiaomi.com/install | bash
mimo --version
```
## Connect your workspace [#connect-your-workspace]
Create a key in your LLM Gateway or DevPass dashboard and export it in the terminal that will launch MiMo Code:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Merge this configuration into `~/.config/mimocode/mimocode.json` on macOS or Linux:
```json
{
"model": "anthropic/MODEL_ID",
"small_model": "anthropic/MODEL_ID",
"provider": {
"anthropic": {
"options": {
"apiKey": "{env:LLMGATEWAY_API_KEY}",
"baseURL": "https://api.llmgateway.io/v1"
},
"models": {
"MODEL_ID": {
"name": "Gateway coding model",
"id": "MODEL_ID",
"limit": {
"context": 200000,
"output": 8192
}
}
}
}
}
}
```
Replace every `MODEL_ID` with the exact gateway model ID. Choose a model with tool support from the [live catalogue](https://llmgateway.io/models?features=tools). Adjust the example context and output limits to values supported by that model.
Here `anthropic/` in the top-level selection identifies MiMo Code's local provider. The nested `id` is the model ID sent to LLM Gateway. The provider name selects the Anthropic API format; the base URL sends those requests to the gateway.
> **Using DevPass?** Keep the nested `id` canonical and choose a model included in your plan. Adding an upstream provider prefix to that ID pins routing and is not supported on coding plans.
## Verify a task [#verify-a-task]
```bash
cd your-project
mimo
```
Review the workspace trust prompt. Ask the agent to inspect a function, fix a failing test case, and run the existing tests without changing them. Approve file and command permissions as needed, then review the diff and test output.
Check usage in the workspace that issued your key.
## Troubleshooting [#troubleshooting]
**The request exceeds the model's output limit:** MiMo Code 0.1.15 forces a large output allowance for some model names, overriding `limit.output`. If your request is rejected, select a compatible model or update MiMo Code; changing the configured limit alone may not fix it.
**A tool schema is rejected:** MiMo Code's tool definitions may exceed what the selected model or upstream provider accepts. Try another tool-capable model and inspect the returned error.
**Authentication fails:** export the key before starting MiMo Code and confirm that the key is active.
**A model is unavailable:** check the nested model `id`, account access, and plan restrictions.
See the [MiMo Code provider reference](https://github.com/XiaomiMiMo/MiMo-Code/blob/main/packages/opencode/src/skill/builtin/.bundle/mimocode-docs/reference/providers.md) for other configuration options.
# n8n Integration
URL: https://llmgateway.io/guides/n8n
Connect an n8n **OpenAI Chat Model** to LLM Gateway to use an accessible model in an AI workflow. This walkthrough uses a chat trigger and an AI Agent.
## Video walkthrough [#video-walkthrough]
## Create a chat workflow [#create-a-chat-workflow]
1. Add **On chat message** as the first step. The canvas names it **When chat message received**.
2. Connect it to an **AI Agent** node.
3. Keep the agent's prompt source connected to the chat trigger. Its message expression is `{{ $json.chatInput }}`.
4. Click the plus under the agent's **Chat Model** connector and choose **OpenAI Chat Model**.
For a first connection test, leave memory and external tools disconnected.
## Add the gateway credential [#add-the-gateway-credential]
In **OpenAI Chat Model**, click **Connect to OpenAI** or create a new OpenAI credential from the credential selector.
| Field | Value |
| --------------- | ------------------------------ |
| API Key | Your LLM Gateway workspace key |
| Organization ID | Leave blank |
| Base URL | `https://api.llmgateway.io/v1` |
Save the credential and select it on the model node. The OpenAI credential selects the API format; the base URL directs requests to LLM Gateway.
Keep the key in n8n's credential store, rather than in a prompt or workflow expression.
## Configure the chat model [#configure-the-chat-model]
1. Turn **Use Responses API** off for this Chat Completions walkthrough.
2. Change the model selector to **By ID** and enter the exact ID from the [live catalogue](https://llmgateway.io/models).
3. For an agent that calls tools, choose a model with tool support. Set any output token limit within that model's supported range.
With a [DevPass](https://devpass.llmgateway.io) key, choose a canonical model included in your plan. Upstream provider prefixes pin routing and are not supported on coding plans.
## Run and inspect [#run-and-inspect]
Return to the canvas, click **Open chat**, and send a short prompt. Check the answer and the execution log for successful **AI Agent** and **OpenAI Chat Model** steps.
The gateway request belongs to the workspace that issued your key. Review its usage in that workspace's dashboard. n8n's execution details help identify which workflow step made the request.
Once the connection works, add memory or approved tools as needed. Review permissions before connecting actions that change external systems.
## Troubleshooting [#troubleshooting]
**Authentication fails:** check the saved credential, active key, and exact base URL, including `/v1`.
**The model is absent from the picker:** use **By ID** with an accessible model from the live catalogue.
**The model request fails:** confirm **Use Responses API** is off for this setup, then inspect the failing model step's error and token settings.
**The agent has no prompt:** connect the chat trigger and check the `chatInput` expression.
See the official [OpenAI Chat Model reference](https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatopenai/) for node options.
# Oh My Pi Integration
URL: https://llmgateway.io/guides/oh-my-pi
[Oh My Pi](https://omp.sh) (`omp`) is a terminal coding agent with file editing, shell, language-server, and debugger tools. Connect it to LLM Gateway with a pay-as-you-go or DevPass API key.
## Video walkthrough [#video-walkthrough]
## Install Oh My Pi [#install-oh-my-pi]
On macOS or Linux:
```bash
curl -fsSL https://omp.sh/install | sh
omp --version
```
See the [installation guide](https://omp.sh/docs) for other platforms and package managers.
## Connect LLM Gateway or DevPass [#connect-llm-gateway-or-devpass]
Create an API key in your [LLM Gateway dashboard](https://llmgateway.io/dashboard) or [DevPass dashboard](https://devpass.llmgateway.io/dashboard). Export it in the terminal where you will run Oh My Pi:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Create or update `~/.omp/agent/models.yml`. Merge this entry into any existing `providers` mapping:
```yaml
providers:
llmgateway:
baseUrl: https://api.llmgateway.io/v1
api: openai-completions
apiKey: LLMGATEWAY_API_KEY
discovery:
type: openai-models-list
```
`apiKey` names the environment variable. Discovery loads the gateway's `/v1/models` catalogue, so you do not need to maintain a model list in the configuration. The same endpoint works with either kind of key; the key determines your workspace and billing.
## Select a model [#select-a-model]
Start Oh My Pi in your project:
```bash
cd your-project
omp
```
On first launch, finish the setup wizard; the configured provider appears in the model step.
Run `/model`, choose **llmgateway**, and select a text model with tool support from the [live catalogue](https://llmgateway.io/models?features=tools). With DevPass, choose a model supported by your plan.
To select a model when launching, replace `MODEL_ID` with its canonical catalogue ID:
```bash
omp --model llmgateway/MODEL_ID
```
Here, `llmgateway/` selects the custom provider inside Oh My Pi. It is not an upstream provider pin. Keep the remaining model ID canonical for DevPass routing.
## Verify the connection [#verify-the-connection]
Ask Oh My Pi to fix a small failing test in your project:
```text
Read the failing test, make the smallest fix, run the tests again,
and summarize the result. Do not edit the tests.
```
Review the diff and test output, then check usage in the dashboard for the workspace that issued your key.
For a one-shot task:
```bash
omp --model llmgateway/MODEL_ID -p "Explain this project without changing files"
```
## Troubleshooting [#troubleshooting]
* **Provider missing:** Check `~/.omp/agent/models.yml`, including YAML indentation, then restart `omp`.
* **Authentication failed:** Export `LLMGATEWAY_API_KEY` in the same shell before launching the agent.
* **Model rejected:** Select a tool-capable model available to your account. DevPass does not support upstream provider-pinned model IDs.
* **Discovery failed:** Check the base URL and use `openai-models-list` for the gateway's OpenAI-compatible catalogue.
See the [Oh My Pi model configuration reference](https://github.com/can1357/oh-my-pi/blob/main/docs/models.md) for additional settings.
# OpenClaw Integration
URL: https://llmgateway.io/guides/openclaw
[OpenClaw](https://openclaw.ai) runs agents locally and connects them to messaging channels. Configure LLM Gateway as a custom model provider, then verify a local task before connecting a channel.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Use a Node.js version supported by the current [OpenClaw installation guide](https://docs.openclaw.ai/install). The recorded version requires Node 24.16+ or 26.1+.
```bash
pnpm add -g openclaw
openclaw --version
```
## Configure the provider [#configure-the-provider]
Export a key from the workspace you want to use:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Merge this provider into `~/.openclaw/openclaw.json`. Replace `MODEL_ID`, the display name, and the example limits with values for your chosen model from the [live catalogue](https://llmgateway.io/models?features=tools).
```json
{
"models": {
"mode": "merge",
"providers": {
"llmgateway": {
"baseUrl": "https://api.llmgateway.io/v1",
"apiKey": "${LLMGATEWAY_API_KEY}",
"api": "openai-completions",
"models": [
{
"id": "MODEL_ID",
"name": "Gateway coding model",
"contextWindow": 200000,
"maxTokens": 8192
}
]
}
}
},
"agents": {
"defaults": {
"model": { "primary": "llmgateway/MODEL_ID" }
}
}
}
```
`llmgateway/` in the primary model names OpenClaw's local provider entry. The nested `id` is the model identifier sent to LLM Gateway.
With a [DevPass](https://devpass.llmgateway.io) key, retain OpenClaw's local `llmgateway/` prefix and use a canonical model ID included in your plan. Do not add an upstream provider prefix inside the nested model ID.
## Verify a local agent task [#verify-a-local-agent-task]
From a small project you can review, run:
```bash
openclaw agent exec --config ~/.openclaw/openclaw.json --cwd . --code-mode direct "Read the failing test, fix the implementation, and run the tests. Do not change the tests or use subagents."
```
`agent exec` runs one agent turn without a running OpenClaw gateway. It can execute commands and change files in the selected workspace, so use a controlled project. A successful exit alone does not prove the task was completed: inspect the diff and run the tests independently.
For a focused coding workflow, restrict the tool policy in your configuration:
```json
{
"tools": {
"profile": "coding",
"allow": ["read", "write", "edit", "exec", "process"]
}
}
```
Merge this with your configuration rather than replacing the provider settings. Review the [OpenClaw agent command reference](https://docs.openclaw.ai/cli/agent) for execution policy and isolation options. `--auth-env-only` cannot be combined with `--config`.
## Connect channels after verification [#connect-channels-after-verification]
Follow OpenClaw's channel-specific setup for the messaging service you use. Review who can reach the agent and which tools it may call before enabling incoming messages.
Requests use the workspace associated with your gateway key. Review model usage and errors in that workspace's dashboard.
## Troubleshooting [#troubleshooting]
**Startup rejects Node.js:** update to a supported runtime and check the version in the shell launching OpenClaw.
**The model is unavailable:** check the primary provider alias, nested model ID, account access, and catalogue limits.
**The agent only describes a plan:** verify that tools are enabled and the selected model actually returns tool calls. Try a compatible tool-capable model and inspect the resulting file changes; a text-only answer is not evidence of execution.
**A key is missing:** export the environment variable before launching OpenClaw, including when starting it through a service manager.
# OpenCode Desktop Integration
URL: https://llmgateway.io/guides/opencode-desktop
[OpenCode Desktop](https://opencode.ai/download) is a desktop interface for agent sessions in local projects. Its built-in provider picker includes LLM Gateway and DevPass.
## Video walkthrough [#video-walkthrough]
## Install and connect [#install-and-connect]
Download OpenCode Desktop from the [official site](https://opencode.ai/download).
1. Open the provider connection control on the start screen.
2. Search for **LLM Gateway**.
3. Choose **LLM Gateway** for pay-as-you-go usage or **DevPass (LLM Gateway)** for a coding plan.
4. Enter an API key from the matching dashboard and click **Continue**.
The built-in provider supplies the endpoint. You do not need a manual base URL for the hosted gateway.
## Open a project [#open-a-project]
Use the project picker below the composer and select **Add project**. Choose the local folder where you want the agent to work.
Check the project name before submitting a task. Start with a small repository whose changes you can review.
## Choose a model [#choose-a-model]
Use the model picker in the composer to select a tool-capable model from your connected provider. The [live catalogue](https://llmgateway.io/models?features=tools) lists current capabilities and availability.
For DevPass, choose a canonical model included in your plan. Upstream provider prefixes pin routing and are not supported on coding plans.
## Verify a small change [#verify-a-small-change]
Ask OpenCode to inspect a function, fix a failing test case, and run the existing tests without changing them. Review permissions before approving requested actions.
Expand the tool activity to inspect edits and shell output. Check the test result and resulting diff before keeping the change. Requests appear in the workspace that issued your API key.
## Troubleshooting [#troubleshooting]
**The provider is missing:** update OpenCode Desktop and search the complete provider list.
**Authentication fails:** check that your key is active and matches the selected billing mode.
**The agent works in the wrong folder:** use the project picker before starting a session.
**A model is unavailable:** confirm its exact ID, tool support, and availability to your account or plan.
# OpenCode Integration
URL: https://llmgateway.io/guides/opencode
[OpenCode](https://opencode.ai) is an open-source coding agent for your terminal, desktop, and editor. LLM Gateway is a built-in provider, with usage tracked in your gateway dashboard.
This walkthrough was verified with OpenCode 1.18.27, including a file edit and a successful test run.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Use the [OpenCode download page](https://opencode.ai/download) for your platform, or install the CLI:
```bash
pnpm add -g opencode-ai
opencode --version
```
## Connect your API key [#connect-your-api-key]
Start OpenCode in your project:
```bash
opencode
```
Run `/connect`, search for **LLM Gateway**, and enter a key from your [LLM Gateway dashboard](https://llmgateway.io/dashboard). OpenCode saves credentials for later sessions.
Open `/models` to choose a model. Browse the [live catalogue](https://llmgateway.io/models) for current capabilities and pricing.
> **Using DevPass?** Select a canonical model ID without an upstream provider prefix. Provider-pinned routing is not available on coding plans.
## Configure with an environment variable [#configure-with-an-environment-variable]
For scripts or a project-specific configuration, set your key:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Add an `opencode.json` in the project root:
```json
{
"provider": {
"llmgateway": {
"options": {
"apiKey": "{env:LLMGATEWAY_API_KEY}"
}
}
},
"model": "llmgateway/deepseek-v4-flash"
}
```
`llmgateway` is OpenCode's provider ID. The rest of the `model` string is the gateway model ID. The example uses the model tested in this walkthrough; replace it with one from the live catalogue.
The provider already defines the gateway endpoint, so this configuration only supplies the key and model. For a custom endpoint override, use `provider.llmgateway.options.baseURL` with `https://api.llmgateway.io/v1`.
## Verify a coding task [#verify-a-coding-task]
Ask OpenCode to fix a specific file and run its tests:
```text
Fix slugify.ts so all tests pass. Read the files, make the smallest fix,
run node --test slugify.test.ts, and summarize. Do not edit the tests.
```
Review the diff, approve commands as needed, and check the test output. Then confirm the request's model, tokens, and cost in your [dashboard](https://llmgateway.io/dashboard).
You can also run a one-shot task:
```bash
opencode run --model llmgateway/deepseek-v4-flash "Explain this project"
```
## Switching models [#switching-models]
Use `/models` in the terminal, or list the provider's available IDs:
```bash
opencode models llmgateway
```
Copy an exact ID from that output into the `model` field or the `--model` option. Canonical IDs let the gateway choose the upstream provider; provider-prefixed IDs select a specific deployment when your account supports pinned routing.
## Troubleshooting [#troubleshooting]
### Provider not found [#provider-not-found]
Check `opencode --version` and run `opencode models llmgateway`. The verified version uses `llmgateway`; older instructions referring to `llmgateway-providers` may not match your installed release.
### Authentication error [#authentication-error]
Check that the key is active and available in the shell that launches OpenCode. The environment reference uses OpenCode's `{env:VARIABLE_NAME}` syntax.
### Model missing [#model-missing]
Refresh the model picker or restart OpenCode. Copy the exact ID from `opencode models llmgateway` and compare it with the [gateway catalogue](https://llmgateway.io/models).
See [OpenCode's provider documentation](https://opencode.ai/docs/providers/#llm-gateway) for additional configuration options.
# Pi Integration
URL: https://llmgateway.io/guides/pi
[Pi](https://pi.dev) is a terminal coding agent with tools for reading files, editing code, and running commands. Add LLM Gateway as a custom provider to choose from the [live model catalogue](https://llmgateway.io/models) and track usage in one dashboard.
This setup was verified with Pi 0.85.1, including file edits and a successful test run.
## Video walkthrough [#video-walkthrough]
## Install Pi [#install-pi]
Install the current package:
```bash
pnpm add -g @earendil-works/pi-coding-agent
pi --version
```
The older `@mariozechner/pi-coding-agent` package is deprecated. See the [Pi website](https://pi.dev) for installation options.
## Configure the provider [#configure-the-provider]
Create an API key in your [LLM Gateway dashboard](https://llmgateway.io/dashboard), then set it in the shell where you will run Pi:
```bash
export LLMGATEWAY_API_KEY="your_api_key"
```
Add this provider to `~/.pi/agent/models.json`. Merge it with any existing providers:
```json
{
"providers": {
"llmgateway": {
"baseUrl": "https://api.llmgateway.io/v1",
"api": "openai-completions",
"apiKey": "$LLMGATEWAY_API_KEY",
"headers": { "x-source": "pi" },
"models": [
{
"id": "deepseek-v4-flash",
"reasoning": true,
"contextWindow": 1050000,
"maxTokens": 4096
}
]
}
}
}
```
The model is a working example. Choose a text model with tool support from the [models page](https://llmgateway.io/models), and use its exact ID. Match `reasoning` and `contextWindow` to the selected model. This example caps the response at 4,096 tokens with `maxTokens`.
**Keep the `$` in `"$LLMGATEWAY_API_KEY"`.** Current Pi interpolates environment variables only with `$NAME` or `${NAME}`. A plain `"LLMGATEWAY_API_KEY"` is sent as the literal key and causes an authentication error.
> **Using DevPass?** Use a canonical model ID without an upstream provider prefix. Coding plans let the gateway select the serving provider.
## Select the model [#select-the-model]
Start Pi from your project directory and open the model picker:
```bash
pi
```
Type `/model`, then choose the LLM Gateway model. Pi reloads `models.json` when you open the picker, so configuration changes do not require a restart.
You can also select the provider and model when launching:
```bash
pi --provider llmgateway --model deepseek-v4-flash
```
## Verify the connection [#verify-the-connection]
Give Pi a small task with a clear check:
```text
Fix slugify.ts so all tests pass. Read the files, make the smallest fix,
run node --test slugify.test.ts, and summarize. Do not edit the tests.
```
Inspect the resulting diff and test output. Requests appear in your [LLM Gateway dashboard](https://llmgateway.io/dashboard), with the model, token usage, and cost.
For a one-shot command:
```bash
pi --provider llmgateway --model deepseek-v4-flash -p "Explain this project"
```
## Troubleshooting [#troubleshooting]
* **Authentication error:** Check that the shell variable is set, the key is active, and `apiKey` includes the `$` prefix.
* **Model missing:** Copy its exact ID from the live catalogue, then reopen `/model`.
* **Wrong endpoint:** Use `https://api.llmgateway.io/v1` with `api: "openai-completions"`.
* **Unsupported reasoning setting:** Match the model's reasoning support and supported effort levels.
See Pi's [custom provider documentation](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md) for advanced configuration.
# Reasonix Integration
URL: https://llmgateway.io/guides/reasonix
[Reasonix](https://github.com/esengine/DeepSeek-Reasonix) is an open-source coding agent with a terminal interface, desktop app, and editor integration. Its current release supports OpenAI-compatible endpoints, so you can connect it directly to LLM Gateway.
This walkthrough was verified with Reasonix 1.38.1: the agent read a TypeScript project, edited a function, and ran its tests through the gateway.
## Video walkthrough [#video-walkthrough]
## Install [#install]
Install the current native CLI:
```bash
pnpm add -g reasonix
reasonix --version
```
See the [official installation instructions](https://github.com/esengine/DeepSeek-Reasonix#install) for other platforms and installation methods. These instructions apply to Reasonix 1.x; the older 0.x release uses a different configuration format.
## Connect to LLM Gateway [#connect-to-llm-gateway]
Run the provider setup:
```bash
reasonix setup
```
Add an **OpenAI-compatible** provider with these values:
| Setting | Value |
| ------------- | ----------------------------------------------------------------------------------- |
| Provider name | `llmgateway` |
| Base URL | `https://api.llmgateway.io/v1` |
| API key | Your LLM Gateway API key |
| Model | A text model with tool support from the [models page](https://llmgateway.io/models) |
Choose **Save and exit**, then select this provider as your default.
Reasonix stores provider definitions in `~/.reasonix/config.toml` on macOS and Linux, or `%AppData%\reasonix\config.toml` on Windows. A minimal configuration looks like this:
```toml
default_model = "llmgateway"
[[providers]]
name = "llmgateway"
kind = "openai"
base_url = "https://api.llmgateway.io/v1"
model = "deepseek-v4-flash"
api_key_env = "LLMGATEWAY_API_KEY"
headers = { x-source = "reasonix" }
```
The model above is the example used for this walkthrough. Copy your preferred model ID from the live catalogue.
**Save the key through `reasonix setup`.** The `api_key_env` field names the entry in Reasonix's own `.env` file. Current Reasonix reads provider secrets from that file inside its configuration directory; exporting a shell variable alone does not configure the key.
> **Using DevPass?** Use a canonical model ID without an upstream provider prefix. The gateway selects the serving provider for coding plans.
## Try a coding task [#try-a-coding-task]
Start Reasonix from your project directory:
```bash
cd your-project
reasonix
```
Ask it to fix a specific problem and verify the result:
```text
Fix slugify.ts so all tests pass. Read the files, make the smallest fix,
run node --test slugify.test.ts, and summarize. Do not edit the tests.
```
Reasonix can read files, propose edits, and execute tests. Review any permission prompts before allowing commands. For a one-shot task, use `reasonix run "your task"`.
Check the request's model, tokens, and cost in your [LLM Gateway dashboard](https://llmgateway.io/dashboard).
## Troubleshooting [#troubleshooting]
### Missing key or authentication error [#missing-key-or-authentication-error]
Open `reasonix setup` and save your LLM Gateway key for the configured provider. Check that `api_key_env` matches the entry in Reasonix's own `.env` file. Keep that file out of your project repository.
### Model not found [#model-not-found]
Copy the exact ID from the [models page](https://llmgateway.io/models). In Reasonix, `--model llmgateway` selects the configured provider; the provider's `model` field selects the gateway model.
### Requests go to another provider [#requests-go-to-another-provider]
Set `default_model = "llmgateway"`, or launch with `reasonix --model llmgateway`. Check for a project-level `reasonix.toml`, which can override your user configuration.
### Connection errors [#connection-errors]
Use `kind = "openai"` and include `/v1` in the base URL. For configuration and diagnostic commands, see the [Reasonix guide](https://github.com/esengine/DeepSeek-Reasonix/blob/main-v2/docs/GUIDE.md).
# T3 Code Integration
URL: https://llmgateway.io/guides/t3codes
[T3 Code](https://t3.codes) is an open-source desktop, web, and mobile interface for the coding agents installed on your machine. It does not call models itself: it drives Claude Code, Codex, OpenCode, and other agents. Point one of them at LLM Gateway and every thread you start in T3 Code runs on the model you choose from the catalogue.
This walkthrough was verified with T3 Code 0.1.11 and Claude Code 2.1.329: the agent read a TypeScript project, fixed a function, and ran its tests with `glm-5.2` through LLM Gateway.
## Video walkthrough [#video-walkthrough]
## Prerequisites [#prerequisites]
* Install T3 Code from the [download page](https://t3.codes/download) or with `brew install --cask t3-code`. To try the server and web app once without installing, run `npx t3@latest`.
* Install Claude Code using the [Claude Code setup instructions](https://code.claude.com/docs/en/setup), then check `claude --version`. It is the agent this guide configures, and it needs no Anthropic login here. Codex and OpenCode are covered at the end.
* Create an [LLM Gateway API key](https://docs.llmgateway.ai-stage.zibl.ir/learn/api-keys), or use a [DevPass](https://docs.llmgateway.ai-stage.zibl.ir/devpass) plan key.
## Add an LLM Gateway provider to T3 Code [#add-an-llm-gateway-provider-to-t3-code]
In T3 Code, each configured agent is a provider instance. Add a Claude instance that only talks to LLM Gateway.
On first launch, T3 Code shows a welcome page with the agents it found. If no agent is ready, click **Start without an agent**; otherwise click **Start**. Then:
1. Open **Settings → Providers** and click **Add provider**.
2. Choose **Claude**, then click **Next**.
3. Set **Label** to `LLM Gateway` and click **Next**.
4. Set the `CLAUDE_CONFIG_DIR` path to `~/.claude_llmgateway`, then click **Add instance**.
The separate config directory keeps this instance apart from any Anthropic login and conversation state in your default Claude Code setup. T3 Code's [Claude provider documentation](https://github.com/pingdotgg/t3code/blob/main/docs/user/providers-claude.md) covers multiple accounts, launch arguments, and remote machines.
## Set the endpoint and key [#set-the-endpoint-and-key]
Select the new instance, scroll to **Environment**, and click **Add variable** for each of these:
| Variable | Value |
| ---------------------- | --------------------------- |
| `ANTHROPIC_BASE_URL` | `https://api.llmgateway.io` |
| `ANTHROPIC_AUTH_TOKEN` | Your LLM Gateway API key |
| `ANTHROPIC_API_KEY` | Add with an empty value |
Use the base URL exactly as shown. Claude Code adds `/v1/messages` itself. The empty `ANTHROPIC_API_KEY` stops an Anthropic key in your environment from overriding the LLM Gateway key.
Values are sensitive by default: T3 Code stores them separately and shows **Stored secret** instead of the value afterwards. Leave the key sensitive. For the other two, click the lock next to the value first, so they are saved as plain text and stay readable, as in the screenshot below.
The instance status changes to **Authenticated · Custom API endpoint** once the base URL is saved. The status does not check the key, so a wrong key only fails when you send a message.
The default **Claude** instance can stay signed out. A thread uses the instance whose model you select.
## Choose a model [#choose-a-model]
T3 Code sends its built-in Claude models by ID. In T3 Code 0.1.11, 13 of the 14 built-in IDs exist in the LLM Gateway catalogue, and Claude Haiku 5.5 passed the task in this guide without further setup.
For any other model, or a built-in one that LLM Gateway rejects as unsupported, scroll to **Models** in the same instance, click **Add custom model**, and enter the exact ID from the [tool-capable models list](https://llmgateway.io/models?features=tools), for example `glm-5.2`. Custom models can have fewer effort and thinking controls than the built-in ones.
> **Using DevPass?** Use a canonical model ID without an upstream provider prefix, and choose a model included in your plan. LLM Gateway selects the serving provider for coding plans.
## Try a coding task [#try-a-coding-task]
Click **Add project**, choose **Local folder**, and enter your repository's path. T3 Code opens a new thread for the project.
Open the model picker at the bottom of the composer and select a model under your **LLM Gateway** instance. Confirm the selection before your first message: T3 Code preselects a model for new threads, which was Claude Opus 5.5 in this walkthrough.
Then ask for a specific fix and a way to check it. This prompt comes from the demo project, so replace the file and the test command with your own:
```text
Fix slugify.ts so all tests pass. Read the files, make the smallest fix,
run node --test slugify.test.ts, and summarize. Do not edit the tests.
```
By default, new threads use **Full access**, which runs commands and edits without prompts. Switch the thread to **Supervised** in the composer to approve each command and file change.
When the turn finishes, click **Open diff** to review the change before you commit it. Then open your [LLM Gateway dashboard](https://llmgateway.io/dashboard), select the project that issued the key, and open **Activity** to see the request's model, tokens, and cost.
## Use Codex or OpenCode instead [#use-codex-or-opencode-instead]
T3 Code passes an instance's environment variables to Codex and OpenCode in the same way. The same task also passed through both, with Codex CLI 0.159.0 and OpenCode 1.18.29.
* **OpenCode:** click **Add provider**, choose **OpenCode**, and set `LLMGATEWAY_API_KEY` in the new instance's **Environment** variables. The model picker then lists the catalogue under **LLM Gateway** and **DevPass (LLM Gateway)**. The [OpenCode guide](https://docs.llmgateway.ai-stage.zibl.ir/guides/opencode) covers its own configuration.
* **Codex:** create a directory such as `~/.codex_llmgateway` and save the provider block from the [Codex CLI guide](https://docs.llmgateway.ai-stage.zibl.ir/guides/codex-cli) as `config.toml` inside it. Click **Add provider**, choose **Codex**, then **Configure manually**, and set the `CODEX_HOME` path to that directory. Then set `LLMGATEWAY_API_KEY` in the instance's **Environment** variables and pick a model that exists in the catalogue. GPT-5.6 Terra from the built-in list passed the task.
## Troubleshooting [#troubleshooting]
### The instance shows Not found [#the-instance-shows-not-found]
T3 Code cannot find the `claude` binary. Install Claude Code, check `claude --version` in a terminal, then click **Refresh provider status**.
### The instance shows Not authenticated [#the-instance-shows-not-authenticated]
`ANTHROPIC_BASE_URL` is missing, was not saved, or does not start with `https://`. Enter `https://api.llmgateway.io`, then click **Refresh provider status**.
### A thread shows Retrying provider, then a 401 error [#a-thread-shows-retrying-provider-then-a-401-error]
The key is wrong or revoked. The instance status does not check it. Enter a current LLM Gateway key in `ANTHROPIC_AUTH_TOKEN`, then start a new thread.
### Requests still use your Anthropic account [#requests-still-use-your-anthropic-account]
The thread is running on the default **Claude** instance. Open the model picker and select a model under **LLM Gateway**.
### Model not found [#model-not-found]
Copy the exact ID from the [model catalogue](https://llmgateway.io/models) into **Add custom model**. On DevPass, remove any upstream provider prefix.
### The agent stops early or prints raw tool-call text [#the-agent-stops-early-or-prints-raw-tool-call-text]
Claude Code depends on reliable tool calls. Switch the thread to another tool-capable model from the catalogue.
### Codex reports a missing environment variable [#codex-reports-a-missing-environment-variable]
A Codex session that started before you saved `LLMGATEWAY_API_KEY` keeps its old environment. Restart T3 Code, then start a new thread.
# VS Code Integration
URL: https://docs.llmgateway.ai-stage.zibl.ir/guides/vscode
The official [LLM Gateway extension](https://marketplace.visualstudio.com/items?itemName=llmgateway.llmgateway-vscode) adds LLM Gateway to the Copilot Chat model picker in VS Code. Connect your key once, then choose from the chat models available to your account.
Copilot Chat and agent mode support BYOK models. Copilot's inline code
completions (the gray autocomplete suggestions accepted with Tab) currently do
not support BYOK or custom endpoints, including LLM Gateway.
Verified with VS Code **1.135.0** and the LLM Gateway extension **0.1.0**. The video demonstrates model configuration and a real response without GitHub sign-in.
## Video walkthrough [#video-walkthrough]
## Prerequisites [#prerequisites]
* VS Code 1.134.0 or later with Copilot Chat available.
* An LLM Gateway API key from your [dashboard](https://llmgateway.io/dashboard), or a [DevPass](https://devpass.llmgateway.io) plan key.
## Install and connect [#install-and-connect]
1. Install **LLM Gateway**, published by **llmgateway**, from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=llmgateway.llmgateway-vscode).
2. Open the chat view, click the model picker, and choose **Manage Models…**.
3. Select **LLM Gateway** and enter your API key when prompted.
4. If VS Code prompts you to configure BYOK utility models, set **Chat: Byok Utility Model Default** to **Main Agent Model**.
5. Select an LLM Gateway model from the picker and send a message.
You can also install from the terminal:
```bash
code --install-extension llmgateway.llmgateway-vscode
```
The gateway URL is already configured. Your key is stored in VS Code's secret storage, never in settings files. Run **LLM Gateway: Set API Key** from the Command Palette to replace it, or **LLM Gateway: Clear API Key** to remove it.
## Choose a model [#choose-a-model]
The extension fetches models using your key and lists active chat models with streaming support. Your organization's model access rules and DevPass plan restrictions apply. Browse the [models page](https://llmgateway.io/models) for current capabilities and pricing.
For agent mode, select a model with tool calling. Image attachments require a model with image input support. Responses stream into the chat view.
Both PAYG and DevPass keys use the same setup. PAYG requests use your gateway billing configuration; DevPass requests follow your plan's model access and usage limits. The extension sends canonical model IDs, so no provider prefix is needed for DevPass.
BYOK chat works without GitHub sign-in or a Copilot plan. Utility tasks can use the selected model; semantic search and inline completions still have separate authentication requirements. See the [VS Code model documentation](https://code.visualstudio.com/docs/agent-customization/language-models).
## Settings [#settings]
Search for **LLM Gateway** in VS Code Settings to configure:
| Setting | Default | Purpose |
| ---------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------- |
| `llmgateway.baseUrl` | `https://api.llmgateway.io/v1` | Change the endpoint for a self-hosted gateway. Include `/v1`. |
| `llmgateway.models` | `[]` | Limit the picker to specific model IDs. An empty list shows all eligible chat models your key can access. |
| `llmgateway.reasoningEffort` | `default` | Override reasoning effort for reasoning-capable models. Choose a level supported by the selected model. |
Run **LLM Gateway: Refresh Models** to reload the model list, or **LLM Gateway: Open Dashboard** to review usage.
## Troubleshooting [#troubleshooting]
### Models do not appear [#models-do-not-appear]
Check that the extension is enabled and VS Code meets the minimum version. Run **LLM Gateway: Set API Key**, then **LLM Gateway: Refresh Models**. If you configured `llmgateway.models`, clear it to `[]` to see all eligible models for your key.
### Authentication fails [#authentication-fails]
A `401` response clears the stored key. Run **LLM Gateway: Set API Key** with an active key from your dashboard.
### Credits or plan limits [#credits-or-plan-limits]
Read the gateway's error message. PAYG accounts may need credits; DevPass accounts may have reached a plan limit. Check the relevant dashboard before retrying.
For connection errors, open **View → Output** and select **LLM Gateway**. If you use a self-hosted gateway, check `llmgateway.baseUrl`.
Source code and issue reporting are available in the [extension repository](https://github.com/theopenco/llmgateway-vscode).
# Coding Agents
URL: https://docs.llmgateway.ai-stage.zibl.ir/learn/coding-agents
The Coding Agents section of the [DevPass dashboard](https://devpass.llmgateway.io/dashboard)
breaks your DevPass usage down by the tool that produced it, so you can tell at
a glance whether your allowance is going to Claude Code, Cursor, OpenCode, or
something else.
Agents are recognised from the `x-source` header their requests send. See
[Guides](https://docs.llmgateway.ai-stage.zibl.ir/guides) for supported tools and setup instructions. Some recognised
agents, such as SoulForge, do not have a setup guide yet.
The overview lists the **last 7 days**. Open an agent to pick a wider window.
If nothing shows up yet, point your tool at DevPass with the two environment
variables from the dashboard's Quick start card and run it once.
## Agent Cards [#agent-cards]
| Field | Description |
| --------------- | ------------------------------------------------ |
| **Name** | The coding tool, matched from its request source |
| **Total cost** | Spend attributed to this agent |
| **Requests** | Number of API requests |
| **Tokens** | Prompt and completion tokens combined |
| **Last active** | When the agent last sent a request |
Cards use hourly aggregates for the entire window, regardless of how many individual requests are loaded. A request that falls back counts once; billed costs and tokens include every attempt. Last active identifies the latest hourly bucket containing usage.
Click a card to open the agent's detail page.
## Agent Detail [#agent-detail]
The header repeats the agent's totals for the selected period and holds the
two controls for the page. Totals include the first and current hours; the beginning of each window is rounded down to the hour.
Historical source counts are repaired where complete request history is still retained. Counts from expired or partly pruned history stay unchanged because they cannot be reconstructed reliably.
The controls are:
* **Time range** — 1h, 4h, 24h, 7d or 30d (7d by default), stored in the URL so
the view can be shared.
* **Export CSV** — downloads every request in the period, not just the rows
currently loaded.
Below it are three blocks:
**Model usage chart** — spend over time, split by model.
**Model usage table** — one row per model with Provider, Requests, Tokens,
Cost, Cache cost, and a share-of-tokens bar. Every column header sorts.
**Requests** — the individual calls, newest first, each showing the model used,
cache status, token count and cost. More rows load as you scroll, or with
**Load more**.
## Related pages [#related-pages]
* [**Model Categories & Fair Use**](https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories) — which models
count against the premium allowance
* [**Agents Monitoring**](https://docs.llmgateway.ai-stage.zibl.ir/learn/agents) — the same breakdown for a regular
gateway project, with sessions and BYOK filtering
# Model Categories & Fair Use
URL: https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories
**Plan changes from October 15, 2026**
DevPass subscription prices stay the same, but included usage decreases. Daily
and premium weekly caps and Reset Pass benefits change on October 15; existing
monthly allowances change at the first renewal on or after that date. New
subscriptions from that date start with the new allowance. Review
the [dated plan-change
notice](https://devpass.llmgateway.io/legal/terms#october-2026-plan-changes)
before subscribing.
Every model in the gateway is sorted into a category. Categories power dashboard filtering, analytics, and — for DevPass coding plans — the fair-use limits that keep flagship models available to everyone.
## Categories [#categories]
| Category | Description |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| **Premium** | High-cost frontier / flagship models — priced at **$15+ per million output tokens** or **$5+ per million input tokens** |
| **Standard** | Every other model — the broad catalog of fast, cost-effective everyday models |
The classification is computed automatically from catalogue prices — there is no hand-picked list. Active public discounts count: a model on a promotion that brings every provider below both thresholds is standard while the promotion runs. Organization-specific discounts do not change the category. To see exactly which models are premium right now, check the live [**Premium Models**](https://llmgateway.io/models/premium) page, or browse the full catalog on the [**Supported Models**](https://llmgateway.io/models) page and filter by use case, capabilities, provider, price, and context size. On the [DevPass models directory](https://devpass.llmgateway.io/models), you can additionally filter by pricing tier, since the premium/standard distinction only affects DevPass fair-use limits.
## Fair-use caps on premium models (DevPass only) [#fair-use-caps-on-premium-models-devpass-only]
Fair-use caps apply **only to DevPass** — the fixed-price monthly plans for
coding tools (Lite, Pro, Max). They do **not** apply to the LLM Gateway API or
pay-as-you-go credits: when you call the API directly, premium models are
limited only by your credit balance, with no weekly cap.
Premium models are the most expensive to run, so DevPass plans apply a **weekly fair-use cap** on premium usage. The cap works on a fixed 7-day window: the window opens with your first premium-model request, all premium usage during those 7 days counts against the cap, and the full allowance resets at once when the window ends. It sits on top of the plan's normal monthly credit allowance. The cap scales with each plan: it's a share of your current cycle's credit allowance (including any credits carried over at renewal or rolled over from an upgrade), so higher tiers get a larger weekly premium allowance.
| DevPass plan | Premium fair-use cap (per week) |
| ------------ | ------------------------------- |
| **Lite** | 10% of monthly credits |
| **Pro** | 12% of monthly credits |
| **Max** | 15% of monthly credits |
Within DevPass, the weekly cap applies only to **premium** models. Standard
models do not use the weekly premium allowance, but still share the daily
usage cap and monthly plan allowance.
Once a DevPass plan reaches its weekly premium cap, premium requests are paused until the current 7-day window ends — usage does not gradually free up over time. The reset countdown runs from when the window opened, not from when you hit the cap, so the full allowance can return anywhere from moments to 7 days after you reach the limit. Standard models remain available within the daily usage cap and monthly allowance. Upgrading the DevPass plan raises the weekly cap.
The fair-use window is a limiter on the plan allowance, not on your own money: with [pay-as-you-go overflow](https://docs.llmgateway.ai-stage.zibl.ir/learn/payg-overflow) enabled and a positive credits balance, premium requests past the weekly cap keep flowing and bill that balance at provider rates — mid-cycle with monthly allowance remaining, or after the monthly pool is fully used alike. Standard models keep drawing from the plan allowance as usual.
## Daily pacing allowance (DevPass only) [#daily-pacing-allowance-devpass-only]
Separately from the premium cap, every DevPass plan paces its monthly allowance with a **daily pacing allowance** that applies to all models, standard and premium alike. Each rolling 24-hour window can use a published share of the monthly credits — the window opens with the first request, everything spent from the plan allowance during those 24 hours counts against it, and the full share is available again once the window ends. The share is taken from your current cycle's credit allowance, including any credits carried over at renewal or rolled over from an upgrade.
| DevPass plan | Daily pacing allowance (per rolling 24h) |
| ------------ | ---------------------------------------- |
| **Lite** | 8% of monthly credits |
| **Pro** | 9% of monthly credits |
| **Max** | 10% of monthly credits |
When a window fills, requests are paused until it rolls over; the gateway's `402` response says how long that is. Like the premium cap, pacing limits only the plan allowance: with [pay-as-you-go overflow](https://docs.llmgateway.ai-stage.zibl.ir/learn/payg-overflow) enabled and a positive credits balance, requests past the daily share keep flowing and bill that balance at provider rates. Upgrading the plan raises the share, and the current dollar figures for each tier are on the [DevPass pricing page](https://devpass.llmgateway.io/pricing).
## Reset Passes [#reset-passes]
You don't have to wait out the window: redeeming a [**Reset Pass**](https://docs.llmgateway.ai-stage.zibl.ir/learn/reset-passes) instantly restores the full weekly premium allowance and starts a fresh 7-day window. A pass removes the weekly limit only — it grants no extra credits and does not affect daily pacing, so premium usage after a reset still draws from the plan's monthly allowance. Max includes 2 passes per billing cycle; on every tier, extra passes are a one-time purchase from the DevPass dashboard. See the [Reset Passes page](https://docs.llmgateway.ai-stage.zibl.ir/learn/reset-passes) for how redemption, included passes, and billing work.
## Provider routing on DevPass [#provider-routing-on-devpass]
DevPass plans always use the gateway's [smart routing](https://docs.llmgateway.ai-stage.zibl.ir/features/routing): request a model by its plain id (e.g. `claude-sonnet-5`) and the gateway picks the best provider in real time based on uptime, throughput, price, and prompt-cache support. [Sticky session routing](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#sticky-session-routing) still keeps each coding session on one provider automatically, so upstream prompt caches stay warm across a conversation.
Both `auto` and `price` routing account for cached input costs using your project's recent model usage once enough history exists, and assume **90% cached input and a 2% output:input ratio** before then, including when choosing a provider for a short opening session prompt. This helps sessions that repeatedly reuse context choose providers with lower expected token costs. See [how routing learns your token mix](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#smart-routing-algorithm) for the sample requirements, defaults, and override behavior.
**Provider pinning is not available on DevPass.** Provider-prefixed model ids
such as `openai/gpt-4o` — which pin a request to one specific provider on
pay-as-you-go — are rejected with a `403` on DevPass coding plans, as is
custom provider routing. If you need to target an exact provider or region,
use [pay-as-you-go credits](https://llmgateway.io) with the LLM Gateway API,
where [provider-specific routing](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#provider-specific-routing)
is fully supported.
# Pay-As-You-Go Overflow
URL: https://docs.llmgateway.ai-stage.zibl.ir/learn/payg-overflow
**Plan changes from October 15, 2026**
DevPass subscription prices stay the same, but included usage decreases. Daily
and premium weekly caps and Reset Pass benefits change on October 15; existing
monthly allowances change at the first renewal on or after that date. New
subscriptions from that date start with the new allowance. Review
the [dated plan-change
notice](https://devpass.llmgateway.io/legal/terms#october-2026-plan-changes)
before subscribing.
By default a DevPass plan is a hard cap: once the monthly allowance is fully used, requests are rejected until renewal. **Pay-as-you-go overflow** is an opt-in on the DevPass **Usage** page that keeps requests flowing past the allowance — extra usage bills a credits balance at provider rates, with the same API key and the same coding agents. The Usage page also carries the full allowance meters, the [weekly premium allowance](https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories), [Reset Passes](https://docs.llmgateway.ai-stage.zibl.ir/learn/reset-passes), and the model usage chart.
Overflow is **off by default** — until you enable it, nothing ever charges
past your subscription price. It never touches your plan allowance either:
credits cover only usage the plan itself wouldn't serve — spend past the
monthly pool, the daily usage cap, and premium usage past the weekly cap.
## When overflow applies [#when-overflow-applies]
| Situation | Overflow off (default) | Overflow on |
| ------------------------------------------- | ---------------------------- | ---------------------------------- |
| Within all plan limits | Plan credits | Plan credits |
| Daily usage cap reached | Requests rejected with `402` | Requests bill your credits balance |
| Monthly allowance exhausted | Requests rejected with `402` | Requests bill your credits balance |
| Weekly premium cap hit, allowance remaining | Reset Pass or wait | Premium models bill your balance |
| Weekly premium cap hit, allowance exhausted | Requests rejected with `402` | Premium models bill your balance |
| Credits balance empty | — | Requests rejected with `402` |
The weekly premium fair-use cap limits what the **plan allowance** pays for, not what your own balance can: with overflow on and a positive balance, premium requests past the cap keep flowing and bill your credits at provider rates, while standard models keep drawing from the monthly allowance as usual. A [Reset Pass](https://docs.llmgateway.ai-stage.zibl.ir/learn/reset-passes) is still the way to keep that premium spend inside your already-paid plan allowance instead of on the balance. Once the monthly pool itself is gone, overflow covers everything.
If the allowance runs out with overflow off (or with an empty balance), the gateway's `402` says what to do:
```json
{
"error": {
"message": "Dev Plan credit limit reached. Upgrade your plan or wait for renewal on 8/24/2026. Or enable pay-as-you-go overflow in your DevPass dashboard to keep going past your allowance.",
"type": "invalid_request_error",
"code": "billing_error"
}
}
```
## Daily usage cap [#daily-usage-cap]
The daily cap applies to **all models** in a rolling 24-hour window, independently of the monthly allowance and weekly premium cap. It can be reached while both other meters still show unused allowance.
The dashboard Overview and Usage pages show daily usage, the reset time, and a **Daily usage cap reached** notice explaining whether requests are paused or billing pay-as-you-go credits. Overflow spending does not advance the monthly or weekly premium allowance meters, so those meters can stop below 100% while your credits balance decreases.
When the daily cap rejects a request, the gateway returns `402` identifying the daily cap amount, its all-model scope, the exact UTC reset time, and how to enable overflow or top up. If multiple limits are exhausted, premium requests may receive the weekly-cap error first; with overflow enabled but both the monthly allowance and credits balance empty, the monthly-limit error takes precedence. A Reset Pass resets only the weekly premium allowance, not the daily cap. After the daily reset, requests can draw on the plan again if monthly and applicable weekly allowance remain.
## Topping up [#topping-up]
Enable overflow on the Usage page, pick a preset ($10, $25, $50, $100) or a custom amount between **$10 and $5,000**, and **Top up** — the charge goes to the card already backing your DevPass subscription, with no checkout redirect. Usage itself is metered at provider rates with no markup on tokens; a 5% platform fee applies when you buy credits (plus 1.5% for international cards). Each top-up emails a PDF invoice and appears in your billing history.
Top-ups are idempotent end to end: a double-click or a retried request reuses the same charge instead of creating a second one.
## Auto-reload [#auto-reload]
Turn on **Auto-reload** and the balance refills itself: when it falls below your threshold ($5–$1,000), your reload amount ($10–$5,000) is charged to the saved card automatically.
Guardrails worth knowing:
* **Disabling overflow always disables auto-reload** — you can never buy credits you cannot spend.
* Failed auto-reload charges back off exponentially (1h doubling up to 24h), and auto-reload switches itself off after 7 days of continuous payment failures.
Overflow is available on **every DevPass tier**. If you find yourself covering
a lot of usage from the balance every cycle, a tier upgrade is usually the
better deal: plan allowances turn every subscription dollar into $2 of usage,
while overflow bills at cost. Compare on the [DevPass pricing
page](https://devpass.llmgateway.io/pricing).
# Reset Passes
URL: https://docs.llmgateway.ai-stage.zibl.ir/learn/reset-passes
**Plan changes from October 15, 2026**
DevPass subscription prices stay the same, but included usage decreases. Daily
and premium weekly caps and Reset Pass benefits change on October 15; existing
monthly allowances change at the first renewal on or after that date. New
subscriptions from that date start with the new allowance. Review
the [dated plan-change
notice](https://devpass.llmgateway.io/legal/terms#october-2026-plan-changes)
before subscribing.
DevPass plans include a [weekly fair-use allowance](https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories) for premium frontier models. A **Reset Pass** restores that full allowance the moment you redeem it — no waiting for the rolling 7-day window — and a fresh window starts with your next premium request. The pass card lives on the DevPass dashboard directly under the premium allowance meter, styled as a stamped visa extension: each pass you hold appears as a stamp.
A Reset Pass removes the weekly limit — it does **not** add credits. Premium
usage after a reset draws from your plan's monthly credit allowance exactly as
before; the pass just lets you keep using premium models now instead of
waiting for the window. With [pay-as-you-go overflow](https://docs.llmgateway.ai-stage.zibl.ir/learn/payg-overflow)
enabled, premium usage past the cap bills your credits balance at provider
rates instead — a pass is what brings that spend back inside the plan
allowance you already paid for. And once the monthly allowance itself is
exhausted, overflow is what keeps requests flowing, not a pass.
Reset Passes exist only on **DevPass** (Lite, Pro, Max). Pay-as-you-go API
usage has no weekly premium cap, so there is nothing to reset.
## Included and purchased passes [#included-and-purchased-passes]
| Plan | Included per billing cycle | Extra passes |
| -------- | -------------------------- | ------------ |
| **Lite** | — | $5 each |
| **Pro** | — | $15 each |
| **Max** | 2 | $45 each |
Two kinds of stamps appear on the card:
* **Included passes** come with Max. They refresh every billing cycle, don't roll over, and are always consumed before purchased passes.
* **Purchased passes** are one-time purchases at the tier's price, bound to the tier they were bought for — a pass purchased on Pro is redeemable while you're on Pro. They never expire, so an unused pass applies again whenever you're back on that tier, even after a cancelled plan.
## Redeeming a pass [#redeeming-a-pass]
Click **Use a pass** on the card. Your premium usage for the week is zeroed immediately and the 7-day window restarts with your next premium request. Redemption is deliberately explicit — a pass is never consumed automatically, and it is rejected while your allowance is untouched. Once you've used more than 90% of your monthly credit allowance, the dashboard also asks you to confirm: a reset restores the weekly cap, but only the remaining monthly allowance is available to spend. Once the monthly allowance is fully used, Reset Passes cannot be redeemed.
Standard models are unaffected either way: they never count against the weekly cap.
## Renewal and the weekly window [#renewal-and-the-weekly-window]
The weekly window does not carry over between billing cycles — every monthly renewal starts it fresh:
* **The weekly premium allowance resets in full.** Renewal zeroes your premium usage and starts a new 7-day window at the renewal moment, alongside the monthly credit reset. You never begin a cycle mid-window or with a partially used allowance. The cap is a share of the new cycle's allowance, including any [unused allowance carried over](https://docs.llmgateway.ai-stage.zibl.ir/devpass#unused-allowance).
* **Included passes replenish.** Max's 2 included passes are restored every cycle; unused ones don't roll over. Purchased passes are unaffected — they persist until redeemed.
An immediate tier upgrade restarts your billing cycle and performs the same full reset.
Between renewals the window is **rolling, not on a fixed schedule**. When a 7-day window ends, the next one starts with your next premium request — and a redeemed pass clears the window entirely, so your next premium request starts a fresh 7 days. There is no weekly reset schedule that redeeming late (or early) can shift into the next cycle.
In practice, a 30-day cycle of steady premium usage fits about five weekly windows (starting around days 0, 7, 14, 21, and 28) before any passes. On Max, whose weekly cap is 15% of the monthly allowance, those five windows plus the two included passes already unlock more than the entire monthly credit pool — so even spending exclusively on premium models needs no front-loaded pass redemptions or timing strategy. Redeem when you actually hit the cap. (The [daily pacing allowance](https://docs.llmgateway.ai-stage.zibl.ir/learn/model-categories#daily-pacing-allowance-devpass-only) still applies; a pass resets the weekly window only.)
If you hit the cap from a coding agent, the gateway's `402` response points here:
```json
{
"error": {
"message": "You've used your weekly allowance for premium-tier models on the pro plan. Redeem a Reset Pass from your dashboard for an instant reset, upgrade for a higher allowance, or use any standard model now. Resets in 6 days.",
"type": "invalid_request_error",
"code": "billing_error"
}
}
```
## Buying and billing [#buying-and-billing]
**Buy a pass** shows a confirmation dialog, then charges the payment method saved on your DevPass — no checkout redirect, no subscription change, no proration. Each purchase emails a PDF invoice and appears in the DevPass billing history alongside plan charges. Purchases are paused once you've used more than 95% of your monthly credit allowance — a pass would give you almost nothing to use at that point — and open up again when your credits renew.
An unused pass can be returned: for 7 days after purchase, a purchased pass that hasn't been redeemed can be self-refunded from the billing history. The refund goes back to your payment method, the pass is removed from your passport, and your DevPass plan itself is unaffected.
Reaching for a Reset Pass every week? Upgrading a tier is usually the better
deal — the next tier raises the weekly cap itself and brings a larger monthly
allowance. Compare on the [DevPass pricing
page](https://devpass.llmgateway.io/pricing).
# Health check
URL: https://docs.llmgateway.ai-stage.zibl.ir/health
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create speech
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_audio_speech
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create transcription
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_audio_transcriptions
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Cancel batch
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_batches_cancel
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create batch
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_batches_create
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List batches
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_batches_list
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Retrieve batch
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_batches_retrieve
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Chat Completions
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_chat_completions
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Decisions
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_decisions
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Embeddings
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_embeddings
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Retrieve file content
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_files_content
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Upload file
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_files_create
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Delete file
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_files_delete
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List files
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_files_list
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Retrieve file
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_files_retrieve
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Edit image
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_images_edits
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create image
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_images_generations
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Retrieve key status
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_key_retrieve
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Anthropic Messages
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_messages
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Models
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_models
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Moderations
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_moderations
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# OCR
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_ocr
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create a realtime client secret
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_realtime_client_secrets
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Rerank
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_rerank
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Search
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_search
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# System One
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_systemone
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Video content
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_videos_content
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create video
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_videos_create
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Video log content
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_videos_log_content
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Retrieve video
URL: https://docs.llmgateway.ai-stage.zibl.ir/v1_videos_retrieve
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Anthropic API Compatibility
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/anthropic-endpoint
LLMGateway provides a native Anthropic-compatible endpoint at `/v1/messages` that allows you to use any model in our catalog while maintaining the familiar Anthropic API format
This is especially useful for applications designed for Claude that you want to extend to use other models.
## Overview [#overview]
The Anthropic endpoint transforms requests from Anthropic's message format to the OpenAI-compatible format used by LLMGateway, then transforms the responses back to Anthropic's format. This means you can:
* Use **any model** available in LLMGateway with Anthropic's API format
* Maintain existing code that uses Anthropic's SDK or API format
* Access models from OpenAI, Google, xAI, and other providers through the Anthropic interface
* Leverage LLMGateway's routing, caching, and cost optimization features
## Basic Usage [#basic-usage]
## Configuration for Claude Code [#configuration-for-claude-code]
This endpoint is perfect for configuring Claude Code to use any model available in LLMGateway:
```bash
export ANTHROPIC_BASE_URL=https://api.llmgateway.io
export ANTHROPIC_AUTH_TOKEN=llmgtwy_your_api_key_here
# optional: specify a model, otherwise it uses the default Claude model
export ANTHROPIC_MODEL=gpt-5 # or any model from our catalog
# now run claude!
claude
```
Environment variables are read once at startup. The `/model` picker lists
Claude models only, so non-Claude models are selected with `ANTHROPIC_MODEL`
or `--model`. See the [Claude Code guide](https://docs.llmgateway.ai-stage.zibl.ir/guides/claude-code) for the
settings-file options and gateway model discovery.
### Choosing Models [#choosing-models]
You can use any model from the [models page](https://llmgateway.io/models). Popular options for Claude Code include:
```bash
# Use OpenAI's latest model
export ANTHROPIC_MODEL=gpt-5
# Use a cost-effective alternative
export ANTHROPIC_MODEL=gpt-5-mini
# Use Google's Gemini
export ANTHROPIC_MODEL=gemini-3.1-pro-preview
# Use Anthropic's actual Claude models
export ANTHROPIC_MODEL=claude-sonnet-4-6
```
## Environment Variables [#environment-variables]
When configuring Claude Code or other Anthropic-compatible applications, you can use these environment variables:
### ANTHROPIC\_MODEL [#anthropic_model]
Specifies the main model to use for primary requests.
* **Default**: `claude-sonnet-4-20250514`
* **Example**: `export ANTHROPIC_MODEL=gpt-5`
### ANTHROPIC\_SMALL\_FAST\_MODEL [#anthropic_small_fast_model]
Specifies a smaller, faster model used for background functionality and internal operations.
* **Default**: `claude-3-5-haiku-20241022`
* **Example**: `export ANTHROPIC_SMALL_FAST_MODEL=gpt-5-nano`
```bash
# Example configuration
export ANTHROPIC_BASE_URL=https://api.llmgateway.io
export ANTHROPIC_AUTH_TOKEN=llmgtwy_your_api_key_here
export ANTHROPIC_MODEL=gpt-5
export ANTHROPIC_SMALL_FAST_MODEL=gpt-5-nano
```
## Advanced Features [#advanced-features]
### Making a manual request [#making-a-manual-request]
```bash
curl -X POST "https://api.llmgateway.io/v1/messages" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
],
"max_tokens": 100
}'
```
The endpoint accepts the API key either as `Authorization: Bearer` or as Anthropic's native `x-api-key` header, so `ANTHROPIC_API_KEY=llmgtwy_…` works as well as `ANTHROPIC_AUTH_TOKEN`.
### Response Format [#response-format]
The endpoint returns responses in Anthropic's message format:
```json
{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"model": "gpt-5",
"content": [
{
"type": "text",
"text": "Hello! I'm doing well, thank you for asking. How can I help you today?"
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 13,
"output_tokens": 20,
"cost": 0.0002325,
"cost_details": {
"input_cost": 0.0000325,
"output_cost": 0.0002,
"total_cost": 0.0002325
}
},
"metadata": {
"requested_model": "gpt-5",
"used_model": "gpt-5",
"used_provider": "openai"
}
}
```
`usage.cost` and `usage.cost_details` are what the request was billed in USD, the same figures `/v1/chat/completions` returns (see [Cost Breakdown](https://docs.llmgateway.ai-stage.zibl.ir/features/cost-breakdown)); on streaming responses they are part of the `message_delta` event's `usage`.
`metadata` is the same gateway object `/v1/chat/completions` returns: it names the provider, model and region that served the request, and lists every attempt in `routing` when a fallback happened (see [Routing Transparency](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#routing-transparency)). On streaming responses it is attached to the `message_delta` event.
### Request Format [#request-format]
`/v1/messages` expects Anthropic Messages requests and always answers in Anthropic's format. Because the two formats share `model` and `messages`, an OpenAI Chat Completions body can reach this endpoint by accident — and since unknown parameters are ignored rather than rejected, the request succeeds and returns an Anthropic response body that OpenAI SDKs cannot read. If your client reports an empty completion here, check that it is pointed at `/v1/chat/completions`.
Unknown parameters are deliberately ignored rather than rejected, so a valid Anthropic request is never denied for carrying an extra field. As a consequence, OpenAI-only parameters (`response_format`, `n`, `frequency_penalty`, and similar) have no effect here — the model will not honour them. Use `/v1/chat/completions` if you need them. (`max_completion_tokens`, `stop`, `seed`, and `stream_options` are ignored on `/v1/chat/completions` too — use `max_tokens` for the token limit.) The Anthropic sampling and stop parameters `top_p`, `top_k`, and `stop_sequences` are currently ignored as well, and `temperature` must be between 0 and 1.
A body that is *structurally* OpenAI is rejected by the schema — OpenAI-shaped `tools` (`{"type": "function", "function": {…}}`) or assistant turns with `content: null`. Content blocks whose `type` the gateway does not recognize are instead accepted and silently dropped (so a client sending a newer Anthropic beta block degrades instead of failing every request) — this includes OpenAI content parts such as `image_url`. `image` blocks accept both a `base64` source and a `url` source (`{"type": "url", "url": "https://…"}`). Anthropic `document` blocks are supported: a `base64` (e.g. PDF) or `text` source is forwarded to the provider as file input, with `title` used as the filename; any other source (`url`, file ids) returns a `400` asking for an inline source — see [Document Reading](https://docs.llmgateway.ai-stage.zibl.ir/features/documents). The structural rejections name the mismatch and point at the right endpoint instead of returning an opaque validation error:
```json
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "This endpoint implements Anthropic's Messages API, and the request body uses OpenAI Chat Completions structures (tools[0].function) that Anthropic's format has no equivalent for. Send OpenAI-format requests to /v1/chat/completions instead, or convert the body to Anthropic's Messages format."
}
}
```
Rejected requests are recorded in your logs with a `client_error` finish reason and zero cost, so a malformed client is visible in the activity feed rather than failing silently.
### Prompt Caching [#prompt-caching]
For Claude models, `cache_control` markers on `system` and message content blocks are forwarded to the provider unchanged, including the optional `ttl` (`5m` or `1h`):
```json
{
"model": "claude-sonnet-4-6",
"max_tokens": 100,
"system": [
{
"type": "text",
"text": "",
"cache_control": { "type": "ephemeral" }
}
],
"messages": [{ "role": "user", "content": "Hello!" }]
}
```
Cache usage comes back in Anthropic's native fields: `usage.cache_creation_input_tokens` (tokens written to the cache this request, billed at the write premium), `usage.cache_read_input_tokens` (tokens served from cache at the discounted rate), and `usage.cache_creation` (the per-TTL write breakdown).
A `system` message inside `messages` (as Claude Code sends on recent Claude models) stays at its position instead of being merged into the top-level `system` prompt, so the cached conversation prefix is not rewritten on every turn. Where the upstream model does not accept that role, or does not accept it at that position (it must follow a user turn and precede an assistant turn or end the conversation), it is sent in place as a user message wrapped in `` tags. If system messages interrupt a complete tool-call/result turn, the gateway moves them after all results for that turn so the results remain adjacent to the tool calls. Incomplete turns and unrelated user messages are left unchanged. Claude Code's `tool_addition` and `tool_removal` blocks are accepted and passed to the model as a text note.
Each Claude model has a minimum cacheable prompt length (it varies by model
and is exposed as `min_cacheable_tokens` on `/v1/models`). A `cache_control`
marker on a shorter prompt is accepted but silently not cached — both cache
usage fields stay `0`. See [Provider Cache
Control](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/provider-cache-control) for details.
### Tool choice [#tool-choice]
`tool_choice` (`auto`, `any`, `none`, or `{"type": "tool", "name": …}`) is honoured on every provider: it is translated into the upstream's own forced-tool form (Anthropic `any`/`tool`, OpenAI `required`/named function, Gemini `functionCallingConfig`), and a mapping that cannot force a tool is skipped during routing. `disable_parallel_tool_use: true` is carried as well; on providers without an equivalent it is ignored. An OpenAI-style `tool_choice` value (`"required"`, `{"type": "function", …}`) is dropped rather than rejected.
### Tool definitions and results [#tool-definitions-and-results]
A tool's `strict: true` reaches the Anthropic API (with its structured-outputs beta) and OpenAI-compatible providers as `function.strict`; providers without an equivalent receive the tool without it. `allowed_callers` is forwarded to the Anthropic API only, with the advanced-tool-use beta, and stripped elsewhere. `eager_input_streaming: true` (fine-grained tool streaming) is forwarded to Anthropic models on the Anthropic API, Google Vertex AI, Microsoft Foundry and AWS Bedrock; Claude models that Bedrock serves only through its Converse API take it as the request-wide fine-grained tool streaming beta when every tool sets it. It is stripped elsewhere; `input_json_delta` events are relayed as they arrive from the upstream.
Gemini models take tool schemas through Google's typed `parameters` carrier, which has no `const` or `additionalProperties`. A `const` is sent as a single-member `enum` (typed from the value when the node has no `type`; on non-string nodes, where Vertex rejects `enum`, it becomes an "Allowed values" hint in the description), and an explicit `enum` on the same node wins. `pattern` is forwarded on string nodes. `additionalProperties` is dropped. The same translation applies on `/v1/chat/completions`.
An `image` block inside a `tool_result` (a screenshot returned by a tool, say) reaches the model as an image: an image block on Anthropic models (a result that mixes text and images keeps its order), an `input_image` in the function call output on the OpenAI Responses API, and inline image data right after the function response on Gemini. Chat Completions only takes text on a tool message, so on those providers the text stays in the tool message and the image moves into the user turn that follows the tool results, labelled with the tool call it came from. The same applies to `image_url` parts in a `tool` message sent to `/v1/chat/completions`. Images fetched by the gateway use the same URL guards and size limits as user-turn images; an invalid or blocked URL returns HTTP 400. With URL guards enabled, DNS is checked again when connecting, and redirects are refused.
### Web Search and Web Fetch [#web-search-and-web-fetch]
Anthropic's server-side web search and web fetch tools work on this endpoint. Pass them as usual:
```json
{
"model": "anthropic/claude-haiku-4-5",
"max_tokens": 400,
"messages": [{ "role": "user", "content": "What shipped in Node 24?" }],
"tools": [
{ "type": "web_search_20250305", "name": "web_search" },
{ "type": "web_fetch_20250910", "name": "web_fetch" }
]
}
```
When an Anthropic model on the Anthropic API, Google Cloud, or Microsoft Foundry serves the request, the response carries the content blocks exactly as Anthropic returned them, streamed or not: `server_tool_use` with its input, `web_search_tool_result` and `web_fetch_tool_result` with `encrypted_content`, text blocks with their `citations`, and `usage.server_tool_use`. Replay the assistant turn verbatim on the next request and the blocks reach Anthropic with every field intact, ahead of the turn's text, so the model sees the earlier results.
Web search on other providers works too. The response then carries a `server_tool_use` and `web_search_tool_result` pair rebuilt from the provider's citations, without `encrypted_content`. Those rebuilt blocks are dropped on replay. Anthropic does not offer web search or web fetch on AWS Bedrock, nor web fetch on Google Cloud, and other providers have no web fetch equivalent, so the tool is dropped there. Pin the provider (`anthropic/claude-sonnet-4-6`) when you rely on it.
### Thinking Signatures [#thinking-signatures]
Thinking blocks served by the Anthropic API carry Anthropic's own signatures, so you can continue a conversation started here on Anthropic directly, and the other way round. Other providers serve Claude with their own signatures. Their thinking blocks carry a provider prefix, and the gateway replays a block only to the provider that signed it. A block without a prefix, such as one from a conversation started elsewhere, is replayed to the Anthropic API.
### Tool Search [#tool-search]
Anthropic's server-side [tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) works on this endpoint. Pass a `tool_search_tool_*` tool alongside your catalog and mark the tools that should load on demand with `defer_loading: true`:
```json
{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"messages": [{ "role": "user", "content": "What is the weather in Paris?" }],
"tools": [
{
"type": "tool_search_tool_regex_20251119",
"name": "tool_search_tool_regex"
},
{
"name": "get_weather",
"description": "Get the weather at a specific location",
"input_schema": { "type": "object" },
"defer_loading": true
}
]
}
```
Deferred tools stay out of the rendered tools section, so adding one does not invalidate an existing prompt cache. The response carries the `server_tool_use` and `tool_search_tool_result` blocks; replay them verbatim on the next request and Anthropic keeps expanding the `tool_reference` entries they carry, so Claude reuses a discovered tool instead of searching again. `tool_reference` blocks returned from your own client-side search inside a `tool_result` are forwarded unchanged too.
Send every tool definition on every request, including the deferred ones — Anthropic needs them server-side to run the search. At least one tool must stay non-deferred (normally the tool search tool itself), and a tool cannot carry both `defer_loading: true` and `cache_control`.
**Where it works.** Tool search reaches the provider on the Anthropic API, on Anthropic models served through Google Cloud, and on AWS Bedrock through its Anthropic Messages API, and it needs a Claude 4.5-generation model or newer — older Claude models reject it upstream. On every other provider, including Claude models that Bedrock serves only through its Converse API, the tool search tool and `defer_loading` are dropped and all tools are sent eagerly. The request still succeeds, it just loses the cache and token savings, so pin the provider (`anthropic/claude-sonnet-4-6`) when those savings matter.
### Auto Mode Safeguard Review [#auto-mode-safeguard-review]
In [auto mode](https://code.claude.com/docs/en/permission-modes#server-side-classifier-review), Claude Code asks Anthropic to review risky tool calls as part of its normal requests, at no charge: it sends a `safeguards` field with a paired `anthropic-beta` value, and Anthropic returns the verdicts in `safeguard_results` (on the final `message_delta` event when streaming). The gateway forwards both halves to Claude on the Anthropic API or Amazon Bedrock and returns the verdicts unchanged, so Claude Code keeps using the free server-side checks instead of its own billed classifier requests. Run `/status` in Claude Code to confirm: the **Auto mode server** row reads `Enabled`.
**Routing requirements.** A nonempty `safeguards` field paired with its dated beta restricts automatic selection and retries to providers that support forwarding server-side review. These are the Anthropic API and Claude models on Amazon Bedrock. An incompatible saved session pin is replaced; an explicitly requested incompatible provider, or automatic selection with no compatible provider, returns HTTP `400`, including for streaming requests. A beta header alone does not restrict routing.
Upstream availability still depends on the model, credentials, and rollout. If the provider returns no available verdict, Claude Code can fall back to its own billed classifier requests. To use another provider deliberately, set `CLAUDE_CODE_AUTO_MODE_SERVER=0` before starting Claude Code; its client-side classifier requests are billed normally.
### Gateway Response Cache [#gateway-response-cache]
If [gateway caching](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/gateway-caching) is enabled on the project, a repeated request with the same [cache-key fields](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/gateway-caching#cache-key-generation) — resolved provider and model, messages, and the other keyed parameters; fields outside the cache key and insignificant JSON whitespace don't affect matching, but the key order inside message and tool objects does, and a request routed to a different provider is a cache miss — is replayed from cache instead of being sent upstream. The replayed body keeps the original `id`, content, and token counts, so check the `x-llmgateway-cache: HIT` response header or `metadata.cached`. Send `x-no-cache: true` to bypass the cache for a single request.
# LLM Gateway Authentication, API Keys & IAM Rules
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/api-keys
API keys are the primary method for authenticating with the LLM Gateway. This guide covers creating API keys, managing them, and configuring IAM rules for fine-grained access control.
## Overview [#overview]
LLM Gateway provides comprehensive API key management with the following features:
* **Basic API Key Management**: Create, list, rename, update, and delete API keys
* **Usage Limits**: Set lifetime and recurring spending limits on individual API keys
* **Expiration (TTL)**: Give a key a time-to-live so it disables itself automatically
* **Rotation (Rolling)**: Replace a key's secret in place without losing its settings or history
* **IAM Rules**: Fine-grained access control for models, providers, and pricing
* **Usage Tracking**: Monitor API key usage and costs
* **Status Management**: Enable/disable keys without deletion
### Related key types [#related-key-types]
This page covers gateway API keys (`llmgtwy_…`), the keys you send to the
gateway as a bearer token. LLM Gateway also issues three other kinds of keys,
each with its own page:
| Key | What it is for |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------- |
| [Master keys](https://docs.llmgateway.ai-stage.zibl.ir/features/master-keys) | Manage projects, gateway API keys, IAM rules, and custom models programmatically |
| [Provider keys](https://docs.llmgateway.ai-stage.zibl.ir/learn/provider-keys) | Bring your own upstream provider credentials so requests bill to your provider account |
| [Platform secret keys](https://docs.llmgateway.ai-stage.zibl.ir/features/embeddable-payments) | Mint end-user sessions from your backend when using the Payments SDK (`sk_…`) |
## Enterprise compliance policies [#enterprise-compliance-policies]
Owners and admins can open a key’s **Compliance** action to configure [provider compliance requirements](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#api-key-policies), headquarters restrictions, and provider/model lists. Key policies can narrow access but never relax enabled organization policies or bypass IAM rules. They also work independently when organization policies are disabled.
The organization **Settings → Compliance** page lists active, unexpired keys with explicit policies across all projects. Removing a key policy restores organization-only enforcement.
## Creating API Keys [#creating-api-keys]
### Via Dashboard [#via-dashboard]
1. Navigate to your project in the LLM Gateway dashboard
2. Go to the **API Keys** section
3. Click **Create API Key**
4. Provide a description for your key
5. Optionally set an all-time usage limit
6. Optionally set a recurring usage limit such as `$10 / day` or `$500 / month`
7. Optionally set an expiration (TTL) such as `30 minutes`, `12 hours`, or `7 days`
8. Click **Create**
API keys are shown in full only once during creation. Make sure to copy and
store them securely. New and rolled secrets are stored only as keyed
HMAC-SHA-256 fingerprints, and authentication compares the fingerprint of the
presented secret.
### Programmatically [#programmatically]
Gateway API keys can also be created, listed, updated, and deleted without the
dashboard using a [master key](https://docs.llmgateway.ai-stage.zibl.ir/features/master-keys) — useful when you provision
a key per customer or per environment from your own backend:
```bash
curl -X POST https://internal.llmgateway.io/v1/master/keys \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"projectId": "proj_...",
"description": "Customer ACME — production key",
"periodUsageLimit": "10.00",
"periodUsageDurationValue": 1,
"periodUsageDurationUnit": "day"
}'
```
Usage limits and IAM rules can be configured through the master key API as well.
Expiration (TTL) and rotation are currently dashboard-only. See the [master key
API reference](https://docs.llmgateway.ai-stage.zibl.ir/features/master-keys#create-a-gateway-api-key) for the full
endpoint list.
## Using API Keys [#using-api-keys]
Once you have an API key, use it in the `Authorization` header of your requests:
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer llmgtwy_your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello!"}]
}'
```
Alternatively, send the key in an `x-api-key` header — the convention Anthropic-style clients use, including on the [`/v1/messages` endpoint](https://docs.llmgateway.ai-stage.zibl.ir/features/anthropic-endpoint). When both headers are present, `Authorization: Bearer` takes precedence.
To show DevPass allowance meters in an integration, see the [DevPass Usage
API](https://docs.llmgateway.ai-stage.zibl.ir/developers/devpass-usage).
## Renaming API Keys [#renaming-api-keys]
A key's name is only a label, so you can change it at any time — from the
dashboard, or with the `description` field on [`PATCH
/v1/master/keys/{id}`](https://docs.llmgateway.ai-stage.zibl.ir/features/master-keys#update-a-gateway-api-key) — without
affecting the secret, its usage history, limits, or IAM rules.
## Budget alerts [#budget-alerts]
Enable **API key budgets** in the dashboard's notification settings to receive in-app or email warnings as a key approaches its lifetime or recurring limit. Choose a threshold from 50% to 100%; the default is 80%. See [Notifications](https://docs.llmgateway.ai-stage.zibl.ir/features/notifications) for delivery and access rules.
## Disabling/Enabling API Keys [#disablingenabling-api-keys]
You can disable an API key to stop it from being used, but the key is not deleted and can be re-enabled later.
To deactivate, reactivate, or delete many keys at once, select them on the
project or organization **API Keys** page and use the bulk actions. The list
flags active keys unused for 30+ days (and, more urgently, 90+ days) so you can
find abandoned keys to deactivate. See [API Keys in the
dashboard](https://docs.llmgateway.ai-stage.zibl.ir/learn/api-keys#selecting-keys-and-bulk-actions).
Low-spend keys without a limit show a one-click [limit
suggestion](https://docs.llmgateway.ai-stage.zibl.ir/learn/api-keys#limit-suggestions), such as $10 per week, so a
leaked key cannot run up costs.
## Rotating (Rolling) API Keys [#rotating-rolling-api-keys]
Rolling a key generates a **new secret for the same key** and invalidates the old
one immediately. Everything else about the key is preserved: its name, usage
history and statistics, all-time and recurring limits (including the active
period window), IAM rules, and expiration.
Use this when a secret may have been exposed — in a commit, a log, a CI
artifact, or a shared environment — and you want to cut off the leaked value
without losing the key's spend tracking or access rules.
1. Open the **API Keys** page and pick the key's actions menu
2. Choose **Roll Key** and confirm
3. Copy the new secret and update every client that used the old one
The old secret stops working the moment the key is rolled, and the new secret
is shown only once. Roll during a window where you can update your clients
promptly.
Requests made with the old secret are rejected with a `401 Unauthorized`.
Rolling is limited to regular gateway API keys — the auto-generated Lounge
key cannot be rolled, and Payments SDK [platform secret
keys](https://docs.llmgateway.ai-stage.zibl.ir/features/embeddable-payments) have their own lifecycle.
## Expiration (TTL) [#expiration-ttl]
You can give an API key a **time-to-live (TTL)** when you create it. Set how long
the key should live — in **minutes**, **hours**, or **days** — and it will be
disabled automatically once that time passes. This is ideal for short-lived
integrations, demos, CI jobs, and temporary access.
* A key works normally until its expiration time
* Once expired, the gateway rejects requests with that key with a `401 Unauthorized`
* A background job marks expired keys as **inactive**, so the dashboard reflects
the disabled state
* Keys created without a TTL never expire (the default)
### Reactivating an Expired Key [#reactivating-an-expired-key]
An expired key is paused, not deleted. To bring it back online you must reactivate
it **with a new future expiration** — an expired key cannot be re-enabled while its
TTL is still in the past. Keys that have no TTL, or whose TTL is still in the
future, can be enabled and disabled freely without setting a new expiration.
Expiration is independent of usage limits. A key can hit its TTL before, or
instead of, reaching a spend cap.
## Usage Limits [#usage-limits]
Usage is tracked per API key on the API Keys page. Usage includes both costs
from LLM Gateway credits and usage from your own provider keys when applicable,
giving you complete visibility into total spending per key.
You can set two independent limits for each key:
* **All-time usage limit**: A lifetime spend cap
* **Recurring usage limit**: A spend cap that resets every configured hour, day, week, or month
When a key reaches either limit, requests using that key return `401
Unauthorized` (error code `api_key_usage_limit_exceeded`) until the key is
updated or, for recurring limits, the next usage window starts. This is
separate from IAM rule violations, which return `403 Forbidden`.
Recurring windows support:
* Minimum duration: **1 hour**
* Maximum duration: **12 months**
* Units: **hour**, **day**, **week**, **month**
For the dashboard walkthrough and field-by-field details, see [API Keys in
Learn](https://docs.llmgateway.ai-stage.zibl.ir/learn/api-keys).
## IAM Rules [#iam-rules]
IAM (Identity Access Management) rules provide fine-grained access control over what models, providers, and pricing tiers an API key can access.
### Endpoint coverage [#endpoint-coverage]
Applicable IAM and compliance checks cover every inference path: chat completions, Responses and compaction, Messages, all AI SDK protocol versions, image generation and edits, embeddings, moderation, OCR, rerank, search, typed decisions, speech, transcription, video creation, and realtime. Internal adapters preserve credentials and the configured trusted client IP; retries and fallback cannot widen access. Realtime also checks transcription models before receiving audio and revalidates access when a session enables transcription.
Moderation intentionally ignores model and pricing IAM rules for compatibility. It still enforces provider/IP ceilings and organization/API-key compliance policies.
Authenticated model discovery and AI SDK config omit models blocked by organization/key compliance or IAM. The unauthenticated model catalogue and public MCP discovery remain public metadata.
Behind an edge that overwrites the trusted IP header, configure `GATEWAY_BACKEND_URL` and `API_BACKEND_URL` with trusted private service URLs for MCP hops. Going back through the public edge can replace the caller’s IP with the gateway’s address; do not work around that by trusting alternate headers.
Private key/credit metadata and MCP account/usage reads validate the credential, expiry, current membership, project, organization, and applicable IP restrictions. They remain readable after quota exhaustion. Historical outputs keep their ownership and signed-download checks; model/provider rules do not retroactively turn a public catalogue or an already-authorized historical read into new inference.
`GET /v1/credits` retains the AI SDK account-credit contract: any authorized regular project key can read organization-wide credit figures. This is separate from role-scoped MCP analytics; end-user wallet sessions cannot use the account-credit endpoint.
### Rule Types [#rule-types]
#### Model Access Rules [#model-access-rules]
Control access to specific models:
* **Allow Models**: Only allow access to specific models
* **Deny Models**: Block access to specific models
#### Provider Access Rules [#provider-access-rules]
Control access to specific providers:
* **Allow Providers**: Only allow access to specific providers
* **Deny Providers**: Block access to specific providers
Provider rules can also target your organization's own [custom providers](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers). The generic `custom` entry matches every custom provider, while a `custom:` entry (offered in the selector for each of your custom providers) matches only the custom provider with that name. Model rules can likewise reference a custom-catalog model as `/`.
#### Pricing Rules [#pricing-rules]
Control access based on model pricing:
* **Allow Pricing**: Set constraints on what pricing tiers are allowed
* **Deny Pricing**: Block specific pricing tiers
* **Free vs Paid**: Allow or deny access to free vs paid models
#### IP Address Rules [#ip-address-rules]
IP address rules are available on the **Enterprise** plan only. Contact us at
[contact@llmgateway.io](mailto:contact@llmgateway.io) to enable them for your organization.
Restrict where the API key can be used from by source IP, using CIDR ranges:
* **Allow IP Ranges (CIDR)**: Only permit requests from the listed IPv4/IPv6 CIDRs
* **Deny IP Ranges (CIDR)**: Block requests from the listed IPv4/IPv6 CIDRs
Both IPv4 (e.g. `192.0.2.0/24`) and IPv6 (e.g. `2001:db8::/32`) ranges are supported, and you can mix both in a single rule. To restrict to a single address, use a `/32` (IPv4) or `/128` (IPv6) prefix.
The gateway reads the client IP from a single header, named by the `CLIENT_IP_HEADER` environment variable. On the hosted service the load balancer overwrites that header on every request, so a value sent by the client cannot spoof the address. Self-hosted deployments default to `X-Forwarded-For`; point `CLIENT_IP_HEADER` at a header your reverse proxy overwrites rather than appends to.
Compatibility endpoints preserve this client IP through internal forwarding, so IP rules apply to Messages, Responses (including compaction), Images, and AI SDK requests as well as Chat Completions. Lounge, docs Ask AI and the API explorer, admin reply generation, API-side generation and embeddings, and MCP tools also forward the configured client-IP header.
For self-hosted server-to-server calls, set `GATEWAY_BACKEND_URL` to a trusted gateway origin that preserves this header. It takes precedence over `GATEWAY_URL` for generation requests; browser-facing and signed content URLs still use `GATEWAY_URL`. Sending these calls through an edge that overwrites the header records the calling server’s IP instead. MCP generation uses `GATEWAY_BACKEND_URL`, and MCP account and usage calls use `API_BACKEND_URL`. These explicitly configured backends may use HTTP within a trusted private network and must preserve the header. Public fallbacks (`GATEWAY_URL` and `API_URL`) and the optional `MCP_GATEWAY_URL` override require HTTPS. Keep backend origins private to trusted services.
When an `allow_ip_cidrs` rule is configured and the gateway cannot determine the client IP, the request is denied. Invalid CIDR syntax is rejected at rule-creation time with a `400` error.
### Combining Multiple Rules [#combining-multiple-rules]
* **Allow rules of the same type are unioned**: a request passes if it matches *any* of them. For example, one `allow_models` rule with `["claude-opus-4-6"]` and another with `["claude-fable-5"]` allow both models — exactly as if you had a single rule listing both.
* **Allow rules of different types are combined with AND**: the request must satisfy every configured allow rule type (e.g. the model must be in the allowed models *and* served by an allowed provider).
* **Deny rules always apply**: a request matching any deny rule is rejected, regardless of allow rules.
* **Moderation is special-cased**: `/v1/moderations` runs a fixed moderation model that cannot appear in model allowlists, so only provider and IP rules apply to it — model and pricing rules are skipped.
### Virtual model aliases [#virtual-model-aliases]
A [virtual model](https://docs.llmgateway.ai-stage.zibl.ir/learn/models#virtual-models) alias resolves to the versioned model it currently names before rules run:
* A rule naming the versioned ID covers requests through the alias.
* `deny_models` naming an alias blocks the model it currently resolves to, through the alias or its versioned ID.
* `allow_models` naming an alias admits only requests that use the alias. Add the versioned ID to allow pinned requests too.
* The same applies to end-user session model scopes. When the alias moves to a new version, these rules follow it.
## Member-Level IAM Rules [#member-level-iam-rules]
The same rule types can also be configured **per organization member** by owners and admins on the [Team page](https://docs.llmgateway.ai-stage.zibl.ir/learn/team) (admins cannot modify an owner's rules). Member-level rules act as an organization-wide ceiling for that member:
* A request must pass **both** the member's rules and the API key's rules. Within each level, rules combine exactly as described above.
* Key rules can only **narrow** access further — they can never grant anything the member's rules deny. For example, if an admin restricts a member to a single approved [provider](https://llmgateway.io/providers) with an `allow_providers` rule, the member can create a key rule allowing only a specific model from that provider, but a key rule allowing any other provider has no effect.
* A key with **no rules of its own** is still fully constrained by its owner's member-level rules.
* Member-level rules apply to all regular API keys created by that member, across every project in the organization.
When a request is denied by a member-level rule, the `403` error message states that the restriction is an organization member IAM rule set by the org admin (rather than the key's own IAM configuration), so key holders know who to contact.
Member-level rules can also be managed programmatically via the [master key API](https://docs.llmgateway.ai-stage.zibl.ir/features/master-keys#member-iam-rules), addressing members by membership id or email.
## Team-Level IAM Rules [#team-level-iam-rules]
The same rule types can additionally be configured on an **organization team**. Team rules apply to members with the `developer` role who are assigned to that team, and they are evaluated **before** member and key rules: a request must pass the team's rules, then the member's rules, then the key's rules, and each layer can only narrow what the previous one allowed. When a request is denied by a team-level rule, the `403` error message states that the restriction is inherited from an organization team IAM rule set by the org admin.
## Error Handling [#error-handling]
When API keys encounter IAM rule violations, the API returns a `403` with the standard OpenAI error envelope:
```json
{
"error": {
"message": "Access denied: Model gpt-4 is not in the allowed models list",
"type": "invalid_request_error",
"param": null,
"code": "permission_denied"
}
}
```
Common `403` scenarios:
* Model not allowed by IAM rules
* Provider blocked by IAM rules
* Pricing limits exceeded
* The key's creator reached their member or team spend budget set on the [Team page](https://docs.llmgateway.ai-stage.zibl.ir/learn/team) (error code `member_budget_exceeded`)
* The key's creator no longer has access to the key's project
Key-validity failures return a `401` instead:
* API key disabled or deleted
* API key expired (TTL passed)
* API key rolled, so the old secret is no longer valid
* Usage limit reached
## Migration from Legacy Keys [#migration-from-legacy-keys]
If you have existing API keys without IAM rules:
1. **Backward Compatibility**: Existing keys continue to work without restrictions
2. **Gradual Migration**: Add IAM rules incrementally
3. **Testing**: Test IAM rules in development before applying to production
4. **Monitoring**: Monitor for access denied errors after implementing rules
API keys without IAM rules have unrestricted access to all models and
providers.
# Audit Logs
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/audit-logs
Audit logs provide complete visibility into all actions within your organization. Track who did what, when, and to which resource.
Audit logs are available on the [**Enterprise
plan**](https://llmgateway.io/enterprise) for organization owners and admins.
## What's Tracked [#whats-tracked]
Every significant action is logged with detailed metadata:
| Field | Description |
| ----------------- | -------------------------------------------------------- |
| **Timestamp** | When the action occurred |
| **User** | Who performed the action (name and email) |
| **Action** | What was done (e.g., `api_key.create`, `project.update`) |
| **Resource Type** | Category of the affected resource |
| **Resource ID** | Unique identifier of the affected resource |
| **Details** | Additional context like resource names or changed fields |
## Tracked Actions [#tracked-actions]
The categories below are illustrative, not exhaustive — many more actions are recorded (master keys, custom models, organization teams and team IAM rules, SSO and SCIM events, invites, plan changes, refunds, and others). The action filter dropdown in the dashboard lists the full set.
### Organization Management [#organization-management]
* `organization.update` — Organization settings changed
* `organization.delete` — Organization deleted
### Project Management [#project-management]
* `project.create` — New project created
* `project.update` — Project settings changed
* `project.delete` — Project deleted
### Team Management [#team-management]
* `team_member.invite` — New member invited
* `team_member.invite_accept` — Invite accepted
* `team_member.invite_revoke` — Invite revoked
* `team_member.auto_join` — Member joined via SSO auto-join
* `team_member.update` — Member role changed
* `team_member.budget_update` — Member budget changed
* `team_member.remove` — Member removed
### API Key Management [#api-key-management]
* `api_key.create` — New API key created
* `api_key.roll` — API key secret rolled
* `api_key.update_status` — API key enabled/disabled
* `api_key.update_description` — API key description changed
* `api_key.update_limit` — Usage limit changed
* `api_key.delete` — API key deleted
* `api_key.iam_rule.create` — IAM rule added
* `api_key.iam_rule.update` — IAM rule modified
* `api_key.iam_rule.delete` — IAM rule removed
### Provider Key Management [#provider-key-management]
* `provider_key.create` — Provider key added
* `provider_key.update` — Provider key changed (status, name, limits, and other settings; base URL and token rotation when done through the master key API). Custom providers are recorded as `provider_key.*` events with `provider: "custom"`
* `provider_key.delete` — Provider key removed
### Billing Events [#billing-events]
* `subscription.create` — Subscription started
* `subscription.cancel` — Subscription cancelled
* `subscription.resume` — Subscription resumed
* `payment.credit_topup` — Credits purchased
## Filtering and Search [#filtering-and-search]
Filter logs by:
* **Action** — Specific action type
* **Resource Type** — Category of resource
* **User** — Who performed the action
* **Date Range** — Time period
## Data Retention [#data-retention]
Audit logs are retained for **at least 90 days** on the Enterprise plan — there is currently no automatic expiry.
## Access Control [#access-control]
Only organization **owners** and **admins** can view audit logs. This ensures sensitive activity data is only visible to authorized personnel.
## Get Started [#get-started]
Audit logs are an Enterprise feature. [Contact us](https://llmgateway.io/enterprise) to enable Enterprise for your organization.
# Status and Pricing Badges
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/badges
Badges are small SVG images with live data from the gateway. They need no API key and no account.
Build one on the [badges page](https://llmgateway.io/badges): pick a provider or model, then copy the Markdown, HTML or image URL. Every [provider status page](https://llmgateway.io/status) also carries the snippet for that provider.
## Provider uptime [#provider-uptime]
Shows the share of requests a provider answered without a gateway or upstream error. Client errors are excluded, and only traffic on platform credentials is counted, so the number reflects the provider rather than its callers. It is the same measurement as the provider status pages.
| Query parameter | Values | Default |
| --------------- | -------------------------------------- | ------- |
| `window` | `90d`, `24h` | `90d` |
| `style` | `flat`, `flat-square`, `for-the-badge` | `flat` |
A provider with no measured traffic in the window shows `no data`.
## Model price [#model-price]
Shows the lowest input and output price per million tokens among the providers currently serving the model. It accepts the same `style` parameter.
Models billed per image, second or request have no price badge, because a token price does not describe what they cost.
## Caching [#caching]
Badges are cached for five minutes. Image proxies, such as the one GitHub puts in front of README images, can hold their own copy for longer.
An unknown provider or model ID returns a grey `not found` badge with status `404`.
# Batch API
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/batch
The Batch API runs thousands of requests in the background without managing concurrency, retries, or rate limits yourself. Upload a JSONL file, create a batch, and download the results when it finishes. It follows the OpenAI Batch API, so the OpenAI SDKs work unchanged.
**Same price as live requests, no batch discount**
Each batch request is billed at the same per-token price as the same request
sent live, priced when that request runs. There is no batch discount and no
fee for storing batch files. Discounts that providers offer on their own batch
APIs (often around half price) are not passed through: the gateway runs each
line as a regular request. The Batch API saves you the work of managing
concurrency, retries, and rate limits, not money.
Each request goes through the normal gateway path: routing, fallback, caching, IAM rules, guardrails, logging, and usage limits all apply. Requests show up in your logs with the source `llmgateway-batch`.
## Supported endpoints and models [#supported-endpoints-and-models]
* `/v1/chat/completions`
* `/v1/responses`
* `/v1/embeddings`
Each line's `body` is the same JSON you would send to that endpoint directly. Any model that endpoint accepts works in a batch: chat models on `/v1/chat/completions` and `/v1/responses`, embedding models on `/v1/embeddings`. Realtime, image-generation, and video models, and custom models that only stream, are not supported. The [models page](https://llmgateway.io/models?batch=true) marks every model and provider that supports the Batch API.
The model in each line is checked when that line runs, not when the batch is validated. A line with an unknown or unsupported model fails with the same error the endpoint returns and lands in the error file.
## 1. Prepare the input file [#1-prepare-the-input-file]
Each line is one request. `custom_id` must be unique within the file, `method` is `POST`, and `url` must match the endpoint of the batch. Streaming (`"stream": true`) is not supported.
```jsonl
{"custom_id": "review-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Summarize: ..."}]}}
{"custom_id": "review-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Summarize: ..."}]}}
```
## 2. Upload the file [#2-upload-the-file]
```bash
curl https://api.llmgateway.io/v1/files \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-F purpose=batch \
-F file=@requests.jsonl
```
## 3. Create the batch [#3-create-the-batch]
```bash
curl https://api.llmgateway.io/v1/batches \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input_file_id": "file-abc123",
"endpoint": "/v1/chat/completions",
"completion_window": "24h",
"metadata": {"job": "nightly-reviews"}
}'
```
The batch starts as `validating`. If any line is invalid, the batch moves to `failed` and `errors` lists each problem with its line number. Otherwise it moves to `in_progress`.
Creating a batch, or uploading a file, needs credits when the project pays with credits; otherwise it returns `402`.
## 4. Check status and download results [#4-check-status-and-download-results]
```python
from openai import OpenAI
client = OpenAI(base_url="https://api.llmgateway.io/v1", api_key=LLM_GATEWAY_API_KEY)
batch = client.batches.retrieve("batch_abc123")
print(batch.status, batch.request_counts) # updates while the batch runs
if batch.status == "completed":
output = client.files.content(batch.output_file_id).text
if batch.error_file_id:
errors = client.files.content(batch.error_file_id).text
```
| Status | Meaning |
| ------------- | --------------------------------------------------------------- |
| `validating` | The input file is being checked |
| `failed` | The batch could not start; see `errors` |
| `in_progress` | Requests are running |
| `finalizing` | All requests finished; output files are being prepared |
| `completed` | Results are ready |
| `expired` | The 24-hour window ended; unfinished requests are in the errors |
| `cancelling` | Cancellation requested; running requests are finishing |
| `cancelled` | Cancelled; requests that did not run are in the error file |
The output file holds requests that returned a 2xx response. The error file holds the rest: non-2xx responses, cancelled requests, and requests that did not finish within the window. Lines are in input order and keep your `custom_id`:
```jsonl
{"id":"batch_req_123","custom_id":"review-1","response":{"status_code":200,"request_id":"batch_req_123","body":{"id":"chatcmpl-...","choices":[...]}},"error":null}
{"id":"batch_req_456","custom_id":"review-2","response":null,"error":{"code":"batch_expired","message":"This request did not run within the completion window."}}
```
`response.request_id` matches the request in your [logs](https://docs.llmgateway.ai-stage.zibl.ir/learn/activity). `request_counts.failed` counts requests that returned an error; cancelled and expired requests appear only in the error file.
## Retries and limits [#retries-and-limits]
* Rate limits (429), an overloaded gateway (529), and insufficient credits (402) do not fail a request. It waits and retries until the window ends, so a batch resumes after you top up.
* When the API key reaches its usage limit, or the key's creator reaches their team spend budget, requests wait and retry until the window ends.
* Provider outages the gateway could not route around (`500` with code `upstream_error`), `502`, `503`, `504`, and connections that never reached the gateway are attempted up to three times in total. These errors are not billed, so a retry never charges twice. Other errors are not retried.
* A request is never sent twice once it may have reached the gateway. If the connection drops mid-request, the request times out, or the worker restarts while it runs, it fails with `request_failed` or `request_interrupted` instead of being retried. Such a request may still have been billed, but its result is lost.
* If the API key is deleted, disabled, rolled, or expires, or the gateway rejects it with any other `401`, the stored key is discarded and the remaining requests fail with `authentication_failed`.
* A response larger than 10 MB is not stored; its line fails with `response_too_large`.
* IP restrictions on the API key apply to the client IP that created the batch.
* `/v1/files` and `/v1/batches` have their own per-minute [rate limits](https://docs.llmgateway.ai-stage.zibl.ir/resources/rate-limits), tighter for uploads and batch creation than for reads.
* Batch requests run as regular requests, so they count toward your organization's per-minute and concurrent request limits alongside live traffic. Up to 16 requests per organization run at once.
| Limit | Value |
| -------------------------------------------- | --------- |
| Input file size | 50 MB |
| Requests per batch | 50,000 |
| Completion window | 24h |
| File and batch result lifetime | 30 days |
| Batch file storage per project (all files) | 10 GB |
| Batches in progress per organization | 100 |
| Requests in running batches per organization | 1,000,000 |
| Stored response size per request | 10 MB |
A batch that would push the organization past the running-request limit fails with `request_limit_exceeded` before any request runs. A batch that cannot be validated within its window ends as `expired`.
## Managing files and batches [#managing-files-and-batches]
| Request | Description |
| ------------------------------------ | ---------------------------------- |
| `GET /v1/files` | List files (filter with `purpose`) |
| `GET /v1/files/{file_id}` | Retrieve a file |
| `GET /v1/files/{file_id}/content` | Download a file's JSONL content |
| `DELETE /v1/files/{file_id}` | Delete a file |
| `GET /v1/batches` | List batches (`limit`, `after`) |
| `GET /v1/batches/{batch_id}` | Retrieve a batch |
| `POST /v1/batches/{batch_id}/cancel` | Cancel a batch |
Files and batches belong to the API key's project: any key in the same project can read and cancel them.
Batch input and output files hold your prompts and completions. They are kept
for 30 days, or until you delete them, regardless of your organization's [data
retention](https://docs.llmgateway.ai-stage.zibl.ir/features/data-retention) setting. The key used to create a batch
is stored encrypted until the batch finishes, or until the key is disabled,
deleted, or rolled, so the gateway can run its requests. While [zero data
retention](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance) is active, uploading files and creating
batches return `400` with code `zdr_storage_conflict`.
# Compliance
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/compliance
Provider compliance policies let you guarantee that requests are only ever routed to providers that meet your organization's regulatory requirements. When a request would be routed to a provider that doesn't meet the policy, the gateway blocks it **before any data leaves the gateway**.
The complete provider compliance policy is available on
[**Enterprise**](https://llmgateway.io/enterprise). DevPass offers only **No
AI training**.
For providers managed entirely through Airside, policy checks use the active
carrier's self-declared profile, including subsequent edits. No separate
compliance review is required. Missing facts fail the corresponding policy
requirement; provider allowlists and blocklists keep using the same provider ID.
Catalogue providers claimed in Airside can also declare their own SOC 2, ISO
27001 and GDPR status: a declared value replaces the reviewed catalogue value,
and an unstated one keeps it.
## Requirements [#requirements]
Enable a policy under **Settings → Compliance** in the dashboard and toggle the requirements you need:
In DevPass, enable **No AI training** directly under **Settings**. It uses the same fail-closed provider policy described below, but the other requirements are not available on DevPass.
| Requirement | A provider is allowed when… |
| ----------------------------- | ---------------------------------------------------------------- |
| **Zero data retention (ZDR)** | it does not log prompts and declares a zero-day retention period |
| **No training on prompts** | it does not train on API prompts |
| **No stealth providers** | it is not a stealth provider |
| **GDPR compliant** | it is GDPR compliant |
| **SOC 2 (Type 1 or 2)** | it holds a SOC 2 report of any type |
| **SOC 2 Type 2** | it holds a SOC 2 Type 2 report specifically |
| **ISO 27001** | it holds an ISO 27001 certification |
| **SOC 2 Type 2 or ISO 27001** | it holds either a SOC 2 Type 2 report or ISO 27001 |
Every requirement is **fail-closed**: a provider passes only if its published data policy explicitly satisfies the requirement. If an attribute is unknown for a provider, that provider is treated as non-compliant.
Some models retain data on a provider that is otherwise zero-retention, for example models that require AWS human review on Bedrock. The data policy is checked per model, so **Zero data retention (ZDR)** routes those models only to providers that meet it for that model, even when the provider passes in the **Provider Impact** preview.
Before enabling **Zero data retention (ZDR)**, set the organization's data retention to **Metadata Only** and disable response caching in every project. While ZDR is active, **Retain All Data** and project response caching are unavailable, gateway response caching is bypassed, provider prompt-cache markers are stripped, Responses API requests must set `store: false`, and asynchronous video generation is unavailable because video jobs require temporary output storage. Disable ZDR before turning payload retention or caching back on. ZDR is a separate Enterprise compliance policy and is unchanged by the Enterprise requirement for **Retain All Data** itself. ZDR does not stop the gateway content filter from keeping an encrypted copy of requests flagged for child safety; see [Flagged Content](https://docs.llmgateway.ai-stage.zibl.ir/features/data-retention#flagged-content).
Existing policies that use the deprecated **No prompt logging** rule continue to enforce their original provider-routing behavior. The legacy rule is no longer available for new configuration and does not enable the gateway-level ZDR controls described above.
Stealth providers are undisclosed platforms that LLM Gateway routes to without naming the operator, so their data policy and headquarters are unknown. That already makes them fail every certification and data-policy requirement above, but **No stealth providers** excludes them explicitly — useful when you want them gone without turning on any other requirement.
The settings page shows a live **Provider Impact** preview of which providers are allowed (green) and which are blocked (red) under the current policy, so you can see the impact before saving. Hovering a blocked provider lists exactly which requirements it does not meet — a missing certification, its data policy, its headquarters country, or a provider-list restriction.
## Provider headquarters [#provider-headquarters]
Beyond certifications, you can restrict routing by the country a provider is headquartered in. The **Provider Headquarters** card presents a country selector, and requests are only routed to providers based in a selected country.
The selector only offers countries that are referenced by a catalogue provider or active Airside profile — browse the [providers directory](https://llmgateway.io/providers) to see the current set and each provider's headquarters. Selecting no country applies no location restriction. The country filter is also fail-closed: when at least one country is selected, a provider whose headquarters is unknown is treated as non-compliant.
The country filter composes with the certification and data-policy requirements above — a provider must satisfy all active requirements to be allowed.
## Provider & model restrictions [#provider--model-restrictions]
Beyond attribute-based requirements, the **Provider & Model Restrictions** card lets you block or allow individual providers and models:
* **Blocked providers / blocked models** — deny lists. A listed provider or model is always blocked, even when it satisfies every requirement above.
* **Allowed providers / allowed models** — fine-grained allow lists. When non-empty, only the listed providers (or models) may be used; everything else is blocked. An empty list applies no restriction.
Model lists take versioned model IDs. An entry also covers requests through a [virtual model](https://docs.llmgateway.ai-stage.zibl.ir/learn/models#virtual-models) alias that currently resolves to it.
Deny lists always win over allow lists, and both compose with the requirements above — an allow-listed provider must still satisfy every active certification, data-policy, and country requirement.
A non-empty allowed-providers list blocks **every** provider not on it,
regardless of certifications or data policy. If you allow-list only a custom
provider, all catalogue providers show as blocked with the reason "Not on the
allowed-providers list" — add any additional provider you want to use to the
allow list.
The selectors include your organization's own [custom providers](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers) (stored as `custom:` refs) and their custom-catalog models (stored as `/` refs), so a specific custom deployment can be blocked or allow-listed individually just like a catalogue provider.
### Choosing a compliant provider [#choosing-a-compliant-provider]
The provider dropdowns are policy-aware, so you can tell **before** adding a provider to a list whether it satisfies your policy:
* A **green shield** marks a provider that meets every active certification, data-policy, and headquarters requirement.
* A **red shield** marks a provider that does not; the requirements it misses (for example "May log prompts" or "Headquartered in China, which is not an allowed country") are listed under its name.
* The **"Only providers that meet policy requirements"** toggle at the top of the dropdown hides incompatible providers entirely.
These indicators evaluate the requirements only — deliberately ignoring the allowed/blocked lists themselves — so an active allow list never paints every other provider red while you're deciding what to add to it. Your own custom providers are evaluated against their [self-attested posture](#custom-providers); one without an attestation on file shows "No compliance attestation on file".
Elsewhere in the dashboard (for example the API-key provider filter), the colored dot next to a provider is simply the provider's **brand color** and carries no compliance meaning.
Organization-level restrictions are **organization-wide** and take precedence over member-level and API-key-level [IAM rules](https://docs.llmgateway.ai-stage.zibl.ir/features/api-keys): they are enforced after IAM evaluation, so no user-, team-, or key-level allow rule can grant access to a provider or model the compliance policy excludes.
## API key policies [#api-key-policies]
On Enterprise, open an API key’s **Compliance** action to configure the same requirements, headquarters filters, and provider/model lists for that key. Organization owners and admins can manage these policies. **Settings → Compliance** also lists active, unexpired keys with explicit settings across the organization’s projects, including policies that are currently disabled.
The organization policy is a mandatory baseline, not an overridable default:
* Every enabled organization requirement still applies; a key can only add restrictions.
* Provider, model, and country allowlists must each pass both policies. Disjoint allowlists block all matching traffic.
* A blocklist at either level wins over an allowlist at the other.
* Disabling or removing the key policy leaves organization restrictions intact. With the organization policy off, an enabled key policy works independently.
Key-level **Zero data retention** forces metadata-only logging and bypasses caching for that key’s requests without changing organization retention or other keys. It also requires `store: false` for Responses requests and blocks asynchronous video generation. Unlike organization-wide ZDR, it does not require changing every project’s caching settings first.
Configuring key policies requires Enterprise access. Saved restrictions remain enforced after a subscription change; owners and admins can remove a key policy to return to organization-only enforcement. Compliance alerts continue to evaluate the organization policy, not individual key policies.
### Deployment rollout [#deployment-rollout]
Key-level policy configuration is off by default. After applying the database migration, upgrade every gateway instance and drain pre-upgrade realtime sessions. Then set `API_KEY_COMPLIANCE_ENABLED=true` on the internal API to allow new key-policy settings. Deploy the editor last. Until enabled, key-policy create/update requests return `503`; ordinary key operations and organization policy updates are unaffected. Owners and admins can still clear a key policy with `null`.
The rollout switch controls configuration only: saved organization and API-key restrictions remain enforced even when the switch is off. Existing keys default to no explicit policy and continue to use their organization policy unchanged.
Organization policies continue to govern video creation without retroactively blocking historical video downloads. An enabled key policy additionally checks historical video access against both organization and key restrictions.
## Enforcement [#enforcement]
When no available provider for a model meets the policy — or a pinned provider is non-compliant — the gateway returns a `403`:
```json
{
"error": {
"message": "This request was blocked by your organization or API key provider compliance policy. No available provider for requested-model meets the required certifications or provider/model restrictions. Contact your LLMGateway admin to adjust the policy."
}
}
```
This applies to both routing modes:
* **Automatic routing** — non-compliant providers are removed from the candidate set, and the request is blocked if none remain.
* **Pinned providers** — a request such as `deepseek/deepseek-v4-pro` is blocked when that specific provider does not meet the policy.
Each block is recorded as a **security event** so administrators can review what was rejected and why.
## Web search engines [#web-search-engines]
When a model without native web search gets a `web_search` tool, LLM Gateway sends the queries the model writes to a [search engine](https://docs.llmgateway.ai-stage.zibl.ir/features/web-search#gateway-run-search). On the [single-search path](https://docs.llmgateway.ai-stage.zibl.ir/features/web-search#gateway-run-search) (models that cannot call tools, `/v1/responses`, `n` above 1, and a few other cases listed there), a query model on Google AI Studio writes the queries from the latest turns instead. Your policies apply to both with the same rules as a provider:
* **The query model**, used only on the single-search path, is checked as the Google AI Studio provider. When the policy rejects it, the gateway skips it and searches your latest user message instead.
* **Perplexity** is checked as the Perplexity provider: blocking or not allowing Perplexity also stops its searches.
* **Exa** is checked against its own data policy: it may retain queries and use them for training. Provider lists address it as `exa`, so a provider allow list blocks it.
A search the policy rejects is skipped and not billed. With `tool_choice: {"type": "web_search"}`, the request fails with a `403` instead. Native web search is part of the provider serving the request, which the policy already covers.
## Custom providers [#custom-providers]
[Custom providers](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers) point at infrastructure your organization operates itself (for example, models hosted in your own cloud account), so they have no entry in the provider catalogue and no published data policy. Under any enabled compliance policy they are therefore **blocked by default** — the same fail-closed rule that applies to catalogue providers with unknown attributes.
To route through a custom provider while a policy is active, an organization owner or admin can record a **self-attestation** of that provider key's compliance posture under **Models → Compliance attestation** in the dashboard. The attestation covers the same attributes as a catalogue data policy — SOC 2 report type, ISO 27001, GDPR, training on API prompts, prompt logging, retention period, and the country the deployment is operated from — and the gateway evaluates it against your policy with **identical fail-closed rules**: an attribute left "unknown" never satisfies a requirement, and only an explicit "No" satisfies requirements like "No training on prompts". Clearing the attestation restores the blocked state.
LLMGateway does not verify attestations — they are your organization's own
assertion about infrastructure you operate. Every attestation change is
recorded in the audit log with the attesting user and timestamp.
Attestations only apply to custom provider keys. They can never be used to clear a catalogue provider that fails your policy.
**Known limitation:** the country selector in the compliance policy only offers countries referenced by catalogue providers or active Airside profiles (see the [providers directory](https://llmgateway.io/providers)). A custom deployment attested to a country outside that set cannot be allowed while a country restriction is active.
## Compliance alerts [#compliance-alerts]
Once a policy is saved and enabled, owners and admins on the Enterprise plan can configure **Compliance Alerts** at the bottom of the Compliance page:
* **Watched models**: pick models that no compliant provider serves yet, up to 100 per organization. Retired models and models blocked by your own model lists are not offered. When a compliant provider starts serving one, LLM Gateway notifies you once — including when your own policy change makes it available. If the model later loses its last compliant provider, the watch re-arms. A model that is already available when you add it is recorded as available, so it sends no initial alert; it can still alert later if it loses its last compliant provider and becomes available again.
* **Downgrades** (on by default): get notified when a provider stops meeting your policy, for example because it loses a certification or starts training on API data. When the audience is owners and admins, that alert also lists the models your organization used on the provider in the last 30 days that no longer have a compliant provider; it is left out for the everyone audience, because it spans every project. A watched model losing its last compliant provider is announced separately. Changes to your own policy never trigger downgrade alerts, and the first check after enabling alerts only records the current state.
* **Recipients**: choose the lowest role that receives alerts — owners only, owners and admins, or everyone in the organization. Higher roles are always included. Owners and admins are linked to this page; other recipients land on the Models page, which shows the same eligibility. Watching the first model saves the defaults: owners and admins, in-app and email delivery, downgrade alerts on.
* **Delivery**: in-app, email, and Slack. In-app and email reach each recipient individually and email needs a verified address; Slack is posted once per organization. Each recipient can turn off in-app or email delivery per alert type under [notification settings](https://docs.llmgateway.ai-stage.zibl.ir/features/notifications) in the dashboard bell.
Alerts are checked every minute against the saved policy. Disabling the policy or leaving the Enterprise plan stops the checks.
### Slack [#slack]
Create a Slack [incoming webhook](https://api.slack.com/messaging/webhooks) for the channel that should receive alerts and save its URL under **Notification Channels** on the organization **Preferences** page — only `https://hooks.slack.com/services/…` URLs are accepted. Once saved, use **Send test message** to verify it, then enable Slack in the Compliance Alerts card. The webhook URL is stored encrypted and only shown masked. Failed posts are retried up to five times within 24 hours, and removing the webhook also turns Slack off in the alert settings.
## Safety identifiers [#safety-identifiers]
LLM Gateway keeps **your end-user identifier** separate from **its provider-facing organization identifier**. Sending an identifier helps correlate your users’ requests in gateway logs; it does not let you choose or override the identifier sent to providers.
### Send an end-user identifier [#send-an-end-user-identifier]
Choose a stable, opaque value for each end user and send it in the request body:
| Endpoint | Request field |
| ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| Chat completions (`/v1/chat/completions`) | `safety_identifier` or `user` |
| Responses (`/v1/responses`) | `safety_identifier` or `user` |
| Responses compaction (`/v1/responses/compact`) and decisions (`/v1/decisions`) | `safety_identifier` |
| Native Messages (`/v1/messages`) | `metadata.user_id` |
| Embeddings (`/v1/embeddings`) | `user` |
| Images (`/v1/images/generations`, `/v1/images/edits`) and videos (`/v1/videos`) | `safety_identifier` or `user` |
| Audio (`/v1/audio/speech`, `/v1/audio/transcriptions` as a form field) | `safety_identifier` or `user` |
| Moderations (`/v1/moderations`), OCR (`/v1/ocr`), rerank (`/v1/rerank`), search (`/v1/search`) | `safety_identifier` or `user` |
| Realtime WebSocket (`/v1/realtime`) | `safety_identifier` or `user` query parameter |
| Realtime client secrets (`/v1/realtime/client_secrets`) | `safety_identifier`; it replaces any value on the WebSocket URL of sessions using the secret |
| AI SDK provider (`@ai-sdk/gateway`) | `providerOptions.gateway.user` or `providerOptions.llmgateway.safety_identifier` |
[Batch](https://docs.llmgateway.ai-stage.zibl.ir/features/batch) request lines for chat completions, Responses, and embeddings use the same fields as those endpoints.
For example, replace `your-model-id` with a model from the [models directory](https://llmgateway.io/models):
```bash
curl https://api.llmgateway.io/v1/chat/completions \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "your-model-id",
"messages": [{ "role": "user", "content": "Hello" }],
"safety_identifier": "app-user-42"
}'
```
Use a non-empty value of at most **128 characters**. Where both are listed, legacy `user` is used when `safety_identifier` is absent or `null`. Longer `safety_identifier` values in a JSON body are rejected; longer `user` or `metadata.user_id` values, and longer values in a form field or WebSocket query parameter, are not recorded as safety identifiers.
In both credits and bring-your-own-key mode, the client value is saved in request log metadata as `params.safety_identifier`, even without debug logging. Rejections before the body is parsed, such as early rate limits, may not include it. Reuse it for the same end user when correlating traffic or reporting requests to us. It remains metadata when prompt/completion retention is disabled and is subject to [metadata retention](https://docs.llmgateway.ai-stage.zibl.ir/features/data-retention). Do not include personal data; it is not an authentication or authorization mechanism.
### What providers receive [#what-providers-receive]
LLM Gateway generates an opaque, random identifier once per organization. It is not your organization ID, reveals no API key, and contains no personal data. Every request from the organization shares this provider-facing identifier, across all of its projects and API keys and after key rotation, even if requests carry different client `safety_identifier` values. It is not derived from your client value and cannot be overridden by it.
* **Credits:** upstream APIs that support abuse attribution receive the fixed organization identifier when forwarding is enabled on the gateway-managed credential, mapped to the field or header their API expects. Your client identifier is not forwarded as their safety identifier.
* **Bring your own key (BYOK):** neither the gateway identifier nor your client identifier is sent as a provider safety identifier.
* **Hybrid:** the credential used on each attempt determines the behavior, including retries and fallback. An attempt using your provider key follows BYOK behavior; one using LLM Gateway’s credentials follows credits behavior.
### Upstream request IDs [#upstream-request-ids]
Every upstream attempt to OpenAI or Azure OpenAI except video jobs, in credits and BYOK mode, carries a fresh random `lgr_…` ID in the provider's client request ID header (`X-Client-Request-Id` or `x-ms-client-request-id`), stored on that attempt's request log. HTTP requests also store the provider's own `x-request-id` when its response includes one, so a provider report quoting either ID maps to the exact request, API key and organization. Realtime WebSocket sessions store only the client request ID, which maps to the session's log rows, API key and organization. The gateway generates the client request ID; clients cannot set it.
## Access Control [#access-control]
Only organization **owners** and **admins** can view and change the compliance policy.
Project-scoped **developer** members cannot see the policy itself, but they can browse the org's available providers and models — including custom providers and their model catalogs — read-only on the **Models** page. This is the recommended way for developers to discover what they can call without being granted additional permissions.
## Related [#related]
* [Notifications](https://docs.llmgateway.ai-stage.zibl.ir/features/notifications) — per-user in-app and email delivery preferences, including compliance alerts.
* [Org Models Directory](https://docs.llmgateway.ai-stage.zibl.ir/features/models-directory) — see per-model eligibility under the active policy in the dashboard.
* [Data Retention](https://docs.llmgateway.ai-stage.zibl.ir/features/data-retention) — control whether request and response payloads are stored (Retain All Data is Enterprise only).
* [Guardrails](https://docs.llmgateway.ai-stage.zibl.ir/features/guardrails) — detect and block harmful or sensitive content.
## Get Started [#get-started]
DevPass subscribers can configure **No AI training** under **Settings**. [Contact us](https://llmgateway.io/enterprise) for the complete provider compliance policy.
# Cost Breakdown
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/cost-breakdown
LLM Gateway provides real-time cost information for each API request directly in the response's `usage` object. This allows you to track costs programmatically without needing to query the dashboard.
Cost breakdown is available for all users on both hosted and self-hosted
deployments.
## Response Format [#response-format]
API responses include cost fields in the `usage` object:
```json
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1234567890,
"model": "openai/gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 15,
"total_tokens": 25,
"cost": 0.000125,
"cost_details": {
"upstream_inference_cost": 0.000125,
"upstream_inference_prompt_cost": 0.000025,
"upstream_inference_completions_cost": 0.0001,
"total_cost": 0.000125,
"input_cost": 0.000025,
"output_cost": 0.0001,
"cached_input_cost": 0,
"request_cost": 0,
"web_search_cost": 0,
"image_input_cost": null,
"image_output_cost": null,
"data_storage_cost": 0.00000025
},
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0,
"image_tokens": 0,
"audio_tokens": 0,
"video_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"image_tokens": 0,
"audio_tokens": 0
}
}
}
```
## Cost Fields [#cost-fields]
| Field | Description |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `cost` | Total inference cost for the request in USD |
| `cost_details.upstream_inference_cost` | Combined upstream inference cost in USD (prompt + completions) |
| `cost_details.upstream_inference_prompt_cost` | Upstream cost for prompt tokens in USD (includes cached prompt discount) |
| `cost_details.upstream_inference_completions_cost` | Upstream cost for completion tokens in USD |
| `cost_details.total_cost` | Total request cost in USD (LLM Gateway extended field) |
| `cost_details.input_cost` | Cost for non-cached prompt tokens in USD |
| `cost_details.output_cost` | Cost for completion tokens in USD |
| `cost_details.cached_input_cost` | Cost for cached prompt tokens in USD |
| `cost_details.cache_write_input_cost` | Cost for prompt tokens written to the provider cache in USD, billed at the provider's cache-write premium (e.g. 1.25x for 5m / 2x for 1h on Anthropic) |
| `cost_details.request_cost` | Per-request flat fee in USD (when the model applies one) |
| `cost_details.web_search_cost` | Cost for web search tool calls in USD |
| `cost_details.image_input_cost` | Cost for image inputs in USD |
| `cost_details.image_output_cost` | Cost for image outputs in USD |
| `cost_details.data_storage_cost` | Storage cost for retained request/response payloads in USD |
## Token Detail Fields [#token-detail-fields]
The `usage` object also includes detailed token counters that mirror OpenAI's extended format:
| Field | Description |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `prompt_tokens_details.cached_tokens` | Number of prompt tokens served from the provider's prompt cache |
| `prompt_tokens_details.cache_write_tokens` | Number of prompt tokens written into the provider's prompt cache |
| `prompt_tokens_details.cache_creation_tokens` | Alias of `cache_write_tokens`, matching Anthropic's naming |
| `prompt_tokens_details.cache_creation` | Per-TTL breakdown of cache writes (`ephemeral_5m_input_tokens` / `ephemeral_1h_input_tokens`), present when a cache write occurred |
| `prompt_tokens_details.image_tokens` | Number of image prompt tokens, as reported by the provider |
| `prompt_tokens_details.audio_tokens` | Number of audio prompt tokens |
| `prompt_tokens_details.video_tokens` | Number of video prompt tokens |
| `completion_tokens_details.reasoning_tokens` | Number of reasoning tokens produced by reasoning models |
| `completion_tokens_details.image_tokens` | Number of image tokens produced |
| `completion_tokens_details.audio_tokens` | Number of audio tokens produced |
## Streaming Responses [#streaming-responses]
Cost information is also available in streaming responses. The cost fields are included in the final usage chunk sent before the `[DONE]` message:
```
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","choices":[...],"usage":{"prompt_tokens":10,"completion_tokens":15,"total_tokens":25,"cost":0.000125,"cost_details":{"upstream_inference_cost":0.000125,"upstream_inference_prompt_cost":0.000025,"upstream_inference_completions_cost":0.0001,"total_cost":0.000125,"input_cost":0.000025,"output_cost":0.0001,"cached_input_cost":0,"request_cost":0,"web_search_cost":0,"image_input_cost":null,"image_output_cost":null,"data_storage_cost":0.00000025}}}
data: [DONE]
```
## Every Endpoint [#every-endpoint]
Every billed reply carries `usage.cost`, what the request was billed in USD, with `usage.cost_details` breaking it down; `cost_details.total_cost` equals `cost`. There is nothing to opt into.
| Endpoint | Where the cost is | What it was billed on, in `usage` |
| -------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `/v1/chat/completions` | `usage`; on streams the final chunk before `[DONE]` | `prompt_tokens`, `completion_tokens`, `total_tokens`, and the token details above |
| `/v1/messages` | `usage`; on streams `message_delta.usage` | `input_tokens` (not cached), `output_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`, `cache_creation`, `server_tool_use` |
| `/v1/responses` | `usage`; on streams `response.usage` in `response.completed` | `input_tokens`, `output_tokens`, `total_tokens`, `input_tokens_details.cached_tokens`, `output_tokens_details.reasoning_tokens` |
| `/v1/responses/compact` | `usage` | as `/v1/responses` |
| `/v1/images/generations`, `/v1/images/edits` | `usage` | `input_tokens`, `output_tokens`, `total_tokens`, `input_tokens_details` and `output_tokens_details` (`image_tokens`, `text_tokens`) |
| `/v1/embeddings` | `usage` | `prompt_tokens`, `total_tokens` |
| `/v1/decisions` | `usage` | `input_tokens`, `output_tokens`, `total_tokens` |
| `/v1/rerank` | `usage` | `input_tokens`, `total_tokens` when the model is priced per token |
| `/v1/audio/transcriptions` | `usage` | `type: "duration"`, `seconds` of input audio |
| `/v1/ocr` | `usage` | `pages_processed` |
| `/v1/moderations`, `/v1/search` | `usage` | billed per request: `cost_details.request_cost` |
| `/v1/audio/speech` | with `stream_format: "sse"`, `usage` of the final `speech.audio.done` event | `input_tokens`, `output_tokens`, `total_tokens` for models priced per token, `input_characters` for models priced per character |
| `/v1/videos` | `usage` of `GET /v1/videos/{id}` and the signed callback, once the job is billed | `cost_details.video_output_cost`, `cost_details.image_input_cost` |
Speech returned as binary audio (the default) has no body to carry a cost. Request `stream_format: "sse"` to receive the audio as `speech.audio.delta` events followed by `speech.audio.done` with its usage and cost; this works for every speech model.
A video job reports `usage` once it reached a terminal status and was billed: a job that failed, was canceled or expired reports a cost of `0`. If a terminal job has no `usage` yet, poll again.
## Example: Tracking Costs in Code [#example-tracking-costs-in-code]
Here's an example of how to track costs programmatically using the cost breakdown feature:
```typescript
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.LLM_GATEWAY_API_KEY,
baseURL: "https://api.llmgateway.io/v1",
});
async function trackCosts() {
const response = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
});
const usage = response.usage as any;
if (usage.cost !== undefined) {
console.log(`Request cost: $${usage.cost.toFixed(6)}`);
console.log(
` Prompt: $${usage.cost_details.upstream_inference_prompt_cost.toFixed(6)}`,
);
console.log(
` Completions: $${usage.cost_details.upstream_inference_completions_cost.toFixed(6)}`,
);
const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;
if (cachedTokens > 0) {
console.log(` Cached prompt tokens: ${cachedTokens}`);
}
}
return response;
}
```
## Use Cases [#use-cases]
### Budget Monitoring [#budget-monitoring]
Track costs in real-time and implement budget limits in your application:
```typescript
let totalSpent = 0;
const BUDGET_LIMIT = 10.0; // $10 budget
async function makeRequest(messages: Message[]) {
const response = await client.chat.completions.create({
model: "gpt-4o",
messages,
});
const cost = (response.usage as any).cost || 0;
totalSpent += cost;
if (totalSpent > BUDGET_LIMIT) {
throw new Error(`Budget exceeded: $${totalSpent.toFixed(2)}`);
}
return response;
}
```
### Per-User Cost Allocation [#per-user-cost-allocation]
Track costs per user for billing or analytics:
```typescript
const userCosts: Map = new Map();
async function makeRequestForUser(userId: string, messages: Message[]) {
const response = await client.chat.completions.create({
model: "gpt-4o",
messages,
});
const cost = (response.usage as any).cost || 0;
const currentCost = userCosts.get(userId) || 0;
userCosts.set(userId, currentCost + cost);
return response;
}
```
### Cost Analytics [#cost-analytics]
Aggregate costs by model, time period, or any other dimension:
```typescript
interface CostEntry {
timestamp: Date;
model: string;
promptCost: number;
completionsCost: number;
totalCost: number;
}
const costLog: CostEntry[] = [];
async function loggedRequest(model: string, messages: Message[]) {
const response = await client.chat.completions.create({
model,
messages,
});
const usage = response.usage as any;
costLog.push({
timestamp: new Date(),
model: response.model,
promptCost: usage.cost_details?.upstream_inference_prompt_cost || 0,
completionsCost:
usage.cost_details?.upstream_inference_completions_cost || 0,
totalCost: usage.cost || 0,
});
return response;
}
```
## Self-Hosted Deployments [#self-hosted-deployments]
If you're running a self-hosted LLM Gateway deployment, cost breakdown is always included in API responses regardless of plan. This allows you to track internal costs and allocate them across teams or projects.
# Custom Providers
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers
LLMGateway supports integrating custom OpenAI-compatible providers, allowing you to use any API that follows the OpenAI chat completions format. This feature is perfect for:
* Private or self-hosted LLM deployments
* Specialized AI providers not natively supported
* Internal AI services within your organization
* Testing against different model endpoints
Custom providers are an **Enterprise** feature. Custom providers created
before this requirement keep serving requests on any plan and can still be
deactivated or deleted, but creating or editing them requires an enterprise
plan.
Custom providers must be OpenAI-compatible, supporting the
`/v1/chat/completions` endpoint format.
## Quick Setup [#quick-setup]
### 1. Add a Custom Provider Key [#1-add-a-custom-provider-key]
Navigate to your organization's provider settings and add a custom provider via the UI (requires an enterprise plan).
Provide a lowercase name, OpenAI-compatible base URL, and API token for the custom provider.
### 2. Make Requests [#2-make-requests]
Once configured, make requests using the format `{customName}/{modelName}`:
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "mycompany/custom-gpt-4",
"messages": [
{
"role": "user",
"content": "Hello from my custom provider!"
}
]
}'
```
## Configuration Requirements [#configuration-requirements]
### Custom Provider Name [#custom-provider-name]
* **Format**: Lowercase letters (`a-z`) with optional single hyphens between them
* **Examples**: `mycompany`, `internal`, `my-company`, `eu-west`
* **Invalid**: `MyCompany`, `my_company`, `123test`, `-mycompany`, `my-`, `my--company`
* **Reserved**: `dynamic` is rejected (it is the [dynamic routes](https://docs.llmgateway.ai-stage.zibl.ir/features/dynamic-routes) model prefix), and the name must be unique within your organization
The custom provider name must match the regex pattern `/^[a-z]+(-[a-z]+)*$/`
exactly.
### Base URL [#base-url]
* Must be a valid URL pointing to your provider's base endpoint
* On the hosted service the URL must be `https://` and must not resolve to a
private, reserved, or internal address. `http://` URLs and private-network
hosts (for example a service on your own network) work only on self-hosted
deployments that set `ALLOW_INSECURE_PROVIDER_URLS=true`
* LLMGateway will append `/v1/chat/completions` automatically — do not include `/v1` in the base URL (it is not stripped, so the path would be doubled)
* **Example**: `https://api.example.com` → `https://api.example.com/v1/chat/completions`
* If your provider serves chat completions at another path, enter the full endpoint ending in `/chat/completions` and LLMGateway uses it as-is
* **Example**: `https://api.example.com/v2/ai/openai/chat/completions` is called unchanged
### API Token [#api-token]
* Provider-specific authentication token
* Used in the `Authorization: Bearer {token}` header
Unlike built-in providers, custom provider models are not validated, giving
you complete flexibility.
## Supported Features [#supported-features]
Custom providers serve **chat completions** — `/v1/chat/completions` and the endpoints that proxy through it (`/v1/responses`, `/v1/messages`, and the AI SDK gateway endpoints under `/v*/ai`). Gateway features that apply to that path (caching, routing, IAM, logging, cost tracking via the custom model catalog) work as usual. Embeddings, images, audio, video, rerank, OCR, and moderations do not route to custom providers.
## Custom Model Catalog [#custom-model-catalog]
The custom model catalog is an **Enterprise** feature. Managing entries
requires an enterprise plan, but the gateway always honors catalog entries
that already exist.
By default, requests through a custom provider are **not billed** and have **no
enforced limits** — LLMGateway has no catalog entry for the model, so it cannot
know its pricing, context window, or capabilities. The **custom model catalog**
lets you define that information per custom provider key, so LLMGateway can
attribute cost, enforce limits, and report usage just like a built-in model.
Custom catalog models are **text-output** models. Multi-modal *input* (images,
audio) is still supported and can be priced via the input fields below; output
generation (images, video, audio) is intentionally out of scope because it is
too provider-specific to bill generically.
### Defining a model [#defining-a-model]
Open **Organization → Models**, pick the custom provider key, and add a
catalog entry. Every field except the model id is optional:
| Field | Purpose |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| **Model id** | The id used after the provider prefix (e.g. `gpt-5.5` in `mycompany/gpt-5.5`). |
| **Display name** | Optional human-readable label. |
| **Context size** | Maximum input window in tokens. Enforced per request. |
| **Max output** | Maximum completion tokens. Enforced against `max_tokens`. |
| **Token prices** | Input, output, cached input, cache read, cache write (5m and 1h), per-request, web search, image input, and audio input prices. |
| **Capabilities** | `streaming`, `vision`, `tools`, `reasoning`, `jsonOutput`, `audio`. |
| **Supported parameters** | Advisory list of accepted request parameters. |
Prices are in **USD per token** and accept either decimal (`0.000003`) or
exponent (`3.0e-6`) notation.
### Cost attribution [#cost-attribution]
When a request matches a catalog entry, LLMGateway bills it using the entry's
token prices and records the cost on the activity log. Without a matching entry
the request stays unbilled (zero/null cost).
A known model id (for example `gpt-5.5`) routed through a custom provider is
**not** billed at that model's public pricing — only the prices you define in
the catalog apply. Define the model in the catalog to attribute cost.
### Limit and capability enforcement [#limit-and-capability-enforcement]
When an entry defines limits or capabilities, LLMGateway enforces them before
forwarding the request:
* **Context size / max output** — requests that would exceed the configured
window or output budget are rejected with `400`.
* **Capabilities** — when a flag is explicitly set to disabled, requests that use
that feature are rejected (e.g. images against a non-`vision` model, tools
against a non-`tools` model, streaming against a non-streaming model). Flags
left unset stay permissive and the upstream provider enforces them.
### Restricting to the catalog [#restricting-to-the-catalog]
Each custom provider key has an **Only allow catalog models** switch. When
enabled, requests through that provider must reference a defined catalog model —
undefined models are rejected with `400`. This guarantees that every request has
known cost attribution and enforced limits. When disabled, undefined models
still work but remain unbilled, as before.
## Prompt caching [#prompt-caching]
Each custom provider key has a **Forward prompt-cache markers** switch
(`forwardCacheControl` in the API). It is on by default for new keys; keys
created before the switch existed keep it off and strip markers until you turn
it on. Turn it off for a provider whose strict OpenAI-compatible API rejects
unknown fields. Set it when creating the key, or toggle it later from the key's
menu on the provider keys page or on the
[custom models](#custom-model-catalog) page.
With the switch on, the gateway forwards your markers on text content parts, and a
`tool_result` marker from `/v1/messages` (or `tool_result_cache_control` on an
OpenAI-format `tool` message) is moved onto the tool message's last text part,
turning a string tool result into a one-part array. Markers are normalized to
`{"type": "ephemeral"}` with an optional `5m` or `1h` `ttl`; malformed markers,
markers on images and other non-text parts, and markers on tool definitions are
dropped.
The switch only forwards markers your client sends; the gateway adds none of
its own for custom providers. A project whose
[provider cache-write mode](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/provider-cache-control) is
**Disabled** still strips every marker.
### Routing bare model ids [#routing-bare-model-ids]
A catalog entry whose model id equals a built-in model id and has a price joins
routing for that bare id: `gpt-5.5` can then be served by your custom provider
or a built-in provider, scored like any other candidate (see
[routing](https://docs.llmgateway.ai-stage.zibl.ir/features/routing)). In hybrid mode, providers you hold a key for are
preferred. A provider-prefixed id always pins that provider.
Because the custom provider is one candidate among several:
* A failed attempt falls back to the next provider under the usual
[retry rules](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#what-triggers-a-retry). Genuine `4xx` client
errors are passed through as-is, while an upstream `401`/`402`/`403`/`404`/`405`/`429`
counts as a provider-side failure and falls back like any other provider.
* Its recent uptime is tracked per model. Below the low-uptime threshold
(default 90%) it is skipped while another provider can serve the request, and
retried a few minutes later.
The serving provider is returned in `metadata.used_provider`.
## Visibility [#visibility]
Every active organization member — including project-scoped **developer**
members — can browse the org's custom providers and their model catalogs
read-only on the **Models** page, so developers can always discover
which providers and models are available to them. Creating, editing, and
deleting providers, models, and attestations stays restricted to organization
owners and admins.
## Compliance attestation [#compliance-attestation]
If your organization enforces a [provider compliance policy](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance),
custom providers are blocked by default — they have no catalogue data policy, so
the fail-closed rules treat them as non-compliant. Organization owners and
admins can record a per-key **self-attestation** of the deployment's compliance
posture under **Models → Compliance attestation**, which the gateway then
evaluates against the policy exactly like a catalogue provider's data policy.
See [Compliance → Custom providers](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#custom-providers) for
details and caveats.
# Data Retention
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/data-retention
LLM Gateway offers configurable data retention policies that allow you to store full request and response payloads. This enables powerful debugging capabilities, detailed analytics, and compliance with data governance requirements.
## Retention Levels [#retention-levels]
LLM Gateway supports two retention levels that can be configured per organization:
| Level | Description | Storage Cost |
| ------------------- | --------------------------------------------------------------------------------------------------------------- | --------------- |
| **Metadata Only** | Stores request metadata (timestamps, models, token counts, costs, latency) without full payloads. Default. | Free |
| **Retain All Data** | Stores complete request and response payloads including messages, tool calls, and attachments. Enterprise only. | $0.01/1M tokens |
Metadata-only retention is enabled by default and provides usage analytics
without additional storage costs.
**Retain All Data** is an [Enterprise](https://llmgateway.io/enterprise)
feature. New organizations default to Metadata Only and cannot enable Retain
All Data unless they are on Enterprise. Existing non-Enterprise organizations
that currently have Retain All Data enabled keep it until **November 8,
2026**, when the hosted platform (llmgateway.io) switches them to Metadata
Only automatically; they can switch to Metadata Only earlier themselves.
Self-hosted deployments are not switched automatically. Once off, Retain All
Data cannot be turned back on without Enterprise.
Retention levels are configurable on standard (pay-as-you-go) organizations
only. DevPass and chat subscriptions are always metadata only — their request
and response payloads are not retained, and there is no setting to turn
payload storage on. The Responses API exception below still applies to them.
## Storage Pricing [#storage-pricing]
When full data retention is enabled, storage is billed at **$0.01 per 1 million tokens**. This rate applies to:
* Input tokens (prompt)
* Cached input tokens
* Output tokens (completion)
* Reasoning tokens
Storage costs are calculated per request and billed separately from inference. When "Retain All Data" is enabled, each response's `usage.cost_details` object includes a `data_storage_cost` field with the per-request storage cost in USD. See [Cost Breakdown](https://docs.llmgateway.ai-stage.zibl.ir/features/cost-breakdown) for the full list of cost fields.
### Example Cost Calculation [#example-cost-calculation]
For a request with:
* 1,000 input tokens
* 500 output tokens
* 1,500 total tokens
Storage cost = 1,500 / 1,000,000 × $0.01 = **$0.000015**
## Configuring Retention [#configuring-retention]
Data retention is configured at the organization level in your dashboard settings. The setting is only available on standard pay-as-you-go organizations, and enabling **Retain All Data** requires an Enterprise plan:
1. Navigate to **Organization Settings** → **Policies**
2. Select your preferred **Data Retention Level**
3. Save changes
Only organization **owners** can change the retention level — admins and project admins receive a `403`.
Changing retention settings applies to new requests only. Existing stored data
follows the retention period active when it was created.
## Retention Periods [#retention-periods]
Data is retained for 30 days for all users, regardless of plan. After the retention period expires, the stored payloads (prompts, completions, tool payloads, raw request and response bodies) are automatically cleared; request metadata used for analytics is kept. Payloads already stored by a non-Enterprise organization during the transition window follow the same 30-day period after it switches to Metadata Only.
The Responses API does not require data retention. Stored responses (used for
`previous_response_id` chaining and `GET /v1/responses/:id`) are kept in
dedicated storage for 30 days — matching OpenAI's own retention — regardless
of your organization's data retention policy, and are not billed as data
storage. Because this is independent of the retention level, it applies to
metadata-only organizations, including DevPass and chat, whose Responses API
input and output items are therefore held for up to 30 days. Send `store:
false` with the request to opt out. When an Enterprise organization's
[zero-data-retention policy](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance) is active, the gateway
rejects Responses API requests unless `store: false` is set, does not retain
compaction state, bypasses the gateway response cache, strips provider
prompt-cache markers, and prevents payload retention or project response
caching from being enabled until ZDR is disabled. ZDR cannot be enabled until
both settings are off. These configuration prerequisites apply to
organization-wide ZDR. A key-level ZDR policy instead forces metadata-only
logging and disables caching only for requests through that key, without
changing other keys or organization settings.
[Batch API](https://docs.llmgateway.ai-stage.zibl.ir/features/batch) input, output, and error files are kept for 30
days, or until you delete them, regardless of your organization's data
retention policy, and are not billed as data storage. The requests a batch
runs are logged under your retention level like any other request. While zero
data retention is active, the Batch API rejects uploads and new batches with
`zdr_storage_conflict`.
## Flagged Content [#flagged-content]
The [gateway content filter](https://docs.llmgateway.ai-stage.zibl.ir/resources/error-handling#gateway-content-filter) keeps an encrypted copy of requests its deciding classifier flags for abuse categories LLM Gateway chooses to review (for example child safety, sexual content, or cyber abuse), whether or not the request was blocked. This happens on every plan except Enterprise (unless the Enterprise agreement provides for it) and independently of the retention level, so it also applies to Metadata Only, DevPass, and chat organizations.
* **What is kept:** the request's messages and tool calls, and image URLs without credentials, query string, or fragment (plus a hash of the full URL). Inline images, audio, and files, including media blocks, data URLs, and long base64 data inside tool calls and results, are reduced to a SHA-256 hash, type, size, and file name; their bytes are never stored. Conversations over about 1 MB are trimmed, oldest messages first.
* **How long:** generally 90 days, then deleted automatically. A request reported to NCMEC is kept for one year after the report, as U.S. law requires. A copy can be kept longer where the law requires it or to investigate abuse; see Section 6 of the [Terms of Use](https://llmgateway.io/legal/terms).
* **Who can see it:** only authorized LLM Gateway staff with full administrative access. Copies are encrypted at the application level, never appear in your request logs or exports, and every access is recorded in an internal audit log.
* **Zero data retention:** while a [ZDR policy](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance) is active, only requests flagged for child safety are kept.
Self-hosted deployments choose the preserved categories in the admin content filter settings, delete expired copies in the worker's retention loop whether or not `ENABLE_DATA_RETENTION_CLEANUP` is set, and can turn preservation off in the admin content filter settings.
## Accessing Stored Data [#accessing-stored-data]
When **Retain All Data** is enabled (Enterprise), you can access your stored requests through the dashboard:
* View request history with full payload inspection
* Filter by model and date range
* Inspect complete request and response payloads
## Use Cases [#use-cases]
### Debugging [#debugging]
Full data retention (Enterprise) enables you to:
* Inspect exact prompts sent to models
* Review complete responses including tool calls
* Trace conversation histories
* Identify issues in production
### Analytics [#analytics]
With stored payloads, you can:
* Analyze prompt patterns and effectiveness
* Track response quality over time
* Build custom dashboards and reports
* Measure model performance across use cases
### Compliance [#compliance]
Data retention helps meet compliance requirements by:
* Maintaining audit trails of AI interactions
* Enabling data governance policies
* Supporting incident investigation
* Providing records for regulatory requirements
## Billing Considerations [#billing-considerations]
### Credit Usage [#credit-usage]
In **API keys mode** (using your own provider keys):
* Only storage costs are deducted from LLM Gateway credits
* Inference costs are billed directly to your provider
In **credits mode**:
* Both inference and storage costs are deducted from credits
### Monitoring Storage Costs [#monitoring-storage-costs]
Storage costs appear in:
* Usage dashboard under "Storage" category
* Billing invoices as a separate line item
Enable [auto top-up](https://llmgateway.io/dashboard) in billing settings to
ensure uninterrupted service when storage costs accumulate.
## Self-Hosted Deployments [#self-hosted-deployments]
Self-hosted deployments have full control over data retention:
* Enable or disable the 30-day cleanup job with `ENABLE_DATA_RETENTION_CLEANUP=true` (disabled by default; the period itself is not configurable)
* Data is stored in your own PostgreSQL database
* No additional storage costs (you manage your own infrastructure)
## Privacy and Security [#privacy-and-security]
* All stored data is encrypted at rest
* Access is restricted to organization members with appropriate permissions
* Stored payloads are automatically cleared after the retention period (on self-hosted deployments, only when the cleanup job is enabled via `ENABLE_DATA_RETENTION_CLEANUP=true`)
* You can request immediate deletion of specific records through support
# Data Streams
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/data-streams
Data streams deliver your organization's logs to the tools your security and data teams already use, as signed HTTPS requests to an endpoint you run:
* **SIEM forwarding** sends [audit logs](https://docs.llmgateway.ai-stage.zibl.ir/features/audit-logs): every admin action in the organization.
* **Log export** sends request log metadata: one event per gateway request with model, provider, tokens, cost, latency, and finish reason.
Data streams are an [**Enterprise**](https://llmgateway.io/enterprise) feature
enabled per organization. Contact us to turn them on; request log export is a
separate switch because each pass reads your request logs. Manage streams on
the [**Data Streams**](https://docs.llmgateway.ai-stage.zibl.ir/learn/data-streams) page.
## What is sent [#what-is-sent]
Events only ever carry metadata. Prompts, completions, tool calls, and tool results are never exported, and there is no option to include them.
| Source | Event fields |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Audit logs** | `id`, `timestamp`, `organizationId`, `userId`, `action`, `resourceType`, `resourceId`, `metadata` (the same change summary shown on the audit log page) |
| **Request logs** | `id`, `timestamp`, `requestId`, `organizationId`, `projectId`, `apiKeyId`, models and providers, token counts, `cost`, latency, finish reasons, error and cache flags |
## Delivery [#delivery]
Each batch is a `POST` with a JSON body of `{ stream, source, events }` and these headers:
* `Content-Type: application/json`
* `X-LLMGateway-Signature: t=,v1=`, where `v1` is the HMAC-SHA256 of `.` with your signing secret, the same scheme as [platform webhooks](https://docs.llmgateway.ai-stage.zibl.ir/features/embeddable-payments).
* `Authorization: Bearer ` when you set an optional bearer token.
Respond with any `2xx` status to accept the batch.
* Events are delivered in order, in batches of up to 500.
* A stream keeps a cursor and advances it only after your endpoint accepts a batch. A failed batch is retried, so delivery is at least once; deduplicate on the event `id`.
* Events are usually sent within 30 seconds. Delivery waits for database writes still in progress, so late writes are never skipped; while a long write runs, events can arrive a few minutes later.
* New streams start with events created after they were added. Use replay to backfill.
* Failed deliveries are retried with backoff, from 1 minute up to 1 hour. A stream pauses itself after 20 failed deliveries in a row, or after 3 deliveries your endpoint rejected with a `4xx` status since the last one it accepted. Owners and admins are notified; resume the stream once the endpoint is fixed and delivery continues from where it stopped.
* Delivery stops while the organization is not on the Enterprise plan or data streams are switched off for it.
## Replay [#replay]
**Replay** re-sends every event in a window of up to 30 days. It runs alongside live delivery and does not move the live cursor.
## Test [#test]
**Send test event** delivers one synthetic event (`"test": true`) and reports the endpoint's response.
All stream changes are recorded in audit logs as `data_stream.*` actions.
# Decisions
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/decisions
LLMGateway exposes an OpenAI-compatible `/v1/decisions` endpoint for decision
models: models that read text or images, answer questions you define, and
return typed answers with calibrated probabilities. There is no free-form text
in the response — every answer is a value your code can branch on directly.
Use it when a model call exists only to make a decision: routing a support
ticket, scoring a retrieved passage, checking a product photo for damage, or
classifying a record. A chat model can do these too, but you then have to parse
prose, and you get no probability to threshold on.
The request and response follow [OpenAI's Decisions API](https://developers.openai.com/api/docs/guides/decisions),
so the OpenAI SDKs work by pointing their base URL at LLMGateway. The same
request shape works for every decision model, whichever provider serves it.
For the full request and response schema, see the
[API reference](https://docs.llmgateway.ai-stage.zibl.ir/v1_decisions). To try a decision model without writing code,
open the [Decision Studio](https://docs.llmgateway.ai-stage.zibl.ir/learn/playground-decisions) in Lounge: build the
questions in the browser, compare models on the same input, and copy the run
as a `/v1/decisions` request.
## Models [#models]
`microsoft-decision-1` is served by Azure and works with LLMGateway credits.
To use your own Azure key instead, deploy Microsoft-Decision-1 in Microsoft
Foundry with the deployment name `Decision-1`, then add the Azure key and
resource in LLMGateway. The gateway calls the resource's Foundry host
(`https://.services.ai.azure.com`).
`gpt-6-luna-decisions` is also served by Azure. With your own Azure key, deploy
`gpt-6-luna` under the deployment name `gpt-6-luna` in a region where Azure
enables decisions for it; the same deployment then serves chat and decisions.
Not every region does (East US 2 serves chat but rejects decisions), so check
Microsoft's
[Decisions API guide](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/decisions)
before deploying.
Browse all decision models on the
[models page](https://llmgateway.io/models?filters=1).
Providers list their own decision models through
[Airside](https://docs.llmgateway.ai-stage.zibl.ir/features/airside#decision-models); those models are served on
`/v1/decisions` like any other and billed at their approved fares.
## Endpoint [#endpoint]
`POST https://api.llmgateway.io/v1/decisions`
## Question types [#question-types]
| Type | Ask | Answer |
| ----------- | ------------------------------------ | ---------------------------------------------------------------- |
| `predicate` | Whether a condition is true | `probability`: 0 to 1 |
| `choice` | One option from `choices` you define | `choice`, `probabilities` per option, `confidence` |
| `score` | A rating across ordered `levels` | `score` (can land between levels), `probabilities`, `confidence` |
Answers come back in the order you asked, echoing each question's `name`. A
question the model declines returns `{ "type": "refusal", "name": … }` while
the others are still answered.
## cURL [#curl]
```bash
curl -X POST "https://api.llmgateway.io/v1/decisions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-luna-decisions",
"input": "Help! My payouts have been failing for 3 days.",
"questions": [
{
"type": "choice",
"name": "department",
"instructions": "Which team should handle this?",
"choices": [
{ "value": "billing", "description": "Payments, invoicing, refunds" },
{ "value": "technical", "description": "Bugs, outages, integrations" }
]
},
{
"type": "predicate",
"name": "is_urgent",
"instructions": "Does this convey urgency?"
},
{
"type": "score",
"name": "impact",
"instructions": "Rate the operational impact.",
"levels": [{ "label": "None" }, { "label": "Limited" }, { "label": "Critical" }]
}
]
}'
```
```json
{
"model": "openai/gpt-6-luna-decisions",
"answers": [
{
"type": "choice",
"name": "department",
"choice": "billing",
"probabilities": [
{ "value": "billing", "probability": 0.88 },
{ "value": "technical", "probability": 0.12 }
],
"confidence": 0.81
},
{ "type": "predicate", "name": "is_urgent", "probability": 0.95 },
{
"type": "score",
"name": "impact",
"score": 1.9,
"probabilities": [
{ "value": 0, "label": "None", "probability": 0.0 },
{ "value": 1, "label": "Limited", "probability": 0.1 },
{ "value": 2, "label": "Critical", "probability": 0.9 }
],
"confidence": 0.88
}
],
"usage": {
"input_tokens": 318,
"output_tokens": 0,
"total_tokens": 318,
"cost": 0.0000318,
"cost_details": {
"input_cost": 0.0000318,
"request_cost": 0,
"total_cost": 0.0000318
}
}
}
```
`usage.cost` is what the request was billed in USD (see [Cost Breakdown](https://docs.llmgateway.ai-stage.zibl.ir/features/cost-breakdown)).
## OpenAI SDK [#openai-sdk]
Point the client at LLMGateway and call `decisions.create` (OpenAI JavaScript
SDK 7.30.0 or later, Python SDK 3.26.0 or later):
```ts
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.llmgateway.io/v1",
apiKey: process.env.LLM_GATEWAY_API_KEY,
});
const decision = await client.decisions.create({
model: "gpt-6-luna-decisions",
input: ticket,
questions: [
{
type: "predicate",
name: "is_urgent",
instructions: "Does this convey urgency?",
},
],
});
const [answer] = decision.answers;
if (answer.type === "predicate" && answer.probability > 0.8) {
await escalate(ticket);
}
```
## Images [#images]
Send user messages with `input_text` and `input_image` parts to evaluate images
on models that accept them:
```json
{
"model": "gpt-6-luna-decisions",
"input": [
{
"role": "user",
"content": [
{ "type": "input_text", "text": "Inspect the product in this photo." },
{ "type": "input_image", "image_url": "data:image/png;base64,…" }
]
}
],
"questions": [
{
"type": "predicate",
"name": "visible_damage",
"instructions": "Does the product have visible damage?"
}
]
}
```
Text-only models such as `microsoft-decision-1` reject image parts with a 400.
TypeSafe's Jev models take PNG and JPEG images only. The gateway accepts up to
16 images and 22.5 MB of image data per request, 16 MB per image, so the
request fits TypeSafe's body limit; TypeSafe rejects images under 280 or over
1568 pixels per side. Requests with images run in TypeSafe's long-context mode
(262k tokens). TypeSafe treats image input as experimental.
Decision models are billed on input tokens only — the input plus every
question. There is no output, cache-read or cache-write charge.
Decision models only work on `/v1/decisions` (TypeSafe models also on the
legacy `/v1/systemone`). Requesting one on `/v1/chat/completions` returns a
400 pointing you at the right endpoint, and they cannot generate text or call
tools. There is no streaming — the response is a single object.
## Migrating from /v1/systemone [#migrating-from-v1systemone]
`/v1/systemone` is TypeSafe's request format and serves Jev only. It will be
deprecated in favor of `/v1/decisions`, and new decision models ship on
`/v1/decisions` only. Jev works on both, at the same price, so you can move
without changing models. The exception is Jev 1.14's
[`box` questions](https://docs.llmgateway.ai-stage.zibl.ir/features/system-one#bounding-boxes), which OpenAI's format
has no type for: keep those on `/v1/systemone`.
| `/v1/systemone` | `/v1/decisions` |
| --------------------------------- | ------------------------------------------------------- |
| `state` (string, object or array) | `input` (string, or user messages with text and images) |
| `questions` map keyed by id | `questions` array; the id goes in `name` |
| `noul` question | `predicate` question |
| `choice` `criteria` record | `choices`: `[{ value, description }]` |
| `score` `criteria` list | `levels`: `[{ label, description }]` |
| `answers` map keyed by id | `answers` array in question order, with `name` |
| `noul` answer | `probability` |
| `probabilities` record | `probabilities` array of `{ value, probability }` |
| `legend` on score answers | `label` on each score probability |
Structured state has no direct equivalent: serialize it to a string (for
example with `JSON.stringify`) and pass it as `input`.
# Document Reading
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/documents
LLMGateway supports sending documents (PDFs and other file types) to document-capable models using OpenAI's `file` content block format. The gateway forwards the document to the underlying provider so the model can read and reason over its contents.
## Document-Capable Models [#document-capable-models]
Find document-capable models and the providers that serve them on the [models page with the document filter](https://llmgateway.io/models?filters=1\&document=true).
On the Anthropic-compatible [`/v1/messages`](https://docs.llmgateway.ai-stage.zibl.ir/features/anthropic-endpoint) endpoint, send the document as a `document` block with a `base64` or `text` source instead. Other source types return `400`.
## Sending a Document [#sending-a-document]
Add a `file` content block to a user message. The `file_data` field must be a base64-encoded data URL that includes the document's MIME type.
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.6-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Summarize this document."
},
{
"type": "file",
"file": {
"filename": "report.pdf",
"file_data": "data:application/pdf;base64,JVBERi0xLjQKJ..."
}
}
]
}
]
}'
```
### Content Block Fields [#content-block-fields]
* **`type`**: must be `"file"`.
* **`file.filename`** *(optional)*: original filename, shown in Lounge and forwarded for context.
* **`file.file_data`**: base64-encoded data URL of the form `data:;base64,`.
The `file.file_id` field (for referencing files uploaded via a provider's
Files API) is accepted by the schema but not forwarded to any provider. Use
`file_data` with an inline base64 data URL.
## Supported File Types [#supported-file-types]
The accepted MIME types depend on the target model. Gemini models commonly support:
* `application/pdf`
* `text/plain`
* `text/html`
* `text/css`
* `text/javascript`
* `text/csv`
* `text/markdown`
* `text/xml`
Claude models read `application/pdf` and any UTF-8 encoded `text/*` type, which is sent as plain text.
If the upstream provider rejects the MIME type, the gateway surfaces a `400` error including the unsupported MIME type and the provider it was sent to. To use a different file type, encode the file with the matching MIME type in the data URL prefix.
## Encoding a File as a Data URL [#encoding-a-file-as-a-data-url]
Any tool that can produce base64 output works. For example, in a shell:
```bash
DATA=$(base64 -i report.pdf | tr -d '\n')
echo "data:application/pdf;base64,$DATA"
```
Or in JavaScript:
```javascript
import { readFileSync } from "node:fs";
const buffer = readFileSync("report.pdf");
const fileData = `data:application/pdf;base64,${buffer.toString("base64")}`;
```
Then pass `fileData` as the `file.file_data` value in your request.
## Multiple Documents [#multiple-documents]
You can include multiple `file` blocks in a single message, optionally mixed with text and image content:
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.1-pro-preview",
"messages": [
{
"role": "user",
"content": [
{ "type": "text", "text": "Compare these two reports." },
{
"type": "file",
"file": {
"filename": "q1.pdf",
"file_data": "data:application/pdf;base64,JVBERi0x..."
}
},
{
"type": "file",
"file": {
"filename": "q2.pdf",
"file_data": "data:application/pdf;base64,JVBERi0x..."
}
}
]
}
]
}'
```
## Error Handling [#error-handling]
The gateway returns `400` for the following document-related errors:
* The selected model does not support document input.
* The `file` block is missing both `file_data` and `file_id`.
* `file_data` is not a valid base64 data URL.
* The upstream provider rejects the document's MIME type for the selected model.
# Dynamic Routes
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/dynamic-routes
Dynamic routes let you move routing logic out of your application code and into the gateway. Instead of hardcoding a model, you define a named decision graph — conditions on the request, classifier verdicts, percentage-based traffic splits, and model targets — and invoke it by putting `dynamic/` in the `model` field of a chat request. Dynamic routes are resolved on `/v1/chat/completions` and the endpoints that proxy through it (`/v1/responses`, `/v1/messages`, and the AI SDK gateway endpoints under `/v*/ai`) — not on embeddings, images, audio, video, rerank, OCR, or moderations:
```bash
curl https://api.llmgateway.io/v1/chat/completions \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "x-user-tier: paid" \
-d '{
"model": "dynamic/support",
"messages": [{"role": "user", "content": "Hello!"}]
}'
```
The graph is evaluated on every request. Once it resolves to a model, the request flows through the same [smart routing](https://docs.llmgateway.ai-stage.zibl.ir/features/routing) as any other request: weighted provider scoring, sticky sessions, and automatic cross-provider fallback all apply to the resolved target.
Dynamic routes are available on the Enterprise plan. Manage them under{" "}
Project Settings → Dynamic Routes in the dashboard, either in a visual
drag-and-drop editor or as raw JSON.
## The route graph [#the-route-graph]
A route is a JSON document with an `entry` node id and a list of nodes. Evaluation starts at `entry` and follows branches until it reaches a `model` node (route the request) or an `end` node (reject the request with a `400`).
```json
{
"entry": "tier",
"nodes": [
{
"id": "tier",
"type": "conditional",
"conditions": [
{
"field": { "source": "header", "path": "x-user-tier" },
"op": "eq",
"value": "paid",
"next": "premium"
}
],
"else": "split"
},
{ "id": "premium", "type": "model", "model": "claude-sonnet-4-6" },
{
"id": "split",
"type": "percentage",
"splits": [
{ "weight": 80, "next": "stable" },
{ "weight": 20, "next": "experiment" }
]
},
{
"id": "stable",
"type": "model",
"model": "gpt-5-nano",
"providers": ["openai"]
},
{ "id": "experiment", "type": "model", "model": "gemini-2.5-flash" }
]
}
```
Node ids may contain letters, digits, hyphens, and underscores.
## Node types [#node-types]
### `conditional` [#conditional]
Evaluates its conditions top to bottom; the first match wins and the request follows that condition's `next`. When nothing matches, the request follows `else`.
Each condition reads one field from the request:
| `field.source` | What `field.path` means |
| -------------- | --------------------------------------------------------------------------------- |
| `header` | A request header name (case-insensitive), e.g. `x-user-tier` |
| `body` | A dot-path into the JSON request body, e.g. `metadata.segment` or `max_tokens` |
| `metadata` | A gateway-provided request attribute: `orgId`, `projectId`, `apiKeyId`, or `plan` |
Supported operators:
| Operator | Matches when | Value type |
| ---------- | ------------------------------------------------------------------------- | ------------------------- |
| `eq` | The field equals the value (compared as strings) | string / number / boolean |
| `neq` | The field differs from the value — also matches when the field is missing | string / number / boolean |
| `in` | The field equals any entry in the value array | array of strings |
| `contains` | The field's string form contains the value | string |
| `gt`, `lt` | The field is numerically greater / less than the value | number |
| `exists` | The field is present (no value) | — |
### `classifier` [#classifier]
Rates the request with a classifier and branches on one of its answers. Set `kind` to the classifier to use (currently `jev`, TypeSafe's decision model) and `on` to the answer to branch on:
| `on` | Values |
| ------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `difficulty` | `low`, `medium`, `high` |
| `task` | `coding`, `math`, `analysis`, `writing`, `extraction`, `summarization`, `translation`, `conversation`, `agentic`, `other` |
| `outputType` | `short_answer`, `long_form`, `code`, `structured_data` |
```json
{
"id": "rate",
"type": "classifier",
"kind": "jev",
"on": "difficulty",
"cases": [
{ "value": "high", "next": "frontier" },
{ "value": "low", "next": "cheap" }
],
"else": "balanced"
}
```
The node adds one short round trip before the upstream call, and only routes that contain a `classifier` node pay for it. Each rating is billed at the catalogue rate for [`jev-1.13.0`](https://llmgateway.io/models/jev-1.13.0/typesafe) — roughly $0.0001 per call — and recorded as its own log entry against the same project and API key as the request that triggered it; see [what the classifier costs](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#what-it-costs). A [sticky session](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#sticky-session-routing) is rated once and the rest of the conversation reuses that verdict, so a multi-turn chat is not re-rated per turn.
`else` covers both outcomes you need it to: no case matched, **and** no verdict was produced. The classifier is fail-open — an outage, a timeout, a missing credential, or a compliance policy that blocks its provider all take the `else` branch rather than failing the route. Give `else` a sensible default model rather than an `end` node.
The verdict is recorded on the request log under `routingMetadata.dynamicRoute.classifier`, so you can see which branch was taken and why.
### `percentage` [#percentage]
Splits traffic across branches by relative weight. The draw is **deterministic per session**: the split key is the request's session id (`x-session-id` and the other [sticky session routing](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#sticky-session-routing) signals), so a conversation keeps its assignment across requests instead of flip-flopping between experiment arms. Requests without a session id get an independent draw per request.
Weights are relative — `{ 80, 20 }` and `{ 4, 1 }` produce the same split.
### `model` [#model]
Terminates evaluation and routes the request to a catalog model (see the [models page](https://llmgateway.io/models) for available ids). Optional `providers` restricts routing to those providers in preference order for initial selection and cross-provider fallback. Eligibility checks and hybrid-mode key preference apply first. A healthy session pin takes precedence; when a pin becomes unavailable, the next request chooses its replacement using the order. Retryable failures can also move a sticky session to the next eligible provider; a successful replacement becomes the new session pin. Scores choose among regions of the same provider, and explicit provider order disables exploration. When `providers` is omitted, every eligible provider serving the model is a candidate and weighted smart routing picks the best one.
A `model` node can also target one of your organization's [custom catalog models](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers#custom-model-catalog) as `/`. Such a node must not set `providers` (the custom model already fixes its provider), and the referenced custom model must be active in your organization when the route is saved or published.
### `end` [#end]
Terminates evaluation and rejects the request with a `400`. Useful as an explicit deny branch — for example, refusing traffic that doesn't carry a required header.
## Validation [#validation]
Graphs are validated when you save a draft and again when you publish:
* every referenced node must exist and be reachable from `entry`
* cycles are rejected — evaluation is deterministic per request, so a revisited node would loop forever
* model ids and provider ids must exist in the catalog, and each listed provider must actually serve the model
* operator/value mismatches (e.g. `gt` with a non-numeric value) are rejected
* a `classifier` node's case values must be valid for its `on` answer, and must not repeat
An invalid graph can never be saved or published, and publishing re-validates against the live model catalog so a stale draft can't resurrect a removed model.
## Versions and rollback [#versions-and-rollback]
Edits always go to the route's **draft**. Publishing snapshots the draft as an immutable, numbered version and points the route at it; the published version is what serves traffic. Rolling back re-points the route at any previous version instantly — no data migration, no re-deploy.
A route only serves requests when it is **enabled** and has a **published version**; otherwise requests using it are rejected with a `404`.
## Observability [#observability]
Each request served through a dynamic route records the route name, published version, and the node path the evaluation took in its routing metadata, alongside the usual provider scoring details — visible in the activity log detail view.
The project's **Analytics** page compares each route's spend with sending every request to the priciest model in the route; see [routing savings](https://docs.llmgateway.ai-stage.zibl.ir/features/routing#routing-savings).
## Reliability [#reliability]
Published routes are cached in the gateway and carry a stale fallback: when the database is temporarily unreachable, recently used routes keep resolving from cache, the same way API keys and project settings do.
# Embeddable Payments
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/embeddable-payments
The **Payments SDK** lets you drop **end-user payments + in-app credit purchases** into your product the same way Stripe Elements lets you drop in payments. Your end-users get their **own wallet**, buy credits **inside your app**, and pay per request for any model the gateway supports. LLM Gateway is the merchant of record; you set a markup and keep the margin.
**Preview — opt-in only.** Embeddable Payments is in preview and enabled on an
opt-in basis per project. The **Settings → Payments SDK** dashboard page shows
a read-only preview until the feature is turned on for your project. [Contact
us](mailto:contact@llmgateway.io) to request access before integrating.
## When to use this [#when-to-use-this]
Reach for the Payments SDK when **you embed LLM Gateway's billing on your own site** and want **your end-users to pay for the AI they use**, each with their own wallet and credit balance. It handles end-user **payments and sessions**: per-user wallets, in-app credit top-ups (Stripe), short-lived browser sessions scoped to a single wallet, and developer-margin payouts.
**This is a payments product, not an AI client SDK.** Do not confuse it with a
normal AI SDK such as the OpenAI SDK or the Vercel AI SDK. If you just want to
call models from your own backend with a single API key, use the
[OpenAI-compatible API](https://docs.llmgateway.ai-stage.zibl.ir/quick-start) instead — you do not need the Payments
SDK. Use the Payments SDK only when you need to **charge your own end-users**
and give each of them a wallet and checkout inside your app.
It ships as three packages:
| Package | Runs in | Use it for |
| ---------------------- | ------------------------- | ------------------------------------------------------------------------------------ |
| `@llmgateway/server` | Your backend (secret key) | Mint end-user sessions, manage wallets/customers, verify webhooks, trigger payouts |
| `@llmgateway/client` | Browser (headless) | Framework-agnostic chat/image/embeddings + balance/top-up, with auto session refresh |
| `@llmgateway/elements` | React | Drop-in ``, ``, `` + hooks |
A complete, runnable Next.js example lives in the templates repo:
[**Embeddable Payments
template**](https://github.com/theopenco/llmgateway-templates/tree/main/templates/embeddable-credits).
## How it works [#how-it-works]
```
Your backend ──(secret key sk_)──▶ POST /v1/sessions ──▶ ephemeral session token (es_, ~15 min)
│ │
└────────── returns es_ to your frontend ◀────────────────┘
│
Browser (es_) ──▶ chat / images / embeddings ──▶ debits the end-user wallet
└──▶ buy credits (Stripe Elements) ─▶ credits land in the wallet
```
* Your **secret key** (`sk_…`) never leaves your backend. It mints short-lived **ephemeral session tokens** (`es_…`) scoped to one end-user wallet.
* The **browser** only ever holds the `es_…` token (and a publishable Stripe key). It calls the gateway directly; usage is billed to that user's wallet.
* **Markup is applied at top-up time**: if you set a 20% markup and a user buys $10, their wallet is credited the net spend power and your **margin accrues to your organization** for later payout.
* **Top-up bonus (optional)**: set a bonus percent to credit end-users *more* than they pay — e.g. a 50% bonus turns a $10 top-up into $15 of spend power. The extra credits are funded from **your organization's credit balance** at top-up time (capped at your available credits), so it's a promotional lever you can switch on or off anytime. Markup and bonus are independent: the bonus is applied on top of the net credited amount.
## Set up in the dashboard [#set-up-in-the-dashboard]
Before you write any code, configure the project you want to embed:
1. Open the LLM Gateway dashboard and select your project.
2. After preview access is approved for your project, go to **Settings → Payments SDK** and turn on **End-user sessions**. Preview approval only unlocks setup; it does not enable sessions automatically.
3. *(Optional)* Set a **markup percent** — the margin you earn on every top-up — and/or a **top-up bonus percent** to gift end-users extra credit (funded from your organization's credit balance).
4. Add the browser origins allowed to call the gateway, one per line (e.g. `https://app.example.com`).
5. Under **Receipts & branding**, set your **brand name**, **support email** and **statement descriptor** so end-user payments are recognisable as yours (see below), then click **Save Settings**.
6. Under **Platform Secret Keys**, click **Create Live Key** (or **Create Test Key**) and copy the `sk_…` value immediately.
7. Store it as a server-side environment variable, for example `LLMGATEWAY_SECRET_KEY`.
The platform secret key (`sk_…`) is different from a regular gateway API key (`llmgtwy_…`): it mints end-user sessions and must only ever be used from your backend.
## Receipts and statement descriptors [#receipts-and-statement-descriptors]
LLM Gateway is the **merchant of record** for every end-user top-up. Your
end-users are charged by us, and the receipt and card statement both carry our
details — which is confusing for someone who only ever visited *your* product.
The branding fields exist to close that gap.
After a successful top-up we email the end-user a receipt with a PDF attached:
* Your **brand name** leads the email and appears on the PDF as the product the
payment was for. It defaults to the project name.
* Your **support email**, when set, is the first contact address on the receipt.
Ours appears below it, since we are the merchant of record and have to stay
reachable for billing questions.
* Your **statement descriptor** is appended to our prefix on the cardholder's
statement, giving `LLMGTWY* ACME AI` rather than a bare `LLMGTWY`. Card
networks cap the whole string at 22 characters, so the suffix you supply is
limited to 13 and normalized on save.
The receipt also states that LLM Gateway processed the payment and what the
charge is called on the statement. That explanation appears **only** on these
receipts — a direct LLM Gateway purchase has no third party to explain, so it
gets a plain receipt instead.
Refunds send a credit note the same way.
We can only send a receipt to an address we have. Mint sessions with
`customer: { externalId: "user_123", email: "user@example.com" }` — a bare
`customer: "user_123"` string leaves the end customer without an email and no
receipt is sent. Passing the email on a later session updates the stored
record.
Test-mode wallets never receive receipts, matching Stripe's own behaviour of
not emailing receipts for sandbox payments.
**Test mode.** A `sk_test_…` key is a sandbox key: end-user wallet top-ups go
through Stripe's sandbox (use Stripe [test cards](https://docs.stripe.com/testing),
no real charges), and its wallets are fully segregated from live ones — the same
end-user gets independent test and live wallets. To keep sandbox money from
buying real inference, **test-mode wallets can only call free models**: use the
`auto` route (it picks a free model automatically) or a free model id; paid
models return a `403`. Pair a test secret key on your backend with
`mode="test"` on `` (see below) — the two must match.
Test-mode top-ups never receive the developer-funded top-up bonus, and a
`sk_test_…` key cannot manage webhook endpoints or use Stripe Connect
onboarding/payouts (both return `403` — use a live secret key).
Session tokens can use speech generation, but charges come only from the bound end-user wallet; project BYOK settings, organization credits, and chat-plan allowances do not subsidize that wallet. Session expiry, customer/wallet state, allowed origin, model scope, and sandbox restrictions are checked before provider dispatch.
For `/v1/responses`, end-user sessions must provide direct input. Their responses are never stored and always report `store: false`, whatever the request sets, so zero data retention does not reject a session request that omits `store`. SDK requests to `/v1/responses/compact` are also direct-input only and never persist compaction state; that endpoint does not accept a `store` option. Session tokens cannot retrieve stored responses or use `previous_response_id` or `item_reference` inputs, because stored Responses state is project-scoped rather than wallet-scoped. Keep conversation history in your app and resend it as direct input.
The platform secret key is shown only once. Do not put it in frontend code,
browser bundles, mobile apps, or public repos. Only a keyed HMAC-SHA-256
fingerprint and masked preview are stored, so create a replacement if you lose
the secret.
## 1. Install [#1-install]
```bash
# backend
npm install @llmgateway/server
# frontend (pick one)
npm install @llmgateway/elements # React drop-in components
npm install @llmgateway/client # headless / non-React
```
## 2. Mint a session on your backend [#2-mint-a-session-on-your-backend]
Identify your signed-in user and mint a session bound to their wallet. Scope which models they may call.
```ts
// app/api/llmgateway/session/route.ts (Next.js Route Handler)
import { LLMGateway } from "@llmgateway/server";
const lg = new LLMGateway({ secretKey: process.env.LLMGATEWAY_SECRET_KEY! });
export async function POST() {
const session = await lg.sessions.create({
customer: { externalId: "user_123" }, // your stable user id
scope: { models: ["openai/gpt-4o-mini"] }, // lock down what they can call
ttlSeconds: 900, // optional, default 15 min
});
return Response.json(session); // { sessionToken, walletId, endCustomerId, expiresAt, publishableKey }
// publishableKey is null unless the project has an active publishable
// browser key — the browser authenticates with the sessionToken (es_…).
}
```
Always mint sessions server-side. Never ship your `sk_…` secret key to the
browser.
## 3a. Drop in the React components [#3a-drop-in-the-react-components]
Wrap your UI in `` and use the components. `fetchSession` is how the client refreshes the short-lived token before it expires.
```tsx
"use client";
import {
LLMGatewayProvider,
Chat,
CreditBalance,
BuyCredits,
} from "@llmgateway/elements";
const fetchSession = () =>
fetch("/api/llmgateway/session", { method: "POST" }).then((r) => r.json());
export default function Assistant({ session }) {
return (
);
}
```
Need full control over rendering? Use the hooks instead of the components:
* `useBalance()` → `{ balance, currency, recentLedger, loading, error, refetch, refetchUntilChange }`
* `useChat({ model })` → `{ turns, send, streaming, ... }`
`useBalance().refetchUntilChange()` polls until the balance actually changes —
use it after a purchase, since the wallet is credited asynchronously once the
Stripe webhook lands.
## 3b. Or go headless (any framework) [#3b-or-go-headless-any-framework]
```ts
import { LLMGatewayClient } from "@llmgateway/client";
const client = new LLMGatewayClient({
session: { token: session.sessionToken, expiresAt: session.expiresAt },
refresh: fetchSession, // auto-refreshes ~60s before expiry
});
// stream a completion (billed to the user's wallet)
for await (const delta of client.stream({
model: "openai/gpt-4o-mini",
messages: [{ role: "user", content: "Hello!" }],
})) {
process.stdout.write(delta);
}
const { balance } = await client.getBalance();
```
The headless client also exposes `chat()`, `image()`, `embeddings()`, `getBalance()`, `createTopUp(amount, paymentMethodId)`, and `confirmTopUp(paymentIntentId)`.
### Spend limits [#spend-limits]
`getBalance()` (and `useBalance()`) also returns a `limits` object describing the spend limits enforced on the session, the amount consumed so far, and — when a windowed limit is configured — when it resets. This lets you show the user how much of their allowance is left before a request is rejected.
```ts
const { balance, limits } = await client.getBalance();
// limits: {
// usageLimit, // lifetime spend cap (null = uncapped)
// usage, // consumed over the session's lifetime
// periodUsageLimit, // per-window cap (null = no windowed limit)
// periodUsageDurationValue, // e.g. 1
// periodUsageDurationUnit, // "hour" | "day" | "week" | "month"
// currentPeriodUsage, // consumed in the current window
// currentPeriodStartedAt, // ISO timestamp, or null
// currentPeriodResetAt, // ISO timestamp the window resets, or null
// }
```
`null` limit fields mean that cap is not configured. `currentPeriodUsage` is `"0"` and `currentPeriodResetAt` is `null` until the first spend in a fresh window.
## Buying credits [#buying-credits]
`` collects a card with Stripe's `PaymentElement`, then shows a fee breakdown before the user confirms payment. Every purchase adds the **5% platform fee**; cards issued outside the United States add a separate **1.5% international card fee**, calculated on the credit purchase amount. US-issued cards do not pay the international fee. Card country comes from Stripe, not the browser. These fees do not reduce wallet credits or developer margin. Once LLM Gateway's webhook processes it, the wallet is credited the **net** amount (after your markup) and your margin accrues to your organization. If you've configured a **top-up bonus**, the additional developer-funded credit is applied on top of the net amount at the same time (debited from your organization's credit balance). The top-up API response includes `netCredited` and `bonusCredited` (the boosted total is their sum), and the `wallet.credited` webhook additionally carries `totalCredited`.
`@llmgateway/elements` bundles LLM Gateway's browser-safe Stripe publishable keys. Pass `mode="test"` to `` while developing to use Stripe test mode; omit it or pass `mode="prod"` for live payments (`"prod"` is the default). You never need to provide LLM Gateway's Stripe publishable key yourself, and the end-user never sees your `sk_…` secret key.
The frontend `mode` prop and the backend secret key must match. A `sk_test_…`
key creates the top-up PaymentIntent in the Stripe sandbox, which only the
`mode="test"` publishable key can confirm — mixing a test key with `mode="prod"`
(or vice versa) makes `` fail to confirm.
### Headless checkout and upgrading [#headless-checkout-and-upgrading]
Upgrade both `@llmgateway/client` and `@llmgateway/elements` to versions supporting card-priced top-ups before using this flow. Older clients that omit `paymentMethodId` are rejected rather than silently skipping the surcharge.
Use `getStripePublishableKey` from `@llmgateway/client` to load LLM Gateway's bundled, mode-matched Stripe key. Pass `"test"` for sandbox wallets and `"prod"` for live wallets; do not use your own Stripe account's key or the mode-agnostic `/v1/config` response. `` selects the same keys automatically.
```ts
import { getStripePublishableKey } from "@llmgateway/client";
import { loadStripe } from "@stripe/stripe-js";
async function createCheckoutElements(amount: number, mode: "test" | "prod") {
const stripe = await loadStripe(getStripePublishableKey(mode));
if (!stripe) throw new Error("Stripe failed to load");
const elements = stripe.elements({
mode: "payment",
amount: amount * 105, // initial cents: whole-dollar credits plus 5%
currency: "usd",
paymentMethodTypes: ["card"],
paymentMethodCreation: "manual",
});
elements.create("payment").mount("#payment-element");
return { stripe, elements };
}
```
1. Initialize Elements as above using the validated whole-dollar credit amount. Call `elements.submit()`, then `stripe.createPaymentMethod({ elements })`.
2. Call `client.createTopUp(amount, paymentMethod.id)`. It returns an unconfirmed intent and `platformFee`, `internationalFee`, `totalAmount`, `netCredited` and `bonusCredited`. Show the fees and total, then ask the user to confirm.
3. Call `client.confirmTopUp(quote.paymentIntentId)`. If `status` is `requires_action`, call `stripe.handleNextAction({ clientSecret })`, then call `confirmTopUp` again after authentication. Treat only `succeeded` or `processing` as submitted; wallet credit still waits for the webhook.
The corresponding authenticated endpoints are `POST /v1/wallet/top-up` (`{ amount, paymentMethodId }`) and `POST /v1/wallet/confirm-top-up` (`{ paymentIntentId }`). Do not call `stripe.confirmPayment`: confirmation is server-side so the quoted card cannot be replaced with one that incurs different fees. Changing the card requires a fresh quote. Only card payments are supported by this checkout.
## Managing wallets & customers (server-side) [#managing-wallets--customers-server-side]
```ts
// grant credits directly (e.g. free trial); live grants are funded from your
// organization's credit balance and fail with 402 when it is too low
await lg.wallets.credit({ walletId, amount: 5, reason: "Signup bonus" });
const wallet = await lg.wallets.retrieve(walletId);
// analytics: customers with balances + lifetime spend
const { customers } = await lg.customers.list();
const detail = await lg.customers.retrieve(endCustomerId);
```
## Webhooks [#webhooks]
Register an endpoint to react to wallet events. Events are signed (`X-LLMGateway-Signature`); verify them like Stripe.
```ts
await lg.webhookEndpoints.create({
url: "https://yourapp.com/webhooks/llmgateway",
enabledEvents: ["wallet.credited", "wallet.low_balance"],
});
// in your handler
const event = lg.webhooks.constructEvent(
rawBody,
signatureHeader,
endpointSecret,
);
```
Webhook URLs must be **https** and public — requests to private/internal
addresses are rejected (SSRF protection), both at registration and at delivery
time. Redirects are not followed, so register the final URL.
## Margin payouts (Stripe Connect) [#margin-payouts-stripe-connect]
Your accrued markup is held as a margin balance for the whole organization. Onboard a connected account and pay it out with a live secret key created by an organization owner or admin; keys created by project admins get `403`:
```ts
const { url } = await lg.connect.createOnboardingLink({
refreshUrl: "https://yourapp.com/settings/payouts",
returnUrl: "https://yourapp.com/settings/payouts?done=1",
});
// redirect the developer to `url`, then later:
const status = await lg.connect.status(); // { onboarded, payoutsEnabled, marginBalance }
const payout = await lg.connect.payout(); // transfer the accrued margin out
```
## Security model [#security-model]
* **Ephemeral tokens** (`es_…`) are short-lived and revocable; mint them per-user from your backend. While end-user sessions are turned off for a project, its outstanding tokens are rejected. Platform secrets and ephemeral tokens are stored only as keyed fingerprints, never as retrievable plaintext.
* **Model scopes** restrict each session to an allow-list of models.
* **Origin allowlist** (configured on the project) blocks browser calls from unexpected origins.
* **Per-session spend caps** (`scope.maxSpend`) bound how much a single session can spend.
## Full example [#full-example]
The end-to-end Next.js app — backend session route, provider, chat, and buy-credits — is in the templates repo:
➡️ [**Embeddable Payments template**](https://github.com/theopenco/llmgateway-templates/tree/main/templates/embeddable-credits)
# Embeddings
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/embeddings
LLMGateway exposes an OpenAI-compatible `/v1/embeddings` endpoint for generating vector representations of text — useful for semantic search, clustering, recommendations, and RAG.
Browse available embedding models on the [models page](https://llmgateway.io/models?filters=1\&embedding=true).
## Supported providers [#supported-providers]
* **OpenAI** — `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002`
* **Azure** — the same OpenAI embedding models, pinned with the `azure/` prefix
* **Google AI Studio** — `gemini-embedding-2` (recommended), `gemini-embedding-001` (legacy)
* **Google Vertex AI** — `gemini-embedding-001`, `text-embedding-005`
The gateway translates between provider-native request/response shapes (e.g. Google's `:embedContent` / `:batchEmbedContents`) and the OpenAI-compatible payload, so you can swap models without changing your client code.
## cURL [#curl]
```bash
curl -X POST "https://api.llmgateway.io/v1/embeddings" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "text-embedding-3-small",
"input": "The quick brown fox jumps over the lazy dog."
}'
```
## OpenAI JS SDK [#openai-js-sdk]
```ts
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.LLM_GATEWAY_API_KEY,
baseURL: "https://api.llmgateway.io/v1",
});
const response = await client.embeddings.create({
model: "text-embedding-3-small",
input: "The quick brown fox jumps over the lazy dog.",
});
console.log(response.data[0].embedding);
```
Embedding models are billed only for input tokens. There are no output tokens
since embeddings are fixed-size vectors.
## Improving retrieval quality [#improving-retrieval-quality]
Vector similarity is fast but approximate. For RAG, pair embeddings with
[rerank](https://docs.llmgateway.ai-stage.zibl.ir/features/rerank): use embeddings to pull a broad candidate set, then
rerank those candidates to pick the few documents that actually go in the
prompt.
# Guardrails
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/guardrails
Guardrails protect your organization by automatically detecting and blocking harmful content in LLM requests before they reach the model.
Guardrails are available on the [**Enterprise
plan**](https://llmgateway.io/enterprise).
## Overview [#overview]
Guardrails run on every API request, scanning message content for:
* Security threats (prompt injection, jailbreak attempts)
* Sensitive data (PII, secrets, credentials)
* Policy violations (blocked terms, restricted topics)
When a violation is detected, you control what happens: block the request, redact the content, or log a warning.
## Organization and Project Scopes [#organization-and-project-scopes]
Guardrails are configured for the whole organization by default, and every project uses that configuration.
A project can opt out and define its own guardrails instead — useful when one application needs stricter or looser rules than the rest of the organization. Turn off **Use organization guardrails** in the project's Guardrails settings, and that project's configuration and custom rules fully replace the organization's for its traffic.
Exactly one scope is ever in force for a request:
| Project setting | What runs on that project's requests |
| ----------------------------------- | --------------------------------------------------------- |
| **Use organization guardrails** on | The organization configuration and its custom rules |
| **Use organization guardrails** off | The project's own configuration and its custom rules only |
Opting out never inherits partially: the organization's custom rules stop applying to that project too, and the project starts with a copy of the organization's current settings so nothing is silently dropped at the moment you opt out. Other projects are unaffected either way.
Both pages state which scope wins. A project page names itself and, while it inherits, shows the organization settings read-only; the organization page lists any projects that override it, so it is clear those settings apply everywhere else.
Organization owners and admins manage the organization guardrails; project owners and admins manage a project's own guardrails.
## What Gets Scanned [#what-gets-scanned]
Guardrails run on `/v1/chat/completions` and on `/v1/messages` and `/v1/responses`, which use the same pipeline. They scan the request's messages before routing: text parts, tool results, and attached images, audio and files.
Rules that look for instructions (prompt injection, jailbreak, topic restrictions and classifier rules) skip `system` and `developer` messages, because the system prompt is yours. Rules that look for data (PII, secrets, blocked terms, regex, sensitive data, document leakage) scan every message, including the system prompt.
## Detection Methods [#detection-methods]
* **Pattern rules** run inside the gateway with no extra latency or cost.
* **ML classifier rules** score the request with a calibrated [decision model](https://llmgateway.io/models), Jev 1.14 by default. They catch paraphrased, obfuscated and non-English attempts that patterns miss.
Each request that has classifier rules enabled triggers **one** extra [`/v1/decisions`](https://docs.llmgateway.ai-stage.zibl.ir/features/decisions) request that answers every classifier question at once. It runs with the caller's API key, so it:
* is billed to your organization at the decision model's price, like any other request;
* appears in your activity logs as its own `/v1/decisions` request;
* follows your project mode, API key and compliance settings. A project that only uses your own provider keys needs a key for the decision model's provider, or credits.
Pick the decision model under **Classifier model** in the guardrail settings. Any decision model works, optionally provider-prefixed (`typesafe/jev-1.14.0`). Default thresholds are tuned for Jev 1.14, so recheck them after switching.
The classifier only sees non-system messages, after redaction, so values redacted by PII or sensitive-data rules never reach it. If the classifier request fails (for example, insufficient credits), classifier rules are skipped for that request and pattern rules still apply.
Each classifier rule has a score threshold between 0 and 1 (default `0.8`), set through the API: `systemRules..threshold` for system rules, `config.threshold` for custom rules. Raise it to reduce false positives.
## System Rules [#system-rules]
### Prompt Injection Detection [#prompt-injection-detection]
Detects attempts to override, replace or extract instructions, such as "ignore all previous instructions", fake `[system]` sections or "reveal your system prompt". Turn on **Also score with the ML classifier** to catch paraphrased and indirect injections, for example instructions hidden in a document or tool result.
### Jailbreak Prevention [#jailbreak-prevention]
Detects attempts to bypass safety measures, such as DAN prompts, "developer mode" activation and requests to disable safety filters. The ML classifier option works as it does for prompt injection.
### PII Detection [#pii-detection]
Detects personal data. Choose which entities to detect:
| Entity | Validation |
| ---------------- | --------------------------------------------- |
| Email | Address format |
| Phone | Grouping separators or a nearby phone keyword |
| Credit card | Issuer prefix, length and Luhn checksum |
| IBAN | ISO 13616 mod-97 checksum |
| SSN | Valid area, group and serial blocks |
| IP address | Not part of a version number |
| Passport | Nearby passport keyword |
| Driver's license | Nearby license keyword |
With the **redact** action, matches are replaced with placeholders such as `[EMAIL_REDACTED]` before the request is forwarded.
### Secrets Detection [#secrets-detection]
Detects private keys, AWS, GitHub, GitLab, Slack, Stripe, OpenAI, Anthropic, Google, npm, Hugging Face and SendGrid credentials, JWTs, bearer tokens, connection strings, and API keys or passwords assigned in code or config. Template values such as `YOUR_API_KEY`, `${OPENAI_API_KEY}` or `********`, git SHAs and hex digests are ignored. Supports **redact**.
### File Restrictions [#file-restrictions]
Checks images, audio and files attached to messages against the allowed types and the maximum size. Allowed types are MIME types (`image/png`, `image/*`) or file extensions (`pdf`); an empty list allows every type. Remote URLs are checked by their file extension and are not size-checked; a file whose type cannot be determined is only size-checked.
### Document Leakage Prevention [#document-leakage-prevention]
Flags confidentiality markers such as "internal use only", "attorney-client privilege" or "under NDA". Disabled by default.
### Harmful Content [#harmful-content]
Scores harassment, hate, illicit activity, self-harm, sexual content, sexual content involving minors and violence with the ML classifier. Disabled by default.
## Actions [#actions]
| Action | Behavior |
| ---------- | ---------------------------------------------------------------- |
| **Block** | Reject the request with a `content_policy_violation` error (400) |
| **Redact** | Mask the matched content, then forward the request |
| **Warn** | Log the violation and forward the request unchanged |
Redact is available for PII, secrets, blocked terms, custom regex and sensitive data rules. The other rules can only block or warn.
A blocked request returns the matched rules:
```json
{
"error": {
"message": "Request blocked by content policy: PII Detection (rule system:pii_detection, category pii)",
"type": "guardrail_violation",
"code": "content_policy_violation",
"violations": [
{
"rule_id": "system:pii_detection",
"rule_name": "PII Detection",
"category": "pii",
"action": "block"
}
]
}
}
```
## Custom Rules [#custom-rules]
Create custom rules on the organization or on a single project. The dashboard offers templates for common policies, such as blocking email addresses or keeping an assistant on topic.
### Sensitive Data [#sensitive-data]
Detects selected PII entities with the same validated detectors as PII detection, under its own action. For example, block email addresses while the PII rule redacts phone numbers.
### Blocked Terms [#blocked-terms]
Blocks specific words or phrases. Match by exact word, substring or regex, optionally case-sensitive.
### Custom Regex [#custom-regex]
Matches patterns unique to your organization, such as internal codenames or customer identifiers. Patterns that could backtrack catastrophically are ignored.
### Topic Restriction [#topic-restriction]
Blocks requests about specific topics. By default, preset topics (`politics`, `religion`, `violence`, `adult_content`, `illegal_activities`, `gambling`, `medical_advice`, `financial_advice`) use keyword lists matched as whole words; other topics match as a phrase.
Turn on the ML classifier to judge topics by meaning instead. Classifier mode also supports **allowed topics**: anything outside them is a violation, which keeps a support assistant on topic.
### ML Classifier [#ml-classifier]
Describe what to detect in plain language, for example "The text asks for legal advice about the user's own situation." The classifier scores every request against it.
## Testing Rules [#testing-rules]
Use the test endpoint in the dashboard API (`POST /guardrails/test/{organizationId}` or `POST /guardrails/projects/{projectId}/test`) to check text against the pattern rules. Classifier rules are reported as skipped there, because they run only on gateway requests.
## Security Events Dashboard [#security-events-dashboard]
Monitor all guardrail violations with a dedicated dashboard:
* **Total violations** — Overall count and trends
* **By action** — Breakdown of blocked, redacted, and warned
* **By category** — Which rules are being triggered
* **Detailed logs** — Individual violations with timestamps and matched patterns
Each rule records at most one violation per request. Matched values from PII, secrets and sensitive-data rules are stored redacted, and matched content is stored only when your organization retains request data.
## How It Works [#how-it-works]
1. **Scope resolved** — The project's own guardrails if it overrides, otherwise the organization's
2. **Pattern rules** — Text and attachments are checked in the gateway
3. **Classifier rules** — If any are enabled, one billed decision request scores the redacted conversation
4. **Action taken** — Any blocking violation rejects the request; otherwise redactions are applied
5. **Violations logged** — Every violation is recorded for the Security Events dashboard
6. **Request proceeds** — The (possibly redacted) request is routed to the model
## Best Practices [#best-practices]
1. **Start with warnings** — Enable rules in warn mode first to understand your traffic patterns
2. **Review violations** — Check the Security Events dashboard regularly
3. **Tune custom rules** — Adjust blocked terms and regex patterns based on false positives
4. **Layer defenses** — Use multiple rule types together for comprehensive protection
## Get Started [#get-started]
Guardrails are an Enterprise feature. [Contact us](https://llmgateway.io/enterprise) to enable Enterprise for your organization.
# Image Generation
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/image-generation
LLMGateway supports image generation through two APIs:
1. **`/v1/images/generations`** — OpenAI-compatible images endpoint (recommended for simple image generation)
2. **`/v1/images/edits`** — OpenAI-compatible image editing endpoint
3. **`/v1/chat/completions`** — Chat completions with image generation models (for conversational image generation and editing)
For asynchronous video generation, see [Video Generation](https://docs.llmgateway.ai-stage.zibl.ir/features/video-generation).
## Available Models [#available-models]
You can find all available image generation models on our [models page](https://llmgateway.io/models?filters=1\&imageGeneration=true).
## OpenAI Images API [#openai-images-api]
The `/v1/images/generations` endpoint provides a drop-in replacement for OpenAI's image generation API. It works with any OpenAI-compatible client library.
### Parameters [#parameters]
| Parameter | Type | Default | Description |
| -------------------- | ------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `prompt` | string | required | A text description of the desired image(s) |
| `model` | string | `"auto"` | The model to use. `auto` resolves to `gemini-3-pro-image` |
| `n` | integer | `1` | Number of images to generate (1-10) |
| `size` | string | — | Image dimensions. Supported sizes depend on the model/provider — see [Image Configuration](#image-configuration) |
| `quality` | string | — | Image quality. Supported values depend on the model/provider — see [Image Configuration](#image-configuration) |
| `moderation` | string | `"auto"` | Content filtering strictness for models that support it: `auto` or `low` — see [Moderation](#moderation) |
| `complexity` | string | — | `low`, `medium`, or `high` for supported models — see [Complexity](#complexity) |
| `frame_count` | integer | — | GIF frames, 2–16; requires `output_format: "gif"` |
| `frame_duration_ms` | integer | — | GIF frame duration in milliseconds, 20–2000 |
| `response_format` | string | `"b64_json"` | Only `b64_json` is supported |
| `style` | string | — | Image style: `vivid` or `natural` |
| `output_format` | string | `"png"` | GPT Image models: `png`, `jpeg`, `webp`, `svg`, or `gif` — see [SVG output](#svg-output) |
| `output_compression` | integer | — | GPT Image models: `0`–`100`, for `jpeg` and `webp` output |
| `service_tier` | string | — | Processing tier for mappings that offer one: `flex`, `priority`, or `default` — see [Service Tiers](https://docs.llmgateway.ai-stage.zibl.ir/features/service-tiers) |
### curl [#curl]
```bash
curl -X POST "https://api.llmgateway.io/v1/images/generations" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-pro-image",
"prompt": "A cute cat wearing a tiny top hat",
"n": 1,
"size": "1024x1024"
}'
```
### Usage and cost [#usage-and-cost]
Both `/v1/images/generations` and `/v1/images/edits` return a `usage` object with the token counts and the billed cost of the request, in USD:
```json
"usage": {
"input_tokens": 10,
"input_tokens_details": { "image_tokens": 0, "text_tokens": 10 },
"output_tokens": 229,
"output_tokens_details": { "image_tokens": 229, "text_tokens": 0 },
"total_tokens": 239,
"cost": 0.00692,
"cost_details": { "input_cost": 0.00005, "image_output_cost": 0.00687 }
}
```
`cost_details` has the same fields as `usage.cost_details` on [chat completions](#response-format).
### GIF output [#gif-output]
GPT Image 2.6 Sunburst and Flare support `output_format: "gif"` on generations and edits, including multipart edits. Set `frame_count` (2–16) and `frame_duration_ms` (20–2000) to control the animation. Omit them to use OpenAI's defaults. `output_compression` is not supported for GIF.
`data[0].b64_json` contains the GIF bytes, and the response echoes `output_format: "gif"`. In chat completions, put these options in `image_config`; the image URL uses `data:image/gif;base64,...`. The gateway requests GIFs synchronously from the provider, including for streaming chat clients.
```json
{
"model": "openai/gpt-image-2.6-flare",
"prompt": "Animate a bouncing ball",
"output_format": "gif",
"frame_count": 8,
"frame_duration_ms": 100
}
```
### SVG output [#svg-output]
GPT Image 2.6 (`openai/gpt-image-2.6-sunburst` and `openai/gpt-image-2.6-flare`) returns vector graphics when you set `output_format: "svg"`. Use it for icons, logos, stickers, and illustrations that need editable paths, shapes, and colors.
```bash
curl -X POST "https://api.llmgateway.io/v1/images/generations" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-image-2.6-flare",
"prompt": "A flat bakery logo: a golden loaf above the words Field & Flour",
"output_format": "svg",
"svg": { "model": "gpt-5.4-mini", "reasoning": { "effort": "low" } },
"quality": "medium"
}' | jq -r '.data[0].b64_json' | base64 --decode > logo.svg
```
`data[0].b64_json` holds the base64-encoded SVG document (UTF-8 XML), and the response echoes `"output_format": "svg"`. The document contains static vector content only: no scripts, external resources, or embedded raster images.
* `n` must be `1`, and `output_compression` is not accepted.
* `/v1/images/edits` returns SVG too, drawn from your input images, with the same `svg` options (multipart: `svg[model]` and `svg[reasoning][effort]`). An SVG is not accepted as an edit input. The gateway requests SVG from OpenAI without streaming.
* `quality` controls the reference image the SVG is drawn from.
* If your OpenAI account has SVG model selection enabled, supply `svg.model` as in the example; otherwise omit `svg`. Optional `svg.reasoning.effort` controls the author independently of image quality.
* On `/v1/images/generations` and `/v1/images/edits`, requesting `svg` from a model without SVG output, or from `auto`, returns a `400` before any provider is called. In chat completions, the provider judges the value.
OpenAI draws a reference image with the image model, then a separate authoring model writes the SVG. The request is billed for both: the image tokens at the image model's rates, and the authoring model's tokens at that model's catalogue rates, included in `input_cost` and `output_cost`. Each component uses its own model's applicable discount. If the authoring model's rates are unknown, its authoring cost is omitted and logged for reconciliation; the reference image is still billed.
In chat completions, set `image_config.output_format` to `"svg"` and pass author settings in `image_config.svg`; the image arrives as a `data:image/svg+xml;base64,...` URL.
### OpenAI SDK [#openai-sdk]
Works with the standard OpenAI client library — just point the base URL to LLMGateway.
```ts
import OpenAI from "openai";
import { writeFileSync } from "fs";
const client = new OpenAI({
baseURL: "https://api.llmgateway.io/v1",
apiKey: process.env.LLM_GATEWAY_API_KEY,
});
const response = await client.images.generate({
model: "gemini-3-pro-image",
prompt: "A futuristic city skyline at sunset with flying cars",
n: 1,
size: "1024x1024",
});
response.data.forEach((image, i) => {
if (image.b64_json) {
const buf = Buffer.from(image.b64_json, "base64");
writeFileSync(`image-${i}.png`, buf);
}
});
```
### Vercel AI SDK [#vercel-ai-sdk]
Use the `@llmgateway/ai-sdk-provider` with `generateImage`.
```ts
import { createLLMGateway } from "@llmgateway/ai-sdk-provider";
import { generateImage } from "ai";
import { writeFileSync } from "fs";
const llmgateway = createLLMGateway({
apiKey: process.env.LLM_GATEWAY_API_KEY,
});
const result = await generateImage({
model: llmgateway.image("gemini-3-pro-image"),
prompt:
"A cozy cabin in a snowy mountain landscape at night with aurora borealis",
size: "1024x1024",
n: 1,
// aspectRatio and quality are model-specific — only some providers honor them.
// aspectRatio works on Gemini image models; OpenAI gpt-image-2 ignores it
// (use a literal WxH `size` instead).
aspectRatio: "16:9",
// quality works on OpenAI gpt-image-2 ("low" | "medium" | "high" | "auto").
// The AI SDK only forwards it through providerOptions.
providerOptions: {
llmgateway: { quality: "high" },
},
});
result.images.forEach((image, i) => {
const buf = Buffer.from(image.base64, "base64");
writeFileSync(`image-${i}.png`, buf);
});
```
## OpenAI Images Edit API [#openai-images-edit-api]
The `/v1/images/edits` endpoint is OpenAI-compatible and supports a focused subset of `images.edit` parameters.
When `/v1/chat/completions` is converted to an OpenAI-compatible multipart image edit, remote input images must return an image content type and stay within the caller's image size limit. The gateway checks downloaded bytes even when `Content-Length` is missing or understated, stops oversized downloads, and returns a `400` error.
### Parameters [#parameters-1]
| Parameter | Type | Required | Description |
| -------------------- | ------------------------ | -------- | --------------------------------------------------------------------------------- |
| `images` | array of `{ image_url }` | yes | Input images. `image_url` supports HTTPS URLs and base64 data URLs |
| `prompt` | string | yes | A text description of the desired image edit |
| `model` | string | no | Image editing model |
| `background` | enum | no | `transparent`, `opaque`, or `auto` — see [Transparency](#transparency) |
| `input_fidelity` | enum | no | `high` or `low` |
| `n` | integer | no | Number of edited images to generate |
| `output_format` | enum | no | `png`, `jpeg`, `webp`, `gif`, or `svg` — see [SVG output](#svg-output) |
| `svg` | object | no | SVG author `model` and `reasoning.effort` — see [SVG output](#svg-output) |
| `output_compression` | integer | no | Compression level for `jpeg`/`webp` |
| `quality` | enum | no | `low`, `medium`, `high`, or `auto`; GPT Image 2.5 also supports `xhigh` and `max` |
| `moderation` | enum | no | `auto` or `low` — see [Moderation](#moderation) |
| `complexity` | enum | no | `low`, `medium`, or `high` — see [Complexity](#complexity) |
| `frame_count` | integer | no | GIF frames, 2–16; requires `output_format: "gif"` |
| `frame_duration_ms` | integer | no | GIF frame duration in milliseconds, 20–2000 |
| `size` | string | no | Output size. Examples: `1024x1024`, `1536x1024`, `1K`, `2K`, `4K` |
| `aspect_ratio` | string | no | Aspect ratio override. Examples: `1:1`, `16:9`, `4:3`, `5:4` |
| `service_tier` | enum | no | `flex`, `priority`, or `default` — see [Service Tiers](https://docs.llmgateway.ai-stage.zibl.ir/features/service-tiers) |
`mask` is not supported yet on `/v1/images/edits`.
`multipart/form-data` requests upload one `image` file instead of `images`. `input_fidelity`, `aspect_ratio`, and `service_tier` are JSON-only.
### Edit markup [#edit-markup]
Send a markup PNG to guide a focused edit. For JSON requests, pass `markup: { "image_url": "https://example.com/markup.png" }` (a PNG data URL also works). For multipart edits, upload it as the separate `markup` file field. Markup is forwarded separately, not added as a reference image.
Use a PNG under the current image upload limit, with the same dimensions as the first input image. Markup is forwarded to OpenAI and Azure image models; availability depends on the model. It cannot be combined with the multipart `mask` field. Provider file IDs are not accepted for markup.
### Transparency [#transparency]
On `/v1/images/edits` and in chat `image_config`, `background`, `output_format`, and `output_compression` are sent to OpenAI and Azure, which return a `4xx` for values the model does not support. `/v1/images/generations` accepts `output_format` and `output_compression` but not `background`. For a transparent image, use `openai/gpt-image-2.5-sunburst` or `openai/gpt-image-2.5-flare` with `background: "transparent"` and `output_format: "png"` or `"webp"`.
Other providers do not receive these as parameters. `/v1/images/edits` adds them to the prompt instead, so their output can be opaque. When a request sets `output_format`, the response reports the format the provider returned if the gateway can detect it, and otherwise omits the field.
### curl (HTTPS image URL) [#curl-https-image-url]
```bash
curl -X POST "https://api.llmgateway.io/v1/images/edits" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"images": [
{
"image_url": "https://example.com/source-image.png"
}
],
"prompt": "Add a watercolor effect to this image",
"model": "gemini-3-pro-image",
"aspect_ratio": "16:9",
"quality": "high",
"size": "4K"
}'
```
### curl (base64 data URL) [#curl-base64-data-url]
```bash
curl -X POST "https://api.llmgateway.io/v1/images/edits" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"images": [
{
"image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"prompt": "Turn this into a pixel-art style image"
}'
```
## Chat Completions API [#chat-completions-api]
Image generation also works through the `/v1/chat/completions` endpoint, which is useful for conversational image generation, image editing with vision, and multi-turn interactions.
### Making Requests [#making-requests]
Simply use an image generation model and provide a text prompt describing the image you want to create.
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-pro-image",
"messages": [
{
"role": "user",
"content": "Generate an image of a cute golden retriever puppy playing in a sunny meadow"
}
]
}'
```
### Response Format [#response-format]
Image generation models return responses in the standard chat completions format, with generated images included in the `images` array within the assistant message:
```json
{
"id": "chatcmpl-1756234109285",
"object": "chat.completion",
"created": 1756234109,
"model": "gemini-3-pro-image",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Here's an image of a cute dog for you: ",
"images": [
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,"
}
}
]
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 8,
"completion_tokens": 1303,
"total_tokens": 1311
}
}
```
A request stopped by the [gateway content filter](https://docs.llmgateway.ai-stage.zibl.ir/resources/error-handling#gateway-content-filter) returns `finish_reason: "content_filter"` on the Chat Completions API and an empty `data` array on the Images API.
A provider's own safety rejection is returned the same way, and it is billed the way the provider bills us: a rejection the provider returns as an error carries no usage and costs nothing, apart from a rejection fee the provider publishes (currently only xAI's chat models). A block the provider serves as a normal response with usage, as Gemini image models do, is charged for the input tokens it reports, never for the blocked image.
### Vision support [#vision-support]
You can edit or modify images by combining image generation with [vision models](https://docs.llmgateway.ai-stage.zibl.ir/features/vision) by including the image in the `messages` array.
### Response Structure [#response-structure]
#### Images Array [#images-array]
The `images` array contains one or more generated images with the following structure:
* `type`: Always `"image_url"` for generated images
* `image_url.url`: A data URL containing the base64-encoded image data (format: `data:image/png;base64,`)
#### Content Field [#content-field]
The `content` field may contain descriptive text about the generated image, depending on the model's behavior.
### AI SDK (Chat Completions) [#ai-sdk-chat-completions]
You can use the AI SDK to generate images with your existing generateText or streamText calls using the LLMGateway provider.
#### Example [#example]
```ts title="/api/chat/route.ts"
import { streamText, type UIMessage, convertToModelMessages } from "ai";
import { createLLMGateway } from "@llmgateway/ai-sdk-provider";
interface ChatRequestBody {
messages: UIMessage[];
}
export async function POST(req: Request) {
const body = await req.json();
const { messages }: ChatRequestBody = body;
const llmgateway = createLLMGateway({
apiKey: "llmgateway_api_key",
baseUrl: "https://api.llmgateway.io/v1",
});
try {
const result = streamText({
model: llmgateway.chat("gemini-3-pro-image"),
messages: convertToModelMessages(messages),
});
return result.toUIMessageStreamResponse();
} catch {
return new Response(
JSON.stringify({ error: "LLM Gateway request failed" }),
{
status: 500,
},
);
}
}
```
Then you can render the image in your frontend using the `Image` component from the [ai-elements](https://ai-sdk.dev/elements/components/image).
Here is a full example of how to use the AI SDK to generate images in your frontend:
```tsx title="/app/page.tsx"
"use client";
import { useState, useRef } from "react";
import { useChat } from "@ai-sdk/react";
import { parseImagePartToDataUrl } from "@/lib/image-utils";
import {
PromptInput,
PromptInputBody,
PromptInputButton,
PromptInputSubmit,
PromptInputTextarea,
PromptInputToolbar,
} from "@/components/ai-elements/prompt-input";
import {
Conversation,
ConversationContent,
} from "@/components/ai-elements/conversation";
import { Image } from "@/components/ai-elements/image";
import { Loader } from "@/components/ai-elements/loader";
import { Message, MessageContent } from "@/components/ai-elements/message";
import { Response } from "@/components/ai-elements/response";
export const ChatUI = () => {
const textareaRef = useRef(null);
const [text, setText] = useState("");
const { messages, status, stop, regenerate, sendMessage } = useChat();
return (
<>
>
);
};
```
```ts title="/lib/image-utils.ts"
/**
* Parses a file object containing image data and returns a properly formatted data URL
* and normalized media type.
*
* Handles:
* - Normalizing mediaType from various property names (mediaType, mime_type)
* - Detecting existing data: URLs
* - Detecting base64-looking content
* - Stripping whitespace from base64 content
* - Building proper data:...;base64,... URLs
*/
export function parseImageFile(file: {
url?: string;
mediaType?: string;
mime_type?: string;
}): { dataUrl: string; mediaType: string } {
const mediaType = file.mediaType || file.mime_type || "image/png";
let url = String(file.url || "");
const isDataUrl = url.startsWith("data:");
const looksLikeBase64 =
!isDataUrl && /^[A-Za-z0-9+/=\s]+$/.test(url.slice(0, 200));
if (looksLikeBase64) {
url = url.replace(/\s+/g, "");
}
const dataUrl = isDataUrl
? url
: looksLikeBase64
? `data:${mediaType};base64,${url}`
: url;
return { dataUrl, mediaType };
}
/**
* Extracts base64-only content from a data URL.
* Returns empty string if the input is not a valid data URL.
*/
export function extractBase64FromDataUrl(dataUrl: string): string {
if (!dataUrl.startsWith("data:")) {
return "";
}
const comma = dataUrl.indexOf(",");
return comma >= 0 ? dataUrl.slice(comma + 1) : "";
}
/**
* Parses an image part (either image_url or file type) and returns
* dataUrl, base64Only, and mediaType ready for rendering.
*
* Handles error cases gracefully by returning empty base64Only string
* when parsing fails, allowing the renderer to skip invalid images.
*/
export function parseImagePartToDataUrl(part: any): {
dataUrl: string;
base64Only: string;
mediaType: string;
} {
try {
// Handle image_url parts
if (part.type === "image_url" && part.image_url?.url) {
const url = part.image_url.url;
const mediaType = "image/png"; // Default for image_url parts
if (url.startsWith("data:")) {
// Extract media type from data URL if present
const match = url.match(/data:([^;]+)/);
const extractedMediaType = match?.[1] || mediaType;
return {
dataUrl: url,
base64Only: extractBase64FromDataUrl(url),
mediaType: extractedMediaType,
};
}
return {
dataUrl: url,
base64Only: "",
mediaType,
};
}
// Handle file parts (AI SDK format)
if (part.type === "file") {
const { dataUrl, mediaType } = parseImageFile(part);
return {
dataUrl,
base64Only: extractBase64FromDataUrl(dataUrl),
mediaType,
};
}
return {
dataUrl: "",
base64Only: "",
mediaType: "image/png",
};
} catch {
return {
dataUrl: "",
base64Only: "",
mediaType: "image/png",
};
}
}
```
## Image Configuration [#image-configuration]
You can customize the generated image using the optional `image_config` parameter (for chat completions) or `size`/`quality`/`style` parameters (for the images API). The supported parameters vary by provider.
### Discovering limits from `/v1/models` [#discovering-limits-from-v1models]
Each image provider entry in [`GET /v1/models`](https://docs.llmgateway.ai-stage.zibl.ir/v1_models) lists what that mapping accepts:
| Field | Meaning |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `supported_image_sizes` | `WIDTHxHEIGHT` values for `size`. Exhaustive unless `supports_custom_image_size` is `true`, then common presets. |
| `supports_custom_image_size` | Other `WIDTHxHEIGHT` sizes are accepted within the provider's own limits. |
| `supported_aspect_ratios` | Values for `aspect_ratio`. Omitted when the model ignores `aspect_ratio`; choose a `size` instead. |
| `supported_image_resolutions` | Resolution tiers for `size`, such as `1K`, `2K` or `4K`. |
| `supported_image_qualities` | Values for `quality`. Omitted when the model has no quality control. |
| `max_input_images` | Most input images one request accepts on `/v1/images/edits` (0 when the model does not edit). |
| `max_images_per_request` | Largest `n`. Omitted when the provider sets no fixed limit. |
| `supports_image_edit` | Whether the model accepts input images. |
| `supports_transparent_background` | Whether `background: "transparent"` returns transparency natively. |
`/v1/images/generations` and `/v1/images/edits` check `size`, `aspect_ratio`, `quality`, `n` and the number of input images against these fields before calling a provider, and return a `400` naming the supported values when no provider of the requested model accepts the request. `size: "auto"` and fields a model does not declare are passed through.
### Google Models [#google-models]
Available Google models:
| Model | Description |
| ------------------------ | ---------------------------------------------------------------------------------------------- |
| `gemini-3-pro-image` | Gemini 3 Pro with native image generation. Supports aspect ratios and 1K–4K sizes. |
| `gemini-3.1-flash-image` | Gemini 3.1 Flash with native image generation. Supports 0.5K–4K sizes (default 1K). |
| `gemini-nano-banana-2.1` | Nano Banana 2.1, the Flash-tier successor to Nano Banana 2. Supports 1K–4K sizes (default 1K). |
| `gemini-2.5-flash-image` | Gemini 2.5 Flash Image (Nano Banana). Supports aspect ratios; always 1K, `image_size` ignored. |
#### gemini-3-pro-image [#gemini-3-pro-image]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-pro-image",
"messages": [
{
"role": "user",
"content": "Generate an image of a mountain landscape at sunset"
}
],
"image_config": {
"aspect_ratio": "16:9",
"image_size": "4K"
}
}'
```
| Parameter | Type | Description |
| -------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `aspect_ratio` | string | The aspect ratio of the generated image. Options: `"1:1"`, `"2:3"`, `"3:2"`, `"3:4"`, `"4:3"`, `"4:5"`, `"5:4"`, `"9:16"`, `"16:9"`, `"21:9"` |
| `image_size` | string | The resolution of the generated image. Options: `"1K"` (1024x1024), `"2K"` (2048x2048), `"4K"` (4096x4096) |
#### gemini-3.1-flash-image [#gemini-31-flash-image]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.1-flash-image",
"messages": [
{
"role": "user",
"content": "Generate an image of a mountain landscape at sunset"
}
],
"image_config": {
"image_size": "1K"
}
}'
```
| Parameter | Type | Description |
| -------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aspect_ratio` | string | The aspect ratio of the generated image. Options: `"1:1"`, `"1:4"`, `"1:8"`, `"2:3"`, `"3:2"`, `"3:4"`, `"4:1"`, `"4:3"`, `"4:5"`, `"5:4"`, `"8:1"`, `"9:16"`, `"16:9"`, `"21:9"` |
| `image_size` | string | The resolution of the generated image. Options: `"0.5K"` (512x512), `"1K"` (1024x1024, default), `"2K"` (2048x2048), `"4K"` (4096x4096) |
`gemini-3.1-flash-image` uniquely supports `"0.5K"` resolution, which is not
available on other Google image models.
### Meta Models [#meta-models]
Muse Image uses Meta's Responses API for generation and editing. It reasons
before rendering and can use reference images across refinement turns.
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "meta/muse-image-1.0",
"messages": [
{
"role": "user",
"content": "Create a product photo on a warm studio background"
}
],
"image_config": {
"image_size": "1024x1536"
}
}'
```
| Parameter | Type | Description |
| ------------ | ------ | -------------------------------------------------------------------------- |
| `image_size` | string | One of `"1024x1024"`, `"1024x1536"`, or `"1536x1024"`. Defaults to square. |
Muse Image does not expose a quality setting. Use `image_size` to choose square,
portrait, or landscape output.
### fal Models [#fal-models]
fal serves fast text-to-image models. They do not accept input images.
| Model | Description |
| --------------------------- | --------------------------------------------- |
| `fal-ai/flux-2-klein-4b` | FLUX.2 Klein 4B, Black Forest Labs' fastest. |
| `fal-ai/flux-3-klein` | FLUX 3 Klein with built-in prompt expansion. |
| `fal-ai/z-image-turbo` | Z-Image Turbo, photorealistic with text. |
| `fal-ai/recraft-v4.1-flash` | Recraft V4.1 Flash for photo and illustration |
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "fal-ai/flux-2-klein-4b",
"messages": [{ "role": "user", "content": "A lighthouse at dusk" }],
"image_config": { "image_size": "1536x1024", "n": 2 }
}'
```
| Parameter | Type | Description |
| --------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `image_size` | string | One of `"1024x1024"` (default), `"1536x1024"`, `"1024x1536"`, `"1344x768"`, `"768x1344"`, or `"2048x2048"`. Price varies by size. |
| `n` | integer | Number of images. Not supported by Recraft. |
| `seed` | integer | Random seed. Not supported by Recraft. |
| `output_format` | string | `png`, `jpeg`, or `webp`. Not supported by Recraft. |
Images flagged by fal's safety checker are removed; if none remain, the response
returns `finish_reason: "content_filter"`.
### Alibaba Models [#alibaba-models]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "alibaba/qwen-image-3.0",
"messages": [
{
"role": "user",
"content": "Generate an image of a mountain landscape at sunset"
}
],
"image_config": {
"image_size": "1024x1536",
"n": 1,
"seed": 42
}
}'
```
| Parameter | Type | Description |
| ------------ | ------- | ------------------------------------------------------------------------------------------------ |
| `image_size` | string | Image dimensions in `WIDTHxHEIGHT` format. Examples: `"1024x1024"`, `"1024x1536"`, `"1536x1024"` |
| `n` | integer | Number of images to generate (1-4) |
| `seed` | integer | Random seed for reproducible generation |
Available Alibaba models (see the [models page](https://llmgateway.io/models?filters=1\&imageGeneration=true) for current pricing):
| Model | Description |
| ------------------------------ | ---------------------------------------------------------------------------------------------------- |
| `alibaba/qwen-image-2.1-pro` | Generation and editing from up to 10 reference images, flat price per output image |
| `alibaba/qwen-image-2.1-turbo` | Fast, low-cost generation and editing from up to 10 reference images, flat price per output image |
| `alibaba/qwen-image-3.0` | Third-generation image generation and editing |
| `alibaba/qwen-image-3.0-pro` | Highest quality third-generation generation and editing. Priced per output size tier |
| `alibaba/wan-2-7-image` | Fast Wan 2.7 generation and editing from up to 9 input images, up to 2K, flat price per image |
| `alibaba/wan-2-7-image-pro` | Flagship Wan 2.7 generation up to 4K (text-to-image only) and editing up to 2K, flat price per image |
Alibaba models use explicit pixel dimensions (e.g., `"1024x1536"`) instead of
aspect ratios. For portrait orientation use `"1024x1536"`, for landscape use
`"1536x1024"`. Wan 2.7 models also accept the tiers `"1K"` and `"2K"`
(default), plus `"4K"` on `wan-2-7-image-pro` for text-to-image; tiers without
an input image produce square output.
### Z.AI Models [#zai-models]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "zai/cogview-4",
"messages": [
{
"role": "user",
"content": "Generate an image of a futuristic city skyline"
}
],
"image_config": {
"image_size": "1024x1024"
}
}'
```
| Parameter | Type | Description |
| ------------ | ------- | ------------------------------------------------------------------------------------------------ |
| `image_size` | string | Image dimensions in `WIDTHxHEIGHT` format. Examples: `"1024x1024"`, `"2048x1024"`, `"1024x2048"` |
| `n` | integer | Number of images to generate |
Available Z.AI models (see the [models page](https://llmgateway.io/models?filters=1\&imageGeneration=true) for current pricing):
| Model | Description |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `zai/cogview-4` | CogView-4 with bilingual support and excellent text rendering |
| `zai/glm-image` | GLM-Image with hybrid auto-regressive architecture, excellent for text-rendering and knowledge-intensive generation |
CogView-4 supports both Chinese and English prompts and excels at generating
images with embedded text.
### OpenAI Models [#openai-models]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-image-2",
"messages": [
{
"role": "user",
"content": "Generate a photo-real cinematic landscape at golden hour"
}
],
"image_config": {
"image_size": "3072x2160",
"image_quality": "low"
}
}'
```
| Parameter | Type | Description |
| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `image_size` | string | Image dimensions in `WIDTHxHEIGHT` format, or `"auto"` to let the model choose. |
| `image_quality` | string | `"low"`, `"medium"`, `"high"`, or `"auto"`; GPT Image 2.5 and 2.6 also support `"xhigh"` and `"max"`. Defaults to `"auto"` when omitted. |
| `moderation` | string | `"auto"` or `"low"` — see [Moderation](#moderation). Defaults to `"auto"` when omitted. |
| `complexity` | string | `low`, `medium`, or `high` — see [Complexity](#complexity). |
| `frame_count` | integer | GIF frames, 2–16; requires `output_format: "gif"`. |
| `frame_duration_ms` | integer | GIF frame duration in milliseconds, 20–2000. |
| `background` | string | `"transparent"`, `"opaque"`, or `"auto"` — see [Transparency](#transparency). |
| `output_format` | string | `"png"`, `"jpeg"`, or `"webp"`; GPT Image 2.6 also supports `"svg"` and `"gif"` — see [SVG output](#svg-output). |
| `output_compression` | number | `0`–`100`, for `jpeg` and `webp` output. |
OpenAI image models do **not** accept `aspect_ratio`. Always specify
`image_size` as `WIDTHxHEIGHT` (e.g. `"1024x1024"`, `"3072x2160"`). OpenAI
requires both width and height to be divisible by 16, the longest edge to be ≤
3840, and the total pixel count to fit within the model's pixel budget;
requests outside these bounds are rejected with HTTP 400.
Available OpenAI image models:
| Model | Description |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `openai/gpt-image-2` | OpenAI's next-generation image model with improved quality and prompt adherence, supporting text and vision. |
| `openai/gpt-image-2.5-sunburst` | Image generation and precise editing with text and image inputs; adds `xhigh` and `max` quality. |
| `openai/gpt-image-2.5-flare` | Fast everyday image generation and editing with text and image inputs; adds `xhigh` and `max` quality. |
| `openai/gpt-image-2.6-sunburst` | Detailed image generation and editing; adds `xhigh` and `max` quality and [SVG output](#svg-output). |
| `openai/gpt-image-2.6-flare` | Fast image generation and editing for iteration; adds `xhigh` and `max` quality and [SVG output](#svg-output). |
OpenAI shuts off `gpt-image-2` on February 10, 2027; `openai/gpt-image-2`
requests fail from that date. Migrate to GPT Image 2.6 Sunburst or Flare.
GPT Image 2.5 supports `1024x1024`, `1536x1024`, `1024x1536`, `auto`, and
custom sizes within the limits above. Its aspect ratio must stay between 1:3
and 3:1, with 655,360–8,294,400 total pixels. Resolutions above `2560x1440`
are experimental.
Both variants use the same per-token rates as GPT Image 2. Actual image token
usage varies by model, size, quality, and input; billing uses the provider's
reported usage. See the [models page](https://llmgateway.io/models?filters=1\&imageGeneration=true)
for current pricing.
GPT Image 2.6 uses the same per-token rates; OpenAI serves it directly only.
GPT Image 2 and both GPT Image 2.5 variants are also served through Azure at
the same rates — swap the `openai/` prefix for `azure/` to pin that route, or
send the bare model id and let the gateway pick.
### ByteDance Models [#bytedance-models]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "bytedance/seedream-4-5",
"messages": [
{
"role": "user",
"content": "Generate an image of a futuristic cyberpunk city at night"
}
],
"image_config": {
"image_size": "2048x2048"
}
}'
```
| Parameter | Type | Description |
| --------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `image_size` | string | Image dimensions in `WIDTHxHEIGHT` format or a preset. Examples: `"1K"`, `"2K"`, `"1024x1024"`, `"2048x2048"`, `"4096x4096"` |
| `background` | string | Seedream 5.5 only: `"auto"`, `"opaque"`, or `"transparent"` (requires `png` output) |
| `output_format` | string | Seedream 5.5 only: `"png"` (default) or `"jpeg"` |
| `seed` | number | Seedream 5.5 only: seed for reproducible output |
Available ByteDance models (see the [models page](https://llmgateway.io/models?filters=1\&imageGeneration=true) for current pricing):
| Model | Description |
| ------------------------------ | --------------------------------------------------------------- |
| `bytedance/seedream-4-0` | High-quality text-to-image generation with 2K default output |
| `bytedance/seedream-4-5` | Enhanced quality and consistency with improved prompt adherence |
| `bytedance/seedream-5-0-pro` | Precise generation and reference-image editing at 1K or 2K |
| `bytedance/seedream-5-0-flash` | Fast, low-cost generation and reference-image editing up to 2K |
| `bytedance/seedream-5-5` | Consistent editing, accurate text, and transparent backgrounds |
Seedream models support up to 2-10 reference images for multi-image fusion and
generation. The default output resolution is 2048×2048 (2K). Seedream 4.0 and
4.5 support up to 4096×4096 (4K); Seedream 5.0 Pro, 5.0 Flash, and 5.5 top out
at 2K. Seedream 5.5 accepts the `1K`, `1.5K`, and `2K` presets or custom sizes
between 921,600 and 4,624,220 pixels, and bills each reference image
separately.
### Tencent Models [#tencent-models]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "tencent/hy-image-v3.5-preview",
"messages": [
{
"role": "user",
"content": "A neon sign reading \"Open Late\" above a rainy storefront"
}
],
"image_config": {
"image_size": "4096x2304"
}
}'
```
| Parameter | Type | Description |
| ------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `image_size` | string | Exact output size in `WIDTHxHEIGHT` format. Each side 256–8192. Omit it to let the model pick the size from the prompt (\~1.5K) |
| `seed` | integer | Seed for reproducible output |
| Model | Description |
| ------------------------------- | -------------------------------------------------------------------------------------- |
| `tencent/hy-image-v3.5-preview` | Generation and editing from up to 20 reference images, up to 4K, strong text in images |
Each request returns one image. Tencent bills a fixed token count per image
(more at 4K); billing uses the token count Tencent reports. See the
[models page](https://llmgateway.io/models?filters=1\&imageGeneration=true) for
current pricing.
### MiniMax Models [#minimax-models]
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax/minimax-h3-image",
"messages": [
{
"role": "user",
"content": "A red apple on a weathered wooden table, soft window light"
}
],
"image_config": {
"image_size": "2K",
"aspect_ratio": "16:9"
}
}'
```
| Parameter | Type | Description |
| -------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `image_size` | string | `1K`, `2K` or `4K` area tier (default `4K`), or an exact `WIDTHxHEIGHT` between 655,360 and 20,000,000 pixels |
| `aspect_ratio` | string | `auto` (default, picked by prompt enhancement) or `X:Y` between `1:3` and `3:1`. Ignored when `image_size` is `WIDTHxHEIGHT` |
| `n` | number | 1–10 images |
| Model | Description |
| -------------------------- | ---------------------------------------------------------------------------------------- |
| `minimax/minimax-h3-image` | Generation and editing from up to 16 reference images, up to 4K, with prompt enhancement |
MiniMax always enhances the prompt, and bills it as input tokens. Images that
fail MiniMax's content safety check are dropped; the request returns
`content_filter` when none remain. Billing uses the text, reference-image and
output-image token counts MiniMax reports. See the
[models page](https://llmgateway.io/models?filters=1\&imageGeneration=true) for
current pricing.
## Complexity [#complexity]
GPT Image 2.6 Sunburst and Flare accept `complexity: "low" | "medium" | "high"` on `/v1/images/generations` and `/v1/images/edits` (JSON or multipart). For chat completions, use `image_config.complexity`. If omitted, OpenAI defaults both models to `high`; the gateway does not override this default.
Complexity controls planning before rendering, independently of `quality`. Lower values can suit focused edits such as changing an outfit or background; higher values can help with dense text and complex layouts. See OpenAI's [image complexity guide](https://developers.openai.com/api/docs/guides/image-generation).
## Moderation [#moderation]
GPT Image models expose a `moderation` parameter that controls how strict the
provider's content filtering is:
* `auto` (default) — standard filtering, which limits certain categories of
potentially age-inappropriate content.
* `low` — less restrictive filtering. OpenAI's content policy still applies.
Send it as a top-level parameter on `/v1/images/generations` and
`/v1/images/edits`, or inside `image_config` on `/v1/chat/completions`:
```bash
curl -X POST "https://api.llmgateway.io/v1/images/generations" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-image-2.5-flare",
"prompt": "A cute cat wearing a tiny top hat",
"moderation": "low"
}'
```
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-image-2.5-flare",
"messages": [{ "role": "user", "content": "A cute cat wearing a tiny top hat" }],
"image_config": { "moderation": "low" }
}'
```
Models without a moderation control ignore the parameter.
## Usage Notes [#usage-notes]
Image generation models typically have higher token costs compared to
text-only models due to the computational requirements of image synthesis.
Generated images are returned as base64-encoded data URLs, which can be large.
Consider the payload size when integrating image generation into your
applications.
# Master Keys
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/master-keys
Master keys are org-scoped bearer tokens that let you create projects, gateway API keys, IAM rules (both per key and per organization member), and your organization's custom providers and custom models programmatically — without going through the dashboard. They are intended for server-to-server provisioning (e.g. multi-tenant onboarding from your own backend).
They also expose [usage and cost reporting](#usage-and-cost-reporting), so you can pull per-member and per-model spend into your own dashboards, data warehouse, or chargeback process.
Master keys are available on the **Enterprise** plan only. Contact us at
[contact@llmgateway.io](mailto:contact@llmgateway.io) to enable them for your organization.
## Security [#security]
* Master keys are stored as **HMAC-SHA256 hashes** in the database (using the `GATEWAY_API_KEY_HASH_SECRET` secret). The plain token is shown to you **only once** at creation time.
* Each master key is scoped to a single organization and cannot access resources in other organizations.
* Deleting or deactivating a master key revokes all programmatic access immediately.
* All creates/deletes/status changes are recorded in your organization audit log.
## Limits [#limits]
* Maximum **10 master keys per organization**, counting active and inactive keys — only deleting a key frees a slot.
* Programmatic project and API-key creation enforces the same per-org and per-project limits as the dashboard flow.
## Managing master keys [#managing-master-keys]
In the dashboard, go to **Organization → Master Keys**. From there you can:
* Create a new master key (the plain token is shown once — copy it immediately).
* View the masked token, status, creator, and last-used timestamp for each existing key.
* Activate / deactivate or delete keys.
## Authentication [#authentication]
All programmatic endpoints live under `/v1/master/*` and require a master key in the `Authorization` header:
```
Authorization: Bearer llmgmk_...
```
A request with a missing, invalid, inactive, or non-enterprise master key receives a 401 / 403 response. A master key is also rejected with `403` when its creator is no longer an owner or admin of the organization (keys are effectively revoked on demotion) or when the organization has been deactivated or deleted.
## Endpoints [#endpoints]
### List projects [#list-projects]
`GET /v1/master/projects`
Returns all non-deleted projects in the master key's organization.
```bash
curl https://internal.llmgateway.io/v1/master/projects \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"projects": [
{
"id": "proj_...",
"name": "Customer ACME",
"organizationId": "org_...",
"cachingEnabled": false,
"cacheDurationSeconds": 60,
"mode": "hybrid",
"status": "active",
"createdAt": "...",
"updatedAt": "..."
}
]
}
```
### Create a project [#create-a-project]
`POST /v1/master/projects`
```bash
curl -X POST https://internal.llmgateway.io/v1/master/projects \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Customer ACME",
"cachingEnabled": false,
"mode": "hybrid"
}'
```
Body parameters:
| Field | Type | Description |
| -------------------------- | ------------------------------------------------ | ----------------------------------------------------------------- |
| `name` | string | Project name (1–255 chars) |
| `cachingEnabled` | boolean (optional) | Default `false` |
| `cacheDurationSeconds` | number (optional) | 10–31536000, default 60 |
| `providerCacheControlMode` | `"auto" \| "passthrough" \| "off"` (optional) | [Provider cache writes](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/provider-cache-control) |
| `providerCacheAutoTtl` | `"5m" \| "1h"` (optional) | TTL for auto-injected cache markers |
| `mode` | `"api-keys" \| "credits" \| "hybrid"` (optional) | Default `"hybrid"` |
Response (201): the created project.
### Update a project [#update-a-project]
`PATCH /v1/master/projects/{id}`
Updates a project owned by the master key's organization. All body fields are optional; provide only the ones you want to change.
```bash
curl -X PATCH https://internal.llmgateway.io/v1/master/projects/proj_... \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Customer ACME (renamed)",
"cachingEnabled": true,
"status": "inactive"
}'
```
Body parameters (all optional, at least one required):
| Field | Type | Description |
| -------------------------- | ------------------------------------- | ----------------------------------------------------------------- |
| `name` | string | 1–255 chars |
| `cachingEnabled` | boolean | |
| `cacheDurationSeconds` | number | 10–31536000 |
| `providerCacheControlMode` | `"auto" \| "passthrough" \| "off"` | [Provider cache writes](https://docs.llmgateway.ai-stage.zibl.ir/features/caching/provider-cache-control) |
| `providerCacheAutoTtl` | `"5m" \| "1h"` | TTL for auto-injected cache markers |
| `mode` | `"api-keys" \| "credits" \| "hybrid"` | |
| `status` | `"active" \| "inactive"` | Toggle the project without deleting |
Response (200): the updated project. It carries both `providerCacheControlMode` and the older `providerCacheControlEnabled` boolean, which reports `false` only for `"off"`.
### Delete a project [#delete-a-project]
`DELETE /v1/master/projects/{id}`
Soft-deletes a project (sets `status` to `"deleted"`). Cascades to its API keys. Mirroring the dashboard's owner-only project deletion, this endpoint returns a `403` unless the user who created the master key is currently an **owner** of the organization.
```bash
curl -X DELETE https://internal.llmgateway.io/v1/master/projects/proj_... \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{ "message": "Project deleted successfully" }
```
### List gateway API keys [#list-gateway-api-keys]
`GET /v1/master/keys`
Returns the developer-created gateway API keys in the master key's organization, each with its creator, project, configured limits, the usage consumed so far, and — when a windowed limit is set — the time the current period resets. `projectName` provides the human-readable project name alongside `projectId`. `createdBy` contains the creator's internal user ID, while `createdByEmail` contains their email address (`null` when unavailable). Pass an optional `projectId` query parameter to scope the list to a single project.
```bash
curl "https://internal.llmgateway.io/v1/master/keys?projectId=proj_..." \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"apiKeys": [
{
"id": "ak_...",
"description": "Customer ACME — production key",
"status": "active",
"projectId": "proj_...",
"projectName": "Customer ACME",
"createdBy": "usr_...",
"createdByEmail": "member@example.com",
"maskedToken": "llmgtwy_AbCd•••••",
"usageLimit": "100.00",
"usage": "42.13",
"periodUsageLimit": "10.00",
"periodUsageDurationValue": 1,
"periodUsageDurationUnit": "day",
"currentPeriodUsage": "3.50",
"currentPeriodStartedAt": "2025-01-15T00:00:00.000Z",
"currentPeriodResetAt": "2025-01-16T00:00:00.000Z",
"createdAt": "...",
"updatedAt": "..."
}
]
}
```
Limit and usage fields:
| Field | Description |
| -------------------------- | ---------------------------------------------------------------------------------- |
| `usageLimit` | Lifetime spend cap (`null` when uncapped) |
| `usage` | Total spend accrued against `usageLimit` over the key's lifetime |
| `periodUsageLimit` | Recurring per-window spend cap (`null` when no windowed limit is configured) |
| `periodUsageDurationValue` | Length of the window, paired with `periodUsageDurationUnit` |
| `periodUsageDurationUnit` | `"hour" \| "day" \| "week" \| "month"` |
| `currentPeriodUsage` | Spend accrued in the current window (`"0"` when unconfigured or the window lapsed) |
| `currentPeriodStartedAt` | When the current window began (`null` when unconfigured or lapsed) |
| `currentPeriodResetAt` | When the windowed limit resets (`null` when unconfigured or lapsed) |
The plain token is never returned by this endpoint — only a masked form for identification.
### Get a gateway API key [#get-a-gateway-api-key]
`GET /v1/master/keys/{id}`
Returns a single gateway API key in the master key's organization, with the same limit, usage, and reset-time fields as the list endpoint.
```bash
curl https://internal.llmgateway.io/v1/master/keys/ak_... \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"apiKey": {
"id": "ak_...",
"description": "Customer ACME — production key",
"status": "active",
"projectId": "proj_...",
"projectName": "Customer ACME",
"createdBy": "usr_...",
"createdByEmail": "member@example.com",
"maskedToken": "llmgtwy_AbCd•••••",
"usageLimit": "100.00",
"usage": "42.13",
"periodUsageLimit": "10.00",
"periodUsageDurationValue": 1,
"periodUsageDurationUnit": "day",
"currentPeriodUsage": "3.50",
"currentPeriodStartedAt": "2025-01-15T00:00:00.000Z",
"currentPeriodResetAt": "2025-01-16T00:00:00.000Z",
"createdAt": "...",
"updatedAt": "..."
}
}
```
### Create a gateway API key [#create-a-gateway-api-key]
`POST /v1/master/keys`
```bash
curl -X POST https://internal.llmgateway.io/v1/master/keys \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"projectId": "proj_...",
"description": "Customer ACME — production key"
}'
```
Body parameters:
| Field | Type | Description |
| -------------------------- | ------------------------------------------------- | -------------------------------------------- |
| `projectId` | string | Must belong to the master key's organization |
| `description` | string | API key description (1–255 chars) |
| `usageLimit` | string (optional) | Lifetime usage limit |
| `periodUsageLimit` | string (optional) | Recurring period usage limit |
| `periodUsageDurationValue` | number (optional) | Required if `periodUsageLimit` is set |
| `periodUsageDurationUnit` | `"hour" \| "day" \| "week" \| "month"` (optional) | Required if `periodUsageLimit` is set |
The created gateway API key's plain token is returned in the response **only
once**. Persist it immediately on your side.
Response (201):
```json
{
"apiKey": {
"id": "ak_...",
"token": "llmgtwy_...",
"description": "Customer ACME — production key",
"status": "active",
"projectId": "proj_...",
"createdBy": "usr_...",
"createdAt": "...",
"updatedAt": "..."
}
}
```
API-key create and update requests also accept `providerCompliancePolicy`: a [compliance policy](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#api-key-policies) object, or `null` to remove key-specific settings. Key responses include the saved policy. Enabled organization policies remain mandatory; key policies can only add restrictions.
### Update a gateway API key [#update-a-gateway-api-key]
`PATCH /v1/master/keys/{id}`
Updates an API key in a project owned by the master key's organization. All body fields are optional; provide only the ones you want to change.
```bash
curl -X PATCH https://internal.llmgateway.io/v1/master/keys/ak_... \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"status": "inactive",
"usageLimit": "100.00"
}'
```
Body parameters (all optional, at least one required):
| Field | Type | Description |
| -------------------------- | -------------------------------------- | -------------------------------------- |
| `description` | string | 1–255 chars |
| `status` | `"active" \| "inactive"` | |
| `usageLimit` | string \| null | Lifetime usage limit (null to clear) |
| `periodUsageLimit` | string \| null | Recurring period limit (null to clear) |
| `periodUsageDurationValue` | number \| null | Required if `periodUsageLimit` is set |
| `periodUsageDurationUnit` | `"hour" \| "day" \| "week" \| "month"` | Required if `periodUsageLimit` is set |
Response (200): the updated API key, including its configured limits, consumed `usage` / `currentPeriodUsage`, and the `currentPeriodResetAt` window-reset time (same fields as the [list endpoint](#list-gateway-api-keys)). The plain token is **not** included — it is only returned at creation.
Two dashboard-only key features have no master API equivalent yet: [expiration
(TTL)](https://docs.llmgateway.ai-stage.zibl.ir/features/api-keys#expiration-ttl) and [rolling a key's
secret](https://docs.llmgateway.ai-stage.zibl.ir/features/api-keys#rotating-rolling-api-keys). To replace a key
programmatically, create a new one and delete the old one once your clients
have switched over.
### Delete a gateway API key [#delete-a-gateway-api-key]
`DELETE /v1/master/keys/{id}`
Soft-deletes the API key (sets `status` to `"deleted"`). Any in-flight requests using the key will be rejected immediately on next auth check.
```bash
curl -X DELETE https://internal.llmgateway.io/v1/master/keys/ak_... \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{ "message": "API key deleted successfully" }
```
The managed Playground API key cannot be updated or deleted via the master
API.
## Usage and cost reporting [#usage-and-cost-reporting]
`GET /v1/master/usage`
Returns usage and cost for the master key's organization as a flat list of rows, grouped by any combination of member, model, provider, project, and API key, and bucketed hourly, daily, or not at all. This is the endpoint to point an internal reporting tool, data warehouse, or chargeback job at — it is the only usage surface that authenticates with a token rather than a dashboard session.
Like every `/v1/master/*` endpoint, this requires an **Enterprise** plan. A
master key on any other plan receives a `403`.
```bash
# Cost per member for a month
curl -G https://internal.llmgateway.io/v1/master/usage \
-H "Authorization: Bearer $MASTER_KEY" \
-d from=2026-07-01 -d to=2026-07-31 \
-d granularity=total -d groupBy=user
```
Query parameters:
| Param | Type | Default | Description |
| ------------- | ----------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------- |
| `from`, `to` | `YYYY-MM-DD` | last 7 days | Inclusive window, interpreted as wall-clock days in `timezone`. Max 366 days |
| `timezone` | IANA timezone | `UTC` | Timezone the day/hour buckets are labelled in |
| `granularity` | `hour` \| `day` \| `total` | `day` | Time bucket. `total` collapses the window into one row per group. `hour` caps at 31 days |
| `groupBy` | comma-separated: `user`, `model`, `provider`, `project`, `apiKey` | `user,model` | Dimensions to break down by. Pass an empty value for organization-wide totals |
| `projectId` | string | — | Restrict to one project. `404` if it is not in this organization |
| `userId` | string | — | Restrict to one member |
| `apiKeyId` | string | — | Restrict to one gateway API key |
| `limit` | 1–10000 | `1000` | Rows per page |
| `offset` | ≥ 0 | `0` | Row offset for paging |
| `format` | `json` \| `csv` | `json` | `csv` returns a `text/csv` attachment with a fixed header |
Response (200):
```json
{
"from": "2026-07-01",
"to": "2026-07-31",
"granularity": "day",
"groupBy": ["user", "model"],
"rows": [
{
"date": "2026-07-01",
"userId": "usr_...",
"userName": "Ada Lovelace",
"userEmail": "ada@example.com",
"projectId": null,
"projectName": null,
"apiKeyId": null,
"apiKeyName": null,
"model": "gpt-5.6-sol",
"provider": "openai",
"requestCount": 128,
"errorCount": 2,
"inputTokens": 481203,
"outputTokens": 92844,
"totalTokens": 574047,
"cachedTokens": 120000,
"reasoningTokens": 18320,
"cost": 3.4127,
"inputCost": 2.1,
"outputCost": 1.3127,
"creditsRequestCount": 128,
"apiKeysRequestCount": 0,
"creditsCost": 3.4127,
"apiKeysCost": 0
}
],
"pagination": { "limit": 1000, "offset": 0, "hasMore": false }
}
```
Every row carries the full column set. Dimension fields you did not group by are `null`, and `date` is `null` when `granularity=total`, so the row shape stays stable for a schema-driven consumer. `creditsCost` / `apiKeysCost` split the blended `cost` into credit-billed and BYOK traffic.
### Per-member, per-model breakdown [#per-member-per-model-breakdown]
Combine the two dimensions to get the cross-tab most reporting tools want — one row per member, model, and day:
```bash
curl -G https://internal.llmgateway.io/v1/master/usage \
-H "Authorization: Bearer $MASTER_KEY" \
-d from=2026-07-01 -d to=2026-07-31 \
-d granularity=day -d groupBy=user,model \
-d timezone=Europe/Berlin
```
### CSV export [#csv-export]
```bash
curl -G https://internal.llmgateway.io/v1/master/usage \
-H "Authorization: Bearer $MASTER_KEY" \
-d from=2026-07-01 -d to=2026-07-31 \
-d granularity=day -d groupBy=user,model -d format=csv \
-o usage-july.csv
```
The CSV header is the same fixed column set regardless of the dimensions requested, so a scheduled export never changes shape.
**Usage is attributed to the member who created the API key** (there is no
per-caller identity on an inference request). A key shared by several people
reports entirely under its creator. For accurate per-person reporting, issue
one gateway API key per member — the per-member key limit under **Organization
→ Members** is the lever that enforces it.
Two more things worth knowing:
* These figures come from hourly rollups, not the request log, so they are **not** affected by your [data retention](https://docs.llmgateway.ai-stage.zibl.ir/features/data-retention) setting — per-member and per-model history stays available even with retention turned off.
* Traffic from [embeddable payments](https://docs.llmgateway.ai-stage.zibl.ir/features/embeddable-payments) end-user keys rolls up to the member who provisioned the platform key.
## IAM rules [#iam-rules]
Each gateway API key can have one or more IAM rules that restrict which models, providers, or pricing tiers it is allowed to use. Rules are evaluated at request time by the gateway. A key with no active rules has no IAM restrictions.
Rule types:
| `ruleType` | Description |
| ----------------- | ----------------------------------------------------------- |
| `allow_models` | Only the listed models are permitted |
| `deny_models` | The listed models are blocked |
| `allow_providers` | Only the listed providers are permitted |
| `deny_providers` | The listed providers are blocked |
| `allow_pricing` | Only models matching the pricing constraint are permitted |
| `deny_pricing` | Models matching the pricing constraint are blocked |
| `allow_ip_cidrs` | Only requests from the listed IPv4/IPv6 CIDRs are permitted |
| `deny_ip_cidrs` | Requests from the listed IPv4/IPv6 CIDRs are blocked |
The `ruleValue` JSON object holds the rule's parameters. The fields it accepts depend on the `ruleType`:
| Field | Type | Used by |
| ---------------- | ------------------ | ----------------------------------- |
| `models` | string\[] | `allow_models`, `deny_models` |
| `providers` | string\[] | `allow_providers`, `deny_providers` |
| `pricingType` | `"free" \| "paid"` | `allow_pricing`, `deny_pricing` |
| `maxInputPrice` | number | `allow_pricing`, `deny_pricing` |
| `maxOutputPrice` | number | `allow_pricing`, `deny_pricing` |
| `ipCidrs` | string\[] | `allow_ip_cidrs`, `deny_ip_cidrs` |
### IP CIDR rules [#ip-cidr-rules]
IP CIDR rules restrict gateway requests by source IP. Both IPv4 (e.g. `192.0.2.0/24`) and IPv6 (e.g. `2001:db8::/32`) ranges are supported, and you can mix both in a single rule. To restrict to a single address, use a `/32` (IPv4) or `/128` (IPv6) prefix.
The gateway reads the client IP from a single header, named by the `CLIENT_IP_HEADER` environment variable. On the hosted service the load balancer overwrites that header on every request, so a value sent by the client cannot spoof the address. Self-hosted deployments default to `X-Forwarded-For`; point `CLIENT_IP_HEADER` at a header your reverse proxy overwrites rather than appends to.
IPv4-mapped IPv6 addresses (`::ffff:1.2.3.4`) are normalized to IPv4 so a single `1.2.3.0/24` rule still matches when the upstream connection happens to be IPv6.
When an `allow_ip_cidrs` rule is configured and the gateway cannot determine the client IP, the request is denied. Invalid CIDR syntax is rejected at rule-creation time with a `400` error.
All endpoints scope by the master key's organization: a `404` is returned if the API key (or rule) is not part of the authenticated master key's organization.
### List IAM rules [#list-iam-rules]
`GET /v1/master/keys/{id}/iam`
```bash
curl https://internal.llmgateway.io/v1/master/keys/ak_.../iam \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"rules": [
{
"id": "iam_...",
"apiKeyId": "ak_...",
"ruleType": "allow_models",
"ruleValue": {
"models": ["openai/gpt-4o", "anthropic/claude-sonnet-4-6"]
},
"status": "active",
"createdAt": "...",
"updatedAt": "..."
}
]
}
```
### Create an IAM rule [#create-an-iam-rule]
`POST /v1/master/keys/{id}/iam`
```bash
curl -X POST https://internal.llmgateway.io/v1/master/keys/ak_.../iam \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"ruleType": "allow_models",
"ruleValue": {
"models": ["openai/gpt-4o", "anthropic/claude-sonnet-4-6"]
}
}'
```
Body parameters:
| Field | Type | Description |
| ----------- | ------------------------ | ------------------------------------------------------- |
| `ruleType` | rule type enum (above) | Required |
| `ruleValue` | object (see table above) | Must include the fields appropriate for the chosen type |
| `status` | `"active" \| "inactive"` | Optional, defaults to `"active"` |
Restricting by source IP:
```bash
curl -X POST https://internal.llmgateway.io/v1/master/keys/ak_.../iam \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"ruleType": "allow_ip_cidrs",
"ruleValue": {
"ipCidrs": ["192.0.2.0/24", "2001:db8::/32"]
}
}'
```
Response (201): the created IAM rule.
### Update an IAM rule [#update-an-iam-rule]
`PATCH /v1/master/keys/{id}/iam/{ruleId}`
All body fields are optional; provide only the ones you want to change.
```bash
curl -X PATCH https://internal.llmgateway.io/v1/master/keys/ak_.../iam/iam_... \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"status": "inactive"
}'
```
Body parameters (all optional, at least one required):
| Field | Type | Description |
| ----------- | ------------------------ | --------------------------------------- |
| `ruleType` | rule type enum (above) | Change the rule type |
| `ruleValue` | object (see table above) | Replace the rule value |
| `status` | `"active" \| "inactive"` | Activate or deactivate without deleting |
Response (200): the updated IAM rule.
### Delete an IAM rule [#delete-an-iam-rule]
`DELETE /v1/master/keys/{id}/iam/{ruleId}`
Permanently removes an IAM rule from the API key.
```bash
curl -X DELETE https://internal.llmgateway.io/v1/master/keys/ak_.../iam/iam_... \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{ "message": "IAM rule deleted successfully" }
```
## Member IAM rules [#member-iam-rules]
The same rule types can be applied to an **organization member** instead of a single API key. Member-level rules are an organization-wide ceiling: a request must pass both the member's rules and the key's rules, so key rules can only narrow access further, never expand it. They apply to all regular API keys created by that member. See [Member-Level IAM Rules](https://docs.llmgateway.ai-stage.zibl.ir/features/api-keys#member-level-iam-rules) for the full semantics.
The `{member}` path parameter accepts either the **membership id** or the member's **email address** (matched case-insensitively). Email references must resolve to a user who is a member of the master key's organization — an email belonging to a user outside the organization, or an unknown reference, returns a `404`.
The `ruleType`, `ruleValue`, and `status` fields are identical to the per-key IAM endpoints above.
### List member IAM rules [#list-member-iam-rules]
`GET /v1/master/members/{member}/iam`
```bash
curl https://internal.llmgateway.io/v1/master/members/jane@example.com/iam \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"rules": [
{
"id": "iam_...",
"userOrganizationId": "uo_...",
"ruleType": "allow_providers",
"ruleValue": {
"providers": ["openai"]
},
"status": "active",
"createdAt": "...",
"updatedAt": "..."
}
]
}
```
### Create a member IAM rule [#create-a-member-iam-rule]
`POST /v1/master/members/{member}/iam`
```bash
curl -X POST https://internal.llmgateway.io/v1/master/members/jane@example.com/iam \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"ruleType": "allow_providers",
"ruleValue": {
"providers": ["openai"]
}
}'
```
Response (201): the created member IAM rule.
### Update a member IAM rule [#update-a-member-iam-rule]
`PATCH /v1/master/members/{member}/iam/{ruleId}`
All body fields are optional; provide only the ones you want to change.
```bash
curl -X PATCH https://internal.llmgateway.io/v1/master/members/uo_.../iam/iam_... \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"status": "inactive"
}'
```
Response (200): the updated member IAM rule.
### Delete a member IAM rule [#delete-a-member-iam-rule]
`DELETE /v1/master/members/{member}/iam/{ruleId}`
```bash
curl -X DELETE https://internal.llmgateway.io/v1/master/members/uo_.../iam/iam_... \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{ "message": "Member IAM rule deleted successfully" }
```
## Custom providers [#custom-providers]
Custom providers are your own OpenAI-compatible endpoints, registered as BYOK provider keys with `provider: "custom"`. The gateway routes to them with the model string `/` (e.g. `acme/acme-large`). See [Custom Providers](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers) for the dashboard flow and routing semantics.
Only custom providers are exposed through the master API — catalog providers (OpenAI, Anthropic, …) require an interactive upstream credential check and must be added from the dashboard.
All endpoints scope by the master key's organization: a `404` is returned if the provider key is not a non-deleted custom provider in that organization.
The provider token is stored but never returned. Responses only include a
`maskedToken` for identification.
### List custom providers [#list-custom-providers]
`GET /v1/master/custom-providers`
```bash
curl https://internal.llmgateway.io/v1/master/custom-providers \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"customProviders": [
{
"id": "pk_...",
"provider": "custom",
"name": "acme",
"baseUrl": "https://llm.acme.example.com",
"maskedToken": "sk-abc123def•••••",
"status": "active",
"customModelsOnly": true,
"complianceAttestation": null,
"organizationId": "org_...",
"createdAt": "...",
"updatedAt": "..."
}
]
}
```
### Get a custom provider [#get-a-custom-provider]
`GET /v1/master/custom-providers/{id}`
Returns a single custom provider in the master key's organization.
### Create a custom provider [#create-a-custom-provider]
`POST /v1/master/custom-providers`
```bash
curl -X POST https://internal.llmgateway.io/v1/master/custom-providers \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "acme",
"baseUrl": "https://llm.acme.example.com",
"token": "sk-acme-...",
"customModelsOnly": true
}'
```
Body parameters:
| Field | Type | Description |
| ----------------------- | ------------------ | -------------------------------------------------------------------------------------------- |
| `name` | string | Lowercase letters and single hyphens only. Unique per organization; used in the model string |
| `baseUrl` | string | OpenAI-compatible base URL. Internal/reserved addresses are rejected |
| `token` | string | Upstream API key. Stored server-side, never returned |
| `customModelsOnly` | boolean (optional) | Restrict the provider to models defined in your custom catalog. Default `false` |
| `forwardCacheControl` | boolean (optional) | Forward `cache_control` markers to the provider instead of stripping them. Default `true` |
| `complianceAttestation` | object (optional) | Self-attested compliance posture. `attestedAt` / `attestedByUserId` are stamped server-side |
Response (201): the created custom provider.
### Update a custom provider [#update-a-custom-provider]
`PATCH /v1/master/custom-providers/{id}`
All body fields are optional; provide only the ones you want to change.
```bash
curl -X PATCH https://internal.llmgateway.io/v1/master/custom-providers/pk_... \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"baseUrl": "https://llm2.acme.example.com",
"token": "sk-acme-rotated-..."
}'
```
Body parameters (all optional, at least one required):
| Field | Type | Description |
| ----------------------- | ------------------------ | ---------------------------------------------- |
| `baseUrl` | string | Repoint the provider at a new endpoint |
| `token` | string | Rotate the upstream API key |
| `status` | `"active" \| "inactive"` | Disable the provider without deleting it |
| `customModelsOnly` | boolean | Toggle the custom-catalog restriction |
| `forwardCacheControl` | boolean | Toggle forwarding of `cache_control` markers |
| `complianceAttestation` | object \| null | Replace the attestation, or `null` to clear it |
The provider `name` cannot be changed through the master API — it is the routing segment your model strings reference. Owners and admins can rename a custom provider from the dashboard, which changes the `/` prefix clients must use.
Response (200): the updated custom provider.
### Delete a custom provider [#delete-a-custom-provider]
`DELETE /v1/master/custom-providers/{id}`
Soft-deletes the provider (sets `status` to `"deleted"`). Its custom models stop resolving immediately.
Response (200):
```json
{ "message": "Custom provider deleted successfully" }
```
## Custom models [#custom-models]
Custom models are your organization's catalogue entries for a custom provider: the context window, output limit, per-token pricing, and capability flags the gateway uses to route, validate, and bill requests to that model. When a provider has `customModelsOnly: true`, only models in this catalogue can be called through it.
Query these endpoints to read the full catalogue you have registered — including `contextSize`, `maxOutput`, and every price field — for surfacing in your own dashboards or cost tooling.
Per-token prices are strings in USD per token. Use `e-6` notation so the
coefficient reads directly as USD per million tokens — `"3.0e-6"` is $3.00/M.
### List custom models [#list-custom-models]
`GET /v1/master/custom-models`
Returns the non-deleted custom models in the master key's organization. Pass an optional `providerKeyId` query parameter to scope the list to a single custom provider.
```bash
curl "https://internal.llmgateway.io/v1/master/custom-models?providerKeyId=pk_..." \
-H "Authorization: Bearer $MASTER_KEY"
```
Response (200):
```json
{
"customModels": [
{
"id": "cm_...",
"providerKeyId": "pk_...",
"organizationId": "org_...",
"modelName": "acme-large",
"displayName": "Acme Large",
"contextSize": 200000,
"maxOutput": 32000,
"inputPrice": "3.0e-6",
"outputPrice": "15.0e-6",
"cachedInputPrice": "0.3e-6",
"streaming": "true",
"vision": true,
"tools": true,
"reasoning": null,
"jsonOutput": true,
"supportedParameters": ["temperature", "top_p"],
"status": "active",
"createdAt": "...",
"updatedAt": "..."
}
]
}
```
### Get a custom model [#get-a-custom-model]
`GET /v1/master/custom-models/{id}`
Returns a single custom model in the master key's organization.
### Create a custom model [#create-a-custom-model]
`POST /v1/master/custom-models`
```bash
curl -X POST https://internal.llmgateway.io/v1/master/custom-models \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"providerKeyId": "pk_...",
"modelName": "acme-large",
"displayName": "Acme Large",
"contextSize": 200000,
"maxOutput": 32000,
"inputPrice": "3.0e-6",
"outputPrice": "15.0e-6",
"tools": true
}'
```
Body parameters:
| Field | Type | Description |
| ------------------------ | ----------------------------------- | ---------------------------------------------------------- |
| `providerKeyId` | string | Must be a custom provider in the master key's organization |
| `modelName` | string | Model id sent upstream. Unique per provider |
| `displayName` | string (optional) | Human-readable label |
| `contextSize` | number (optional) | Context window in tokens |
| `maxOutput` | number (optional) | Max output tokens |
| `inputPrice` | string (optional) | USD per input token |
| `outputPrice` | string (optional) | USD per output token |
| `cachedInputPrice` | string (optional) | USD per cached input token |
| `cacheReadInputPrice` | string (optional) | USD per cache-read token |
| `cacheWriteInputPrice` | string (optional) | USD per cache-write token (5m TTL) |
| `cacheWriteInputPrice1h` | string (optional) | USD per cache-write token (1h TTL) |
| `requestPrice` | string (optional) | Flat USD charged per request |
| `webSearchPrice` | string (optional) | USD per web search |
| `imageInputPrice` | string (optional) | USD per image input token |
| `audioInputPrice` | string (optional) | USD per audio input token |
| `streaming` | `"true" \| "false" \| "only"` | Streaming support (`"only"` = streaming-only model) |
| `vision` | boolean (optional) | Accepts image input |
| `tools` | boolean (optional) | Supports tool calling |
| `reasoning` | boolean (optional) | Emits reasoning output |
| `jsonOutput` | boolean (optional) | Supports JSON / structured output |
| `audio` | boolean (optional) | Accepts audio input |
| `supportedParameters` | string\[] (optional) | Request parameters the upstream accepts |
| `status` | `"active" \| "inactive"` (optional) | Defaults to `"active"` |
Response (201): the created custom model.
### Update a custom model [#update-a-custom-model]
`PATCH /v1/master/custom-models/{id}`
Accepts the same fields as create (except `providerKeyId`), all optional — provide only the ones you want to change. Renaming to a `modelName` already used by another model on the same provider returns a `400`.
```bash
curl -X PATCH https://internal.llmgateway.io/v1/master/custom-models/cm_... \
-H "Authorization: Bearer $MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{ "contextSize": 400000, "outputPrice": "12.0e-6" }'
```
Response (200): the updated custom model.
### Delete a custom model [#delete-a-custom-model]
`DELETE /v1/master/custom-models/{id}`
Soft-deletes the model (sets `status` to `"deleted"`).
Response (200):
```json
{ "message": "Custom model deleted successfully" }
```
# Metadata
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/metadata
LLM Gateway supports sending additional metadata with your requests using custom headers. This allows you to include information like user sessions, application versions, tenant IDs, or other contextual data that can be useful for analytics and monitoring.
Later, you can filter by specific values to return, such as for a specific user or session. Additionally, in the future, you will be able to segment your analytics and monitoring based on this metadata. For example, you could show cost and latency breakdowns per user, application, country, feature, or any other dimension you want to track.
## Custom Headers [#custom-headers]
You can include custom headers with the `X-LLMGateway-` prefix to send metadata alongside your LLM requests:
```bash
curl -X POST https://api.llmgateway.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "X-LLMGateway-Country: US" \
-H "X-LLMGateway-User-ID: 9403f741-a524-4b18-b1b2-dbb71cdff2a4" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Hello, how are you?"
}
]
}'
```
## End-user safety identifiers [#end-user-safety-identifiers]
To correlate requests for an end user, send a `safety_identifier` in the request body. LLM Gateway records it separately as `params.safety_identifier`; it does not override the fixed organization identifier used with providers. See [Safety identifiers](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#safety-identifiers) for an example, endpoint-specific fields, and credits/BYOK forwarding rules.
## Best Practices [#best-practices]
### Header Naming [#header-naming]
* Use the `X-LLMGateway-` prefix for all custom metadata
* Use descriptive, consistent naming conventions
* Avoid special characters; use hyphens to separate words
### Data Privacy [#data-privacy]
* Be mindful of sensitive data in headers
* Consider hashing or anonymizing user identifiers
* Follow your organization's data privacy policies
### Performance [#performance]
* Keep header values reasonably short
* Avoid sending unnecessary metadata that won't be used for analytics
* Consider the impact on request size, especially for high-volume applications
## Example: Multi-tenant Application [#example-multi-tenant-application]
For a multi-tenant application, you might use metadata headers like this:
```bash
curl -X POST https://api.llmgateway.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "X-LLMGateway-Tenant-ID: acme-corp" \
-H "X-LLMGateway-User-ID: user-12345" \
-H "X-LLMGateway-App-Version: 2.1.4" \
-H "X-LLMGateway-Feature: chat-assistant" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Summarize this document..."
}
]
}'
```
This allows you to track usage and costs per tenant, user, application version, and feature, providing detailed insights into how your LLM integration is being used across your platform.
# Org Models Directory
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/models-directory
The **Models** page in the dashboard (`Organization → Models`) lists every model your organization can route to in a single directory: the full LLM Gateway catalogue plus the models defined for your own [custom providers](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers). It answers two questions for your whole team:
* **What can we call?** — every catalogue and custom model, searchable and filterable by capability, provider, price, and context size, exactly like the public [models page](https://llmgateway.io/models).
* **What are we allowed to call?** — when a [provider compliance policy](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance) is active, each provider mapping is marked eligible or blocked using the same fail-closed evaluation the gateway applies at request time.
## Who can see it [#who-can-see-it]
Every active organization member can browse the directory read-only — including project-scoped **developer** members, who see it as their only organization page. This is the recommended way for developers to discover available providers and models without being granted additional permissions. Management actions (custom-model catalog, attestations) remain restricted to organization owners and admins.
## Custom models in the directory [#custom-models-in-the-directory]
Custom models appear alongside catalogue models, addressed as `{customProvider}/{modelName}` — the exact model string to send to the gateway:
```bash
curl -X POST "https://api.llmgateway.io/v1/chat/completions" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "internal-vllm/llama-4-maverick",
"messages": [{ "role": "user", "content": "Hello!" }]
}'
```
Their pricing, context and output limits, and capability flags come from the [custom model catalog](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers#custom-model-catalog). A **Source** filter switches between catalogue models, custom models, or both.
## Compliance eligibility [#compliance-eligibility]
With an enabled compliance policy (Enterprise), the directory evaluates every provider mapping against the policy — certifications, data-policy requirements, country restrictions, and provider/model allow and deny lists:
* Blocked mappings render greyed out with a ban icon; its tooltip lists the exact failing requirements (for example "No SOC 2 Type 2 report" or "Not on the allowed-providers list").
* Custom providers are evaluated against their [compliance attestation](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#custom-providers); without one on file they are blocked while a policy is active.
* An **Eligible only** filter narrows the directory to models the gateway will actually route to.
* A blocked model can be watched, so the organization hears when a compliant provider starts serving it — see [compliance alerts](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#compliance-alerts).
The directory mirrors gateway enforcement — the same predicates decide both
the markers on this page and the 403 responses at request time. If a model is
marked blocked here, requests for it will be rejected while the policy is
active.
## Discover models with an API key [#discover-models-with-an-api-key]
Call `GET /v1/models` with your API key to list models available under your
organization's compliance policy, inherited team and member IAM rules, and the
key's own IAM rules. Blocked provider mappings are omitted; models with no
remaining mappings are omitted too. Pricing and capabilities reflect the
remaining mappings. Accessible custom models use `{customProvider}/{modelName}` IDs.
```bash
curl "https://api.llmgateway.io/v1/models" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY"
```
The endpoint also accepts the `x-api-key` header. Without either authentication
header, it returns the public catalogue. Invalid, inactive, or expired credentials
return `401`.
Set `?include_restricted=true` to return the full public catalogue even with an
authenticated API key. This skips organization, team, member, key, project, and
plan filtering for discovery. Private custom models are omitted. Other query
filters still apply, and inference requests still enforce all access restrictions.
The default is `false`, which keeps authenticated results filtered.
Use `?mapped=true` for provider-prefixed entries. Existing query filters, including
`no_training`, apply alongside access restrictions. Discovery reflects model
permissions and project configuration; it does not check remaining credits,
usage budgets, or current provider health.
Deactivated mappings are omitted unless you set `?include_deactivated=true`.
Each provider mapping's `pricing` carries the full rate card: token, cache, audio
and image rates, `image_output_tokens_by_resolution`, per-second and per-image
prices, context-length `tiers` (the prompt size selects the tier, and the open-ended
top tier has `up_to_tokens: null`), and `peak` time-of-day rates. Mappings also list
`regions` with their own pricing and limits, and `service_tiers` with their price
multipliers. `discount` is the active discount as a fraction of the listed,
pre-discount prices; with an API key it includes your organization's own discounts.
## Provider deployments and pricing [#provider-deployments-and-pricing]
Capabilities and prices belong to individual provider mappings, not just model
families. Use the [models page](https://llmgateway.io/models) to check a deployment's
context window, reasoning controls, vision and tool support before pinning it.
Different upstream deployments of the same family can have different limits and
rates, including peak and off-peak token pricing.
The gateway omits unsupported sampling controls and clamps temperature to the
configured deployment ceiling. For deployments that reject empty text blocks,
it removes those blocks while preserving the rest of the message.
For bring-your-own-key access, a provider's model list does not guarantee that your
key has that model enabled. Activate the required service in the provider's
console and use the region associated with your key. The gateway catalogue lists
only the regions configured for each mapping.
## Related [#related]
* [Knowledge base → Models](https://docs.llmgateway.ai-stage.zibl.ir/learn/models) — a walkthrough of the page itself.
* [Custom Providers](https://docs.llmgateway.ai-stage.zibl.ir/features/custom-providers) — bring your own OpenAI-compatible endpoints and define their model catalog.
* [Compliance](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance) — configure the provider compliance policy.
# Moderations
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/moderations
LLMGateway supports the OpenAI-compatible `/v1/moderations` endpoint for text
and multimodal safety classification.
Use it when you want to:
* Screen user prompts before they reach a model
* Review generated output before displaying it
* Apply the same moderation API shape you already use with OpenAI clients
For the full request and response schema, see the
[API reference](https://docs.llmgateway.ai-stage.zibl.ir/v1_moderations).
## Endpoint [#endpoint]
`POST https://api.llmgateway.io/v1/moderations`
Authenticate with your LLMGateway API key:
```bash
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY"
```
## Supported Inputs [#supported-inputs]
The `input` field accepts:
* A single string
* An array of strings
* An array of multimodal content items with `text` and `image_url`
The default model is `omni-moderation-latest`.
## Pricing [#pricing]
Since **Friday, August 7, 2026**, moderation requests are billed at a
flat **$0.00001 per request**, independent of the input size, the number of
inputs, or the moderation model you pick. Only successful requests are billed —
failed and retried attempts cost nothing.
Because the endpoint is paid, it also requires a credit balance: moderation
requests from an organization with no credits are rejected with `402`.
When your project runs in `api-keys` mode and the request is served with your
own OpenAI key, no credits are deducted and no balance is required.
## curl [#curl]
### Single text input [#single-text-input]
```bash
curl -X POST "https://api.llmgateway.io/v1/moderations" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input": "I want to harm someone."
}'
```
### Multiple text inputs [#multiple-text-inputs]
```bash
curl -X POST "https://api.llmgateway.io/v1/moderations" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "omni-moderation-latest",
"input": [
"This is a harmless sentence.",
"I want to attack somebody."
]
}'
```
### Multimodal input [#multimodal-input]
```bash
curl -X POST "https://api.llmgateway.io/v1/moderations" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input": [
{
"type": "text",
"text": "Check this image for violent content."
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.png"
}
}
]
}'
```
## OpenAI SDK [#openai-sdk]
```ts
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.llmgateway.io/v1",
apiKey: process.env.LLM_GATEWAY_API_KEY,
});
const response = await client.moderations.create({
model: "omni-moderation-latest",
input: "I want to harm someone.",
});
console.log(response.results[0]?.flagged);
```
## Response Shape [#response-shape]
The response follows the standard OpenAI moderation format:
```json
{
"id": "modr-123",
"model": "omni-moderation-latest",
"results": [
{
"flagged": true,
"categories": {
"violence": true,
"self_harm": false
},
"category_scores": {
"violence": 0.98,
"self_harm": 0.01
}
}
],
"usage": {
"cost": 0.00001,
"cost_details": { "request_cost": 0.00001, "total_cost": 0.00001 }
}
}
```
`usage` is an LLM Gateway addition: what the request was billed in USD (see [Cost Breakdown](https://docs.llmgateway.ai-stage.zibl.ir/features/cost-breakdown)).
## When To Use This Instead Of Chat Content Filtering [#when-to-use-this-instead-of-chat-content-filtering]
Use `/v1/moderations` when you want an explicit moderation decision in your own
application flow.
If you want moderation to happen automatically as part of model requests, use
LLMGateway content filtering on `/v1/chat/completions` instead.
# Notifications
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/notifications
Open the **Notifications** bell in the dashboard header, then select **Notification settings**. Choose **In-app**, **Email**, both, or neither for each alert type. Most alerts start disabled; the compliance alerts start enabled for everyone in the organization's alert audience, and organization limit alerts start enabled for owners and admins. Email delivery always requires a verified email address. Your preferences apply across projects you can access.
| Alert | When it appears |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| API key budgets | A regular API key reaches your selected percentage of its lifetime or recurring budget. The default threshold is 80%. |
| Model retirements | A model mapping you used in the last 30 days is scheduled for deprecation or deactivation within 30 days. The alert links to the model catalogue so you can choose a newer model. |
| Model price changes | A provider changes a model's base token, image input, request, or web search price. Choose which models count, as described below. |
| Provider issues | A model you recently used has a high error rate on its provider. Choose the threshold and windows, as described below. |
| Compliance: models available | A model your organization watches becomes routable under its [compliance policy](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#compliance-alerts). |
| Compliance: downgrades | A provider, or a watched model, stops meeting your organization's compliance policy. |
| Organization limits | A seat or API key limit blocks directory sync (SCIM), an SSO sign-in, an invite, or a new API key. Sent to owners and admins. |
Organization limit alerts are sent at most once per day for each kind of limit; rejected directory sync pushes are also listed in the [audit log](https://docs.llmgateway.ai-stage.zibl.ir/features/audit-logs). Budget alerts repeat for each new recurring period, or when you change the limit or alert threshold. Unlimited keys do not trigger budget warnings. Each scheduled model retirement is announced once; ongoing provider issues produce at most one alert per day per affected model mapping (model, provider and region) and project, or per accessible key for developers.
### Provider issue settings [#provider-issue-settings]
A provider issue alert fires when a model's error rate on a provider reaches your threshold. Choose:
* **Error rate**: 10%, 20%, 30% (default) or 50% of requests.
* **Error window**: the last 5 minutes, 15 minutes (default) or 1 hour. Shorter windows alert sooner.
* **Usage window**: only models you used in the last 1 hour, 4 hours (default) or 24 hours are covered.
The rate counts gateway traffic on credits, across all customers, that returned a provider or gateway error. Client errors (4xx caused by the request), response-cache hits, and failed attempts the gateway retried on another provider are not counted. A model needs at least 20 requests in the window before it is judged. Checks run every minute.
Retirement dates apply per provider mapping. A mapping can be retired when its provider redirects requests to a newer model. Check the [model catalogue](https://llmgateway.io/models) and update your requested model before the mapping's deactivation date.
Model price change alerts start disabled. Under the alert, choose which models it covers:
* **Models I used in the last 30 days (over $1)** (default): models your accessible API keys spent more than $1 on in the last 30 days. Developers count only their own keys.
* **All models**: every price change in the catalogue.
* **Only models I choose**: the models you select, saved with **Save models**.
A change on any provider of a covered model sends one alert per model, listing the old and new price for each provider and region; when more than three covered models change at once, you get one alert that groups the models under each provider's old and new price. New models and providers do not send an alert, and long-context tier, peak-hour, image output, audio, and video prices and discounts are not tracked. Price change alerts describe public catalogue prices, so they do not depend on project access.
Provider alerts require at least 20 non-cached, non-client-error requests and an upstream error rate of at least 20% in the latest hourly statistics window. Stale statistics do not trigger alerts. Checks run about once a minute; these warnings are not a guarantee that every outage or budget crossing will be caught before a request fails.
[Compliance alerts](https://docs.llmgateway.ai-stage.zibl.ir/features/compliance#compliance-alerts) follow organization role instead of project access: you receive them while your role is inside the audience the organization selected, and leaving that audience hides them from the inbox and stops pending email. They are also the only alerts that can be posted to a shared Slack channel, once per organization rather than per recipient.
Every other notification follows your existing project permissions. Developers receive alerts only for their own keys in assigned projects. Removed project access also removes those alerts from the inbox and prevents pending email delivery.
The inbox shows your 50 most recent in-app alerts. Open an alert to follow its action, or select **Mark all as read** to clear the unread indicator. Turn off a channel in notification settings to stop future delivery through it.
Alerts of the same type that are ready to email together, such as several retirements found right after you turn an alert on, arrive as one email listing each of them. Every alert email links to unsubscribe from that alert type and to your notification settings.
# OCR
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/ocr
LLMGateway exposes a dedicated `/v1/ocr` endpoint for optical character
recognition. It extracts text, tables, and layout from PDFs and images and
returns them as clean markdown, one entry per page.
Use it when you want to:
* Turn scanned PDFs or photos into machine-readable markdown
* Pull structured text out of receipts, invoices, forms, or screenshots
* Feed document contents into a downstream model or RAG pipeline
For the full request and response schema, see the
[API reference](https://docs.llmgateway.ai-stage.zibl.ir/v1_ocr).
## Endpoint [#endpoint]
`POST https://api.llmgateway.io/v1/ocr`
Authenticate with your LLMGateway API key:
```bash
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY"
```
The current model is `mistral-ocr-latest`, billed at **$4 per 1,000 pages**
processed.
## Document Input [#document-input]
The `document` field accepts either a document URL (PDF) or an image:
* `{ "type": "document_url", "document_url": "https://…/file.pdf" }`
* `{ "type": "image_url", "image_url": "https://…/image.png" }`
Both `document_url` and `image_url` accept a public URL or a base64 data URL
(`data:application/pdf;base64,…` / `data:image/png;base64,…`). The `image_url`
field may also be passed as an object: `{ "url": "…" }`.
### Scoping pages [#scoping-pages]
By default the entire document is processed and every page is billed. Use the
optional `pages` field to restrict (and cap the cost of) a request:
* A list of zero-based indices: `"pages": [0, 1, 2]`
* A range string: `"pages": "0-4"`
## curl [#curl]
### Document URL [#document-url]
```bash
curl -X POST "https://api.llmgateway.io/v1/ocr" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "mistral-ocr-latest",
"document": {
"type": "document_url",
"document_url": "https://arxiv.org/pdf/2201.04234"
}
}'
```
### Only specific pages [#only-specific-pages]
```bash
curl -X POST "https://api.llmgateway.io/v1/ocr" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "mistral-ocr-latest",
"document": {
"type": "document_url",
"document_url": "https://arxiv.org/pdf/2201.04234"
},
"pages": "0-4"
}'
```
### Image input [#image-input]
```bash
curl -X POST "https://api.llmgateway.io/v1/ocr" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "mistral-ocr-latest",
"document": {
"type": "image_url",
"image_url": "https://example.com/receipt.png"
}
}'
```
### Inline (base64) document [#inline-base64-document]
```bash
BASE64_PDF=$(base64 -i invoice.pdf)
curl -X POST "https://api.llmgateway.io/v1/ocr" \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"mistral-ocr-latest\",
\"document\": {
\"type\": \"document_url\",
\"document_url\": \"data:application/pdf;base64,${BASE64_PDF}\"
}
}"
```
## Response Shape [#response-shape]
```json
{
"pages": [
{
"index": 0,
"markdown": "# Document title\n\nExtracted body text…",
"images": [],
"dimensions": { "dpi": 200, "height": 2200, "width": 1700 }
}
],
"model": "mistral-ocr-latest",
"document_annotation": null,
"usage_info": {
"pages_processed": 1,
"doc_size_bytes": 125344
},
"usage": {
"pages_processed": 1,
"cost": 0.004,
"cost_details": {
"page_cost": 0.004,
"request_cost": 0,
"total_cost": 0.004
}
}
}
```
Each entry in `pages` carries the markdown for one page. `usage_info.pages_processed`
reflects exactly how many pages were billed for the request, and `usage.cost` what
they were billed in USD (see [Cost Breakdown](https://docs.llmgateway.ai-stage.zibl.ir/features/cost-breakdown)).
## Billing [#billing]
OCR is billed per page processed, not per token. A request that processes 12
pages bills `12 × $0.004 = $0.048`. Scoping a request with `pages` reduces both
the work and the cost.
## OCR Models Use This Endpoint, Not Chat [#ocr-models-use-this-endpoint-not-chat]
OCR models are not chat models and cannot be called through
`/v1/chat/completions` — doing so returns a `400` pointing you here. Send OCR
requests to `/v1/ocr`.
# Organization skills
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/organization-skills
Organization skills are reusable instructions and supporting files that enterprise teams share through the CLI. Owners and admins publish skills in the dashboard; developers can discover and download them using a project API key from the same organization.
## Publish a skill [#publish-a-skill]
1. Open **Organization → Skills** in the dashboard.
2. Choose **Import SKILL.md** for a single skill, **Import folder** for a skill with references, scripts, or assets, or **New custom skill** to write instructions.
3. Review the content and save. New skills are enabled immediately.
A skill folder must contain `SKILL.md` at its root. Its YAML header needs a unique lowercase, hyphenated `name` of up to 64 characters and a `description` of up to 1,024 characters. Write the instructions below the header:
```md
---
name: code-review
description: Review code changes against the team's standards.
---
# Code review
- Check correctness and error handling.
- Explain the impact of each finding.
- Suggest tests for important edge cases.
```
Bundles support up to 100 additional files and 1 MB of total content. `SKILL.md` supports up to 200,000 characters within that limit. Supporting paths must be relative to the skill folder; duplicate paths and parent-directory traversal are rejected. Existing YAML fields, such as `license` or `allowed-tools`, are preserved.
## Manage access [#manage-access]
All active organization members can view skills. Owners and admins can edit, disable, or delete them. Keep a published skill's name unchanged; create a new skill to use a different name.
Disabling a skill removes it from CLI discovery and prevents new downloads. Deleting it also removes its stored content. These actions cannot remove copies already downloaded to a developer's machine. Publishing and management actions appear in the organization's audit log without recording the skill content.
## CLI API contract [#cli-api-contract]
These endpoints belong to the [platform API](https://internal.llmgateway.io/docs). Authenticate with `Authorization: Bearer `, using a regular project API key issued to an active member with access to that project.
| Method | Path | Response |
| ------ | ------------------- | ------------------------------------------------ |
| GET | `/v1/skills` | `{ skills: [...] }` with enabled skill summaries |
| GET | `/v1/skills/{name}` | `{ skill: { ...summary, content, files } }` |
A summary contains `id`, `name`, `description`, `enabled`, `createdAt`, and `updatedAt`. Timestamps use ISO 8601. `content` is the complete `SKILL.md`, including its YAML header. Each supporting file contains a relative `path`, `content`, and optional `encoding` (`utf-8` by default, or `base64` for binary files).
Clients should discover skills at the start of a session, download selected skills by name, and write each bundle into its own directory. Revalidate authorization before reusing organization content and remove cached availability when access is denied. Treat supporting scripts as code to review before running.
The server derives the organization from the API key. Expired or revoked keys return `401`; removed project access or missing enterprise access returns `403`; missing or disabled skills return `404`. Responses use `Cache-Control: private, no-store`.
Dashboard management uses session authentication at `/orgs/{organizationId}/skills`: `GET` lists summaries and `POST` creates a bundle. At `/orgs/{organizationId}/skills/{id}`, `GET` reads a bundle, `PUT` replaces `{ content, files }`, `PATCH` sets `{ enabled }`, and `DELETE` removes it. Duplicate names return `409`.
# Project access
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/project-access
Use **Project admin** to let someone manage specific projects without giving them organization administration. Owners and admins assign the role and its project grants from [Team → Members](https://docs.llmgateway.ai-stage.zibl.ir/learn/team).
| Role | Scope | Permissions |
| ------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Owner | All organization projects | Organization administration, billing settings, membership, and project management |
| Admin | All organization projects | Organization and project management; cannot change billing settings or modify owners |
| Project admin | Assigned projects | Project settings, routing, dynamic routes, guardrails, Payments SDK settings and platform keys, all project API keys, and project-wide usage |
| Developer | Assigned projects | Own API keys and own usage; cannot change project settings |
Project admin and Developer assignments require Enterprise access and at least one project grant. Existing feature and preview requirements still apply. Project admins cannot create or archive projects, change organization settings or provider keys, manage membership, or access organization billing controls. Archiving projects and deleting organizations require an Owner.
## Assign project access [#assign-project-access]
In **Team → Members**, choose **Add Member** or an existing member's **Manage access** action. Select **Project admin**, choose the allowed projects, and save. Invitations carry the selected grants through acceptance. Removing a grant removes access to that project's settings, keys, and usage; the gateway also checks the creator's project access when a key is used, subject to normal cache propagation.
For an authenticated management API session, use `project_admin` with `projectIds` when adding a member:
```json
{
"email": "member@example.com",
"role": "project_admin",
"projectIds": ["your-project-id"]
}
```
Send this body to `POST /team/{organizationId}/members`. Use `PATCH /team/{organizationId}/members/{memberId}` with `role` and the complete `projectIds` list to replace an existing member's access.
## Budgets, teams, and SSO [#budgets-teams-and-sso]
Personal member budgets and IAM rules still apply to the member's keys. Organization teams and default developer budgets apply only to Developers; promoting a Developer clears their team assignment.
[SSO group mappings](https://docs.llmgateway.ai-stage.zibl.ir/features/sso) can assign `project_admin`. Role priority is Owner, Admin, Project admin, then Developer. Project-scoped roles still require explicit project grants: a role mapping does not grant every project.
Project guardrails can display the organization policy they inherit, while changes to that policy remain restricted to organization administrators.
# Prompt Management
URL: https://docs.llmgateway.ai-stage.zibl.ir/features/prompt-management
Prompt management keeps your prompts in LLM Gateway instead of your code. Each prompt has immutable versions, and named labels such as `production` and `staging` point at them. Change a prompt, move a label, and every request that follows that label picks it up without a redeploy.
Manage prompts on the [**Prompts**](https://docs.llmgateway.ai-stage.zibl.ir/learn/prompts) page of a project, or through the API.
## Templates and variables [#templates-and-variables]
A version holds a list of messages, an optional default model, and optional parameters (`temperature`, `top_p`, `max_tokens`, `frequency_penalty`, `presence_penalty`, `reasoning_effort` from `none` to `max`). Write `{{name}}` anywhere in a message to declare a variable. Names start with a letter or underscore and may contain letters, digits, `_`, `.`, and `-`.
## Labels and versions [#labels-and-versions]
Saving a change always creates a new version; existing versions never change. Labels are named pointers at a version:
* `production` is what requests use when they pick nothing else. Creating a prompt points it at version 1.
* Any other label (`staging`, `canary`, a customer name) lets you run one version somewhere while `production` serves another.
* `latest` always means the newest version. It is implicit and cannot be assigned.
Deploying is moving `production`. Roll back by pointing it at an earlier version. `production` can be moved but not removed, so a request that names no label always resolves. Label names start with a letter and may contain letters, digits, `_`, `.`, and `-`.
## Calling a prompt [#calling-a-prompt]
Reference a prompt through `model`, or send a `prompt` object:
```bash
curl https://api.llmgateway.io/v1/chat/completions \
-H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "@prompt/support-reply",
"messages": [{ "role": "user", "content": "How do I rotate my key?" }]
}'
```
`model: "@prompt/"` works with any OpenAI-compatible client, including tools that only let you set a base URL and a model. Add `@