> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sketricgen.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime API

> Use the SketricGen Runtime API to execute existing AI agents, stream responses, continue conversations, attach files, and resume human input.

## Overview

The SketricGen Runtime API executes agents that you created in SketricGen. Use it to send a message, continue a conversation, attach previously uploaded files, stream the response, or resume a Human Input pause.

The customer-facing Runtime API intentionally exposes one programmatic execution endpoint. Teamspace and agent management belong to the [Admin API](https://docs.sketricgen.ai/dev-guide/admin-api.md), while conversational AI management belongs to the [SketricGen MCP server](https://docs.sketricgen.ai/dev-guide/mcp-connect.md).

**Base URL:**
`https://chat-v2.sketricgen.ai/api/v1`

## When to use the Runtime API

Use the Runtime API when you want to call an existing SketricGen agent from your own product, backend, workflow runner, or custom UI.

Common use cases:

* Run AI Workforce agents from your own application
* Add SketricGen agents to an internal product experience
* Build a custom chat UI instead of using the hosted website widget
* Trigger an agent from backend jobs or server-side automations
* Keep conversation identity aligned with users or contacts in your own system

If you only need a copy-paste website chat bubble or iframe, use [Deploy an AI Chatbot to a Custom Website](https://docs.sketricgen.ai/deploy/custom-website.md) instead.

## Authentication

Every Runtime API request requires a Teamspace API key with **Run agents** access. Current keys begin with `sk_api_`.

Create it from **Teamspace settings → API keys → Create key**. Enable **Run agents**, choose the narrowest Project and agent scope that supports the integration, and copy the plaintext key when it is shown once. You can also enable **Manage resources** if the same credential needs Admin API access.

**Required Header:**

```http theme={null}
API-KEY: sk_api_YOUR_KEY
```

The key must have **Run agents** access. A key with only **Manage resources** access cannot execute agents through the Runtime API.

## Quick start

```bash theme={null}
export SKETRICGEN_RUNTIME_API_KEY="sk_api_YOUR_KEY"

curl -X POST "https://chat-v2.sketricgen.ai/api/v1/run-workflow" \
  -H "API-KEY: $SKETRICGEN_RUNTIME_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agent_abc123xyz",
    "user_input": "Summarize the latest product feedback.",
    "stream": false
  }'
```

Keep the Runtime API key on a server or in a secret manager. Do not call the Runtime API directly from public browser code.

## Endpoints

### Run Workflow

**POST** `/run-workflow`
Execute an AI workflow using a specified agent to generate intelligent responses based on user input.

### Request Headers

| Header | Type | Required | Description |
| - | - | - | - |
| `API-KEY` | string | Yes | Teamspace API key with **Run agents** access, beginning with `sk_api_` |
| `Content-Type` | string | Yes | Must be `application/json` |

### Request Body

| Field | Type | Required | Description | Constraints |
| - | - | - | - | - |
| `agent_id` | string | Yes | Unique identifier for the AI agent to use | - |
| `user_input` | string | Conditional | The user's message or query to process | Max 10,000 characters. Required unless you send `hitl_resume` or `assets` |
| `conversation_id` | string | No | ID of existing conversation to continue | If omitted, creates new conversation |
| `contact_id` | string | No | External identifier to associate conversation with a contact | Max 255 characters |
| `assets` | array | No | Previously uploaded asset file IDs to include with the message | Array of file ID strings |
| `stream` | boolean | No | Enable real-time response streaming | Default: `false` |
| `disable_conversation_history` | boolean | No | Skip prior messages when processing this turn | Default: `false` |
| `enable_hitl` | boolean | No | Allow Human Input and approval tools to pause this request | Default: `false`; include it again when resuming |
| `hitl_resume` | object | No | Decisions that resume a paused HITL request | Requires `conversation_id`; omit `user_input` |

### Example Request

```json theme={null}
{
	"agent_id": "agent_abc123xyz",
	"user_input": "Help me analyze this quarterly sales data",
	"conversation_id": "conv_def456ghi",
	"contact_id": "customer_12345",
	"stream": false
}
```

## Contact ID and User Grouping

Use `contact_id` when your product already knows who the end user or contact is. Conversations sent with the same `agent_id` and `contact_id` are grouped under the same contact in SketricGen.

This is useful when you want to:

* See all conversations from one customer or app user together
* Continue reviewing a user's history across multiple sessions
* Connect SketricGen conversations back to your CRM, database, or product user record
* Keep a consistent mapping between SketricGen conversations and your own user records

Use a stable internal ID, UUID, or hashed value. Do not send emails, phone numbers, names, or other directly identifiable personal data as the contact ID.

Good examples:

```text theme={null}
customer_12345
user_uuid_550e8400-e29b-41d4-a716-446655440000
customer_hash_abc123def456
```

Avoid:

```text theme={null}
john.doe@email.com
555-123-4567
John Doe
```

### Identity Fields by Deployment Method

`contact_id` is a Runtime API field. Browser embeds do not accept a caller-supplied contact identifier:

| Deployment method | Agent identifier | Contact identifier |
| - | - | - |
| Runtime API | `agent_id` in the JSON body | `contact_id` in the JSON body |
| Chat bubble widget | `data-agent-id` on the script tag | Assigned by SketricGen |
| Floating pill widget | `data-agent-id` plus `data-layout="floating"` | Assigned by SketricGen |
| Inline iframe | Agent ID in `/iframe-widget/YOUR_AGENT_ID` | Assigned by SketricGen |
| Fullscreen link | Agent ID in `/fullscreen-widget/YOUR_AGENT_ID` | Assigned by SketricGen |

API example:

```json theme={null}
{
	"agent_id": "agent_abc123xyz",
	"user_input": "What's my order status?",
	"contact_id": "customer_12345",
	"stream": false
}
```

> [!WARNING]
>
> `data-contact-id` on the embed script and the `contactId` query parameter on iframe and fullscreen URLs are ignored. Conversations are keyed by contact, so a page-supplied identifier would let any website claim to be one of your known contacts. Embedded widgets receive a server-assigned identity instead, and a returning visitor keeps it through a stored visitor credential.

Use the Runtime API from your backend when conversations must map to your own user records. Requests without `contact_id` still work; they create conversations with no external user mapping.

## Human-in-the-Loop Runs

Human-in-the-loop (HITL) lets an agent pause a Runtime API run and wait for a person to answer a question or approve an action. Use it when your custom application needs to render the request, collect a decision, and continue the same conversation.

HITL is disabled by default for Runtime API calls. Set `enable_hitl` to `true` on every request where the agent should be allowed to pause, including a request that resumes an earlier pause.

> [!NOTE]
>
> Enabling HITL does not force every run to pause. The run pauses only when the agent reaches a configured HITL-capable tool, such as Human Input or a schedule approval.

### 1. Start a HITL-enabled run

Send the normal request with `enable_hitl: true`. HITL works with both non-streaming and streaming responses.

```bash theme={null}
curl -X POST "https://chat-v2.sketricgen.ai/api/v1/run-workflow" \
  -H "API-KEY: $SKETRICGEN_RUNTIME_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agent_abc123xyz",
    "user_input": "Prepare the campaign and ask me to approve it before scheduling.",
    "enable_hitl": true,
    "stream": false
  }'
```

Without `enable_hitl: true`, HITL-capable tools do not pause the run through the Runtime API.

### 2. Detect a pause

For a non-streaming request, check `run_paused_hitl`. When it is `true`, use the accompanying `hitl_request` to render the requested decision.

```json theme={null}
{
  "agent_id": "agent_abc123xyz",
  "conversation_id": "conv_def456ghi",
  "response": "Agent needs your input.",
  "error": false,
  "run_paused_hitl": true,
  "hitl_request": {
    "request_id": "hitl_req_789",
    "action_requests": [
      {
        "name": "request_human_input",
        "args": {
          "question": "Which launch date should I use?"
        }
      }
    ],
    "review_configs": [
      {
        "allowed_decisions": ["respond"]
      }
    ]
  }
}
```

Store the returned `conversation_id` and `hitl_request.request_id`. Read `action_requests` to understand what paused, and use the corresponding `review_configs.allowed_decisions` entry to determine which decision types your interface can submit.

For a streaming request, handle these additional events:

| Event | Meaning |
| - | - |
| `CUSTOM_EVENT` with name `deep_agents_hitl` | Contains the `request_id`, `action_requests`, and `review_configs` needed to render the request |
| `RUN_PAUSED_HITL` | Terminal event indicating that the stream ended in a paused state instead of completing with `RUN_FINISHED` |

After `RUN_PAUSED_HITL`, close the stream and resume with a new `POST /run-workflow` request. Runtime API keys do not use the first-party stream attach or cancel path to resume HITL.

### 3. Submit a decision and resume

Resume through the same `POST /run-workflow` endpoint. Send the original `conversation_id`, keep `enable_hitl: true`, and pass one decision for each pending action in the order returned by `action_requests`.

```bash theme={null}
curl -X POST "https://chat-v2.sketricgen.ai/api/v1/run-workflow" \
  -H "API-KEY: $SKETRICGEN_RUNTIME_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agent_abc123xyz",
    "conversation_id": "conv_def456ghi",
    "enable_hitl": true,
    "hitl_resume": {
      "request_id": "hitl_req_789",
      "decisions": [
        {
          "type": "respond",
          "message": "Launch on October 15."
        }
      ]
    },
    "stream": false
  }'
```

Do not send a new `user_input` when resuming. The decision continues the paused run on the existing conversation. A resumed run can pause again, which is why `enable_hitl: true` must also be present on the resume request.

### Decision types

Use only a decision type returned in `review_configs.allowed_decisions`.

| Requested decision | Allowed values | Payload example |
| - | - | - |
| Answer a question | `respond` | `{"type":"respond","message":"Tuesday at 3:00 PM"}` |
| Approve an action | `approve` | `{"type":"approve"}` |
| Reject an action | `reject` | `{"type":"reject"}` |

If the pause contains multiple actions, submit the same number of decisions in the same order. Do not infer that `approve` or `reject` is supported when the corresponding review configuration allows only `respond`.

### Resume errors

| Status | Meaning | Action |
| - | - | - |
| `409 Conflict` | The request is no longer pending or another resume is already in progress | Refresh the conversation state; do not blindly retry the same decision |
| `422 Unprocessable Entity` | A decision is missing, out of order, or not allowed for the pending action | Rebuild the payload from `action_requests` and `review_configs` |

Treat a resume as a single-use operation. Disable duplicate submission in your interface while the resume request is in progress.

## Response Formats

The endpoint supports two response modes.

### 1. Standard Response (stream: false)

**HTTP Status:** `201 Created`

**Response Body:**

| Field | Type | Description |
| - | - | - |
| `agent_id` | string | The agent that processed the request |
| `user_id` | string | Identifier for the user account |
| `conversation_id` | string | ID of the conversation (new or existing) |
| `response` | string | The AI agent's generated response |
| `owner` | string | Owner of the agent |
| `error` | boolean | Indicates if an error occurred |
| `assets` | array | Generated assets, such as images, with presigned URLs |
| `run_paused_hitl` | boolean | `true` when the run stopped on a Human Input request |
| `hitl_interrupts` | array | Serialized interrupts, present when `run_paused_hitl` is `true` |
| `hitl_request` | object or `null` | Pending Human Input request metadata, including the `request_id`, actions, and allowed decisions needed to resume |
| `run_halted_out_of_credits` | boolean | `true` when the run stopped mid-flight because the credit balance was exhausted |

The response does not echo `contact_id`. Track the contact identifier you sent in your own system, or read it back from the conversation record.

**Example Response:**

```json theme={null}
{
	"agent_id": "agent_abc123xyz",
	"user_id": "user_789xyz",
	"conversation_id": "conv_def456ghi",
	"response": "I'll help you analyze your quarterly sales data. Please share the data file or provide the key metrics you'd like me to examine.",
	"owner": "company_abc",
	"error": false,
	"assets": [],
	"run_paused_hitl": false,
	"run_halted_out_of_credits": false
}
```

### 2. Streaming Response (stream: true)

**HTTP Status:** `200 OK`
**Content-Type:** `text/event-stream`

When streaming is enabled, the endpoint returns real-time Server-Sent Events (SSE) as the AI processes the request.

**Event Types:**

| Event Type | Description |
| - | - |
| `RUN_STARTED` | Workflow execution has begun |
| `TEXT_MESSAGE_START` | AI has started generating a text response |
| `TEXT_MESSAGE_CONTENT` | Incremental text content (streaming) |
| `TEXT_MESSAGE_END` | AI has finished generating text response |
| `TOOL_CALL_START` | AI has started using a tool/function |
| `TOOL_CALL_ARGS` | Incremental tool-call arguments (streaming) |
| `TOOL_CALL_END` | AI has finished using a tool/function |
| `CUSTOM_EVENT` | Named side-channel payload. `deep_agents_hitl` carries a Human Input interrupt; `deep_agents_workspace` carries workspace file activity |
| `RUN_PAUSED_HITL` | The run paused on a Human Input request and is waiting for a `hitl_resume` call |
| `RUN_HALTED_OUT_OF_CREDITS` | The run stopped mid-flight because the credit balance was exhausted. Output emitted before this point is persisted |
| `RUN_FINISHED` | Workflow execution completed successfully |
| `RUN_ERROR` | An error occurred during execution |

`RUN_FINISHED`, `RUN_ERROR`, `RUN_PAUSED_HITL`, and `RUN_HALTED_OUT_OF_CREDITS` are all terminal for the current turn. Treat any of them as the end of the stream rather than waiting for `RUN_FINISHED` alone.

**Example Streaming Events:**

```
data: {"type": "RUN_STARTED", "timestamp": 1640995200, "thread_id": "conv_def456ghi", "run_id": "run_123abc"}

data: {"type": "TEXT_MESSAGE_START", "timestamp": 1640995201, "message_id": "msg_456def"}

data: {"type": "TEXT_MESSAGE_CONTENT", "timestamp": 1640995202, "message_id": "msg_456def", "delta": "I'll help"}

data: {"type": "TEXT_MESSAGE_CONTENT", "timestamp": 1640995203, "message_id": "msg_456def", "delta": " you analyze"}

data: {"type": "TEXT_MESSAGE_END", "timestamp": 1640995210, "message_id": "msg_456def"}

data: {"type": "RUN_FINISHED", "timestamp": 1640995211, "thread_id": "conv_def456ghi", "run_id": "run_123abc"}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.