# Sypnia AI documentation > Sypnia AI is the layer between your app and the AI models. One key and one API reach many models, from OpenRouter and from AWS, and you choose the right one for each task. Every call is paid with credits, shown under the use case that made it, kept inside the limits you set, and sent to Telemetry as part of the case’s trace. Your keys never reach a browser. Sypnia comes two ways, and every page says which one it is about: - **Sypnia AI gateway** (open source, with your own openrouter or aws account): Ingest, storage, aggregation, problem grouping, sessions, replay data and uptime checks. You read it through: The HTTP API, the MCP server, the CLI and the Console: one built-in page with the problems list and the session replay viewer. - **Sypnia Cloud** (our provider accounts, paid with credits): The same engine, run by us. You read it through: The full app: replay player, performance, uptime, daily summary, search and teams. Every page is also plain Markdown: add `.md` to its address (`https://ai.docs.sypnia.com/start/open-source-and-cloud.md`). All pages in one file: https://ai.docs.sypnia.com/llms-full.txt ## Start here What Sypnia AI is, how it works, what is open source and what is Sypnia Cloud, and the quickstarts. - [Start here: overview](https://ai.docs.sypnia.com/start.md): Section index for Sypnia AI: the models layer of the Sypnia suite. One OpenAI-compatible API (https://ai.api.sypnia.com/v1) over OpenRouter and Amazon Bedrock; tasks and routes (task → model + fallbacks); usage in credits by product, project, case, key and end user; limits and budgets; zero-retention providers only; bodies not stored by default; every call a span in the case's Telemetry trace; secret keys server-only, short-lived browser tokens from the end user's Data session. Open-source gateway (AGPL-3.0, Rust) self-hosted with your own keys; @sypnia/ai SDK (MIT). [Engine, Cloud] - [What Sypnia AI is](https://ai.docs.sypnia.com/start/what-it-is.md): Sypnia AI = a gateway to AI models used by every Sypnia product and customer project. Concepts: model, token, provider, task, route, embedding. Does: one key and one OpenAI-compatible API for many models (OpenRouter, Amazon Bedrock); model choice per task with fallbacks; usage paid in credits and shown by product, project, case, key and end user; limits and budgets; zero-retention providers only; content safety and redaction options; every call a span in Telemetry; keys never in browsers. Not: a model, a chatbot product, a place that trains on your data. [Engine, Cloud] - [How it works](https://ai.docs.sypnia.com/start/how-it-works.md): Call path: app → POST https://ai.api.sypnia.com/v1/chat/completions (model: "task:" or a catalog id; headers Sypnia-Case, Sypnia-End-User) → key check → route resolved (model, fallbacks, params, safety) → limits checked (project, key, case, end user, task) → estimate reserved from credits (max output tokens) → redaction/moderation → provider (OpenRouter or Bedrock), stream back → actual usage charged, reservation released → span exported to Telemetry (gen_ai.* attributes + sypnia.case, credits) → call record (metadata 90 days; bodies only if opted in). [Engine, Cloud] - [Open source and Sypnia Cloud](https://ai.docs.sypnia.com/start/open-source-and-cloud.md): Gateway (open source, AGPL-3.0, Rust): routes, limits, usage counted in your provider's currency, redaction, moderation hook, OpenTelemetry export, MCP; providers = your OpenRouter key, your AWS account (Bedrock), any OpenAI-compatible endpoint; no console. Cloud: Sypnia's provider accounts (zero-retention only), or your own key; credits; console ai.app.sypnia.com and App; organization limits; Telemetry wiring automatic. Same API, SDK and routes (the [ai] table of sypnia.toml) both ways. @sypnia/ai MIT. [Engine, Cloud] - [Quickstart: Sypnia Cloud](https://ai.docs.sypnia.com/start/quickstart-cloud.md): AI Cloud quickstart: npx @sypnia/app login (shared Sypnia login, device flow); npx @sypnia/ai link --project la-espiga; write [ai.tasks.write] in sypnia.toml (model default, instructions, params) and npx @sypnia/ai routes apply; npx @sypnia/ai try write "…" --case publish-bread-of-the-day; npx @sypnia/ai keys create la-espiga-server --scope call → SYPNIA_SECRET_KEY on the server; createAI({apiKey}).chat({task, case, messages}); npx @sypnia/ai usage --by case. Same in App: project → AI. [Cloud] - [Quickstart: self-host](https://ai.docs.sypnia.com/start/quickstart-self-host.md): Self-host quickstart: compose.yaml with ghcr.io/sespinosav/sypnia-ai + postgres:16; env SYPNIA_GATEWAY_DATABASE_URL, SYPNIA_GATEWAY_ROOT_TOKEN, SYPNIA_GATEWAY_OPENROUTER_KEY, SYPNIA_GATEWAY_AUTO_MIGRATE=true; port 8095; ai routes apply --url http://localhost:8095 with an explicit model id (no default model when self-hosted); keys create; OpenAI-compatible call with curl. [Engine] - [How Sypnia uses it](https://ai.docs.sypnia.com/start/how-sypnia-uses-it.md): Dogfooding: Telemetry (the pilot, built on Sypnia end to end) calls Sypnia AI under its own project for problem analysis (task summarize, the agent's sentence per problem, structured output), the daily summary (task write), weekly suggestions; each call is a span inside the trace of the Telemetry case that made it (e.g. analyze-problem), visible in Telemetry itself; per-case budgets; bodies not stored. Self-hosted Telemetry engines can point SYPNIA_AI_PROVIDER=openai-compatible + SYPNIA_AI_BASE_URL at a self-hosted gateway. Agent, Cases' editor, Design's helpers, Learn and App's chat also call it, each under its own task routes, using the Sypnia session instead of a secret key. [Engine, Cloud] ## Models and routes How you choose a model for each task, where models come from, and what happens when one is down. - [Models and routes: overview](https://ai.docs.sypnia.com/models.md): Models section: tasks (built-in: chat, write, code, summarize, extract, classify, vision, embed; plus your own) and routes (task → model + fallbacks + instructions + params + safety + limits), kept in sypnia.toml ([ai.tasks.]) and the project; providers OpenRouter and Amazon Bedrock (Cloud: zero-retention only), any OpenAI-compatible endpoint when self-hosted; bring your own key; fallbacks and availability. [Engine, Cloud] - [Tasks and routes](https://ai.docs.sypnia.com/models/tasks-and-routes.md): Built-in tasks: chat, write, code, summarize, extract, classify, vision, embed (Cloud gives each a default model chosen and tested by Sypnia; self-hosted has no defaults). Own tasks: kebab-case names. Request: model "task:" or a catalog id (direct model use still metered, logged, limited; can be switched off per project with direct_models: false). sypnia.toml: [ai] {direct_models}, [ai.tasks.] {model (default | catalog id), fallbacks [ids], instructions (locked, placed first), params {temperature, max_output_tokens, reasoning}, output (JSON schema file), tools (allowed names), browser (bool), limits, safety {moderation, redact}, store {days}, cache {ttl}, pin}. ai routes diff|apply; applying needs owner or admin (a person); every change versioned with who/when; rollback. [Engine, Cloud] - [Providers](https://ai.docs.sypnia.com/models/providers.md): Providers: OpenRouter (many vendors behind one account; Cloud uses only endpoints with zero data retention and no training, enforced per request), Amazon Bedrock (models hosted inside AWS, us-east-1 in Cloud; data stays in AWS), OpenAI-compatible endpoints (self-hosted only: a local model server or another gateway). Catalog: ai models / GET /v1/models lists id, provider, tasks it fits, context size, inputs (text, image, pdf), tools, structured output, retention, price per million tokens in credits (Cloud) or provider currency (self-hosted). [Engine, Cloud] - [Your own key](https://ai.docs.sypnia.com/models/your-own-key.md): BYOK in Cloud: ai provider-keys add openrouter (key stored encrypted, write-only, never shown again) or bedrock (an IAM role in your AWS account that Sypnia AI assumes with an external id). Per project; routes can use byok:/. With your own key Sypnia charges nothing for the call (no credits, no fee); only your provider bills you; Sypnia AI still applies routes, limits, safety, traces. Zero-retention rule is yours to choose. Removing the key: calls on routes using it fail with provider_key_failed unless they have fallbacks. [Cloud] - [Fallbacks and availability](https://ai.docs.sypnia.com/models/fallbacks-and-availability.md): Fallbacks: tried in order on provider error (5xx), rate limit from provider, timeout before first token (default 20 s, route param first_token_timeout_s), refusal for capacity; not on 4xx caused by the request (bad schema, content blocked). Streaming: only before the first token is sent; after that an error event. Each attempt is a child span; only the attempt that answered is charged (a failed attempt that already produced tokens is charged its tokens). All fail → 503 provider_unavailable with the attempts. Retired models: the catalog marks retiring date; routes using it get a notice 30 days before; pinned routes move to the default for the task on retirement. [Engine, Cloud] ## Using it Chat and streaming, tools and structured answers, images and files, embeddings, the browser, and use cases. - [Using it: overview](https://ai.docs.sypnia.com/using.md): Using section: OpenAI-compatible chat completions with streaming (SSE), tool calls and JSON-schema structured output, image and PDF input, embeddings, browser tokens from the end user's Sypnia Data session, and the Sypnia-Case/Sypnia-End-User headers that tie each call to a use case and a person. [Engine, Cloud] - [Chat and streaming](https://ai.docs.sypnia.com/using/chat-and-streaming.md): POST /v1/chat/completions (OpenAI-compatible): model task: or catalog id, messages (system|user|assistant|tool), stream true → SSE chunks then a final chunk with usage and a sypnia object {route, model, attempts, credits, call_id}, then [DONE]. Sypnia headers: Sypnia-Case (case id), Sypnia-End-User (stable id of the app's person, not an e-mail), Sypnia-Budget (max credits for this call), Sypnia-Store (true|false within the route's allowance), traceparent. SDK: ai.chat({task, case, endUser, messages, stream}). OpenAI SDK: baseURL https://ai.api.sypnia.com/v1 + defaultHeaders. Response includes sypnia.call_id for support. [Engine, Cloud] - [Tools and structured answers](https://ai.docs.sypnia.com/using/tools-and-structured-output.md): Tools: OpenAI tools/tool_calls; the route's tools list allows names (others → 400 tool_not_allowed); max_tool_rounds per call in the SDK (default 5); tool results are data, not instructions. SDK ai.chat({tools: {get_product: {schema, run}}}) runs the loop on your server. Structured output: response_format {type: json_schema, json_schema {name, schema, strict: true}} or route output: schema file; ai.extract({task, schema (zod or JSON Schema)}) returns typed object; the gateway validates the answer, retries once with the error on another attempt of the same model, then 422 output_invalid. Only models with structured_output are used for such routes. [Engine, Cloud] - [Images and files](https://ai.docs.sypnia.com/using/images-and-files.md): Vision input: content parts image_url (https URL or data: URL) and file (PDF, base64 or a Sypnia Files signed URL). Formats PNG, JPEG, WebP, GIF (first frame), PDF. Limits: 10 images per request, 10 MB each, PDFs 20 MB and 100 pages, request body 25 MB. Images are priced as tokens by the model; the catalog's inputs field says which models read images/PDFs; routes for vision use the vision task. Files fetched from URLs: https only, 10 s, no private addresses. Nothing is kept unless store is on. [Engine, Cloud] - [Embeddings](https://ai.docs.sypnia.com/using/embeddings.md): POST /v1/embeddings (OpenAI-compatible): model task:embed (or own task), input string or array (up to 256 items, each within the model's context), dimensions where the model supports it, encoding_format float|base64. SDK ai.embed({task, case, input}). The route pins the embedding model: changing it means re-embedding (vectors of different models are not comparable); ai routes apply warns. Store vectors in Postgres with pgvector in Sypnia Data. Priced per input token. [Engine, Cloud] - [From the browser](https://ai.docs.sypnia.com/using/from-the-browser.md): Secret keys (syp_sk_…) are server-only; a request with an Origin header and a secret key is refused (403 secret_key_in_browser). Two ways for browsers: (1) through your server (recommended for anything sensitive); (2) a browser token syp_ait_… valid 10 minutes, for one project, one end user and only routes with browser: true: minted by exchanging the end user's Sypnia Data session (POST /v1/browser-tokens with the publishable key syp_pk_… + the Data access token) or by your server for apps without Data (POST /v1/browser-tokens with the secret key and end_user). Browser routes must set limits.end_user; instructions locked; tools only those the route allows and run in the browser are not offered (tools need your server). SDK @sypnia/ai/browser createAI({ project, getToken }) refreshes the token. CORS: allowed origins per project. [Engine, Cloud] - [Use cases and traces](https://ai.docs.sypnia.com/using/cases-and-traces.md): Case attribution: Sypnia-Case header or SDK case option; ids from the Cases map (cases//.case.yaml); unknown ids accepted and flagged (case_unknown in usage, scope error in Cases when the project is linked). Inside a traced request (@sypnia/telemetry), the SDK sends traceparent and reads the active case, so case can be omitted. Each call = span named chat or embeddings in that trace (gen_ai.* attributes); fallback attempts = child spans named attempt. A use case file can say it uses AI (ai: {tasks: [allergen-answer]}) and the Cases check compares with real usage. Usage views by case in App, the console and ai usage --by case. [Engine, Cloud] ## Usage and limits What each call spends, how to see it, the limits you set, budgets per case and per person, and caching. - [Usage and limits: overview](https://ai.docs.sypnia.com/usage.md): Usage section: every call priced by tokens read and written (and cached tokens), reserved before and charged after; seen by product, project, case, task, key, end user, model; limits per minute and caps in credits at project, key, task, case and end-user level; Sypnia-Budget per call; response cache and provider prompt caching. [Engine, Cloud] - [Credits and usage](https://ai.docs.sypnia.com/usage/credits-and-usage.md): Price of a call = input tokens × model's input price + output tokens × output price (cached input tokens at the model's cached price) in credits (Cloud; prices in the catalog) or provider currency (self-hosted, from the price table). Before: reserve the maximum (input + max_output_tokens) from prepaid credits; 402 insufficient_credits if the balance can't cover it, after the 7 days of grace. After: charge the real tokens, release the rest. Usage views: by product, project, case, task, key, end user, model, day; in App (ledger entries per case), console, ai usage --by …, GET /v1/usage. Exports CSV. Self-hosted: same records, amounts in the provider's currency. [Engine, Cloud] - [Limits](https://ai.docs.sypnia.com/usage/limits.md): Limit scopes: project, key, task (route limits), case, end user. Kinds: requests_per_minute, tokens_per_minute, credits_per_day, credits_per_month (+ requests_per_day for end users). Errors: 429 rate_limited (per-minute, with retry-after), 402 budget_exceeded (a cap of yours, names the scope), 402 spending_limit_reached (organization/project/product limit set in App), 402 insufficient_credits. Notices at 80 % and 100 % of every cap. Set in sypnia.toml ([ai.limits] for project/keys/cases, limits inside each [ai.tasks.]), console, CLI ai limits set. Days and months in the organization's time zone. Cloud plan limits for requests/tokens per minute are published with the plans. [Engine, Cloud] - [Budgets per case and per person](https://ai.docs.sypnia.com/usage/budgets-per-case-and-user.md): Patterns: cap each case (limits.cases..credits_per_day) so one feature cannot starve others; cap each end user (route limits.end_user, required for browser routes) to stop abuse; cap a single call with Sypnia-Budget / SDK budget (refused before calling with 402 budget_exceeded if the estimate exceeds it; output cut at the budget with finish_reason budget); map errors to the case's failure (e.g. TooManyQuestions) in your app. Agents' tasks: Sypnia Agent passes its task budget as Sypnia-Budget. [Engine, Cloud] - [Caching](https://ai.docs.sypnia.com/usage/caching.md): Two caches. (1) Provider prompt caching: automatic where the model supports it; long stable prefixes (route instructions first, then tools, then messages) are read again at the model's cached price; usage shows cached_input_tokens. (2) Gateway response cache: off by default; route cache {ttl: 1 m–24 h}; key = route version + full request (messages, params, schema) + end user unless cache.shared: true; hit costs nothing and is marked sypnia.cache: hit and a span attribute; only for non-streaming or replayed streaming; never for tools that change things; stored encrypted for the ttl only (an exception to 'bodies not stored', documented); purge with ai cache purge --task. [Engine, Cloud] ## Safety What is kept and for how long, content checks, prompt injection, and what goes to Telemetry. - [Safety: overview](https://ai.docs.sypnia.com/safety.md): Safety section: zero-retention providers only (Cloud); bodies not stored by default (opt-in per route 1–30 days, encrypted); call metadata 90 days; redaction of e-mails, phones, cards and ids before sending; moderation of input/output; locked instructions, allowed tools and structured outputs against prompt injection; spans to Telemetry without bodies. [Engine, Cloud] - [Data and retention](https://ai.docs.sypnia.com/safety/data-and-retention.md): Kept: call record metadata (time, project, key id, route+version, model, attempts, tokens, credits, case, end-user id, latency, status, error code) for 90 days in Cloud (configurable when self-hosted, SYPNIA_GATEWAY_CALL_RETENTION_DAYS); usage totals as long as the organization exists (ledger). Not kept by default: messages, files, answers. Opt-in: route store {days 1–30} or Sypnia-Store header within it; encrypted with a per-project key in object storage, deleted at the end; readable in the console by owners/admins and via GET /v1/calls/{id}/body with an admin key; every read audited. Providers: zero-retention only (Cloud). Deleting a person: DELETE /v1/end-users/{id} removes their stored bodies and replaces the id in records with a hash. [Engine, Cloud] - [Content safety](https://ai.docs.sypnia.com/safety/content-safety.md): Redaction (route safety.redact: email, phone, card, national-id, address; custom regex patterns): replaced before sending with placeholders [email-1]…; restore: true puts originals back in the answer (not in streamed chunks until complete per placeholder). Moderation (safety.moderation off|input|both; categories violence, hate, sexual, self-harm, harassment, illegal): blocked → 422 content_blocked {stage, categories}; self-harm returns help text option; costs a small classification call counted in usage. POST /v1/moderations to check text on its own. Off by default; recommended for browser routes. [Engine, Cloud] - [Prompt injection](https://ai.docs.sypnia.com/safety/prompt-injection.md): Prompt injection = text inside the input (a customer message, a web page, a tool result) that tries to give the model new orders. No filter stops it reliably, so design for it: locked route instructions (callers cannot replace them; browser tokens only add user messages); tools allowlist per route; tools that change things require your server to confirm with the person (never act on the model's word alone); structured outputs with enums so the answer can only be one of a list; no secrets or other people's data in the context; untrusted content wrapped as data (SDK untrusted() helper adds delimiters and a note); least data in the context; tool results never trigger further tools without limits (max_tool_rounds). [Engine, Cloud] - [Logs in Telemetry](https://ai.docs.sypnia.com/safety/logs-and-telemetry.md): Spans exported via OTLP: Cloud → the project's Sypnia Telemetry automatically; self-hosted → SYPNIA_GATEWAY_OTLP_ENDPOINT (+ headers). Span name gen_ai. ; attributes gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cached_input_tokens, gen_ai.response.finish_reasons, sypnia.ai.task, sypnia.ai.route_version, sypnia.ai.credits, sypnia.ai.call_id, sypnia.ai.cache, sypnia.case, enduser.id (hashed), time to first token; child spans per attempt. Never message or answer content in spans. Errors become Telemetry problems (provider_unavailable bursts, output_invalid). [Engine, Cloud] ## SDK, CLI and MCP The @sypnia/ai package, the ai command and the MCP tools for agents. - [SDK, CLI and MCP: overview](https://ai.docs.sypnia.com/tools.md): Tools: @sypnia/ai (MIT; /server with secret key, /browser with browser tokens; chat, extract, embed, browserTokens, usage), the ai CLI (npx @sypnia/ai; login shared with npx @sypnia/app login), the MCP server https://mcp.ai.sypnia.com (reads, try_prompt within a budget, draft_routes; applying routes and changing limits need a person). Any OpenAI-compatible client works against /v1. [Engine, Cloud] - [SDK](https://ai.docs.sypnia.com/tools/sdk.md): @sypnia/ai (MIT, TypeScript, Node 20+, Bun, Deno, edge runtimes). @sypnia/ai/server createAI({apiKey, baseUrl?, project?, defaultCase?, timeoutMs (600000), retries (2 on network/429 with retry-after)}) → chat({task|model, case?, endUser?, messages, tools?, maxToolRounds (5), stream?, budget?, store?, params?}) → {text, message, toolCalls, usage{input_tokens, output_tokens, cached_input_tokens, credits}, model, callId, finishReason}; stream → async iterator + final(); extract({task, schema (zod or JSON Schema), input, case?}) → {data}; embed({task, input, dimensions?}) → {vectors, usage}; browserTokens.create({endUser, tasks, ttlSeconds ≤600}); usage({groupBy, since}); untrusted(text). @sypnia/ai/browser createAI({project, getToken, baseUrl?}) → chat, extract, embed (browser routes only). Errors: AIError {code, status, message, callId, retryAfter}. Reads the active Telemetry case and trace. [Engine, Cloud] - [CLI](https://ai.docs.sypnia.com/tools/cli.md): npx @sypnia/ai (command ai once installed). Sign-in shared with npx @sypnia/app login (device flow, ~/.config/sypnia); self-hosted: SYPNIA_AI_URL + SYPNIA_AI_TOKEN. Commands: link --project; models [--task]; tasks; routes pull|diff|apply|history|rollback --to; try [--case --file]; keys create --scope call|read|admin [--credits-per-day] | list | revoke; provider-keys add openrouter|bedrock | list | remove (Cloud); origins add|list|remove; limits show|set; usage --by case|task|key|end-user|model --since [--csv]; calls [--case --status] | call ; cache purge --task; end-users delete . Global --project, --json. Exit codes 0 ok, 1 error, 2 usage, 3 needs a person's approval. [Engine, Cloud] - [MCP for agents](https://ai.docs.sypnia.com/tools/mcp.md): MCP at https://mcp.ai.sypnia.com (self-hosted /mcp): OAuth (PKCE, DCR) or PAT; project tokens limit to one project. Tools: list_models(task?), list_tasks, get_routes, usage(group_by, since), search_calls(case?, status?, since?), get_call(id) (no bodies unless the token's person is owner/admin and store is on), try_prompt(task, input, case?) charged within the project MCP try budget (ai.mcp.try_credits_per_day in sypnia.toml), draft_routes(toml) → proposal with diff (stored as draft), estimate(task, input_tokens, output_tokens). Not tools: apply routes, change limits, create keys, provider keys — a person does those (403 person_required for agent tokens on the API). Every call audited. [Engine, Cloud] ## API reference The AI API: addresses, authentication, the Sypnia headers, errors and limits. - [API reference: overview](https://ai.docs.sypnia.com/api.md): AI API at https://ai.api.sypnia.com/v1 (self-hosted /v1). OpenAI-compatible: /chat/completions, /embeddings, /models, /moderations. Auth Authorization: Bearer: secret keys syp_sk_… (project key, or AI keys with scopes call|read|admin; refused with an Origin header), browser tokens syp_ait_… (10 min, browser routes only), Sypnia session/PAT/OAuth tokens (people and agents; agent tokens 403 person_required for routes apply, limits, keys, provider keys). Sypnia headers: Sypnia-Case, Sypnia-End-User, Sypnia-Budget, Sypnia-Store, traceparent. Error shape {error {code, message, type, param, call_id}} (OpenAI-compatible fields + code). Codes: 400 invalid_request/tool_not_allowed/input_not_supported/context_too_long, 401 unauthorized, 402 insufficient_credits/budget_exceeded/spending_limit_reached, 403 forbidden/person_required/secret_key_in_browser/task_not_allowed, 404 not_found/task_not_found/model_not_found, 409 conflict, 413 too_large, 422 content_blocked/output_invalid, 429 rate_limited/end_user_limit (retry-after), 502 provider_key_failed, 503 provider_unavailable. [Engine, Cloud] - [Endpoints](https://ai.docs.sypnia.com/api/endpoints.md): AI API endpoints: POST /chat/completions, POST /embeddings, POST /moderations, GET /models, GET /models/{id}; GET /tasks; GET /routes, PUT /routes (person), GET /routes/history, POST /routes/rollback; GET /usage?group_by=&since=&until=; GET /calls?case=&status=&since=&cursor=, GET /calls/{id}, GET /calls/{id}/body (admin, audited, only when stored); GET|PUT /limits; GET|POST /keys, DELETE /keys/{id}; POST /browser-tokens; GET|POST /provider-keys, DELETE /provider-keys/{id} (Cloud); GET|POST /origins, DELETE /origins/{id}; POST /cache/purge; DELETE /end-users/{id}; GET /health. OpenAPI at spec/openapi.yaml in the gateway repository. [Engine, Cloud] ## Architecture How Sypnia AI is built: the gateway's parts, where Rust runs, and how they connect. - [Architecture: overview](https://ai.docs.sypnia.com/architecture.md): AI architecture: one Rust binary, the gateway (axum, tokio, reqwest; streaming proxy): API (OpenAI-compatible + Sypnia endpoints), router (routes, fallbacks), limiter (token buckets with leases from Postgres) and meter (reservations, charges), safety (redaction, moderation), provider adapters (OpenRouter, Bedrock via aws-sdk, OpenAI-compatible), OTLP exporter, MCP server. Postgres for routes, keys, limits, call records, usage; object storage only for opted-in bodies and the response cache. Cloud adds the credits ledger (shared with the suite), the console (TypeScript, private) and Sypnia's provider accounts. @sypnia/ai TypeScript MIT. [Engine, Cloud] - [Request paths](https://ai.docs.sypnia.com/architecture/request-paths.md): Call: TLS → key/token check (cache 60 s; revocation within 60 s) → route resolve (route version cached, invalidated on apply) → limits (in-memory buckets refilled by leases from Postgres) → estimate + reservation (Cloud: ledger hold) → redact/moderate → provider adapter (OpenAI shape ↔ provider shape) → response (or SSE passthrough with token counting) → charge + release → call record + usage rows (batched every second) → span export (batched OTLP). Browser: token exchange verifies the Data session JWT (JWKS cached) and origin, mints syp_ait_ (signed, 10 min, carries project, end user, tasks). Route change: PUT /routes by a person → validate (schema, models exist, tools, browser routes have end_user limits, embedding model change warning) → new version → caches invalidated. [Engine, Cloud] - [Data model](https://ai.docs.sypnia.com/architecture/data-model.md): Schema sypnia_ai: projects (id, org, settings: direct_models, zero_retention_only), route_versions (project, version, toml, json, created_by, created_at, active), keys (id, project, name, prefix, hash argon2id, scopes, credits_per_day, last_used_at, revoked_at), provider_keys (project, provider, encrypted secret or role ARN + external id, zero_retention), origins, limits (scope kind+id, kind, value), limit_leases, calls (id, project, key_id, task, route_version, case_id, end_user_hash, model, provider, attempts jsonb, input/output/cached tokens, credits, status, error_code, ttft_ms, duration_ms, trace_id, created_at; partitioned by day, dropped after retention), usage_daily (project, day, case, task, key, end_user_hash, model, calls, tokens, credits), stored_bodies (call_id, object key, expires_at), cache_entries (key hash, object key, expires_at), audit (who, what, when). [Engine, Cloud] - [Reference implementation on AWS](https://ai.docs.sypnia.com/architecture/reference-implementation-aws.md): AI on AWS (us-east-1): Lambda (Rust, arm64) with response streaming behind CloudFront for ai.api.sypnia.com and mcp.ai.sypnia.com; RDS PostgreSQL (shared suite instance, schema sypnia_ai, RDS Proxy); Amazon Bedrock (InvokeModel/InvokeModelWithResponseStream, same region, IAM role; customers' Bedrock via sts:AssumeRole with external id); OpenRouter over HTTPS with Sypnia's account key in Secrets Manager; SQS (+ DLQ) for usage records to the suite's credits ledger; S3 (kept bodies and response cache, lifecycle by days, SSE-KMS with per-project data keys); KMS; EventBridge Scheduler (daily rollups, partition drops, retirement notices); CloudWatch alarms (provider error rate, time to first token, DLQ depth); spans to Sypnia Telemetry. [Cloud] - [Failures and scaling](https://ai.docs.sypnia.com/architecture/failures-and-scaling.md): Provider down/slow: route fallbacks; circuit breaker per provider+model (opens after 5 failures in 30 s, half-open after 30 s), health in GET /health and Telemetry. Postgres unavailable: calls with cached key/route continue for up to 5 min using local conservative limits (half of per-minute limits, caps checked against last known totals), records spooled locally/SQS and written after; browser tokens and end-user-limited routes fail closed (503). Ledger unavailable (Cloud): holds queued; calls allowed up to the organization's last known balance minus outstanding holds; never past spending limits. Usage queue failure: DLQ, replayed; usage never lost or double-counted (idempotent call id). Gateway instance dies mid-stream: client gets a cut stream; charged for written tokens; hold released by a sweeper after 15 min. Scaling: stateless gateway, Lambda concurrency; calls table partitioned by day. [Engine, Cloud] - [Codebase](https://ai.docs.sypnia.com/architecture/codebase.md): sypnia-ai repo (Sypnia Git, GitHub mirror): gateway/ Rust workspace (api, router, limits, meter, safety, providers/{openrouter,bedrock,openai_compat}, otel, mcp, store), migrations/, packages/ai (@sypnia/ai server/browser/cli), prices/ (price table format for self-hosting), deploy/ (compose with a fake provider, AWS template), spec/openapi.yaml, spec/routes.schema.json, docs/ARCHITECTURE.md; tests against a recorded fake provider (no keys needed) and contract tests per provider run with real keys in CI. [Engine, Cloud] ## Self-hosting Run the open-source gateway yourself, with your own OpenRouter key, AWS account or a model on your own machine. - [Self-hosting: overview](https://ai.docs.sypnia.com/self-hosting.md): Self-hosting the gateway: one container (ghcr.io/sespinosav/sypnia-ai) + Postgres 16; optional S3-compatible storage (kept bodies, response cache); providers via your OpenRouter key, AWS credentials for Bedrock, or OpenAI-compatible endpoints (local model servers). No credits: usage counted in provider currency from a price table. No default models. Spans to any OTLP endpoint. What you lose vs Cloud: console, Sypnia's provider accounts, credits, organization spending limits. [Engine] - [Docker](https://ai.docs.sypnia.com/self-hosting/docker.md): compose.yaml: ai (ghcr.io/sespinosav/sypnia-ai:1, port 8095, env SYPNIA_GATEWAY_*), db (postgres:16), optional minio for bodies/cache, optional local model server as an OpenAI-compatible provider (SYPNIA_GATEWAY_PROVIDERS=local=http://models:11434/v1). Health GET /v1/health; metrics GET /metrics (Prometheus) on the same port behind the root token. Sizing: 256 MB RAM handles hundreds of concurrent streams; Postgres small. [Engine] - [Configuration](https://ai.docs.sypnia.com/self-hosting/configuration.md): Settings (env, prefix SYPNIA_GATEWAY_ to avoid clashing with the Telemetry engine's SYPNIA_AI_*): DATABASE_URL (required), ROOT_TOKEN (required), PUBLIC_URL, PORT (8095), OPENROUTER_KEY, BEDROCK_REGION (+ standard AWS credential chain; BEDROCK_ROLE_ARN optional), PROVIDERS (name=url[;key=…], comma list of OpenAI-compatible endpoints), ZERO_RETENTION_ONLY (true), PRICES (path to price table YAML; default built-in table for OpenRouter/Bedrock refreshed on upgrade), CURRENCY (USD), STORAGE_URL (s3-compatible, optional), CALL_RETENTION_DAYS (90), OTLP_ENDPOINT, OTLP_HEADERS, DATA_JWKS_URL (Sypnia Data engine for browser tokens), FIRST_TOKEN_TIMEOUT_S (20), REQUEST_TIMEOUT_S (600), MAX_BODY_MB (25), AUTO_MIGRATE (false), LOG (info), MCP (true). [Engine] - [Upgrades](https://ai.docs.sypnia.com/self-hosting/upgrades.md): Semver; image tags :1 (latest 1.x), :1.4, :1.4.2. Migrations forward-only, backward compatible within a major (old and new copies can run together during a rolling upgrade). Upgrade: pull, run migrate (or AUTO_MIGRATE), restart. The built-in price table and the catalog of model capabilities update with each release (changelog lists price changes); your own PRICES file is never overwritten. Routes format 1 stays readable by every 1.x. Major versions: written notice in the changelog with steps. [Engine] ## Security Keys, the threat model and the checklist. - [Security: overview](https://ai.docs.sypnia.com/security.md): Security section: secret keys server-only (refused with Origin), hashed at rest, scoped (call/read/admin), capped; browser tokens 10 min, one person, browser routes only; provider keys encrypted and write-only; agents cannot change routes, limits or keys; audited reads of kept bodies; threat model and checklist. [Engine, Cloud] - [Threat model](https://ai.docs.sypnia.com/security/threat-model.md): Threats → answers: leaked secret key (scopes, per-key caps, refused from browsers, revoke within 60 s, alerts on unusual spend); stolen browser token (10 min, one person, browser routes, per-person caps, origins); one person abusing a public feature (end_user limits required, moderation); prompt injection making the model leak or act (locked instructions, tool allowlist, your server confirms actions, minimal context); provider keeping data (zero-retention only in Cloud); Sypnia staff reading prompts (not stored by default; kept bodies encrypted per project, reads audited and shown); runaway agent spending (MCP cannot change limits/keys/routes; Sypnia-Budget per step); price/usage tampering (server-side counting, idempotent records); SSRF via image URLs (https only, no private addresses, 10 s); denial of service (CloudFront, per-minute limits, reservations). [Engine, Cloud] - [Checklist](https://ai.docs.sypnia.com/security/checklist.md): Checklist: secret key only in server env; AI keys with call scope and a daily cap; browser routes have end_user limits + moderation input + origins set; instructions in routes not in client code; tools allowlisted, side effects confirmed by a person; no secrets/others' data in prompts; structured outputs where possible; Sypnia-End-User set (stable id, never e-mail); each call names its case; project and case caps set; store off unless needed, shortest days; DELETE /end-users wired to your account deletion; spans reaching Telemetry; alerts on budget_exceeded/provider_unavailable; route changes reviewed in pull requests. [Engine, Cloud] ## Sypnia Cloud Projects, what is measured in credits, and plans. - [Sypnia Cloud: overview](https://ai.docs.sypnia.com/cloud.md): AI in Sypnia Cloud: belongs to a project of the organization (shared across products); Sypnia account sign-in (roll-in on first use); console ai.app.sypnia.com and App's AI panel; usage paid from prepaid credits; roles: owner/admin apply routes and set limits, billing manages credits, members read usage and calls, agents read and draft. [Cloud] - [Credits and limits](https://ai.docs.sypnia.com/cloud/credits-and-limits.md): Metered: tokens read, written and read from cache, per model at catalog prices in credits; embeddings tokens; moderation checks; kept bodies storage (GB-days); calls routed with your own provider key are free on Sypnia (no credits, no fee; only the provider bills). Not metered: refused calls, cache hits, the console, the CLI, MCP reads. Paid from prepaid credits, reserved then charged; no charges after the fact. Plan sets requests/tokens per minute per project, keys, retention options; values published with the plans. [Cloud] - [Plans](https://ai.docs.sypnia.com/cloud/plans.md): AI plans: AI on its own (plans of its own), the global Sypnia subscription (tiers include an amount of AI usage), extra capacity per item (higher per-minute limits, longer retention) on any plan; usage beyond included amounts paid from prepaid credits; everything prepaid; when credits run out: 80/100 % notices (80 % of the balance after the last top-up), 7 days of grace with calls working, then new calls refused with 402 insufficient_credits (own-key calls keep working), nothing deleted; Sypnia's own products' calls are charged like any project's. [Cloud] ## Reference Glossary, limits, design decisions, common questions and the changelog. - [Reference: overview](https://ai.docs.sypnia.com/reference.md): Glossary, limits, design decisions, common questions and the changelog. [Engine, Cloud] - [Glossary](https://ai.docs.sypnia.com/reference/glossary.md): Sypnia AI vocabulary: model, token, provider, task, route, fallback, embedding, catalog, gateway, secret key, browser token, end user, reservation, credits, cap, structured answer, tool, redaction, moderation, prompt injection, zero retention, kept body, response cache, span, bring your own key. [Engine, Cloud] - [Limits](https://ai.docs.sypnia.com/reference/limits.md): Fixed limits: request body 25 MB; 10 images × 10 MB; PDF 20 MB / 100 pages; embeddings 256 inputs; tools 128 per request, 5 tool rounds by default in the SDK (max 20); output schema 64 KB; instructions 32 KB per route; 200 tasks per project; route file 1 MB; first token timeout 20 s (1–120); request timeout 600 s; browser token 600 s; key revocation within 60 s; call records 90 days (Cloud); kept bodies 1–30 days; response cache TTL 1 min–24 h; management API 600 requests/min per token; keys 100 per project (Cloud default, plan may differ); origins 20 per project; model retirement notice 30 days; default change notice 7 days. Per-minute model limits per project: by plan. [Engine, Cloud] - [Design decisions](https://ai.docs.sypnia.com/reference/decisions.md): Decisions: tasks not models in code; OpenAI-compatible API plus Sypnia headers; routes in the [ai] table of sypnia.toml applied by a person; zero-retention providers only in Cloud; bodies not stored by default, opt-in 1–30 days; reserve-then-charge; per-person limits mandatory for browser routes; browser tokens from the Data session; Rust gateway AGPL-3.0, @sypnia/ai MIT; no default models when self-hosted; SYPNIA_GATEWAY_ settings prefix; spans with OpenTelemetry gen_ai conventions, no content; Lambda with response streaming in us-east-1; agents read and draft, people apply; response cache off by default. [Engine, Cloud] - [Common questions](https://ai.docs.sypnia.com/reference/faq.md): FAQ: how it differs from OpenRouter (adds routes per task, credits, per-case/per-person limits, Telemetry spans, browser tokens, zero-retention rule; uses OpenRouter underneath); which models (catalog; docs name none); can I use my own key (yes, BYOK); does Sypnia train on my data (no; providers that keep or train are not used); do I need other Sypnia products (no; Data for browser tokens via session, Telemetry for traces, both optional); can I use the OpenAI SDK (yes, baseURL); what if a model disappears (notice, route moves); can I move off (self-host the same gateway, or point clients elsewhere). [Engine, Cloud] - [Changelog](https://ai.docs.sypnia.com/reference/changelog.md): What changed in Sypnia AI, newest first. [Engine, Cloud]