Skip to content

Inference (LLM & Embeddings) ​

The inference service provides OpenAI-compatible chat completion and embedding endpoints backed by multiple LLM providers. Models are configured in Model Hub and called through the runtime documented below.

Model discovery ​

OpenAI-compatible clients can discover project-scoped LLMs before starting a chat:

http
GET /api/client/v1/models
Authorization: Bearer <api-token>

The response preserves the OpenAI list envelope and Cognipeer's legacy model records:

json
{
  "object": "list",
  "data": [
    {
      "id": "support-fast",
      "object": "model",
      "created": 1785403593,
      "owned_by": "cognipeer",
      "name": "Support Fast",
      "context_length": 131072,
      "max_output_tokens": 16384,
      "supports_image_input": true,
      "supports_reasoning": true,
      "supports_structured_outputs": true,
      "supports_tool_calls": true,
      "architecture": {
        "input_modalities": ["text", "image"],
        "output_modalities": ["text"]
      },
      "cognipeer": {
        "schema_version": "1.0",
        "canonical_model_id": "upstream/model-27b",
        "capabilities": {
          "contextWindow": 131072,
          "maxOutputTokens": 16384,
          "inputModalities": ["text", "image"],
          "outputModalities": ["text"],
          "supportsReasoning": true,
          "supportsStructuredOutputs": true,
          "supportsToolCalls": true
        }
      }
    }
  ],
  "models": []
}

data[].id is the stable public alias and must be sent as the model in inference requests. cognipeer.canonical_model_id is the provider-facing model identifier used for capability correlation; clients must not substitute it for the public alias. Consumers that only implement the OpenAI core schema can ignore all additional fields.

The route admits a token that holds the Models service (read) or the Agents service (read), and what the caller sees follows the service it holds. When the token's owner may read the Agents service, the list also carries the project's active agents as agent:<key> entries (owned_by: "cognipeer-agent", cognipeer: { "kind": "agent", "key": "<key>" }), so an OpenAI-compatible client can pick an agent from its model dropdown. A token with Models only simply sees the models. A token with Agents only gets the agents, models: [] and no providers. A token with neither is 403. A narrowing query (category other than llm, providerKey, providerDriver) lists models only, and agents are not part of the legacy models array. GET /api/client/v1/models/agent:<key> retrieves one agent (404 when it is not an active agent of the project or the token may not read agents; a model id needs Models read, so an Agents-only token gets 403 for it).

Capability values come from the explicit Model Hub profile. Legacy model records without that profile continue to work through normalized fallback fields, so upgrading does not require a database migration.

Calling an agent ​

POST /api/client/v1/chat/completions and POST /api/client/v1/responses also accept model: "agent:<key>" (a bare agent key works when no model has that key). The call runs the agent's published version, so any OpenAI client or SDK can use an agent. The token's owner needs the Agents service for it. A few things differ from a model call: only the last user message is the turn (system messages and sampling parameters are ignored and listed in the X-Cognipeer-Ignored-Params response header), the agent keeps the session (conversation_id or X-Cognipeer-Session-Id), Idempotency-Key makes a retry the same run, and a call still running when the wait window ends answers 202 while the run continues in the background. On /responses, a bare name is resolved as a model of the project first and then as an agent (404 model_not_found when it is neither). A model called on /responses is translated to a chat completion and runs through the same gateway (quota, rate limits, guardrails, routing; usage rows under the route responses), and nothing is stored, so previous_response_id, conversation and background are refused with 400 unsupported_parameter. Details are in OpenAI SDK and the Agents API.

Where inference is observed ​

Operators monitor live inference through Operate → Model Monitoring. The page summarises every connected inference server in four tiles, Total Servers, Active, Errored and Queue Backlog, and each server card carries its own status badge (active, disabled or errored). From here you also wire up new self-hosted endpoints (vLLM, TGI, llama.cpp, Ollama) that don't fit the cloud-provider model.

Model Monitoring with one vLLM server

For per-call inspection — request body, completion, token usage, tool calls — open the Logs tab on a model's detail page in Model Hub, or query Agent Tracing for the full trace timeline.

Chat Completions ​

Endpoint ​

POST /api/client/v1/chat/completions
Authorization: Bearer <api-token>

Request ​

json
{
  "model": "gpt-4",
  "messages": [
    { "role": "system", "content": "You are a helpful assistant." },
    { "role": "user", "content": "What is the capital of France?" }
  ],
  "temperature": 0.7,
  "max_tokens": 1000,
  "stream": false
}

Response (Non-Streaming) ​

json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "model": "gpt-4",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "The capital of France is Paris." },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 8,
    "total_tokens": 33
  },
  "request_id": "req_abc123"
}

Streaming ​

Set "stream": true to receive Server-Sent Events:

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"delta":{"content":"The"},"index":0}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"delta":{"content":" capital"},"index":0}]}

data: [DONE]

Embeddings ​

Endpoint ​

