Skip to main content

TTLLM Gateway

LLM gateway exposing an Anthropic-compatible API (POST /v1/messages), routing requests to any supported provider (Bedrock via direct boto3 Converse API, OpenAI-compatible via LangChain). Tracks tokens, costs, and maintains audit trails. Supports user management with per-user model access control.

Supported Features

Feature Bedrock OpenAI-compatible
Text messages Yes Yes
Multi-turn conversations Yes Yes
System prompts Yes Yes
Streaming (SSE) Yes Yes
Tool use (client-defined) Yes Yes
Image inputs (base64) Yes Yes (including inside tool results)
Document inputs (PDF) Yes No — 400 invalid_request_error¹
Extended thinking Yes Emulated (returned as plain text)¹
Token tracking & cost Yes Yes
Cache token reporting Yes No
Server-side tools 501 (not proxied) 501 (not proxied)
safeguards (Claude Code auto-mode server-side classifier) Yes² Dropped (client-side classifier used)

¹ Requests are translated through a provider-agnostic internal representation (see Architecture Note below); when the OpenAI-compatible provider can't faithfully represent a piece of content it either emulates it with a non-misleading substitute (extended thinking becomes plain text; an image inside a tool result is passed through as multimodal content — this used to crash) or returns an explicit 400 rather than silently dropping it (document inputs, since the model would otherwise answer as if it had read an attachment it never saw). See docs/content-mapping.md for the full per-content-type policy.

² Forwarded through Converse. Results are rekeyed to Converse's tool-use ids by position, because Converse rewrites the ids. See "Safeguards" in docs/content-mapping.md.

Architecture Note

Requests cross a provider-agnostic internal representation (core/model.py) rather than being translated directly between wire formats: the Anthropic input adapter (core/adapters/anthropic.py) converts wire JSON to/from the internal representation once, and each provider translates the internal representation to/from its own wire format. Bedrock requests are handled via direct boto3 converse() / converse_stream() calls against that internal representation — no LangChain involved, which keeps latency low and enables native support for extended thinking, document inputs, and cache token reporting. OpenAI-compatible providers (Ollama, vLLM, etc.) translate the same internal representation to/from LangChain messages. Both providers stream through one shared Anthropic SSE encoder (core/adapters/anthropic_stream.py), so the wire protocol is implemented exactly once regardless of backend. See docs/content-mapping.md for the full mapping reference.

Quick Start

Prerequisites

  • Python 3.12+
  • PostgreSQL 16
  • Docker (optional)

Run with Docker Compose

docker-compose up

This starts PostgreSQL and the API on port 8000. Migrations run automatically on container start.

A default admin account is created by the migrations:

  • Email: admin@localhost
  • Password: value of TTLLM_ADMIN_PASSWORD (defaults to admin)

Set TTLLM_ADMIN_PASSWORD before running migrations to use a custom password. Log in via ttllm login and change the password or create a new admin user immediately.

Run from Docker Image

# From GitHub Container Registry
docker run -p 8000:8000 \
  -e TTLLM_DATABASE__URL="postgresql+asyncpg://user:pass@host:5432/ttllm" \
  ghcr.io/ponquersohn/ttllm-gateway:latest

Passing configuration

Option A - Mount a config file:

docker run -p 8000:8000 \
  -v /path/to/config.yaml:/app/config.yaml \
  -e TTLLM_CONFIG_FILE=/app/config.yaml \
  -e TTLLM_CONFIG_ENV=prod \
  ghcr.io/ponquersohn/ttllm-gateway:latest

Option B - Environment variables only:

docker run -p 8000:8000 \
  -e TTLLM_DATABASE__URL="postgresql+asyncpg://user:pass@host:5432/ttllm" \
  -e TTLLM_AUTH__JWT__SECRET_KEY="your-secret" \
  -e TTLLM_ENGINE__LISTEN_PORT=8000 \
  -e TTLLM_PROVIDER__DEFAULT_REGION="us-east-1" \
  ghcr.io/ponquersohn/ttllm-gateway:latest

