Skip to main content

REST API v1

AION Agents exposes a suite of RESTful APIs under the /v1 namespace designed to allow the integration of the agent into any application (web, mobile, backend-to-backend).


Authentication​

The endpoints under /v1/* support two distinct authentication modes depending on the resource type:

1. API Key (Programmatic Server-to-Server)​

Required for managing conversations (/v1/conversations/*) and their related files (/v1/conversations/*/files).

  • Header:
    X-API-Key: aion_..._...
    (or via Authorization: Bearer aion_..._...)
  • Each key belongs to a user, who creates it from chat-ui → Settings → API keys (see User API keys and API keys). The key acts as its owner: same conversations, same allowed profiles, never the admin role.
  • Keys have scopes: chat, conversations:read, conversations:write, files:read, files:write. Access is deny by default: an endpoint that does not explicitly accept API keys answers 403 api_key_not_allowed; a key without the endpoint's scope gets 403 missing_scope. The endpoint-to-scope map is in API keys → Scopes.
  • Keys are validated even when AION_CHAT_PASSWORD_AUTH=0.

2. Chat Authentication (User and BFF)​

Required for chat/streaming interactions (/v1/chat/*), the OpenAI-compatible facade (/v1/models, /v1/chat/completions), MCP integrations (/v1/integrations/*), Query Memory (/v1/query-memory/*) and Navigation Memory (/v1/navigation-memory/*). Accepts one of the following authorization methods:

  • Bearer Token Chat: Opaque HMAC token generated by /auth/login (typically used by the Chat UI).
    Authorization: Bearer <token_hmac>
    (for SSE endpoints like EventSource, which do not support custom headers, it is possible to pass the token in the query string: ?access_token=<token_hmac>)
  • BFF Internal Secret: Server-to-server header for a trusted backend-for-frontend (never a browser). It is the only authenticated mode in which X-AION-User-Id selects the user, and it grants no admin role.
    X-AION-Chat-Ui-Secret: <shared_secret>
    X-AION-User-Id: <user>
  • API Key: An API Key with the chat scope (chat, streaming, /v1/models, /v1/chat/completions). The key acts as its owner: user/user_id in the body and X-AION-User-Id are ignored, and the owner's identifier is used. MCP integrations, Query Memory and Navigation Memory do not accept API keys (403 api_key_not_allowed).

Conversation ownership​

Every endpoint that reads or writes a conversation, session, step or file checks that its owner is the caller's effective identity (src/api/ownership.py). This applies to admins too. A conversation owned by someone else answers 404 (Conversation not found), so its existence is not revealed. Sessions without a DB row yet (e.g. files uploaded before the first message) are bound to their first writer via a .aion_owner marker.

  • Open Mode: If AION_CHAT_PASSWORD_AUTH=0 in the backend, read-only operations are no-op (anonymous identity allowed). Write operations will still require a verified identity.

Management of profile and project Parameters​

The customization of the agent's behavior and the isolation of data are based on two fundamental concepts:

Profile (profile)​

Identifies the agent's configuration (LLM model, system prompt, set of enabled MCP tools).

  • Conversation Creation (POST /v1/conversations): Sent in the JSON body as "profile" or "profile_slug". Permanently associates the session with that profile.
  • Chat and Streaming (POST /v1/chat/stream, POST /v1/chat/prepare): Sent in the JSON body as "profile", "profile_slug" or "profile_name". If omitted, the default value is aion_std.
  • OpenAI-compatible (POST /v1/chat/completions): The model field is the profile slug. See OpenAI-compatible facade.
  • Query Memory (GET/POST /v1/query-memory/projects): Passed as profile query parameter to filter or associate projects.

Project (project)​

Identifies the SQL QueryMemory slot to share and catalog pre-validated queries or user preferences.

  • Chat and Streaming (POST /v1/chat/stream): Sent in the JSON body as "sql_query_project" (e.g. "default", "vendite", "tecnico").
  • Query Memory API (/v1/query-memory/*): Passed as project query parameter (e.g. ?project=vendite).
  • Navigation Memory API (/v1/navigation-memory/*): Passed as project query parameter or inside the JSON body as "project" for upserts.

SQL Project Resolution Flow​

When a message is sent in the chat, the active project is determined with the following priority:

  1. Explicit request: The value of "sql_query_project" present in the body of POST /v1/chat/stream.
  2. Conversation metadata: The value stored in the Conversation table (under metadata_json -> sql_query_project) generated at the previous turn or at creation.
  3. System fallback: The value of the environment variable AION_SQL_QM_DEFAULT_PROJECT set on the server (default: "default").

OpenAI-compatible facade​

Apps that already speak the OpenAI Chat Completions API (LibreChat, Open WebUI, Continue, and similar) can point their base URL at AION and use each profile as a model. The agent still runs with that profile's system prompt and MCP tools. A tools array on the request is ignored: tool execution stays inside AION, and the client only receives the assistant text.

Set the OpenAI base URL to the API origin plus /v1:

DeployBase URL
Local APIhttp://localhost:8001/v1
Docker (Caddy strips /api)https://${DOMAIN}/api/v1

Authentication is the same chat auth as POST /v1/chat: Authorization: Bearer with a chat token or an aion_... API key. When AION_CHAT_PASSWORD_AUTH=0, the endpoints are open.

List models​

GET /v1/models (Requires Chat Auth)

Each allowed profile is one model. id is the profile slug (the value clients must send back as model). name is the profile display name.

{
"object": "list",
"data": [
{
"id": "aion_std",
"object": "model",
"created": 0,
"owned_by": "aion",
"name": "AION Standard"
}
]
}

GET /v1/models/{model_id} returns one card. Unknown slugs are 404 model_not_found (no fallback to the default profile). A profile that exists but is outside the caller's allow-list is 403 model_not_allowed.

Chat completions​

POST /v1/chat/completions (Requires Chat Auth)

{
"model": "aion_std",
"messages": [
{"role": "user", "content": "What is the status of the Prometheus servers?"}
],
"stream": false
}
FieldMeaning
modelProfile slug. Optional profile@llm_provider_slug selects the LLM provider for the turn. Header X-AION-Llm-Provider overrides the suffix.
messagesStandard chat messages. The last user text is the turn. Content may be a string or an array of {type, text} parts; non-text parts are dropped.
streamfalse returns one chat.completion object. true returns SSE chunks (data: {...} then data: [DONE]).
toolsIgnored. The profile's tools run inside the agent.
nOnly 1 (or omitted).
metadata.aion_conversation_idOptional session id. Same values are accepted on the X-AION-Conversation-Id header.

Sampling fields (temperature, max_tokens, and the rest) are ignored. Generation limits stay on AION runtime settings.

Thinking is off on every completion, the same as the chat-ui Thinking toggle set to off (reasoning_effort=off, enable_thinking=false). Clients that cannot send extra fields get that behavior with a normal messages body. A custom field is possible later; it is not read today.

Session. Clients usually resend the whole transcript every call. AION keeps short-term memory on one session so tools and files survive the next turn:

  1. X-AION-Conversation-Id or metadata.aion_conversation_id when the client can set them.
  2. Otherwise an id derived from the caller, the model, and the first user message. Two new chats that open with the same sentence share a session; send an explicit id to avoid that.

The first turn of an empty session also forwards client system / developer messages and any earlier transcript. Later turns send only the newest user message, because the session already holds the history. The response repeats the session id in the X-AION-Conversation-Id header and in aion_conversation_id.

stream: true forwards assistant text as delta.content. Profile reasoning, when present, is delta.reasoning_content. Tool activity is an SSE comment (: aion-tool) so proxies stay open; it is not an OpenAI tool_calls payload, because the client is not expected to execute tools.

The turn budget is AION_OPENAI_COMPAT_TIMEOUT_SEC (default 300). A timeout is 504.


Conversations Management​

Create Conversation​

POST /v1/conversations (Requires conversations:write)

Request Body:

{
"profile": "aion_std",
"title": "Infrastructure Analysis Q2",
"metadata": {"source": "web-portal"},
"tags": ["audit", "q2"]
}

user_id in the body is ignored: the conversation is always owned by the key's owner. The profile must be allowed for the owner (403 profile_not_allowed otherwise).

Response (201 Created):

{
"id": "01907a5e-5df3-7b9a-9f44-3c1d4d2e7f3a",
"tenant_id": "default",
"user_id": "jane.doe",
"profile_slug": "aion_std",
"title": "Infrastructure Analysis Q2",
"message_count": 0,
"metadata": {"source": "web-portal"},
"tags": ["audit", "q2"]
}

List Conversations​

GET /v1/conversations (Requires conversations:read)

Query Parameters:

  • user_id (optional): Filter by user ID.
  • limit (optional): Default 20, max 100.

Response (200 OK):

{
"data": [
{
"id": "01907a5e-5df3-7b9a-9f44-3c1d4d2e7f3a",
"user_id": "jane.doe",
"profile_slug": "aion_std",
"title": "Infrastructure Analysis Q2",
"message_count": 5,
"metadata": {"source": "web-portal"},
"tags": ["audit", "q2"]
}
]
}

Get Conversation Details​

GET /v1/conversations/{conversation_id} (Requires conversations:read)

Response (200 OK): Identical to the structure of the creation response. Returns 404 Not Found if the conversation does not belong to the key's owner or does not exist.

Modify Conversation​

PATCH /v1/conversations/{conversation_id} (Requires conversations:write)

Allows partial modification of the session information.

Request Body (All fields optional):

{
"title": "New Modified Title",
"tags": ["audit", "q2", "updated"],
"metadata": {"source": "web-portal", "edited": true}
}

Delete/Archive Conversation​

DELETE /v1/conversations/{conversation_id} (Requires conversations:write)

Performs a logical deletion (soft-delete by setting archived_at) and releases the allocated MCP Stdio connections in memory for that specific session.


Retrieve Conversation Messages​

GET /v1/conversations/{conversation_id}/messages (Requires conversations:read)

Query Parameters:

  • limit (optional): Default 50, max 1000.
  • include_internal (optional): Default false. If set to true, it also includes the technical messages of execution of the individual tools and the raw plans of the orchestrator, otherwise it only returns the messages visible to the end user (roles user and assistant).

Response (200 OK):

{
"data": [
{
"id": "01907a5e-5df3-7b9a-9f44-...",
"role": "user",
"content": "What is the status of the database?",
"reasoning": null,
"tool_name": null,
"tool_call_id": null,
"created_at": "2026-06-22T15:53:31Z"
},
{
"id": "01907a5e-5df3-7b9a-9f45-...",
"role": "assistant",
"content": "The database responds correctly with latency < 2ms.",
"reasoning": "I checked the logs using the sql_query tool...",
"tool_name": null,
"tool_call_id": null,
"created_at": "2026-06-22T15:53:33Z"
}
]
}

Chat and Streaming​

Agent Pre-heating (Warming Cache)​

POST /v1/chat/prepare (Requires Chat Auth)

Preemptively starts the MCP servers configured for the profile and warms the agent's cache. Useful to invoke when the client opens to avoid cold-start on the first message.

Request Body:

{
"conversation_id": "01907a5e-...",
"profile": "aion_std",
"user_id": "jane.doe",
"agent_mode": "normal"
}

Response (200 OK):

{
"ok": true,
"status": "warming",
"conversation_id": "01907a5e-...",
"mcp_errors": [],
"has_errors": false
}

Status​

GET /v1/chat/prepare/status (Requires Chat Auth)

Performs polling of the loading status of MCPs.

Query Parameters:

  • conversation_id: Conversation ID.
  • profile: Profile name/slug.
  • user_id (optional): User ID.

Sync Chat (JSON)​

POST /v1/chat (Requires Chat Auth)

Sends a message and waits for the full agent reply as a single JSON object. Intended for automation clients (n8n, scripts) that cannot consume SSE. See also N8N Integration.

Request Body:

{
"message": "What is the status of the Prometheus servers?",
"profile": "aion_std",
"conversation_id": null,
"user_id": "n8n",
"message_source": "internal_trigger",
"timeout_seconds": 300
}
FieldDefaultNotes
message—Required
profile / profile_slug / profile_nameaion_stdProfile slug
conversation_id / session_idauto UUIDOmit to create a new conversation
message_sourceinternal_triggerUse user_input for human turns
timeout_seconds300Range 1–3600; 504 on timeout

Response (200 OK):

{
"text": "The Prometheus servers are active...",
"conversation_id": "01907a5e-...",
"session_id": "01907a5e-...",
"profile": "aion_std",
"success": true,
"charts": []
}

Chat Stream (SSE)​

POST /v1/chat/stream (Requires Chat Auth)

Sends a message to the agent and receives a response in real time via Server-Sent Events (SSE).

Request Body:

{
"conversation_id": "01907a5e-...",
"message": "What is the status of the Prometheus servers?",
"attachments": [],
"profile": "aion_std",
"reasoning_effort": "medium",
"thinking_enabled": true,
"web_search_enabled": false,
"sql_query_project": "default"
}

Response: text/event-stream. Every frame event: message carries a JSON event with a type (turn_started, token, tool_event, final, ...). Event types, ordering, error frames, reconnect and the end-of-turn rules are in Chat stream events (SSE).

GET /v1/chat/stream/reconnect/{conversation_id} (scope chat) re-attaches to the turn in progress and replays its events from the start.

Stop Streaming​

POST /v1/chat/stop (Requires Chat Auth)

Sends a cancellation signal to immediately stop the generation of the response in progress.

Query Parameters:

  • conversation_id: ID of the conversation to stop.

File Management (Attachments)​

Upload File​

POST /v1/conversations/{conversation_id}/files (Requires files:write)

Allows multipart/form-data sending of files to be analyzed. Returns an array of attachments saved in the uploads/ folder of the session. For legacy .doc uploads, the API host may also set conversion metadata (LibreOffice on the API process — see Office and legacy Word):

{
"attachments": [
{
"relative_path": "uploads/01907a5e_report.doc",
"original_relative_path": "uploads/report.doc",
"name": "01907a5e_report.doc",
"original_name": "report.doc",
"size_bytes": 18780160,
"mime": "application/msword",
"legacy_word": true,
"conversion_status": "ok",
"converted_docx_path": "derived/converted/report.docx"
}
]
}

Plain text upload (no conversion):

{
"attachments": [
{
"relative_path": "uploads/01907a5e_log.txt",
"original_relative_path": "uploads/log.txt",
"name": "01907a5e_log.txt",
"original_name": "log.txt",
"size_bytes": 1024,
"mime": "text/plain"
}
]
}

List Session Files​

GET /v1/conversations/{conversation_id}/files (Requires files:read)

Returns the list of files present in the session.

Download File​

Downloads of files associated with the session do not go through the /v1/conversations/... endpoints but through the legacy chat download endpoint:

GET /sessions/{session_id}/download (Requires Chat Auth)

Query Parameters:

  • relative_path: The relative path of the file (e.g. uploads/01907a5e_log.txt or workspace/report.md).

Voice dictation​

Used by the chat-ui microphone button. The recording is transcribed in-process and discarded; it never becomes a session file.

GET /v1/voice/status (Requires Chat Auth or chat scope) → {"enabled": true, "mode": "local", "max_duration_sec": 300, "max_bytes": 10485760}

POST /v1/voice/transcribe (Requires Chat Auth or chat scope), multipart:

  • file: the recording (webm/ogg/mp4/wav/mp3);
  • language (optional): ISO code, empty = AION_STT_LANGUAGE, auto = detect.

Returns {"text": "...", "language": "it", "duration_sec": 4.2}. Errors: 413 too_large, 422 too_long|not_audio|empty, 503 voice_input_disabled|engine_failed|decoder_unavailable. See Speech-to-text.


User API keys​

Personal keys are managed by the user with a chat token (Authorization: Bearer <chat token>). API keys calling these endpoints get 403 (a key cannot create keys). Full design in API keys.

EndpointPurpose
GET /v1/me/api-keys{policy: {enabled, max_keys, active_count, max_ttl_days, allowed_scopes}, keys: [...]}; each key has status active, expired or revoked
POST /v1/me/api-keysBody {name, scopes, expires_in_days} (expiration mandatory, ≤ the user's max). 201 with the key object plus key (shown only once). Errors: 403 api_keys_disabled, 409 api_key_quota_exceeded, 422 invalid_scopes, 422 invalid_expiration
DELETE /v1/me/api-keys/{id}Soft revoke (revoked_at); 404 if the key is not the caller's

The per-user policy (can_create_api_keys, max_api_keys, api_key_max_ttl_days) is set by the admin via POST /admin/users / PUT /admin/users/{id}. There are no /admin/api-keys endpoints.

POST /admin/users creates password accounts only: with an SSO login mode active it returns 409 {"code": "sso_active_user_creation_disabled"}. Who can get an account at first SSO sign-in is set with GET/PUT /admin/auth/signup-policy (see SSO migration).


Admin API (selected)​

Admin routes live under /admin/* and require Bearer token with admin role (API keys are always rejected). Full surface is used by admin-ui. Selected endpoints relevant to this release:

Probe LLM provider​

POST /admin/llm-providers/probe (Admin auth)

Tests connectivity to an OpenAI-compatible endpoint and returns discovered model ids plus optional per-model hints (context window, suggested max_chat_tokens).

Request body:

{
"provider": "openai",
"api_base_url": "https://api.openai.com/v1",
"api_key": "sk-..."
}

Supported provider values include openai, anthropic, gemini, ollama, vllm. Implementation: src/runtime/llm_probe.py (SSRF-safe URL validation, GET /v1/models, LiteLLM catalog fallback).

Response (example):

{
"ok": true,
"base_url": "https://api.openai.com/v1",
"latency_ms": 142,
"models": [{"id": "gpt-4o", "hints": {"suggested_max_chat_tokens": 16384}}],
"warning": null
}

Used by admin-ui First setup (/first-setup) and Settings (/settings) for LLM, embeddings, and remote OCR configuration.


API contract and deprecation​

The routes below are a stable contract: external integrations (such as AION SRE) can rely on them across releases. The list lives in src/api/contract.py (CONTRACT_ROUTES).

MethodPathScopeResponse
POST/v1/conversationsconversations:writeJSON
POST/v1/chat/streamchatSSE
GET/v1/chat/stream/reconnect/{conversation_id}chatSSE
POST/v1/chat/stopchatJSON
GET/chat-ui/conversations/{conv_id}/stream-statusconversations:readJSON
GET/chat-ui/conversations/{conv_id}/messagesconversations:readJSON
POST/chat-ui/conversations/{conv_id}/messages/{message_id}/rateconversations:writeJSON
GET/sessions/{session_id}/chartschatJSON
GET/v1/conversations/{conversation_id}/stepsconversations:readJSON
GET/profileschatJSON

GET /sessions/{session_id}/charts is part of the contract and is not covered by the Sunset sent on the other /sessions/* routes.

Guarantees​

  • Changes within a release line are additive: new routes, new response fields, new SSE event types, new optional request fields.
  • Clients must ignore unknown fields and unknown SSE event types.
  • Every contract route declares its response schema in OpenAPI. CI compares it with the committed snapshot docs/api-and-runtime/contract/openapi-contract.json (src/test/test_openapi_contract.py); an incompatible change fails the build. After an additive change, regenerate the snapshot with python scripts/export_openapi.py --update and commit it.

Deprecation rule​

Removing or changing a field or a route of the contract requires:

  1. Notice of at least one minor release. The route is marked deprecated in OpenAPI and every response carries the headers Deprecation: true, Sunset: <HTTP-date> and, when there is a replacement, Link: <successor>; rel="successor-version" (deprecated_route() in src/api/deprecation.py).
  2. A CHANGELOG entry in the release that introduces the deprecation.
  3. Removal only in a release published after the Sunset date. Until then the CI check keeps reporting the change as breaking.

OpenAPI schema​

  • Every GitHub release has the full schema attached as openapi.json (python scripts/export_openapi.py --full openapi.json).
  • A running backend serves it at /openapi.json when AION_API_DOCS_ENABLED=1 (default in code; set to 0 in the Docker compose files).

Common Errors and Rate Limiting​

Rate Limiting​

The endpoints are protected by rate limiting. In case the set thresholds are exceeded, the server returns 429 Too Many Requests. Response Headers:

  • X-RateLimit-Limit: Maximum limit allowed in the time window.
  • X-RateLimit-Remaining: Remaining requests in the current window.
  • X-RateLimit-Reset: UTC timestamp of the counter reset.

Status Codes Table​

CodeMeaningTypical Cause / Resolution
401UnauthorizedAPI Key or Bearer Token missing, expired or invalid. For keys, detail is one of api_key_invalid_format, api_key_invalid, api_key_revoked, api_key_expired, api_key_owner_disabled.
403ForbiddenAPI Key used on an endpoint that does not accept keys (api_key_not_allowed), key lacking the endpoint's scope (missing_scope), profile not allowed for the key's owner (profile_not_allowed), or user not associated with the SQL project.
404Not FoundConversation, file or project does not exist or does not belong to the tenant.
429Too Many RequestsExceeded the limit of allowed calls per minute.
503Service UnavailableThe unified SQLite database or Redis are offline. If the error indicates Unified DB disabled, you need to remove AION_UNIFIED_DB=0 from the configurations to enable the v1 APIs.