Agents
Define an assistant once — model, instructions, tools, knowledge bases and approval policy — version it like a prompt, and run it through the OpenAI-compatible Responses API or embed it in your own application.
Snippet setup
The Python and TypeScript snippets on this page set BASE_URL to the host of the base URL and read your key from AI_2KW_API_KEY. Python: import os, requests, BASE_URL = "https://api.2kw.ai", api_key = os.environ["AI_2KW_API_KEY"] and headers = {"Authorization": f"Bearer {api_key}"}. TypeScript: const BASE_URL = "https://api.2kw.ai" and const apiKey = process.env.AI_2KW_API_KEY.
How It Works
An agent is a stored configuration: which model to call, what instructions to give it, which tools it may use, which knowledge bases it may search, and which tool calls need a human to approve them. Every change creates an immutable version; labels such as production point at the version your callers get.
You run an agent with POST /v1/responses by naming it in the model field. 2kw.ai then runs the whole turn server-side: it calls the model, executes the tools the model asks for (your webhooks, knowledge search, tool discovery), pauses when a call needs approval, and returns the answer with citations.
The workflow is: create an agent → label a version → call /v1/responses with model: "agent/{name}" → handle the answer, or a pause.
The agent is authoritative
When model names an agent, instructions and tools come from the agent version. instructions and tools on the request apply only to direct provider/model calls.
Creating an Agent
POST /v1/agents
Request
curl -X POST https://api.2kw.ai/v1/agents \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_your_api_key" \
-d '{
"name": "support-assistant",
"description": "Answers product questions from the manuals",
"models": ["openai/gpt-4o", "gpt-4.1-mini"],
"instructions": "You support field technicians. Answer from the manuals and cite your sources.",
"options": { "temperature": 0.2, "maxTokens": 1200 },
"tools": [
{ "type": "file_search", "config": { "knowledgeBaseIds": ["kb_123"] } }
]
}'
Send name (unique within the organization; you address the agent by it) and models: the ordered list of models the agent may run on, the first being the default and the others selectable per request. Each entry is provider/model such as openai/gpt-4o, or a platform model name; up to 10, no duplicates. A save is refused with 400 when a listed model is known not to support what the version needs, such as tool calling when it has tools; a model whose abilities are not known is accepted.
instructions (up to 20 000 characters), options (temperature, maxTokens, topP, reasoning.effort, maxToolRounds; sending options replaces the whole object), tools (Tools), hitlPolicy (Approvals), skills (Skills) and description are optional. The legacy scalar model still works: it must equal models[0], and a GET-then-PUT of { name, model } shrinks a multi-model agent to one entry. Every field: API reference.
Creating an agent publishes its configuration as version 1 and points the latest label at it, so the agent can run, is listed in the catalog and can be addressed by name from the moment the call returns. The response carries latestVersionId and latestVersionNumber. Send the configuration you want live: an agent created with a placeholder configuration is runnable with the placeholder until you publish the real one, and that publish becomes version 2. A name that is already taken answers 409. PUT /v1/agents/{id} changes the stored configuration and does not create a version. name is required on every update and description is written as sent, so omitting it clears it. The other fields keep their stored value when the body omits them, so { "name": "invoice-triage" } renames an agent without touching its configuration.
The console offers the same form under Agents in the sidebar, with a knowledge base picker for file_search and a per-agent Embed page.
Members can also talk to a published agent in the chat app.
Versions and Labels
Agents follow the same version and label model as prompts and schemas.
| Operation | Endpoint |
|---|---|
| Create a new version of an existing agent | POST /v1/agents/{agentId}/versions with models (required, ordered; first = default), instructions, options, tools, hitlPolicy, changeDescription |
| List versions | GET /v1/agents/{agentId}/versions |
| Get a version | GET /v1/agents/{agentId}/versions/{versionId}, or /versions/latest |
| Re-activate a version | PUT /v1/agents/{agentId}/versions/{versionId}/activate creates a copy at the head |
| Deactivate a version | DELETE /v1/agents/{agentId}/versions/{versionId} |
| Create a label | POST /v1/agents/{agentId}/labels with name and agentVersionId |
| Move a label | PUT /v1/agents/{agentId}/labels/{labelName} with agentVersionId |
| Delete a label | DELETE /v1/agents/{agentId}/labels/{labelName} |
Label names are lowercase letters, digits and hyphens. latest is system-managed and always points at the newest version.
A run is pinned to the version it started on. Publishing a new version while a turn is paused for approval does not change what the paused turn executes.
Running an Agent
POST /v1/responses
The Responses API endpoint. Address the agent in model:
model | Runs |
|---|---|
agent/support-assistant | The agent at its latest label |
agent/support-assistant@production | The agent pinned to the production label |
agent/agt_0123… | The same, by id |
agent/support-assistant@production#gpt-4.1-mini | The agent pinned to production, run on gpt-4.1-mini for this request only. The model must be one of the version's models, else 400 |
agent/support-assistant#openai/gpt-4o | The same at latest |
openai/gpt-4o | A direct gateway call, no agent |
Request
curl -X POST https://api.2kw.ai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_your_api_key" \
-d '{
"model": "agent/support-assistant@production",
"input": [
{
"type": "message",
"role": "user",
"content": [
{ "type": "input_text", "text": "What torque do the M8 mounting bolts need?" }
]
}
]
}'
Send model (the agent reference, optionally with a #{model} suffix from the version's list, or provider/model) and input: message items with input_text, input_image or input_file parts, plus the continuation items described below and a backbone:mode item (see Conversation Mode). Add conversation (an id from POST /v1/conversations; the turn is appended to it and the reply is stored there) or previous_response_id to continue.
max_output_tokens,temperatureandtop_poverride the agent's values for one call;tool_choicecan restrict which tool is called, never add one;metadatais stored with the response and echoed back.timezoneis your IANA time zone, for exampleEurope/Berlin. The model is told the current date and hour in it, so "today" and "this week" are right. Without it the model reads the zone of your earlier turns in the conversation, else UTC. An unknown zone reads as UTC and the response carriesX-Backbone-Adjustments: timezone=utc.storeis accepted for compatibility: responses are always persisted so they can be chained and read back from their conversation.instructionsandtoolsapply to directprovider/modelcalls only; they are ignored for agents.
Streaming
"stream": true returns Server-Sent Events in the Open Responses format: response.created, the
output items as they happen (text arrives as response.output_text.delta, tool calls and approvals as
whole items), then one of response.completed, response.incomplete or error + response.failed,
and data: [DONE]. A paused turn ends with response.completed whose status is requires_action.
The official OpenAI SDKs' stream helpers consume it as is. If the connection drops, the turn still
runs to its end and is stored with its conversation.
Switching models
An agent version lists the models it may run on; the first is the default. A caller with an organization credential picks another entry by appending #{model} to the reference. The switch applies to that request only: the conversation history is preserved, later turns without a suffix run on the default again. The echo carries the suffix back ("model": "agent/support-assistant@4#gpt-4.1-mini"), so the response says which model answered.
Two things to know before switching mid-conversation:
- Every switch drops the provider's cached prompt prefix, so frequent switching costs more, not less.
- No context-window check is made on a switch. If the accumulated conversation exceeds the new model's window, the provider's error is returned as-is.
Embedded surface visitors cannot switch; a # suffix from a surface token is refused as an unknown agent.
curl https://api.2kw.ai/v1/responses \
-H "Authorization: Bearer $AI_2KW_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "model": "agent/support-assistant@production#gpt-4.1-mini",
"input": "Summarise the last three tickets.",
"conversation": "conv_…" }'
Response
{
"id": "resp_…",
"object": "response",
"status": "completed",
"model": "agent/support-assistant@4",
"output": [
{
"type": "message",
"role": "assistant",
"status": "completed",
"phase": "final_answer",
"content": [
{ "type": "output_text", "text": "Tighten the four M8 bolts to 25 Nm in a cross pattern [h_0]." }
]
},
{
"type": "backbone:citation",
"handle": "h_0",
"knowledge_base_id": "kb_123",
"document_id": "doc_…",
"document_version_id": "ver_…",
"chunk_id": "chk_…",
"document_name": "service-manual-2026.pdf",
"page_start": 14,
"page_end": 14,
"status": "completed"
}
],
"usage": { "input_tokens": 1874, "output_tokens": 42, "total_tokens": 1916 },
"conversation": { "id": "conv_…" },
"conversation_mode": null
}
model echoes the concrete version that ran (agent/{name}@{versionNumber}), even when you addressed a label, plus the #{model} suffix when your request carried one.
conversation_mode is the conversation mode this request ran under: plan, ask, auto, or null when none is set.
status | Meaning |
|---|---|
completed | The turn finished with an answer |
requires_action | The turn is paused: a tool call is waiting for your client to answer it, for an approval, or for the user to connect a connector. Continue with previous_response_id |
incomplete | Stopped early, for example at max_output_tokens or the tool-round limit (max_tool_iterations), or when a tool call keeps failing with the same arguments (repeated_tool_failure). incomplete_details says why |
cancelled | Your client stopped the turn (see Stopping a turn). output holds what finished before the stop. The turn stays in the conversation and later turns see it |
A request that fails before or during the run does not produce a response object; it returns an HTTP error in the OpenAI error envelope (see Errors).
Items whose type starts with backbone: are 2kw.ai extensions. Branch on item.type and ignore types you do not know; the OpenAI SDKs tolerate them.
A turn can carry more than one message item. When the model says something on its way to a tool call, for example "Let me look that up.", that text is a message with "phase": "commentary", placed before the calls it introduced. The answer is the last message, with "phase": "final_answer". A turn that pauses or stops early can end on commentary. To show only the answer, read the last message item; joining the text of every message shows the commentary and the answer together.
Conversations
A conversation stores the turns of one chat so you do not have to replay the transcript yourself.
| Operation | Endpoint |
|---|---|
| Create | POST /v1/conversations with optional metadata and initial items. Returns { "id": "conv_…", "object": "conversation", "created_at": … } |
| Use | Pass the id as conversation on POST /v1/responses. Each response is appended |
| Read back | GET /v1/conversations/{conversationId}/items returns the items in replay order, oldest first. Each item also names the response it belongs to (response_id, logical_predecessor_id, turn_start) and its time (created_at: when a message was sent, when an answer finished). Every field: API reference |
| Get, update | GET /v1/conversations/{conversationId}, POST /v1/conversations/{conversationId} replaces metadata |
| Delete | DELETE /v1/conversations/{conversationId} deletes the conversation and the responses recorded against it. Pending approvals in it are cancelled |
| Stop a turn | POST /v1/conversations/{conversationId}/cancel with { "turn_id": "…" } asks a running turn to stop. Answers 204. See Stopping a turn |
| Branch | POST /v1/conversations/{conversationId}/fork with { "through_response_id": "resp_…" } returns a new conversation holding the messages through that response. See Branching a conversation |
Chaining by previous_response_id works with or without a conversation. The response carries conversation.id, so a client that only kept the last response id can find its conversation again.
Stopping a turn
A chat client can stop a turn that is still running, as the Stop button in chat apps does.
- Mint an id for each turn, for example a UUID, and send it on every
POST /v1/responsesof that turn in theBackbone-Turn-Idheader. A tool-output continuation belongs to the same turn and carries the same id; an approval decision starts a new turn with a new id. The id is 1–64 characters ofA-Z,a-z,0-9,_and-. The turn needs a conversation id you already know: passconversation(create one withPOST /v1/conversationsfirst), or chain withprevious_response_id. A turn whose conversation the server creates cannot be stopped until you know its id. - To stop it, call
POST /v1/conversations/{conversationId}/cancelwith that id as{ "turn_id": "…" }.
204 means the stop was accepted, not that the turn stopped. The turn's own POST /v1/responses still returns, and its status says what happened: cancelled, or completed when the stop arrived after the answer was ready.
- The turn stops at its next step boundary: before or after a model call, or after a batch of tool calls. Work already in flight finishes, including a running tool call. Its results stay in
output. - A model round that returns after the stop is billed and discarded: its text is not in
output, and its tokens are inusage. - Closing the connection does not stop a turn. Without the header a turn cannot be stopped.
- A stop applies to the id, in this conversation: every later request carrying it stops at its first check, a tool-output continuation included. A stop for an id no request carries again changes nothing, and repeating a stop changes nothing. Mint a fresh id per turn and never reuse one.
- A malformed
Backbone-Turn-Idrefuses the whole turn with400. The stop call answers400for a malformedturn_id, and404for an unknown conversation or one the caller may not address.
Branching a Conversation
POST /v1/conversations/{conversationId}/fork with { "through_response_id": "resp_…" } creates a new conversation holding this one's messages up to and including that response, and returns it. The conversation you branched from is never changed. This is what Branch, Regenerate and Edit do in the chat: to run a turn again, branch through the response before it and send the message on the copy.
- Only the person who started a conversation can branch it. For anyone else it answers
404, exactly as an unknown id does. through_response_idmust be the last response of a turn and lie on the conversation's current line. Send the next message withprevious_response_idset tobackbone.head_response_idof the returned conversation, or just pass its id asconversation.- The copy keeps the messages and their sources, and nothing else. An attached file or image becomes a line of text naming it; no tool call, approval decision or uploaded file is carried over, so a link in a copied answer to a file the original produced no longer resolves. The title is kept. The copy keeps the model that answered each turn; your next message resolves the agent as any new conversation does.
- Errors:
400 invalid_fork_point(nothrough_response_id, or one that is not the last response of a turn or not on the current line),404(no such conversation for this caller),409 fork_point_not_ready(the conversation is still working on that turn),409 agent_unavailable(the conversation's agent cannot answer),413 conversation_too_long,429(too many branches in a minute).
Embedding an Agent
An agent can be placed inside your own web application as a chat panel: your users talk to it under their own login, and tools can run inside your application under the user's own permissions. See Embeddable Surface.
Errors
A request that fails before or during the run returns an HTTP error in the OpenAI error envelope: { "error": { "type": …, "code": …, "message": … } }. The ones you meet most with agents:
| Status | When |
|---|---|
400 | A malformed model reference, a #{model} override the version does not list, a bad continuation or approval decision, or a malformed Backbone-Turn-Id header |
404 | Unknown agent, or an agent the caller may not address |
409 agent_not_published | The agent has no published version: publish one with POST /v1/agents/{agentId}/versions |
410 file_expired | An attached file's lifetime ran out |
429 | A limit was reached; which one decides what to do |
Every status and code, with what to do about it, is on Errors.