The container listens on port 8000 by default (configurable via engine.listen_port). Map it to any host port with -p <host>:<container>.

Debugging failed containers

By default the container exits on error. Set TTLLM_EXIT_ON_ERROR=false to keep the container alive after a failure, so you can exec into it for debugging:

docker run -p 8000:8000 \
  -e TTLLM_EXIT_ON_ERROR=false \
  -e TTLLM_DATABASE__URL="postgresql+asyncpg://user:pass@host:5432/ttllm" \
  ghcr.io/ponquersohn/ttllm-gateway:latest

Install from PyPI

pip install ttllm-gateway

Run Locally

pip install -e .
alembic upgrade head
uvicorn ttllm.handlers.ecs_entrypoint:app --reload

Configuration

Settings are resolved in order: YAML config file -> environment variables -> defaults.

Environment Variable Description Default
TTLLM_CONFIG_FILE Path to YAML config file (none)
TTLLM_CONFIG_ENV Environment section to load dev
TTLLM_DATABASE__URL PostgreSQL connection string postgresql+asyncpg://ttllm:dev@localhost:5432/ttllm
TTLLM_ENGINE__LISTEN_PORT Server listen port 8000
TTLLM_ENGINE__BASE_URL External-facing URL (for OAuth callbacks) http://localhost:4000
TTLLM_ENGINE__CORS_ORIGINS Allowed CORS origins ["*"]
TTLLM_AUTH__JWT__SECRET_KEY JWT signing secret CHANGE-ME-IN-PRODUCTION
TTLLM_PROVIDER__DEFAULT_REGION AWS region for Bedrock us-east-1
TTLLM_SECRETS__ENCRYPTION_KEY Fernet key for encrypting secrets (none)

Nested env vars use __ as delimiter. YAML values support env://VAR,default and secret://arn resolution patterns. Local overrides via local.config.yaml (git-ignored).

Config file example

dev:
  database:
    url: "postgresql+asyncpg://ttllm:dev@localhost:5432/ttllm"
    pool_size: 5
  engine:
    base_url: "http://localhost:8000"
    listen_port: 8000
    cors_origins: ["*"]
    log_request_bodies: false
    rules_cache_ttl_seconds: 30          # how long each worker caches active rules before reloading
    quota_lock_timeout_ms: 5000          # wait for a quota bucket lock before answering 529
    quota_reservation_ttl_seconds: 900   # when an unfinished request stops counting against a quota
    quota_reservation_retention_seconds: 86400  # when an expired reservation is deleted
  auth:
    allowed_redirect_origins:
      - "https://myapp.example.com"
    jwt:
      secret_key: "dev-secret"
      algorithm: "HS256"
      access_token_ttl_minutes: 15
    identity_providers:
      entra:
        name: "Entra ID"
        type: "oidc"
        client_id: "..."
  provider:
    default_region: "us-east-1"
    allowed_base_urls:                          # regex patterns for custom base_url targets
      - "http://ollama\\..*:11434/v1"
    allow_private_targets: false                # set true to allow private/internal IPs
  secrets:
    encryption_key: "env://TTLLM_SECRETS_ENCRYPTION_KEY"

Rules Engine

The gateway includes a rules engine that evaluates incoming requests before model resolution. Rules are evaluated by weight (highest first); the first matching rule's action is applied.

Rules are managed via the admin API (/admin/rules) and CLI (ttllm rules). Each worker caches active rules in memory. The worker that serves a create/update/delete reloads immediately; other workers pick up the change within engine.rules_cache_ttl_seconds (default 30s), so a write may take up to that long to take effect across all workers.

📖 For the full reference — conditions, actions, message templating, and operational notes — see docs/rules-engine.md. For limits on requests, tokens, and spend, see Quotas.

