Dashboard

Cookbook Recipe

Access Control

Hand out a limited key

Give a contractor, a demo, a CI job or a single client project its own key with a spending limit, a list of models and an expiry, and revoke it the moment you need to. Your account key never leaves you.

POSThttps://api.devupai.com/v1/chat/completions

What you'll build

You create a Scoped JWT in the dashboard for one holder, with its own spending limit, allowed models and expiry. The holder runs a short program with that token in place of an API key: it sends one chat request, lists the catalog, and turns each error a limited key can get into a clear next step. When the work ends, you revoke the token and the next request with it is refused.

Before you start

  • A DEVUP AI account, signed in to the dashboard (with your second factor, if you turned it on). Tokens are created on the Scoped Tokens tab of the API Keys page, which the Keys item in the sidebar opens. Step 1 walks through it.
  • For the holder: Python 3.10+ with pip install openai, or Node.js 22.12 or later with npm install devupai.
  • The token, stored on the holder's side in the environment variable DEVUP_SCOPED_TOKEN.

The complete program

This is what the holder runs. The Node.js program uses the official devupai SDK; the Python program uses the openai package with the DEVUP AI base URL. Both pass the token as the API key. Automatic retries are off here; see the error-handling recipe for a full retry policy.

"""Run with a limited DEVUP AI key: send one chat request, list the catalog, explain errors."""

import os
import sys

import openai
from openai import OpenAI

BASE_URL = "https://api.devupai.com/v1"
MODEL = "deepseek-ai/DeepSeek-V4-Pro"
ERRORS_PAGE = "https://docs.devupai.com/docs/errors"

# What the holder of a limited key does for each error code.
ACTIONS = {
    "budget_exhausted": "This key's spending limit is used up. Ask the key owner for a new token.",
    "model_not_allowed": "This key does not allow that model. Use a model this key allows.",
    "token_expired": "This key has expired. Ask the key owner for a new token.",
    "token_revoked": "This key was revoked. Ask the key owner for a new token.",
    "invalid_api_key": "This key is not accepted. Copy the whole token again, or ask the key owner for a new token.",
    "scoped_token_not_allowed": "This key can't read account endpoints. Ask the key owner for account details.",
    "insufficient_balance": "The key owner's account balance is used up. Tell the key owner.",
    "service_unavailable": "This request was not confirmed. Contact support with the request ID below before repeating it.",
}


def describe_scoped_error(status, code):
    """Return what to do about an error the API returned to a limited key."""
    if code in ACTIONS:
        return ACTIONS[code]
    return f"HTTP {status} ({code or 'no code'}). See {ERRORS_PAGE}"


def list_model_ids(client):
    """Return the IDs of the models in the catalog."""
    return [model.id for model in client.models.list()]


def ask(client, prompt):
    """Send one chat request and return the reply text."""
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "user", "content": prompt}],
    )
    return completion.choices[0].message.content