POST /api/client/v1/embeddings
Authorization: Bearer <api-token>

Request ​

json
{
  "model": "text-embedding-ada-002",
  "input": "Hello world"
}

Response ​

json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0023, -0.0092, ...]
    }
  ],
  "model": "text-embedding-ada-002",
  "usage": {
    "prompt_tokens": 2,
    "total_tokens": 2
  }
}

Processing Pipeline ​

Request → requireApiToken()
       → Resolve model by key
       → Validate model category (LLM vs embedding)
       → Guardrail check (if configured)
       → Semantic cache lookup (if enabled)
       → Build provider runtime (via runtimePool)
       → Execute with withResilience()
       → Convert to OpenAI format
       → Log usage (fireAndForget)
       → Return response

Features ​

Semantic Caching ​

When enabled on a model, similar queries return cached responses:

  • Cache lookup before provider call
  • Cache store after successful response
  • Configurable similarity threshold

Guardrail Integration ​

Models can have guardrails attached that evaluate input before sending to the provider:

typescript
// If guardrail blocks the request
throw new GuardrailBlockError(guardrailKey, action, findings);

Usage Logging ​

Every request is logged asynchronously (via fireAndForget):

  • Token counts (prompt, completion, total)
  • Latency (ms)
  • Model and provider info
  • Tool call metadata
  • Request ID for correlation

Output limits ​

One output limit travels from the request to the provider:

  • A caller's max_tokens (max_completion_tokens, max_output_tokens) is a hard cap. It is never raised, and a thinking budget is fitted under it.
  • Without one, the model's Default max tokens applies (see Model Hub). When that is blank too, no limit is sent and the provider's own default applies, except on the anthropic driver, whose Messages API requires one: it gets the model's maximum, which is the model's Maximum output tokens, else the maximum Cognipeer knows for recent Claude models by their model ID, else 8,192. A non-streaming call's default stays at or below 21,333.
  • A model's own limit (not a caller's) is raised when reasoning needs room for its thinking, up to the model's maximum.
  • A call that stops on the limit before any answer (no visible text and no tool call) ends as 422 with code output_token_limit_exceeded. The tokens the provider spent are still recorded and count against budgets. A call that stops on the limit with an answer is delivered with finish_reason: "length".
  • When the provider itself ends a call in an error finish (for example malformed_function_call), the call ends as 502 with type: "server_error" and the provider's reason as the code, instead of an empty success.

Prompt caching ​

For Claude models (Anthropic, Bedrock Claude, Vertex Claude) the gateway marks the stable start of a request for the provider's prompt cache, so repeated input bills at the cache-read price. It is on by default for Claude and can be switched per model; see Model Hub. Cache markers a client sends itself on /chat/completions and /v1/messages are kept whether the switch is on or off. Providers that cache by themselves need nothing.

Usage and cost ​

Every metered call (gateway, agents, trace ingest, batch, OCR, evaluations, guardrail judge and decision calls) reports usage the same way:

  • inputTokens is the whole prompt: uncached, cache read and cache write together. cachedInputTokens (cache read) and cachedWriteTokens (cache write) are parts of it, never added on top.
  • outputTokens includes reasoning tokens; reasoningTokens is a part of it. totalTokens is input plus output.
  • Cost is uncached input at the input price, cache reads at the cache-read price, cache writes at the cache-write price, and output at the output price. A blank or 0 cache price bills at the input price. For a Claude model with no cache-write price, writes bill at 1.25 times the input price and the cost is flagged as assumed.
  • A stream that ends without provider usage (a client cancel, a guardrail block, an upstream that sends none) is booked with an estimate of about one token per four characters, and its log row is marked usage_estimated.
  • On the OpenAI wire, cache reads are prompt_tokens_details.cached_tokens and cache writes prompt_tokens_details.cache_write_tokens.

Set the cache prices on the model, or use Fill from catalog, so cost reports show the savings.

Provider Resilience ​

External provider calls are wrapped with:

  • Retry — Exponential backoff for transient failures
  • Circuit breaker — Automatic rejection when provider is down
  • Runtime pooling — Cached SDK clients for performance

Model Configuration ​

Models are configured in the dashboard with:

FieldDescription
keyUnique model identifier per tenant
categoryllm or embedding
providerKeyWhich provider config to use
modelIdProvider-specific model name
capabilitiesContext/output limits, modalities, reasoning, structured output, and tool-call support
pricingCost per 1M tokens (input/output)
overridesDefault parameters (temperature, maxTokens, etc.)

Error Handling ​

StatusMeaning
400Missing model key or invalid request body
422output_token_limit_exceeded: the model used its whole output limit before answering, often a reasoning model; raise the limit or lower the reasoning effort
401Invalid or missing API token
429Quota, rate limit, or budget exceeded
500Provider/internal error (includes unresolved model, category mismatch, and circuit-breaker-open)

Studio · Pulse · Console · Agent SDK and more — the Cognipeer documentation hub · Contact Support