Permissions

Rules management requires dedicated permissions:

  • rule.view — List and show rules
  • rule.create — Create new rules
  • rule.modify — Update existing rules
  • rule.delete — Delete rules

API

# List rules
GET /admin/rules

# Create a rule
POST /admin/rules

# Get/update/delete a specific rule
GET    /admin/rules/{rule_id}
PATCH  /admin/rules/{rule_id}
DELETE /admin/rules/{rule_id}

CLI

ttllm rules list
ttllm rules show <name>
ttllm rules create --name <name> --conditions '<json>' --action '<json>' --weight 50
ttllm rules create --name <name> --conditions '<json>' --apply-quota <quota>
ttllm rules update <name> --weight 100 --enabled true
ttllm rules delete <name>

Example: Create a rule via API

POST /admin/rules
{
  "name": "reroute-large-to-haiku",
  "weight": 50,
  "description": "Route large requests to a cheaper model",
  "conditions": {
    "logic": "and",
    "conditions": [
      {"type": "parameter", "field": "model", "operator": "exact", "value": "dynamic_model"},
      {"type": "function", "field": "count_tokens", "operator": "gt", "value": 50000}
    ]
  },
  "action": {"type": "reroute", "target": "claude-haiku"}
}

More examples:

// Block jailbreak attempts (weight: 100 = high priority)
{
  "name": "block-jailbreak",
  "weight": 100,
  "conditions": {
    "logic": "or",
    "conditions": [
      {"type": "content", "field": "messages", "operator": "regex", "value": "(?i)(ignore previous instructions|DAN mode)"}
    ]
  },
  "action": {"type": "block", "message": "Request rejected: content policy violation"}
}

// Mask SSN patterns in content
{
  "name": "mask-ssn",
  "weight": 80,
  "conditions": {
    "logic": "and",
    "conditions": [
      {"type": "content", "field": "messages", "operator": "regex", "value": "\\d{3}-\\d{2}-\\d{4}"}
    ]
  },
  "action": {"type": "rewrite", "pattern": "\\d{3}-\\d{2}-\\d{4}", "replacement": "[SSN-REDACTED]"}
}

// Attach a quota to everyone in a group
{
  "name": "apply-eng-budget",
  "conditions": {
    "logic": "and",
    "conditions": [
      {"type": "subject", "field": "group", "value": "engineering"}
    ]
  },
  "action": {"type": "apply_quota", "quota_ids": ["<quota id>"]}
}

Condition Types

Type Field Description
parameter model, max_tokens, temperature, top_p, top_k, stream, resolved_model Match on request parameters. model is the name the client sent; resolved_model is the model that will serve it — use resolved_model for block/reroute/quota rules, since any name a model's match_pattern accepts reaches the same model
header any header name Match on HTTP headers (case-insensitive)
content messages or system Match on message/system text, including text inside tool results, documents, search results and tool-call arguments
function count_tokens, message_length, keyword_count Match on computed values
subject user_id, user_email, token_id, group Match on the authenticated caller, which clients can't influence

Operators

exact, regex, contains, in, gt, lt, gte, lte

All conditions support negate: true to invert the match.

Actions

Action Fields Description
reroute target Change target model name before resolution
block message, status_code Reject the request. status_code defaults to 403
allow — Explicitly pass through (skip remaining rules)
rewrite pattern, replacement Regex replace in message and system content (every place a content condition matches, except signed thinking blocks)
apply_quota quota_ids Attach quotas. Not terminal: every matching rule applies, and no other rule can skip it

Condition Groups

Conditions can be composed with logic: and or logic: or, and groups can be nested for complex rules.

Quotas

Quotas limit requests, tokens, or spend per interval. They're defined separately and attached by rules with the apply_quota action. For example, to limit every user to $50 a day:

