# Agents & Automation Source: https://docs.prem.io/agents Build unattended, agentic, or automated systems on Prem API: which integration to use, required config, and the operational gotchas that matter at scale. This page is for anyone building a system that calls Prem API **without a human watching each call**: agent loops, batch jobs, evaluation harnesses, or any tool that fires many requests unattended. Unattended callers hit different failure modes than an interactive app. A truncated response, a burned rate-limit budget, or a duplicated retry may not be noticed until it has already happened many times. > [!TIP] > > If you want an AI coding agent (Claude Code, Cursor, Windsurf) to help you **write** this integration, see [Use LLMs](/use-llms). It loads the Prem API docs into your coding agent's context. This page is about the system you build calling Prem API, not the coding agent that helps you build it. ## Pick your integration | | TypeScript SDK | Confidential Proxy | ZDR | | - | - | - | - | | **Best for** | Node.js agents, single-process automation | Polyglot agent frameworks (LangChain, Python/Go agent loops), anything already using an OpenAI or Anthropic SDK | OpenAI-compatible tools that need the ZDR model catalog | | **Encryption** | In-process | A local HTTP process encrypts/decrypts for you | Not confidential | | **Code changes** | Use `@premai/api-sdk` instead of `openai` | Point `baseURL` at the proxy | Point a Chat Completions client at `https://gateway.prem.io/openai` | > [!WARNING] > > The TypeScript SDK and Confidential Proxy are the confidential paths. ZDR > does not provide enclave confidentiality. Use ZDR only when its model > catalog is more important than confidential processing. See [Developer Experience](/developer-experience) for both, in detail. For an agent that runs continuously, run the Confidential Proxy as a **background daemon** rather than in the foreground: ```bash theme={"system"} confidential-proxy start --compat openai --kek "$CLIENT_KEK" confidential-proxy status ``` See [Confidential Proxy](/confidential-proxy#run-the-proxy-as-a-daemon) for the full daemon lifecycle (`start` / `stop` / `status`, state and log files, graceful shutdown). ## Required configuration Both confidential integration paths need the same four values. Set them once in the environment where the agent runs, not for each call: | Variable | Used by | Description | | - | - | - | | `PREM_API_KEY` | Both | Your API key. See [API Keys](/api-keys). | | `CLIENT_KEK` | Both | A 32-byte key encoded as 64 hexadecimal characters. You generate and keep it. See [Encryption](/encryption). | | `PROXY_URL` | Both | The Prem API Gateway endpoint. | | `ENCLAVE_URL` | Both | The enclave endpoint. | Get the current `PROXY_URL` / `ENCLAVE_URL` values from [`dashboard.prem.io/endpoints.json`](https://dashboard.prem.io/endpoints.json) at deploy time rather than hardcoding them. ZDR uses the same `PREM_API_KEY` at `https://gateway.prem.io/openai`. See [ZDR overview](/zdr/overview) for the ZDR setup. ## Gotchas that only show up at automation scale These are easy to miss in a one-off script and expensive to miss in a loop that runs thousands of times. > [accordion] Reasoning is on by default and is billed > > Reasoning models generate a chain-of-thought before every answer unless you turn it off. > Those tokens are billed, count against your rate limit, and share the same inference's token budget as the visible answer. Reasoning can consume a tight `max_completion_tokens` value and leave `message.content: null`. > > Default to the lowest `reasoning_effort` value that the model family accepts in automated pipelines unless you explicitly consume the reasoning trace. See [Models & Pricing](/models-and-pricing#reasoning-effort) for the values that each family accepts. > [accordion] Concurrency is shared within each inference family > > Your tier sets separate concurrency limits for Confidential and ZDR. All keys and users in an organization share each family's concurrency limit. Every endpoint in a family counts toward the same limit. A request above the limit returns `429` with: > > ```json theme={"system"} > {"status": 429, "error": "Concurrent request limit reached. Your limit allows 5 concurrent request(s). Wait for ongoing requests to complete, or contact us for higher limits."} > ``` > > The TypeScript SDK uses the encrypted `/rvenc/chat/completions` endpoint. The endpoint returns JSON by default. It returns `text/event-stream` when `stream: true`. A request holds a concurrency slot while it waits for model capacity and while inference runs. Use a shared queue or concurrency limit for workers in the organization and inference family. More API keys do not increase the limit. > > All keys in the organization share each family's request-rate, token, and audio allowances. Confidential usage does not use the ZDR allowance. ZDR usage does not use the Confidential allowance. See [Tiers](/tiers) for the current limits and allowance scope. > [accordion] 429 responses don't all look the same > > Some `429` responses have a structured body and a `Retry-After` header. An upstream rate limit can return a generic body without a `Retry-After` header. Read the HTTP status and the error details. Use exponential backoff for temporary limits when the header is absent. Set a maximum number of retries. Stop automatic retries for this error: `Inference request allowance exhausted. Contact us for higher limits.` Time does not restore this allowance. See [Rate limits](/rate-limits#non-standard-429-responses). > [accordion] Retries need to be idempotent > > An agent that retries blindly after a timeout or a `5xx` can duplicate the underlying action (a file upload, a resource creation). Send an `Idempotency-Key` header so a retried request has the same effect as the original. See [Idempotency](/idempotency). > [accordion] Check finish\_reason and content > > A `null` or empty `message.content` is not necessarily a failed call. If `finish_reason` is `"length"`, reasoning, a long answer, or both consumed the token budget. Treat it as truncation and retry with a larger `max_completion_tokens` or a lower `reasoning_effort`, not as an empty result to discard. ## A request shaped for unattended use ```typescript theme={"system"} import createRvencClient from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, }); const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: "Summarize this log file." }], reasoning_effort: "low", // reduce reasoning unless you consume it max_completion_tokens: 4096, // headroom for the answer }, { headers: { "Idempotency-Key": crypto.randomUUID() }, // safe to retry }); const choice = response.choices[0]; if (choice.finish_reason === "length") { // Truncated: raise max_completion_tokens or retry; do not treat as empty. } console.log(choice.message.content); ``` ## Before you deploy * [ ] `reasoning_effort` set deliberately (the lowest value the model family accepts, or a value you've budgeted `max_completion_tokens` for) * [ ] Retries use exponential backoff and don't assume `Retry-After` is present * [ ] Idempotency keys on any retried write * [ ] Concurrent requests stay within each family's concurrency limit * [ ] Every response checks `finish_reason` before treating `content` as final * [ ] `support_id` is logged on every error for support escalation > [!NOTE] > > This checklist is agent-specific. For the full production checklist (key management, tiers, attestation), see [Production Checklist](/production-checklist). ## Related > [card] [Tiers](/tiers) > > The request, token, and audio limits of each tier. > [card] [Rate limits](/rate-limits) > > Retry code, the 429 shapes, and non-standard 429 bodies. > [card] [Idempotency](/idempotency) > > Make retries safe with the Idempotency-Key header. > [card] [Confidential Proxy](/confidential-proxy) > > Daemon mode, config, and connecting any language. > [card] [OpenCode](/guides/opencode) > > Connect OpenCode to Prem API through the local proxy. > [card] [OpenClaw](/guides/openclaw) > > Configure a Prem-backed OpenClaw provider and its tool boundary. > [card] [Hermes Agent](/guides/hermes) > > Use an explicit Chat Completions transport through Prem. > [card] [Goose](/guides/goose) > > Connect Goose's built-in OpenAI provider to Prem. > [card] [Cursor compatibility](/guides/cursor) > > Review why Cursor's provider override is not a confidential local path. > [card] [Codex CLI compatibility](/guides/codex-cli) > > Review the current Responses API protocol mismatch. # API Keys Source: https://docs.prem.io/api-keys Learn how API keys work, how to manage them, and how to use scopes and IP restrictions. API keys are the primary method of authentication for our APIs. Each API key belongs to an organization and has permission scopes. You can also protect an API key with IP restrictions. > [card] [Create and Manage API Keys](https://dashboard.prem.io/api-keys) > > You can generate and manage API keys in your Prem API Dashboard > Developers > API Keys section. ## API keys and organizations We issue API keys **at the organization level**, not to individual users. This means: * The API attributes each action of an API key to the **owning organization**. * Many team members can work together with separate keys in the same organization. * API keys stay valid independently of individual user accounts. ## Unlimited Keys per Organization Each organization can create **any number of API keys**. This gives flexibility across environments, services, or teams. Common usage patterns include: * One key per environment (e.g., `development`, `staging`, `production`) * One key per integration (e.g., billing automation, analytics) * Temporary keys for CI/CD or testing purposes ## IP Restrictions For better security, you can **restrict an API key to specific IP addresses or subnets**: * The restrictions **support IPv4**, **IPv6**, and **CIDR notation** * The API rejects requests from unauthorized IPs with a `403 Forbidden` error Example entries: * `192.168.1.10` * `2001:0db8::/32` * `203.0.0.0/8` > [!TIP] > > Use IP allowlists to protect critical integrations (e.g., production). ## Scoped Permissions You can limit each API key to a specific set of **scopes**. The scopes define the parts of the API that the key can access. The dashboard asks you to set these scopes when you create an API key. If you do not specify scopes, the API key has full permissions. ## API Scopes Reference | Scope | Description | | - | - | | `api_keys.read` | View and list API keys associated with your organization. | | `chats.completion` | Access chat completion functionality. | | `tools.execute` | Execute tools and integrations. | | `files.encrypted.read` | Read encrypted files. | | `files.encrypted.create` | Upload encrypted files. | | `files.encrypted.delete` | Delete encrypted files. | | `audio.transcription` | Transcribe audio files to text. | | `audio.translation` | Translate audio from any language to English. | This lets you apply the **principle of least privilege** and isolate permissions for each use case. > [!NOTE] > > A request from a key without the required scope returns `403 Forbidden`. ## Best Practices * **Rotate keys regularly** to decrease exposure * **Use least privilege**: assign only the required scopes * **Restrict by IP** where possible * **Do not share keys between environments** or teams For key management, go to your **Dashboard > API > API Keys**. If you need help, contact [support](mailto:support@premai.io) or refer to the [Authentication Guide](/authentication). # Get an API key Source: https://docs.prem.io/api-reference/api-keys/get-api-key get /developers/api_keys/{id} Get details of a specific API key by ID # Get API key analytics Source: https://docs.prem.io/api-reference/api-keys/get-api-key-analytics get /analytics/api_keys Get analytics data for API key usage # Get API key request Source: https://docs.prem.io/api-reference/api-keys/get-api-key-request get /developers/api_keys/requests/{id} Get details of a specific API key request/usage log entry by ID # List API key requests Source: https://docs.prem.io/api-reference/api-keys/list-api-key-requests post /developers/api_keys/requests Get a filtered list of API key requests/usage logs # List API key scopes Source: https://docs.prem.io/api-reference/api-keys/list-api-key-scopes get /developers/api_keys/scopes List all available scopes for API keys # List API keys Source: https://docs.prem.io/api-reference/api-keys/list-api-keys get /developers/api_keys List all API keys for the organization # Encrypted Audio Transcriptions (RVENC) Source: https://docs.prem.io/api-reference/audio-transcriptions post /rvenc/audio/transcriptions Transcribe an end-to-end encrypted audio file into text, in the language spoken in the audio. Nothing is stored: neither the audio nor the transcript. ## TypeScript SDK The SDK is available on GitHub: [premAI-io/api-sdk-ts](https://github.com/premAI-io/api-sdk-ts) ### Basic Setup Create a 32-byte KEK. Encode it as 64 hexadecimal characters. Keep the KEK. Reuse it for later requests. ```bash theme={"system"} export CLIENT_KEK="$(openssl rand -hex 32)" ``` Create the client: ```typescript theme={"system"} import { createRvencClient } from "@premai/api-sdk"; import fs from "fs"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK }); ``` ### Pre-generate Keys You can pre-generate encryption keys and reuse them with the same KEK: ```typescript theme={"system"} import { createRvencClient, generateEncryptionKeys } from "@premai/api-sdk"; const encryptionKeys = await generateEncryptionKeys(); const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, encryptionKeys, requestTimeoutMs: 60000, // optional maxBufferSize: 20 * 1024 * 1024, // optional }); ``` ### Basic Transcription ```typescript theme={"system"} const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('./audio.wav'), model: 'deepgram/general-nova-3', smart_format: true, }); console.log(transcription.results?.channels?.[0]?.alternatives?.[0]?.transcript ?? ''); ``` ### Transcription with Options ```typescript theme={"system"} const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('./audio.mp3'), model: 'deepgram/general-nova-3', diarize: true, smart_format: true, }); ``` ### Configuration | Option | Default | Description | | - | - | - | | `file` | required | Audio file (ReadStream, Buffer, Blob, etc.) | | `model` | required | Current enabled model ID: `'deepgram/general-nova-3'` | | `diarize` | `false` | Ask the backend to identify speakers | | `smart_format` | `false` | Ask the backend to format dates, numbers, and punctuation | > **Note:** The current Deepgram route is non-streaming and returns Deepgram-style `metadata` and `results`, not an OpenAI `{ text }` object. ## OpenAI-Compatible API Server Run the SDK as a standalone server. The proxy requires the same 32-byte KEK described above and automatically manages one DEK store for each API key: ```bash theme={"system"} bunx -p @premai/api-sdk@2.1.0 confidential-proxy --kek "$CLIENT_KEK" # Server runs on http://127.0.0.1:8787 ``` Use the server with any OpenAI-compatible client: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/audio/transcriptions \ -H "Authorization: Bearer your-api-key" \ -F "file=@audio.mp3" \ -F "model=deepgram/general-nova-3" ``` You can also use the OpenAI SDK against the local proxy: ```typescript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY, baseURL: "http://127.0.0.1:8787/v1", }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream('./audio.mp3'), model: 'deepgram/general-nova-3', }); console.log(JSON.stringify(transcription, null, 2)); ``` The server establishes a secure client instance for each API key. ## API Reference # Encrypted Audio Translations (RVENC) Source: https://docs.prem.io/api-reference/audio-translations post /rvenc/audio/translations Translate an end-to-end encrypted audio file into English text, whatever the input language. Nothing is stored: neither the audio nor the translation. ## TypeScript SDK The SDK provides `client.audio.translations.create(...)`. The Confidential Proxy provides the `/v1/audio/translations` route. ### Set the KEK Create a 32-byte KEK. Encode it as 64 hexadecimal characters. Keep the KEK. Reuse it for later requests. ```bash theme={"system"} export CLIENT_KEK="$(openssl rand -hex 32)" ``` ### List the models Start the proxy: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --compat openai \ --kek "$CLIENT_KEK" ``` List the available models: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` Use a model ID that supports audio translation. ## API Reference # Encrypted Chat Completions (RVENC) Source: https://docs.prem.io/api-reference/chat-completions post /rvenc/chat/completions Create a chat completion from an end-to-end encrypted payload, decrypted only inside the confidential compute environment. Stateless: no chat history is kept and no files can be attached. ## TypeScript SDK The SDK is available on GitHub: [premAI-io/api-sdk-ts](https://github.com/premAI-io/api-sdk-ts) ### Basic Setup Create a 32-byte KEK. Encode it as 64 hexadecimal characters. Keep the KEK. Reuse it for later requests. ```bash theme={"system"} export CLIENT_KEK="$(openssl rand -hex 32)" ``` Create the client: ```typescript theme={"system"} import createRvencClient from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK }); ``` ### Pre-generate Keys You can pre-generate encryption keys and reuse them: ```typescript theme={"system"} import createRvencClient, { generateEncryptionKeys } from "@premai/api-sdk"; const encryptionKeys = await generateEncryptionKeys(); const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, encryptionKeys, requestTimeoutMs: 60000, // optional maxBufferSize: 20 * 1024 * 1024, // optional }); ``` ### Non-streaming Requests ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello!" }], }); ``` ### Streaming Requests ```typescript theme={"system"} const stream = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello!" }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` ### Configuration | Option | Default | Description | | - | - | - | | `apiKey` | required | Authorization token | | `encryptionKeys` | auto-generated | Pre-generated `{ sharedSecret, cipherText }` | | `requestTimeoutMs` | 30000 | Request timeout in ms | | `maxBufferSize` | 10MB | Max SSE buffer size | ## OpenAI-Compatible API Server Run the SDK as a standalone server. The server automatically manages one DEK store for each API key: ```bash theme={"system"} bunx -p @premai/api-sdk@2.1.0 confidential-proxy --kek "$CLIENT_KEK" # Server runs on http://127.0.0.1:8787 ``` Use the server with any OpenAI-compatible client: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer your-api-key" \ -H "Content-Type: application/json" \ -d '{"model": "deepseek-v4.1-flash-1017", "messages": [{"role": "user", "content": "Hello!"}], "stream": false}' ``` You can also use the SDK directly in Node.js: ```typescript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY, baseURL: "http://127.0.0.1:8787/v1", }); const stream = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Count to 10" }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` The server establishes a secure client instance for each API key. ## Reasoning models Reasoning tokens are billed and count against your token rate limits. See [Usage](/billing/usage) for billing, output-token interaction, and instructions to disable or limit reasoning. The valid `reasoning_effort` values depend on the model family. See [Models & Pricing](/models-and-pricing#reasoning-effort) for the values that each family accepts. ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "", messages: [{ role: "user", content: "Hello!" }], reasoning_effort: "low", // reduce reasoning }); ``` ## API Reference # List available models for confidential inference Source: https://docs.prem.io/api-reference/list-models get /rvenc/models Get a list of models available for confidential (rvenc) inference ## Confidential catalog This endpoint returns the models that your API key can use for confidential inference. Use [`GET /openai/models`](/api-reference/zdr-list-models) for the [Zero Data Retention](/zdr/overview) catalog. ```bash theme={"system"} curl "https://gateway.prem.io/rvenc/models?type=CHAT" \ -H "Authorization: Bearer $PREM_API_KEY" ``` The `regions` field of each entry shows the confidential regions that give the model. # Create chat completion (OpenAI-compatible) Source: https://docs.prem.io/api-reference/zdr-chat-completions post /openai/chat/completions Create a chat completion. Compatible with the OpenAI Chat Completions API. Not end-to-end encrypted — use `/rvenc/chat/completions` for that. ## Zero Data Retention This is the standard inference route. Prem sends the request to a trusted partner. Prem does not keep your prompts or completions, and the partner does not keep them. Your content is plaintext at the Prem API Gateway and at the partner. Use [`/rvenc/chat/completions`](/api-reference/chat-completions) for a confidential path with client-side encryption and attestation. See [ZDR vs Confidential](/zdr/comparison). ## Base URL Set the base URL of an OpenAI client to `https://gateway.prem.io/openai`. Do not add a `/v1` segment. ```python theme={"system"} import os from openai import OpenAI client = OpenAI( api_key=os.environ["PREM_API_KEY"], base_url="https://gateway.prem.io/openai", ) response = client.chat.completions.create( model="kimi-k3", messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) ``` ## Streaming Set `"stream": true` to get a stream of server-sent events in the OpenAI format: ```python theme={"system"} stream = client.chat.completions.create( model="kimi-k3", messages=[{"role": "user", "content": "Count to 10"}], stream=True, ) for chunk in stream: print(chunk.choices[0].delta.content or "", end="") ``` ## Model availability Send a model that `GET /openai/models` returns for your API key. A confidential-only model returns a 400 status with this message: `Model {model} is available for encrypted inference only.` See [Models & Pricing](/models-and-pricing) for the mode errors. # Decisions Source: https://docs.prem.io/api-reference/zdr-decisions post /typesafe/v1/systemone Answer typed decision questions with probabilities over a TypeSafe-compatible API. ## Zero Data Retention This is a Zero Data Retention route. Prem sends the request to a trusted partner. Prem does not keep your prompts or completions, and the partner does not keep them. Your content is plaintext at the Prem API Gateway and at the partner. There is no client-side encryption and no Trusted Execution Environment. See [ZDR vs Confidential](/zdr/comparison). ## Base URL ```text theme={"system"} https://gateway.prem.io/typesafe/v1/systemone ``` Authenticate with a standard Prem API key in the `Authorization: Bearer` header. The key must have the `chats.completion` scope. No client KEK is used on this route. ```bash theme={"system"} curl https://gateway.prem.io/typesafe/v1/systemone \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "dgemma", "state": "x", "questions": {"a": {"type": "noul", "instructions": "y"}}}' ``` ## Request shape The request uses a TypeSafe-compatible API, so the official [TypeSafe client](https://www.npmjs.com/package/@typesafe-ai/sdk) works against this route. Set its base URL to `https://gateway.prem.io/typesafe`. The client appends `/v1/systemone` and `/v1/models`. ```typescript theme={"system"} import { choice, noul, score, TypeSafeClient } from "@typesafe-ai/sdk"; const client = new TypeSafeClient({ apiKey: process.env.PREM_API_KEY, baseURL: "https://gateway.prem.io/typesafe", defaultModel: "dgemma", }); const res = await client.systemOne({ state: "Customer says: 'I was charged twice for the same purchase.'", questions: { category: choice("What is this ticket about?", { billing: null, technical: null, other: null }), urgent: noul("Is this request urgent?"), severity: score("How severe is this issue?", ["not severe", "mild", "moderate", "severe", "critical"] as const), }, }); console.log(res.answers.category.choice, res.answers.urgent.noul, res.answers.severity.score); ``` It is not the OpenAI Chat Completions shape, so an OpenAI client does not work against this route. | Field | Required | Description | | - | - | - | | `model` | yes | Model name from `GET /typesafe/v1/models`. | | `state` | yes | The context the questions are asked about. A string, object, array, number, boolean, or null. | | `questions` | yes | A map of question id to a typed question. | | `images` | no | At most one base64 image data URL. | | `videos` | no | At most one base64 MP4 data URL. A `dgemma` extension. | | `samples` | no | Number of reads to average. | | `steps` | no | Number of denoising steps. | | `provider` | no | Pin the request to one of the model's configured backends. | Each question carries `type`, `instructions`, and `criteria`: | `type` | `criteria` | Answer field | | - | - | - | | `choice` | A map of 1 to 26 labels to descriptions | `choice`, `probabilities`, `confidence` | | `noul` | Optional. Descriptions for the two outcomes | `noul` | | `score` | An ordered list of 2 to 10 levels | `score`, `legend`, `probabilities`, `confidence` | ## Response shape | Field | Description | | - | - | | `model` | The resolved model name. | | `answers` | One entry per question id, keyed by the id that you sent. | | `usage` | `input_tokens` and `output_tokens` for the request. | | `diagnostics` | Engine detail for the call. Informational, and it can change. | Read `answers` by your own question ids. A `noul` answer puts its scalar in `noul`; a `noul` answer has no `probabilities` field. A `score` answer reports the probability-weighted mean over the zero-indexed levels. > [!WARNING] > > The values in `probabilities` are normalized scores over the supplied labels. They are not calibrated correctness estimates, and label order can change the prediction. See the guide's [current limits](/guides/decisions#current-limits). ## Media input Use `images` or `videos`, not both in one request. * `images` holds at most one base64 image data URL. The image is placed ahead of the state. * `videos` holds at most one base64 MP4 data URL, up to 10 MiB, 30 seconds, and 1920 x 1080 pixels. Four frames are sampled and audio is not processed. This is a `dgemma` extension and is not part of the base request shape. Use a raw JSON request if your HTTP client does not expose the field. ## Streaming This route is non-streaming. A `stream` field is not supported. The call returns one JSON object. ## Model availability Send a model that `GET /typesafe/v1/models` returns for your API key. `dgemma` is served through this route and is not available on the chat completions routes. A chat model on this route returns a validation error. See [Models & Pricing](/models-and-pricing). ## Limits * Up to 16 questions per request. * `choice` holds 1 to 26 criteria. `score` holds 2 to 10 levels. * At most one image or one video per request. * Questions are independent. One question cannot read another question or its answer. * Decisions requests count toward your organization's ZDR limits for request rate, tokens, and concurrency. ZDR chat completions count toward the same limits. All keys and members share these limits. Confidential inference has separate limits. At the [concurrency limit](/tiers#concurrent-requests), the API returns `429` for new requests. ## Related > [card] [Decisions guide](/guides/decisions) > > Worked examples for each question type. > [card] [ZDR security boundary](/zdr/security-boundary) > > What Prem records and what the partner records. # List available models for standard inference Source: https://docs.prem.io/api-reference/zdr-list-models get /openai/models Get a list of models available for standard (OpenAI-compatible) inference ## Zero Data Retention catalog This endpoint returns the models that your API key can use for [ZDR inference](/zdr/overview). Use `GET /rvenc/models` for the confidential catalog. The response uses the OpenAI models list format. It has `"object": "list"` and an array in `data`. Each entry has the standard `id`, `object`, `created`, and `owned_by` fields, and Prem adds more fields after them. ```bash theme={"system"} curl "https://gateway.prem.io/openai/models?type=CHAT" \ -H "Authorization: Bearer $PREM_API_KEY" ``` An OpenAI SDK reads this endpoint with its standard method: ```python theme={"system"} for model in client.models.list(): print(model.id) ``` The `regions` field of each entry shows the ZDR regions that give the model. See [Models & Pricing](/models-and-pricing) for the full field reference. # Attestation Source: https://docs.prem.io/attestation How Prem verifies confidential infrastructure and release measurements before sending protected requests. Attestation is hardware-signed evidence about a confidential-computing environment. Before a protected request leaves your device, the Prem SDK checks that evidence against manufacturer collateral, a fresh challenge, and signed release references. ## What a pass means A pass requires all four checks: 1. **Authenticity:** hardware evidence verifies against manufacturer collateral. 2. **Freshness:** the evidence binds the verifier's challenge to the reported manifest. 3. **Configuration:** claims satisfy the applicable CPU or GPU policy. 4. **Identity:** measured values match an approved reference for the reported release and workload configuration. > [!WARNING] > > A valid manufacturer signature only proves that evidence came from the hardware trust chain. It does not prove that the measured software is an approved Prem release. That is the identity check. The references come from [Trustbase](https://github.com/prem-research/trustbase), which links supported [PodVM](https://github.com/prem-research/podvm) releases (the confidential-VM image source and its measurements) with workload initialization data. The client verifies Trustbase signatures and file digests, then passes the reference values to its OPA policy engine. [Tinysig](https://github.com/prem-research/tinysig) supplies the signature-verification components. Measurement comparison is on by default for registered releases; you do not supply image fingerprints. ## Released attestation stack The current integration uses `@premai/api-sdk` **2.1.0** and `@premai/reticle` **0.6.2**. The [Confidential chat models](/models-and-pricing#confidential-models) use the standard attestation protocol, **v2**, which returns a single confidential-VM report containing the workload manifest, CPU evidence, and optional GPU evidence. | Check | Released behavior | | - | - | | AMD SEV-SNP | Verifies the report signature and manifest-bound nonce, then compares the launch measurement and host data with signed references | | Intel TDX | Verifies the quote, collateral and manifest-bound nonce; checks MRTD, RTMR0–2 and MRCONFIGID against signed references | | NVIDIA GPU | Verifies supplied token signatures, digest links, bound nonces and policy claims | | Release references | Verifies signed Trustbase policies and measurement files before policy evaluation | The CPU challenge binds the manifest to the evidence; the GPU challenge binds supplied GPU evidence to that CPU report. ## Where Reticle runs Reticle is the verifier library. It runs in the SDK or proxy process on your side, not on the GPU cluster. The attestation endpoint runs with the confidential runtime and only produces the evidence. ```mermaid theme={"system"} flowchart LR subgraph Client["Client device or local proxy"] SDK["Prem SDK / Confidential Proxy"] R["@premai/reticle verifier"] SDK --> R end subgraph Prem["Prem services"] G["Gateway and model routing"] A["Attestation endpoint in the confidential runtime"] M["Model backend"] end R -->|"request unified report with nonce and model"| G G --> A A -->|"hardware evidence and session header"| R SDK -->|"encrypted request with session header"| G G --> M ``` Reticle is written in Rust and published as a WASM package, `@premai/reticle`, for Node.js, Bun, Deno, modern browsers, and mobile (iOS and Android). ## How the SDK gates a request With the default `attest: true`, `@premai/api-sdk`: 1. Builds a Reticle client against `PROXY_URL`, authenticated with your Prem API key. 2. Adds the requested model to the attestation query and calls `client.attest()`. 3. Reads `x-session-id` from the returned attestation headers. 4. Sends the encrypted inference request with that session ID, so the platform can associate it with the attested backend path. A successful session ID is cached for 30 seconds per API key and model, and simultaneous attestation calls are coalesced. Transient transport errors are retried, up to four attempts in total. A non-transient failure or a missing session ID throws before the inference request is sent. > [!WARNING] > > `attest: false` and the proxy flag `--no-attest` bypass this gate. Do not use them for a workflow that claims attested confidential inference. ## Attestation error handling When the gate fails, the SDK throws an `AttestationError` before the inference request is sent. The SDK exports four helpers to inspect the error: | Helper | Returns | Purpose | | - | - | - | | `isAttestationError(err)` | `boolean` | True when `err` is an `AttestationError` thrown by the attestation gate | | `isGatewayError(err)` | `boolean` | True when the error is a gateway rejection (a structured object with a non-empty message) | | `getGatewayErrorMessage(err)` | `string \| null` | The raw gateway rejection message, or `null` when the error is not a gateway error | | `getAttestationErrorMessage(err)` | `string` | A user-safe message: the gateway rejection body if there is one, otherwise the SDK's own message unless it is the generic `An internal error occurred`, otherwise the outermost cause | ### The two cases behind an `AttestationError` An `AttestationError` indicates that the request was stopped at the attestation gate. It does not necessarily indicate that attestation itself failed. The error represents one of two conditions, and each requires a different response: 1. **Gateway rejection.** The gateway declined the request before attestation could complete, for example with `Authentication token is invalid` on a `401`. This is an API or authentication issue, not an attestation failure, and the caller can resolve it by correcting the API key or checking the quota. 2. **Attestation failure.** The attestation exchange itself did not succeed. No user-actionable message is available; the SDK logs the full cause chain for debugging. Call `isGatewayError` first. If it returns `true`, surface the message from `getGatewayErrorMessage`. Treat the error as an attestation failure only when it returns `false`: ```typescript theme={"system"} import { createRvencClient, isAttestationError, isGatewayError, getGatewayErrorMessage, getAttestationErrorMessage, } from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, }); try { const chat = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello" }], }); } catch (err) { if (!isAttestationError(err)) throw err; if (isGatewayError(err)) { // Not an attestation failure (e.g. invalid API key). Show the actionable message. console.error("Request rejected:", getGatewayErrorMessage(err)); } else { console.error("Attestation failed:", getAttestationErrorMessage(err)); } } ``` A gateway rejection means the request never reached the model backend, so you can retry safely once the cause is fixed. The gateway check matches on the error's shape rather than `instanceof`. It stays reliable when you drive Reticle directly (for example, through `useAttestation` in a browser bundle) and the error comes from a different Reticle WASM instance than the one the SDK cached. ## Verify directly with Reticle You can run the same verification yourself, without the SDK. See the [Run Attestation](/guides/run-attestation) guide. > [!WARNING] > > The low-level `request_attestation(nonce)` method only fetches raw evidence. A successful fetch is not an attestation pass; use `attest()` for a verification decision. ## Multi-GPU attestation and load balancing A single model can be served by several physical GPUs at once. When NVIDIA evidence is supplied, Reticle checks the overall and detached tokens, their signatures and digest links, the bound nonce, and the GPU policy claims. The supplied GPU set must match NVIDIA's signed overall result, and duplicate GPU identities are rejected. Verification either succeeds for the whole supplied set or fails. ## Supported hardware **CPUs.** Reticle implements the evidence formats and manufacturer collateral for AMD SEV-SNP and Intel TDX. Other CPUs are not automatically insecure; they are unsupported until there is a corresponding confidential-computing architecture, evidence format, collateral path, and policy implementation. Support for a CPU family lets a client authenticate its evidence and freshness. Workloads, measurements, and firmware states still have to pass policy. **GPUs.** NVIDIA confidential computing depends on hardware and firmware. “Hopper” and “Blackwell” are architecture families, not policy inputs; the verifier examines the signed token and claims for the deployed SKU and software stack. GPUs without a supported confidential-computing mode and attestation format can still run inference, but Reticle cannot produce the same remote evidence for them. ## What attestation does not show * **Backend internals.** Attestation is model-scoped and the session ID is forwarded with the request. That does not prove every backend scheduling, load-balancing, or billing detail. Separately from attestation, the gateway authenticates the API key, applies limits and billing metadata, and selects the service path for the requested alias, all while handling encrypted content. * **Billing.** A failed attestation stops the inference request before it is sent. Confirm final billing from your Prem usage records. * **An assurance profile per model.** Model-list and completion types have no `assurance`, `attestation`, `tee`, or similar fields. OpenAI-format and direct SDK completions can return a backend-resolved model ID in `response.model`; the Anthropic adapter returns the requested alias. Neither is a substitute for an assurance profile. See [Models & Pricing](/models-and-pricing) for the models in each inference mode. ## Audit records Record non-sensitive decision metadata: * request/support ID and time; * requested alias and resolved model ID when exposed; * verifier and policy version; * evidence type, hardware identity fields, and TCB result; * nonce/freshness result; * reference-set identifier and measurement result when available to your integration; * allow/deny decision and reason. Do not record prompts, responses, API keys, KEKs, raw decrypted payloads, or secrets. See [Platform Status](/platform-status) for released capabilities. # Authentication Source: https://docs.prem.io/authentication Authenticate with the Prem API using your API key and client encryption key (KEK). ## Basic API Key Authentication Authenticate with your API key: ```typescript theme={"system"} import createRvencClient from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK }); // Verify authentication const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ## Use Pre-generated Keys Use pre-generated encryption keys for better performance: ```typescript theme={"system"} import createRvencClient, { generateEncryptionKeys } from "@premai/api-sdk"; // Generate keys once const encryptionKeys = await generateEncryptionKeys(); // Reuse keys across multiple requests const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, encryptionKeys, }); const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ## Use Custom Options Configure custom options such as timeout and buffer size: ```typescript theme={"system"} const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, requestTimeoutMs: 60000, // 60 seconds maxBufferSize: 20 * 1024 * 1024, // 20MB }); ``` # Balance Source: https://docs.prem.io/billing/balance Manage your organization balance and auto top-up settings. Prem API uses a **prepaid balance** model. Inference draws from your organization's balance. The cost depends on the model and its token or audio pricing. Confidential and ZDR usage share this balance. View and manage your balance in the [dashboard](https://dashboard.prem.io/billing). ## Top Up Balance You can add funds to your organization at any time in the dashboard. * **Minimum amount:** \$1 * **Payment processing:** Stripe When Stripe confirms the payment, the funds go to your balance immediately. > [!TIP] > > Keep your balance above zero to prevent interruptions. If your balance is zero, Prem API blocks new inference requests until you top up. ## Auto Top-Up Auto top-up adds funds automatically when your balance goes below a configured threshold. This helps you keep API access without interruption. To enable auto top-up, configure these settings in the dashboard: | Setting | Description | | - | - | | **Minimum Balance Threshold** | When your balance goes below this amount, the system starts an automatic top-up | | **Top Up To** | The target balance after the auto top-up completes | > [!NOTE] > > You must set a [default payment method](/billing/payment) before you enable auto top-up. ### Example This example uses a Minimum Balance Threshold of 10 USD and a Top Up To value of 100 USD: * When your balance goes below the threshold, the system automatically charges your default payment method. * The system tops up your balance to 100 USD. # Limits Source: https://docs.prem.io/billing/limits Configure monthly spending limits. ## Monthly Limit (Budget) You can set a **monthly spending limit** (budget) for your organization. It stops new inference requests once the period's spending reaches the amount you choose. Confidential and ZDR usage share this budget. Set a positive budget to limit new requests. A budget of `0` disables this check. Your tier does not set a maximum budget. When your spending gets to the limit that you set, Prem API blocks new inference requests until: * The next billing period starts (the 1st of the next month), or * You increase the limit in the [dashboard](https://dashboard.prem.io/billing) > [!NOTE] > > Your monthly spending (`period_spent`) goes to zero automatically on the **1st of each month**. ## Reasons to change your limit * **Cost protection**: prevent unexpected charges from scripts that do not stop or from integrations with an incorrect configuration * **Team budget control**: keep the spending in the budget of your organization * **Scale up**: increase the limit when your usage grows ## Budget and inference allowances The budget and balance apply to the organization across both inference families. Request, concurrency, token and audio allowances remain separate for Confidential and ZDR usage. See [Tiers](/tiers#limits-by-tier). Requests already running can take spending beyond the remaining budget. > [!TIP] > > You can change your monthly limit at any time in the dashboard. An increase of the limit is effective immediately. # Payment Source: https://docs.prem.io/billing/payment Manage payment methods. Manage your payment methods in the [dashboard](https://dashboard.prem.io/billing). Prem uses payment methods for [balance top-ups](/billing/balance) and [auto top-up](/billing/balance#auto-top-up). ## Add a payment method Add a new card in the dashboard. Stripe stores the card securely. You can use the card for subsequent transactions. ## Default payment method You can store more than one payment method. But **you must set one payment method as the default**. Prem uses the default payment method for: * Manual balance top-ups * Automatic top-ups, when your balance goes below the configured threshold > [!NOTE] > > You can change the default payment method at any time in the dashboard. # Usage Source: https://docs.prem.io/billing/usage Monitor your resource consumption and token usage. The Usage section in the [dashboard](https://dashboard.prem.io/billing/usage) gives analytics on the resource consumption of your organization. ## Select the usage view Choose **Confidential**, **ZDR**, or **Combined** to inspect either inference family or their combined usage. Select a time window from one hour to 30 days; the default is 30 days. The family selector filters analytics. Confidential and ZDR usage still draw from the same organization's balance and monthly budget. ## Usage and cost The dashboard shows request counts and spend alongside prompt, cached, completion and reasoning tokens. It also includes audio usage and streaming performance where available. Use the model, speed and API-key breakdowns to identify which workloads consume resources. Usage from keys owned by different organization members contributes to the organization's usage. > [!TIP] > > Reasoning tokens are billed according to the model's price configuration, including when they do not appear in `message.content`. See [Agents & Automation](/agents) for how to disable or bound reasoning. ## Allowances Allowances for requests, concurrency, tokens and audio are shared at the **organization and inference-family** level. More members or API keys do not increase a family's allowance. Confidential usage does not consume ZDR allowances, and ZDR usage does not consume Confidential allowances. See [Tiers](/tiers) for allowance scope, [Rate limits](/rate-limits) for enforcement and retries, and [Limits](/billing/limits) for the shared monthly budget. # Changelog & Release Notes Source: https://docs.prem.io/changelog Unified changelog and release notes for the Confidential API. ## 2026-09-24 ### Decisions (Zero Data Retention) Prem now answers typed decision questions with probabilities, powered by the new DiffusionGemma model. See [Models & Pricing](/models-and-pricing) for the price and the region. To get started, read the [Decisions guide](/guides/decisions) and the [Decisions API reference](/api-reference/zdr-decisions), or try a ready-made example in the [dashboard](https://dashboard.prem.io). ### DeepSeek V4.1 Flash (Zero Data Retention) DeepSeek V4.1 Flash is available in ZDR mode as `deepseek-v4.1-flash`. See [Models & Pricing](/models-and-pricing) for the price and the region. # Confidential Proxy Source: https://docs.prem.io/confidential-proxy Run a local proxy for supported OpenAI- and Anthropic-compatible routes. Point a compatible client at the local base URL. The **Confidential Proxy** is a local termination proxy that comes with [`@premai/api-sdk`](https://www.npmjs.com/package/@premai/api-sdk). It exposes supported **OpenAI- and Anthropic-compatible** HTTP routes on your machine. Use **SDK 2.1.0** for the [Confidential chat models](/models-and-pricing#confidential-models); they use standard attestation. See [Attestation](/attestation#released-attestation-stack) for the verification flow. For a supported OpenAI client, set the base URL to `http://127.0.0.1:8787/v1`. Anthropic clients use the same local base URL when the proxy runs in Anthropic mode. In `both` mode, use the separate prefixes documented below. > [!TIP] > > If you use the TypeScript SDK, you do not need the Confidential Proxy. > > The SDK encrypts in the same process. Use the Confidential Proxy for other languages and for existing OpenAI or Anthropic codebases. ## How it works The Confidential Proxy runs on your machine and applies the SDK's client-side encryption. It encrypts the request payload **before** network egress. The Prem API Gateway receives payload ciphertext plus operational metadata. The selected confidential runtime decrypts the request inside its Trusted Execution Environment (TEE). ```mermaid theme={"system"} flowchart LR subgraph Local["Your Machine"] A[OpenAI / Anthropic client] -->|"baseURL → 127.0.0.1:8787"| B[confidential-proxy] B -->|"encrypt"| C[Encrypted request] end subgraph Gateway["Prem API Gateway"] D[Payload ciphertext and metadata] end subgraph Enclave["Prem API Enclave (TEE)"] E[Decrypt → process → encrypt] end C --> D --> E E --> D D -->|Encrypted response| B B -->|Decrypted response| A ``` See [Encryption](/encryption) for the full cryptographic design: the XWing key exchange, the two-server model, and the threat model. ## Upgrade an existing proxy The bundled launchers can reuse an existing managed proxy without checking its SDK version. When updating the SDK, finish active requests and stop the managed proxy: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy stop ``` Then run a pinned 2.1.0 command below or restart your launcher. For a foreground process, stop it in its terminal first. After starting the new proxy, confirm that its root endpoint reports `"version": "2.1.0"`: ```bash theme={"system"} curl http://127.0.0.1:8787/ ``` Changing the launcher package alone does not upgrade a daemon already running. ## Run the server Run the Confidential Proxy directly with `bunx` or `npx`. No installation is necessary. As an alternative, install it globally: ```bash theme={"system"} # Run without installing (bun or npm) bunx -p @premai/api-sdk@2.1.0 confidential-proxy --kek "$CLIENT_KEK" npx -p @premai/api-sdk@2.1.0 confidential-proxy --kek "$CLIENT_KEK" # Or install globally, then run (confirm your global bin dir is on your PATH) npm i -g @premai/api-sdk@2.1.0 # or: bun i -g @premai/api-sdk@2.1.0 confidential-proxy --kek "$CLIENT_KEK" ``` The pinned npm commands above select SDK 2.1.0. If you use Docker, confirm the image reports that SDK version before using it for the new models. The `latest` tag is mutable. A prebuilt Docker image is available at `ghcr.io/premai-io/confidential-proxy:latest`: ```bash theme={"system"} docker pull ghcr.io/premai-io/confidential-proxy:latest # OpenAI-compatible server on port 8787 docker run -p 127.0.0.1:8787:8787 \ -e PROXY_URL=... -e ENCLAVE_URL=... \ ghcr.io/premai-io/confidential-proxy:latest \ --kek "$CLIENT_KEK" # Extra arguments go to the CLI docker run -p 127.0.0.1:8787:8787 \ -e PROXY_URL=... -e ENCLAVE_URL=... \ ghcr.io/premai-io/confidential-proxy:latest \ --kek "$CLIENT_KEK" --log-level debug ``` The image sets `HOST=0.0.0.0` and `PORT=8787`. You can override these values with environment variables or CLI flags. Use CLI flags for `--compat` and `--tls`. You cannot set these two flags with environment variables. By default, the server listens on **`http://127.0.0.1:8787`**. > [!NOTE] > > `8787` is the default in `@premai/api-sdk` and in the `confidential-claude` launcher. Port `8000` also works when you start the proxy with `--port 8000` and point every client at the same port. A client configured for `8000` cannot reach a proxy that was started without a port override, because that proxy listens on `8787`. > [!NOTE] > > Set `PROXY_URL` and `ENCLAVE_URL` to the values for your environment. Get the latest values from [`dashboard.prem.io/endpoints.json`](https://dashboard.prem.io/endpoints.json). ## Configuration Configure the Confidential Proxy with environment variables or CLI flags. Flags have precedence. ### Environment variables | Variable | Required | Default | Description | | - | - | - | - | | `ENCLAVE_URL` | Yes | - | The enclave endpoint that decrypts the data and runs inference | | `PROXY_URL` | Yes | - | The Prem API Gateway endpoint that routes encrypted payloads | | `JSON_BODY_LIMIT` | No | `32mb` | The maximum size of the request body | | `HOST` | No | `127.0.0.1` | The interface to bind | | `PORT` | No | `8787` | The port to listen on | | `CONFIDENTIAL_PROXY_LOG_LEVEL` | No | `info` | `error`, `warn`, `info`, `http`, `verbose`, `debug`, or `silly` | | `PREM_API_KEY` | No | - | A default API key. The proxy uses this key when a client does not send its own key | > [!WARNING] > > Set `PREM_API_KEY` to a default API key. The proxy applies this key when a client does not supply its own key. Each client can also send its own API key with each request. Use `Authorization: Bearer ` for OpenAI routes. Use `x-api-key: ` for Anthropic routes. The Confidential Proxy keeps one client in memory for each API key. > > `CLIENT_KEK` is a separate key. The Confidential Proxy uses it only to wrap encryption keys. It is not an API key. The current CLI does not bind the `CLIENT_KEK` environment variable to the server option. Pass the value explicitly with `--kek "$CLIENT_KEK"`. ### CLI options Foreground execution and `start` accept server options: ```bash theme={"system"} # Bind host / port confidential-proxy --host 127.0.0.1 --port 8787 --kek "$CLIENT_KEK" # Override backend endpoints confidential-proxy --proxy-url https://gateway.prem.io --enclave-url https://conf-engine.prem.io --kek "$CLIENT_KEK" # Pass the client KEK from the environment # The value must be 32 bytes encoded as 64 hexadecimal characters. confidential-proxy --kek "$CLIENT_KEK" # Raise the JSON body size limit confidential-proxy --json-body-limit 64mb --kek "$CLIENT_KEK" ``` ## Compatibility modes Use `--compat` to select the API surface: | Mode | Routes | Description | | - | - | - | | `openai` | `/v1/*` | The OpenAI-compatible API only | | `anthropic` | `/v1/*` | The Anthropic-compatible Messages API only | | `both` | `/openai/v1/*` and `/anthropic/v1/*` | The two APIs together, each with a separate prefix | ```bash theme={"system"} # OpenAI only (default surface) confidential-proxy --compat openai --kek "$CLIENT_KEK" # Anthropic only confidential-proxy --compat anthropic --kek "$CLIENT_KEK" # Both, with custom prefixes confidential-proxy --compat both --openai-prefix /openai --anthropic-prefix /anthropic --kek "$CLIENT_KEK" ``` In `both` mode, the Confidential Proxy serves the two APIs under separate prefixes. This stops route conflicts. Set the base URL to `http://127.0.0.1:8787/openai/v1` for OpenAI clients. Set it to `http://127.0.0.1:8787/anthropic/v1` for Anthropic clients. The Confidential Proxy translates each Anthropic Messages request into the format for confidential inference. It then returns the response as Anthropic SSE events. ## Connect a client ### OpenAI Set the base URL to `http://127.0.0.1:8787/v1`. If you use `--compat both`, set it to `http://127.0.0.1:8787/openai/v1`. Send your API key as a bearer token: > [!TIP] > > See [OpenAI-compatible clients](/guides/openai-compatible-clients) for supported routes, configuration patterns, production controls, and compatibility limits. ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer your-api-key" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "messages": [{"role": "user", "content": "Hello!"}], "stream": false }' ``` As an alternative, use the OpenAI SDK in Node.js: ```typescript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY!, baseURL: "http://127.0.0.1:8787/v1", }); const stream = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Count to 10" }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` The same pattern applies to all other languages. This is a Python example: ```python theme={"system"} from openai import OpenAI client = OpenAI( api_key="your-api-key", base_url="http://127.0.0.1:8787/v1", ) response = client.chat.completions.create( model="deepseek-v4.1-flash-1017", messages=[{"role": "user", "content": "Hello, privately."}], ) print(response.choices[0].message.content) ``` ### Anthropic Set the base URL to `http://127.0.0.1:8787/v1`. If you use `--compat both`, set it to `http://127.0.0.1:8787/anthropic/v1`. Authenticate with `x-api-key`. Send the `anthropic-version` header: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/messages \ -H "x-api-key: your-api-key" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello!"}] }' ``` Add `"stream": true` for incremental responses: ```bash theme={"system"} curl -N http://127.0.0.1:8787/v1/messages \ -H "x-api-key: your-api-key" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "max_tokens": 1024, "messages": [{"role": "user", "content": "Count to 10"}], "stream": true }' ``` The Anthropic surface supports system prompts, tool use, image inputs, stop sequences, `temperature`, and `top_p`. Streaming responses follow the Anthropic SSE format (`message_start`, `content_block_start`, `content_block_delta`, `content_block_stop`, `message_delta`, `message_stop`). > [!TIP] > > See [Anthropic-compatible clients](/guides/anthropic-compatible-clients) for translation behavior, model substitution, token estimates, tool handling, and known limits. ### Agent harnesses Use a dedicated guide for each harness. The provider schema, protocol selection, tool boundary, and startup command differ. > [card] [OpenCode](/guides/opencode) > > Configure an OpenAI-compatible provider in a project. > [card] [Claude Code](/guides/claude-code) > > Launch Claude Code through the bundled Anthropic adapter. > [card] [OpenClaw](/guides/openclaw) > > Configure a custom Chat Completions provider. > [card] [Hermes Agent](/guides/hermes) > > Use a named custom provider with an explicit Chat Completions transport. > [card] [Goose](/guides/goose) > > Point the built-in OpenAI provider at the local proxy. > [card] [Loupe](/guides/loupe) > > Review the current boundary around Loupe's embedded Claude Code workers. > [card] [Cursor compatibility](/guides/cursor) > > Understand why Cursor's base URL override is not a confidential local path. > [card] [Codex CLI compatibility](/guides/codex-cli) > > Review the current Responses API protocol mismatch. ### ZDR alternative ZDR is a separate, non-confidential inference mode. It does not use the Confidential Proxy, client KEK, or attestation path. Use the [ZDR overview](/zdr/overview) for the ZDR setup. ZDR uses `PREM_API_KEY` at `https://gateway.prem.io/openai`; the Confidential API uses `PREM_API_KEY`, a client KEK, and the local proxy. Their data-handling properties are not interchangeable. ### Claude for Microsoft 365 The Confidential Proxy can be the gateway for the [Claude for Microsoft 365 add-in](https://support.claude.com/en/articles/13945233-use-claude-for-microsoft-365-with-third-party-platforms). The add-in uses HTTPS and CORS. Start the proxy with these flags: > [!TIP] > > See [Claude for Microsoft 365](/guides/claude-microsoft-365) for tenant setup, key custody, network placement, acceptance tests, and security boundaries. ```bash theme={"system"} confidential-proxy \ --host 0.0.0.0 --port 8787 \ --compat anthropic \ --kek "$CLIENT_KEK" \ --default-model deepseek-v4.1-flash-1017 \ --cors-origin https://pivot.claude.ai \ --tls --tls-cert ./cert.pem --tls-key ./key.pem ``` > [!NOTE] > > The add-in cannot connect to `127.0.0.1` on macOS. macOS prevents cross-origin browser requests to loopback addresses. Run the proxy on a different machine on your network, or use a container with its own network interface. Point the add-in at that hostname. ## Run the proxy as a daemon By default, the Confidential Proxy runs in the foreground. The CLI can also manage it as a background daemon. | Command | Description | | - | - | | `confidential-proxy` | Run in the foreground, attached to the terminal | | `confidential-proxy start` | Start the server as a background daemon | | `confidential-proxy stop` | Stop the daemon with a graceful shutdown | | `confidential-proxy status` | Show if the daemon runs and is reachable | **1. start** The `start` command does these steps: * It checks for a daemon that is in operation. It does not start a second daemon. * It spawns itself as a child process. It sends the logs to the log file that you configure. * It polls the HTTP endpoint until the server is reachable. * It then exits and the daemon continues to run. **2. stop** The `stop` command requests authenticated graceful shutdown, then polls for up to 10 seconds. If the daemon remains reachable while draining requests, the command reports failure; it does not force-kill the process. Check its status before starting a replacement. **3. status** The `status` command checks if the process is alive and if the HTTP endpoint is reachable. Daemon options depend on the command: | Option | Commands | Default | Description | | - | - | - | - | | `--state-file` | `start`, `stop`, `status` | `/proxy.state.json` | Path to the managed daemon's state file; use the same path for its lifecycle commands | | `--log-file` | `start` | Default proxy log file | Redirect the daemon's stdout/stderr to this file | | `--log-level` | Foreground, `start` | `info` | Log verbosity (`error` … `silly`) | | `--shutdown-timeout` | Foreground, `start` | `30000` | Maximum milliseconds the server waits for in-flight requests during graceful shutdown | > [!WARNING] > > Launcher debug logs can include command arguments containing the KEK. Keep logs private, avoid debug logging with production keys, and remove credentials and keys before sharing diagnostic output. ```bash theme={"system"} # Start in the background, then confirm it's up confidential-proxy start --compat openai --kek "$CLIENT_KEK" confidential-proxy status # Stop it when you're done confidential-proxy stop ``` ## Next steps > [card] [Quickstart](/quickstart) > > The step-by-step guide to get your first request working. > [card] [Developer Experience](/developer-experience) > > The two ways to integrate: the TypeScript SDK and the Confidential Proxy. > [card] [Chat completions](/api-reference/chat-completions) > > The chat API in detail, with streaming and vision payloads. > [card] [Encryption](/encryption) > > The key exchange and the end-to-end encryption in detail. > [card] [Agents & Automation](/agents) > > Running the proxy behind an unattended agent or automation? Start here. > [card] [OpenCode](/guides/opencode) > > Connect OpenCode to the encrypted OpenAI-compatible route. > [card] [Claude Code](/guides/claude-code) > > Launch Claude Code through the encrypted Anthropic-compatible route. > [card] [OpenAI-compatible clients](/guides/openai-compatible-clients) > > Connect existing OpenAI SDKs and applications. > [card] [Anthropic-compatible clients](/guides/anthropic-compatible-clients) > > Use the Messages API shape with explicit compatibility limits. > [card] [Claude for Microsoft 365](/guides/claude-microsoft-365) > > Deploy the proxy as a Microsoft 365 add-in gateway. > [!NOTE] > > The SDK also includes `confidential-claude`. It launches Claude Code with the local Anthropic-compatible proxy and forwards Claude Code's arguments. See [Claude Code](/guides/claude-code) for the exact environment variables, model picker, stop command, and plaintext boundary. # Contact Us Source: https://docs.prem.io/contact-us Get help with integrations, billing, APIs, or anything else. **Live Chat:** This is the fastest option. Open the dashboard. Click the support button in the header. Select "Live Chat". Prem usually replies in a few minutes. **Email:** Send an email to `support@premai.io` for questions that need more detail. Prem replies within 1 business day. **Platform status:** Check the live platform availability on [status.premai.io](https://status.premai.io). ## Product-specific help > [card] [Zero Data Retention](/zdr/overview) > > Read the [ZDR overview](/zdr/overview) to get set up. ZDR is generally available. Create an API key in the [dashboard](https://dashboard.prem.io/api-keys). > [card] [Confidential API](/quickstart) > > Read the [Prem API quickstart](/quickstart) to get set up. For access, use Live Chat or email. # Data Retention Source: https://docs.prem.io/data-retention What Prem API stores, what it never stores, and how you can verify the policy. > [!NOTE] > > **The policy in one sentence:** Prem API does not store your prompts, completions, or audio after it returns the response. The platform keeps zero inference content. > [!NOTE] > > This page tells you about **confidential inference**. The [Zero Data Retention](/zdr/overview) mode gives the same result, but the basis is different. Confidential inference stops retention with cryptography and hardware. ZDR stops it with a contract and with operational controls. See [ZDR security boundary](/zdr/security-boundary). ## What Prem API never stores The platform does not retain inference content: * **Prompts and messages**: not stored after the response * **Completions and model output**: not stored after the response * **Audio for transcription and translation**: not stored after the response The encrypted inference endpoints are named RVENC: raw **volatile** encrypted. Your content exists inside the enclave only in volatile memory, for the duration of the request. See [How It Works](/how-it-works) for the request lifecycle. ## What Prem API stores Some data is necessary to operate the platform: * **Files that you upload**: The platform stores files that you upload to the file endpoints. The files are encrypted with your keys. Only you can decrypt them. You can delete them at any time. See [Encryption](/encryption). * **Request metadata**: The gateway records the time of each request, the payload size, the API key, and the rate limit counters. Prem uses this metadata for billing, rate limits, and analytics. The metadata does not include your content. See the [Security Model](/security-model). * **Error traces**: Error responses include a `support_id`. Prem keeps the trace for that identifier for up to one week. See [Errors](/errors). ## Why you do not have to trust this page Most providers publish a retention policy and ask you to trust it. Prem API adds two verifiable protections: 1. **The platform cannot read your content.** Your device encrypts all content before it leaves. The gateway routes only encrypted bytes. Decryption happens only inside the sealed enclave. A stored copy of your traffic would be useless ciphertext. See [Encryption](/encryption). 2. **You can verify hardware evidence and release measurements.** Reticle applies signed Trustbase policies and references by default. See [Attestation](/attestation). ## Zero Data Retention mode [ZDR](/zdr/overview) is the standard inference mode. Prem sends each ZDR request to a trusted partner. The partner operates under a zero-retention agreement. The partner keeps no prompt, completion, or audio content. The partner uses no content to train a model. The result for retention is the same. The assurance is different. In ZDR mode your content is plaintext at the Prem API Gateway and at the partner. There is no attestation evidence for you to examine. Read [ZDR security boundary](/zdr/security-boundary) before you choose that mode for sensitive data. > [!NOTE] > > Questions about retention, or requirements for a specific agreement? Contact us at [support@premai.io](mailto:support@premai.io). # Developer Experience Source: https://docs.prem.io/developer-experience What it is like to build on Prem API: SDK integration and OpenAI compatibility. > [!NOTE] > > **You do not need encryption knowledge.** The encryption layer is not visible in your application code. If you used the OpenAI API before, you know how to use Prem API. The SDK does all cryptography automatically. You write normal API calls and you get normal responses. ## Two Ways to Integrate ### Option 1: Prem API TypeScript SDK (Recommended) Install the SDK. Use it like an OpenAI client: ```typescript theme={"system"} import { createRvencClient } from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, // Your master key. You generate it, we never see it }); // This looks exactly like an OpenAI call, because it is const chat = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Summarize this quarterly report." }, ], stream: true, }); for await (const chunk of chat) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` The SDK does these steps for you: * It encrypts your messages before it sends them. * It does a secure key exchange with the enclave. * It decrypts each streaming chunk when the chunk arrives. You do not see these steps. Your code looks like an OpenAI integration. ### Option 2: Confidential Proxy (Any Language) The SDK includes the Confidential Proxy, a local server that does all encryption for you. Use it for Python, Go, Java, or other languages with an OpenAI-compatible client library: ```bash theme={"system"} # Start the local proxy (one command) bunx -p @premai/api-sdk@2.1.0 confidential-proxy --kek "$CLIENT_KEK" ``` Then point your existing code at `localhost`: ```python theme={"system"} from openai import OpenAI # Your existing OpenAI code. Just change the base URL client = OpenAI( base_url="http://localhost:8787/v1", api_key="your-api-key", ) response = client.chat.completions.create( model="deepseek-v4.1-flash-1017", messages=[{"role": "user", "content": "Hello, privately."}], ) ``` You make **zero code changes** to your application logic. The Confidential Proxy encrypts outbound requests and decrypts responses automatically. See [Confidential Proxy](/confidential-proxy) for the full configuration and Anthropic support. ## What You Can Do ### Chat with AI Models The chat API is OpenAI-compatible. It includes these features: | Feature | Details | | - | - | | **Streaming** | Output in real time, word by word. Prem API encrypts each chunk separately | | **JSON mode** | Structured output for reliable parsing | | **System messages** | Control the behavior and personality of the model | | **Multi-turn conversations** | Full conversation history and context management | | **Audio transcription** | Convert speech to text with the currently enabled Deepgram model | | **Audio translation** | Route exists, but no enabled translation model was returned on August 4, 2026 | ## Error Handling Prem API uses standard HTTP status codes with structured error responses: | Code | What It Means | What to Do | | - | - | - | | 400 | Invalid request format | Check your input against the API spec | | 401 | Invalid API key | Make sure that your API key is correct and active | | 403 | Insufficient permissions | Check the scopes of your API key | | 429 | Rate limited | Use exponential backoff (examples in [Rate Limits](/rate-limits)) | | 503 | Temporarily unavailable | Wait, then send the request again | Each error includes a `support_id`. Give this ID to the Prem team to help with debugging. ## Rate Limits Each tier has separate Confidential and ZDR limits. All keys and users in an organization share each family's limits. Every endpoint in a family counts toward the same limits: | Dimension | What It Limits | Why | | - | - | - | | **Request burst and RPM** (Requests per minute) | The request capacity and the refill rate | Stops too many requests at one time | | **Concurrency** | The number of requests that run or wait at one time | Limits simultaneous work | | **TPM** (Tokens per minute) | Total token throughput | Manages inference capacity | | **Audio seconds per minute** | Total audio duration that you transcribe or translate | Manages transcription capacity | Your organization's payment history determines its tier. A tier can have different limits for Confidential and ZDR. See [Tiers](/tiers) for limits and allowance scope. See [Rate Limits](/rate-limits) for retry instructions and code examples. > [!NOTE] > > See the [Quickstart](/quickstart) for the step-by-step setup. > See the [Guides](/guides/chat-completion) for examples that you can copy. > If you're building an unattended agent or automation on top of Prem API, see [Agents & Automation](/agents) for the config and operational gotchas that matter at scale. # Encryption Source: https://docs.prem.io/encryption Learn about the end-to-end encryption architecture that protects your data. Prem API uses **end-to-end encryption** (E2EE) to make sure that your data stays private and secure. All encryption occurs on your device. Your plaintext data does not leave your device without encryption. Prem cannot read your data. ## Zero-Knowledge Architecture The platform operates on a **zero-knowledge** principle: > [card] Client-Side Encryption > > Your device encrypts all data before transmission > [card] No Plaintext Access > > The servers see only encrypted data, never your actual data > [card] You Control the Keys > > You generate the encryption keys, and you store them only on your side > [card] Post-Quantum Security > > The encryption protects your data against current threats and future quantum computing threats ## How It Works The encryption architecture uses a **two-server model** for defense in depth: ```mermaid theme={"system"} flowchart LR subgraph Client["Your Device"] A[Plaintext Data] --> B[Encryption] B --> C[Encrypted Data] K[Your Keys] --> B H[Encrypted Response] --> I[Decryption] K --> I I --> J[Plaintext Response] end subgraph Proxy["Prem API Gateway"] D[Encrypted Data Only] end subgraph Enclave["Prem API Enclave"] E[Decrypt] F[Process] G[Encrypt Response] E --> F --> G end C --> D D --> E G --> D D --> H ``` ### Prem API Gateway vs Prem API Enclave | Component | What It Sees | Purpose | | - | - | - | | **Prem API Gateway** | Only encrypted data | Stores and routes encrypted data. It never sees plaintext | | **Prem API Enclave** | Decrypted data | Decrypts requests, processes them, and encrypts responses in an isolated environment | > [!NOTE] > > The **Prem API Gateway** is a secure gateway that **never has access to your plaintext data**. It only sends encrypted payloads forward to the Prem API Enclave. If an attacker gets control of the Prem API Gateway, the attacker sees only encrypted data. The **Prem API Enclave** operates in a **Trusted Execution Environment (TEE)**. A TEE is an isolated environment with hardware protection. In the TEE: * Decryption occurs in a secure environment * Processing occurs in full isolation * The enclave encrypts the responses before the responses leave * Server operators cannot access the plaintext, because no operator access mechanism exists in the images ### Key Types * **Key Encryption Key (KEK)**: Your master key (32 bytes). It protects all other keys. It does not leave your device without encryption. * **Data Encryption Key (DEK)**: A unique key for each file (32 bytes). Each file gets its own key for isolation. * **RAG DEK**: A persistent key (32 bytes). The system uses it for encrypted document search operations. * **CONNECTOR DEK** - A persistent key (32 bytes). The enclave uses it to decrypt connectors. * **KID (Key Identifier)**: The system derives the KID from your KEK. The KID identifies your keys on the server and does not show the KEK. The Prem Enclave generates its own key at boot. The Enclave uses this key for the XWing key exchange with the client. The key does not leave the enclave. This key is separate from your KEK. > [!NOTE] > > Your master key (KEK) does not leave your device without encryption. The SDK wraps the file keys (DEKs) with your KEK before transmission. The server stores the RAG DEK wrapped with your KEK. For RAG operations, the SDK encrypts the file DEKs and the RAG DEK with a temporary shared secret from the XWing key exchange. Then the SDK sends these keys to the enclave. ## Cryptographic Algorithms Prem API uses modern, proven cryptographic algorithms: | Algorithm | Type | Purpose | | - | - | - | | **XChaCha20-Poly1305** | AEAD | Encrypts all your data with authentication | | **AES-KWP** | Key Wrap | Securely wraps the file keys with your master key | | **XWing** | Hybrid KEM | Post-quantum secure key exchange | ### Post-Quantum Security with XWing **XWing** is a hybrid key encapsulation mechanism — think of it as **post-quantum ECDH**. It serves the same role as a classical Diffie-Hellman key exchange (agreeing on a shared secret over an untrusted channel), but stays secure even against a quantum adversary. It combines two algorithms for maximum security: ```mermaid theme={"system"} flowchart LR subgraph XWing["XWing Hybrid KEM"] A["ML-KEM768 (Post-Quantum)"] --> C["Combined Shared Secret"] B["X25519 (Classical)"] --> C end C --> D["XChaCha20-Poly1305 Encryption"] ``` * **ML-KEM768 (Kyber)**: A NIST-standardized quantum-resistant algorithm * **X25519**: A proven elliptic curve algorithm This hybrid method makes sure that your data is safe against current attacks and future quantum computers. If an attacker breaks one algorithm, the other algorithm keeps your data secure. > [!NOTE] > > Sufficiently powerful quantum computers will break traditional encryption, for example RSA and standard elliptic curves. XWing protects against "Harvest Now, Decrypt Later" attacks. In these attacks, adversaries store encrypted data today. They decrypt the data when quantum computers become powerful. ## File Encryption Each file that you upload goes through a secure encryption process: ```mermaid theme={"system"} flowchart TD A[Original File] --> B[Generate Random File Key] B --> C[Encrypt File Content] B --> D[Encrypt Metadata] C --> E[Encrypted File] D --> F[Encrypted Metadata] G[Your Master Key] --> H[Wrap File Key] B --> H H --> I[Wrapped File Key] E --> J[Upload to Server] F --> J I --> J ``` ### Encryption Process **1. Generate the file key** The SDK creates a unique random 32-byte key for this specific file **2. Encrypt the content and metadata** The SDK encrypts the file content and the metadata (filename, type) with XChaCha20-Poly1305 **3. Wrap the file key** The SDK encrypts the file key with your master key. It uses AES-KWP **4. Upload the encrypted data** The SDK sends only encrypted data and wrapped keys to the server ### Decryption Process When you get a file: 1. **Download** the encrypted file and the wrapped key from the server 2. **Unwrap** the file key with your master key 3. **Decrypt** the file content and the metadata ## RAG Encryption For encrypted document search, Prem API uses a **secure key exchange scheme**. This scheme permits AI-powered search and keeps your data private: ```mermaid theme={"system"} flowchart TD subgraph Client["Your Device"] A[XWing Key Exchange] --> B[Generate Shared Secret] C[File Key DEK] --> D[Encrypt with Shared Secret] D --> E[Encrypted File Key] F[RAG Key] --> G[Encrypt with Shared Secret] G --> H[Encrypted RAG Key] B --> D B --> G end subgraph Enclave["Prem API Enclave"] I[Decrypt with Shared Secret] J[Decrypt File Key] K[Decrypt RAG Key] L[Decrypt File Content] M[Build Search Index] I --> J I --> K J --> L K --> M L --> M end E --> I H --> I ``` ### How RAG Search Works **1. Key Exchange** When you index files for search: * The XWing key exchange establishes a shared secret with the enclave * The SDK encrypts the file key (DEK) with the shared secret * The SDK encrypts the RAG key with the shared secret * The SDK sends both encrypted keys to the enclave **2. Search Query** When you search: * The SDK encrypts your query on your device * The SDK establishes a new XWing key exchange * The SDK sends the encrypted query to the enclave **3. Secure Processing** Inside the secure enclave: * The shared secret decrypts the RAG key and the file keys * The enclave decrypts the applicable documents with their file keys * The enclave searches the documents in isolation * The enclave encrypts the results before the results leave **4. Results** The enclave sends the encrypted results back to your device. Your device decrypts the results locally > [!NOTE] > > The Prem API Gateway never sees your search queries or your document contents. All processing occurs in the isolated Prem API Enclave. ## Secure Key Exchange For chat completions and tool operations, the SDK establishes secure communication with the **XWing key exchange**: ```mermaid theme={"system"} sequenceDiagram participant Client as Your Device participant Enclave as Prem API Enclave participant Proxy as Prem API Gateway Note over Client,Enclave: 1. Key Exchange Client->>Enclave: Request public key Enclave-->>Client: Public key Note over Client: 2. Generate Session Key Client->>Client: Create shared secret using XWing Note over Client: 3. Encrypt & Send Client->>Client: Encrypt request Client->>Proxy: Send encrypted data Note over Proxy: Only sees encrypted bytes Proxy->>Enclave: Forward encrypted payload Note over Enclave: 4. Process Securely Enclave->>Enclave: Decrypt and process Enclave->>Enclave: Encrypt response Enclave-->>Proxy: Encrypted response Proxy-->>Client: Forward encrypted response Client->>Client: Decrypt response ``` ## Best Practices > [card] Secure Your Master Key > > Store your master key (KEK) securely and keep backups. The KEK is critical. > [card] Regular Backups > > Make backups of your keys in multiple secure locations. If you lose your master key, you lose your data permanently. > [card] Never Share Keys > > Do not share your encryption keys. Do not transmit them in plaintext. > [card] Verify Integrity > > The system verifies data integrity automatically. Examine all authentication errors. ## Output Integrity Protection For each request, the system does a fresh XWing encapsulation with the attested enclave public key. The encapsulation gives a shared secret unique to that request. The client sends a random nonce. The cipher needs a unique nonce for each encryption. The enclave **encrypts** and **authenticates** the response with XChaCha20-Poly1305 under the per-request secret. The proxy cannot change the response **(modification)**. Without the per-request secret, it cannot produce a valid authentication tag, so it cannot substitute a different model output **(substitution)**. The proxy cannot replay a previous response either **(replay)**. The client chooses a fresh random XChaCha20 nonce for each request, and the enclave binds the response to that nonce under the per-request secret. A response from an earlier request carries a different nonce and a different ephemeral secret, so its authentication tag fails to verify against the current request. The client rejects anything that does not match. The binding is part of the ephemeral key. The binding has the security property of a signed nonce. > [!NOTE] > > The client SDK does all of this for you. It generates the nonce, performs the XWing encapsulation, and verifies the authentication tag on every response automatically. # Errors Source: https://docs.prem.io/errors Learn how API errors work, what status codes mean, and how to handle them properly. Our API returns consistent, structured errors. These errors help you debug and recover from problems in development and in production. ## Error types & status codes The API uses standard HTTP status codes to show the success or failure of a request. Errors always return: * An applicable HTTP status code (`4xx` or `5xx`) * A JSON response body that contains: * `status`: the HTTP status code * `error`: a human-readable error message * `support_id`: a unique reference ID that you can give to support for debugging > [!WARNING] > > Contact us in the week after the error occurs. We keep the `support_id` fields in our systems only for **up to a week**. After that time, they can be lost. Example error response: ```json theme={"system"} { "status": 403, "error": "Access denied. You do not have permission to perform this action.", "support_id": "support_018ecfc3-bfa6-7b95-a29c-bd8fc3f5b2c6" } ``` > [!TIP] > > The `support_id` is a traceable identifier in the format `support_{uuidv7}`. The API includes it in every response, successful or not. If you find a problem, give this ID to our support team. This helps us investigate quickly and accurately. ## Common error codes | Code | Description | | - | - | | `400` | **Bad Request**: The request was malformed or contained invalid parameters. | | `401` | **Unauthorized**: Authentication failed. Your API key may be missing or incorrect. | | `403` | **Forbidden**: You are authenticated, but you do not have permission for the requested action. | | `404` | **Not Found**: The requested resource does not exist. | | `406` | **Not Acceptable**: The API does not support the requested response format (JSON is required). | | `429` | **Too Many Requests**: The request rate, concurrency limit, or model capacity stopped the request. Read the error before you retry. The `Retry-After` header is optional. | | `500` | **Internal Server Error**: An unexpected error occurred on our side. These are rare. | | `503` | **Service Unavailable**: The system is temporarily offline (e.g., during maintenance). | ## Rate limits If your application sends too many requests in a short period, you can receive a 429 Too Many Requests error. These sources can apply a rate limit: * The infrastructure of Prem API * Cloudflare, our edge network These responses always include: * The HTTP status code 429 * A JSON response with status, error, and support\_id * An optional Retry-After header or field that shows when you can try again For a temporary limit, use a fixed maximum number of retries. Obey `Retry-After` when the response has this header. A request window with zero capacity blocks requests in its inference family. An empty window with zero refill blocks requests until its policy changes. Both return `429` with `Inference request allowance exhausted. Contact us for higher limits.` and no `Retry-After`. Do not retry this response automatically. Wait until the policy changes. > [!WARNING] > > Not every `429` follows this shape. > A rate limit upstream of Prem can return a `429` status with a generic body and no `Retry-After` header. > Read the HTTP status and the error details. Use exponential backoff with jitter for temporary limits when the response has no `Retry-After` header. Set a maximum number of retries. > See [Rate limits](/rate-limits#non-standard-429-responses). > [card] [Rate limits](/rate-limits) > > Read the rate limit specifications, how they operate, and how to increase them. ## Best Practices * Always check the status and error fields in responses, also for non-200 statuses. * Log the `support_id` for every request. Show it in error reports. This helps us help you faster. * Handle `5xx` errors safely with retries and exponential backoff. * Check authentication for `401` and `403` errors. Make sure that your API key is valid and has the required scopes. * Wait before you retry a temporary `429` error. Stop automatic retries when the error says that the request allowance is exhausted. ## Tips to debug errors * Use tools such as curl, Postman, or HTTP clients with logs to examine the full request and response cycles. * Make sure that the request goes to the correct endpoint with the correct HTTP method (`GET`, `POST`, etc.). * Make sure that your request body matches the expected structure and content types (e.g., `application/json`). * Refer to the [Authentication](/authentication) and [API Keys](/api-keys) pages for details about access. If the problem continues, contact [support@premai.io](mailto:support@premai.io). Include the `support_id` from the error response. This helps us solve the problem quickly. ## SDK error handling The TypeScript SDK surfaces errors from the attestation gate separately from HTTP API errors. When attestation fails, the SDK throws an `AttestationError` and exposes helpers to inspect it and get a user-safe message. See [Attestation error handling](/attestation#attestation-error-handling) for the full guide. # Glossary Source: https://docs.prem.io/glossary Definitions of the terms that the Prem API documentation uses. This page defines the terms that the Prem API documentation uses. Each page uses these terms with these exact meanings. ## Inference mode terms * **Inference mode**: The processing path for a request. The Prem API has two modes: confidential inference and Zero Data Retention. Each mode has its own routes, its own model catalog, and its own security boundary. * **Confidential inference**: The mode that encrypts your payload on your device. Only a sealed enclave can decrypt it. The routes start with `/rvenc`. See [Security Model](/security-model). * **ZDR (Zero Data Retention)**: The standard mode. Prem sends an OpenAI-compatible request to a trusted partner, and the partner keeps no content. The routes start with `/openai`. Your content is plaintext at the gateway and at the partner. See [ZDR overview](/zdr/overview). * **Standard inference**: The name for the ZDR mode in the analytics and the prices. * **Trusted partner**: An inference operator that gives ZDR capacity under a zero-retention agreement. Prem does not name its partners in this documentation. ## Platform terms * **Prem API**: The end-to-end encrypted, OpenAI-compatible API for confidential AI inference. * **Prem API Gateway**: The service that receives API requests. It authenticates each request and sends it to the correct service. It records the usage for billing. For Confidential inference, it receives encrypted content and operational metadata. For ZDR inference, it receives plaintext content. * **Enclave**: The sealed environment that decrypts your request, runs the AI model, and encrypts the response. The enclave runs inside a Trusted Execution Environment. * **Confidential Proxy**: A local proxy from the SDK. It exposes OpenAI-compatible and Anthropic-compatible routes. It encrypts and decrypts all traffic for you. See [Confidential Proxy](/confidential-proxy). * **RVENC**: Raw volatile encrypted. The name of the encrypted inference endpoints, for example `/rvenc/chat/completions` and `/rvenc/models`. * **Decisions**: Typed questions about a piece of context, answered with probabilities. Served over a TypeSafe-compatible API. See [Decisions](/guides/decisions). * **TypeSafe-compatible API**: The request and response format of Decisions. A state, a map of typed questions, and one distribution per question. The official TypeSafe client works against it. * **Question type**: The kind of a Decisions question: `choice`, `noul`, or `score`. * **Noul**: A Decisions question type that answers yes or no. The answer is a single probability. ## Hardware and attestation terms * **TEE (Trusted Execution Environment)**: A hardware-isolated environment. The processor encrypts the memory of the environment and blocks access from the outside. See [Security Model](/security-model). * **CVM (Confidential Virtual Machine)**: A virtual machine with hardware-encrypted memory. Prem API uses AMD SEV-SNP and Intel TDX technology for CVMs. * **Attestation evidence**: A hardware-signed report or token that carries measurements and security claims. A verifier authenticates the evidence and applies a policy before accepting the runtime. See [Attestation](/attestation). * **Nonce**: A random challenge value that you send with an attestation request. The report contains your nonce. This proves that the report is fresh and not a replay. * **TCB (Trusted Computing Base)**: The firmware and software that the attestation report measures. The TCB version shows the firmware and microcode versions, so you can confirm the security patch levels. ## Key and encryption terms * **KEK (Key Encryption Key)**: Your master key. The current SDK expects 32 bytes encoded as 64 hexadecimal characters. You generate and keep it. It wraps other keys. See [Encryption](/encryption). * **DEK (Data Encryption Key)**: A unique key for one file (32 bytes). Each file gets its own DEK for isolation. * **DEK store**: The local store that holds your wrapped DEKs. Make a backup of it. If you lose it, you lose access to your uploaded files. * **RAG DEK**: A persistent key (32 bytes) for encrypted document search operations. * **KID (Key Identifier)**: An identifier that the system derives from your KEK. It identifies your keys on the server and does not show the KEK. * **XWing**: The hybrid key exchange that Prem API uses. It combines ML-KEM768 and X25519. * **ML-KEM768 (Kyber)**: A NIST-standardized quantum-resistant key encapsulation algorithm. * **X25519**: A proven elliptic curve key exchange algorithm. ## Account and API terms * **API key**: Your authentication credential. Prem issues API keys at the organization level. You can limit an API key with scopes and IP restrictions. See [API Keys](/api-keys). * **Scope**: A permission on an API key. A scope defines which parts of the API the key can access, for example `chats.completion`. * **Organization**: The account level that owns API keys, rate limits, and billing. * **Tier**: The usage level of your organization (`BASE`, `TIER_1`, `TIER_2`, `TIER_3`). The tier controls your rate limits. See [Tiers](/tiers). * **Idempotency key**: A header value that makes a retry safe. The API executes a request with a known key only once in a 24-hour period. > [!NOTE] > > If a term is missing from this page, contact us at [support@premai.io](mailto:support@premai.io). # Anthropic-compatible clients Source: https://docs.prem.io/guides/anthropic-compatible-clients Connect a Messages API client to Prem API through the Confidential Proxy. Does your app already talk to the Anthropic Messages API? Then you can point it at Prem instead. You change one setting: the base URL. Prem runs the model inside a secure enclave. Your prompts stay private on the way there. You connect through a small helper on your machine: the **[Confidential Proxy](/confidential-proxy)**. > [!WARNING] > > "Anthropic-compatible" describes the shape of the requests. It does not mean Anthropic hosts the request. It does not mean a Claude model runs behind it. ## What the proxy does * Accepts the client's Anthropic Messages request on your machine. * Translates and encrypts the request before network egress. * Sends ciphertext and required metadata through the Prem API Gateway. * Decrypts the enclave response locally and returns Anthropic message objects or Server-Sent Events (SSE). ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] C["Anthropic-compatible client"] -->|"Messages request"| A["Anthropic adapter"] A -->|"Translate request"| P["Confidential Proxy"] end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Route encrypted payload"| E["Prem API Enclave
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"Messages response and SSE events"| C ``` Your app and the Confidential Proxy stay on your machine. The proxy translates your Messages request into Prem's format, then seals it. The Prem API Gateway sees only the sealed message. The Prem API Enclave opens it inside a Trusted Execution Environment (TEE). The proxy does two translations for you: 1. It changes your Messages request to a chat request for the Prem API. 2. It changes the reply to Anthropic message objects or Server-Sent Events (SSE). ## What you can connect You can connect any client that lets you set a custom base URL. The proxy gives your app these routes: | Method | Route | What it does | | - | - | - | | `POST` | `/v1/messages` | Creates a message, with or without streaming. | | `POST` | `/v1/messages/count_tokens` | Returns an estimated input token count. | | `GET` | `/v1/models` | Lists the models your account can use. | | `GET` | `/v1/models/:model_id` | Gets one model. | Send the Prem API key with `x-api-key` or with `Authorization: Bearer`. The proxy uses that value as your Prem API key. ## Before you start Get these four things ready: * **An app** that lets you set a custom Anthropic base URL. * **A Prem API key.** This proves who you are. See [API Keys](/api-keys). * **A client Key Encryption Key (KEK).** This is a master key that protects your other keys. * **A model** that your Prem account can use. See [Models & Pricing](/models-and-pricing). > [!NOTE] > > The API key and the KEK are two different secrets. The API key handles sign-in, limits, and billing. The KEK protects your encryption keys. Keep both safe. ## 1. Set your secrets Open a terminal. Set these values in the terminal that runs the proxy: ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Do you not have a KEK yet? Make one, one time only: ```bash theme={"system"} openssl rand -hex 32 ``` Store the KEK in a secret manager. Keep a backup. Use the **same** KEK every time. Do not make a new one each time you start the proxy. > [!NOTE] > > `PROXY_URL` and `ENCLAVE_URL` show the current default endpoints. Check the [Prem dashboard](https://dashboard.prem.io) if the endpoints change. ## 2. Start the Confidential Proxy Start the proxy in Anthropic mode. Keep this terminal open while you work: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat anthropic \ --kek "$CLIENT_KEK" ``` The proxy now listens at `http://127.0.0.1:8787`. Your app adds `/v1/messages` to that base URL. Do you need one proxy for both Anthropic and OpenAI apps? Start it in `both` mode: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat both \ --kek "$CLIENT_KEK" ``` In `both` mode, the Anthropic base URL is `http://127.0.0.1:8787/anthropic`. Your app then adds `/v1/messages`. ## 3. Point your app at the proxy List available models: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "x-api-key: $PREM_API_KEY" \ -H "anthropic-version: 2023-06-01" ``` Use a returned model ID in the Messages request. The Anthropic adapter returns the requested alias in its `model` field. It does not currently expose the backend-resolved model ID or an assurance profile. See [Platform Status](/platform-status). ## 4. Test a message Send a non-streaming request: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/messages \ -H "x-api-key: $PREM_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "max_tokens": 128, "messages": [{"role": "user", "content": "Reply with OK."}] }' ``` Test streaming after the first request succeeds: ```bash theme={"system"} curl -N http://127.0.0.1:8787/v1/messages \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "max_tokens": 128, "stream": true, "messages": [{"role": "user", "content": "Count to three."}] }' ``` The stream uses Anthropic event names. These include `message_start`, content block events, `message_delta`, and `message_stop`. ## 5. Configure a client Set the client's API key and base URL. This example uses the Anthropic Node.js SDK: ```typescript theme={"system"} import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic({ apiKey: process.env.PREM_API_KEY, baseURL: "http://127.0.0.1:8787", }); const response = await client.messages.create({ model: "deepseek-v4.1-flash-1017", max_tokens: 128, messages: [{ role: "user", content: "Reply with OK." }], }); console.log(response.content); ``` Change `deepseek-v4.1-flash-1017` to a model your account can use. See your model IDs on the [Prem dashboard](https://dashboard.prem.io). Each SDK joins the base URL and the route in its own way. Some clients want a host only. Some clients want a path that ends in `/v1`. Check your SDK. ## Send `claude` to a Prem model Some apps send the literal model name `claude`. You can map that one name to a Prem model: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat anthropic \ --default-model deepseek-v4.1-flash-1017 \ --kek "$CLIENT_KEK" ``` The proxy swaps in `deepseek-v4.1-flash-1017` only when the model equals `claude`. It does not change other Claude model names. > [!NOTE] > > This swap changes routing only. It does not make the Prem model behave the same as a Claude model. ## What this setup protects | Component | Reads your text | Notes | | - | - | - | | Your app | Yes | It creates the prompt and reads the reply on your machine. | | Anthropic adapter | Yes, on your machine | It translates requests and replies. | | Confidential Proxy | Yes, on your machine | It seals requests and opens replies. | | Prem API Gateway | No | It handles the sealed message and metadata only. | | Prem API Enclave | Yes, inside the TEE | It opens the request, runs the model, and seals the reply. | | External tools | Depends on the tool | Prem does not put them inside the enclave. | > [!WARNING] > > This setup protects the model path only. It does not put your app or its tools inside the enclave. ## Good to know **Tool calls run on your machine.** The model can return a `tool_use` block. Your app decides whether to run the tool. The tool runs outside the enclave. The next tool result enters the sealed path only after the proxy receives it. Apply your own access, approval, and logging rules to each tool. **Token counts are estimates.** The `count_tokens` route estimates tokens from the text. Use Prem usage records for billing and quota. **Shared Confidential concurrency.** All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). Above it, new requests return `429`. Obey `Retry-After` when the response has it. See [Agents & Automation](/agents). ## Troubleshooting > [accordion] The app returns 404 > > Check that the app adds `/v1/messages`. In `both` mode, check the `/anthropic` prefix. > [accordion] The API says model not found > > List your models with `/v1/models`. Use an enabled Prem model ID, or map the `claude` name. > [accordion] Authentication fails > > Send the Prem API key with `x-api-key` or `Authorization: Bearer`. Never send the KEK. > [accordion] Token counts do not match billing > > The count route returns an estimate. Use Prem usage records for billing and quota. > [accordion] An Anthropic feature does nothing > > The adapter does not support every Anthropic feature. For example, it ignores `top_k`. ## Frequently asked questions ### Does this run a Claude model? No. The request uses an Anthropic-compatible shape. The Prem model you choose runs the request. ### Why does the proxy translate the request? Prem's enclave uses an OpenAI-style chat format. The proxy translates your Messages request before it seals and sends it. ### Are token counts exact? No. The count route estimates tokens from the text and tool definitions. ### Are tool calls private? The model request and reply use the sealed path. Your app runs the tool outside the enclave. ### Can one proxy serve OpenAI and Anthropic apps? Yes. Use `--compat both` with the `/openai` and `/anthropic` prefixes. ## Related > [card] [Confidential Proxy](/confidential-proxy) > > Review every mode, route, key, and daemon option. > [card] [Claude for Microsoft 365](/guides/claude-microsoft-365) > > Apply the Anthropic surface to the Microsoft 365 add-ins. > [card] [OpenAI-compatible clients](/guides/openai-compatible-clients) > > Use the Chat Completions interface through the same proxy. > [card] [Agents & Automation](/agents) > > Review retries, concurrency, reasoning, and tool controls. > [card] [Claude Code](/guides/claude-code) > > Use the verified launcher for Claude Code. > [card] [Platform Status](/platform-status) > > Review released infrastructure and SDK capabilities. # Audio Transcription Source: https://docs.prem.io/guides/audio-transcription Transcribe audio files to text over the encrypted API, step by step. The current catalogue exposes one audio-transcription model: `deepgram/general-nova-3`. Its response uses Deepgram-style `metadata` and `results` fields. ## Basic audio transcription ```typescript theme={"system"} import { createReadStream } from "node:fs"; import { createRvencClient } from "@premai/api-sdk"; async function main() { const apiKey = process.env.PREM_API_KEY; const clientKEK = process.env.CLIENT_KEK; if (!apiKey || !clientKEK) { throw new Error("Set PREM_API_KEY and CLIENT_KEK"); } const client = await createRvencClient({ apiKey, clientKEK }); const transcription = await client.audio.transcriptions.create({ file: createReadStream("./audio.wav"), model: "deepgram/general-nova-3", smart_format: true, }); const alternative = transcription.results?.channels?.[0]?.alternatives?.[0]; console.log(alternative?.transcript ?? ""); } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` For this model, use `diarize` and `smart_format`. The SDK does not send `language`, `prompt`, `response_format`, or `timestamp_granularities` when the model ID starts with `deepgram/`. ## Response shape The response contains: * `metadata.request_id`, duration, channel count, and resolved Deepgram model information; * `results.channels[].alternatives[].transcript`; * confidence and word timing data when the backend returns them. Do not read `transcription.text` for `deepgram/general-nova-3`; that field is not part of the current response. ## Proxy request Start the OpenAI-compatible proxy with an explicit KEK: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --compat openai \ --kek "$CLIENT_KEK" ``` Then send multipart audio: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/audio/transcriptions \ -H "Authorization: Bearer $PREM_API_KEY" \ -F "file=@audio.wav" \ -F "model=deepgram/general-nova-3" ``` The proxy currently returns the same Deepgram-style JSON object. It does not normalize it into OpenAI's `{ "text": "..." }` shape. ## Current limits * This route is non-streaming. * The proxy accepts files up to 25 MB. * Verify a production audio format with your own representative fixture before rollout. # Audio Translation Source: https://docs.prem.io/guides/audio-translation Check whether an audio-translation model is enabled before implementing the route. > [!WARNING] > > No enabled audio-translation model is currently documented. This page intentionally does not present a runnable model ID. `@premai/api-sdk` `2.1.0` and the OpenAI-compatible proxy contain an audio-translation method and `/v1/audio/translations` route. A route existing in the package is not sufficient to make a translation example operational: the account must also receive an enabled translation-capable model from the model catalogue. ## Check availability List the live models and filter by type before implementing translation: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` A runnable translation example requires an enabled audio-translation model, a documented response contract, and a successful authenticated test with a representative audio file. No model currently meets those conditions in this guide. For the currently enabled transcription path, see [Audio Transcription](/guides/audio-transcription). # Chat Completion Source: https://docs.prem.io/guides/chat-completion Create encrypted chat completions with text, vision, and streaming, step by step. ## Text Completion Create a simple chat completion with text: ```typescript theme={"system"} import createRvencClient from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK }); const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Explain quantum computing in simple terms" } ], }); console.log(response.choices[0].message.content); ``` ## Image Analysis Analyze an image and get a detailed description: ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: "Describe this image in detail" }, { type: "image_url", image_url: { url: "https://docs.prem.io/docs/images/examples/basic.jpg", }, }, ], }], }); console.log(response.choices[0].message.content); ``` ## Document & Chart Intelligence with JSON Output Extract structured data from charts, invoices, or reports: ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: `Analyze this sales chart and return the data in JSON format: { "chart_type": "...", "key_findings": ["...", "..."], "data_points": [{"label": "...", "value": "..."}], "trends": "..." }` }, { type: "image_url", image_url: { url: "https://docs.prem.io/docs/images/examples/sales-chart.png", }, }, ], }], response_format: { type: "json_object" }, }); const data = JSON.parse(response.choices[0].message.content || "{}"); console.log(data); ``` ## Receipt & Invoice Processing Extract structured financial information from receipts: ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: `Extract all information from this receipt and format as JSON: { "merchant_name": "...", "date": "YYYY-MM-DD", "items": [{"name": "...", "quantity": 1, "price": 0.00}], "subtotal": 0.00, "tax": 0.00, "total": 0.00, "payment_method": "..." }` }, { type: "image_url", image_url: { url: "https://docs.prem.io/docs/images/examples/invoice.png" }, }, ], }], response_format: { type: "json_object" }, }); const data = JSON.parse(response.choices[0].message.content || "{}"); console.log(data); ``` ## Product Catalog Automation Generate structured product information from images: ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: `Analyze this product image and generate catalog data in JSON: { "product_category": "...", "attributes": {"color": "...", "material": "...", "style": "..."}, "target_audience": "...", "suggested_tags": ["...", "..."], "description": "..." }` }, { type: "image_url", image_url: { url: "https://docs.prem.io/docs/images/examples/tshirt.png" }, }, ], }], response_format: { type: "json_object" }, }); const data = JSON.parse(response.choices[0].message.content || "{}"); console.log(data); ``` ## Image-Based Question Answering Ask specific questions about an image: ```typescript theme={"system"} import fs from "fs"; const imagePath = "./scene.jpg"; const base64Image = fs.readFileSync(imagePath, "base64"); const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: "How many people are in this image and what are they doing?" }, { type: "image_url", image_url: { url: `data:image/jpeg;base64,${base64Image}` }, }, ], }], }); console.log(response.choices[0].message.content); ``` ## Multi-Image Comparison Analysis Compare multiple images for quality control or change detection: ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: "Compare these before/after images and identify all changes." }, { type: "image_url", image_url: { url: "https://docs.prem.io/docs/images/examples/before.png" }, }, { type: "image_url", image_url: { url: "https://docs.prem.io/docs/images/examples/after.png" }, }, ], }], }); console.log(response.choices[0].message.content); ``` ## Streaming Vision Analysis Stream the response to make creative content in real time: ```typescript theme={"system"} const stream = await client.chat.completions.create({ model: "qwen38-27b", messages: [{ role: "user", content: [ { type: "text", text: "Create an engaging social media caption for this image" }, { type: "image_url", image_url: { url: "https://example.com/image.jpg" }, }, ], }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` # Claude Code Source: https://docs.prem.io/guides/claude-code Launch Claude Code through Prem's Confidential Proxy with the bundled confidential-claude wrapper. The `@premai/api-sdk` package includes `confidential-claude`, a launcher that starts the Confidential Proxy in Anthropic mode and then runs the installed Claude Code CLI against it. > [!WARNING] > > This protects supported model traffic after the local proxy encrypts it. Claude Code, repository files, shell commands, MCP servers, hooks, and tool results remain on your machine or in their own external systems. > [tab] Confidential API > > Use `confidential-claude` to connect Claude Code through the local Confidential Proxy. [Go to the confidential setup](#before-you-start). > [tab] ZDR > > ZDR is not available for Claude Code. Claude Code requires the Anthropic Messages API, while ZDR supports OpenAI-compatible Chat Completions. Use [OpenCode](/guides/opencode), [OpenClaw](/guides/openclaw), [Hermes Agent](/guides/hermes), or [Goose](/guides/goose) for a ZDR coding workflow. ## How the launcher works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] C["Claude Code"] -->|"Anthropic Messages API"| P["Confidential Proxy
127.0.0.1:8787"] T["Local tools and MCP servers"] <--> C end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem confidential runtime
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"Anthropic SSE or message"| C ``` The launcher performs these steps on every run: 1. Requires an interactive terminal (TTY). 2. Reads the endpoint, key, and KEK configuration. 3. Starts or reuses the proxy on port `8787` in Anthropic mode with attestation enabled. 4. Displays the list of your enabled models. 5. Sets Claude Code's Anthropic base URL and model environment variables. 6. Forwards every remaining argument to the installed `claude` command. ## Before you start You need: * Claude Code installed and available as `claude` on `PATH`. * A Prem API key. * A 32-byte KEK encoded as 64 hexadecimal characters. * A terminal with interactive input. * `@premai/api-sdk`. Check the installed Claude Code version: ```bash theme={"system"} claude --version ``` ## 1. Set the launcher values ```bash theme={"system"} export API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Generate the KEK once if you do not have one: ```bash theme={"system"} openssl rand -hex 32 ``` `confidential-claude` reads `API_KEY`, not `PREM_API_KEY`. Supplying it through the environment also prevents the launcher from prompting for and saving the API key in its application-data `.env` file. The launcher still saves the selected model ID there. ## 2. Run the first request When updating the SDK, [restart the managed proxy](/confidential-proxy#upgrade-an-existing-proxy) before launching. The launcher can reuse a daemon that is already running. Use `--print` for a bounded first test: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-claude \ --print "Reply with exactly OK. Do not use tools." ``` Choose an enabled model in the picker with the arrow keys or `j` and `k`, then press Enter. > [!NOTE] > > `--print` still requires a TTY because the launcher always displays the model list before it starts Claude Code. ## 3. Start an interactive session ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-claude ``` Claude Code uses the Anthropic-compatible Messages route and receives Server-Sent Events while it works. ## Model selection The picker calls the model-list endpoint on every run. This guide documents these chat models: | Picker ID | Display name | Current catalogue behavior | | - | - | - | | `qwen38-27b` | Qwen 3.8 | Text, image, and video input metadata | | `deepseek-v4.1-flash-1017` | DeepSeek V4.1 Flash · 1017 | Multimodal chat model | The Anthropic adapter returns the requested alias in its message `model` field. It does not expose the backend-resolved model ID or an assurance profile. Do not infer an assurance class from the picker label. See [Platform Status](/platform-status). ## Stop the local proxy The launcher starts a detached proxy and does not stop it when Claude Code exits. Stop it explicitly when you finish: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy stop ``` Check the status before another run when port `8787` appears occupied: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy status ``` ## Plaintext and tool boundary | Component | Plaintext access | Notes | | - | - | - | | Claude Code | Yes | Reads prompts, selected repository files, and tool results locally | | Confidential Proxy | Yes, locally | Translates, encrypts, and decrypts model traffic | | Prem API Gateway | No content access | Receives ciphertext, authentication, and routing metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs the selected model and encrypts the response | | Shell, hooks, MCP, and plugins | Depends on the tool | Outside the Prem inference boundary | Review Claude Code permissions, hooks, MCP servers, and egress separately. A confidential model route does not make local tool execution confidential. ## Troubleshooting > [accordion] TTY environment required > > Run the command directly in an interactive terminal. Piping input or starting it from a non-interactive CI process does not provide the interactive terminal that model selection needs. > [accordion] install claude code > > Install Claude Code and confirm that `claude --version` succeeds in the same shell. > [accordion] Failed to fetch models from proxy > > Check `API_KEY`, `PROXY_URL`, `ENCLAVE_URL`, network access, and proxy logs. Confirm that the key can list models. > [accordion] Port 8787 is occupied > > Run `confidential-proxy status`, then stop the managed proxy. The launcher refuses to take over an unknown process on that port. > [accordion] Attestation fails > > Do not add `--no-attest` to work around the failure. Capture the error and verify the current Reticle boundary in [Attestation](/attestation). > [accordion] The selected model behaves differently from Claude > > The wrapper supplies an Anthropic-compatible API shape. It does not turn a Prem model into an Anthropic-hosted Claude model. ## Frequently asked questions ### Does `confidential-claude` install Claude Code? No. It checks for an existing `claude` command and exits if Claude Code is not installed. ### Does it use my Anthropic API key? No. `API_KEY` is the Prem API key. The launcher removes `ANTHROPIC_API_KEY` and passes the Prem key to Claude Code as the gateway authentication token. ### Does it remember the model? It writes the selected model to its application-data `.env` file, but the current launcher still shows the model list on each run. ### Can I pass normal Claude Code arguments? Yes. The launcher forwards its arguments to `claude`, including `--print`. ### Is the full coding session inside an enclave? No. Only supported inference traffic uses the encrypted Prem path. Files and tools remain in their own local or external trust boundaries. ## Related > [card] [Anthropic-compatible clients](/guides/anthropic-compatible-clients) > > Review the Messages translation and compatibility limits. > [card] [Confidential Proxy](/confidential-proxy) > > Review proxy modes, routes, keys, and daemon controls. > [card] [Platform Status](/platform-status) > > Review released infrastructure and SDK capabilities. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the data flow. # Claude for Microsoft 365 Source: https://docs.prem.io/guides/claude-microsoft-365 Connect the Claude add-ins for Excel, PowerPoint, Word, and Outlook to Prem API. The Claude add-ins for Microsoft 365 can send inference to Prem. Prem runs the model inside a confidential enclave. The add-ins keep their normal look and workflow. Your organization controls the connection. This guide helps you set up that connection. It uses the **LLM gateway** path from Anthropic. Prem provides the gateway software: the [Confidential Proxy](/confidential-proxy). A Microsoft 365 tenant has not been tested end to end with this setup. Complete the acceptance tests before production rollout. > [!NOTE] > > Anthropic documents four connection paths for the Office add-ins: LLM gateway, Bedrock direct, Vertex AI direct, and Foundry direct. This guide covers the **LLM gateway** path only. Read the [Anthropic third-party platforms guide](https://claude.com/docs/office-agents/third-party-platforms) first. It is the source of truth for tenant setup, network allowlists, and feature support. ## Who this guide is for Two roles complete this setup: * **An IT administrator** deploys the add-in and runs the gateway. Sections 1 to 8 are for this role. * **An end user** connects the add-in in their Office application. The [End-user connection](#end-user-connection) section is for this role. You can do both roles yourself for a small pilot. ## What you set up The add-in talks to a gateway that you run. The gateway is the Prem Confidential Proxy. The proxy encrypts each request before it leaves your network. The Prem enclave decrypts the request, runs the model, and encrypts the response. ```mermaid theme={"system"} flowchart TB subgraph M365["Microsoft 365 and user device"] D["Workbook, presentation, document, or email"] --> A["Claude add-in task pane
plaintext"] end A -->|"HTTPS, Anthropic Messages API"| P["Your gateway host
Confidential Proxy"] P -->|"Encrypt before Prem network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem API Enclave
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"Anthropic-style response"| A A -.->|"Office.js action"| D ``` The add-in and the proxy host read plaintext. The Prem API Gateway sees only ciphertext. The Prem Enclave reads plaintext inside its Trusted Execution Environment (TEE). ## What this integration does Users open the Claude task pane in these applications: * Excel * PowerPoint * Word * Outlook The add-in sends its model requests to your Prem gateway. Prem runs the model with confidential inference. ## What this integration does not do This setup does **not** do these things: * It does not set up Microsoft Copilot. * It does not protect the full Microsoft 365 workflow. It protects the model request only. * It does not make a Prem model behave the same as a Claude model. * It does not protect Microsoft Graph calls, connectors, or local add-in storage. * It does not enable work across applications. Anthropic lists this feature as unavailable through third-party platforms. Check the current [feature support table](https://claude.com/docs/office-agents/third-party-platforms) before each rollout. The list changes. ## Before you start Get these items ready: * Microsoft 365 with Microsoft Entra ID for admin consent. * Claude for Excel, PowerPoint, Word, or Outlook, installed from Microsoft AppSource or by admin deployment. * A gateway hostname that every approved device can reach. * A TLS certificate that those devices trust. For a local pilot on macOS, you create one with [mkcert](https://github.com/FiloSottile/mkcert). * [Docker Desktop](https://www.docker.com/products/docker-desktop/) for a local pilot on macOS, or Node.js for a server. * A dedicated Prem API key. * A 32-byte KEK encoded as 64 hexadecimal characters. * The current Prem gateway and enclave endpoints. * A Prem model that supports your workflow. > [!NOTE] > > For Outlook, a Global Administrator grants Microsoft Graph consent one time. The Graph token stays in the user's Outlook client. It never reaches your gateway or Prem. See the [Anthropic Outlook guide](https://claude.com/docs/office-agents/third-party-platforms) for the consent step. ## 1. Choose the gateway hostname The add-in cannot use `localhost` or `127.0.0.1` on macOS. So the gateway needs a real hostname. * Choose a hostname, for example `prem-office-gateway.example.com`. * Point it at the gateway host's network IP address, not `127.0.0.1`. * Add the hostname to your local DNS, or to the `/etc/hosts` file on each approved device. * Confirm that every approved device can resolve the hostname. Use the same hostname everywhere. It must match the certificate and the URL that users enter. ## 2. Create a trusted certificate The task pane runs in a browser. It requires an HTTPS gateway with a trusted certificate. For a local pilot on macOS, create the certificate with mkcert: ```bash theme={"system"} brew install mkcert mkcert -install mkcert prem-office-gateway.example.com ``` `mkcert -install` adds a local certificate authority to the Mac's trust store. `mkcert` then writes two files in the current folder: ```text theme={"system"} prem-office-gateway.example.com.pem # the certificate prem-office-gateway.example.com-key.pem # the private key ``` To trust the certificate on other devices, install the mkcert root certificate on each one. Find it with `mkcert -CAROOT`. For a wider rollout, use an organization-issued or public certificate instead. Keep the private key safe. Do not commit it to a repository. ## 3. Set the gateway secrets Set these values on the gateway host: ```bash theme={"system"} export PREM_API_KEY="your-dedicated-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Store the API key, KEK, certificate key, and endpoints in a secret manager. Do not commit them to a repository. ## 4. Start the gateway The gateway software is the `confidential-proxy` command in the [`@premai/api-sdk`](https://www.npmjs.com/package/@premai/api-sdk) npm package. The package is an end-to-end encrypted client that speaks both the OpenAI and the Anthropic API formats. **Local pilot on macOS (Docker):** run the proxy in a container. Run this command from the folder that holds your certificate files: ```bash theme={"system"} docker run --rm -p 8787:8787 \ -e PREM_API_KEY -e CLIENT_KEK -e PROXY_URL -e ENCLAVE_URL \ -v "$(pwd):/tls:ro" \ node:22-alpine \ npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 0.0.0.0 --port 8787 \ --compat anthropic \ --kek "$CLIENT_KEK" \ --default-model deepseek-v4.1-flash-1017 \ --cors-origin https://pivot.claude.ai \ --tls \ --tls-cert /tls/prem-office-gateway.example.com.pem \ --tls-key /tls/prem-office-gateway.example.com-key.pem ``` **Server (Node.js):** run the proxy directly with npx: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 0.0.0.0 --port 8787 \ --compat anthropic \ --kek "$CLIENT_KEK" \ --default-model deepseek-v4.1-flash-1017 \ --cors-origin https://pivot.claude.ai \ --tls \ --tls-cert /path/to/cert.pem \ --tls-key /path/to/key.pem ``` The proxy now serves the add-in at `https://prem-office-gateway.example.com:8787`. The options mean: * `--compat anthropic` makes the proxy speak the Anthropic Messages API. The add-in uses this format. * `--default-model` is built for the Claude for Microsoft 365 integration. It replaces the literal `claude` request value with a Prem model. Change `deepseek-v4.1-flash-1017` to the Prem model you want. * `--cors-origin` lets the task pane read the responses. The task pane loads from `https://pivot.claude.ai`. > [!WARNING] > > Do not use `--cors-origin *`. CORS is not authentication. An exact origin limits unwanted browser access. ## 5. Restrict network access Do not expose an unauthenticated proxy to the public internet. Allow inbound traffic to port `8787` only from approved networks or your reverse proxy. Choose a topology that fits the rollout: | Topology | Use it for | Required controls | | - | - | - | | Dedicated LAN host | A small pilot on one managed network | Internal DNS, trusted TLS, firewall, dedicated key | | Private VM or container | A managed organization deployment | Private routing, health checks, key storage, updates | | Internet-reachable gateway | Users without private network access | Reverse proxy, strict authentication, firewall, monitoring | For an internet-reachable deployment, put an authenticated gateway in front of the proxy. Apply request limits, authentication, and alerts there. ## 6. Deploy the add-in Anthropic provides a setup wizard for tenant deployment. The wizard generates the add-in manifest and handles admin consent. Install the plugin in your shell: ```bash theme={"system"} claude plugin marketplace add anthropics/financial-services claude plugin install claude-for-msft-365-install@claude-for-financial-services ``` Run the wizard inside Claude: ```text theme={"system"} /claude-for-msft-365-install:setup ``` Choose the **LLM gateway** path when the wizard asks. Give it these values: * **Gateway URL:** the base URL of your proxy, for example `https://prem-office-gateway.example.com:8787`. * **Gateway token:** the dedicated Prem API key. The wizard writes a `manifest.xml` file. For Outlook, it also writes `manifest-outlook.xml`. Upload each manifest in the Microsoft 365 Admin Center. Open **Settings → Integrated apps → Upload custom apps**. Assign the add-in to a pilot group first. Widen the assignment after the pilot passes. > [!NOTE] > > By default, the add-in sends the token in the `x-api-key` header. To use `Authorization: Bearer` instead, set `gateway_auth_header: authorization` in the manifest. See the [Anthropic gateway requirements](https://claude.com/docs/office-agents/third-party-platforms) for all manifest options. ## End-user connection Give these steps to each user. They connect the add-in one time. 1. Open Excel, PowerPoint, Word, or Outlook. 2. Launch the Claude add-in. 3. On the sign-in screen, select **Cloud provider or gateway**. 4. Select **Gateway**. 5. Enter the gateway URL, for example `https://prem-office-gateway.example.com:8787`. 6. Enter the Prem API key as the token. 7. Select **Connect**. Enter the base URL only. Do not add `/v1/messages` to the URL. The add-in stores the token in the browser's local storage, inside its sandboxed frame. To change the token later, open **Settings** in the add-in sidebar, enter the new value, and test the connection. ## Validate the rollout Test each approved application on its own. Use non-sensitive test files first. 1. Open a small range, slide, paragraph, or email. 2. Ask for a short model response. 3. Apply one reversible edit through the add-in. 4. Confirm that streaming finishes. 5. Confirm that the Prem usage record appears. 6. Confirm that an invalid token returns `401`. 7. Confirm that an unapproved user or network cannot reach the gateway. 8. Confirm that a certificate error blocks the connection. Do not widen the pilot until every test passes. ## Responsibility boundaries | Layer | Owner | Responsibility | | - | - | - | | Add-in deployment | Microsoft 365 administrator | Assign add-ins, users, groups, and permissions | | Identity and consent | Microsoft Entra ID administrator | Approve sign-in and Microsoft Graph permissions | | Office content access | Add-in and Microsoft 365 | Read or change selected content | | Gateway host | Your organization | Run TLS, CORS, proxy, firewall, keys, and monitoring | | Confidential Proxy | Your organization and Prem package | Translate, encrypt, decrypt, and return traffic | | Prem API Gateway | Prem | Authenticate, limit, bill, and route encrypted payloads | | Prem API Enclave | Prem | Decrypt, run inference, and encrypt the response | ## Security boundary | Component | Reads plaintext | Note | | - | - | - | | Microsoft 365 application | Yes | Holds the source document or message | | Claude task pane | Yes | Reads selected content and stores the token locally | | Microsoft Entra ID and Graph | Depends on tenant | Outside the Prem inference boundary | | Confidential Proxy host | Yes | Translates, encrypts, decrypts, and holds local secrets | | Prem API Gateway | No | Processes ciphertext, authentication, and metadata | | Prem API Enclave | Yes, inside the TEE | Runs the selected Prem model | | Connectors and external tools | Depends on the feature | Need a separate data-flow review | Anthropic states that prompts and responses go only to your gateway. The add-in loads its interface and telemetry from Anthropic and Microsoft domains. That traffic does not carry prompts or responses. > [!WARNING] > > The add-in stores its token in browser `localStorage`, inside the sandboxed task pane. The current Prem proxy uses that token as the Prem API key. Treat each device and browser profile as a key-bearing asset. For short-lived user tokens, run a separate authenticated gateway in front of the proxy. ## Operational controls Apply these controls for a managed rollout: * Pin the `@premai/api-sdk` package version. * Run the proxy as a supervised service. * Monitor certificate expiry and endpoint health. * Rotate the Prem API key and KEK under a written procedure. * Turn off debug logs in production unless support needs them. * Keep document content out of support bundles. * Record add-in assignments, gateway changes, and key rotations. * Test rollback before each package or manifest update. ## Troubleshooting > [accordion] The add-in reports connection refused > > Check DNS, firewall rules, gateway health, and TLS trust. Confirm the base URL. Do not include `/v1/messages`. > [accordion] The browser reports a CORS error > > Confirm the response includes the allowed origin on `OPTIONS`, `GET`, `POST`, and error responses. > [accordion] The add-in reports no models > > Test `GET /v1/models` with the same token. Confirm the Prem API key can list an enabled model. > [accordion] The request uses an unknown Claude model > > Send `claude` as the model, or send a supported Prem model ID. The default substitution matches only `claude`. > [accordion] The token expired or was rotated > > Update the token in the add-in Settings. Test the connection again. > [accordion] Streaming hangs > > Confirm that firewalls and reverse proxies do not buffer Server-Sent Events. Test the direct gateway path. ## Frequently asked questions ### Is this Microsoft Copilot? No. This connects Anthropic's Claude add-ins for Microsoft 365 to the Prem gateway. ### Does Prem run a Claude model in this setup? Not always. The add-in uses the Anthropic API format. The proxy maps the `claude` placeholder to a Prem model. ### Why can the add-in not use localhost on macOS? The add-in runs in a sandboxed browser frame. It cannot use the loopback path. Use a reachable gateway host with trusted TLS. ### Does CORS protect the API key? No. CORS controls which browser origin can read responses. Authentication, TLS, device controls, and firewall rules protect access. ### Where does the add-in store the token? The add-in stores the token in browser `localStorage`, inside its sandboxed task pane. Treat the device and browser profile as key-bearing assets. ### Does this protect the full document lifecycle? No. It protects the model request after the proxy encrypts it. Microsoft 365 and local add-in processing stay separate. ### Does work across Microsoft 365 applications work through this gateway? No. Anthropic lists this feature as unavailable through third-party platforms. Check the limitation before each rollout. ## Related > [card] [Anthropic third-party platforms](https://claude.com/docs/office-agents/third-party-platforms) > > Read Anthropic's source guide for tenant setup and feature support. > [card] [Anthropic-compatible clients](/guides/anthropic-compatible-clients) > > Understand the Messages adapter and its compatibility limits. > [card] [Confidential Proxy](/confidential-proxy) > > Review every proxy option and daemon control. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the data path. > [card] [Production Checklist](/production-checklist) > > Complete key, attestation, reliability, and support checks. > [card] [Platform Status](/platform-status) > > Review current behavior and the untested tenant boundary. # Codex compatibility Source: https://docs.prem.io/guides/codex-cli Understand why Codex cannot currently connect to Prem API. Codex is not compatible with Prem API today. > [!WARNING] > > Codex custom providers use the OpenAI Responses API. Prem API does not expose > `/v1/responses`, so changing `base_url` is not enough. ## Use a supported coding harness * Use [OpenCode](/guides/opencode) for an OpenAI-compatible coding agent. * Use [Claude Code](/guides/claude-code) through Prem's Anthropic-compatible launcher. Codex support requires a verified Responses API adapter. See the [Codex configuration reference](https://developers.openai.com/codex/config-reference#configtoml) for its current provider protocol. # Cursor compatibility Source: https://docs.prem.io/guides/cursor Understand why Cursor's custom OpenAI base URL is not currently a supported confidential Prem integration. Cursor exposes an **Override OpenAI Base URL** control for OpenAI API requests. That control is not enough to create the same confidential path as OpenCode, Goose, or another local client. > [!WARNING] > > Cursor is not currently supported as a Prem confidential integration. Cursor's documentation states that requests pass through Cursor's servers for final prompt building and that the provider API key is sent through those servers with each request. ## Compatibility verdict | Requirement | Current result | | - | - | | Custom OpenAI base URL control | Available in Cursor Settings under Models and API Keys | | Standard chat models with a custom key | Documented by Cursor | | Direct local call to `127.0.0.1:8787` | Not documented or verified | | Prompt hidden from Cursor's service | No | | Client-to-Prem-enclave confidentiality | Not established | | End-to-end Prem test | Not completed | The [Cursor API key documentation](https://cursor.com/help/models-and-usage/api-keys) says that custom keys work only with chat models. It also says that all requests are routed through Cursor's servers for final prompt building. The key is transmitted to Cursor's backend for each request. ## Why the base URL is insufficient ```mermaid theme={"system"} flowchart TB subgraph Device["Your device"] C["Cursor
prompt, files, and tool context"] L["Local Confidential Proxy
127.0.0.1:8787"] end C -->|"Prompt and provider key"| S["Cursor services
final prompt building"] S -.->|"Custom OpenAI endpoint, if reachable"| R["Remote endpoint or deployed proxy"] L -.->|"Not a documented direct path"| S R -->|"Encrypted only after the proxy receives plaintext"| G["Prem API Gateway"] G --> E["Prem confidential runtime"] ``` The confidentiality problem occurs before Prem receives the request. Cursor's service can process the prompt while it builds the final request. A Prem proxy deployed after that service can protect the later Prem inference path, but it cannot make the earlier Cursor processing confidential. A loopback URL introduces a second problem. `127.0.0.1` refers to the host making the connection. Cursor does not document its custom provider flow as a direct local request from the editor to that address. Do not assume that the local proxy is reachable from Cursor's backend. ## What the current controls establish Cursor can use custom provider credentials for supported chat models. The installed Cursor settings also expose a base URL override for OpenAI requests. These facts do **not** establish any of the following: * that Cursor sends the final request directly from the device to the local Confidential Proxy; * that Cursor cannot read the prompt, file context, tool output, or provider key; * that Cursor uses only `/v1/chat/completions` for every agent feature; * that Cursor Tab, Cloud Agents, Composer, or other Cursor-hosted features use the custom endpoint; * that an agent turn, stream, and tool call work end to end through Prem. The same routing applies to ZDR requests. Even when no client-to-enclave confidentiality is required, the provider API key is still transmitted through Cursor's servers with each request. Cursor is therefore not documented as a ZDR integration either. ## Use a supported local harness Use a client that sends Chat Completions directly to the local proxy when the client-to-enclave boundary is required: * [OpenCode](/guides/opencode) for a terminal coding agent. * [Goose](/guides/goose) for a local agent with built-in and MCP tools. * [OpenClaw](/guides/openclaw) or [Hermes Agent](/guides/hermes) for broader local automation. * [Claude Code](/guides/claude-code) through Prem's bundled Anthropic-compatible launcher. The Codex extension can run inside Cursor as an editor extension, but that is a separate client and provider path. See [Codex CLI compatibility](/guides/codex-cli) before assuming it can use Prem. ## Requirements for confidential support A confidential Cursor integration would require all of these conditions: 1. Cursor documents a direct client-side provider path or a local extension path that does not send plaintext to Cursor's service. 2. The path can target `http://127.0.0.1:8787/v1` and uses `/v1/chat/completions`. 3. A bounded text request reaches the local Confidential Proxy. 4. Streaming and tool calls complete without direct-provider fallback. 5. Network inspection confirms that prompt content and the Prem API key do not transit Cursor's service. 6. Cursor-hosted features that bypass the custom provider are clearly excluded from the guide. ## Frequently asked questions ### Does Cursor allow an OpenAI base URL override? Yes. The current Models settings expose that control. It does not establish a direct or confidential local path. ### Can I point the override at the Prem proxy anyway? No, not as a confidential deployment. Cursor's documented backend processing keeps Cursor in the plaintext trust boundary, and a loopback proxy is not a documented backend-reachable endpoint. ### Would a publicly reachable proxy solve this? It may solve network reachability, but it does not remove Cursor from the plaintext path. You would also need TLS, strict network access, and controlled secret handling on the deployed proxy. ### Does Prem protect Cursor tools and files? No. Even in a future model integration, Cursor, editor files, terminal commands, extensions, and remote tools remain outside the Prem confidential runtime. ## Related > [card] [Cursor API keys](https://cursor.com/help/models-and-usage/api-keys) > > Read Cursor's current provider-key and backend-routing boundary. > [card] [OpenCode](/guides/opencode) > > Use a tested local coding-agent path through Prem. > [card] [Confidential Proxy](/confidential-proxy) > > Review supported routes, modes, and key handling. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the request path. # Decisions Source: https://docs.prem.io/guides/decisions Answer typed decision questions with probabilities, step by step. Decisions answers structured questions about a piece of context. You send a state and a set of typed questions. You get one probability distribution per question. The current catalogue exposes one decision model: `dgemma`. Decisions runs in **Zero Data Retention** mode. Your content is plaintext at the Prem API Gateway and at the partner. There is no client-side encryption and no attestation. See [ZDR overview](/zdr/overview) and [ZDR security boundary](/zdr/security-boundary). ## Basic decision Ask a routing question about an incident: ```bash theme={"system"} curl https://gateway.prem.io/typesafe/v1/systemone \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "dgemma", "state": "All users see HTTP 503 and cannot sign in.", "questions": { "team": { "type": "choice", "instructions": "Which team should handle this?", "criteria": { "billing": "Payments and invoices", "technical": "Software failures", "sales": "New purchases" } } } }' ``` The response carries one answer per question id: ```json theme={"system"} { "model": "dgemma", "answers": { "team": { "type": "choice", "choice": "technical", "probabilities": { "billing": 0.019, "technical": 0.981, "sales": 0.000 }, "confidence": 0.981 } }, "usage": { "input_tokens": 109, "output_tokens": 8 } } ``` `choice` is the most likely label. `probabilities` holds one value per criterion key. `confidence` rescales the top probability against a uniform distribution. It is not a calibrated correctness estimate. ## Question types Each question declares a `type` and a `criteria` shape that matches the type. ### `choice` Pick one label from a named list. `criteria` maps each label to a description. The list holds 1 to 26 entries. ```json theme={"system"} { "topic": { "type": "choice", "instructions": "Which topic does this cover?", "criteria": { "billing": "Payments and invoices", "technical": "Software failures", "sales": "New purchases" } } } ``` ### `noul` Answer yes or no. The answer is a single probability. `criteria` is optional and can name the two outcomes. ```json theme={"system"} { "delivered": { "type": "noul", "instructions": "Was the package delivered?" } } ``` The answer shape is a scalar in `noul`: ```json theme={"system"} { "delivered": { "type": "noul", "noul": 0.02 } } ``` Do not read `probabilities` for a `noul` question. That field is not part of this answer. ### `score` Rate on an ordered scale. `criteria` lists the levels in ascending order, from 2 to 10 levels. ```json theme={"system"} { "severity": { "type": "score", "instructions": "Rate incident severity.", "criteria": ["low", "medium", "high"] } } ``` The answer carries `score`, `legend`, `probabilities`, and `confidence`. The score is the probability-weighted mean over the zero-indexed levels. ## Several questions in one request Each question is independent. One request can carry up to 16 questions. The questions share the state, and each returns its own distribution. ```json theme={"system"} { "model": "dgemma", "state": "Refunds are allowed within 30 days unless the item is final sale. Bought 10 days ago, final sale.", "questions": { "refund": { "type": "noul", "instructions": "Is a refund allowed?" }, "severity": { "type": "score", "instructions": "Rate how clear the policy is.", "criteria": ["unclear", "clear"] } } } ``` > [!NOTE] > > Questions cannot read one another. There is no shared prefix across questions in a request, and one question cannot use the answer to another. Ask a follow-up request if a later question depends on an earlier answer. ## Image input Send one image as a base64 data URL in `images`. The image is placed ahead of the state. ```json theme={"system"} { "model": "dgemma", "state": "Inspect the attached image.", "questions": { "color": { "type": "choice", "instructions": "What color is the square?", "criteria": { "red": "Red", "blue": "Blue", "green": "Green" } } }, "images": ["data:image/png;base64,iVBORw0KGgo..."] } ``` ## Video input Send one MP4 as a base64 data URL in `videos`. This is a `dgemma` extension and is not part of the base request shape. ```json theme={"system"} { "model": "dgemma", "state": "Inspect the attached clip.", "questions": { "hazard": { "type": "choice", "instructions": "Is a hazard visible?", "criteria": { "yes": "A hazard is visible", "no": "No hazard" } } }, "videos": ["data:video/mp4;base64,AAAAIGZ0eXBpc29t..."] } ``` The clip must be at most 10 MiB, 30 seconds, and 1920 x 1080 pixels. Four frames are sampled. Audio is not processed. Use `images` or `videos`, not both in one request. Use a raw JSON request if your HTTP client does not expose the field. ## Response shape The response contains: * `model`, the resolved model name; * `answers`, one entry per question id, with `type`, the answer, and the distribution; * `usage`, with `input_tokens` and `output_tokens`; * `diagnostics`, engine detail for the call. Read `answers` keyed by your own question ids. `diagnostics` is informational and can change without notice. > [!WARNING] > > The values in `probabilities` are normalized scores over the supplied labels. They are not calibrated correctness estimates, and label order can change the prediction. See [Current limits](#current-limits). ## Request with the TypeSafe SDK Decisions uses a TypeSafe-compatible API, so the official [TypeSafe client](https://www.npmjs.com/package/@typesafe-ai/sdk) works against this route. Install it and point the base URL at `https://gateway.prem.io/typesafe`. ```bash theme={"system"} npm install @typesafe-ai/sdk ``` ```typescript theme={"system"} import { choice, noul, score, TypeSafeClient } from "@typesafe-ai/sdk"; const client = new TypeSafeClient({ apiKey: process.env.PREM_API_KEY, baseURL: "https://gateway.prem.io/typesafe", defaultModel: "dgemma", }); const res = await client.systemOne({ state: "I was charged twice for the same purchase.", questions: { team: choice("Which team should handle this?", { billing: "Payments and invoices", technical: "Software failures", sales: "New purchases", }), urgent: noul("Is this request urgent?"), severity: score("How severe is this issue?", ["low", "medium", "high"] as const), }, }); console.log(res.answers.team.choice, res.answers.team.confidence); console.log(res.answers.urgent.noul); console.log(res.answers.severity.score, res.answers.severity.legend); ``` The `choice`, `noul`, and `score` helpers build the typed questions and validate them before the request is sent. `state` accepts any JSON value, so an object such as `{ document: "..." }` works as well as a string. The client throws a `TypeSafeError` on an invalid key and a `BadRequestError` when the server rejects the request, for example when a request carries more than 16 questions. ## Request with the standard library Decisions is not the OpenAI Chat Completions shape, so an OpenAI client does not work against this route. Any HTTP client can send the JSON directly: ```typescript theme={"system"} const response = await fetch("https://gateway.prem.io/typesafe/v1/systemone", { method: "POST", headers: { Authorization: `Bearer ${process.env.PREM_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "dgemma", state: "I was charged twice for the same purchase.", questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments and invoices", technical: "Software failures", sales: "New purchases", }, }, }, }), }); const data = await response.json(); console.log(data.answers.team.choice); ``` ## Current limits * The route is non-streaming. `stream` is not supported. * A request can have up to 16 questions. * Decisions requests count toward your organization's ZDR limits for request rate, tokens, and concurrency. ZDR chat completions count toward the same limits. All keys and members share these limits. Confidential inference has separate limits. At the [concurrency limit](/tiers#concurrent-requests), the API returns `429` for new requests. * `choice` holds 1 to 26 criteria. `score` holds 2 to 10 levels. * At most one image or one video per request, not both. * Questions are independent and cannot read one another. * Probabilities are not calibrated. On a public benchmark slice, 8 of 113 answers above a 0.99 top-probability threshold were wrong, and reversing the order of the criteria changed 17 of 139 predictions. Do not use `confidence` as a correctness guarantee. * The route runs in ZDR mode. There is no client-side encryption and no attestation. See [ZDR vs Confidential](/zdr/comparison). * Verify a production input format with your own representative fixture before rollout. ## Next steps > [card] [Decisions API reference](/api-reference/zdr-decisions) > > The full request and response reference. > [card] [ZDR overview](/zdr/overview) > > What ZDR guarantees and what it does not. > [card] [Models & Pricing](/models-and-pricing) > > The models, the prices, and the regions. > [card] [ZDR vs Confidential](/zdr/comparison) > > Which mode fits your workload. # Goose Source: https://docs.prem.io/guides/goose Connect Goose to Prem API through the local Confidential Proxy. Goose has a built-in OpenAI provider that accepts a custom host and Chat Completions path. Point it at Prem's local Confidential Proxy and select a Prem model ID. > [!WARNING] > > Goose and its extensions run on your machine. Prem protects supported model traffic after the local proxy encrypts it. File, shell, browser, MCP, and extension execution remain outside the Prem confidential runtime. > [tab] Confidential API > > Use the local Confidential Proxy for sensitive model traffic. [Go to the confidential setup](#confidential-api-setup). > [tab] ZDR > > Use Zero Data Retention (ZDR) for OpenAI-compatible inference with non-sensitive data. [Go to the ZDR setup](#zdr-setup). ## Confidential API setup This path uses the local Confidential Proxy to encrypt your prompts end-to-end before they leave your machine. ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] O["Goose"] -->|"OpenAI Chat Completions"| P["Confidential Proxy
127.0.0.1:8787/v1"] T["Built-in tools and MCP extensions"] <--> O end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem confidential runtime
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"OpenAI-compatible response"| O ``` ## Before you start You need: * Goose installed. See the [official installation guide](https://goose-docs.ai/docs/getting-started/installation/). * A Prem API key. See [API Keys](/api-keys). * A 32-byte client KEK encoded as 64 hexadecimal characters. * The current Prem gateway and enclave endpoints. * A chat model returned by your Prem model-list request. Check the installed version: ```bash theme={"system"} goose --version ``` The commands below have been exercised with Goose `1.45.0` using a normal response and a local shell-tool call. ## 1. Set your secrets ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Generate the KEK once if you do not have one: ```bash theme={"system"} openssl rand -hex 32 ``` Store both secrets outside the repository. Do not place the API key in Goose's `config.yaml`. ## 2. Start the Confidential Proxy ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat openai \ --kek "$CLIENT_KEK" ``` > [!WARNING] > > Do not use `--no-attest`. Keep attestation enabled for confidential inference. ## 3. Select an enabled model ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` Use a returned `id`. This example uses `qwen38-27b`: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen38-27b", "messages": [{"role": "user", "content": "Reply with OK."}], "stream": false }' ``` ## 4. Configure Goose Set Goose's OpenAI provider variables in the shell that starts it: ```bash theme={"system"} export GOOSE_PROVIDER="openai" export GOOSE_MODEL="qwen38-27b" export OPENAI_API_KEY="$PREM_API_KEY" export OPENAI_HOST="http://127.0.0.1:8787" export OPENAI_BASE_PATH="v1/chat/completions" ``` `OPENAI_HOST` contains the origin. `OPENAI_BASE_PATH` contains the Chat Completions path without a leading slash. A wrong path usually returns `404`. Goose documents this pattern under [custom OpenAI endpoints](https://goose-docs.ai/docs/getting-started/providers/#using-custom-openai-endpoints). The API key remains in the process environment instead of `~/.config/goose/config.yaml`. ## 5. Run Goose Run one chat-only request first: ```bash theme={"system"} GOOSE_MODE=chat goose run \ --no-session \ --text "Reply with exactly OK. Do not use tools." ``` Then test a tool-capable session in a controlled workspace: ```bash theme={"system"} GOOSE_MODE=approve goose run \ --with-builtin developer \ --text "Read README.md and summarize its first heading." ``` Use `approve` while evaluating commands. Goose can stream model output through the Chat Completions connection. A model-produced tool call returns through the encrypted model channel; Goose executes the tool locally. ## Tool and extension boundary | Component | Plaintext access | Notes | | - | - | - | | Goose | Yes | Reads prompts, workspace files, instructions, and tool results | | Confidential Proxy | Yes, locally | Encrypts model requests and decrypts responses | | Prem API Gateway | No content access | Receives ciphertext and operational metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs inference and encrypts the result | | Built-in or MCP extension | Depends on the tool | Uses its own permissions, credentials, storage, and network path | Limit enabled extensions, review permission mode, and run Goose from the narrowest required workspace. ## Agent limits All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). Goose sessions, recipes, and subagents all count toward it. Above it, new requests return `429`. Begin with one session. Do not switch to another provider if every model call must use Prem. ## Troubleshooting > [accordion] Goose returns 404 from the provider > > Set `OPENAI_HOST` to `http://127.0.0.1:8787` and `OPENAI_BASE_PATH` to `v1/chat/completions`. Do not put `/v1` in both values. > [accordion] Goose reports that no API key was passed > > Export `OPENAI_API_KEY="$PREM_API_KEY"` in the same process that starts Goose. Goose does not read provider API keys from `config.yaml`. > [accordion] The API returns model not found > > Call `/v1/models`, then set `GOOSE_MODEL` to a returned ID. > [accordion] The tool prompt is skipped or denied > > Check `GOOSE_MODE`, the enabled extension, and its permissions. Use `approve` during setup instead of bypassing tool confirmation. > [accordion] The API returns 429 > > For a concurrency rejection, wait for active requests to finish. Use fewer parallel sessions, recipes, and subagents across your organization. Separate keys do not increase the limit. See [Rate limits](/rate-limits) for other `429` errors. ## Frequently asked questions ### Does Goose need a custom provider plugin? No. Its built-in OpenAI provider supports a custom host and Chat Completions path. ### Is Goose itself inside the Prem enclave? No. Goose runs locally. Only supported model traffic uses the encrypted Prem path. ### Are extension calls confidential? Not automatically. The model call is protected through Prem, but each local or remote extension has its own trust boundary. ### Can I persist these settings? You can persist non-secret provider values in your shell or Goose configuration. Keep `OPENAI_API_KEY` in a secret manager or injected environment variable. ## ZDR setup > [!WARNING] > > ZDR is not confidential. Use this path only for non-sensitive prompts, > workspace context, and extension results. Goose uses ZDR through its built-in OpenAI provider and a separate API key. Confirm that `kimi-k3` appears in `GET /openai/models` for this key. Otherwise, use an exact returned model ID. See [Models & Pricing](/models-and-pricing). ```bash theme={"system"} export PREM_API_KEY="your-api-key" export GOOSE_PROVIDER="openai" export GOOSE_MODEL="kimi-k3" export OPENAI_API_KEY="$PREM_API_KEY" export OPENAI_HOST="https://gateway.prem.io" export OPENAI_BASE_PATH="openai/chat/completions" ``` Run a bounded request before enabling tools: ```bash theme={"system"} GOOSE_MODE=chat goose run \ --no-session \ --text "Reply with exactly: zdr ok" ``` This provider does not use the local proxy or KEK. See the [ZDR overview](/zdr/overview) and [Models & Pricing](/models-and-pricing). ## Related > [card] [Confidential Proxy](/confidential-proxy) > > Review proxy modes, routes, keys, and daemon controls. > [card] [OpenAI-compatible clients](/guides/openai-compatible-clients) > > Understand the protocol used by Goose. > [card] [Agents & Automation](/agents) > > Review concurrency, retries, and unattended operation. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the flow. # Hermes Agent Source: https://docs.prem.io/guides/hermes Connect Hermes Agent to Prem API through the local Confidential Proxy. Hermes Agent supports named custom providers that use the OpenAI Chat Completions protocol. Point one of those providers at Prem's local Confidential Proxy. > [!WARNING] > > Do not configure Prem under Hermes' `openai-api` provider. That provider can select the OpenAI Responses API, which the Confidential Proxy does not expose. Use a named custom provider with `transport: chat_completions`. > [tab] Confidential API > > Use the local Confidential Proxy for sensitive model traffic. [Go to the confidential setup](#confidential-api-setup). > [tab] ZDR > > Use Zero Data Retention (ZDR) for OpenAI-compatible inference with non-sensitive data. [Go to the ZDR setup](#zdr-setup). ## Confidential API setup This path uses the local Confidential Proxy to encrypt your prompts end-to-end before they leave your machine. ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] H["Hermes Agent"] -->|"Chat Completions"| P["Confidential Proxy
127.0.0.1:8787/v1"] T["Terminal, files, skills, and tools"] <--> H end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem confidential runtime
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"OpenAI-compatible response"| H ``` ## Before you start You need: * Hermes Agent installed. See the [Hermes Agent repository](https://github.com/NousResearch/hermes-agent). * A Prem API key. See [API Keys](/api-keys). * A 32-byte client KEK encoded as 64 hexadecimal characters. * The current Prem gateway and enclave endpoints. * A chat model returned by the Prem model-list endpoint. Check the installed version: ```bash theme={"system"} hermes --version ``` The configuration below has been exercised with Hermes Agent `0.20.0` using a one-shot response and a local file-reading tool call. ## 1. Set your secrets ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Generate the KEK once if you do not have one: ```bash theme={"system"} openssl rand -hex 32 ``` Keep `PREM_API_KEY` out of `config.yaml`. Hermes resolves it from the environment variable named by `key_env`. ## 2. Start the Confidential Proxy ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat openai \ --kek "$CLIENT_KEK" ``` > [!WARNING] > > Do not use `--no-attest`. Keep attestation enabled for confidential inference. ## 3. Select an enabled model ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` Use a returned `id`. This example uses `qwen38-27b`: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen38-27b", "messages": [{"role": "user", "content": "Reply with OK."}], "stream": false }' ``` Do not continue until this request succeeds. ## 4. Configure Hermes Add this provider to `~/.hermes/config.yaml`: ```yaml theme={"system"} providers: prem-confidential: api: http://127.0.0.1:8787/v1 key_env: PREM_API_KEY transport: chat_completions default_model: qwen38-27b models: qwen38-27b: context_length: 131072 model: default: qwen38-27b provider: custom:prem-confidential context_length: 131072 ``` Replace the model ID and context length when you choose another enabled model. Keep `transport: chat_completions` explicit. The keyed `providers` format is Hermes' current custom-provider schema. See the [Hermes custom-provider documentation](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/integrations/providers.md#named-custom-providers). Check the configuration: ```bash theme={"system"} hermes config check ``` ## 5. Run Hermes Start with a bounded one-shot request: ```bash theme={"system"} hermes --oneshot "Reply with exactly OK. Do not use tools." ``` Then start an interactive session: ```bash theme={"system"} hermes chat ``` Hermes can stream responses and perform tool calls through this provider. The model request and tool-call response use the encrypted model channel. Hermes runs the selected tool on your machine, then sends any resulting context in a later encrypted model request. ## Tool, memory, and gateway boundary | Component | Plaintext access | Notes | | - | - | - | | Hermes Agent | Yes | Reads prompts, memory, rules, workspace data, and tool results | | Confidential Proxy | Yes, locally | Encrypts model requests and decrypts responses | | Prem API Gateway | No content access | Receives ciphertext and operational metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs inference and encrypts the result | | Shell, skills, messaging gateways, and MCP servers | Depends on the integration | Remain outside the Prem confidential boundary | Hermes can connect to messaging channels and run scheduled work. Review sender allowlists, approval rules, toolsets, hooks, and outbound network access before enabling those surfaces. ## Agent limits All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). Hermes sessions, delegated tasks, fallback requests, and channel workers all count toward it. Above it, new requests return `429`. Begin with one session and no delegation. Do not use a non-Prem fallback if every model turn must use Prem's encrypted path. ## Troubleshooting > [accordion] Hermes calls /v1/responses > > The session is using the wrong provider. Set `model.provider` to `custom:prem-confidential` and keep `transport: chat_completions` in the named provider. > [accordion] Hermes reports a missing API key > > Export `PREM_API_KEY` in the process that starts Hermes. Confirm that `key_env` has the exact same name. > [accordion] The API returns model not found > > Call `/v1/models`. Use a returned ID in `default_model`, `providers.prem-confidential.models`, and `model.default`. > [accordion] A tool can read more than expected > > Limit Hermes toolsets, workspace access, approval settings, hooks, and MCP servers. Model-path confidentiality does not restrict local tool permissions. > [accordion] The API returns 429 > > For a concurrency rejection, wait for active requests to finish. Use fewer delegated tasks and parallel workers across your organization. Separate keys do not increase the limit. See [Rate limits](/rate-limits) for other `429` errors. ## Frequently asked questions ### Is Hermes itself running inside the enclave? No. Hermes runs locally. The Prem confidential boundary starts after the local proxy encrypts a supported model request. ### Why not use `OPENAI_BASE_URL` with the built-in OpenAI provider? That route can use `/v1/responses`. The named custom provider fixes the protocol to `/v1/chat/completions`, which the Confidential Proxy supports. ### Can Hermes tools use the encrypted connection? The model can request a tool through the encrypted model channel. Hermes executes the tool outside the enclave. A tool's own network traffic does not pass through Prem unless you configure that tool separately. ### Can Hermes use fallback providers? Yes, but a non-Prem fallback leaves the Prem inference path. Omit those fallbacks when the encrypted route is a requirement. ## ZDR setup > [!WARNING] > > ZDR is not confidential. Use this path only for non-sensitive prompts, > memory, workspace context, and tool results. Hermes uses ZDR through a second named provider. ## 1. Set your API key ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" ``` ## 2. Configure Hermes Add the `prem-zdr` provider to `~/.hermes/config.yaml`: ```yaml theme={"system"} providers: prem-zdr: api: https://gateway.prem.io/openai key_env: PREM_API_KEY transport: chat_completions default_model: kimi-k3 model: default: kimi-k3 provider: custom:prem-zdr ``` Confirm that `kimi-k3` appears in `GET /openai/models` for this key. Otherwise, use an exact returned model ID in `default_model`, `providers.prem-zdr.default_model`, and `model.default`. See [Models & Pricing](/models-and-pricing). Keep `transport: chat_completions` explicit so Hermes does not select the Responses API. The named custom provider format matches the Confidential API setup above. See the [Hermes custom-provider documentation](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/integrations/providers.md#named-custom-providers). Check the configuration: ```bash theme={"system"} hermes config check ``` ## 3. Verify Run a bounded one-shot request before starting a session: ```bash theme={"system"} hermes --oneshot "Reply with exactly: zdr ok" ``` Do not reuse the client KEK for ZDR. ## Related > [card] [Confidential Proxy](/confidential-proxy) > > Review proxy modes, routes, keys, and daemon controls. > [card] [OpenAI-compatible clients](/guides/openai-compatible-clients) > > Understand the protocol used by Hermes. > [card] [Agents & Automation](/agents) > > Review concurrency, retries, and unattended operation. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the flow. # Loupe Source: https://docs.prem.io/guides/loupe Understand the current compatibility boundary between Loupe, Claude Code, and Prem API. [Loupe](https://loupe.build/) is a macOS application that creates AI workers with a browser, terminal, and Claude Code chat. Loupe is not a separate OpenAI- or Anthropic-compatible model client. > [!WARNING] > > Loupe is not currently supported as a Prem integration. Its public documentation does not expose a provider, base URL, or launch-environment setting for embedded Claude Code workers, so the worker cannot be connected to the local Confidential Proxy through a documented configuration. ## What Loupe adds Loupe combines three local surfaces for each worker: * a Claude Code chat; * a terminal; * a browser with Chrome DevTools MCP access. It can pass console and terminal errors to its Claude Code worker. This makes Loupe an orchestration and user-interface layer around Claude Code, not another inference protocol. ```mermaid theme={"system"} flowchart TB subgraph Loupe["Loupe on macOS"] W["Worker"] B["Browser and DevTools MCP"] T["Terminal"] C["Embedded Claude Code"] B --> W T --> W W --> C end C -.->|"Requires a configurable Anthropic endpoint"| P["Confidential Proxy
127.0.0.1:8787/v1"] P -->|"Encrypted model request"| G["Prem API Gateway"] G --> E["Prem confidential runtime"] ``` The dotted connection is conditional. It exists only when Loupe passes Prem's Claude Code endpoint and authentication settings to the embedded process. ## Before you start Separate two questions: 1. **Does Claude Code work through Prem?** Yes. Use the tested [Claude Code guide](/guides/claude-code). 2. **Does Loupe expose the settings needed to make its embedded Claude Code use Prem?** This is not documented by Loupe today. A direct Loupe integration requires all of the following: * a Loupe build that exposes the embedded Claude Code launch environment or command; * a way to set the Anthropic base URL, authentication token, and model for that worker; * a Prem API key and 64-character hexadecimal client KEK; * a successful model-list request, non-streaming turn, streaming turn, and tool call; * confirmation that the worker did not fall back to Anthropic or another provider. ## Use Claude Code through Prem today Run Claude Code outside Loupe with Prem's launcher: ```bash theme={"system"} export API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" npx -p @premai/api-sdk@2.1.0 confidential-claude ``` This starts the local Confidential Proxy, selects an enabled Prem model, and launches Claude Code against the Anthropic-compatible endpoint. It does not reconfigure Loupe's embedded worker. ## Validate a future Loupe integration When Loupe exposes worker configuration, test it in this order: 1. Start the Confidential Proxy in Anthropic mode with attestation enabled. 2. Select a model returned by `/v1/models`. 3. Configure the embedded Claude Code process to use the local proxy and Prem API key. 4. Send a bounded prompt and confirm a request reaches the local proxy. 5. Confirm the response streams through the Anthropic Server-Sent Events route. 6. Run one file-reading tool call and confirm the tool executes locally. 7. Block the direct Anthropic endpoint during the test and confirm Loupe does not fall back. 8. Restart Loupe and confirm the provider configuration remains effective. The model name shown in the Loupe interface does not prove how the request was routed. Confirm that the request reaches the local proxy and that no direct provider connection occurs. ## Security boundary | Component | Plaintext access | Notes | | - | - | - | | Loupe | Yes | Coordinates workers, browser state, terminals, and error context | | Embedded Claude Code | Yes | Reads prompts, files, browser context, and tool results | | DevTools MCP and terminal | Yes, for the data they handle | Remain outside the Prem confidential runtime | | Confidential Proxy | Yes, locally | Encrypts configured model requests and decrypts responses | | Prem API Gateway | No content access | Receives ciphertext and operational metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs inference and encrypts the response | Even after model routing works, Loupe's browser, terminal, DevTools MCP, worker state, and local logs remain separate security surfaces. ## Troubleshooting > [accordion] Loupe offers no provider or environment setting > > The direct integration is not available through the documented product surface. Use Claude Code through `confidential-claude` outside Loupe and request an explicit worker-provider setting from Loupe. > [accordion] Loupe still calls Anthropic directly > > Stop the test. The embedded Claude Code process did not receive or retain the Prem endpoint configuration. Do not treat the session as protected by Prem. > [accordion] The proxy receives no request > > Confirm that Loupe launches the worker with the required environment. A proxy running on `127.0.0.1:8787` is not sufficient by itself. > [accordion] Tools work but the model route is unclear > > Tool execution proves only the local Loupe workflow. Confirm model traffic independently at the Confidential Proxy. ## Frequently asked questions ### Is Loupe a model provider? No. Loupe describes each worker as a browser, terminal, and Claude Code chat. ### Does the Claude Code integration prove that Loupe works with Prem? No. It proves the underlying Claude Code path. Loupe must still expose or inherit the same provider configuration for its embedded worker. ### Can Prem protect Loupe's browser or terminal traffic? No. Prem's model path does not place browser, terminal, DevTools MCP, or local worker state inside the confidential runtime. ### What would make Loupe compatible? A documented worker configuration surface and an end-to-end acceptance test that proves model traffic reaches the local proxy without direct-provider fallback. ## Related > [card] [Claude Code](/guides/claude-code) > > Use the tested Claude Code path through Prem. > [card] [Anthropic-compatible clients](/guides/anthropic-compatible-clients) > > Review the Messages protocol and compatibility limits. > [card] [Confidential Proxy](/confidential-proxy) > > Review proxy modes, routes, and keys. > [card] [Security Model](/security-model) > > Review what the confidential inference path protects. # OpenAI-compatible clients Source: https://docs.prem.io/guides/openai-compatible-clients Connect an OpenAI-compatible SDK or application to Prem API through the Confidential Proxy. Does your app already talk to the OpenAI API? Then you can point it at Prem instead. You change one setting: the base URL. Prem runs the model inside a secure enclave. Your prompts stay private on the way there. You connect through a small helper on your machine: the **[Confidential Proxy](/confidential-proxy)**. > [!WARNING] > > "OpenAI-compatible" describes the shape of the requests. It does not mean the requests go to OpenAI. It does not mean an OpenAI model runs behind them. > [tab] Confidential API > > Use the local Confidential Proxy for sensitive model traffic. [Go to the confidential setup](#confidential-api-setup). > [tab] ZDR > > Use Zero Data Retention (ZDR) for OpenAI-compatible inference with non-sensitive data. [Go to the ZDR setup](#zdr-setup). ## Confidential API setup This path uses the local Confidential Proxy to encrypt your prompts end-to-end before they leave your machine. ## What the proxy does * Accepts the client's OpenAI-compatible request on your machine. * Encrypts request content before network egress. * Sends ciphertext and required metadata through the Prem API Gateway. * Decrypts the enclave response locally and returns the supported OpenAI-compatible response shape. ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] C["OpenAI-compatible client"] -->|"Chat Completions request"| P["Confidential Proxy
127.0.0.1:8787/v1"] end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Route encrypted payload"| E["Prem API Enclave
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"OpenAI-compatible response"| C ``` Your app and the Confidential Proxy stay on your machine. The Prem API Gateway sees only the sealed message. The Prem API Enclave opens it inside a Trusted Execution Environment (TEE). ## What you can connect You can connect any client that lets you set a custom base URL. For example: * OpenAI SDKs for Node.js, Python, and other languages. * Agent frameworks that support a custom OpenAI provider. * Internal apps that call `/v1/chat/completions`. * Audio apps that use the transcription or translation routes. The proxy gives your app the routes below. It does not add every OpenAI feature. | Method | Route | What it does | | - | - | - | | API shape | Sends OpenAI-style JSON or multipart data | Accepts the supported OpenAI routes | | Authentication | Sends `Authorization: Bearer ` | Uses the value as the Prem API key | | Model | Sends a Prem model ID | Sends that model ID to Prem API | | Request content | Plaintext inside the client process | Encrypts content before network egress | | Response content | Receives OpenAI-style output | Decrypts and returns the response locally | | Billing | Reads usage fields when available | Prem bills the organization associated with the API key | The client does not gain every OpenAI API feature. It gains the routes that the Confidential Proxy implements. ## Supported routes The inspected package implements these OpenAI-compatible routes: | Method | Route | Purpose | | - | - | - | | `GET` | `/v1/models` | List enabled Prem models | | `POST` | `/v1/chat/completions` | Run chat completion requests, including streaming | | `POST` | `/v1/audio/transcriptions` | Transcribe supported audio inputs | | `POST` | `/v1/audio/translations` | Translation route; no enabled translation model is currently documented | The current Deepgram transcription response is not normalized to OpenAI's `{ "text": "..." }` shape. It returns Deepgram-style `metadata` and `results` fields. > [!WARNING] > > Do not expect the Responses, Assistants, Realtime, Batches, Embeddings, or Files APIs. Check the Prem API reference before you use another route. ## Before you start Get these four things ready: * **An app** that lets you set a custom OpenAI base URL. * **A Prem API key.** This proves who you are. See [API Keys](/api-keys). * **A client Key Encryption Key (KEK).** This is a master key that protects your other keys. * **A model** that your Prem account can use. See [Models & Pricing](/models-and-pricing). > [!NOTE] > > The API key and the KEK are two different secrets. The API key handles sign-in, limits, and billing. The KEK protects your encryption keys. Keep both safe. ## 1. Set your secrets Open a terminal. Set these values in the terminal that runs the proxy: ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Do you not have a KEK yet? Make one, one time only: ```bash theme={"system"} openssl rand -hex 32 ``` Store the KEK in a secret manager. Keep a backup. Use the **same** KEK every time. Do not make a new one each time you start the proxy. > [!NOTE] > > `PROXY_URL` and `ENCLAVE_URL` show the current default endpoints. Check the [Prem dashboard](https://dashboard.prem.io) if the endpoints change. ## 2. Start the Confidential Proxy Start the proxy in OpenAI mode. Keep this terminal open while you work: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat openai \ --kek "$CLIENT_KEK" ``` The proxy now listens at `http://127.0.0.1:8787/v1`. Your app sends its requests there. Do you need one proxy for both OpenAI and Anthropic apps? Start it in `both` mode: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat both \ --kek "$CLIENT_KEK" ``` In `both` mode, the OpenAI base URL is `http://127.0.0.1:8787/openai/v1`. ## 3. Point your app at the proxy List the models that your Prem API key can use: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` Use the returned `id` value in later requests. Do not substitute an OpenAI model name unless Prem lists that exact ID. See [Models & Pricing](/models-and-pricing) for the models available in each inference mode. ## 4. Test chat completions Send a small non-streaming request: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "messages": [{"role": "user", "content": "Reply with OK."}], "max_completion_tokens": 128, "stream": false }' ``` Replace `deepseek-v4.1-flash-1017` when your account uses another model. Inspect the response `model` field as well as the requested model. The response may contain a resolved backend ID rather than the public alias. Do not continue if this request fails. See [Errors](/errors) and [Rate limits](/rate-limits). ## 5. Configure the application Change only the API key and base URL when the application already uses Chat Completions. ```typescript Node.js theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY, baseURL: "http://127.0.0.1:8787/v1", }); const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Reply with OK." }], max_completion_tokens: 128, }); console.log(response.choices[0]?.message?.content); ``` ```python Python theme={"system"} import os from openai import OpenAI client = OpenAI( api_key=os.environ["PREM_API_KEY"], base_url="http://127.0.0.1:8787/v1", ) response = client.chat.completions.create( model="deepseek-v4.1-flash-1017", messages=[{"role": "user", "content": "Reply with OK."}], max_completion_tokens=128, ) print(response.choices[0].message.content) ``` Change `deepseek-v4.1-flash-1017` to a model your account can use. See your model IDs on the [Prem dashboard](https://dashboard.prem.io). Other clients name the base URL setting in different ways. Look for `baseURL`, `base_url`, endpoint, host, or provider URL. ## What this setup protects | Component | Reads your text | Notes | | - | - | - | | Your app | Yes | It creates the prompt and reads the reply on your machine. | | Confidential Proxy | Yes, on your machine | It seals requests and opens replies. | | Prem API Gateway | No | It handles the sealed message and metadata only. | | Prem API Enclave | Yes, inside the TEE | It opens the request, runs the model, and seals the reply. | | App tools and plugins | Depends on the tool | Prem does not put them inside the enclave. | > [!WARNING] > > This setup protects the model path only. It does not put your app, its tools, or its plugins inside the enclave. ## Good to know **Use a Prem model ID.** Compatibility does not give you OpenAI-hosted models. Use a model that `/v1/models` returns. **Shared Confidential concurrency.** All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). Above it, new requests return `429`. Obey `Retry-After` when the response has it. See [Agents & Automation](/agents). **Check the finish reason.** Read `finish_reason` on each response. Do not treat a cut-off reply as a complete one. ## Troubleshooting > [accordion] The app still calls api.openai.com > > Check the base URL setting. Restart the app after you change it. > [accordion] The API says model not found > > List your models with `/v1/models`. Use an enabled Prem model ID from that list. > [accordion] The app calls /v1/responses > > Set the app to use Chat Completions. The proxy does not expose the Responses API. > [accordion] Streaming stops early > > Check `finish_reason`, timeout settings, proxy logs, and rate limits. Do not treat partial content as complete. > [accordion] The API returns 429 > > Wait for the active request to finish. Follow `Retry-After` when the response has it. ## Frequently asked questions ### Does "OpenAI-compatible" mean OpenAI processes the request? No. The term describes the HTTP interface only. The request goes through Prem and uses the Prem model you choose. ### Can I use an OpenAI model name? Only when `/v1/models` returns that exact ID. Compatibility does not give you OpenAI-hosted models. ### Can I use the Responses API? No. Set the client to use `/v1/chat/completions`. ### Which key goes in the Authorization header? The Prem API key. The KEK is a separate local secret. Never send the KEK. ### Does changing the base URL protect my local tools? No. It protects the model path after the proxy seals the request. Your local tools keep their own trust boundaries. ## ZDR setup > [!WARNING] > > ZDR is not confidential. Do not send secrets, personal data, regulated > data, or other sensitive data through this path. An OpenAI-compatible Chat Completions client can call ZDR directly: | Setting | Confidential API | ZDR | | - | - | - | | Base URL | `http://127.0.0.1:8787/v1` | `https://gateway.prem.io/openai` | | API key | `PREM_API_KEY` | `PREM_API_KEY` | | Client KEK | Required by the local proxy | Not used | | Confidential | Yes, within the documented boundary | No | | Model catalog | Confidential catalog | ZDR catalog | Confirm that `kimi-k3` appears in `GET /openai/models` for this key. Otherwise, use an exact returned model ID. See [Models & Pricing](/models-and-pricing). ```typescript theme={"system"} const zdrClient = new OpenAI({ apiKey: process.env.PREM_API_KEY, baseURL: "https://gateway.prem.io/openai", }); const response = await zdrClient.chat.completions.create({ model: "kimi-k3", messages: [{ role: "user", content: "Reply with zdr ok." }], }); ``` Use an exact ID returned for that key. See [Models & Pricing](/models-and-pricing). ## Related > [card] [Confidential Proxy](/confidential-proxy) > > Review every mode, route, key, and daemon option. > [card] [OpenCode](/guides/opencode) > > Configure OpenCode as a specific OpenAI-compatible client. > [card] [OpenClaw](/guides/openclaw) > > Configure a custom Chat Completions provider. > [card] [Hermes Agent](/guides/hermes) > > Use a named provider with the Chat Completions transport. > [card] [Goose](/guides/goose) > > Point Goose's built-in OpenAI provider at the proxy. > [card] [Anthropic-compatible clients](/guides/anthropic-compatible-clients) > > Use the Messages API shape through the same proxy. > [card] [Agents & Automation](/agents) > > Handle concurrency, retries, reasoning, and unattended operation. > [card] [Platform Status](/platform-status) > > Review released infrastructure and SDK capabilities. # OpenClaw Source: https://docs.prem.io/guides/openclaw Connect OpenClaw to Prem API through the local Confidential Proxy. OpenClaw can use Prem API as a custom OpenAI-compatible provider. OpenClaw sends Chat Completions requests to the local Confidential Proxy, which encrypts them before network egress. > [!WARNING] > > OpenClaw, its workspace, channels, local tools, plugins, and MCP servers remain outside the Prem confidential runtime. This setup protects supported model traffic, not the complete agent. > [tab] Confidential API > > Use the local Confidential Proxy for sensitive model traffic. [Go to the confidential setup](#confidential-api-setup). > [tab] ZDR > > Use Zero Data Retention (ZDR) for OpenAI-compatible inference with non-sensitive data. [Go to the ZDR setup](#zdr-setup). ## Confidential API setup This path uses the local Confidential Proxy to encrypt your prompts end-to-end before they leave your machine. ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] O["OpenClaw"] -->|"OpenAI Chat Completions"| P["Confidential Proxy
127.0.0.1:8787/v1"] T["Workspace, tools, channels, and MCP"] <--> O end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem confidential runtime
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"OpenAI-compatible response"| O ``` ## Before you start You need: * OpenClaw installed. See the [OpenClaw setup guide](https://docs.openclaw.ai/start/setup). * A Prem API key. See [API Keys](/api-keys). * A 32-byte client KEK encoded as 64 hexadecimal characters. * The current Prem gateway and enclave endpoints. * A chat model returned by your Prem model-list request. Check the installed version: ```bash theme={"system"} openclaw --version ``` This configuration has been exercised with OpenClaw `2026.7.1-2` using a normal agent turn and a local file-reading tool call. ## 1. Set your secrets ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Generate the KEK once if you do not have one: ```bash theme={"system"} openssl rand -hex 32 ``` Store the KEK in a secret manager. Do not place either secret in `openclaw.json` as a literal value. ## 2. Start the Confidential Proxy ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat openai \ --kek "$CLIENT_KEK" ``` > [!WARNING] > > Do not use `--no-attest`. Keep attestation enabled for confidential inference. ## 3. Select an enabled model ```bash theme={"system"} curl http://127.0.0.1:8787/v1/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` Use an `id` returned by this request. The example below uses `qwen38-27b`. Test it before starting OpenClaw: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen38-27b", "messages": [{"role": "user", "content": "Reply with OK."}], "stream": false }' ``` ## 4. Configure OpenClaw OpenClaw reads JSON5 from `~/.openclaw/openclaw.json`. Add a custom provider: ```json theme={"system"} { "models": { "mode": "merge", "providers": { "prem-confidential": { "baseUrl": "http://127.0.0.1:8787/v1", "apiKey": "${PREM_API_KEY}", "api": "openai-completions", "timeoutSeconds": 600, "models": [ { "id": "qwen38-27b", "name": "Qwen 3.8 27B through Prem", "reasoning": true, "input": ["text"], "contextWindow": 131072, "maxTokens": 8192 } ] } } }, "agents": { "defaults": { "model": { "primary": "prem-confidential/qwen38-27b" } } } } ``` The provider must use `api: "openai-completions"`. The Confidential Proxy does not expose `/v1/responses`. OpenClaw allows the exact `baseUrl` origin in its guarded model-request path. See the [OpenClaw custom-provider reference](https://docs.openclaw.ai/gateway/config-tools#custom-providers-and-base-urls). Validate the file: ```bash theme={"system"} openclaw config validate ``` ## 5. Run one agent turn Run a bounded local turn before connecting channels or schedules: ```bash theme={"system"} openclaw agent \ --local \ --agent main \ --message "Reply with exactly OK." \ --json ``` Inspect the returned provider and model. They should identify `prem-confidential` and the model you configured. OpenClaw can stream model output through the Chat Completions connection. Tool calls return through the encrypted model channel, but OpenClaw executes each tool in its local environment. ## Tool and channel boundary | Component | Plaintext access | Notes | | - | - | - | | OpenClaw | Yes | Reads prompts, channel messages, memory, and tool results | | Confidential Proxy | Yes, locally | Encrypts model requests and decrypts responses | | Prem API Gateway | No content access | Receives ciphertext and operational metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs inference and encrypts the result | | Channel, plugin, tool, or MCP server | Depends on its function | Uses its own storage, credentials, and network boundary | Review channel allowlists, tool permissions, secret storage, workspace access, and external egress separately. ## Agent limits All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). All OpenClaw agents in your organization count toward it. Above it, new requests return `429`. Begin with one worker. Read [Agents & Automation](/agents) before you use unattended schedules or channels. ## Troubleshooting > [accordion] OpenClaw rejects the configuration > > Run `openclaw config validate`. Check the field names and confirm that `api` is `openai-completions`. > [accordion] OpenClaw calls /v1/responses > > The provider is using the wrong adapter. Set `api` to `openai-completions` and restart the affected agent process. > [accordion] The provider cannot reach 127.0.0.1:8787 > > Confirm that the Confidential Proxy is running in the same host environment. A container or remote OpenClaw worker needs a reachable proxy address instead of its own loopback interface. > [accordion] The API returns model not found > > Call `/v1/models` with the Prem API key and use a returned model ID in both provider locations. > [accordion] The API returns 429 > > For a concurrency rejection, wait for active requests to finish. Use fewer parallel agent turns across your organization. Separate keys do not increase the limit. See [Rate limits](/rate-limits) for other `429` errors. ## Frequently asked questions ### Is OpenClaw running inside the enclave? No. OpenClaw runs on your machine. Only supported model inference traffic passes through the encrypted Prem path. ### Does OpenClaw need the Prem TypeScript SDK? No. It calls the OpenAI-compatible surface exposed by the local proxy. ### Can OpenClaw use tools through this setup? Yes, when the selected model produces compatible tool calls. OpenClaw executes those tools outside the enclave. ### Can I expose the proxy to a remote OpenClaw host? Yes, but that changes the local trust boundary. Use TLS, authenticated private networking, a restrictive firewall, and a controlled host binding. Do not expose an unauthenticated plaintext listener to the public internet. ## ZDR setup > [!WARNING] > > ZDR is not confidential. Use this path only for non-sensitive prompts, > workspace context, and tool results. OpenClaw uses ZDR through a separate `openai-completions` provider. ## 1. Set your API key ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" ``` ## 2. Configure OpenClaw Add the `prem-zdr` provider to `~/.openclaw/openclaw.json`: ```json theme={"system"} { "models": { "mode": "merge", "providers": { "prem-zdr": { "baseUrl": "https://gateway.prem.io/openai", "apiKey": "${PREM_API_KEY}", "api": "openai-completions", "timeoutSeconds": 600, "models": [ { "id": "kimi-k3", "name": "Kimi K3 (ZDR)" } ] } } }, "agents": { "defaults": { "model": { "primary": "prem-zdr/kimi-k3" } } } } ``` The provider must use `api: "openai-completions"`. Confirm that `kimi-k3` appears in `GET /openai/models` for this key and use an exact returned `id` in both the `models` entry and the agent `primary`. Otherwise, use an exact returned model ID. See [Models & Pricing](/models-and-pricing). Add `reasoning`, `contextWindow`, and `maxTokens` to the `models` entry when you set model-specific values, as in the Confidential API setup above. Validate the file: ```bash theme={"system"} openclaw config validate ``` ## 3. Verify Run a bounded local turn before connecting channels or schedules: ```bash theme={"system"} openclaw agent \ --local \ --agent main \ --message "Reply with exactly: zdr ok" \ --json ``` Inspect the returned provider and model. It should identify `prem-zdr` and `kimi-k3`. Do not start the Confidential Proxy or pass a KEK for this provider. ## Related > [card] [Confidential Proxy](/confidential-proxy) > > Review modes, routes, keys, and daemon controls. > [card] [OpenAI-compatible clients](/guides/openai-compatible-clients) > > Understand the interface used by OpenClaw. > [card] [Agents & Automation](/agents) > > Review concurrency, retries, and unattended operation. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the flow. # OpenCode Source: https://docs.prem.io/guides/opencode Connect OpenCode to Prem API through the local Confidential Proxy. OpenCode is a coding assistant that runs in your terminal. This guide connects it to Prem API. Prem runs the model inside a secure enclave. Your prompts stay private on the way there. > [!NOTE] > > OpenCode does not use the TypeScript SDK directly. It uses the OpenAI-compatible routes from the Confidential Proxy. The proxy is part of `@premai/api-sdk`. > [tab] Confidential API > > Use the local Confidential Proxy for sensitive prompts and source code. [Go to the confidential setup](#confidential-api-setup). > [tab] ZDR > > Use Zero Data Retention (ZDR) for OpenAI-compatible inference with non-sensitive data. [Go to the ZDR setup](#zdr-setup). ## Confidential API setup This path uses the local Confidential Proxy to encrypt your prompts end-to-end before they leave your machine. ### Use the bundled launcher When updating the SDK, [restart the managed proxy](/confidential-proxy#upgrade-an-existing-proxy) before launching. The launcher can reuse a daemon that is already running. `@premai/api-sdk` includes `confidential-opencode`. It automates the manual setup below: it starts or reuses the local proxy in Anthropic mode, lists your enabled models, lets you pick one, and launches the installed `opencode` command against the local endpoint. It needs OpenCode 2, an interactive terminal, and the same endpoints and keys as the manual setup. The launcher reads the Prem API key from `API_KEY`, not `PREM_API_KEY`: ```bash theme={"system"} export API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" npx -p @premai/api-sdk@2.1.0 confidential-opencode ``` The launcher passes its provider configuration through `OPENCODE_CONFIG_CONTENT` and starts OpenCode with `--standalone`. It ignores the project `opencode.json` and turns off model fetching, sharing, and auto-update. It picks the model itself, so it drops `--model` and `-m` from the arguments you pass. It forwards the rest to OpenCode, which needs a subcommand before any flag. Use `confidential-opencode run ` when you pass a subcommand. Stop the proxy it started with `confidential-proxy stop`. The manual steps below configure the same connection by hand. Use them when you want to control the `opencode.json` yourself. ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] O["OpenCode"] -->|"OpenAI-compatible request"| P["Confidential Proxy
127.0.0.1:8787/v1"] end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Route the encrypted payload"| E["Prem API Enclave (TEE)
decrypt, infer, encrypt"] E -.->|"Encrypted response returns on the same path"| P P -.->|"Decrypt on your machine"| O ``` OpenCode and the Confidential Proxy stay on your machine. The Prem API Gateway sees only the sealed message. The Prem API Enclave opens it inside a Trusted Execution Environment (TEE). ## Before you start Get these four things ready: * **OpenCode.** Both OpenCode 1 and OpenCode 2 work with Prem API. Pick your version below. * **A Prem API key.** This proves who you are. See [API Keys](/api-keys). * **A client Key Encryption Key (KEK).** This is a master key that protects your other keys. * **A model** that your Prem account can use. See [Models & Pricing](/models-and-pricing). > [!NOTE] > > The API key and the KEK are two different secrets. The API key handles sign-in, limits, and billing. The KEK protects your encryption keys. Keep both safe. ### Which OpenCode version are you? > [tab] OpenCode 1 > > Install OpenCode 1: > > ```bash theme={"system"} > curl -fsSL https://opencode.ai/install | bash > ``` > > This guide shows the OpenCode 1 configuration keys (`provider`, `options`, `permission`) in each setup step. > [tab] OpenCode 2 > > Install OpenCode 2: > > ```bash theme={"system"} > curl -fsSL https://opencode.ai/v2/install | bash > ``` > > OpenCode 1 and OpenCode 2 both use the `opencode` command. > You cannot install both side by side with the same command. > > This guide shows the OpenCode 2 configuration keys (`providers`, `package`, `settings`, `permissions`) in each setup step. ## 1. Set your secrets Open a terminal. Set these values in the terminal that runs the proxy: ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Do you not have a KEK yet? Make one, one time only: ```bash theme={"system"} openssl rand -hex 32 ``` Store the KEK in a secret manager. Keep a backup. Use the **same** KEK every time. Do not make a new one each time you start the proxy. > [!NOTE] > > `PROXY_URL` and `ENCLAVE_URL` show the current default endpoints. Check the [Prem dashboard](https://dashboard.prem.io) if the endpoints change. ## 2. Start the Confidential Proxy Start the proxy in OpenAI mode. Keep this terminal open while you work: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --host 127.0.0.1 \ --port 8787 \ --compat openai \ --kek "$CLIENT_KEK" ``` The proxy now listens at `http://127.0.0.1:8787/v1`. OpenCode sends its requests there. ## 3. Do a proxy test Send one request before you start OpenCode: ```bash theme={"system"} curl http://127.0.0.1:8787/v1/chat/completions \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek-v4.1-flash-1017", "messages": [{"role": "user", "content": "Reply with OK."}], "max_completion_tokens": 128, "stream": false }' ``` Use a different model ID if your account does not have `deepseek-v4.1-flash-1017`. Inspect the response `model` field. The response may contain a resolved backend ID rather than the public alias. The response does not include an assurance-profile field. See [Platform Status](/platform-status). Do not continue if this request does not complete. See [Errors](/errors) and [Rate limits](/rate-limits). ## 4. Configure OpenCode Create `opencode.json` in the project root: > [tab] OpenCode 1 > > ```json theme={"system"} > { > "$schema": "https://opencode.ai/config.json", > "model": "prem-confidential/deepseek-v4.1-flash-1017", > "small_model": "prem-confidential/deepseek-v4.1-flash-1017", > "enabled_providers": ["prem-confidential"], > "share": "disabled", > "provider": { > "prem-confidential": { > "npm": "@ai-sdk/openai-compatible", > "name": "Prem API through the Confidential Proxy", > "options": { > "baseURL": "http://127.0.0.1:8787/v1", > "apiKey": "{env:PREM_API_KEY}", > "timeout": 600000, > "chunkTimeout": 60000 > }, > "models": { > "deepseek-v4.1-flash-1017": { > "name": "DeepSeek V4.1 Flash · 1017" > } > } > } > }, > "permission": { > "edit": "ask", > "bash": "ask" > } > } > ``` > > Here is what each part does: > > | Setting | What it does | > | - | - | > | `baseURL` | Sends OpenCode's requests to your local proxy. | > | `apiKey` | Reads the Prem API key from your terminal. | > | `model` and `small_model` | Uses Prem for big and small tasks. | > | `enabled_providers` | Uses Prem only. No other provider. | > | `share: disabled` | Does not create public chat links. | > | `permission` | Asks you before it edits files or runs shell commands. | > > This follows the [OpenCode custom provider docs](https://opencode.ai/docs/providers/). Change `deepseek-v4.1-flash-1017` to the model your account uses. Change it in both `model` and `models`. > [tab] OpenCode 2 > > ```json theme={"system"} > { > "$schema": "https://opencode.ai/config.json", > "model": "prem-confidential/deepseek-v4.1-flash-1017", > "share": "disabled", > "providers": { > "prem-confidential": { > "name": "Prem API through the Confidential Proxy", > "env": ["PREM_API_KEY"], > "package": "@opencode/ai/providers/openai-compatible", > "settings": { > "baseURL": "http://127.0.0.1:8787/v1" > }, > "models": { > "deepseek-v4.1-flash-1017": { > "name": "DeepSeek V4.1 Flash · 1017" > } > } > } > }, > "permissions": [ > { "action": "edit", "resource": "*", "effect": "ask" }, > { "action": "shell", "resource": "*", "effect": "ask" } > ] > } > ``` > > Here is what each part does: > > | Setting | What it does | > | - | - | > | `baseURL` | Sends OpenCode's requests to your local proxy. | > | `env` | Reads the Prem API key from your terminal. | > | `model` | Uses Prem for all tasks. | > | `share: disabled` | Does not create public chat links. | > | `permissions` | Asks you before it edits files or runs shell commands. | > > This follows the [OpenCode 2 providers guide](https://opencode.ai/v2/docs/providers/). Change `deepseek-v4.1-flash-1017` to the model your account uses. Change it in both `model` and `models`. ## 5. Start OpenCode Start OpenCode from the folder that has `opencode.json`: ```bash theme={"system"} opencode ``` Send a short prompt, such as "Say hello." Watch the proxy terminal. You see the request arrive. That is it. OpenCode now talks to Prem through the sealed path. > [!TIP] > > Type `/models` in OpenCode to check the model. The provider shows as **Prem API through the Confidential Proxy**. ## What this setup protects | Component | Reads your text | Notes | | - | - | - | | OpenCode | Yes | It reads your prompt, your code, and the tool results on your machine. | | Confidential Proxy | Yes, on your machine | It seals requests and opens replies. | | Prem API Gateway | No | It handles the sealed message and metadata only. | | Prem API Enclave | Yes, inside the TEE | It opens the request, runs the model, and seals the reply. | | External tool or MCP server | Depends on the tool | A tool reads the data that OpenCode sends to it. | > [!WARNING] > > This setup protects the model path only. It does not put OpenCode, your code, shell commands, plugins, MCP servers, or local files inside the enclave. ## Good to know **Tool calls run on your machine.** The model can ask OpenCode to run a tool. The model traffic uses the sealed path. But OpenCode runs the tool on your machine, outside the enclave. So keep the `edit` and `bash` permissions set to `ask`. Do not treat a private model as a private tool. **Shared Confidential concurrency.** All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). Above it, new requests return `429`. Begin with one OpenCode session and no parallel subagents. See [Agents & Automation](/agents). ## Troubleshooting > [accordion] OpenCode cannot connect > > Check that the proxy runs at `127.0.0.1:8787`. Check that `baseURL` ends with `/v1`. > [accordion] The proxy returns 401 > > Check that `PREM_API_KEY` is correct. Check that the API key is active. > [accordion] The API says model not found > > Change `deepseek-v4.1-flash-1017` to a model your account can use. Change it in `model` and in `models`. > [accordion] The API returns 429 > > Wait for active streams to finish. Reduce parallel work. Follow the `Retry-After` header if the response has one. > [accordion] OpenCode shows a different provider > > Check that `enabled_providers` lists only `prem-confidential`. Restart OpenCode after you change `opencode.json`. ## Frequently asked questions ### Which OpenCode versions work with Prem API? Both OpenCode 1 and OpenCode 2. Pick your version at the top of the setup, and each configuration step shows the keys for your version. ### Does OpenCode use the Prem TypeScript SDK? No. The local proxy gives OpenCode an OpenAI-compatible interface. OpenCode does not import the SDK. ### Is the API key the same as the KEK? No. The API key handles access, limits, and billing. The KEK protects your encryption keys. ### Does this protect my whole OpenCode session? No. It protects the model path. OpenCode and its local tools stay on your machine. ### Can OpenCode use tool calls? Yes, when the selected model supports tool calls. The model traffic uses the encrypted path. OpenCode runs each tool outside the enclave. ## ZDR setup > [!WARNING] > > ZDR is not confidential. Do not send secrets, private source code, > personal data, or regulated data through this path. ZDR uses a separate OpenCode provider. It does not use the Confidential Proxy, client KEK, or attestation path. Confirm that `kimi-k3` appears in `GET /openai/models` for this key. Otherwise, use an exact returned model ID. See [Models & Pricing](/models-and-pricing). ## 1. Set your API key ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" ``` OpenCode reads the key from this environment variable via the `{env:PREM_API_KEY}` reference in the provider config below. ## 2. Configure OpenCode Add the `prem-zdr` provider in `opencode.json` at the project root: > [tab] OpenCode 1 > > ```json theme={"system"} > { > "$schema": "https://opencode.ai/config.json", > "model": "prem-zdr/kimi-k3", > "enabled_providers": ["prem-zdr"], > "share": "disabled", > "provider": { > "prem-zdr": { > "npm": "@ai-sdk/openai-compatible", > "name": "Prem ZDR", > "options": { > "baseURL": "https://gateway.prem.io/openai", > "apiKey": "{env:PREM_API_KEY}", > "timeout": 600000, > "chunkTimeout": 60000 > }, > "models": { > "kimi-k3": { > "name": "Kimi K3 (ZDR)" > } > } > } > } > } > ``` > > | Setting | What it does | > | - | - | > | `baseURL` | Sends OpenCode's requests to the ZDR gateway. No `/v1` segment; `/openai` is the ZDR route. | > | `apiKey` | Reads the Prem API key from the `PREM_API_KEY` environment variable. | > | `model` | Uses `prem-zdr/kimi-k3` as the default model. | > | `enabled_providers` | Uses Prem only. No other provider. | > [tab] OpenCode 2 > > ```json theme={"system"} > { > "$schema": "https://opencode.ai/config.json", > "model": "prem-zdr/kimi-k3", > "share": "disabled", > "providers": { > "prem-zdr": { > "name": "Prem ZDR", > "env": ["PREM_API_KEY"], > "package": "@opencode/ai/providers/openai-compatible", > "settings": { > "baseURL": "https://gateway.prem.io/openai" > }, > "models": { > "kimi-k3": { > "name": "Kimi K3 (ZDR)" > } > } > } > } > } > ``` > > | Setting | What it does | > | - | - | > | `baseURL` | Sends OpenCode's requests to the ZDR gateway. No `/v1` segment; `/openai` is the ZDR route. | > | `env` | Reads the Prem API key from the `PREM_API_KEY` environment variable. | > | `model` | Uses `prem-zdr/kimi-k3` as the default model. | Change `kimi-k3` to the model your key can use in both `model` and `models`. Keep the provider names separate when both paths are configured: | Path | Provider | Key | Data boundary | | - | - | - | - | | Confidential API | `prem-confidential` | `PREM_API_KEY` | Encrypted through the local proxy | | ZDR | `prem-zdr` | `PREM_API_KEY` | Not confidential | ## 3. Verify Run a model-list check, then a bounded request, then start OpenCode: ```bash theme={"system"} # From the project folder containing opencode.json: OpenCode sees the provider opencode models prem-zdr # A real request through Prem ZDR opencode run --model prem-zdr/kimi-k3 "Reply with exactly: PREM_ZDR_OK" # Start OpenCode normally; Prem ZDR is the default opencode ``` `opencode models prem-zdr` should list `prem-zdr/kimi-k3`. The bounded request should return `PREM_ZDR_OK`. Use a model ID your key can use if your key does not have `kimi-k3`. ## Related > [card] [Confidential Proxy](/confidential-proxy) > > Learn the proxy modes, routes, keys, and daemon controls. > [card] [Agents & Automation](/agents) > > Review concurrency, retries, reasoning, and error controls. > [card] [OpenAI-compatible clients](/guides/openai-compatible-clients) > > Understand the compatibility layer that OpenCode uses. > [card] [Security Model](/security-model) > > Learn what the enclave protects and what stays outside the TEE. > [card] [Production Checklist](/production-checklist) > > Complete the key, reliability, capacity, and attestation checks. > [card] [Platform Status](/platform-status) > > Review released infrastructure and SDK capabilities. # Pi Source: https://docs.prem.io/guides/pi Connect Pi to Prem API with the Prem provider extension. Pi is a coding agent that runs in your terminal. The `@premai/api-extension-pi` extension registers a `prem-api` provider inside Pi. By default the extension encrypts model requests inside the Pi process, so you do not need the local Confidential Proxy. > [!WARNING] > > Use extension **0.1.1** or later. > [tab] Confidential API > > Use the extension's built-in encryption for sensitive model traffic. [Go to the confidential setup](#confidential-api-setup). > [tab] ZDR > > Use Zero Data Retention (ZDR) for OpenAI-compatible inference with non-sensitive data. [Go to the ZDR setup](#zdr-setup). ## Confidential API setup This path encrypts your prompts end-to-end before they leave your machine. ## How the connection works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] P["Pi"] --> X["Prem extension
attest and encrypt"] T["Terminal, files, and tools"] <--> P end X -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem confidential runtime
decrypt, infer, encrypt"] E -.->|"Encrypted response"| X ``` ## Before you start You need: * **Pi**, installed. See the [Pi install guide](https://pi.dev/docs/latest/install). * **A Prem API key.** See [API Keys](/api-keys). * **A 32-byte client KEK** encoded as 64 hexadecimal characters. Optional, see below. * **An enabled confidential chat model.** See [Models & Pricing](/models-and-pricing). ## 1. Set your environment Set these variables in the terminal that runs Pi: ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" ``` Generate the KEK once if you do not have one: ```bash theme={"system"} openssl rand -hex 32 ``` The extension reads `PREM_API_KEY` at request time. Without `CLIENT_KEK`, the extension generates an ephemeral KEK for each Pi process. Leave `ENABLE_ZDR` unset for this path. ## 2. Install the extension Add the extension and default provider to your Pi `settings.json`: ```json theme={"system"} { "packages": ["npm:@premai/api-extension-pi@0.1.1"], "defaultProvider": "prem-api" } ``` The extension registers the provider when Pi starts. It refreshes the available chat models from `GET /rvenc/models` and sends encrypted requests to `/rvenc/chat/completions`. Pi picks a model from the returned catalog; set `defaultModel` if you want a specific enabled model, for example `qwen38-27b`. ## 3. Start Pi Start Pi from the folder containing your settings: ```bash theme={"system"} pi ``` Send a short prompt using an enabled confidential model. ## Configuration | Variable | Required | Value | | - | - | - | | `PREM_API_KEY` | Yes | Your Prem API key | | `CLIENT_KEK` | No | 64 hexadecimal characters. Defaults to an ephemeral key per process | | `PROXY_URL` | No | Defaults to `https://gateway.prem.io` | | `ENCLAVE_URL` | No | Defaults to `https://conf-engine.prem.io` | | `ENABLE_ZDR` | No | Leave unset. `true` switches to the [ZDR setup](#zdr-setup) | ## Security boundary | Component | Plaintext access | Notes | | - | - | - | | Pi and the extension | Yes, locally | Read prompts, workspace data and tool results. The extension encrypts model requests and decrypts responses | | Prem API Gateway | No content access | Receives ciphertext and operational metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs inference and encrypts the result | | Shell, plugins and MCP servers | Depends on the integration | Remain outside the Prem confidential boundary | Tool calls run on your machine or on the external services you configure. Model-path confidentiality does not protect local files, shell commands, plugins or MCP servers. Review the data each tool receives and the permissions it has. ## Usage and concurrency All API keys in your organization share one Confidential [concurrency limit](/tiers#concurrent-requests). Additional Pi sessions or API keys do not increase it. Above it, new requests return `429`. See [Agents & Automation](/agents). ## Troubleshooting > [accordion] Pi does not show the prem-api provider > > Check that the extension is in the `packages` array. Restart Pi after changing `settings.json`. > [accordion] The provider returns 401 > > Check that `PREM_API_KEY` is correct and active in the terminal running Pi. > [accordion] The API says model not found > > Select a model returned by the catalog for your mode: `GET /rvenc/models` for the Confidential API, `GET /openai/models` for ZDR. Restart Pi after changing `ENABLE_ZDR`. > [accordion] Attestation fails > > Check that `settings.json` pins extension `0.1.1` or later, then restart Pi. If you set `PROXY_URL` or `ENCLAVE_URL`, confirm they point at the current Prem endpoints. > [accordion] Pi warns that CLIENT\_KEK is not set > > The extension generated an ephemeral KEK for this process. Export `CLIENT_KEK` before starting Pi to reuse one key across runs. > [accordion] The API returns 429 > > Wait for active requests to finish and reduce parallel work. Follow `Retry-After` when present. See [Rate limits](/rate-limits). ## ZDR setup > [!WARNING] > > ZDR is not confidential. It does not provide client-side encryption or attestation. Use this path only for non-sensitive prompts, workspace context and tool results. Pi uses [ZDR](/zdr/overview) through the same extension and `settings.json`. ## 1. Set your environment ```bash theme={"system"} export PREM_API_KEY="your-prem-api-key" export ENABLE_ZDR=true ``` ZDR requires no client KEK. Do not reuse the client KEK for ZDR. ## 2. Start Pi ```bash theme={"system"} pi ``` With `ENABLE_ZDR=true`, the extension refreshes chat models from `GET /openai/models` and sends requests to `/openai/chat/completions`. Send a short prompt using an enabled ZDR model. See [Models & Pricing](/models-and-pricing). ZDR requests travel over HTTPS, but the Prem API Gateway and inference partner process plaintext content. Retention is governed by the ZDR agreement and operational controls. See [ZDR security boundary](/zdr/security-boundary). All API keys share the organization's ZDR request, concurrency and token allowances. See [Tiers](/tiers). ## Related > [card] [Attestation](/attestation) > > Understand what the client verifies before it encrypts a request. > [card] [ZDR overview](/zdr/overview) > > Understand the ZDR API and its data-handling contract. > [card] [Models & Pricing](/models-and-pricing) > > Find models available to your API key and inference mode. > [card] [Agents & Automation](/agents) > > Review concurrency, retries, reasoning and error controls. # Qwen Code Source: https://docs.prem.io/guides/qwen-code Launch Qwen Code through Prem's Confidential Proxy with the bundled confidential-qwen wrapper. The `@premai/api-sdk` package contains `confidential-qwen`. This launcher starts the Confidential Proxy in Anthropic mode. Then it runs the installed Qwen Code CLI against the proxy. > [!WARNING] > > The local proxy encrypts supported model traffic before network egress. Qwen Code, repository files, shell commands, MCP servers, and tool results remain on your machine or in their own external systems. > [tab] Confidential API > > Use `confidential-qwen` to connect Qwen Code through the local Confidential Proxy. [Go to the confidential setup](#before-you-start). > [tab] ZDR > > ZDR is not available for `confidential-qwen`. The launcher drives Qwen Code over the Anthropic Messages API. ZDR supports only OpenAI-compatible Chat Completions. Use [OpenCode](/guides/opencode), [OpenClaw](/guides/openclaw), [Hermes Agent](/guides/hermes), or [Goose](/guides/goose) for a ZDR coding workflow. ## How the launcher works ```mermaid theme={"system"} flowchart TB subgraph Local["Your machine: plaintext is available"] C["Qwen Code"] -->|"Anthropic Messages API"| P["Confidential Proxy
127.0.0.1:8787"] T["Local tools and MCP servers"] <--> C end P -->|"Encrypt before network egress"| G["Prem API Gateway
ciphertext and metadata"] G -->|"Encrypted request"| E["Prem confidential runtime
decrypt, infer, encrypt"] E -.->|"Encrypted response"| P P -.->|"Anthropic SSE or message"| C ``` The launcher does these steps on every run: 1. Requires an interactive terminal (TTY). 2. Reads the endpoint, key, and KEK configuration. 3. Starts or reuses the proxy in Anthropic mode with attestation enabled. 4. Displays the list of your enabled models. 5. Prepares an isolated Qwen home and chooses the `anthropic` authentication type. 6. Sets the Qwen Code Anthropic base URL and the model environment variables. 7. Sends every remaining argument to the installed `qwen` command. > [!NOTE] > > Qwen Code connects to Prem through its Anthropic provider. It does not use Qwen OAuth or a DashScope key. The launcher passes `--auth-type anthropic` and removes all OAuth, OpenAI, Gemini, and Google credentials from the child environment. ## Before you start You need: * Qwen Code installed and available as `qwen` on `PATH`. * A Prem API key. * A 32-byte KEK encoded as 64 hexadecimal characters. * A terminal with interactive input. * `@premai/api-sdk`. Check the installed Qwen Code version: ```bash theme={"system"} qwen --version ``` > [!WARNING] > > Use `@premai/api-sdk@2.1.0` for Qwen and DeepSeek. Confirm the binary with `npx -p @premai/api-sdk@2.1.0 confidential-qwen --help`. ## 1. Set the launcher values ```bash theme={"system"} export API_KEY="your-prem-api-key" export CLIENT_KEK="your-64-character-hex-kek" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Generate the KEK once if you do not have one: ```bash theme={"system"} openssl rand -hex 32 ``` `confidential-qwen` reads `API_KEY`, not `PREM_API_KEY`. Supply it through the environment. This also prevents the launcher from prompting for the API key and saving it in the application-data `.env` file. The launcher still saves the selected model ID there. > [!NOTE] > > `confidential-qwen` uses its own application-data directory. The directory is separate from the one that `confidential-claude` uses. Configure each launcher once. ## 2. Run the first request When updating the SDK, [restart the managed proxy](/confidential-proxy#upgrade-an-existing-proxy) before launching. The launcher can reuse a daemon that is already running. Use `--prompt` for a bounded first test: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-qwen \ --prompt "Reply with exactly OK. Do not use tools." ``` Choose an enabled model in the picker. Use the arrow keys or `j` and `k`. Then press Enter. > [!NOTE] > > `--prompt` still needs a TTY. The launcher always shows the model list before it starts Qwen Code. ## 3. Start an interactive session ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-qwen ``` Qwen Code uses the Anthropic-compatible Messages route. It receives Server-Sent Events while it works. ## Arguments the launcher owns The launcher sets the model and the authentication type itself. It removes these flags from the arguments that you pass. It removes both the `--flag value` and `--flag=value` forms: | Flag | Reason | | - | - | | `--model` | The picker sets the model | | `-m` | Short form of `--model` | | `--auth-type` | The launcher requires `anthropic` | The launcher sends every other argument to `qwen` without changes. Choose a different model by restarting the launcher and selecting it in the picker. ## Model selection The picker calls the model-list endpoint on every run. This guide documents these chat models: | Picker ID | Display name | Current catalogue behavior | | - | - | - | | `qwen38-27b` | Qwen 3.8 | Text, image, and video input metadata | | `deepseek-v4.1-flash-1017` | DeepSeek V4.1 Flash · 1017 | Multimodal chat model | The Anthropic adapter returns the requested alias in the message `model` field. It does not show the backend-resolved model ID or an assurance profile. Do not infer an assurance class from the picker label. See [Platform Status](/platform-status). > [!NOTE] > > A Qwen picker label names a Prem catalogue model. It does not show that Qwen Code connects to an Alibaba-hosted Qwen endpoint. ## Isolated Qwen home The launcher does not write Prem credentials into `~/.qwen/settings.json`. It builds a private `QWEN_HOME` under its application-data directory for the session: * The launcher links your existing `~/.qwen` entries into the private home. Extensions, commands, and history remain available. * The launcher copies `settings.json`. Then the copy sets the `anthropic` authentication type. * The launcher merges your settings changes back into `~/.qwen/settings.json` when Qwen Code exits. It restores your original authentication and model keys. It removes the local endpoint and the API key from anything it writes back. * The launcher removes the private home on exit. A later run also removes directories that a previous run leaves behind after a crash. The launcher prints a warning if it cannot parse `~/.qwen/settings.json`. It leaves the file unchanged. It does not sync anything back. > [!NOTE] > > Set `QWEN_HOME` before you start the launcher. The launcher reads that location as your real Qwen home. It still isolates the session from it. ## Environment the launcher sets | Variable | Value | | - | - | | `ANTHROPIC_BASE_URL` | The local proxy root, including the route prefix | | `ANTHROPIC_API_KEY` | Your Prem API key | | `ANTHROPIC_MODEL` | The model that you selected | | `QWEN_HOME` | The private session home | | `QWEN_STREAM_IDLE_TIMEOUT_MS` | `600000`, which permits long confidential responses | The launcher removes `ANTHROPIC_AUTH_TOKEN`, `QWEN_OAUTH`, `QWEN_MODEL`, and the `OPENAI_`, `GEMINI_`, and `GOOGLE_` credential and model variables from the child environment. A stale credential cannot redirect traffic away from the proxy. ## Stop the local proxy The launcher starts a detached proxy. The proxy continues to run when Qwen Code exits. Stop it explicitly when you finish: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy stop ``` Check the status before another run when the default proxy port appears occupied: ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy status ``` `confidential-claude` and `confidential-qwen` share one proxy in Anthropic mode. You do not need a second proxy to run both at the same time. One `confidential-proxy stop` ends the session for both. ## Plaintext and tool boundary | Component | Plaintext access | Notes | | - | - | - | | Qwen Code | Yes | Reads prompts, selected repository files, and tool results locally | | Confidential Proxy | Yes, locally | Translates, encrypts, and decrypts model traffic | | Prem API Gateway | No content access | Receives ciphertext, authentication, and routing metadata | | Prem confidential runtime | Yes, inside the protected runtime | Runs the selected model and encrypts the response | | Shell, MCP servers, and extensions | Depends on the tool | Outside the Prem inference boundary | Review Qwen Code permissions, MCP servers, extensions, and egress separately. A confidential model route does not protect local tool execution. ## Troubleshooting > [accordion] TTY environment required > > Run the command directly in an interactive terminal. Piping input or starting it from a non-interactive CI process does not supply the interactive terminal that model selection needs. > [accordion] install qwen code > > Install Qwen Code and confirm that `qwen --version` succeeds in the same shell. See the [Qwen Code documentation](https://qwenlm.github.io/qwen-code-docs/en/users/overview/). > [accordion] Failed to fetch models from proxy > > Check `API_KEY`, `PROXY_URL`, `ENCLAVE_URL`, network access, and proxy logs. Make sure that the key can list models. > [accordion] A proxy is running in OpenAI-only mode > > The launcher needs an Anthropic Messages route. It refuses to use a proxy that cannot serve one. Run `confidential-proxy stop`. Then start the launcher again. Pre-start the proxy with `confidential-proxy start --compat anthropic` or `--compat both`. > [accordion] The default proxy port is occupied > > Run `confidential-proxy status`. Then stop the managed proxy. The launcher refuses to take over an unknown process on that port. > [accordion] Qwen Code asks for OAuth or a DashScope key > > A stale credential or authentication setting overrides the Anthropic provider. Confirm that you did not pass `--auth-type`. Check `~/.qwen/settings.json` for a pinned authentication type. > [accordion] could not parse \~/.qwen/settings.json > > The launcher still runs. But it does not sync settings back. Repair the JSON. Then start it again. > [accordion] Attestation fails > > Do not add `--no-attest` to work around the failure. Capture the error. Verify the current Reticle boundary in [Attestation](/attestation). ## Frequently asked questions ### Does `confidential-qwen` install Qwen Code? No. It checks for an existing `qwen` command. It exits if Qwen Code is not installed. ### Does it use my Qwen or DashScope credentials? No. `API_KEY` is the Prem API key. The launcher clears all Qwen OAuth, OpenAI, Gemini, and Google variables. It passes the Prem key to Qwen Code as the Anthropic provider token. ### Does it change my Qwen Code configuration? It runs the session against a private home. It merges your settings changes back into `~/.qwen/settings.json` on exit. It does not write the local endpoint or the API key. Your original authentication and model keys are restored. ### Can I pass normal Qwen Code arguments? Yes, except `--model`, `-m`, and `--auth-type`. The launcher sets those values and removes them. ### Can I run it beside `confidential-claude`? Yes. Both use Anthropic mode and share one proxy. ### Is the full coding session inside an enclave? No. Only supported inference traffic uses the encrypted Prem path. Files and tools remain in their own local or external trust boundaries. ## Related > [card] [Claude Code](/guides/claude-code) > > Review the sibling launcher that shares the same proxy mode. > [card] [Anthropic-compatible clients](/guides/anthropic-compatible-clients) > > Review the Messages translation and compatibility limits. > [card] [Confidential Proxy](/confidential-proxy) > > Review proxy modes, routes, keys, and daemon controls. > [card] [Security Model](/security-model) > > Review the protected and unprotected parts of the data flow. # React Native (BareKit) Source: https://docs.prem.io/guides/react-native Run the Prem TypeScript SDK inside a react-native-bare-kit worklet. Building a mobile app? You get the same confidentiality and security as on the server. The `@premai/api-sdk` TypeScript client runs inside a [react-native-bare-kit](https://github.com/holepunchto/react-native-bare-kit) worklet. It encrypts each request on the device, before the request leaves the phone. The Prem API Gateway sees only ciphertext. The enclave opens the request inside a Trusted Execution Environment (TEE). The encryption path is identical to the [standard client](/quickstart). The worklet runs the same WASM cryptography, so the [security model](/security-model) and [attestation](/attestation) guarantees also apply on mobile. This is the same method that powers [Sotto](https://sotto.prem.io), Prem's confidential dictation app. > [!TIP] > > Want a working starting point? The [`reticle-expo`](https://github.com/prem-research/reticle-expo) example app runs the worklet on iOS and Android. It verifies enclave attestation from the device, with no server-side proxy. Clone it and use it as a scaffold for your own app. ## Pass an assets directory Pass an `assets` directory to `new Worklet(...)`. bare-kit extracts the bundled assets to that directory at startup. It then rewrites the paths to real `file://` URLs. The WASM module loads from disk on the fast path. ```js theme={"system"} import { Worklet } from "react-native-bare-kit"; import * as FileSystem from "expo-file-system"; const cacheDir = new FileSystem.Directory(FileSystem.Paths.cache, "reticle-assets"); if (!cacheDir.exists) cacheDir.create(); const worklet = new Worklet({ assets: cacheDir.uri.replace(/^file:\/\//, ""), }); await worklet.start("/worklet.bundle", source); ``` > [!NOTE] > > If you omit `assets`, the SDK falls back to an inline base64 copy of the WASM bytes. The disk path is faster, so pass `assets` when you can. ## Related > [card] [reticle-expo example](https://github.com/prem-research/reticle-expo) > > Clone the example Expo app and use it as a scaffold. > [card] [Attestation](/attestation) > > See how the device verifies real confidential hardware. > [card] [Confidential Proxy](/confidential-proxy) > > Learn the proxy modes, routes, keys, and daemon controls. > [card] [Quickstart](/quickstart) > > Send your first encrypted request with the TypeScript client. # Run Attestation Source: https://docs.prem.io/guides/run-attestation Run confidential enclave attestation directly with Reticle. The Prem SDK and the Confidential Proxy verify attestation automatically. To check a confidential runtime yourself, use `@premai/reticle`, the same verifier they use. > [!NOTE] > > You need a Prem API key. Create one in the [Prem Dashboard](https://dashboard.prem.io). ## 1. Install Reticle ```bash theme={"system"} npm install @premai/reticle@0.6.2 ``` Reticle runs on Node.js, Bun, Deno, modern browsers, and mobile devices (iOS and Android via [React Native](/guides/react-native)). ## 2. Verify the runtime ```typescript theme={"system"} import { ClientBuilder, QueryParams } from "@premai/reticle"; const apiKey = process.env.PREM_API_KEY; const proxyUrl = process.env.PROXY_URL || "https://gateway.prem.io"; if (!apiKey) { throw new Error("Set the PREM_API_KEY environment variable"); } const client = await new ClientBuilder(proxyUrl) .with_authorization(apiKey) .build(); client.set_query(new QueryParams().with("model", "deepseek-v4.1-flash-1017")); const result = await client.attest(); console.log("Verified modules:", result.modules()); console.log("Session ID:", result.headers().get("x-session-id")); ``` The builder loads and verifies signed policies and measurement references from [Trustbase](https://github.com/prem-research/trustbase). `client.attest()` then: 1. Generates a fresh challenge and requests a unified report for the selected model. 2. Verifies CPU evidence and manufacturer collateral, including the challenge bound to the workload manifest. 3. Checks supplied GPU evidence, including signatures, digest links and the nonce bound to the CPU report. 4. Evaluates policy claims and CPU measurements against the signed release references for registered PodVM releases and workload initialization data. > [!WARNING] > > `request_attestation(nonce)` retrieves raw evidence without performing these checks. Use `attest()` for a verification decision. ## 3. Read the result `attest()` throws if a required verification or policy check fails. On success, the result exposes: | Method | Returns | | - | - | | `modules()` | The verified modules | | `headers()` | Response headers, including `x-session-id` | | `pod_report()` | The workload manifest | A standalone Reticle call does not send an inference request. The Prem SDK is what forwards the session ID with protected requests. This guide uses the standard attestation flow for the [Confidential chat models](/models-and-pricing#confidential-models). See [Attestation](/attestation) for what a pass does and does not show. ## Related > [card] [Attestation Concept](/attestation) > > Read the full attestation architecture and current implementation status. > [card] [Security Model](/security-model) > > Understand the threat model and confidential computing boundaries. > [card] [Trustbase](https://github.com/prem-research/trustbase) > > Inspect signed release references and attestation policies. > [card] [Mobile Example (Expo)](https://github.com/prem-research/reticle-expo) > > See how to run on-device Reticle verification in React Native. # How It Works Source: https://docs.prem.io/how-it-works Architecture overview: how the SDK or local proxy encrypts content for processing in the Prem confidential runtime. > [!NOTE] > > **Scope:** This page tells you about the **confidential inference** path. The [Zero Data Retention](/zdr/overview) mode uses a different path. That path has no client-side encryption and no enclave. See [ZDR security boundary](/zdr/security-boundary). ## The Simple Version This is the core idea, before the architecture diagrams: 1. **You type a prompt.** 2. **Your device encrypts the prompt** before it sends data over the network. 3. **Our gateway receives the encrypted payload.** The gateway handles authentication and billing, but it cannot read your data. 4. **The encrypted payload enters a sealed hardware environment** (a Confidential Virtual Machine). There, the enclave decrypts the payload, the AI model processes it, and the enclave encrypts the response again. 5. **The encrypted response travels back to your device.** Your device decrypts the response and shows it. Your data is plaintext in your application and, when used, the local Confidential Proxy. The protected runtime must decrypt it to process the request. The network-facing Prem gateway handles ciphertext plus authentication, routing, size, timing, and billing metadata. ## Architecture Overview ```mermaid theme={"system"} flowchart LR subgraph You["Your Device"] SDK["Prem API SDK"] end subgraph Platform["Prem API Platform"] Proxy["Proxy Gateway"] Enclave["Secure Enclave (TEE)"] end subgraph Infra["Supporting Services"] S3["Encrypted File Storage"] VectorDB["RAG"] Redis["Redis Cache"] end SDK -->|"encrypted payload"| Proxy Proxy -->|"encrypted payload"| Enclave Enclave --> S3 Enclave --> VectorDB Proxy --> Redis Enclave -->|"encrypted response"| Proxy Proxy -->|"encrypted response"| SDK ``` ## The Components ### Your Device: The Prem API SDK The SDK runs on your side: your laptop, your server, your application, or your browser. It is the only location, besides the sealed enclave, where your data exists in readable form. The functions of the SDK: * **Encrypts all data** before the data leaves your device, with modern, quantum-resistant cryptography * **Holds your master encryption key**: a key that you generate and that never leaves your device * **Decrypts responses** when they come back From the perspective of your code, the SDK operates like the standard OpenAI SDK. The encryption is invisible. The SDK does the encryption automatically. ### PREM API: The Blind Gateway The proxy is the entry point of the platform. The proxy handles the operational tasks: it checks your API key, enforces rate limits, tracks usage for billing, and routes requests. **The critical point: the proxy never sees your actual data.** The proxy processes only encrypted payloads and metadata, such as API keys and timestamps. It has no encryption keys and no method to decrypt the data that passes through it. The proxy must collect this metadata to operate the platform. The metadata is necessary for billing, rate limits, routing, health, and capacity monitoring. | What the Proxy does | What the Proxy cannot do | | - | - | | Validate your API key and permissions | Read your prompts or responses | | Enforce rate limits for your organization | Access any encryption keys | | Route encrypted payloads to the correct enclave | Log or inspect your data | | Track usage for billing | Decrypt the files that you uploaded | If an attacker compromises the Prem API Gateway, the intended exposure is encrypted content plus operational metadata. A local Confidential Proxy is different: it is a client-side plaintext termination point and belongs inside your local trust boundary. ### Prem API Enclave: The Sealed Processing Environment The enclave is the location where your data is processed. The enclave runs inside a **Trusted Execution Environment (TEE)**, a sealed area of the processor with its own encrypted memory. The rest of the system cannot access this memory. The enclave is comparable to a bank vault inside a building. The building owner has keys to every room. But the vault has its own lock, and the building owner cannot open this lock. In this analogy, the "building" is the server. The "building owner" is the operator of the server: us, or our infrastructure provider. The "vault" is the TEE. The steps inside the enclave: 1. Your encrypted payload arrives. 2. The enclave decrypts the payload with a secure key exchange. 3. The AI model processes your request. 4. The enclave encrypts the response before the response leaves. 5. The enclave wipes all plaintext from memory. The enclave runs on **AMD SEV-SNP** or **Intel TDX** processors, with **NVIDIA Hopper and Blackwell architecture GPUs** in confidential compute mode. On the Blackwell **HGX** nodes, the GPUs run in NVIDIA's MPT CC mode: up to eight GPUs are passed through to the same Confidential VM, transfers between the host and the GPUs are encrypted, and the GPUs communicate over encrypted NVLink. The [Confidential chat models](/models-and-pricing#confidential-models) use standard attestation with SDK 2.1.0. See [Security Model](/security-model) for the full MPT CC description. The isolation is not a software setting that admin privileges can turn off. ### Model Routing Model routing selects a backend for the requested alias, applies health and capacity decisions, and associates an attestation session with the subsequent request. The public API does not currently expose a machine-readable provider-backed or Reticle-verifiable assurance profile. Do not infer the complete backend trust boundary from an alias. See [Platform Status](/platform-status) for the current limitation. ### Confidential boundary The intended confidential boundary contains the components that decrypt or process protected content. The network gateway remains outside and handles encrypted payloads plus operational metadata. The released SDK uses Reticle 0.6.2 to verify signed Trustbase policies and compare CPU measurements with approved release references. See [Attestation](/attestation). ### The Infrastructure Locations Prem API runs on a **hybrid infrastructure**, a mix of hardware that we own and capacity that we rent: * **Owned infrastructure** is in **Switzerland**, under Swiss data protection law * **Rented infrastructure** is primarily in **Europe**, with some deployments in the **United States** TEE hardware is designed to reduce trust in the host operator. Deployment access controls, geography, and unattended-operation claims are operational controls that must be audited separately. [Attestation](/attestation) explains how the client verifies hardware evidence and release measurements. ## The Lifecycle of a Chat Request This is the full lifecycle of a chat request: ```mermaid theme={"system"} sequenceDiagram participant You as Your Device participant Gateway as Proxy (sees only encrypted data) participant Enclave as Sealed Enclave (CVM) participant LLM as AI Model (inside CVM) Note over You: 1. Prepare You->>Enclave: Request enclave's public key Enclave-->>You: Public key Note over You: 2. Encrypt You->>You: Generate shared secret with enclave You->>You: Encrypt your message Note over You,Proxy: 3. Send (encrypted) You->>Proxy: Encrypted payload Note over Proxy: Check API key, rate limits Proxy->>Enclave: Forward (still encrypted) Note over Enclave: 4. Process (sealed hardware) Enclave->>Enclave: Decrypt your message Enclave->>LLM: Run inference LLM-->>Enclave: AI response Enclave->>Enclave: Encrypt response Note over Enclave,You: 5. Return (encrypted) Enclave-->>Proxy: Encrypted response Proxy-->>You: Forward (still encrypted) You->>You: Decrypt and display ``` For **streaming responses** (word-by-word output in the style of ChatGPT), the enclave encrypts each chunk individually before it sends the chunk. The proxy forwards the chunks and does not buffer or inspect them. ## The Tasks That the SDK Does for You The SDK does all these tasks automatically. You do not need to: * Understand or manage encryption algorithms * Do key exchanges manually * Encrypt or decrypt data in your application code * Handle streaming decryption From the perspective of your application, you make standard API calls and get standard responses. The encryption layer is fully invisible. > [!NOTE] > > See the [Encryption](/encryption) reference for the full cryptographic details: algorithms, key types, and protocols. Continue to [Security Model](/security-model) for the security guarantees and their limits. # Idempotency Source: https://docs.prem.io/idempotency Ensure safe retries and prevent duplicates using the Idempotency-Key header. We support **idempotent requests** so that you can retry safely without duplicates. This is important for actions that **create resources**, **upload files**, or **modify data**. For these actions, repeated requests can cause unwanted side effects. ## The definition of idempotency With idempotency, the **same request, sent many times**, has the **same effect** as one request. If your client gets a timeout or a network error, retry the request with the **same idempotency key**. We process the request only **once**. ## The operation of idempotency To make an idempotent request, include a unique key in the header: `Idempotency-Key: your-unique-idempotency-key` We store the **status code and response body** of the first request for that key. Each subsequent request with the same key: * Returns the **original result**, for success or for failure * Prevents **duplicate processing** of resource creation or updates * Keeps **data integrity** across retries This behavior applies also if the first request caused a `500` or other server error. This keeps the result consistent for all outcomes. > [!NOTE] > > The API ignores the `Idempotency-Key` in `GET` or `DELETE` requests. ## Inference paths are not idempotent The **inference endpoints** are **not idempotent**: * `/rvenc/` * `/openai/` The API **ignores** the `Idempotency-Key` header on these paths. Inference responses are streamed or returned directly and are not stored against an idempotency key, so a retry with the same key cannot be replayed. If you need to avoid duplicate inference calls, handle retries in your client (for example, by tracking which requests already completed). ## Key Expiration * We store idempotency keys for **24 hours**. * After expiration, the API treats the same key as a **new request**. * Keys can be **up to 255 characters long**. ## Response Headers When you use an `Idempotency-Key`, we include these response headers. They help clients see how we processed the request: | Header | Description | | - | - | | `Idempotency-Key` | Shows the key from the request. This confirms that the API accepted and applied the key | | `Idempotency-Status` | Shows how we processed the request: `new`: the first execution of the key, `replayed`: a cached response from an earlier identical request | Example: ``` HTTP/1.1 200 OK Idempotency-Key: 6aa2f8a3-4ef4-4899-8234-d45a93d1f191 Idempotency-Status: replayed ``` These headers help you debug retries. They show if the API replayed the result or generated a new one. ## Best Practices * Use a **UUIDv4** or another random, high-entropy string to generate keys. * **Use a key again** only when you retry the **same exact request**. * **Do not use the same key** for different operations, endpoints, or payloads. > [!NOTE] > > Prem API rejects a repeat request with the same key if the **parameters differ** from the original. This prevents accidental misuse. ## When to Use Idempotency Use idempotency for each request where duplication has negative effects. Use it when you: * Upload encrypted files * Create or modify resources with the API * Send webhooks or external callbacks * Start long-running or asynchronous tasks ## Summary | Header | Required | Description | | - | - | - | | `Idempotency-Key` | Optional (but recommended for all `POST`/`PUT`/`PATCH` requests) | Makes sure that the API performs a given operation only once, also after retries | The idempotency layer of Prem API **does not cache invalid requests**. If a request fails validation, or if we reject it before execution, we do not store the key. You can retry those requests. If you need help with implementation or with debugging, contact [support@premai.io](mailto:support@premai.io). Include your request payload and your idempotency key. # What is Prem API Source: https://docs.prem.io/index Client-encrypted model APIs with confidential-computing evidence and explicit assurance boundaries. > [!NOTE] > > **In one sentence:** Prem API provides OpenAI- and Anthropic-compatible model routes with client-side encryption and confidential-computing evidence. The released verifier checks CPU measurements against signed references. ## The Problem When you use a standard AI API, your prompts, files, and conversations are processed on infrastructure that you do not control. HTTPS protects data in transit, but the service normally receives plaintext for processing. For many teams, this model is acceptable. Teams handling patient records, financial data, legal documents, source code, or trade secrets may need a narrower processing boundary and evidence they can inspect. Prem API changes where plaintext is available and adds confidential-computing evidence. It does not remove every dependency or trust assumption. ## What Prem API Does Prem API exposes supported chat and audio routes. The TypeScript SDK or local Confidential Proxy encrypts the request payload before network egress. The gateway handles ciphertext and operational metadata, and the selected processing runtime decrypts the payload for inference. > [card] Client-side encryption > > The SDK or local proxy encrypts the request payload before sending it to the Prem gateway. > [card] Gateway boundary > > The gateway receives payload ciphertext plus authentication, model, size, timing, routing, and billing metadata. > [card] Protected processing > > Supported confidential routes process plaintext inside a Trusted Execution Environment (TEE). Attestation evidence and policy define what the client can conclude about that runtime. ## The Comparison with a Standard AI API | | Standard AI API | Prem API | | - | - | - | | **Access to your data** | The provider, the provider's staff, and possibly the cloud host | Your application and the protected processing runtime; a local proxy also sees plaintext when used | | **Gateway payload** | The service normally receives the request body | The Prem gateway receives ciphertext plus operational metadata | | **Processing boundary** | Provider-managed workload | A supported confidential route uses a protected runtime; verify the selected route | | **Security evidence** | Provider policy, controls, and audit material | Hardware-signed evidence plus measurement, TCB, and route policy | | **Host access control** | Defined by the provider's architecture | Confidential-computing hardware is designed to restrict host access; deployment validation still applies | | **API compatibility** | Provider-specific | Supported subsets of OpenAI- and Anthropic-compatible interfaces | ## Who Prem API Is For > [card] Regulated Industries > > Healthcare, finance, legal, and government teams that need to map an AI data path to their own legal, compliance, and security controls. > [card] AI Application Builders > > Development teams that need a client-encrypted inference path and can validate the supported API surface. > [card] Security-First Organizations > > Teams that require hardware evidence and an explicit policy decision in addition to provider documentation. > [card] Enterprises with Sensitive IP > > Companies evaluating AI for internal documents, proprietary code, or strategic planning under a defined threat model. ## What You Can Do Today Prem API exposes a supported subset of OpenAI-compatible and Anthropic-compatible interfaces: * **Chat with AI models**: Streaming conversations, multi-step reasoning, and tool use * **Transcribe audio**: Use the currently enabled Deepgram model and its response shape * **Make decisions**: Answer typed questions with probabilities through [Decisions](/guides/decisions) The Prem API has two inference modes: * **Confidential inference**: Client-side encryption, a Trusted Execution Environment, and attestation evidence that you can examine. Use this mode for sensitive data and for production workloads. * **[Zero Data Retention](/zdr/overview)**: An OpenAI-compatible endpoint that needs no code changes. Prem sends the request to a trusted partner, and the partner keeps no content. Use this mode for evaluation, for prototypes, and for public data. See [ZDR vs Confidential](/zdr/comparison) for the decision. See [Platform Status](/platform-status) for the released confidential infrastructure and SDK integration. ## Get Started You can integrate Prem API into an application, or you can evaluate Prem API for your organization. The procedure is the same: **1. Install the SDK** ```bash theme={"system"} npm install @premai/api-sdk@2.1.0 ``` **2. Create a client with your encryption key** ```typescript theme={"system"} import { createRvencClient } from "@premai/api-sdk"; const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK, // You generate this. We never see it. }); ``` **3. Send a chat request** ```typescript theme={"system"} const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello, privately." }], }); ``` For Python, Go, or another language, use the bundled local proxy with a client that supports a custom base URL and the documented routes. Check the [Confidential Proxy](/confidential-proxy) compatibility limits before rollout. ## What to Read Next > [card] [How It Works](/how-it-works) > > Learn the architecture: the function of each component and the data flow through the system. > [card] [Security Model](/security-model) > > Examine the trust model: TEEs, attestation, the threat model, and the known limitations. > [card] [Developer Experience](/developer-experience) > > Read the integration guide: SDK options, capabilities, code examples, and the API reference. > [card] [Platform Status](/platform-status) > > See the features that are available today, the features that are not ready, and the roadmap. > [card] [Agents & Automation](/agents) > > Building an unattended or agentic system? Start here. > [card] [Zero Data Retention](/zdr/overview) > > The standard mode. It is OpenAI-compatible, it uses trusted partners, and nobody keeps your content. > [!NOTE] > > Go to the [Quickstart guide](/quickstart) to start immediately. # Legal Source: https://docs.prem.io/legal Prem's Terms of Service and Privacy Policy. ## Terms of Service The Prem Terms of Service govern your use of the Prem API and the dashboard. > [card] [Read the Terms of Service](https://dashboard.prem.io/legal/terms) > > View the full Terms of Service. ## Privacy Policy The Prem Privacy Policy explains how Prem collects, uses, and protects your data. > [card] [Read the Privacy Policy](https://dashboard.prem.io/legal/privacy) > > View the full Privacy Policy. # Link Nostr Source: https://docs.prem.io/link-nostr Connect your Nostr account to your profile and sync your name and profile picture. You can link your Nostr account to your account from the dashboard. The link retrieves your Nostr profile, and you can sync your display name and profile picture from it at any time. ## Install a Nostr signer extension Linking requires a Nostr signer extension in your browser. The extension signs the connection request with your Nostr keys: * **Firefox:** [nos2x-fox](https://github.com/diegogurpegui/nos2x-fox) * **Chrome:** [nos2x](https://github.com/fiatjaf/nos2x) For more signer options, see the [NIP-07 browser extensions](https://github.com/aljazceru/awesome-nostr#nip-07-browser-extensions) list on awesome-nostr. ## Link your Nostr account 1. Open the [dashboard](https://dashboard.prem.io). 2. Go to **Settings → Security → Nostr**. 3. Click **Connect Nostr**. 4. Approve the request in your Nostr signer extension. ## Sync your name and profile picture Your name and profile picture are retrieved from your Nostr profile. To sync them, click the name and the profile picture in **Settings → Security → Nostr**. Repeat this after you change your Nostr profile. ## Continue with Nostr Once linked, Nostr works as a single sign-on (SSO) method for fast login. On the authentication page, click **Continue with Nostr** and approve the request in your Nostr signer extension to log in without a password. ## Unlink your Nostr account To remove the link, go to **Settings → Security → Nostr** and click **Unlink**. # Link Passkey Source: https://docs.prem.io/link-passkey Add a passkey to your profile for passwordless login. You can add a passkey to your account from the dashboard. Passkeys let you sign in without a password using your device's native authentication or a security key. Passkeys work with FIDO2-certified devices and device-native passkeys (such as Touch ID, Face ID, Windows Hello, and Android biometrics). ## Add a passkey 1. Open the [dashboard](https://dashboard.prem.io). 2. Go to **Settings → Security → Login Passkeys**. 3. Click **Add Passkey**. 4. Follow your device or security key prompt to create the passkey. ## Continue with Passkey Once added, a passkey works as a single sign-on (SSO) method for fast login. On the authentication page, click **Continue with Passkey** and confirm with your device's native authentication or security key to log in without a password. ## Remove a passkey To remove a passkey, go to **Settings → Security → Login Passkeys** and click **Remove** next to the passkey. # Models & Pricing Source: https://docs.prem.io/models-and-pricing Explore every model on the Prem API platform — confidential inference and Zero Data Retention — with prices, in one place. This page shows the prices for all available models on the Prem API platform. All prices are pay-as-you-go, by usage. Prem serves two inference modes: * **Confidential inference** — the local proxy encrypts the inference end-to-end. See the [Confidential Proxy](/confidential-proxy) guide. * **Zero Data Retention (ZDR)** — the gateway at `https://gateway.prem.io` serves the inference without state. You need no client KEK and no local proxy. See the [ZDR overview](/zdr/overview). The tables that follow list the top models for each mode. The catalog changes with your API key and with the inference mode. Use `GET /rvenc/models` to get the confidential catalog and `GET /openai/models` to get the ZDR catalog. ## Confidential models The Confidential chat models use standard attestation. Use [SDK 2.1.0](/quickstart). See [Platform Status](/platform-status) for the current release. These are the top models available for confidential inference. Prices are per 1M tokens; check the model endpoint's current `price_config` before estimating costs. | Model | API ID | Type | Modalities | Pricing | | :- | :- | :- | :- | :- | | **Qwen 3.8** · 27B ([weights](https://huggingface.co/Qwen/Qwen3.8-27B)) | `qwen38-27b` | Chat | Text, Image, Video | \$0.30 in (\$0.00 cached\*\*) · \$2.40 out / 1M tokens | | **DeepGram General Nova 3** | `deepgram/general-nova-3` | Audio Transcription | Audio | \$0.05 / audio minute | | **DeepSeek V4.1 Flash · 1017** ([weights](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017)) | `deepseek-v4.1-flash-1017` | Chat | Text, Image, Video | \$0.35 in (\$0.00 cached\*\*) · \$1.40 out / 1M tokens | > [!NOTE] > > \*\* Promotional offer: cached prompt tokens for confidential inference are free (\$0.00) **until December 1, 2026.** * **Qwen 3.8**: A dense architecture with Gated DeltaNet and Gated Attention layers. It gives frontier-level intelligence with low latency. * **DeepGram General Nova 3**: A general-purpose ASR model with the highest performance. Use it for meetings, captions, and multilingual audio. * **DeepSeek V4.1 Flash · 1017**: 763B multimodal MoE, frontier agentic coding at flash speed. [Try in Playground](https://dashboard.prem.io) ## ZDR models These are the top models available for Zero Data Retention inference. Prices are per 1M tokens and match the `price_config` field of the models endpoint. | Model | API ID | Type | Modalities | Pricing | Region | | :- | :- | :- | :- | :- | :- | | **Qwen 3.8 2.4T A95B** | `qwen38-24t` | Chat | Text | \$2.50 in (\$0.25 cached) · \$6.00 out / 1M tokens | `eu` | | **DeepSeek V4 Pro** | `deepseek-v4-pro` | Chat | Text | \$1.75 in (\$0.058 cached) · \$3.50 out / 1M tokens | `eu`, `uk` | | **DeepSeek V4.1 Flash** | `deepseek-v4.1-flash` | Chat | Text, Image, Video | \$0.30 in (\$0.01 cached) · \$1.20 out / 1M tokens | `eu` | | **DeepSeek V4.1 Flash · 1017** | `deepseek-v4.1-flash-1017` | Chat | Text, Image, Video | \$0.30 in (\$0.01 cached) · \$1.20 out / 1M tokens | `eu` | | **GLM 5.2** | `glm-5.2` | Chat | Text | \$1.50 in (\$0.28 cached) · \$4.50 out / 1M tokens | `eu`, `uk` | | **Kimi K3** | `kimi-k3` | Chat | Text | \$3.50 in (\$0.35 cached) · \$15.25 out / 1M tokens | `eu` | | **Kimi K3.1 Pro** | `kimi-k3.1-pro` | Chat | Text, Image | \$2.20 in (\$0.22 cached) · \$11.00 out / 1M tokens | `eu` | | **DeepSeek V4 Flash** | `deepseek-v4-flash` | Chat | Text | \$0.25 in (\$0.005 cached) · \$0.30 out / 1M tokens | `eu` | | **GLM 5.3 Flash** | `glm-5.3-flash` | Chat | Text, Image, Video | \$0.22 in (\$0.044 cached) · \$0.52 out / 1M tokens | `eu` | | **Qwen3.8 Flash Next** | `qwen38-flash-next` | Chat | Text, Image, Video | \$0.22 in (\$0.022 cached) · \$0.52 out / 1M tokens | `eu` | | **DiffusionGemma** · 26B A4B ([weights](https://huggingface.co/nvidia/diffusiongemma-26B-A4B-it-NVFP4)) | `dgemma` | [Decisions](/guides/decisions) | Text, Image, Video | \$0.04 in · \$0.00 out / 1M tokens | `uk` | [Try in Playground](https://dashboard.prem.io) > [!NOTE] > > The prices above match the `price_config` field of the models endpoint. The `regions` field of `GET /openai/models` gives the current region of each model. ## Prompt caching Prompt tokens served from prefix cache are automatically detected and billed at the cached input rate: * **ZDR models**: cached prompt tokens are billed at discounted market rates (up to 98% discount compared to full input price). * **Confidential models**: cached prompt tokens are **\$0.00 / 1M tokens** under a promotional offer ending on **December 1, 2026**. * **Uncached prompt tokens**: billed at the standard input price per model. When a request benefits from prefix cache, token usage details are reported in the OpenAI-compatible usage object: ```json theme={"system"} { "usage": { "prompt_tokens": 1500, "completion_tokens": 250, "total_tokens": 1750, "prompt_tokens_details": { "cached_tokens": 1200 } } } ``` In this example, only the 300 uncached prompt tokens (1500 − 1200) are billed at the model's standard input rate, while the 1200 cached tokens are billed at the model's cached rate (or free under the confidential promotional offer). > [!NOTE] > > You get access to all models by an OpenAI-compatible API. See the [Quickstart](/quickstart) guide to start. ## Get the models your key can use The catalog changes with your API key and with the inference mode. A model that is available for ZDR is not always available for confidential inference. The opposite is also true. Call the models endpoint with the same API key that you use for chat requests. * `GET /rvenc/models` returns the confidential catalog. * `GET /openai/models` returns the ZDR catalog. ```bash curl theme={"system"} curl https://gateway.prem.io/rvenc/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` ```bash curl-zdr theme={"system"} curl https://gateway.prem.io/openai/models \ -H "Authorization: Bearer $PREM_API_KEY" ``` ```python Python theme={"system"} import os from openai import OpenAI client = OpenAI( api_key=os.environ["PREM_API_KEY"], base_url="https://gateway.prem.io/openai", ) for model in client.models.list(): print(model.id, model.type, model.regions) ``` ```typescript TypeScript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY!, baseURL: "https://gateway.prem.io/openai", }); for await (const model of client.models.list()) { console.log(model.id); } ``` > [!NOTE] > > The `GET /openai/models` endpoint uses the OpenAI models list format. The standard `client.models.list()` method of an OpenAI SDK reads it. Prem adds more fields to each entry, and an OpenAI SDK ignores them. Filter the catalog by the type of the model: ```bash theme={"system"} curl "https://gateway.prem.io/openai/models?type=CHAT" \ -H "Authorization: Bearer $PREM_API_KEY" ``` The `type` parameter accepts these values: `CHAT` and `AUDIO_TRANSCRIPTION`. Send the exact model ID from the response. Do not add a provider prefix or a slash. ### The response fields The response has `"object": "list"` and an array in `data`. Each entry has these fields: | Field | Description | | - | - | | `id` | The model ID to send in a chat request | | `object` | Always `model` | | `created` | The Unix timestamp of the moment that Prem added the model | | `owned_by` | The owner of the model | | `name` | The display name of the model | | `description` | A short description of the model | | `type` | `CHAT` or `AUDIO_TRANSCRIPTION` | | `input_modalities` | The input types that the model accepts | | `price_config` | The price for each mode and region | | `regions` | The regions that give this model for the endpoint's mode | | `usage_mode` | The method that the platform uses to meter the model | The first four fields are the standard OpenAI fields. The other fields are Prem fields, and an OpenAI SDK ignores them. ## Regions The `regions` field shows the regions that give the model. The endpoint that you call decides the mode: * `GET /openai/models` returns the ZDR catalog. The `regions` field shows the ZDR regions. * `GET /rvenc/models` returns the confidential catalog. The `regions` field shows the confidential regions. ```json theme={"system"} { "regions": ["eu", "uk"] } ``` The ZDR partners operate in the European Union (`eu`), Switzerland (`ch`), and the United Kingdom (`uk`). The regions for one model can be different from the regions for another model. The `regions` field is the current source of truth for each model. ## Mode errors The API rejects a model that the mode you chose does not give. The response has a 400 status and one of these messages: | Message | Cause | | - | - | | `Model {model} is available for encrypted inference only.` | You sent a confidential-only model to `/openai/chat/completions`. Use the confidential routes. | | `Model {model} is not available for confidential inference.` | You sent a ZDR-only model to a confidential route. Use `/openai/chat/completions`. | Call the models endpoint again after you change the API key. Then remove each model that the new key does not return. ## Reasoning effort Reasoning models generate a chain of thought before they answer. The `reasoning_effort` field controls how much the model reasons. The valid values depend on the model family. The table shows the values for each family. | Family | Valid values | | :- | :- | | Qwen | `xhigh`, `medium`, `low` | | DeepSeek | `low`, `high`, `max` | | Z.ai (GLM) | `max`, `xhigh`, `high`, `medium`, `low`, `minimal`, `none` | | Kimi | `low`, `high`, `max` | The proxy sends the value to the model unchanged. The model rejects a value that it does not support. To reduce reasoning, use the lowest value that the family accepts. ## Deployment Strategies | Feature | Explorer | Developer | Enterprise | | - | - | - | - | | **API Deployment** | Multi-Tenant APIs | Dedicated APIs | Dedicated APIs | | **Model Deployment** | Curated Models | Custom Model Choice | Custom Model Choice | | **Infrastructure** | Shared Instances | Dedicated Instances | air-gapped / on-prem | > [!TIP] > > See the [Tiers](/tiers) page for the limits of each usage tier. The page covers the request rate, the token limit (TPM), the audio limit, and the monthly budget. > [!TIP] > > Prem serves all APIs in agreement with its security model. For more information, see the [Security Model](/security-model) page. ## Get Started > [card] [Create Account](https://dashboard.prem.io) > > Register. Then start to use the Confidential APIs. > [card] [Quickstart](/quickstart) > > Make your first API call in minutes. > [card] [ZDR Overview](/zdr/overview) > > Set up your first ZDR request. > [card] [Contact Sales](mailto:sales@premai.io) > > Contact Prem for enterprise features, custom models, or dedicated infrastructure. # Platform Status & Roadmap Source: https://docs.prem.io/platform-status Released confidential infrastructure, attestation and SDK integration. ## Released as of 12 November 2026 | Area | Current behavior | | - | - | | SDK integration | `@premai/api-sdk` 2.1.0 is published and depends on `@premai/reticle` ^0.6.2; Reticle 0.6.2 is published | | Confidential chat models | DeepSeek V4.1 Flash · 1017 (`deepseek-v4.1-flash-1017`) and Qwen 3.8 27B (`qwen38-27b`) are registered in [Trustbase](https://github.com/prem-research/trustbase) | | Client encryption | The SDK and local Confidential Proxy encrypt protected request content before sending it to the gateway | | Attestation gate | With attestation enabled, the SDK verifies the unified report and requires a session ID before protected requests | | Local client integration | OpenAI- and Anthropic-compatible routes are bundled with the SDK; see each [client guide](/guides/openai-compatible-clients) for compatibility limits | | Zero Data Retention (ZDR) | Separate `/openai` routes rely on partner zero-retention agreements; they do not provide confidential-VM attestation | | Models and pricing | Availability is specific to the API key and inference mode; see [Models & Pricing](/models-and-pricing) | Use SDK **2.1.0** for confidential inference. It includes the standard attestation integration. ## Attestation status | Capability | Status | Verification | | - | - | - | | Unified CPU evidence verification | Released | Verifies manufacturer evidence and a challenge bound to the workload manifest | | Signed policies and measurement references | Released | The default client verifies Trustbase signatures and compares policy-selected CPU fields with approved references | | Intel TDX reference comparison | Released | Includes MRTD, RTMR0–2 and MRCONFIGID | | AMD SEV-SNP reference comparison | Released | Includes the launch measurement and host data | | NVIDIA evidence verification | Released for supplied evidence | Checks signed tokens, digest links, bound nonces and policy claims | | Public CVM image source | Released | [PodVM](https://github.com/prem-research/podvm) publishes the source and release measurements for the read-only confidential-VM image | | Release-to-measurement references | Released | [Trustbase](https://github.com/prem-research/trustbase) registers PodVM releases and workload initialization data | ## Independent audit An independent platform audit is planned. ## Model catalog and pricing Model availability depends on your API key and the selected inference mode (Confidential or ZDR). See [Models & Pricing](/models-and-pricing) for the full list of available models, context windows, modalities, and prices. # Production Checklist Source: https://docs.prem.io/production-checklist Complete these steps before you send production traffic to Prem API. Complete this checklist before you send production traffic. Each item links to the page with the full instructions. ## Keys and secrets * Store your Key Encryption Key (KEK) in a secure location with backups. If you lose it, Prem cannot recover your data. See [Encryption](/encryption). * Make a backup of your DEK store. If you lose it, you lose access to your uploaded files. * Store all keys in environment variables. Do not commit keys to source control. See [Quickstart](/quickstart). * Use one API key for each environment, for example `development`, `staging`, and `production`. See [API Keys](/api-keys). ## API key security * Give each API key only the scopes that it needs. A key without explicit scopes has full permissions. See [API Keys](/api-keys). * Add IP restrictions to the keys for critical integrations. * Rotate your API keys on a regular schedule. * Do not share one API key between teams or environments. ## Reliability * Retry failed requests with exponential backoff and random jitter. See [Rate limits](/rate-limits). * Obey `Retry-After` when a temporary `429` response has this header. Otherwise, use exponential backoff with a maximum number of retries. Stop automatic retries when the error says that the request allowance is exhausted. See [Rate limits](/rate-limits). * Use idempotency keys for requests that you cannot repeat safely. See [Idempotency](/idempotency). * Handle each error code that the API returns. See [Errors](/errors). * Record the `support_id` value from error responses. Contact support in the week after the error occurs. See [Errors](/errors). ## Capacity and cost * Check that your tier's Confidential and ZDR limits cover your traffic: request rate, concurrency, tokens, and audio. All API keys in your organization share these limits. See [Tiers](/tiers). * Set a monthly budget limit for your organization. See [Limits](/billing/limits). * Configure auto top-up so that your balance does not reach zero. See [Balance](/billing/balance). * Monitor your token usage in the dashboard. See [Usage](/billing/usage). ## Verification * Keep attestation on. The SDK verifies the enclave automatically because `attest: true` is the default. See [Attestation](/attestation). * For independent verification, use the `@premai/reticle` package to check the attestation reports yourself. * Get the current endpoint values from [`dashboard.prem.io/endpoints.json`](https://dashboard.prem.io/endpoints.json) at deployment time. ## Before launch * Monitor the platform availability on the [status page](https://status.premai.io). * Read the [Security Model](/security-model) page, including the limitations section. * Read the [Platform Status](/platform-status) page for the current feature availability. * Confirm that the models in your code appear in [Models & Pricing](/models-and-pricing). > [!TIP] > > Questions before a production launch? Contact us at [support@premai.io](mailto:support@premai.io). # Quickstart Source: https://docs.prem.io/quickstart Send chat and audio requests with client-side encryption through the Prem SDK or local proxy. Prem API exposes client-encrypted chat and audio routes. Use the TypeScript SDK directly, or run the bundled **Confidential Proxy** for the documented OpenAI- and Anthropic-compatible routes. > [!NOTE] > > The Prem API has two inference modes. This page tells you about **confidential inference**. See [Zero Data Retention](/zdr/overview) for an OpenAI-compatible endpoint that needs no code changes. See the [comparison](/zdr/comparison) to choose a mode. > [!TIP] > > If you use an AI coding agent, load Prem API into the context of your agent with one command. See [Use LLMs](/use-llms). ## Use the Prem API SDK ### 1. Create an API key 1. Open the [dashboard](https://dashboard.prem.io). Sign in or register. 2. Go to the [API](https://dashboard.prem.io/api-keys) section. 3. Create a new API key. Copy the key to a safe location. Store the API key in an environment variable, for example `PREM_API_KEY`. Do not commit the API key to source control. ### 2. Install the SDK and make your first call Install the verified **2.1.0** release from npm. It includes Reticle **^0.6.2** for attestation of the [Confidential chat models](/models-and-pricing#confidential-models): ```bash theme={"system"} npm install @premai/api-sdk@2.1.0 ``` > [!NOTE] > > The SDK runs natively on Node.js, Bun, Deno, and [Bare](https://github.com/holepunchto/bare). It needs no native add-ons. You use one client library across all of them, from a backend service to a mobile app. See the [React Native guide](/guides/react-native). Then use this code to initialize the client and call the API: ```typescript theme={"system"} import { createRvencClient } from "@premai/api-sdk"; async function main() { const apiKey = process.env.PREM_API_KEY; const clientKEK = process.env.CLIENT_KEK; if (!apiKey || !clientKEK) { throw new Error("Set PREM_API_KEY and CLIENT_KEK"); } const client = await createRvencClient({ apiKey, clientKEK }); const response = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Reply with exactly OK." }], max_completion_tokens: 128, }); console.log(response.choices[0]?.message?.content); console.log("Resolved model:", response.model); } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` You must set all four environment variables. `CLIENT_KEK` is your Key Encryption Key (KEK). The SDK expects a 32-byte key encoded as exactly 64 hexadecimal characters. The KEK protects your encryption keys and does not leave your device. See [Encryption](/encryption). ```bash theme={"system"} export PREM_API_KEY="your-api-key" export CLIENT_KEK="$(openssl rand -hex 32)" export PROXY_URL="https://gateway.prem.io" export ENCLAVE_URL="https://conf-engine.prem.io" ``` Store the KEK in a secret manager and reuse it. Do not regenerate it on each process start. The SDK verifies attestation by default. See [Attestation](/attestation) for the verification flow and assurance boundary. > [!NOTE] > > Get the latest endpoint values from [`dashboard.prem.io/endpoints.json`](https://dashboard.prem.io/endpoints.json). ### 3. Run a request Run your script. The console shows the response. > [!TIP] > > For error codes and HTTP conventions, see [Errors](/errors). For request limits, see [Rate limits](/rate-limits). ## Use the OpenAI SDK Run the bundled **Confidential Proxy** to expose OpenAI-compatible routes on your machine. Point the `baseURL` of an OpenAI client at the Confidential Proxy. ```bash theme={"system"} npx -p @premai/api-sdk@2.1.0 confidential-proxy \ --compat openai \ --kek "$CLIENT_KEK" ``` The current CLI reads `PROXY_URL` and `ENCLAVE_URL` from the environment. Pass the KEK with `--kek`; `CLIENT_KEK` is not currently bound as a CLI environment option. > [!NOTE] > > Get the latest endpoint values from [`dashboard.prem.io/endpoints.json`](https://dashboard.prem.io/endpoints.json). When the Confidential Proxy runs, install the OpenAI JavaScript SDK. Point the SDK at your local `/v1` URL. The client sends your API key as the bearer token with each request: ```typescript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY!, baseURL: "http://127.0.0.1:8787/v1", }); const stream = await client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [{ role: "user", content: "Hello!" }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` > [!TIP] > > See [Confidential Proxy](/confidential-proxy) for all proxy options: Anthropic compatibility, daemon mode, and the full configuration. ## Verify the selected route Model-list and completion responses expose the requested alias and, for OpenAI-format completions, the resolved model ID. They do **not** expose an assurance profile. Do not classify a route from its model name. For `deepseek-v4.1-flash-1017`, the completion response returns the resolved backend ID in `response.model`. See [Platform Status](/platform-status) for the current assurance boundary. ## Next steps > [card] [API reference](/api-reference/chat-completions) > > Chat completions and other endpoints in detail. > [card] [Guides](/guides/chat-completion) > > Step-by-step guides for common flows (chat, audio, and more). > [card] [Models & Pricing](/models-and-pricing) > > Available models, pricing tiers, and deployment strategies. > [card] [Agents & Automation](/agents) > > Building a bot, agent loop, or batch job? The config and gotchas that matter unattended. # Rate limits Source: https://docs.prem.io/rate-limits Understand how Prem enforces limits and how to handle a 429. Several controls apply to each request: the request rate, concurrency, token or audio quotas, the budget, and model capacity. The API refuses requests that cannot pass these controls. For tier qualifications, see [Tiers](/tiers). ## The purpose of rate limits We apply rate limits for three reasons. They protect the API against abuse, because a malicious actor can send too many requests and make the service unavailable. They make access fair for all users, because one organization cannot make the API slow for the other users. They hold the total load on our infrastructure at a level that gives a constant response time. ## The operation of rate limits Each API tier has separate policies for **Confidential** and **ZDR** inference. Each policy has a concurrency limit, a request burst capacity, a refill rate, a token allowance, and an audio allowance. Use in one family does not consume the other family's allowance. > [!NOTE] > > See your account settings for each family's current limits. | Control | Scope | | - | - | | Inference request rate | The organization and the inference family, across all API keys, users, and endpoints in that family. | | Concurrent inference requests | The organization and the inference family, across all API keys and users. | | Token and audio quotas | The organization, the inference family, the quota type, and the period. | | Spending budget and balance | The organization, across all inference requests. | | Model capacity | The shared capacity for inference. Different model names can use one capacity pool. | A different API key does not increase the family's allowance. Keys from different members share that allowance. A different endpoint within the family does not increase it either. Requests with and without a stream share the family's policy. `/rvenc/chat/completions` and `/rvenc/audio/*` use the Confidential policy. Direct calls to `/openai/chat/completions` and `/typesafe/v1/systemone` use the ZDR policy. OpenAI-compatible clients that use the local Confidential Proxy use Confidential allowances. A model in both families uses the allowance for the family of the request. API requests use the organization's tier. Anonymous requests use IP-based controls. The family split does not create separate balances, budgets, file storage, or model-capacity pools. ## Request limits A request-rate bucket has a capacity and a refill rate. The API deducts one request credit when a request passes the rate limit. Credits refill continuously. This lets you send a short burst, then send requests at the refill rate. Request credits are separate from model tokens. ### Burst capacity and RPM Burst capacity is the maximum number of request credits that the bucket holds. **RPM** is the refill amount over 60 seconds. A bucket with a capacity of 10 and a refill of 60 RPM lets you send 10 requests at once. It then adds one request credit each second. A family can have several active request windows, such as per-minute and daily allowances. Each active window with a finite limit must have a request credit. The API deducts one credit from these windows together. If one window has no credit, the API deducts no credits from the other windows. The API does not return these credits if it refuses the request later or inference does not finish. If Prem disables a request window, the API keeps its stored balance. An unlimited window keeps its stored balance too. The API deducts no credits from these windows. If an allowance had no refill, its consumed credits stay consumed when Prem restores that allowance without refill. Your account settings show the burst capacity, refill rate, and period for each family's active windows. One tier can have different values for Confidential and ZDR. These values are maximum request rates. Concurrency, usage quotas, and model capacity can further limit the rate of successful requests. Non-inference endpoints and anonymous inference use their separate request-rate controls. ## Token and audio quotas Each usage quota has a capacity, a refill amount, and a period in seconds. A per-minute bucket refills continuously over 60 seconds. A daily bucket refills over 86,400 seconds. These buckets do not reset at each clock minute or at midnight. Each active period for the quota must have sufficient allowance for a new request. Before a chat request begins, the API makes sure that the token quota has sufficient allowance. For audio requests, the API makes sure that both the token and audio quotas have sufficient allowance. The API deducts reported usage after inference finishes. Audio usage keeps fractional seconds. **Usage quotas do not reserve allowance for requests that have not finished.** Several requests can begin before the API receives their total usage. This can put a bucket below zero. A depleted bucket refuses new requests until it refills to 20% of its capacity. The API rounds this threshold up to a whole unit. A bucket below zero must first refill to zero, then to this threshold. ### Token limits (TPM / Tokens DQ) Each family's token policy has a capacity and a refill rate for each active period. TPM uses a 60-second period. A daily token allowance uses an 86,400-second period. Your account settings show your tier's current values for Confidential and ZDR. The API deducts the total token usage that the model reports. If the model reports no positive total, the API adds the prompt and completion tokens. Quota usage is separate from the price. A discount for cached tokens does not change the token count. ### Audio processing limits (APM / Audio DQ) Audio policies measure the duration in seconds, with fractional seconds. Each inference family has its own capacity, refill rate, and periods. The available audio endpoints use the Confidential family. ### Quota configuration values * A limit of `-1` means no limit for that quota. * A limit of `0` stops requests that need that quota. * A positive limit defines the capacity. A refill of `0` adds no allowance over time. * These values apply independently within each inference family. Other controls still apply when a quota is unlimited. ## Concurrent request limits Tier concurrency counts active requests across the organization within one inference family. Consider an organization with a Confidential limit of 5 and a ZDR limit of 20. Five active Confidential requests use all its Confidential slots. The organization still has its separate ZDR allowance. Requests that wait for model capacity occupy a family concurrency slot. Each request holds its slot until it finishes or stops. A client disconnect does not always stop the model immediately. At the concurrency limit, the API returns `429` for new requests until a slot becomes available. A concurrency limit of `-1` means unlimited. A limit of `0` stops new requests. A positive limit is the maximum number of active requests. Model capacity and the other limits still apply when concurrency is unlimited. ## Usage tiers Your account settings show the organization's current API tier. ### Spending budgets Before inference begins, the API makes sure that the organization has sufficient balance and budget. The budget applies across the organization. It does not divide by API key or inference family. The optional monthly budget has no tier-based ceiling. If you do not set a budget, the API applies no budget limit. A budget of `0` has this effect too. A positive budget stops new requests when the period's cost reaches that amount. The balance requirement and other limits still apply. The API does not reserve funds for requests that have not finished. Their total cost can be more than the budget left when they began. The budget stops new requests, but it does not cap the cost of requests that already began. ### Rate limits in headers A rejection can have a `Retry-After` header with a delay in seconds. Some concurrency and model-service errors omit this header. A window with zero capacity or no credits and no refill omits it too. Use your account limits and the error details to understand the rejection. ## Error mitigation ### Steps to decrease rate limit errors Be careful when you give users programmatic access, bulk processing features, and automated posting. Enable these features only for trusted customers. Set a usage limit for each user in a specified period (daily, weekly, or monthly). This protects against automated and high-volume misuse. Add a hard cap or a manual review process for users who exceed the limit. ### Retry with exponential backoff Retry temporary rate-limit rejections with bounded exponential backoff and random jitter. The client waits before each retry. It increases the delay after each rejection, up to a maximum number of retries. This method has three benefits: * Automatic retries let you recover from rate limit errors without crashes or lost data * With exponential backoff, the first retries have short delays, and later retries have longer delays * With random jitter, clients retry at different times > [!TIP] > > The API deducts a request credit when the request passes the rate limit. It does not return this credit if it later refuses the request. Wait before each retry. Do not automatically retry `Inference request allowance exhausted. Contact us for higher limits.` This `429` means a request window has zero capacity, or no credits and no refill. It has no `Retry-After` header because a delay cannot restore a credit. Prem must change the limit before another request can pass. The example that follows uses exponential backoff. #### Example: This example reads the SDK error's `status`, `message` or `error`, `support_id`, and optional `headers["retry-after"]` fields. It stops if the error states that the request allowance has no credits and no refill, or zero capacity. For other `429` responses, it waits before each retry. Use it before the first output arrives. Do not replay a request after you receive output from its stream. ```typescript theme={"system"} import createRvencClient from "@premai/api-sdk"; async function retryWithExponentialBackoff( fn: () => Promise, maxRetries: number = 6, baseDelay: number = 1000 ): Promise { let retries = 0; while (true) { try { return await fn(); } catch (error: any) { const isRateLimitError = error?.status === 429; const message = error?.message ?? error?.error; const allowanceExhausted = message === "Inference request allowance exhausted. Contact us for higher limits."; if (!isRateLimitError || allowanceExhausted || retries >= maxRetries) { throw error; } const parsedRetryAfter = Number(error?.headers?.["retry-after"]); const retryDelay = Number.isFinite(parsedRetryAfter) && parsedRetryAfter > 0 ? parsedRetryAfter * 1000 : baseDelay * 2 ** retries; const delay = retryDelay + Math.random() * baseDelay; retries++; console.log( `Rate limited (support_id ${error?.support_id || "unknown"}). ` + `Retrying in ${Math.round(delay)}ms... (attempt ${retries}/${maxRetries})` ); await new Promise((resolve) => setTimeout(resolve, delay)); } } } // Usage async function main() { const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK }); try { const response = await retryWithExponentialBackoff( () => client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "What is the capital of France?" }, ], }), 6, 1000 ); console.log(response.choices[0].message.content); } catch (error) { console.error("Request failed after retries:", error); } } main().catch(console.error); ``` ### Handle concurrent request limits Make sure that your application does not send more concurrent requests than the family's limit. Use a shared queue for the organization's requests in each family. The queue must limit requests across all your workers. ```typescript theme={"system"} import createRvencClient from "@premai/api-sdk"; class RequestQueue { private maxConcurrent: number; private running: number = 0; private queue: Array<() => void> = []; constructor(maxConcurrent: number = 3) { this.maxConcurrent = maxConcurrent; } async execute(requestFn: () => Promise): Promise { while (this.running >= this.maxConcurrent) { await new Promise((resolve) => this.queue.push(resolve)); } this.running++; try { return await requestFn(); } finally { this.running--; const resolve = this.queue.shift(); if (resolve) resolve(); } } } // Usage async function main() { const client = await createRvencClient({ apiKey: process.env.PREM_API_KEY, clientKEK: process.env.CLIENT_KEK }); const queue = new RequestQueue(3); // max 3 concurrent requests const prompts = [ "Explain photosynthesis", "What is machine learning?", "Describe the water cycle", "Explain gravity", "What is DNA?", ]; try { const results = await Promise.all( prompts.map((prompt) => queue.execute(() => client.chat.completions.create({ model: "deepseek-v4.1-flash-1017", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: prompt }, ], }) ) ) ); results.forEach((response, index) => { console.log(`Response ${index + 1}:`, response.choices[0].message.content); }); } catch (error) { console.error("One or more requests failed:", error); } } main().catch(console.error); ``` ## Tips for developers * **Group related operations** to send fewer requests. * **Cache frequently accessed data** so that you do not request the same data again and again. * **Watch for `TOKEN_LIMIT_EXCEEDED` and `AUDIO_DURATION_LIMIT_EXCEEDED`** on `400` responses, not only for `429`. * **Log the `support_id`** for each unsuccessful request. * **Use `Retry-After` when present** for temporary rejections. Stop automatic retries if the request allowance has zero capacity, or no credits and no refill. * **Read both HTTP and stream errors**: Read `429` responses before the stream begins. Read error events after an SSE connection opens. Do not automatically replay a request after you receive output. ## Example error response If a request bucket has no credits, but has positive capacity and refill, the API returns `429 Too Many Requests`. Its `Retry-After` header states the delay in seconds. A window with zero capacity, or no credits and no refill, returns `429`. The error is `Inference request allowance exhausted. Contact us for higher limits.` The response has no `Retry-After` header. Do not automatically retry this response. Token and audio quota errors return `400` with `TOKEN_LIMIT_EXCEEDED` or `AUDIO_DURATION_LIMIT_EXCEEDED`. Budget and balance errors return `400` with `BUDGET_LIMIT_EXCEEDED` or `INSUFFICIENT_FUNDS`. The API returns `503` if it cannot get the limits for your request. ```json theme={"system"} { "status": 429, "data": null, "error": "Rate limit exceeded, try again in 1 seconds", "message": null, "env": "production", "log": null, "validator": null, "support_id": "req_support_019a3f7c8d2e7b41a0c6" } ``` Record the `support_id`. Send it to support with a timestamp if you need us to trace a request. ## Non-standard 429 responses The API's rate limiter returns the response format in the example. Other services do not always use this format for `429` responses. A model service can return a `429` status with a generic error and no `Retry-After` header: ```json theme={"system"} { "error": { "message": "Internal server error", "type": "server_error" } } ``` The message suggests a `500` error, but the status code is `429`. Your client must use the status code and error details: * **Read the HTTP status and error details.** A `429` refers to the request rate, concurrency, or shared model capacity. Use bounded backoff for temporary rejections. Quota and billing errors can use `400`. Read these errors too. * **Never assume that `Retry-After` is present.** For temporary concurrency or model-service rejections, use bounded exponential backoff with jitter. Stop automatic retries if the request allowance has zero capacity, or no credits and no refill. After an SSE connection sends HTTP `200`, the API sends later errors in the stream. These errors do not change the HTTP status. Read the SDK's stream exception or SSE error event, and the initial HTTP errors. HTTP `200` alone does not mean that inference finished successfully. For repeated rejections without a `Retry-After` header or with an unexpected body, [contact us](/contact-us). Send the `support_id`, if present, and a timestamp. We use these values to trace the request. ## Higher rate limits Your limits increase when you move to a higher tier. See [Tiers](/tiers#how-to-move-to-a-higher-tier). If you need higher limits, [contact us](/contact-us) to discuss custom rate limits. ## Related > [card] [Tiers](/tiers) > > The request, token, and audio limits of each tier. > [card] [Errors](/errors) > > Every status code that the API returns, and what to do about it. # Security Model Source: https://docs.prem.io/security-model Prem API threat boundaries, confidential-computing controls, attestation evidence, and current limitations. > [!NOTE] > > **Summary:** Prem API combines client-side encryption with confidential-computing hardware and attestation evidence. The strength of any claim depends on the verified evidence, an approved measurement/TCB policy, and the route that processed the request. The current limitations are documented below and on [Attestation](/attestation). > [!NOTE] > > **Scope:** This page tells you about the **confidential inference** path only. [Zero Data Retention](/zdr/overview) is a different mode with a different boundary. It has no client-side encryption, no Trusted Execution Environment, and no attestation. See [ZDR security boundary](/zdr/security-boundary). ## The Problem With Trust Each AI API provider tells you that your data is safe. But traditional security relies on **trust**: * Trust that employees do not access server memory * Trust that the infrastructure provider does not inspect VMs * Trust that the privacy policy matches the actual implementation * Trust that a breach did not already occur Prem API combines hardware isolation with attestation evidence. Reticle verifies manufacturer evidence and compares software measurements with signed release references. ## Trusted Execution Environments: The Foundation A Trusted Execution Environment (TEE) is designed to isolate a workload and its memory from the host operating system and hypervisor. The exact confidentiality and integrity guarantees depend on the hardware architecture, firmware, configuration, and known vulnerability state. > [card] Protected memory > > Confidential-computing hardware protects designated workload memory according to the selected CPU or GPU architecture and configuration. > [card] Host isolation > > A TEE is designed to restrict the host operating system and hypervisor from reading or modifying protected workload memory. > [card] Measured state > > Hardware evidence carries architecture-defined measurements. A verifier must compare them with an approved reference before treating a change as a policy failure. > [card] Provable Integrity > > The TEE can produce hardware-signed evidence that includes measurements and security claims. A verifier must compare those values with an approved policy before concluding that the expected workload is running. ### An Analogy As a mental model, think of a sealed request processed inside a restricted chamber and returned in a new sealed envelope. The model explains the intended data boundary. It does not replace the hardware threat model, attestation policy, or software review. ### The Hypervisor The released [PodVM](https://github.com/prem-research/podvm) infrastructure uses Kata Containers and QEMU to launch measured confidential guests. Its source and release configuration are public. The confidential-computing threat model treats the host operating system and hypervisor as untrusted. CPU hardware enforces the guest's memory protections, subject to the architecture, firmware and deployment configuration. Hardware-signed evidence and signed reference measurements let the client verify the measured guest state. They do not remove availability risks or every hardware and application-level side channel. ### CPU Confidential Computing Prem API enclaves run on **Confidential Virtual Machines (CVMs)** with: * **AMD SEV-SNP**: Protects guest memory with hardware-managed keys and supplies an attestation report for policy evaluation. * **Intel TDX**: Creates an Intel trust domain with protected memory and a quote for policy evaluation. Reticle 0.6.2 implements separate CPU verification paths inside its unified attestation flow. The [Confidential chat models](/models-and-pricing#confidential-models) use this attestation flow. ### GPU Confidential Computing During inference, prompts, model weights, and intermediate results are processed in GPU memory. NVIDIA confidential computing extends the confidential VM's protection to this part of the workload: hardware access controls isolate GPU memory from the host, and transfers between the CVM and GPU are encrypted through a shared staging area called a **bounce buffer**. The GPU computes on plaintext inside its protected boundary. These protections require a supported GPU model, compatible firmware and drivers, and an enabled production confidential-computing mode. See [NVIDIA's description of GPU isolation and encrypted transfers](https://developer.nvidia.com/blog/confidential-computing-on-h100-gpus-for-secure-and-trustworthy-ai/). When GPU evidence is supplied, Reticle verifies the attestation evidence for every GPU included in the response. It checks token signatures against NVIDIA's keys, checks that each token contains the client's fresh challenge (the **nonce**), and requires a passing firmware and configuration measurement result for each GPU. For multi-GPU responses, verification succeeds or fails for the set; the public result does not expose individual GPU verdicts. These checks establish the reported GPUs' attested state. See [Multi-GPU attestation and load balancing](/attestation#multi-gpu-attestation-and-load-balancing) for the verification flow. #### NVIDIA MPT CC on Blackwell Our Blackwell deployments (**HGX**) run the GPUs in NVIDIA's **Multiple GPU Passthrough with a Bounce Buffer (MPT CC)** mode. In this mode, GPU-to-GPU traffic is encrypted: GPUs inside the same CVM communicate peer-to-peer over encrypted NVLink connections. The matrix below compares the confidential-computing modes: | | Single GPU Passthrough (SPT CC) | Hopper Multiple GPU Passthrough (PPCIe) | Blackwell MPT CC | | - | - | - | - | | GPUs per CVM | One | Multiple (Hopper) | Up to eight (Blackwell) | | Host-to-GPU PCIe data | Encrypted via bounce buffer | Encrypted via bounce buffer | Encrypted via bounce buffer | | GPU-to-GPU NVLink data | Not applicable (single GPU) | **Not encrypted** | **Encrypted** | ### The Confidential Runtime [PodVM](https://github.com/prem-research/podvm) publishes the confidential-VM base image source and release measurements. The released image uses a read-only dm-verity root filesystem. [Trustbase](https://github.com/prem-research/trustbase) publishes signed policies and references that connect PodVM releases with workload initialization data. Reticle verifies these references and compares the CPU evidence with them by default. These controls verify integrity against approved references. ## The Infrastructure Locations Prem API deployments can use Prem-owned hardware and rented provider capacity. Confirm the exact location, operator, hardware, and policy for the route that your workload uses. TEE evidence can reduce trust in the physical and cloud operator in both owned and rented environments. It does not make their complete operational risk identical. Physical controls, administrator access, firmware supply chain, geography, and incident response remain separate audit inputs. * **Owned infrastructure:** Prem controls more of the physical and operational stack. Attestation evidence does not replace physical-security and change-management review. * **Rented infrastructure:** The provider controls the physical host. Confidential-computing controls are designed to restrict host access, while attestation evidence lets a client inspect hardware claims and freshness. > [!NOTE] > > **For compliance teams:** Manufacturer evidence is one audit input. Reticle 0.6.2 authenticates CPU evidence and its challenge binding, then compares measured values with signed release references. TEE guarantees do not imply identical jurisdiction or availability guarantees across locations. > [!NOTE] > > **Legal scope:** Confidential computing can reduce the plaintext held by infrastructure operators, but it does not eliminate legal obligations, metadata disclosure, endpoint access, or jurisdictional risk. Obtain jurisdiction-specific legal advice for regulated deployments. ## Confidential processing boundary The intended boundary includes every service that decrypts or processes protected content. The Prem API Gateway handles encrypted payloads plus API-key, model, size, timing, routing, and billing metadata. A local Confidential Proxy is a separate plaintext component on the client side. ## KV-Cache and Multi-Tenant Isolation The KV cache (Key-Value cache) is not shared across serving engines or TEEs. Each enclave keeps its own KV cache inside its protected memory, so cached context never crosses the enclave boundary and cannot leak to the host or to another serving engine. This is what enforces multi-tenant isolation: because no cache is shared between tenants, one workload cannot read, reconstruct, or infer the cached context of another workload. Each request is served from a KV cache that lives entirely within a single tenant's confidential-computing boundary. ## Attestation evidence and policy Attestation supplies evidence for selected hardware and workload claims. The client still needs an explicit acceptance policy: ```mermaid theme={"system"} flowchart TD A["Hardware Manufacturer (AMD / Intel / NVIDIA)"] -->|"signs attestation keys at the factory"| B["TEE Hardware (CPU + GPU)"] B -->|"records architecture-defined measurements"| C["Measured Workload State"] C -->|"generates"| D["Attestation Report"] D -->|"you verify"| H["Your Device (SDK or browser)"] ``` **The attestation report tells you:** 1. **Measurements and claims**: The report carries hardware-defined measurements and security-relevant fields. 2. **Evidence authenticity**: The verifier validates the applicable manufacturer certificate or key chain. 3. **Freshness**: The report contains the verifier's nonce. 4. **Policy decision**: Reticle evaluates the evidence against signed Trustbase policies and release measurements. Reticle can compile to WebAssembly for supported JavaScript environments. A browser integration can therefore run the verifier locally, but it must still use trusted collateral, approved references, and an explicit failure policy. > [!TIP] > > **For non-technical readers:** Attestation is comparable to a signed hardware inspection record. The signature authenticates the source of the evidence. Your policy still decides whether the reported configuration is acceptable. See [Attestation](/attestation) for the full technical detail: CPU reports, GPU EAT tokens, certificate chains, and verification code examples. ## Layers of Defense Prem API uses several controls for different risks. These controls are not interchangeable, and one control does not guarantee that another remains effective after a failure: | Layer | What It Does | Plain-Language Impact | | - | - | - | | **Transport encryption** (TLS 1.3) | Encrypts the network connection | Protects against passive network observation within the TLS threat model | | **Client payload encryption** | Encrypts the request payload from the client to the protected processing path | Limits plaintext exposure at the Prem gateway | | **Post-quantum component** | Uses ML-KEM768 as part of a hybrid key exchange | Reduces reliance on classical public-key exchange alone | | **CPU isolation** (AMD SEV-SNP / Intel TDX) | Protects designated confidential-VM memory | Restricts host access according to the hardware and deployment configuration | | **GPU isolation** (NVIDIA Confidential Computing) | Protects designated GPU processing and memory | Requires supported hardware, firmware, drivers, mode, and verified evidence | | **Attestation** (hardware-signed, Rust/WASM verified) | Authenticates hardware evidence and challenge binding; evaluates signed policies and release references | Reduces reliance on operator assertions | | **Client KEK custody** | You generate and retain the Key Encryption Key | Separates client key custody from the Prem API key and server-side routing | ## Common Questions > [accordion] What if someone hacks your servers? > > The intended network-gateway exposure is encrypted content plus operational metadata. A compromise can still affect availability, routing, replay attempts, metadata, and software supply chain. The local Confidential Proxy is a plaintext component and must be secured separately. > [accordion] What if the proxy is compromised? > > Distinguish the Prem API Gateway from the local Confidential Proxy. The gateway is intended to handle ciphertext and operational metadata. The local proxy handles plaintext, the API key, and the KEK on your machine; compromise of that local process can expose content and credentials. > [accordion] What if someone intercepts the network traffic? > > The observed payload is encrypted by TLS and the client payload-encryption layer. Security still depends on correct endpoint authentication, key handling, implementation, and the assumptions of the hybrid key exchange. > [accordion] What about quantum computers? > > Prem API uses a hybrid exchange that combines ML-KEM768 and X25519. The design reduces reliance on X25519 alone for the harvest-now, decrypt-later threat model. It does not support an absolute claim about future cryptographic security. > [accordion] What if a Prem API employee goes rogue? > > TEE isolation is intended to restrict host access, while deployment access controls and change management reduce operator risk. The released CPU verifier compares measured state with signed release references. Operational access, reference approval, routing and incident response remain separate controls. > [accordion] What if someone tampers with the enclave code? > > Hardware evidence contains measurements that change when measured components change. Reticle compares the policy-selected CPU measurements with signed [Trustbase references](https://github.com/prem-research/trustbase). Unregistered or mismatched measured configurations fail policy evaluation. > [accordion] What if there's a bug in the verification code itself? > > Reticle is implemented in Rust and can compile to WebAssembly. Rust prevents many memory-safety bugs in safe code, while unsafe code, dependencies, logic errors, policy errors, and runtime vulnerabilities still require review and testing. > [accordion] What if the cloud provider or data center operator is malicious? > > Confidential-computing hardware is designed to reduce trust in the host operator. Manufacturer evidence, approved measurements, firmware policy, physical controls, and incident response must all be evaluated; infrastructure ownership does not make those risks identical. > [accordion] How does Prem protect response integrity? > > For each request, the system does a fresh key exchange with the enclave. The enclave encrypts the response with a secret unique to that request. The proxy cannot change the response. The proxy cannot send a different response. See [Encryption](/encryption) for more information. ## Shared Responsibility Model Prem operates the managed infrastructure and protected-runtime controls. Customers remain responsible for their applications, local proxy hosts, keys, tool integrations, and workload policy. ### The responsibilities of Prem * Prem operates the confidential-computing and attestation infrastructure * Prem maintains the documented transport, payload-encryption, and protected-processing controls * Prem maintains the documented model serving and protected-runtime controls * Prem manages the physical infrastructure security and the platform availability ### Your responsibilities * **Key management:** Generate, store, and rotate your encryption keys, for example the Key Encryption Key (**KEK**). Do not lose your master key. If you lose it, Prem cannot recover your data. * **Application security:** Secure the endpoints and devices where the Prem API SDK runs. The SDK decrypts data on your local hardware. * **Prompt and model level security:** Defend against prompt injections and jailbreaks in your specific AI workflows. ## Limitations No security system is absolute. The limitations above define the current assurance boundary and the checks that remain necessary. > [!WARNING] > > **Prem API does not protect against:** > > * **Hardware-level side-channel attacks**: Researchers found theoretical and practical side-channel vulnerabilities in TEE hardware. The manufacturers patch these vulnerabilities. The attestation reports include the firmware versions, so you can check the patch levels and we can enforce minimum requirements. Side-channel attacks could be possible in theory. But Prem API selects deployment locations that meet strict security criteria and can apply counter mechanisms to detect invalid states. This is an industry-wide challenge, not a challenge unique to Prem API. > * **A compromised hardware manufacturer**: If the root signing keys of AMD, Intel, or NVIDIA are compromised, the attestation guarantees become weaker. This is the shared root of trust for the full confidential computing industry. > * **Model behavior**: Prem API protects the privacy of your data during processing. Prem API does not control what the AI model itself does with context during a single inference pass. For example, model memorization is a model-level concern, not an infrastructure concern. > * **Metadata**: The Prem gateway handles time, payload size, API key, model, routing, billing, and rate-limit metadata. Payload confidentiality depends on the client encryption path and the selected processing route. > [!NOTE] > > See the [Encryption](/encryption) reference for the full cryptographic specification. Continue to [Attestation](/attestation) for the attestation detail: reports, tokens, and verification code. # Tiers Source: https://docs.prem.io/tiers Compare the usage tiers and the limits of each tier. > [!NOTE] > > **The short answer:** your tier sets the request rate, concurrency, and token/audio allowances for your organization. Confidential and ZDR usage have separate allowances. Your monthly spending budget is a separate organization setting. ## Usage tiers Prem applies tiers to organizations. All API keys in an organization use one tier, including keys that different members own. Each tier has separate **Confidential** and **ZDR** limits for concurrent requests, request rate, tokens, and audio duration. All API keys in an organization share each family's allowance. More users, keys, or endpoints in that family do not increase the allowance. Your tier and eligibility conditions are shown in the dashboard. Eligibility depends on total payments and the time since the first payment, rather than the current account balance. Use the current tier definitions for your organization instead of assuming a fixed allowance from the tier name. ## Limits by tier Choose **Confidential** or **ZDR** on the dashboard's [limits page](https://dashboard.prem.io/billing/limits) to see the current capacities, refill rates and active periods. `GET /billing/tiers` lists tier definitions for your product; the dashboard shows which tier applies to your organization. | Allowance | What it controls | | - | - | | Request rate | Burst capacity and refill rate for each active request window | | Concurrent requests | How many requests may be active in the family at once | | Tokens | Model token usage, with a capacity and refill rate for each active period | | Audio | Audio duration in seconds, with a capacity and refill rate for each active period | All keys in an organization share these allowances, including keys owned by different members. Increasing the number of members or keys does not multiply these allowances. > [!TIP] > > Set an optional organization-wide monthly spending budget in [Limits](/billing/limits). The budget is shared across Confidential and ZDR usage and has no tier-based ceiling. ## Request limits Your tier sets a request burst capacity and a refill rate for each inference family. Requests per minute (RPM) describes the refill rate. The burst capacity is the maximum number of request credits that a bucket can hold. Prem uses token buckets for request limits. A request without an available credit returns `429`. Each active window with a finite limit must have a credit before a request can begin. The dashboard shows your current request capacities and refill rates. Inference endpoints share the request allowance for their family. Confidential chat, transcription, and translation share the Confidential allowance. `/openai/chat/completions` and `/typesafe/v1/systemone` share the ZDR allowance. A Confidential request does not use ZDR credits. A ZDR request does not use Confidential credits. Non-inference endpoints keep their separate request limits. A request for the model list does not use either inference allowance. General request limits apply to each organization and endpoint. Authentication and administration endpoints have their own limits. For the mechanism and for retry code, see [Rate limits](/rate-limits). ## Concurrent requests Prem limits the number of inference requests that an organization can process at one time in each family. All API keys in the organization share each family's concurrency slots. See the dashboard for your current Confidential and ZDR concurrency limits. All inference endpoints in a family use its concurrency limit. A request above the limit returns a `429`. For example, a configured limit of five produces: ```json theme={"system"} { "status": 429, "error": "Concurrent request limit reached. Your limit allows 5 concurrent request(s). Wait for ongoing requests to complete, or contact us for higher limits." } ``` The message shows the family's concurrency limit. The encrypted endpoint `/rvenc/chat/completions` returns JSON by default. It returns `text/event-stream` when `stream: true`. A request holds a slot while it waits for model capacity and while inference runs. Separate API keys do not increase the allowance. See [Agents & Automation](/agents). ## How to move to a higher tier Prem checks payment-based eligibility every five minutes. An organization can advance through more than one eligible tier in a check. This automatic process does not downgrade organizations. To see the tier of your organization, open the [limits page](https://dashboard.prem.io/billing/limits) in the dashboard. The `GET /billing/tiers` endpoint lists the limits of every tier, but it does not tell you which tier your organization has. If you need higher limits, [contact us](/contact-us). The Prem team can discuss custom tier limits for your organization. ## Related > [card] [Rate limits](/rate-limits) > > How Prem applies the limits, and what to do with a 429. > [card] [Limits](/billing/limits) > > Set the monthly spending limit of your organization. > [card] [Models & Pricing](/models-and-pricing) > > The price for each model, and the deployment strategies. > [card] [Production Checklist](/production-checklist) > > Make sure that your capacity and cost settings are correct before you go live. # Trust & Compliance Source: https://docs.prem.io/trust-and-compliance Certifications, audits, and the verifiable security properties of the Prem API platform. This page collects the trust resources for the Prem API platform: certifications, planned audits, and the security properties that you can verify yourself. ## Certifications * **SOC 2 Type I**: An independent auditor issued a SOC 2 Type I report for Prem. The report is available on request. Contact us at [support@premai.io](mailto:support@premai.io). ## Independent verification Prem API does not ask you to trust a report alone. The core security properties are verifiable: > [card] [Attestation](/attestation) > > Verify hardware evidence and signed release references with the SDK or Reticle. > [card] [Encryption](/encryption) > > End-to-end encryption with post-quantum algorithms. You hold the keys. > [card] [Data Retention](/data-retention) > > Zero retention of inference content, and the metadata list that we do keep. > [card] [Security Model](/security-model) > > The full threat model, the trust boundaries, and the limitations. The verification tools are open: * **TypeScript SDK**: [premAI-io/api-sdk-ts](https://github.com/premAI-io/api-sdk-ts) * **Attestation library**: `@premai/reticle` on npm, for server, browser, and mobile use (iOS and Android), with Rust crates for independent verification. See [Attestation](/attestation). * **Signed policies and measurements**: [Trustbase](https://github.com/prem-research/trustbase) — release references and Rego policies used by Reticle 0.6.2. * **Confidential-VM image source**: [PodVM](https://github.com/prem-research/podvm) — source, build configuration and release measurements. * **Signature verification**: [Tinysig](https://github.com/prem-research/tinysig) — components used to authenticate release references. ## Planned audits An independent audit of the platform is planned. We track it on the [Platform Status](/platform-status) page and we will publish the results when the audit completes. ## Resources * **Whitepaper**: [Prem Enclave Whitepaper (PDF)](https://static.prem.io/Prem%20Enclave%20Whitepaper%20-%20v2.pdf). The technical design of the enclave platform. * **Status page**: [status.premai.io](https://status.premai.io). Live platform availability. * **Infrastructure locations**: Owned hardware in Switzerland and rented hardware in Europe and the United States, all with identical TEE guarantees. See the [Security Model](/security-model). > [!NOTE] > > Enterprise requirements, agreements, or security questionnaires? Contact us at [support@premai.io](mailto:support@premai.io). # Use LLMs Source: https://docs.prem.io/use-llms LLM-Friendly documentation for Faster Developer Integration ## Add Prem API to your AI agent with `skill.md` The documentation includes a [`skill.md`](https://docs.prem.io/skill.md) file. This file tells your AI coding agent (Claude Code, Cursor, Windsurf, and others) how to use the Prem API. No manual setup is necessary. ### One-command setup Run this command in your terminal to load the Prem API skill into the context of your agent: ```bash theme={"system"} npx skills add https://docs.prem.io/skill.md ``` No more steps are necessary. ## Use the `llms-full.txt` file with your code editor You can load the full documentation for Prem API into your code editor. The AI assistant can then refer to the documentation directly in your workflow. Do these steps to configure Cursor: 1. Go to **Cursor Settings** > **Features** > **Docs** 2. Click **"Add new doc"** 3. Paste this URL into the prompt: ```text theme={"system"} https://docs.prem.io/llms-full.txt ``` 4. After you add the URL, use **@docs** -> **Prem API** to refer to this documentation directly in your code. > [!NOTE] > > Use this page to load the API documentation into your coding agent. > The agent then understands the SDK ecosystem and how the API works. > It can help you write code that integrates with Prem. > > To deploy a system that calls Prem API itself, see [Agents & Automation](/agents). > Examples are a bot, an agent loop, a batch job, or an automated pipeline. # ZDR Compared With Confidential Inference Source: https://docs.prem.io/zdr/comparison A direct comparison of confidential inference, Zero Data Retention, and a typical inference provider. > [!NOTE] > > **The short answer:** Use confidential inference for sensitive data and for production workloads. Use ZDR for evaluation, for prototypes, and for public data. Do not send sensitive data to a typical inference provider. ## The comparison | | Confidential inference | Zero Data Retention | A typical inference provider | | - | - | - | - | | **Basis of the guarantee** | Hardware and cryptography | A contract and operational controls | A policy | | **Content at the provider** | Ciphertext only | Plaintext, but nobody keeps it | Plaintext, and a policy controls what the provider keeps | | **Encryption** | Client-side, end-to-end | TLS 1.3 in transit | TLS 1.3 in transit | | **Processing environment** | A Trusted Execution Environment (AMD SEV-SNP or Intel TDX, with confidential GPUs) | Standard compute | Standard compute | | **Hardware evidence** | An attestation report that you can examine | None | None | | **Who holds the keys** | You hold the client KEK | Not applicable | The provider | | **Prompts and completions that stay** | None | None | Frequently 30 days, but it is different for each provider | | **Training on your content** | Not possible, because the content is unreadable | The contract does not permit it | Depends on the provider's terms | | **A person reads your content** | Not possible | The contract does not permit it | Frequent, for abuse review | | **Can you make sure of the claim?** | Yes | No | No | | **Post-quantum protection** | Yes, a hybrid ML-KEM768 exchange | No | No | | **Regions** | Switzerland | European Union, Switzerland, United Kingdom | It is different for each provider | | **Integration cost** | The SDK or the local proxy, and the custody of the KEK | Change one base URL | Change one base URL | ## How to choose > [card] [Use confidential inference](/quickstart) > > Regulated data, personal data, health records, financial documents, legal documents, source code, and each production workload with sensitive input. > [card] [Use ZDR](/zdr/overview) > > Evaluation, prototypes, public data, internal tests, and an OpenAI integration that must operate with no code changes. ## Why the basis of the guarantee is the important row One difference causes each row in the table. **Confidential inference removes the need to trust the operator.** Your device encrypts the payload. The Prem API Gateway sends ciphertext only. Only a sealed enclave holds the key material to decrypt it. The hardware supplies signed evidence, and you examine that evidence with an open verifier. Prem cannot read your content. See [Encryption](/encryption) and [Attestation](/attestation). **ZDR makes the trust smaller: one contract.** Two components can read your content: the gateway and the partner. Nobody keeps it. You cannot show this yourself. You rely on the agreement and on the operational controls of Prem. See [ZDR security boundary](/zdr/security-boundary). **A typical provider asks you to trust a policy.** The policy can change. The plaintext boundary contains the staff of the provider and its subprocessors. The provider frequently keeps content for a period, for abuse review. A change to a policy needs no technical change. Thus there is no signal that you can see. > [!WARNING] > > A published retention policy is a statement. It is not a control that you can test. Your threat model can contain the provider. A policy does not correct that risk. ZDR makes the risk smaller with a contract. Confidential inference removes the need to trust the contract. ## What each mode costs you Confidential inference asks for more work from you. You generate a client KEK, and you keep it. You use the Prem SDK, or you operate the local Confidential Proxy. You accept a smaller model catalog. ZDR asks for almost no work. You change the base URL of your OpenAI client. This difference in work is the reason to make one decision for each workload. Do not make one decision for the full application. Many teams use confidential inference for production traffic and ZDR for offline evaluation. > [!NOTE] > > Read the [current limitations](/platform-status) of the confidential path before you make a guarantee for a specific workload. The work on the attestation policy is not complete. > [card] [ZDR security boundary](/zdr/security-boundary) > > What ZDR protects and what it does not. > [card] [Confidential Security Model](/security-model) > > The confidential threat model and its limits. > [card] [Quickstart](/quickstart) > > Set up confidential inference. > [card] [ZDR overview](/zdr/overview) > > Set up ZDR. # Zero Data Retention Source: https://docs.prem.io/zdr/overview OpenAI-compatible inference through trusted partners, with no retention of your prompts or completions at any stage. > [!NOTE] > > **In one sentence:** Zero Data Retention (ZDR) sends OpenAI-compatible inference to trusted partners. Nobody keeps your prompts, completions, or audio content at any stage of the request. ## What ZDR is ZDR is the standard inference mode of the Prem API. You send a standard OpenAI Chat Completions request. Prem sends the request to a trusted inference partner. The partner sends back the completion. Prem does not keep your content, and the partner does not keep your content. Use ZDR when you want an OpenAI-compatible endpoint that needs no code changes. A contract makes sure that nobody keeps your content. ZDR also covers [Decisions](/guides/decisions), which answers typed questions with probabilities. Decisions uses the same ZDR guarantee and the same gateway. ## What ZDR is not ZDR is a different mode from [confidential inference](/how-it-works). The two modes give different guarantees. Read this list before you choose a mode: * **No client-side encryption.** TLS protects your request in transit. Your content is plaintext at the Prem API Gateway and at the partner. * **No Trusted Execution Environment (TEE).** ZDR operates on standard compute. The hardware does not isolate the workload. * **No attestation.** The hardware supplies no signed evidence, and there is nothing for you to examine. `GET /attestation/attest` applies only to confidential models. * **A contract gives the guarantee, not cryptography.** A contract and operational controls stop retention. Mathematics does not stop it. > [!WARNING] > > Use [confidential inference](/quickstart) for regulated data, personal data, health records, source code, or other sensitive data. See [ZDR compared with confidential inference](/zdr/comparison) for the full decision. ## The trusted-partner model Prem does not operate the compute for ZDR. Prem sends each request to a partner. Each partner operates inference capacity under a zero-retention agreement. The agreement tells each partner that it must: * Keep no prompt, completion, or audio content after it sends back the response * Write no content to a log, a cache, or persistent storage * Use no content to train or to evaluate a model * Let no person read the content, and this rule contains abuse review and quality review Prem does not name its partners in this documentation. The partners operate in the European Union, Switzerland, and the United Kingdom. The availability is different for each model. Use the `regions` field from `GET /openai/models` to find where a model operates. See [Models & Pricing](/models-and-pricing). > [!NOTE] > > Do you need the partner list, the agreements, or a data processing agreement for a procurement review? Contact us at [support@premai.io](mailto:support@premai.io). ## Make your first request ### 1. Get an API key ZDR uses your standard Prem API key. Open the [dashboard](https://dashboard.prem.io/api-keys). Then create a key. The key must have the `chats.completion` scope. ```bash theme={"system"} export PREM_API_KEY="your-api-key" ``` You do not need a client KEK. The KEK is necessary only for confidential inference. ### 2. Set the base URL The ZDR base URL is: ```text theme={"system"} https://gateway.prem.io/openai ``` > [!WARNING] > > Do not add a `/v1` segment. The Prem API gives ZDR at `/openai`. A base URL that ends with `/v1` returns a 404 error. ### 3. Send a request ```python Python theme={"system"} import os from openai import OpenAI client = OpenAI( api_key=os.environ["PREM_API_KEY"], base_url="https://gateway.prem.io/openai", ) response = client.chat.completions.create( model="kimi-k3", messages=[{"role": "user", "content": "What can you help me build?"}], ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PREM_API_KEY!, baseURL: "https://gateway.prem.io/openai", }); const response = await client.chat.completions.create({ model: "kimi-k3", messages: [{ role: "user", content: "What can you help me build?" }], }); console.log(response.choices[0].message.content); ``` ```bash curl theme={"system"} curl https://gateway.prem.io/openai/chat/completions \ -H "Authorization: Bearer $PREM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "kimi-k3", "messages": [{"role": "user", "content": "What can you help me build?"}] }' ``` Set `"stream": true` to get a stream of server-sent events. The stream uses the OpenAI format. > [!NOTE] > > The [Prem API TypeScript SDK](/developer-experience) also works with ZDR. Set `enableZdr: true` on `createRvencClient` and point the proxy at `https://gateway.prem.io`. The SDK then returns a plain OpenAI-compatible client for the ZDR endpoint — no client KEK, no attestation, and no local proxy. This gives you one SDK for both confidential inference and ZDR. ## Compatibility The request body and the response body use the OpenAI Chat Completions format. Prem removes the identifiers of the upstream backend from the response. Then Prem sends the response to you. `GET /openai/models` uses the OpenAI models list format. Your OpenAI client can read the catalog with its standard method: ```python theme={"system"} for model in client.models.list(): print(model.id) ``` See [Models & Pricing](/models-and-pricing) for the models, the response fields, the regions, and the mode errors. [Decisions](/guides/decisions) is a separate surface with its own TypeSafe-compatible API at `POST /typesafe/v1/systemone` and its own catalogue at `GET /typesafe/v1/models`. Call it with the official [TypeSafe client](https://www.npmjs.com/package/@typesafe-ai/sdk) or with plain JSON. See the [Decisions API reference](/api-reference/zdr-decisions). ## Next steps > [card] [Security boundary](/zdr/security-boundary) > > What Prem holds, what the partner holds, and what ZDR does not protect. > [card] [Models & Pricing](/models-and-pricing) > > The models, the response fields, the regions, and the mode errors. > [card] [ZDR compared](/zdr/comparison) > > ZDR, confidential inference, and a typical inference provider. > [card] [Chat completions API](/api-reference/zdr-chat-completions) > > The full request and response reference. > [card] [Decisions API](/api-reference/zdr-decisions) > > Typed questions with probabilities, in ZDR mode. # ZDR Security Boundary Source: https://docs.prem.io/zdr/security-boundary Where your content is readable in ZDR mode, what Prem records, what the partner records, and what ZDR does not protect. > [!NOTE] > > **Summary:** In ZDR mode your content is plaintext at the Prem API Gateway and at the trusted partner. Prem does not keep it, and the partner does not keep it. A contract and operational controls give the guarantee. Hardware and cryptography do not give it. ## The path of a request ```mermaid theme={"system"} flowchart LR subgraph You["Your Application"] A["Plaintext request"] end subgraph Prem["Prem API Gateway"] B["Authentication, rate limits, model routing"] end subgraph Partner["Trusted Partner"] C["Inference on standard compute"] end A -->|"TLS 1.3"| B B -->|"TLS 1.3"| C C -->|"TLS 1.3"| B B -->|"TLS 1.3"| A ``` Two components can read your content: the Prem API Gateway and the partner. TLS 1.3 protects the two network connections. This path does not use a Trusted Execution Environment (TEE). The confidential path is different. Your device encrypts the payload, and only a sealed enclave can decrypt it. See [How It Works](/how-it-works). ## What Prem records Prem filters each ZDR request body through a strict allowlist. This filter operates before Prem writes a log record. Prem can record only these fields: `model`, `stream`, `stream_options`, `temperature`, `top_p`, `n`, `seed`, `max_tokens`, `max_completion_tokens`, `presence_penalty`, and `frequency_penalty` The `messages` field is not on the allowlist. Your prompts never reach the request log. The Decisions route carries `state` and `questions` instead of `messages`. Those fields are not on the allowlist either. Your decision context and your questions never reach the request log. Prem does not send the response body to the logger. The gateway sends the completion to you. Then it records only the status code, the model name, and the environment. Your completions never go into the response log. The usage record holds the token counts and the price for each request. It holds no content. | Data | Recorded | | - | - | | Prompts and messages | No | | Completions and model output | No | | Sampling parameters and model name | Yes | | API key, organization, and timestamp | Yes | | Token counts and price | Yes | | Region and selected upstream | Yes | ## What the trusted partner records Nothing. Each partner operates under an agreement. The agreement tells the partner that it must not keep your content. The partner must not write your content to a log or to a cache. The partner must not use your content to train a model. No person at the partner can read your content. Prem makes sure of this with a contract and with an operational review. You cannot make sure of it yourself with a technical control. This is the most important difference from confidential inference. ## What ZDR does not protect against > [!WARNING] > > **ZDR does not protect against:** > > * **Access to the Prem infrastructure.** The Prem API Gateway processes your content in memory. Access controls and audit logs limit this exposure. Hardware does not stop it. > * **Access to the partner infrastructure.** The partner processes your content in plaintext on standard compute. The zero-retention agreement limits what the partner can do. Hardware does not stop it. > * **A breach of contract.** A partner can disobey the agreement. No technical control at Prem finds this condition. > * **A legal order.** A valid legal order can make Prem give the data that is available at that time. The content is not available after the response. The metadata is available. > * **The behavior of a model.** Prem does not have control of what a model does with the context in one inference pass. > > A contract and operational controls stop retention. Mathematics does not stop it. There is no attestation evidence for a ZDR request. There is no cryptographic guarantee. ## When this boundary is not sufficient Use [confidential inference](/quickstart) when a plaintext boundary at the provider is not acceptable. In confidential mode your device encrypts the payload. Only a sealed enclave can decrypt it. The hardware supplies signed evidence, and this evidence lets you examine the runtime that processed your request. See [Security Model](/security-model) and [Attestation](/attestation). > [!NOTE] > > See [ZDR compared with confidential inference](/zdr/comparison) for the decision matrix. ## Your responsibilities * **Choose the correct mode.** Send sensitive content to the confidential routes, not to ZDR. * **Protect your API key.** The key authenticates each request. Prem also uses the key for billing. See [API Keys](/api-keys). * **Make your application secure.** Your content is plaintext in your own application and on your own hosts. * **Defend against prompt injection.** Security at the model level and at the prompt level stays your responsibility. > [card] [ZDR compared](/zdr/comparison) > > ZDR, confidential inference, and a typical inference provider. > [card] [Confidential Security Model](/security-model) > > The threat model for the confidential path, with its limitations. > [card] [Data Retention](/data-retention) > > The retention policy for confidential inference. > [card] [Trust & Compliance](/trust-and-compliance) > > Certifications, audits, and independent verification.