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

# Migrate to Hosted Agents

> Migrate a self-built agent loop on the Model Inference API to Kimi Hosted Agents.

If you have already built your own agent loop on top of the Model Inference API—maintaining message history, executing tools, and handling retries yourself—this guide shows how to migrate that system to Kimi Hosted Agents so the platform manages the runtime while you keep only the logic unique to your product.

> [!NOTE]
>
> Migration does not require an SDK compatibility layer: Hosted Agents exposes standard HTTP + SSE endpoints that you can call with `curl` or any HTTP client. The examples below read your API key from the `KIMI_API_KEY` environment variable.

## What changes

With a self-built harness, your application code owns every part of the runtime. After migrating, those runtime responsibilities move to the platform:

| Capability | Self-Built Harness | Hosted Agents |
| - | - | - |
| Session history | Assemble, store, and resend the message list on every turn | The platform persists the full history as events, ready to fetch at any time |
| Tool execution | Parse tool calls, execute them, and return results yourself | Built-in tools run in a cloud sandbox managed by the platform; [custom tools](https://platform.kimi.ai/docs/hosted-agents/tools.md#custom-tools) run on your client, with calls and results exchanged over the event stream |
| Sandbox | Provision and manage your own environment for commands and file I/O | The platform provides isolated cloud sandboxes with configurable network access and dependencies |
| Crash recovery | Rebuild state yourself after crashes or disconnects | After a platform failure, execution automatically recovers and resumes from where it left off |
| Timeouts and retries | Implement retries and rate-limit backoff yourself | The platform handles execution-layer retries and scheduling |

In short: **hand "how it runs" to the platform, and keep "what task to solve" in your configuration and business code**.

## Migration steps

**1. Move system prompts, tool definitions, and skills into an Agent configuration**

Consolidate the system prompts, tool schemas, and other instructions previously hardcoded in your loop into a persistent Agent configuration object. Create an agent once and reference it by ID across sessions; each update creates a new immutable version.

```bash cURL theme={null}
curl -X POST https://api.moonshot.ai/v1/agents \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -H "kimi-api-version: 2026-09-01-beta" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Research Assistant",
    "model": {"id": "kimi-k3.1-pro"},
    "system": "You are a rigorous research assistant skilled at retrieving, organizing, and citing sources."
  }'
```

```bash CLI theme={null}
kha agents create --name "Research Assistant" --model kimi-k3.1-pro --system "You are a rigorous research assistant skilled at retrieving, organizing, and citing sources."
```

Here is how components from your loop map to Hosted Agents:

* System prompt → the agent's `system` field.
* Business tools executed on your client → declare them as [custom tools](https://platform.kimi.ai/docs/hosted-agents/tools.md#custom-tools) so your client continues executing them; to let the platform connect directly to third-party services, use [MCP](https://platform.kimi.ai/docs/hosted-agents/mcp.md).
* Hand-written utility tools (search, file I/O, shell commands) → agents get built-in cloud sandbox tools (file read/write, code execution, web search, and more) by default—no declaration needed—so you can delete your own implementations.
* Structured domain playbooks (prompts + scripts + templates) → package and attach them as [skills](https://platform.kimi.ai/docs/hosted-agents/skills.md).

For full agent configuration fields and versioning behavior, see [Create and Manage Agents](https://platform.kimi.ai/docs/hosted-agents/agents.md).

**2. Delete your custom agent loop and message history storage**

In this step, you can remove the following boilerplate harness components entirely:

* The main orchestration loop ("call model → parse tool calls → execute tools → append results → call model again").
* Assembling and truncating message history, and maintaining persistent message storage.
* Fallback logic for crash recovery, stream reconnection, and timeout retries.

Context compaction, history management, and interruption recovery are handled by the platform—you no longer resend the full conversation history on each request.

**3. Switch to creating a session, subscribing to the event stream, and sending events**

Replace single-turn Model Inference API calls with a three-step flow: create a session, subscribe to its event stream, and send events. Below, `AGENT_ID` is the `id` returned in Step 1, `SESSION_ID` is the `id` returned when creating the session, and `ENVIRONMENT_ID` is the `id` returned when you [create an execution environment](https://platform.kimi.ai/docs/hosted-agents/environments.md):

```bash cURL theme={null}
# 1. Create a session (does not start execution)
curl -X POST https://api.moonshot.ai/v1/sessions \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -H "kimi-api-version: 2026-09-01-beta" \
  -H "Content-Type: application/json" \
  -d "{\"agent_id\": \"$AGENT_ID\", \"environment_id\": \"$ENVIRONMENT_ID\", \"title\": \"My first task\"}"

# 2. Subscribe to the event stream first (run in another terminal)
curl -N https://api.moonshot.ai/v1/sessions/$SESSION_ID/events/stream \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -H "kimi-api-version: 2026-09-01-beta" \
  -H "Accept: text/event-stream"

# 3. Send a user message to start the agent
curl -X POST https://api.moonshot.ai/v1/sessions/$SESSION_ID/events \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -H "kimi-api-version: 2026-09-01-beta" \
  -H "Content-Type: application/json" \
  -d '{"events": [{"type": "user.message", "data": {"content": [{"type": "text", "text": "Research recent industry trends"}]}}]}'
```

```bash CLI theme={null}
# 1. Create a session (does not start execution)
kha sessions create --agent "$AGENT_ID" --environment "$ENVIRONMENT_ID" --title "My first task"

# 2. Subscribe to the event stream first (run in another terminal)
kha sessions attach "$SESSION_ID"

# 3. Send a user message to start the agent
kha sessions send "$SESSION_ID" "Research recent industry trends"
```

> [!TIP]
>
> Subscribe to the event stream before sending the message so you do not miss events emitted right after submission. If the connection drops, reconnect with the `Last-Event-ID` header set to the last received SSE message `id` to resume from where the stream left off; see [Event Stream](https://platform.kimi.ai/docs/hosted-agents/event-stream.md).

For session creation, status transitions, and lifecycle details, see [Create a Session](https://platform.kimi.ai/docs/hosted-agents/sessions.md).

## What you do not need to migrate

The platform provides the capabilities below out of the box, so you do not need to rebuild them in your system:

* **Persistent session history**: Event history is persisted server-side and can be fetched in full at any time without maintaining your own message database.
* **Disconnect and failure recovery**: Event streams resume from a cursor after network drops, and after a platform failure, execution automatically recovers and resumes from where it left off.
* **Timeouts and retries**: Execution-layer retries, scheduling, and context compaction are managed by the platform—your client only needs to handle HTTP error codes for its own requests.

> [!TIP]
>
> If you want to keep your own agent loop and fine-grained control over every model call, continue using the [Model Inference API](https://platform.kimi.ai/docs/api/overview.md). Kimi Hosted Agents is built for long-horizon tasks where you want to offload the entire runtime to the platform.

## Next steps

> [card] [Migrate agent configuration](https://platform.kimi.ai/docs/hosted-agents/agents.md)
>
> Consolidate system prompts and tool definitions into a versioned Agent configuration.

> [card] [Start a managed session](https://platform.kimi.ai/docs/hosted-agents/sessions.md)
>
> Create sessions and send events in place of a self-built agent loop.

> [card] [Inspect event history](https://platform.kimi.ai/docs/hosted-agents/event-stream.md)
>
> Subscribe to events, resume from cursors, and review all event types.
