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

> ## Agent Instructions
> The Venice API is OpenAI-compatible: use any OpenAI SDK with the base URL `https://api.venice.ai/api/v1` and a Venice API key, or pay per request from a USDC wallet through x402 with no account.
> Read model IDs from `GET /models` or `GET /models/traits` at runtime instead of hardcoding them from memory or from these pages. Models are added and retired often.
> Every model's price is in https://docs.venice.ai/pricing.md. Quote video and audio jobs with `POST /video/quote` or `POST /audio/quote` before you queue them.
> Search these docs from an MCP client at https://docs.venice.ai/mcp. The full agent guide is https://docs.venice.ai/agents.md.

# Generating an API Key

> Create a Venice API key, store it securely, verify it, and troubleshoot 402 spend limit errors when an account balance is available but the key is capped.

Venice API requests are authenticated with Bearer API keys. This guide shows how to create a key from the Venice dashboard, store it safely, and verify that it works.

> [!NOTE]
>
> If you are building an autonomous agent that needs to mint its own key with a wallet, use the [Autonomous Agent API Key Creation](https://docs.venice.ai/guides/integrations/generating-api-key-agent.md) guide instead.

## Before you start

* Sign in to your Venice account.
* Make sure the account has a spendable balance before calling paid endpoints. You can create a key before funding the account, but model requests will not succeed until the account can consume DIEM, bundled credits, or USD.

**1. Open API settings**

Visit [https://venice.ai/settings/api](https://venice.ai/settings/api?utm_source=venice-api-documentation). You can also open this page from the Venice app by selecting **API** in your settings.

The API settings dashboard shows your balances, API tier, usage, and existing API keys.

**2. Start a new key**

Select **Generate New API Key**, then configure the key:

* **Description:** Use a short name that identifies the app, environment, or integration that will use this key.
* **API Key Type:** Use **Inference Only** for normal model requests. Use **Admin** only when the key must manage API keys programmatically.
* **Expires at:** Optionally set an expiration date. If you leave this blank, the key does not expire automatically.
* **Epoch Consumption Limits:** Optionally cap how much DIEM or USD this key can spend during a 24-hour epoch. If you leave this blank, the key can use the account's available balance subject to your account limits.

**3. Generate and copy the key**

Click **Generate**. Venice will show the full API key one time.

> [!WARNING]
>
> Copy the key immediately and store it in a secure location. After you close the dialog, Venice only shows identifying metadata such as the key description and last characters. If you lose the secret value, delete the key and create a new one.

Paste the key exactly as it was issued. Use the dialog's copy button rather than selecting the text by hand, so you do not clip the first or last character or pick up a trailing newline. When a tool asks for the key in a form field, enter the key on its own: no `Bearer` prefix, no surrounding quotes, and no leading or trailing spaces. Because the dashboard shows only the last few characters once the dialog closes, never try to rebuild a lost key by retyping that masked value.

Add the key to your local environment or secret manager:

```bash theme={"system"}
export VENICE_API_KEY=your-api-key-here
```

**4. Verify the key**

Make a low-risk request to confirm that authentication is working. [Get API Key Rate Limits and Balances](https://docs.venice.ai/api-reference/endpoint/api_keys/rate_limits.md) costs nothing and accepts either key type. Use it rather than `GET /models`, which returns the model catalog with or without a key and therefore succeeds even when your key is wrong:

```bash theme={"system"}
curl --request GET \
  --url https://api.venice.ai/api/v1/api_keys/rate_limits \
  --header "Authorization: Bearer $VENICE_API_KEY"
```

A successful response returns your API tier, balances, and rate limits, and `data.accessPermitted` reports whether the key may consume the inference endpoints.

A `401` with `AUTHENTICATION_FAILED` means the key itself was rejected. Print the stored value and compare it against the last characters shown in the dashboard: the usual causes are a partial copy, a `Bearer` prefix or quotes captured into the value itself, or a stray space or newline on either end. Also confirm the header is `Bearer`, one space, then the key itself, for example `Authorization: Bearer $VENICE_API_KEY` in a shell.

> [!WARNING]
>
> Disabling USD spending during API key creation in the Venice app sets your USD spend limit to zero for the given API key. API calls may fail with an insufficient balance error when your available DIEM or bundled credits cannot cover the request, even if your account has a USD balance.

## Key format

New keys start with a type prefix followed by 42 URL-safe characters:

| Prefix | Key type |
| - | - |
| `VENICE_INFERENCE_KEY_` | Inference Only |
| `VENICE_ADMIN_KEY_` | Admin |

Older keys keep working as issued: some use hyphens in the prefix (`VENICE-INFERENCE-KEY-`, `VENICE-ADMIN-KEY-`), and the oldest have no prefix.

Use the key exactly as it was issued. The API checks the whole string, so a key that a tool has lowercased, re-punctuated, stripped of its prefix or given a different prefix fails with `401` and `Authentication failed`. Some community pages say Venice keys start with `vapi_`. They don't, and adding `vapi_` to a key breaks it.

The prefix identifies the key type. An Admin key also works on model endpoints, because it is the broader type. An Inference Only key on an admin endpoint, such as listing or creating keys or reading the balance, fails with `401` and `Admin API key required`. `GET /api_keys/rate_limits` accepts either type.

## Troubleshooting spend limit errors

Per-key spend limits are separate from your account balance. A key can be blocked from spending even when your account still has funded USD credits, DIEM, or bundled credits. If a request returns a 402 with one of these codes, the cause is the key's own limit rather than your account balance:

* `API_KEY_USD_SPEND_LIMIT_EXCEEDED` — the key's USD spend limit is set to zero (USD spending was disabled at creation) or the current epoch has reached its USD cap.
* `API_KEY_DIEM_SPEND_LIMIT_EXCEEDED` — the key has reached its DIEM cap for the current 24-hour epoch.

To confirm the current state of a key, call [Get API Key Rate Limits and Balances](https://docs.venice.ai/api-reference/endpoint/api_keys/rate_limits.md) and inspect `data.accessPermitted` and `data.balances`. To see the key's configured limits, call [Get API Key](https://docs.venice.ai/api-reference/endpoint/api_keys/get.md) with an Admin key and read `consumptionLimits`.

To resolve the error, either raise or remove the key's Epoch Consumption Limits at [venice.ai/settings/api](https://venice.ai/settings/api?utm_source=venice-api-documentation), or call [Update API Key](https://docs.venice.ai/api-reference/endpoint/api_keys/update.md) with a new `consumptionLimit` object. The request field is singular, even though API key responses return `consumptionLimits`. Account-wide balances (USD, DIEM, and bundled credits) are independent payment sources and are consumed automatically as available; you do not need to choose one at request time.

See [Error Codes](https://docs.venice.ai/api-reference/error-codes.md) for the full list of billing-related responses.

## Best practices

* Create separate keys for development, staging, and production.
* Prefer **Inference Only** keys for applications that only call model endpoints.
* Keep **Admin** keys rare, tightly scoped, and stored only in trusted server-side environments.
* Never commit API keys to source control or expose them in client-side code.
* Set expiration dates and consumption limits for keys used in temporary, shared, or higher-risk environments.
* Delete unused keys and rotate any key that may have been exposed.

## Calling from a browser

The API sends `access-control-allow-origin: *`, so a browser can call it directly — but the key then lives in your bundle and is public. Put a small proxy in front and keep the key server-side.

A proxy alone is not enough. `access-control-allow-origin` does not authenticate anything: `curl` and other servers ignore CORS entirely, and the Worker hostname is public. A proxy that only injects the key is an open tap on your balance. The caller has to prove itself too.

There are two levels, and it matters which one you are building:

* **A shared secret** gates spending. Every visitor holds the same value, so it stops anonymous use of your Worker but not a visitor forwarding it on. Good for a prototype.
* **A per-user token** identifies the caller. The browser authenticates to your own backend, which mints a short-lived token, and the Worker validates that. This is the production shape.

Both samples below keep the Venice key server-side. A third rule applies to both: **use an inference-only key**, because an admin key routed through a public proxy can `POST /api_keys` and read the new secret straight back out of the proxied response.

### Level 1: a shared secret

The Worker holds the Venice key and a secret, and rejects anything without the secret. Keep the secret off the browser: have your backend attach it when it calls the Worker, so the browser only ever talks to your backend.

```js index.js theme={"system"}
// Only the paths you need. Add deliberately: an inference key still reads
// balances through GET /api_keys/rate_limits.
const ALLOWED = new Set(['/chat/completions', '/image/generate']);

export default {
  async fetch(request, env) {
    if (request.method === 'OPTIONS') {
      return new Response(null, { headers: cors() });
    }
    if (!ALLOWED.has(new URL(request.url).pathname)) {
      return json(404, { error: 'Not found' });
    }
    if (request.method !== 'POST') {
      return json(405, { error: 'Method not allowed' });
    }
    if (request.headers.get('x-proxy-key') !== env.PROXY_SECRET) {
      return json(401, { error: 'Proxy secret required' });
    }
    return forward(request, env);
  },
};

async function forward(request, env) {
  const path = new URL(request.url).pathname;
  const upstream = await fetch(`${env.VENICE_BASE_URL}/api/v1${path}`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', authorization: `Bearer ${env.VENICE_API_KEY}` },
    body: await request.text(),
  });
  return new Response(upstream.body, {
    status: upstream.status,
    headers: { ...cors(), 'content-type': upstream.headers.get('content-type') ?? 'application/json' },
  });
}

const cors = () => ({
  'access-control-allow-origin': 'https://your-site.example',
  'access-control-allow-headers': 'content-type,x-proxy-key',
  'access-control-allow-methods': 'POST,OPTIONS',
});

const json = (status, body) =>
  new Response(JSON.stringify(body), { status, headers: { ...cors(), 'content-type': 'application/json' } });
```

```bash Deploy theme={"system"}
npx wrangler deploy index.js --name venice-proxy
npx wrangler secret put VENICE_API_KEY      # an inference-only key
npx wrangler secret put PROXY_SECRET        # any long random value
npx wrangler secret put VENICE_BASE_URL     # https://api.venice.ai
```

Call it from your backend, where the secret stays:

```js Server theme={"system"}
await fetch('https://venice-proxy.<account>.workers.dev/chat/completions', {
  method: 'POST',
  headers: { 'content-type': 'application/json', 'x-proxy-key': process.env.PROXY_SECRET },
  body: JSON.stringify({ model: 'venice-uncensored-1-2', messages: [{ role: 'user', content: 'Hi' }] }),
});
```

Paths are appended directly, so `/chat/completions` reaches `/api/v1/chat/completions` upstream. Keep `/v1` out of the base URL in any OpenAI client you point here.

A shared secret is still a shared credential: rate-limit the route with Cloudflare's rate limiting rules before it takes public traffic.

### Level 2: a per-user token

When the browser must call the Worker directly, put your own auth in front of it. Your backend verifies the session it already has, signs a short-lived token, and the Worker checks that token instead of a shared value. It reuses `ALLOWED`, `forward`, `cors` and `json` from the Level 1 Worker:

```js index.js theme={"system"}
export default {
  async fetch(request, env) {
    if (request.method === 'OPTIONS') {
      return new Response(null, { headers: cors() });
    }
    if (!ALLOWED.has(new URL(request.url).pathname) || request.method !== 'POST') {
      return json(404, { error: 'Not found' });
    }
    if (!(await validToken(request.headers.get('authorization')?.replace(/^Bearer /, ''), env))) {
      return json(401, { error: 'Token required' });
    }
    return forward(request, env);
  },
};

// Verify a token issued by your backend: its signature, expiry and subject.
// Any HMAC over `sub.exp` works; this is the shape, not a full implementation.
async function validToken(token, env) {
  if (!token) return false;
  // The payload itself contains a dot, so split on the last one only.
  const cut = token.lastIndexOf('.');
  if (cut < 1) return false;
  const payload = token.slice(0, cut);
  const key = await crypto.subtle.importKey(
    'raw', new TextEncoder().encode(env.PROXY_SIGNING_KEY),
    { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'],
  );
  const ok = await crypto.subtle.verify('HMAC', key, hexToBytes(token.slice(cut + 1)), new TextEncoder().encode(payload));
  return ok && Number(payload.slice(payload.lastIndexOf('.') + 1)) > Date.now();
}

const hexToBytes = (hex) => new Uint8Array(hex.match(/../g).map((b) => parseInt(b, 16)));
```

Mint the token on the backend after your own session check, so the Worker never holds user state. That gives you per-user rate limits, revocation, and an attributable bill.

## Programmatic key management

For a walkthrough of creating capped keys, tracking their usage, changing their limits, and revoking them, see [Managing API Keys](https://docs.venice.ai/guides/getting-started/managing-api-keys.md).

Admin keys can manage API keys through the API reference endpoints:

> [card] [Create API Key](https://docs.venice.ai/api-reference/endpoint/api_keys/create.md)
>
> Create a new dashboard-style API key from an existing admin key.

> [card] [List API Keys](https://docs.venice.ai/api-reference/endpoint/api_keys/list.md)
>
> View active keys and their metadata.

> [card] [Update API Key](https://docs.venice.ai/api-reference/endpoint/api_keys/update.md)
>
> Update a key description, expiration date, or consumption limits.

> [card] [Delete API Key](https://docs.venice.ai/api-reference/endpoint/api_keys/delete.md)
>
> Revoke a key that is no longer needed.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.