{"openapi":"3.1.0","info":{"title":"grunden.ai API","version":"2.0.0","description":"OpenAI-compatible API for open-source language models running in the EU.\n\n## Request id\n\nEvery response carries `x-request-id`, errors and streamed responses too. You may send your own `x-request-id`: if it is a UUID (canonical form, any version) it is the request's id and comes back unchanged. Otherwise it is replaced, and the response carries the id we gave the request. Quote that id when you contact us about a call. Idempotency still reads your own value: `Idempotency-Key`, or `x-request-id` as before, decides whether a resend is rejected with 409.\n\n## Changelog\n\n| Date | Change |\n|---|---|\n| 2026-11-17 | `/v1/messages`: a `model` we don't have (such as the one Claude Code sends) runs on `deepseek-v4.1-flash-1017` instead of `glm-5.3-flash`. `glm-5.3-flash` can still be requested by name. |\n| 2026-11-02 | Every response carries `x-request-id`. An inbound `x-request-id` that is not a UUID is replaced by our own id in the response. |\n| 2026-10-29 | With a Hydra token (`hydraAuth`) the entitlement is checked per user: the user must be included in the organization's subscription. New error codes `no_seat` (403), `quota_not_configured` (503) and `concurrency_limit_exceeded` (429, at most 16 calls in flight per user, organization and app; the web chat counts separately); `daily_cap_reached` (429) applies to the user's daily cap, resets at midnight Swedish time and carries `error.resets_at` and `Retry-After`. `error.type` follows the status — use `code`. Errors from `/v1/messages` now carry `error.code`. `GET /v1/usage/allocation` shows web chat and Grunden Work usage that the organization's balance pays when a person's daily cap is reached, with `api_key_name` \"Webbchatt – <name>\" and \"Grunden Work – <name>\". |\n| 2026-10-27 | `GET /v1/usage/allocation` includes evals and prompt-optimisation runs, which are charged to the organisation's balance, per user with `api_key_name` \"Evals – <name>\". `requests` counts a streaming transcription (`/v1/audio/realtime`) as one request per started audio minute instead of one per session. |\n| 2026-10-17 | Wallets and prices in EUR. `GET /v1/usage/allocation`: `cost_gross_microore`, `cost_net_microore` and `cost_vat_microore` are now `cost_gross_nanoeur`, `cost_net_nanoeur` and `cost_vat_nanoeur` (JSON and CSV), with no overlap period, and `currency` is `EUR`. The integers are unchanged: earlier periods are reported converted at 10 kr = €1. `currency_decimals` is 2 as before, the currency's display decimals; the scale of the amounts is in the field name (€1 = 10^9 nano-euro). |","contact":{"email":"hej@grunden.ai","url":"https://grunden.ai"},"license":{"name":"Grunden AI AB terms of service","url":"https://grunden.ai/terms"},"termsOfService":"https://grunden.ai/terms"},"externalDocs":{"description":"Full documentation","url":"https://grunden.ai/docs"},"servers":[{"url":"https://api.grunden.ai","description":"Production"},{"url":"https://staging.grunden.ai","description":"Staging (unstable, no SLA)"}],"tags":[{"name":"Chat","description":"OpenAI-compatible chat completions. SSE streaming is supported."},{"name":"Models","description":"Model catalog. Readable anonymously — no API key required for discovery."},{"name":"Usage","description":"Usage summed per key and cost dimension. Org-scoped to the API key."},{"name":"Batch","description":"Asynchronous jobs delivered via webhook when the result is ready."},{"name":"Embeddings","description":"Text embedding vectors. OpenAI-compatible response."},{"name":"Rerank","description":"Cross-encoder reranking (BGE-reranker-v2-m3). Dedicated endpoint — NOT model-routed via /v1/chat/completions."},{"name":"PII","description":"PII detection and masking (GLiNER). Dedicated endpoint — NOT model-routed via /v1/chat/completions; send text directly, no model field."},{"name":"Knowledge bases","description":"Build and fill knowledge bases (RAG): create, upload documents/text, link API keys. Query them via knowledge_base_id on POST /v1/chat/completions."},{"name":"Messages (Anthropic-kompatibel)","description":"The Anthropic Messages API in wire format. IMPORTANT: grunden.ai does NOT run Claude/Anthropic models — this endpoint serves our own models (default deepseek-v4.1-flash-1017) in Anthropic's request/response shape, so that Anthropic SDK tools (Claude Code etc.) can point at an EU-hosted model. No US providers involved. Auth: x-api-key (Anthropic SDK style) or Authorization: Bearer."},{"name":"Konto","description":"Account actions and traceability: balance, erasure under GDPR Article 17 and reading your own audit log."},{"name":"Meta","description":"The contract itself. The spec can be fetched without an API key — a client should be able to generate code before it has a key."}],"x-rate-limits":{"description":"Default per API key. Increases available via support for paying customers.","free":{"rpm":60,"tpm":100000},"paid":{"rpm":600,"tpm":1000000},"notes":"rpm = requests per minute, tpm = input+output tokens per minute. Värden skickas tillbaka i X-RateLimit-headers vid 429."},"security":[{"bearerAuth":[]}],"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"API key","description":"API key starting with 'sk-grunden-'. Create one via Settings → API keys on your team."},"hydraAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Access token from auth.grunden.ai (OIDC). Intended for apps in the ecosystem that sign the user in with SSO instead of handling an API key. ALWAYS requires the X-Grunden-Org header with the organization's UUID — usage is metered and billed to that organization, and authorization is checked against exactly that value. Accepted on most endpoints; the exceptions are /v1/batch/{id}, DELETE /v1/account, /v1/audit-log, /v1/balance and /v1/usage/allocation, which require an API key."}},"parameters":{"OrgHeader":{"name":"X-Grunden-Org","in":"header","required":true,"schema":{"type":"string","format":"uuid"},"description":"The organization the call applies to. Required when you authenticate with hydraAuth; ignored with an API key, which is already bound to an organization."}},"schemas":{"ChatMessage":{"type":"object","required":["role"],"description":"A message in the conversation. Required fields vary by role: user/system require content; assistant allows null content if tool_calls is present; tool requires tool_call_id + content (string).","properties":{"role":{"type":"string","enum":["system","user","assistant","tool"]},"content":{"description":"String (text), null (assistant turns with only tool_calls), or an array of content parts for multimodal models.","oneOf":[{"type":"string"},{"type":"array","items":{"$ref":"#/components/schemas/ContentPart"}},{"type":"null"}]},"name":{"type":"string","description":"Optional name to distinguish between participants."},"tool_calls":{"type":"array","description":"Tool calls the assistant wants the client to perform. Only on assistant messages.","items":{"$ref":"#/components/schemas/ToolCall"}},"tool_call_id":{"type":"string","description":"References which tool_call this tool message responds to. Required for role=tool."}}},"ToolCall":{"type":"object","required":["id","type","function"],"properties":{"id":{"type":"string"},"type":{"type":"string","enum":["function"]},"function":{"type":"object","required":["name","arguments"],"properties":{"name":{"type":"string"},"arguments":{"type":"string","description":"JSON-serialized arguments — not an object. The client JSON.parses them itself."}}}}},"ToolDefinition":{"type":"object","required":["type","function"],"properties":{"type":{"type":"string","enum":["function"]},"function":{"type":"object","required":["name"],"properties":{"name":{"type":"string","description":"Function name. Max 64 characters, [a-zA-Z0-9_-] recommended."},"description":{"type":"string","description":"Explanation of when the model should use the tool."},"parameters":{"type":"object","description":"JSON Schema for the function parameters. Leave empty for parameterless functions."}}}}},"ContentPart":{"oneOf":[{"type":"object","required":["type","text"],"properties":{"type":{"type":"string","enum":["text"]},"text":{"type":"string"}}},{"type":"object","required":["type","image_url"],"properties":{"type":{"type":"string","enum":["image_url"]},"image_url":{"type":"object","required":["url"],"properties":{"url":{"type":"string","description":"Either a public https URL or a data:image/...;base64, URI."},"detail":{"type":"string","enum":["auto","low","high"],"default":"auto"}}}}}]},"BatchWebhookPayload":{"type":"object","description":"Payload POSTed to the tier=async webhook_url when the job is done. Signed with HMAC-SHA256 in the X-Grunden-Signature header (v1) + X-Grunden-Signature-V2 (timestamp + replay protection, recommended — see the /webhooks endpoint for the format). The HMAC key is shown once when the key is created.","required":["id","status","created_at"],"properties":{"id":{"type":"string","description":"Batch job id."},"object":{"type":"string","enum":["batch.job.completed"]},"status":{"type":"string","enum":["completed","failed","expired"]},"model":{"type":"string"},"created_at":{"type":"integer"},"completed_at":{"type":["integer","null"]},"response":{"oneOf":[{"$ref":"#/components/schemas/ChatCompletionResponse"},{"type":"null"}]},"error":{"type":["string","null"]},"usage":{"$ref":"#/components/schemas/Usage"}}},"ChatCompletionChunk":{"type":"object","required":["id","object","created","model","choices"],"description":"An SSE chunk in 'data: {...}\\n\\n' format. The last event before the end of the stream is 'data: [DONE]' (no JSON).","properties":{"id":{"type":"string"},"object":{"type":"string","enum":["chat.completion.chunk"]},"created":{"type":"integer"},"model":{"type":"string"},"choices":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer"},"delta":{"type":"object","properties":{"role":{"type":"string","enum":["assistant"]},"content":{"type":"string"}}},"finish_reason":{"type":["string","null"],"enum":["stop","length","content_filter",null]}}}},"usage":{"description":"Only in the last chunk of the stream.","oneOf":[{"$ref":"#/components/schemas/Usage"},{"type":"null"}]}}},"Usage":{"type":"object","properties":{"prompt_tokens":{"type":"integer","minimum":0},"completion_tokens":{"type":"integer","minimum":0},"total_tokens":{"type":"integer","minimum":0}}},"ChatCompletionRequest":{"type":"object","required":["model","messages"],"properties":{"model":{"type":"string","description":"Canonical model id (e.g. 'deepseek-v4.1-flash-1017'). Get the list via GET /v1/models."},"messages":{"type":"array","items":{"$ref":"#/components/schemas/ChatMessage"}},"stream":{"type":"boolean","default":false,"description":"If true: return an SSE stream instead of JSON."},"tier":{"type":"string","enum":["priority","normal","async"],"default":"normal","description":"Price tier. `normal` is the list price per 1M tokens in `GET /v1/models`; `async` costs half (webhook within 12h). `priority` is temporarily unavailable."},"webhook_url":{"type":"string","format":"uri","description":"Required for tier=async. Grunden POSTs the result here when the job is done."},"temperature":{"type":"number","minimum":0,"maximum":2},"max_tokens":{"type":"integer","minimum":1},"reasoning_effort":{"type":"string","enum":["none","minimal","low","medium","high","max"],"description":"Reasoning level. Levels are per model — see `reasoning_levels` and `default_reasoning_level` in GET /v1/models. GLM 5.3: low | high | max, omitted = max. Gemma 4: none | high (thinking off/on), omitted = none. The full OpenAI vocabulary is accepted and mapped to the model's nearest level: on GLM, none/minimal → low and medium → high; on Gemma, everything except none → high. A valid value never yields 400. GLM cannot be turned off entirely: low is the floor. Send either reasoning_effort or the corresponding chat_template_kwargs key — if they say different things, the API responds 400. The reasoning is delivered separately in the reasoning_content field. On models without levels the parameter is ignored."},"top_p":{"type":"number","minimum":0,"maximum":1},"frequency_penalty":{"type":"number","minimum":-2,"maximum":2},"presence_penalty":{"type":"number","minimum":-2,"maximum":2},"user":{"type":"string","maxLength":128,"example":"kund-4711","description":"Your own cost dimension — a tag you choose yourself, e.g. per customer, department or project. Stored on the usage row and summed per dimension in GET /v1/usage/allocation. Optional; without it the call ends up under 'Not dimensioned'. Trimmed; at most 128 characters; control and invisible formatting characters are rejected with 400 (the value is NEVER truncated, since two dimensions sharing a prefix would then be merged silently). Send an opaque identifier, not personal data — see the data protection terms."},"prompt_cache_key":{"type":"string","maxLength":1024,"example":"konversation-8f3a2c","description":"Optional key for cache routing (OpenAI's field). Requests with the same key go to the same model instance and share its prefix cache, so the turns of a conversation become cheaper and faster. Use ONE key per conversation, e.g. its id — a single key for the whole app gathers all your traffic on one instance and makes it slower. Without the key, the instance is chosen from the system prompt and the first user message. At most 1,024 characters; an invalid value is ignored. Not passed on to the model."},"knowledge_base_id":{"type":"string","format":"uuid","description":"Grunden extension (RAG): id of a knowledge base to ground the answer in. Relevant excerpts are retrieved and injected automatically as context before the answer. The knowledge base must be linked to the API key via POST /v1/knowledge-bases/{id}/keys. Not supported with tier=async."},"knowledge_base_top_k":{"type":"integer","minimum":1,"maximum":10,"default":5,"description":"Number of knowledge base excerpts to inject (1–10). Only together with knowledge_base_id."},"tools":{"type":"array","description":"Functions the model may choose to call. The upstream provider must support tool calling — otherwise 400 is returned.","items":{"$ref":"#/components/schemas/ToolDefinition"}},"tool_choice":{"description":"Controls whether/how the model should use tools: 'auto' (default when tools are given), 'none', 'required', or an explicit function.","oneOf":[{"type":"string","enum":["auto","none","required"]},{"type":"object","required":["type","function"],"properties":{"type":{"type":"string","enum":["function"]},"function":{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}}}]}}},"ChatCompletionResponse":{"type":"object","required":["id","object","created","model","choices"],"properties":{"id":{"type":"string"},"object":{"type":"string","enum":["chat.completion"]},"created":{"type":"integer","description":"Unix timestamp."},"model":{"type":"string","description":"Canonical grunden.ai id (never underlying ids)."},"choices":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer"},"message":{"$ref":"#/components/schemas/ChatMessage"},"finish_reason":{"type":"string","enum":["stop","length","content_filter"]}}}},"usage":{"type":"object","properties":{"prompt_tokens":{"type":"integer"},"completion_tokens":{"type":"integer"},"total_tokens":{"type":"integer"}}}}},"BatchJobResponse":{"type":"object","properties":{"id":{"type":"string"},"object":{"type":"string","enum":["batch.job"]},"status":{"type":"string","enum":["queued","running","completed","failed","expired"]},"model":{"type":"string"},"tier":{"type":"string","enum":["async"]},"created_at":{"type":"integer"},"expires_at":{"type":"integer"},"completed_at":{"type":["integer","null"]},"webhook_url":{"type":["string","null"]},"response":{"type":["object","null"]},"error":{"type":["string","null"]}}},"EmbeddingRequest":{"type":"object","required":["model","input"],"properties":{"model":{"type":"string","description":"Embedding model. Currently: 'bge-m3' (BAAI/bge-m3, 1024-dim multilingual). Get the list via GET /v1/models with capabilities=embeddings. AT MOST 32 texts per call when input is an array — more yields 422 with the code batch_size_exceeded."},"input":{"description":"A single string or an array of strings for batch embedding.","oneOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"encoding_format":{"type":"string","enum":["float","base64"],"default":"float"},"dimensions":{"type":"integer","description":"Optional reduced dimension — supported only by some models."}}},"EmbeddingResponse":{"type":"object","required":["object","data","model","usage"],"properties":{"object":{"type":"string","enum":["list"]},"data":{"type":"array","items":{"type":"object","properties":{"object":{"type":"string","enum":["embedding"]},"index":{"type":"integer"},"embedding":{"description":"Array of float64 or a base64-encoded buffer depending on encoding_format.","oneOf":[{"type":"array","items":{"type":"number"}},{"type":"string"}]}}}},"model":{"type":"string"},"usage":{"type":"object","properties":{"prompt_tokens":{"type":"integer"},"total_tokens":{"type":"integer"}}}}},"RerankRequest":{"type":"object","required":["query","texts"],"description":"Reranking request. No model field — the endpoint serves BGE-reranker-v2-m3 directly.","properties":{"query":{"type":"string","description":"The search query the documents are ranked against."},"texts":{"type":"array","items":{"type":"string"},"description":"The documents/text passages to be ranked."}}},"RerankResponse":{"type":"array","description":"Array sorted by relevance (highest score first). `index` refers to the position in the request `texts`.","items":{"type":"object","required":["index","score"],"properties":{"index":{"type":"integer","description":"Index in the request `texts` array."},"score":{"type":"number","description":"Relevance 0–1 (cross-encoder)."}}}},"PiiRedactRequest":{"type":"object","required":["text"],"description":"PII redaction request. No model field and no labels — the endpoint serves GLiNER directly and detects Swedish entities automatically.","properties":{"text":{"type":"string","description":"The text to analyze and mask."}}},"PiiRedactResponse":{"type":"object","required":["masked","entities"],"properties":{"masked":{"type":"string","description":"The text with each detected entity replaced by [REDACTED]."},"entities":{"type":"array","items":{"type":"object","required":["start","end","text","label","score"],"properties":{"start":{"type":"integer","description":"Start offset in text."},"end":{"type":"integer","description":"End offset in text."},"text":{"type":"string","description":"The detected string."},"label":{"type":"string","description":"Entity type, e.g. person, personnummer, address, email, phone."},"score":{"type":"number","description":"Confidence 0–1."}}}}}},"AnthropicContentBlock":{"description":"A content block in an Anthropic message. text/image in user messages, tool_use in assistant responses, tool_result back from the client. NOTE: image blocks are not supported by the model and are replaced with a text placeholder.","oneOf":[{"type":"object","required":["type","text"],"properties":{"type":{"type":"string","enum":["text"]},"text":{"type":"string"}}},{"type":"object","required":["type","id","name","input"],"properties":{"type":{"type":"string","enum":["tool_use"]},"id":{"type":"string"},"name":{"type":"string"},"input":{"type":"object"}}},{"type":"object","required":["type","tool_use_id"],"properties":{"type":{"type":"string","enum":["tool_result"]},"tool_use_id":{"type":"string"},"content":{"oneOf":[{"type":"string"},{"type":"array","items":{"$ref":"#/components/schemas/AnthropicContentBlock"}}]},"is_error":{"type":"boolean"}}}]},"AnthropicInputMessage":{"type":"object","required":["role","content"],"properties":{"role":{"type":"string","enum":["user","assistant"]},"content":{"description":"String (plain text) or an array of content blocks (text/image/tool_use/tool_result).","oneOf":[{"type":"string"},{"type":"array","items":{"$ref":"#/components/schemas/AnthropicContentBlock"}}]}}},"AnthropicTool":{"type":"object","required":["name","input_schema"],"description":"Tool definition in Anthropic's format.","properties":{"name":{"type":"string"},"description":{"type":"string"},"input_schema":{"type":"object","description":"JSON Schema for the tool's parameters."}}},"AnthropicMessagesRequest":{"type":"object","required":["max_tokens","messages"],"description":"Anthropic Messages request. `model`: a model we have runs as requested, an unknown name (e.g. claude-sonnet-4-5) runs on the default deepseek-v4.1-flash-1017 (we do not run Claude).","properties":{"model":{"type":"string","description":"A model we have (id or alias from GET /v1/models) runs as requested. An unknown name runs on the default deepseek-v4.1-flash-1017, so Anthropic SDKs always get an answer."},"max_tokens":{"type":"integer","minimum":1,"description":"Maximum number of tokens to generate."},"messages":{"type":"array","minItems":1,"items":{"$ref":"#/components/schemas/AnthropicInputMessage"}},"system":{"description":"System prompt: a string or an array of text blocks.","oneOf":[{"type":"string"},{"type":"array","items":{"type":"object"}}]},"tools":{"type":"array","items":{"$ref":"#/components/schemas/AnthropicTool"}},"tool_choice":{"type":"object","description":"Anthropic format: {type:'auto'|'any'|'none'|'tool', name?:string}."},"temperature":{"type":"number","minimum":0,"maximum":1},"top_p":{"type":"number","minimum":0,"maximum":1},"stop_sequences":{"type":"array","items":{"type":"string"}},"stream":{"type":"boolean","default":false,"description":"If true: SSE event stream in Anthropic's format (message_start, content_block_delta, message_delta, message_stop)."}}},"AnthropicMessage":{"type":"object","required":["id","type","role","model","content","stop_reason","usage"],"description":"Anthropic Messages response (non-streamed). `model` is the model that served the call.","properties":{"id":{"type":"string"},"type":{"type":"string","enum":["message"]},"role":{"type":"string","enum":["assistant"]},"model":{"type":"string","example":"deepseek-v4.1-flash-1017"},"content":{"type":"array","description":"Array of text and/or tool_use blocks. Always contains at least one block.","items":{"oneOf":[{"type":"object","required":["type","text"],"properties":{"type":{"type":"string","enum":["text"]},"text":{"type":"string"}}},{"type":"object","required":["type","id","name","input"],"properties":{"type":{"type":"string","enum":["tool_use"]},"id":{"type":"string"},"name":{"type":"string"},"input":{"type":"object"}}}]}},"stop_reason":{"type":"string","enum":["end_turn","max_tokens","stop_sequence","tool_use"]},"stop_sequence":{"type":["string","null"]},"usage":{"type":"object","required":["input_tokens","output_tokens"],"properties":{"input_tokens":{"type":"integer","minimum":0},"output_tokens":{"type":"integer","minimum":0},"cache_creation_input_tokens":{"type":"integer","minimum":0},"cache_read_input_tokens":{"type":"integer","minimum":0}}}}},"ModelsListResponse":{"type":"object","description":"Model catalog. IMPORTANT: every model has `type` + `endpoint`, which specify HOW it is called. Only `type:\"chat\"` models go via /v1/chat/completions; the others (embedding/rerank/pii) have dedicated endpoints given in `endpoint`. Never send a non-chat model to /v1/chat/completions.","properties":{"object":{"type":"string","enum":["list"]},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"object":{"type":"string","enum":["model"]},"created":{"type":"integer"},"owned_by":{"type":"string","enum":["grunden.ai"]},"type":{"type":"string","enum":["chat","embedding","rerank","stt","tts","pii"],"description":"The model's category. Determines which endpoint serves it. (stt/tts are temporarily inactive.)"},"endpoint":{"type":"string","description":"The path that serves the model, e.g. /v1/chat/completions, /v1/embeddings, /v1/rerank, /v1/pii/redact. Call the model HERE — not via the model field on another endpoint.","example":"/v1/pii/redact"},"context_window":{"type":["integer","null"],"description":"Context window in tokens. null when the catalog has no value — that is not the same as zero.","example":200000},"capabilities":{"type":"array","items":{"type":"string"},"description":"What the serving supports for the model: chat, tools, vision, reasoning (levels low/high/max), thinking_toggle (thinking off/on), embeddings, audio_transcription, rerank, pii. The capability lives in the DEPLOYMENT, not in the weights — a model without a tool-call parser on the machine serving it lacks `tools` here, and calls with `tools` against it are rejected with 400.","example":["chat","reasoning","tools","vision"]},"supported_parameters":{"type":"array","items":{"type":"string"},"description":"Non-obvious request parameters the model accepts (`tools`, `reasoning_effort`). Derived from capabilities.","example":["reasoning_effort","tools"]},"reasoning_levels":{"type":"array","items":{"type":"string","enum":["none","low","high","max"]},"description":"The model's actual levels for `reasoning_effort`, ascending. Per model: GLM 5.3 `[\"low\",\"high\",\"max\"]`, Gemma 4 `[\"none\",\"high\"]` (thinking off/on). Other valid values are mapped to the nearest level. Omitted for models without levels — there the parameter does nothing.","example":["low","high","max"]},"default_reasoning_level":{"type":"string","enum":["none","low","high","max"],"description":"The level the model runs at when `reasoning_effort` is omitted. Always one of `reasoning_levels`; omitted when those are.","example":"max"},"input_modalities":{"type":"array","items":{"type":"string","enum":["text","image"]},"description":"Only type=chat. What the model actually READS, not what the endpoint accepts: `image` is listed only when every active provider row for the model has `vision`. Omitted when the model has no active rows.","example":["text","image"]},"output_modalities":{"type":"array","items":{"type":"string","enum":["text"]},"description":"Only type=chat. What the model produces.","example":["text"]},"tool_calling":{"type":"boolean","description":"Only type=chat. true when the model returns structured `tool_calls` — requests with `tools` are then routed to a row with a tool-call parser."},"reasoning":{"type":"boolean","description":"Only type=chat. true when `reasoning_effort` has an effect — the same as `reasoning_levels` being present."},"context_length":{"type":"integer","description":"Only type=chat. The largest prompt + `max_tokens` the API lets through (95 % of `context_window`); above the limit the API responds 400 before the model is called. Omitted when the window is unknown. There is no separate limit on response length beyond this.","example":31129},"pricing":{"type":"object","required":["input_per_1m_tokens","cached_input_per_1m_tokens","output_per_1m_tokens"],"description":"Only type=chat. What the model costs per 1M tokens on the standard tier — the amount deducted from the balance, VAT included. Computed with the same formula as billing. If the model has several active provider rows with different prices, the most expensive one is given per field, so the price is a ceiling. Omitted when the price cannot be computed. cached_input_per_1m_tokens is the price for input tokens that hit the prefix cache (usage.prompt_tokens_details.cached_tokens); it is set per model and may equal the input price, in which case the model has no cache discount.","properties":{"input_per_1m_tokens":{"$ref":"#/components/schemas/MoneyAmount"},"cached_input_per_1m_tokens":{"$ref":"#/components/schemas/MoneyAmount"},"output_per_1m_tokens":{"$ref":"#/components/schemas/MoneyAmount"}}}}}}}},"MoneyAmount":{"type":"object","required":["amount","currency"],"properties":{"amount":{"type":"string","description":"Amount in the major unit as a decimal string, rounded up to at most six decimals. A string so that clients reading JSON numbers as floating point don't lose precision.","example":"0.5218"},"currency":{"type":"string","description":"ISO 4217 currency code. Currently always EUR.","example":"EUR"}}},"Balance":{"type":"object","description":"The organization's balance at the time of the call.","required":["object","org_id","balance"],"properties":{"object":{"type":"string","const":"balance"},"org_id":{"type":"string","format":"uuid","description":"The organization that owns the API key."},"balance":{"type":"object","description":"Amount and currency.","required":["amount","currency"],"properties":{"amount":{"type":"string","description":"The balance in the major unit as an exact decimal string — at least two decimals, otherwise as many as needed, never rounded. Can be negative. A string so as not to lose precision in clients that read JSON numbers as floats.","example":"42.517300125"},"currency":{"type":"string","description":"ISO 4217 currency code. Currently always EUR.","example":"EUR"}}}}},"Error":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["message","type","code"],"properties":{"message":{"type":"string"},"type":{"type":"string"},"code":{"type":"string","description":"The error code. Branch on it, never on `type` or the message.","enum":["invalid_request","invalid_lang","unauthorized","insufficient_balance","no_subscription","daily_cap_reached","rate_limit_exceeded","not_found","provider_unavailable","internal_error","missing_org","not_a_member","client_not_enabled","no_seat","feature_not_in_plan","access_disabled","concurrency_limit_exceeded","concurrency_check_failed","quota_not_configured","billing_check_unavailable"]},"resets_at":{"type":"string","format":"date-time","description":"Only with `daily_cap_reached`: when the user's daily cap resets (next midnight Swedish time), in UTC."}}}}}}},"paths":{"/v1/chat/completions":{"post":{"summary":"Chat completion","description":"OpenAI-compatible chat completion. Supports streaming via SSE with stream=true. For tier=async, returns 202 with a batch job id.","operationId":"createChatCompletion","tags":["Chat"],"parameters":[{"name":"Idempotency-Key","in":"header","required":false,"description":"Client-generated UUID/ULID (max 128 characters). A retry with the same key within 24 h is rejected with 409 (conflict) instead of being charged again — treat 409 as 'the original call stands'. The response body is not replayed. Recommended for all retries. (x-request-id is also accepted, but Idempotency-Key is preferred.)","schema":{"type":"string","maxLength":128,"pattern":"^[A-Za-z0-9_-]+$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatCompletionRequest"},"examples":{"basic":{"summary":"Simple chat request","value":{"model":"deepseek-v4.1-flash-1017","messages":[{"role":"user","content":"Hej!"}]}},"streaming":{"summary":"Streaming","value":{"model":"deepseek-v4.1-flash-1017","stream":true,"messages":[{"role":"user","content":"Skriv en haiku om regn."}]}},"async":{"summary":"Async via webhook","value":{"model":"deepseek-v4.1-flash-1017","tier":"async","webhook_url":"https://example.com/webhook","messages":[{"role":"user","content":"Sammanfatta följande text…"}]}}}}}},"responses":{"200":{"description":"Chat completion (JSON or SSE stream).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatCompletionResponse"}},"text/event-stream":{"schema":{"$ref":"#/components/schemas/ChatCompletionChunk"}}}},"202":{"description":"Async job queued (tier=async).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchJobResponse"}}}},"400":{"description":"Bad request (invalid_request) — missing fields, unknown tier, invalid webhook_url, etc.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Insufficient balance or subscription required (no_subscription / insufficient_balance).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown model or temporarily out of service.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded (rate_limit_exceeded / daily_cap_reached).","headers":{"Retry-After":{"schema":{"type":"integer"},"description":"Number of seconds to wait before the next attempt. Use exponential backoff with this as the lower bound."},"X-RateLimit-Remaining-Requests":{"schema":{"type":"integer"},"description":"Number of requests remaining in the current minute window."},"X-RateLimit-Remaining-Tokens":{"schema":{"type":"integer"},"description":"Number of tokens remaining in the current minute window."}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), or the concurrency could not be checked (concurrency_check_failed). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/models":{"get":{"summary":"List models","description":"Returns all active models in OpenAI format. No API key required: the catalog and the prices are public, so you can pick a model and see what it costs before you have a key. A key sent along is ignored. The limit is 60 requests per minute per IP address, and the response may be cached for 60 seconds.\n\nIn addition to OpenAI's fields, each model carries metadata about the serving: `context_window`, `capabilities`, `supported_parameters` and (when the model has reasoning levels) `reasoning_levels` and `default_reasoning_level`. Chat models additionally carry `input_modalities`, `output_modalities`, `tool_calling`, `reasoning`, `context_length` (the applied limit) and `pricing` (price per 1M input and output tokens in EUR). Unknown fields are omitted rather than guessed. The fields are additive — clients that don't know them can ignore them.","operationId":"listModels","tags":["Models"],"security":[],"responses":{"200":{"description":"Model list.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ModelsListResponse"},"examples":{"list":{"value":{"object":"list","data":[{"id":"deepseek-v4.1-flash-1017","object":"model","created":1793380738,"owned_by":"grunden.ai","type":"chat","endpoint":"/v1/chat/completions","context_window":1048576,"capabilities":["chat","reasoning","tools","vision"],"supported_parameters":["reasoning_effort","tools"],"reasoning_levels":["low","high","max"],"default_reasoning_level":"max","input_modalities":["text","image"],"output_modalities":["text"],"tool_calling":true,"reasoning":true,"context_length":996147,"pricing":{"input_per_1m_tokens":{"amount":"0.50","currency":"EUR"},"cached_input_per_1m_tokens":{"amount":"0.10","currency":"EUR"},"output_per_1m_tokens":{"amount":"1.50","currency":"EUR"}}}]}}}}}},"429":{"description":"Rate limit exceeded.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/usage/allocation":{"get":{"summary":"Usage per key and cost dimension","description":"Usage summed per API key and/or per cost dimension (the `user` field in the call), so you can allocate the cost to your own customers, departments or projects. Intended to be fetched by your business system.\n\nUsage billed to the organization's balance is counted: calls made with keys you can call the API with yourself, and evals and prompt optimization runs, which are shown per user with `api_key_name` \"Evals – <name>\" (\"Evals – [Raderad]\" for a deleted account), and web chat and Grunden Work usage when the organization's balance pays because a seat's daily cap is reached, per person and app with `api_key_name` \"Webbchatt – <name>\" and \"Grunden Work – <name>\". Usage included in the subscription is not shown. `requests` counts a streaming transcription (`/v1/audio/realtime`) as one request per started audio minute, so a 59½-minute session gives 60. The period is [from, to) — `from` inclusive, `to` exclusive — so two consecutive periods never count the same second twice.\n\nAmounts are integers in nano-euro (€1 = 10^9 nano-euro); `currency` is `EUR`, or null for an organization without a wallet. `cost_gross_nanoeur` is what was deducted from the balance and includes VAT; `cost_net_nanoeur` is the same amount excluding VAT; `cost_vat_nanoeur` is the difference. `currency_decimals` is the currency's ISO 4217 decimals for display, not the scale of the amounts. `vat` states which VAT rate and rule the breakdown is based on — under reverse charge the rate is 0 and net = gross. Usage before 2026-10-17 is reported in EUR with unchanged integers (see the changelog).","operationId":"getUsageAllocation","tags":["Usage"],"parameters":[{"name":"from","in":"query","required":true,"schema":{"type":"string","format":"date-time"},"example":"2026-08-01T00:00:00+02:00","description":"Start of the period, inclusive. ISO-8601 with time zone — you control which zone the month boundary refers to."},{"name":"to","in":"query","required":true,"schema":{"type":"string","format":"date-time"},"example":"2026-09-01T00:00:00+02:00","description":"End of the period, EXCLUSIVE. Must be after from."},{"name":"group_by","in":"query","required":false,"schema":{"type":"string","default":"api_key,end_user"},"example":"api_key,model","description":"Comma-separated grouping without duplicates: `api_key`, `end_user` and/or `model`. `end_user` groups on the cost dimension from the `user` field; `model` on the model that responded (the `model_id` field in the response, always present — null when `model` was not requested). Omitted gives `api_key,end_user`. Unknown values are rejected with 400."},{"name":"format","in":"query","required":false,"schema":{"type":"string","enum":["json","csv"],"default":"json"},"description":"CSV is delivered with content-disposition for download. Text values are quoted, and values starting with =, +, -, @, TAB or CR are prefixed with an apostrophe so spreadsheet programs don't execute them as formulas."}],"responses":{"200":{"description":"The allocation for the period.","content":{"application/json":{"examples":{"svensk":{"summary":"Swedish customer, grouped by key and dimension","value":{"object":"usage.allocation","from":"2026-10-31T23:00:00.000Z","to":"2026-11-30T23:00:00.000Z","group_by":["api_key","end_user"],"currency":"EUR","currency_decimals":2,"vat":{"rate_bp":2500,"reason":"domestic"},"data":[{"api_key_id":"3f2b1a9c-0000-0000-0000-000000000000","api_key_name":"Produktion","api_key_prefix":"sk-grunden-abc","end_user_ref":"kund-4711","requests":128,"prompt_tokens":51200,"completion_tokens":18400,"total_tokens":69600,"cost_net_nanoeur":2000000000,"cost_vat_nanoeur":500000000,"cost_gross_nanoeur":2500000000}],"totals":{"requests":128,"prompt_tokens":51200,"completion_tokens":18400,"total_tokens":69600,"cost_net_nanoeur":2000000000,"cost_vat_nanoeur":500000000,"cost_gross_nanoeur":2500000000}}}}},"text/csv":{"schema":{"type":"string"}}}},"400":{"description":"Period missing, reversed or empty; unknown group_by or format."},"401":{"description":"Missing or invalid API key."}}}},"/v1/embeddings":{"post":{"summary":"Create embeddings","description":"OpenAI-compatible embeddings endpoint. Returns vector(s) for one or more strings.","operationId":"createEmbedding","tags":["Embeddings"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EmbeddingRequest"},"examples":{"single":{"summary":"Single string","value":{"model":"bge-m3","input":"Hej världen!"}},"batch":{"summary":"Batch of several","value":{"model":"bge-m3","input":["Första texten","Andra texten"]}}}}}},"responses":{"200":{"description":"Embedding vectors.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EmbeddingResponse"}}}},"400":{"description":"Bad request.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Insufficient balance, subscription required, or a plan without the feature (no_subscription / insufficient_balance / feature_not_in_plan).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded (rate_limit_exceeded), the user's daily cap reached (daily_cap_reached, with `error.resets_at`) or too many calls in flight (concurrency_limit_exceeded). `Retry-After` gives the seconds until the next attempt.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), the concurrency could not be checked (concurrency_check_failed) or the billing check failed (billing_check_unavailable). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/rerank":{"post":{"summary":"Rerank documents against a query","description":"Cross-encoder reranking with BGE-reranker-v2-m3. Dedicated endpoint — send `query` + `texts`, NOT `model`. Not called via /v1/chat/completions.","operationId":"rerank","tags":["Rerank"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RerankRequest"},"examples":{"basic":{"summary":"Rank two documents","value":{"query":"huvudstad i Sverige","texts":["Stockholm är Sveriges huvudstad","Bananer är gula"]}}}}}},"responses":{"200":{"description":"Documents sorted by relevance.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RerankResponse"}}}},"401":{"description":"Invalid or missing API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Insufficient balance, subscription required, or a plan without the feature (no_subscription / insufficient_balance / feature_not_in_plan).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded (rate_limit_exceeded), the user's daily cap reached (daily_cap_reached, with `error.resets_at`) or too many calls in flight (concurrency_limit_exceeded). `Retry-After` gives the seconds until the next attempt.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), the concurrency could not be checked (concurrency_check_failed) or the billing check failed (billing_check_unavailable). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/pii/redact":{"post":{"summary":"Detect and mask PII","description":"PII detection and masking with GLiNER (Swedish entities). Dedicated endpoint — send only `text`, NO `model` field and no `labels`. NOT called via /v1/chat/completions (the model `gliner-multi-pii` in /v1/models is served by this endpoint).","operationId":"redactPii","tags":["PII"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PiiRedactRequest"},"examples":{"basic":{"summary":"Mask a sentence","value":{"text":"Anna Andersson, personnummer 19900101-1234, bor i Stockholm."}}}}}},"responses":{"200":{"description":"Masked text + detected entities.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PiiRedactResponse"}}}},"401":{"description":"Invalid or missing API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Insufficient balance, subscription required, or a plan without the feature (no_subscription / insufficient_balance / feature_not_in_plan).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded (rate_limit_exceeded), the user's daily cap reached (daily_cap_reached, with `error.resets_at`) or too many calls in flight (concurrency_limit_exceeded). `Retry-After` gives the seconds until the next attempt.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), the concurrency could not be checked (concurrency_check_failed) or the billing check failed (billing_check_unavailable). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/audio/transcriptions":{"post":{"summary":"Transcribe audio to text","description":"Speech to text with KB-Whisper Large (trained on Swedish speech). Send the audio file as multipart/form-data in the `file` field (as OpenAI) or `audio` — both engines take both. The cap is 50 MB per file — larger yields 413, and the file is counted byte by byte during streaming, so an incorrect content-length does not get past the cap. The output is NOT labeled as AI-generated: it is text transcribed from your own audio, not synthetic content. The `model` field picks the engine: omitted runs KB-Whisper Large, `pianissimo-sv`/`pianissimo-da` runs Pianissimo by KlangAI (CC BY 4.0). There is NO vocabulary hint (initial_prompt/hotwords) per call, so proper names and technical terms are transcribed by ear. The language is fixed per model: Swedish (KB-Whisper, `pianissimo-sv`) or Danish (`pianissimo-da`). Transcription is serialized — one call at a time for the whole service. Latency on an idle cluster: 30 s audio → 1.4 s, 3 min → 3.3 s. For STREAMING real-time transcription there is `wss://api.grunden.ai/v1/audio/realtime` (WebSocket, WhisperLive) — it cannot be expressed as an OpenAPI path; see /docs/kapaciteter/tal-till-text for protocol, billing and limits.","operationId":"createTranscription","tags":["Ljud"],"parameters":[{"name":"min_speakers","in":"query","required":false,"description":"Lower bound for the number of speakers when diarize=true. Default 1.","schema":{"type":"integer","default":1}},{"name":"max_speakers","in":"query","required":false,"description":"Upper bound for the number of speakers when diarize=true. Default 8.","schema":{"type":"integer","default":8}},{"name":"diarize","in":"query","required":false,"description":"Speaker diarization (who speaks when). Opt-in. ALSO requires the header X-Diarize-Attestation: true — without it the endpoint responds 400.","schema":{"type":"boolean"}},{"name":"X-Diarize-Attestation","in":"header","required":false,"description":"Must be 'true' when diarize=true. Your confirmation that you have a legal basis under GDPR Article 9.2 for the data subjects whose voices are separated — voice data that identifies persons is sensitive personal data. Every diarized call is logged for traceability.","schema":{"type":"string","enum":["true"]}}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"model":{"type":"string","enum":["pianissimo-sv","pianissimo-da"],"description":"Picks the engine. Omitted (or any other value): KB-Whisper Large. `pianissimo-sv` / `pianissimo-da`: Pianissimo by KlangAI (CC BY 4.0) for Swedish/Danish — faster and half the price, answers with `model`, `language`, `duration`, `text` and `segments`, no diarization."},"file":{"type":"string","format":"binary","description":"The audio file, in the `file` field (as OpenAI) or `audio` — send one of them. Max 50 MB. Decoded with ffmpeg: WAV, MP3, AAC in mp4/m4a, Opus in ogg and webm are verified."},"audio":{"type":"string","format":"binary","description":"The audio file, in the `file` field (as OpenAI) or `audio` — send one of them. Max 50 MB. Decoded with ffmpeg: WAV, MP3, AAC in mp4/m4a, Opus in ogg and webm are verified."}}}}}},"responses":{"200":{"description":"WhisperX's own response shape, NOT OpenAI's: `segments` (start, end, text, words, avg_logprob) and `word_segments` with a timestamp per word. There is no combined `text` field — assemble it from the segments' text. `response_format` is not supported."},"400":{"description":"diarize=true without X-Diarize-Attestation: true."},"402":{"description":"Insufficient balance, subscription required, or a plan without the feature (no_subscription / insufficient_balance / feature_not_in_plan).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"413":{"description":"The file is larger than 50 MB."},"422":{"description":"The multipart is missing the `audio` field (e.g. because the client sent `file`)."},"429":{"description":"Rate limit exceeded (rate_limit_exceeded), the user's daily cap reached (daily_cap_reached, with `error.resets_at`) or too many calls in flight (concurrency_limit_exceeded). `Retry-After` gives the seconds until the next attempt.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), the concurrency could not be checked (concurrency_check_failed) or the billing check failed (billing_check_unavailable). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/audio/speech":{"post":{"summary":"Synthesize speech from text","description":"Text to speech with Chatterbox. JSON in, audio file out — wav by default, mp3 and opus are also supported. Every file is labeled as AI-generated INSIDE the file (LIST/INFO chunk in WAV, ID3v2.4 in MP3, OpusTags in Ogg/Opus, all streams), with reference to EU AI Act Article 50.2, so the label travels with the file when it is saved or passed on. If a file cannot be labeled, 502 is returned instead of unlabeled audio — handle that error case. The audio data is not changed; only metadata is added.","operationId":"createSpeech","tags":["Ljud"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["model","input","voice"],"properties":{"model":{"type":"string","example":"chatterbox"},"voice":{"type":"string","description":"Required — without it the endpoint responds 422. Fixed set of voice file names; there is no list endpoint through our API. Valid values: Abigail.wav, Adrian.wav, Alexander.wav, Alice.wav, Austin.wav, Axel.wav, Connor.wav, Cora.wav, Elena.wav, Eli.wav, Emily.wav, Everett.wav, Gabriel.wav, Gianna.wav, Henry.wav, Ian.wav, Jade.wav, Jeremiah.wav, Jordan.wav, Julian.wav, Layla.wav, Leonardo.wav, Michael.wav, Miles.wav, Olivia.wav, Ryan.wav, Taylor.wav, Thomas.wav.","example":"Axel.wav"},"language":{"type":"string","example":"sv"},"response_format":{"type":"string","example":"wav"},"speed":{"type":"number"},"seed":{"type":"integer"},"input":{"type":"string","description":"The text to be read aloud.","example":"Hej och välkommen."}}}}}},"responses":{"200":{"description":"The audio file, labeled as AI-generated. The response also carries the header X-AI-Generated: true.","content":{"audio/wav":{"schema":{"type":"string","format":"binary"}}}},"402":{"description":"Insufficient balance, subscription required, or a plan without the feature (no_subscription / insufficient_balance / feature_not_in_plan).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded (rate_limit_exceeded), the user's daily cap reached (daily_cap_reached, with `error.resets_at`) or too many calls in flight (concurrency_limit_exceeded). `Retry-After` gives the seconds until the next attempt.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"502":{"description":"The audio could not be labeled as AI-generated and is therefore not let through."},"503":{"description":"The subscription has no daily cap (quota_not_configured), the concurrency could not be checked (concurrency_check_failed) or the billing check failed (billing_check_unavailable). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/messages":{"post":{"summary":"Anthropic Messages (default deepseek-v4.1-flash-1017)","description":"Anthropic Messages API in wire format. IMPORTANT: grunden.ai does NOT run Claude/Anthropic models — this endpoint serves our own models (default deepseek-v4.1-flash-1017) in Anthropic's request/response shape. Purpose: let Anthropic SDK tools (Claude Code etc.) point at an EU-hosted model without switching tools. Set ANTHROPIC_BASE_URL=https://api.grunden.ai and ANTHROPIC_API_KEY=sk-grunden-…. Auth: send x-api-key: sk-grunden-… (Anthropic SDK style, primary) OR Authorization: Bearer sk-grunden-… (the global bearerAuth scheme). The `model` field: a model we have runs as requested, otherwise the default deepseek-v4.1-flash-1017. SSE streaming is supported with stream:true. Not supported: image blocks (replaced with a text placeholder), thinking mode, prompt caching, top_k.","operationId":"createAnthropicMessage","tags":["Messages (Anthropic-kompatibel)"],"parameters":[{"name":"x-api-key","in":"header","required":false,"description":"API key (sk-grunden-…) in Anthropic SDK style. Alternative to Authorization: Bearer. At least one of them is required.","schema":{"type":"string"}},{"name":"anthropic-version","in":"header","required":false,"description":"The Anthropic SDK sends this header (e.g. 2023-06-01). Accepted and ignored.","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AnthropicMessagesRequest"},"examples":{"basic":{"summary":"Simple Messages request","value":{"model":"deepseek-v4.1-flash-1017","max_tokens":1024,"messages":[{"role":"user","content":"Hej!"}]}},"streaming":{"summary":"Streaming","value":{"model":"deepseek-v4.1-flash-1017","max_tokens":1024,"stream":true,"messages":[{"role":"user","content":"Skriv en haiku om regn."}]}}}}}},"responses":{"200":{"description":"Anthropic Messages response (JSON), or an SSE event stream when stream:true.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AnthropicMessage"}},"text/event-stream":{"schema":{"type":"string","description":"Anthropic SSE event sequence: message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop."}}}},"400":{"description":"Bad request — missing/empty messages array, wrong role value, invalid temperature/top_p, etc. Response in Anthropic's error format ({type:'error', error:{type, message}}).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Missing or invalid API key. Set ANTHROPIC_API_KEY (or x-api-key) to your sk-grunden-… key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Insufficient balance or subscription required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), or the concurrency could not be checked (concurrency_check_failed). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/batch/{id}":{"get":{"summary":"Get batch job","description":"Status + result for a batch job. The job, with its prompt and response, is deleted 30 days after it was created; after that the endpoint answers 404.","operationId":"getBatchJob","tags":["Batch"],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Async job status.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchJobResponse"}}}},"404":{"description":"The job does not exist, belongs to another user, or has been deleted (older than 30 days).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/knowledge-bases":{"post":{"tags":["Knowledge bases"],"summary":"Create knowledge base","operationId":"createKnowledgeBase","description":"Creates an empty knowledge base. Max 5 per organization (API keys). Then link the key with POST /v1/knowledge-bases/{id}/keys and upload content.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name"],"properties":{"name":{"type":"string","maxLength":128},"description":{"type":"string","maxLength":500}}}}}},"responses":{"201":{"description":"Created.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"description":{"type":["string","null"]},"total_bytes":{"type":"integer"},"doc_count":{"type":"integer"},"created_at":{"type":"string","format":"date-time"}}}}}},"429":{"description":"Quota exceeded (max 5 per org)."}}},"get":{"tags":["Knowledge bases"],"summary":"List knowledge bases","operationId":"listKnowledgeBases","description":"Lists the organization's knowledge bases.","responses":{"200":{"description":"List.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"description":{"type":["string","null"]},"total_bytes":{"type":"integer"},"total_chunks":{"type":"integer"},"doc_count":{"type":"integer"},"created_at":{"type":"string","format":"date-time"}}}}}}}}}}}},"/v1/knowledge-bases/{id}":{"delete":{"tags":["Knowledge bases"],"summary":"Delete knowledge base","operationId":"deleteKnowledgeBase","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Deleted (incl. all documents/chunks)."},"404":{"description":"Not found."}}}},"/v1/knowledge-bases/{id}/keys":{"post":{"tags":["Knowledge bases"],"summary":"Link the calling API key to the knowledge base","operationId":"linkKnowledgeBaseKey","description":"Binds the API key making the call to the knowledge base. The binding is required to use knowledge_base_id in chat calls.","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Linked."},"404":{"description":"Not found."}}},"delete":{"tags":["Knowledge bases"],"summary":"Remove link between key and knowledge base","operationId":"unlinkKnowledgeBaseKey","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Unlinked."},"404":{"description":"The link was not found."}}}},"/v1/knowledge-bases/{id}/documents":{"post":{"tags":["Knowledge bases"],"summary":"Upload document","operationId":"uploadKnowledgeBaseDocument","description":"Uploads a file (base64) that is extracted, chunked and embedded asynchronously. Supported formats: PDF, DOCX, PPTX, XLSX, CSV, TXT, Markdown, HTML. Max 50 MB per file, 200 MB total per knowledge base. The status goes extracting → chunking → embedding → ready.","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["filename","mime_type","content"],"properties":{"filename":{"type":"string"},"mime_type":{"type":"string","description":"E.g. application/pdf, text/plain, text/markdown, text/csv, application/vnd.openxmlformats-officedocument.wordprocessingml.document."},"content":{"type":"string","description":"File content, base64-encoded."}}}}}},"responses":{"201":{"description":"Received, ingest started.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"filename":{"type":"string"},"mime_type":{"type":"string"},"size_bytes":{"type":"integer"},"status":{"type":"string","example":"extracting"}}}}}},"400":{"description":"Invalid file / unsupported format."},"413":{"description":"File too large (max 50 MB)."},"429":{"description":"Storage quota exceeded (200 MB)."}}}},"/v1/knowledge-bases/{id}/snippets":{"post":{"tags":["Knowledge bases"],"summary":"Add text snippet","operationId":"createKnowledgeBaseSnippet","description":"Adds raw text (title + content) to the knowledge base without a file upload. Embedded asynchronously.","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["title","content"],"properties":{"title":{"type":"string","maxLength":256},"content":{"type":"string","maxLength":50000}}}}}},"responses":{"201":{"description":"Created, ingest started."},"404":{"description":"The knowledge base was not found."}}},"get":{"tags":["Knowledge bases"],"summary":"List text snippets","operationId":"listKnowledgeBaseSnippets","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"List of snippets."}}}},"/v1/knowledge-bases/snippets/{snippetId}":{"put":{"tags":["Knowledge bases"],"summary":"Update text snippet","operationId":"updateKnowledgeBaseSnippet","description":"Replaces the title and/or content. Changed content is re-embedded asynchronously.","parameters":[{"name":"snippetId","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"title":{"type":"string","maxLength":256},"content":{"type":"string","maxLength":50000}}}}}},"responses":{"200":{"description":"Updated."},"404":{"description":"The snippet was not found."}}},"delete":{"tags":["Knowledge bases"],"summary":"Delete text snippet","operationId":"deleteKnowledgeBaseSnippet","parameters":[{"name":"snippetId","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Deleted (incl. embeddings)."},"404":{"description":"The snippet was not found."}}}},"/v1/knowledge-bases/{id}/content":{"post":{"tags":["Knowledge bases"],"summary":"Add content (document or text)","operationId":"createKnowledgeBaseContent","description":"Unified entry point for filling a knowledge base: send either a file (base64) or raw text in the same call. The content is chunked and embedded asynchronously.","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"oneOf":[{"type":"object","required":["kind","filename","mime_type","content"],"properties":{"kind":{"type":"string","enum":["document"]},"filename":{"type":"string"},"mime_type":{"type":"string"},"content":{"type":"string","description":"File content, base64-encoded."}}},{"type":"object","required":["kind","title","content"],"properties":{"kind":{"type":"string","enum":["snippet"]},"title":{"type":"string","maxLength":256},"content":{"type":"string","maxLength":50000}}}]}}}},"responses":{"201":{"description":"Received, ingest started."},"400":{"description":"Invalid body or unsupported format."},"404":{"description":"The knowledge base was not found."},"413":{"description":"The content is too large."}}},"get":{"tags":["Knowledge bases"],"summary":"List content","operationId":"listKnowledgeBaseContent","description":"Lists both uploaded documents and text snippets with their current ingest status.","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"List of content items."},"404":{"description":"The knowledge base was not found."}}}},"/v1/knowledge-bases/{id}/content/{entryId}":{"delete":{"tags":["Knowledge bases"],"summary":"Delete content item","operationId":"deleteKnowledgeBaseContent","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}},{"name":"entryId","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Deleted (incl. chunks and embeddings)."},"404":{"description":"The item was not found."}}}},"/v1/audio/realtime":{"x-websocket":true,"get":{"tags":["Audio"],"summary":"Real-time transcription over WebSocket","operationId":"audioRealtime","description":"WebSocket endpoint for streaming speech to text. OpenAPI 3.1 lacks a WS operation, so the handshake is described here as GET and the path item is marked \"x-websocket\": true — connect with wss://, not with a plain GET call.\n\nConnect to wss://api.grunden.ai/v1/audio/realtime and send Authorization: Bearer <token> as an HTTP header DURING the upgrade (not as a WS message). Both an API key and a Hydra token are accepted; with a Hydra token, X-Grunden-Org is also required.\n\nSend audio as binary messages (max 2 MB per message) and receive transcriptions as JSON messages. The endpoint requires the audio services to be enabled — otherwise the upgrade fails.\n\nAccess is checked as on the REST paths: at the upgrade and then for every audio minute. A refusal at the upgrade returns the REST error's status and JSON body with `code`, plus `Retry-After` and `x-should-retry` where the REST error has them. A refusal mid-session closes it with close code 4402 (no_subscription, feature_not_in_plan, insufficient_balance), 4403 (no_seat, not_a_member), 4429 (daily_cap_reached) or 4503 (quota_not_configured), and with 1011 (billing_check_unavailable) when no decision could be made. The close reason is JSON, {\"code\": …}, with `resets_at` only for daily_cap_reached.","parameters":[{"$ref":"#/components/parameters/OrgHeader"}],"responses":{"101":{"description":"Upgraded to WebSocket."},"401":{"description":"Missing or invalid token."},"402":{"description":"Insufficient balance, subscription required, or a plan without the feature (no_subscription / insufficient_balance / feature_not_in_plan).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"With a Hydra token: the user has no seat in the organization's subscription (no_seat) or is not a member (not_a_member), or the client is not enabled (client_not_enabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded (rate_limit_exceeded), the user's daily cap reached (daily_cap_reached, with `error.resets_at`) or too many calls in flight (concurrency_limit_exceeded). `Retry-After` gives the seconds until the next attempt.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"The subscription has no daily cap (quota_not_configured), the concurrency could not be checked (concurrency_check_failed) or the billing check failed (billing_check_unavailable). Try again later.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/v1/bug-reports":{"post":{"tags":["Konto"],"summary":"Submit bug report","operationId":"createBugReport","description":"Reports a problem or a feature request to support. Accepts an API key or a Hydra token (with X-Grunden-Org). Limit: 10 reports per hour per API key, and 15 per hour per user with a Hydra token.","parameters":[{"$ref":"#/components/parameters/OrgHeader"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["summary"],"properties":{"summary":{"type":"string","minLength":1,"maxLength":200},"detail":{"type":"string","maxLength":8000},"kind":{"type":"string","enum":["bug","feature"]},"context":{"type":"object"}}}}}},"responses":{"201":{"description":"Received."},"400":{"description":"Invalid body."},"401":{"description":"Missing or invalid token."},"403":{"description":"With a Hydra token: the user isn't a member of the organization (not_a_member), the client isn't enabled (client_not_enabled), or access has been disabled for the user in the organization (access_disabled).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Too many reports — see the limit above. Retry-After says when the next one is accepted."}}}},"/v1/audit-log":{"get":{"tags":["Konto"],"summary":"Read the audit log","operationId":"getAuditLog","description":"Events for your own organization, newest first. Provided for the traceability requirements of ISO 27001 and GDPR. Requires an API key (does not accept a Hydra token).","security":[{"bearerAuth":[]}],"parameters":[{"name":"before","in":"query","required":false,"schema":{"type":"string","format":"date-time"},"description":"Pagination: fetch events older than this point in time."},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":1000}},{"name":"window_days","in":"query","required":false,"schema":{"type":"integer","minimum":1},"description":"Limit to the last N days."}],"responses":{"200":{"description":"List of events."},"400":{"description":"Invalid query parameters."}}}},"/v1/balance":{"get":{"tags":["Konto"],"summary":"Read the balance","operationId":"getBalance","description":"The organization's current balance — the same amount the billing page shows. Requires an API key (does not accept a Hydra token); the key determines the organization.\n\nThe balance includes VAT and all credits (trial, campaigns). It can be negative: a request already in progress can take it below zero. New paid requests are rejected with HTTP 402 when the balance is zero or lower. Requests are charged when they finish — streamed ones after the last chunk, batch jobs when the job completes — so the balance normally lags by a few seconds. It can also increase without you doing anything, for example when someone else in the organization tops up. The call counts against the key's rpm limit; fetch the balance at most about once a minute.","security":[{"bearerAuth":[]}],"parameters":[{"name":"org_id","in":"query","required":false,"schema":{"type":"string","format":"uuid"},"description":"Optional. Must be the API key's organization; any other value gives 400 (`org_mismatch`)."}],"responses":{"200":{"description":"The organization's balance.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Balance"},"example":{"object":"balance","org_id":"7f3c2a1e-0000-0000-0000-000000000000","balance":{"amount":"42.517300125","currency":"EUR"}}}}},"400":{"description":"org_id does not match the API key's organization (`org_mismatch`)."},"401":{"description":"Missing or invalid API key."},"404":{"description":"The organization has no wallet (`wallet_not_found`)."}}}},"/v1/account":{"delete":{"tags":["Konto"],"summary":"Delete account","operationId":"deleteAccount","description":"Deletes the account and associated personal data under GDPR Article 17. Irreversible. Requires an API key (does not accept a Hydra token) and an explicit confirmation string in the body.","security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["confirm"],"properties":{"confirm":{"type":"string","enum":["DELETE MY ACCOUNT"],"description":"Must be exactly 'DELETE MY ACCOUNT'. Protection against accidental calls."}}}}}},"responses":{"200":{"description":"Account deleted."},"400":{"description":"The confirmation string is missing or wrong."},"409":{"description":"The account cannot be deleted yet. `code` says why:\n\n- `active_subscription`: the account has an active paid subscription. Cancel the subscription, or delete the account, at grunden.ai/profile — that also cancels it with the payment provider.\n- `sole_owner`: the account is the sole owner of one or more teams that have other members. Make another member owner of each team, or delete the team, and try again. `org_ids` lists the teams.","content":{"application/json":{"schema":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["message","type","code"],"properties":{"message":{"type":"string"},"type":{"type":"string","enum":["invalid_request_error"]},"code":{"type":"string","enum":["active_subscription","sole_owner"]},"org_ids":{"type":"array","items":{"type":"string","format":"uuid"}}}}}},"examples":{"active_subscription":{"summary":"An active paid subscription","value":{"error":{"message":"The account has an active paid subscription. Cancel it, or delete the account, at https://grunden.ai/profile.","type":"invalid_request_error","code":"active_subscription"}}},"sole_owner":{"summary":"Sole owner of a team with other members","value":{"error":{"message":"The account is the sole owner of one or more teams that have other members (org_ids). Make another member owner of each team, or delete the team, at https://grunden.ai, then try again.","type":"invalid_request_error","code":"sole_owner","org_ids":["7f3c2a1e-0000-0000-0000-000000000000"]}}}}}}}}}},"/openapi.json":{"get":{"tags":["Meta"],"summary":"Get this spec","operationId":"getOpenApiSpec","description":"Returns the OpenAPI document. Unauthenticated: a client should be able to generate code before it has a key. The response is cached for one hour and open to all origins.\n\nThe same document is also served at /swagger/v1/swagger.json and /.well-known/openapi.json for tools that look there; they are aliases and are not documented separately. All three take `lang`.","security":[],"parameters":[{"name":"lang","in":"query","required":false,"schema":{"type":"string","enum":["sv","en","fi","nb","da"],"default":"sv"},"description":"The language of the document's descriptions. Omitted gives Swedish. Only text is translated — paths, field names, enum values and examples are the same in all languages."}],"responses":{"200":{"description":"The OpenAPI 3.1 document. The Content-Language header states the language.","content":{"application/json":{"schema":{"type":"object"}}}},"400":{"description":"The language is not supported (invalid_lang).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"webhooks":{"batchJobCompleted":{"post":{"summary":"Async job done","description":"Grunden POSTs to your `webhook_url` when a batch job reaches completed/failed/expired. Two signature headers are sent: (1) `X-Grunden-Signature: sha256=<hex>` (v1) — HMAC-SHA256 over the raw body. (2) `X-Grunden-Signature-V2: t=<unix_ts>,v1=<hex>` (v2, recommended) — HMAC-SHA256 over `v1:<unix_ts>:<raw_body>`; the timestamp protects against replay (reject if `abs(now-t) > 5 min`). Always verify the signature BEFORE processing the payload. Retry: up to 5 attempts with exponential backoff (1m, 5m, 30m, 2h, 12h) — return 2xx within 10 s to acknowledge receipt.","operationId":"batchJobCompleted","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchWebhookPayload"}}}},"responses":{"200":{"description":"Webhook received. We will not retry."},"2XX":{"description":"Any 2xx response counts as acknowledgment."}}}}}}