ttllm quotas create --name daily-spend --measure cost --limit 50 --window day
ttllm rules create --name apply-daily-spend \
  --conditions '{"logic":"and","conditions":[]}' \
  --apply-quota daily-spend
  • Windows: calendar (hour, day, week, month, in a timezone), or a session of any length that starts at the first request.
  • Dimensions: per user, model, token, or any combination; none means one shared budget.
  • Enforcement: usage is reserved before the provider call, so parallel requests can't get around a limit. soft (the default) can overshoot by about one request; strict never exceeds the limit.
  • When exceeded: block (a 429 with an exact Retry-After) or reroute to another model.
ttllm quotas list|show|create|update|delete
ttllm quotas buckets <name>     # current usage per bucket
ttllm quotas reset <name>       # discard all usage
ttllm me quotas                 # your own standing
ttllm quotas overrides issue --duration 4h --code-ttl 1d --reason "..."   # single-use quota override code
ttllm quotas overrides list|revoke

A user with the quota.override permission can issue a quota override code. Whoever enters it in the web UI's Quota tab (the issuer included) is exempt from every quota until the override expires. Each code works once, has a redeem deadline and an override duration, and needs a reason, which is audited. See Quota overrides.

Upgrading from the old rolling-window quota condition: those rules are disabled by migration 020 and their limits aren't enforced until recreated. See the upgrade notes.

📖 For the full reference, see docs/quotas.md.

Secrets Management

Provider credentials (AWS keys, API keys, etc.) can be stored encrypted in the database and referenced from model configs using secret://name. This avoids storing plaintext credentials in config_json.

Setup

  1. Generate an encryption key and add it to your config:
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

Add to config.yaml:

dev:
  secrets:
    encryption_key: "your-generated-key"

Or via environment variable: TTLLM_SECRETS__ENCRYPTION_KEY.

  1. Create secrets:
ttllm secrets create --name aws-bedrock-key        # prompts for value (hidden)
ttllm secrets create --name aws-bedrock-secret      # prompts for value (hidden)
  1. Reference secrets in model config:
ttllm models create \
  --name claude-sonnet \
  --provider bedrock \
  --provider-model-id anthropic.claude-3-sonnet-20240229-v1:0 \
  --config '{"aws_access_key_id":"secret://aws-bedrock-key","aws_secret_access_key":"secret://aws-bedrock-secret","region":"us-west-2"}'

At runtime, secret:// references are resolved transparently before the provider client is created. Secret values are never exposed through the API or CLI.

OpenAI-Compatible Providers (Ollama, vLLM, etc.)

Any service exposing an OpenAI-compatible /v1 endpoint (Ollama, vLLM, LiteLLM, etc.) works with the built-in openai provider — no dedicated provider needed.

Setup

  1. Whitelist the target URL and enable private-network access in config.yaml:
dev:
  provider:
    allowed_base_urls:
      - "http://ollama\\.mynetwork\\.internal:11434/v1"
    allow_private_targets: true   # required when the target is on a private network

allowed_base_urls entries are regex patterns matched with re.fullmatch. Metadata endpoints (169.254.169.254, etc.) are always blocked regardless of allow_private_targets.

  1. Register the model:
ttllm models create \
  --name llama3-local \
  --provider openai \
  --provider-model-id llama3 \
  --config '{"base_url":"http://ollama.mynetwork.internal:11434/v1","api_key":"unused"}'
  1. Assign the model to users/groups as usual:
ttllm models assign llama3-local --user alice

Requests to this model are routed through Ollama's OpenAI-compatible API and tracked the same as any other provider.

Model Name Matching

By default, a request's model field must exactly match the name of a registered model. For more flexible matching, you can attach a regex pattern to a model via --match-pattern:

ttllm models create \
  --name claude-haiku \
  --provider bedrock \
  --provider-model-id anthropic.claude-haiku-4-5-20241022-v1:0 \
  --match-pattern 'claude-haiku-4\.5.*'

