> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.agentrouter.to/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.agentrouter.to/_mcp/server.

# Chat Completion

Runs an OpenAI-compatible message list against a selected chat model.

```http
POST /domains/models/capabilities/chat-complete/execute
```

Call [List All Models](/domains/models/list-all-models) first. The exact returned `models[].id` becomes this endpoint's `model` value.

## Request

#### TypeScript SDK

```ts
import { AgentRouterClient } from "@agentrouter/agentrouter";

const client = new AgentRouterClient({
  apiKey: process.env.AGENTIC_API_KEY,
});

const result = await client.models.chat.complete.execute(
  {
    model: "openai/gpt-4.1-nano",
    messages: [
      {
        role: "system",
        content: "You write concise landing-page copy.",
      },
      {
        role: "user",
        content: "Write a one-line hero for an AI course builder.",
      },
    ],
    max_tokens: 120,
    temperature: 0.2,
  },
  { allowFallback: true },
);

console.log(result.completionText);
console.log(result.creditsCharged);
```

#### cURL

```bash
curl -X POST \
  "https://api.agentrouter.to/api/agentic-api/domains/models/capabilities/chat-complete/execute" \
  -H "Authorization: Bearer $AGENTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4.1-nano",
    "messages": [
      {
        "role": "user",
        "content": "Write a one-line hero for an AI course builder."
      }
    ],
    "max_tokens": 120,
    "temperature": 0.2,
    "routeKey": "models.chat.complete.openrouter.mpp",
    "allowFallback": false
  }'
```

### Capability input

| Field         | Type      | Required | Description                                                                 |
| ------------- | --------- | -------- | --------------------------------------------------------------------------- |
| `model`       | string    | yes      | Exact live model ID. For OpenRouter, use an ID returned by List All Models. |
| `messages`    | object\[] | yes      | OpenAI-compatible messages with `role` and `content`.                       |
| `max_tokens`  | integer   | no       | Maximum generated tokens. Must be at least `1`.                             |
| `temperature` | number    | no       | Sampling temperature from `0` to `2`.                                       |
| `top_p`       | number    | no       | Nucleus sampling value from `0` to `1`.                                     |
| `stop`        | string    | no       | Stop sequence. Support can vary by provider and model.                      |
| `stream`      | boolean   | no       | Request streaming when the selected route supports it.                      |

Check the selected catalog entry's `supported_parameters` before sending optional model fields.

### Routing controls

Routing controls are the SDK method's second argument. With raw HTTP they are fields in the same JSON body.

| Field           | Type    | Required | Description                                                                  |
| --------------- | ------- | -------- | ---------------------------------------------------------------------------- |
| `routeKey`      | string  | no       | Pin a route such as `models.chat.complete.openrouter.mpp`.                   |
| `provider`      | string  | no       | Provider hint such as `openrouter`, `deepseek`, or `groq`.                   |
| `allowFallback` | boolean | no       | Let AgentRouter use another compatible route when the preferred route fails. |

## Response

```json
{
  "success": true,
  "completionText": "Build your course in minutes, not months.",
  "model": "openai/gpt-4.1-nano",
  "provider": "openrouter",
  "routeKey": "models.chat.complete.openrouter.mpp",
  "fallbackUsed": false,
  "finishReason": "stop",
  "usage": {
    "promptTokens": 31,
    "completionTokens": 10,
    "totalTokens": 41
  },
  "creditsCharged": 1
}
```

The token counts and charge above are illustrative. Always use the values returned by the live response.

### Response fields

| Field            | Type    | Description                                            |
| ---------------- | ------- | ------------------------------------------------------ |
| `completionText` | string  | Generated text. This is the primary result.            |
| `model`          | string  | Model that handled the request.                        |
| `provider`       | string  | Provider selected for execution.                       |
| `routeKey`       | string  | Concrete route used.                                   |
| `fallbackUsed`   | boolean | Whether AgentRouter moved to a fallback route.         |
| `finishReason`   | string  | Why generation stopped when published by the provider. |
| `usage`          | object  | Provider token usage when available.                   |
| `creditsCharged` | number  | Authoritative credits debited for this request.        |

## Common scenarios

The endpoint always performs model inference. Your prompt and messages define the job.

| Scenario    | Input pattern                                                                                   |
| ----------- | ----------------------------------------------------------------------------------------------- |
| Sales page  | System message sets voice and structure; user message contains offer, audience, proof, and CTA. |
| Course plan | Ask for a JSON schema or structured outline in the user message.                                |
| HTML        | Ask for HTML/CSS and state whether markdown fences are allowed.                                 |
| Email draft | Provide recipient context and desired action. This drafts text; it does not send email.         |
| Extraction  | State the output schema and ask for JSON only.                                                  |

## Pricing

Catalog rates are estimates per one million input and output tokens. The paid MPP route obtains a request-specific quote. `creditsCharged` is the final amount; do not calculate the debit from the catalog alone.

## Inspect the exact route contract

```ts
const context = await client.catalog.routes.context(
  "models.chat.complete.openrouter.mpp",
);

console.log(context.execute?.requiredFields);
console.log(context.execute?.optionalFields);
console.log(context.execute?.fields);
```

> **Note**
>
> The capability-level contract is currently partial. Route context is the machine-readable source of truth for a pinned model route.

## Errors

| Status         | Meaning                                                    | Fix                                                     |
| -------------- | ---------------------------------------------------------- | ------------------------------------------------------- |
| `400` or `422` | Missing field, invalid parameter, or unsupported parameter | Verify `model`, `messages`, and the route's context.    |
| `401`          | Missing or invalid AgentRouter API key                     | Send `Authorization: Bearer aak_...`.                   |
| `402`          | Insufficient AgentRouter credits or payment-route funding  | Add funds, then retry the same request.                 |
| `404`          | Model or pinned route is unavailable                       | Refresh List All Models or remove the stale `routeKey`. |
| `429`          | Provider or gateway rate limit                             | Retry with exponential backoff.                         |