def main():
    token = os.environ.get("DEVUP_SCOPED_TOKEN")
    if not token:
        print("Set DEVUP_SCOPED_TOKEN to the token you were given.", file=sys.stderr)
        sys.exit(1)
    # Automatic retries are off: the program never repeats a request on its own.
    client = OpenAI(api_key=token, base_url=BASE_URL, max_retries=0)
    try:
        # Send one chat request, then list the catalog.
        print(ask(client, "Say hello in one short sentence."))
        for model_id in list_model_ids(client):
            print(model_id)
    except openai.APIStatusError as e:
        print(describe_scoped_error(e.status_code, e.code), file=sys.stderr)
        print(f"x-request-id: {e.response.headers.get('x-request-id')}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

Run it with python program.py or node program.mjs. It prints the reply, then the model IDs. Without DEVUP_SCOPED_TOKEN it says so and exits with status 1 before any request. On an error it prints what to do and the x-request-id of the response, and exits with status 1.

How it works

1Create the key in the dashboard

Scoped JWTs are created only from your signed-in dashboard. Create one per holder:

  1. In the dashboard, open Keys (the API Keys page).
  2. Open the Scoped Tokens tab and select Generate Scoped Token.
  3. In Token Name (optional), enter the holder, such as the contractor, the demo, the CI job or the client project.
  4. In Allowed Models, choose only the models the holder needs. The Allow all models (*) checkbox grants every model.
  5. In Expiration, pick the shortest window that covers the work.
  6. In Spending Limit (DZD), enter the most this holder may spend, then select Generate Token.
  7. Copy the token from Token Generated. It is shown once: the dashboard keeps only a masked preview.

The allowed values for each field are on Creating and using Scoped JWTs. A token's models, limit and expiry are fixed when it is created: to change them, create a new token and revoke the old one. Give the token to the holder through a secret store or a password manager, never in a chat message or an email.

2What the holder runs

The token goes where an API key goes: in Authorization: Bearer <token>, against the same base URL, https://api.devupai.com/v1. The client sends that header for you, so no request or response shape changes. The program passes the token explicitly and stops before creating the client when the variable is missing. The devupai client reads no environment variable, so this check is what keeps a request from going out without a valid key, and no other key from the environment is ever sent.

def main():
    token = os.environ.get("DEVUP_SCOPED_TOKEN")
    if not token:
        print("Set DEVUP_SCOPED_TOKEN to the token you were given.", file=sys.stderr)
        sys.exit(1)
    # Automatic retries are off: the program never repeats a request on its own.
    client = OpenAI(api_key=token, base_url=BASE_URL, max_retries=0)

The program sends one chat request with deepseek-ai/DeepSeek-V4-Pro, then lists the catalog with GET /v1/models. A chat request for a model outside the token's allowed models returns 403 model_not_allowed before it runs. The token is accepted on GET /v1/models, and the list is the full catalog, not only the models this token allows.

        # Send one chat request, then list the catalog.
        print(ask(client, "Say hello in one short sentence."))
        for model_id in list_model_ids(client):
            print(model_id)

Every error the API returns carries a stable error.code, which the client exposes as e.code (Python) and err.code (Node.js). The program matches on that code, not on the message, and prints the action from describe_scoped_error / describeScopedError, a pure function of the status and the code. A 402 arrives as the base DevupAPIError (Node.js) or APIStatusError (Python), which this handler covers too. Network errors and timeouts (APIConnectionError, status 0 in Node.js) carry no error code, so the program lets them surface as they are.

    except openai.APIStatusError as e:
        print(describe_scoped_error(e.status_code, e.code), file=sys.stderr)
        print(f"x-request-id: {e.response.headers.get('x-request-id')}", file=sys.stderr)
        sys.exit(1)

Once the token's limit is used up, requests return 402 budget_exhausted before they run. How spend counts against the limit is on Budget semantics and remaining allowance. Usage is also paid from your account balance, so a holder can see 402 insufficient_balance when that balance is used up, even with limit left on the token.

3What the holder can't do

The token runs models and reads the catalog. It does not open your account:

  • GET /v1/me and GET /v1/me/avatar return 403 scoped_token_not_allowed.
  • GET /v1/user/balance takes account keys (sk-devup-...) only. With a Scoped JWT it returns 401 unauthorized.
  • Tokens are created and revoked only in your signed-in dashboard, never with a token.
JSON
{
  "error": {
    "message": "This endpoint accepts account API keys (sk-devup-...) only, not scoped tokens.",
    "type": "devup_error",
    "code": "scoped_token_not_allowed"
  }
}

If the holder needs to know what is left, read it for them on the Scoped Tokens tab: each token's row shows Spend / Budget and Expires.

4Revoke the key

On the Scoped Tokens tab, select Revoke on the token's row and confirm with Revoke. The token is checked on every request, so the next request with it returns 401 token_revoked:

JSON
{
  "error": {
    "message": "This scoped token has been revoked.",
    "type": "devup_error",
    "code": "token_revoked"
  }
}

A revoked token stays in the list. Once you delete it from the list (Delete Permanently), requests with it return 401 invalid_api_key instead. Revoking one token leaves your account key and every other token as they are. A token that reaches its expiry stops the same way, with 401 token_expired; see Token expiration and revocation.

In production

  • One token per holder. Name it after the holder, so its spend is visible on its own row and revoking it cuts off that holder only.
  • Short expiry, then re-issue. Pick the shortest expiry that fits, track each token's Expires date, and issue a new token before it, so the holder never sees token_expired mid-job.
  • Keep tokens secret. Store them in a secret store, such as your CI's secret variables or a password manager. Never put a token in a browser or a mobile app, and never commit it to a public repository.
  • Revoke on offboarding. When a contract, a demo or a project ends, revoke its token the same day.
  • Retries. The program never repeats a request on its own. Before repeating a request that returned 503 service_unavailable, contact support with its request ID. For a full retry policy, see Production error handling.

Errors this recipe handles

Every error uses the body {"error":{"message","type":"devup_error","code"}}. The full list is on Common Scoped JWT errors.

HTTPCodeWhenWhat to do
402budget_exhaustedThe token's spending limit is used up. Requests return this before they run.Ask the key owner for a new token.
403model_not_allowedThe request names a model that is not in the token's allowed models.Use a model this key allows.
401token_expiredThe token's expiry has passed.Ask the key owner for a new token.
401token_revokedThe key owner revoked the token.Ask the key owner for a new token if access is still intended.
401invalid_api_keyThe token was not copied in full, or it no longer exists in the dashboard.Copy the whole token again, or ask the key owner for a new token.
403scoped_token_not_allowedThe token was sent to GET /v1/me or GET /v1/me/avatar, which take account keys only.Ask the key owner for the account details you need.
402insufficient_balanceThe balance of the account that owns the token is used up.Tell the key owner, who tops up the account.
503service_unavailableThe request could not be confirmed.Contact support with the request ID before repeating the request.

Next steps