Now any request with a model string starting with claude-haiku-4.5 (e.g. claude-haiku-4.5-20241022, claude-haiku-4.5-latest) will resolve to this model.

Rules:

  • Exact name match always takes priority over regex.
  • Patterns use Python re.fullmatch semantics — the entire model string must match.
  • Invalid regex patterns are rejected at creation time.
  • To clear a pattern: ttllm models update <name> --match-pattern ""

Display Name

--name is the routing key: it must be unique, and it's what clients put in a request's model field (and what's echoed back in the response). It is not meant to be a friendly label.

For a human-readable label shown in model listings, set --display-name separately:

ttllm models create \
  --name claude-sonnet \
  --display-name "TTLLM - Claude Sonnet" \
  --provider bedrock \
  --provider-model-id anthropic.claude-sonnet-4-20250514-v1:0

display_name is purely cosmetic — it's rendered by GET /anthropic/v1/models (model discovery), GET /me/models, and the ttllm models/ttllm me models CLI tables, and falls back to --name when unset. It has no effect on request routing, the rules engine, or quota scoping, all of which continue to match on name. Update it any time with ttllm models update <name> --display-name "..." (empty string clears it, falling back to --name again).

Model Pricing

Each model carries per-1K-token prices used to compute the cost recorded in audit logs:

ttllm models create \
  --name claude-sonnet \
  --provider bedrock \
  --provider-model-id anthropic.claude-sonnet-4-20250514-v1:0 \
  --input-cost 0.003 \
  --output-cost 0.015 \
  --cache-read-cost 0.0003 \
  --cache-write-cost 0.00375
  • --input-cost / --output-cost — price per 1K fresh input and output tokens.
  • --cache-read-cost / --cache-write-cost — price per 1K prompt-cache read and write tokens (Bedrock). Cache-read tokens are billed at this rate instead of the input rate, not in addition to it. When unset (null), cache tokens are billed at the model's input rate, so cached prompts can't slip past cost quotas for free. An explicit 0 is respected. Migration 022 converted existing 0 cache prices (the old default) to unset.

All four are also accepted by ttllm models update with the same flags. ttllm models update --reset-cache-costs unsets both cache prices again (API: send null for cache_read_cost_per_1k / cache_write_cost_per_1k).

To update individual keys within config_json without replacing the entire object, pass --merge-config:

ttllm models update claude-sonnet --config '{"region":"eu-west-1"}' --merge-config

This shallow-merges the provided keys into the existing config. Without --merge-config, --config replaces the entire config object.

The total cost of each request is computed by its provider (the cost shape is provider-specific — Bedrock bills input + output + cache read/write) and stored authoritatively on the audit row, alongside a provider_metadata JSONB blob holding the raw usage payload and the per-component cost breakdown. Usage aggregation (ttllm usage summary / costs) sums the stored totals rather than recomputing, so reported costs always match what was recorded — including cache and any future cost dimensions. ttllm usage summary reports an overall total_cost. Requests denied by a quota are left out of every usage figure and reported separately as quota_blocked_requests.

Bedrock Model Config

Bedrock models accept these keys in config_json (all optional):

  • region — AWS region; falls back to provider.default_region.
  • aws_profile — named profile, or aws_access_key_id / aws_secret_access_key / aws_session_token for explicit credentials (use secret:// references for the secret values).
  • endpoint_url — override the Bedrock runtime endpoint. Useful for VPC interface endpoints, LocalStack, or pointing tests at a fake Bedrock server. Omit to use the AWS default endpoint for the region.
ttllm models create \
  --name claude-sonnet \
  --provider bedrock \
  --provider-model-id anthropic.claude-sonnet-4-20250514-v1:0 \
  --config '{"region":"us-east-1","endpoint_url":"https://bedrock-runtime.us-east-1.amazonaws.com"}'

CLI

Admin operations via the ttllm CLI:

ttllm login [--url URL]              # Email + password login
ttllm login --idp <slug>             # SSO login (opens a local browser)
ttllm login --device                 # Device code login: approve from any browser (SSH/headless)
ttllm status                         # Show server version, status, and config checks
ttllm whoami                         # Show current user, groups, and permissions
ttllm me models                      # List models available to you
ttllm me tokens                      # List your active tokens
ttllm me tokens create               # Create a token for yourself
ttllm me tokens delete <id>          # Revoke one of your tokens
ttllm run claude [claude args...]    # Run Claude Code via the gateway with a temporary token
ttllm users list|show|create|update|delete
ttllm users deactivate|activate <user> # Block/unblock a user (all tokens rejected, login refused)
ttllm models list|show|create|update|delete|assign|unassign
ttllm groups list|show|create|update|delete
ttllm tokens list|show|create|delete
ttllm secrets list|show|create|update|delete
ttllm usage summary|costs [--user] [--email] [--model] [--since] [--until]
ttllm usage by-user [--limit] [--since] [--until]   # usage per user, highest cost first
ttllm reports generate [--user] [--since] [--until] [--format pdf|html] [-o file]  # preview
ttllm audit-logs [--user] [--model] [--request-id] [--limit]

Every command accepts --json for machine-readable output instead of formatted tables/text — including mutations (create/update/delete/assign/...). Commands that create or update a resource emit the resource object; delete/revoke commands (which return HTTP 204) emit a small status object such as {"status": "deleted", "id": "..."}.

ttllm usage --since/--until accepts ISO datetimes and relative UTC offsets such as -24h, -7d, -30m, or -1w.

ttllm usage summary and costs can scope to a single user by --user <id> or --email <email> (the email is resolved server-side; an unknown email returns 404). ttllm usage by-user lists usage and cost grouped per user, ordered by total cost descending; pass --limit N for the top N spenders.

Running Claude Code through the gateway

ttllm run claude                          # interactive Claude Code session via the gateway
ttllm run claude -p "explain this repo"   # any claude arguments are passed through
ttllm run claude --ttl-days 2 --small-model <gateway-model> --keep-env CLAUDE_CONFIG_DIR -- --help

ttllm run claude uses your login session to mint a temporary llm.invoke token (POST /me/tokens, label ttllm run claude@<host>, default lifetime 1 day). It then launches claude as a child process and revokes the token (DELETE /me/tokens/{id}) when Claude exits. If the revoke fails, it prints the token id so you can run ttllm me tokens delete <id>. If the CLI is killed outright, the TTL is the fallback.

The child process gets a scrubbed environment:

  • Every ANTHROPIC_* and CLAUDE* variable, plus AWS_BEARER_TOKEN_BEDROCK, is removed so a stray API key or CLAUDE_CODE_USE_BEDROCK can't bypass the gateway. To keep a specific one, pass --keep-env VAR (repeatable).
  • ANTHROPIC_BASE_URL is set to <gateway>/anthropic.
  • ANTHROPIC_AUTH_TOKEN is set to the temporary token. It is sent as Authorization: Bearer; the gateway doesn't accept x-api-key, so ANTHROPIC_API_KEY isn't used.

Claude Code's model names must match gateway model names (see Model Name Matching). Use claude's own --model <name> to pick the main model. --small-model <name> sets ANTHROPIC_DEFAULT_HAIKU_MODEL for Claude Code's background calls. The ttllm run claude options (--ttl-days, --small-model, --keep-env, --claude-bin) must come before the first positional claude argument. Put -- before claude flags that would otherwise be read by ttllm, such as --help.

Self-Service Endpoints

Any authenticated user (including gateway-only users) can access the /me endpoints to discover their available models and manage their own tokens. The /me/tokens endpoints require a login-session JWT (password, SSO or device login): a gateway API token is rejected, so a leaked key can't mint new or broader credentials. Likewise, when POST /admin/tokens is called with an API token rather than a login session, the new token's permissions must be a subset of the caller's token:

Endpoint Description
GET /me Current user info, groups, and permissions
GET /me/models Models assigned to you (direct + group)
GET /me/tokens Your active tokens
POST /me/tokens Create a token scoped to your permissions
DELETE /me/tokens/{id} Revoke one of your tokens
GET /me/quotas Your standing against the quotas that apply to you
GET /me/quota-overrides Your active quota overrides
POST /me/quota-overrides/lookup Preview a quota override code (login session)
POST /me/quota-overrides/redeem Redeem a quota override code (login session)

Status Checks

ttllm status (and GET /admin/status) runs health checks against the current configuration and reports their results:

Check Condition Status
encryption_key Valid Fernet key configured ok
encryption_key Empty or invalid error
jwt_secret Custom value ok
jwt_secret Still using CHANGE-ME-IN-PRODUCTION warning
database SELECT 1 succeeds ok
database Connection fails error

The overall status is ok when all checks pass, or degraded when any check returns warning or error.

Releasing

Releases must be cut from reviewed code: the released commit has to be on main or a release/* branch. Both are protected (a reviewed PR is required to land code), and the release workflow verifies this before publishing — a release whose commit is not contained in one of those branches fails the publish job. The version is derived automatically from git tags (via hatch-vcs), so no source file needs editing.

make release         # Patch bump (v0.0.1 -> v0.0.2)
make release-minor   # Minor bump (v0.1.0 -> v0.2.0)
make release-major   # Major bump (v1.0.0 -> v2.0.0)

After running make release*, follow the printed instructions to push the tag and create the GitHub release. Publishing a GitHub release triggers the CI workflow to:

  1. Publish the Python package to PyPI (only if the release commit is on main or a release/* branch)
  2. Build and push the Docker image to ghcr.io/ponquersohn/ttllm-gateway

Self-Service Web UI

A browser-based UI is available at /ui for self-service tasks without needing the CLI or raw API calls.

Features

  • Login with email/password or SSO (configured identity providers are detected automatically)
  • View models assigned to your account
  • Manage tokens — create new API tokens and revoke existing ones
  • Usage — your requests, tokens, and costs (costs rounded to cents)
  • Quota — your current quota buckets (used / in flight / limit, reset time), an override banner while one is active, and a form to apply a quota override code. Users with quota.override also get a form to issue codes

Access

Navigate to http://localhost:8000/ui (or your deployed base URL + /ui). The UI uses only /me/ endpoints, except the quota override issue form, which calls POST /admin/quota-overrides and is shown only to users holding quota.override.

Authentication state is stored in sessionStorage, so it is scoped to the browser tab and cleared when the tab is closed.

Device login approval

ttllm login --device (RFC 8628 device code flow) prints a code and a link to <base_url>/ui/?device=1&user_code=XXXX-XXXX. The user signs in to the UI as usual (password or SSO), checks the requesting client, IP, and user agent, and approves or denies. The CLI polls and receives the same management tokens a normal login issues.

Endpoints:

  • POST /auth/device/code (public): {client_name?} returns device_code, user_code, verification_uri, verification_uri_complete, expires_in (600), and interval (5)
  • POST /auth/device/token (public): {device_code} returns tokens, or a 400 with error type authorization_pending, slow_down, access_denied, or expired_token
  • GET /auth/device/lookup?user_code= and POST /auth/device/approve {user_code, approve}: require a login-session JWT; gateway API tokens are rejected

Device and user codes are stored only as SHA-256 hashes in device_authorizations, expire after 10 minutes, and can be used once. Verification links are built from engine.base_url, so set it to the public gateway URL.

Public API

The endpoint GET /auth/identity-providers returns the list of configured identity providers (slug, name, type) without requiring authentication. This is used by the UI to render SSO buttons.

User Guide

For end-user documentation covering login, token creation, API usage, SDK integration, and Claude Code setup, see docs/user-guide.md.

Development

pip install -e ".[dev]"
pytest                       # unit tests (integration and migration tests are excluded by default)

Migration tests

tests/migrations/ tests Alembic migrations themselves against a real, disposable Postgres (spun up per test run via testcontainers, not docker-compose) — things unit tests can't reach because they mock the database entirely: does a migration's data backfill actually produce the right shape (JSONB round-tripping through the real asyncpg driver, not a sync one that might hide a serialization bug), do ON DELETE CASCADEs actually fire, is upgrade → downgrade → upgrade reversible, and — the single highest-value generic check — does the live schema after upgrade head actually match the SQLAlchemy models (Base.metadata), catching drift between a hand-edited ORM model and its migration.

pytest -m migrations

Needs a local Docker daemon (no docker-compose stack — testcontainers talks to Docker directly). Runs in its own CI job (.github/workflows/integration.yml), never alongside the rest of the suite: Alembic's Config calls logging.config.fileConfig() internally, which reconfigures Python's global logging and would otherwise corrupt other tests' caplog expectations later in the same process.

Integration tests

End-to-end tests run the real gateway + PostgreSQL + a fake Bedrock server (which speaks the actual boto3 converse / converse_stream wire protocol, including AWS event-stream framing) via docker-compose, then exercise the full flow: create user → create model → assign → mint token → POST /v1/messages (streaming and non-streaming).

docker compose -f docker-compose.integration.yml up -d --build
pytest tests/integration -m integration     # hits http://localhost:8000
docker compose -f docker-compose.integration.yml down -v

The fake Bedrock is reached by the gateway at its compose-internal URL (http://fake-bedrock:9099), configured per-model via config_json.endpoint_url (see below). The fake echoes the last user message back, but validates every request the way real Bedrock does (tests/integration/fake_bedrock/validation.py): against botocore's bedrock-runtime service model, plus semantic rules observed on real Bedrock (document names, text document sources needing citations, toolUse/toolResult pairing, ...). A request real Bedrock would reject gets the same 400 ValidationException. Those rules are also unit-tested offline in tests/test_fake_bedrock_validation.py, which checks that requests the gateway builds pass them. If host port 8000 is busy, set TTLLM_HOST_PORT and point the tests at it with TTLLM_TEST_BASE_URL. These tests also run automatically in CI (.github/workflows/integration.yml).

Metadata

Release files for ttllm-gateway 0.3.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ttllm-gateway 0.3.3
File Size Uploaded Provenance Actions
ttllm_gateway-0.3.3.tar.gz 300.5 kB With provenance Details for ttllm_gateway-0.3.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ttllm-gateway 0.3.3
File Interpreter ABI Platform Actions
ttllm_gateway-0.3.3-py3-none-any.whl Python 3 none any Details for ttllm_gateway-0.3.3-py3-none-any.whl

Total release size: 503.2 kB

Release files / ttllm_gateway-0.3.3.tar.gz

Download URL ttllm_gateway-0.3.3.tar.gz
Size 300.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ea0091e9c8ea66ed34bf17e67bc57823e056a8c6bf6f91ec0daaef1eb5dc55b9
BLAKE2b-256 checksum
How to use checksums
7c694dc057fc26e8e20f8d9e6ea251065dfb6e40c1fc890b6bc69603b978d36c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / ttllm_gateway-0.3.3-py3-none-any.whl

Download URL ttllm_gateway-0.3.3-py3-none-any.whl
Size 202.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
21dc35486e8f8993ae2652cfc017eaf5cc3676b273de6b69e6e311a0386eec14
BLAKE2b-256 checksum
How to use checksums
0b9be2f33bcf660a708c3edfc8cd7aaa2fcc0a6336e1be439dcc8e7272225e17
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for ttllm-gateway 0.3.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ttllm_gateway-0.3.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.3 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page