Create session

Updated at:

Create a session, bind it to an agent and runtime environment, and submit the first input.

Endpoint

A non-streaming request returns 201 JSON; with stream=true, the response is 201 text/event-stream. A 201 means the session and first input were accepted, not that the turn has completed.

POST/agents/sessions

Request body

environmentobjectRequired

Runtime environment, see below

agent_idstring / nullConditional

Saved agent ID; up to 64 characters

agentobjectConditional

Inline agent configuration, when provided with agent_id, acts as session-level overrides, and fields not overridden keep the saved values

Properties

modelstringConditional

Model ID; required for inline creation; can be inherited when referencing a saved agent. The create precheck allows up to 256 characters, and the model must match a model available in the current workspace. For available models, see Available models.

instructionsstring / nullOptional

System instructions, up to 1,048,576 Unicode characters; merged into the system prompt at execution

namestring / nullOptional

Display name; removed from the execution configuration

reasoning

effortstring / nullOptional

Reasoning effort, none, minimal, low, medium, high, xhigh, max, or ultra; returns none when unspecified

summarystring / nullOptional

Reasoning summary type, auto, concise, detailed, or none; returns auto when unspecified. The string none differs from JSON null

text

formatobject / nullOptional

Text format configuration; only type: text is accepted; unknown fields are rejected, omitted or null becomes {"type":"text"}

verbositystring / nullOptional

Output verbosity, only medium is accepted, omitted or null becomes medium

toolsarrayOptional

Tool list, omitted becomes an empty list, an explicit null is not accepted. Up to 32 function tools and 16 MCP servers

Properties

function

typestringRequired

Tool type, fixed as function

namestringRequired

Function name, 1-64 bytes with characters A-Za-z0-9_.:-; must be unique within the agent

descriptionstringRequired

Function description, must be non-empty after trimming and no more than 1024 bytes

parametersobjectRequired

Parameter definition; must be a JSON Schema with type: object

mcp

typestringRequired

Tool type, fixed as mcp

server_labelstringRequired

MCP server label, 1-64 bytes and unique within the agent

transportobjectRequired

HTTP or stdio transport configuration

Properties

typestringRequired

Transport type, http or stdio

server_urlstringConditional

MCP server URL; service accepts only Model Studio locator URLs (/api/v1/mcps/{code}/mcp); environment accepts ordinary HTTP addresses reachable from the environment

headersobject<string,string> / nullOptional

Additional HTTP headers

authorizationstring / nullOptional

Used only for the HTTP branch with connection_origin=environment

commandstringConditional

Command to start the server

cwdstringConditional

Absolute path; stdio requires an environment

argsarray<string>Optional

Command arguments

allowed_toolsarray<string> / nullOptional

Allowed tool names; null means no filter

connection_originstringOptional

Connection origin, service or environment, defaults to service

requiredbooleanOptional

Whether MCP initialization must succeed

multi_agentobject / nullOptional

Multi-agent configuration, omitted or null disables subagents, when the object is present, enabled can be omitted and defaults to false, an explicit null is rejected

Properties

max_concurrent_subagentsintegerOptional

Maximum concurrent subagents, an explicit value requires enabled=true and must be 1..32, an explicit null is rejected, when enabled, omitted defaults to 6, when disabled, the returned value is null

inputstring or array / nullConditional

First input. A string is shorthand for one user text message; an empty string is rejected

Properties

rolestringRequired

Message role, fixed as user

typestringOptional

Message type, if set, only message

contentarrayRequired

Message content; cannot be empty

Properties

typestringRequired

Content part type; input_text or input_image

textstringConditional

Text content; up to 1,048,576 characters; the same item cannot also contain image_url

image_urlstringConditional

Image URL; up to 1,048,576 characters; the same item cannot also contain text; URL reachability is not guaranteed

metadataobject / nullOptional

Metadata, string key-value pairs, up to 16 items; key up to 64 characters, value up to 512 characters; null values are not accepted

streambooleanOptional

Whether to return an SSE stream, when true, the create response is an SSE stream that ends after the session becomes idle or failed, omitted is false, and null is invalid

vault_idsarray<string> / nullOptional

Vaults to attach, up to 10, omitted or null becomes []

Request example

curl -sS -X POST "$BASE_URL/agents/sessions" \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "OpenAI-Beta: agents=v1" \
  -H "Content-Type: application/json" \
  -d '{
    "agent": {
      "model": "qwen3.8-max",
      "instructions": "Answer briefly."
    },
    "environment": {"type": "none"},
    "input": "Hello"
  }'
session = client.beta.agents.sessions.create(
    agent={
        "model": "qwen3.8-max",
        "instructions": "Answer briefly.",
    },
    environment={"type": "none"},
    input="Hello",
)
print(session.id, session.status)

Environment

FormDescription
{"type":"none"}No sandbox; no built-in shell or file tools
{"type":"openai_hosted"}Create a managed environment with the inline configuration
{"type":"openai_hosted","environment_id":"..."}Reference an existing environment; do not add files, skills, or other configuration at the same time

For fields, limits, and asynchronous preparation, see Environment. self_hosted is not supported. Creating a session that references the environment can fail before preparation completes; confirm the status is ready before using the environment.

NoteWhen referencing an existing environment, vault_ids must match the vault_ids used to create the environment. You cannot add new vaults on the session.

Agent configuration

agent is used for inline creation or to override a saved agent. When agent_id is also provided, top-level replacement applies: omitted fields keep the saved values, and an explicit null follows the field's own rule. The final effective configuration runs the same precheck as an inline configuration.

Example with both fields: {"agent_id":"agent_xxx","agent":{"instructions":"Reply with OK only"},"environment":{"type":"none"},"input":"Reply with OK only"}.

agent.id is generated in the response or comes from a saved agent and cannot be specified inline. Unknown fields such as agent.metadata, compaction, and experimental are rejected. A tool of one type must not carry fields from another branch; a boolean null is not equivalent to an omitted field.

Message and content

When input is an array, each item is a user message. Unknown fields in message and content are rejected.

Unknown top-level fields are rejected. The request body limit is 16 MiB. After removing instructions, the compact JSON of agent + metadata + environment is limited to 1,310,720 bytes.

Response fields

null when the fields are incomplete. The status in the create response can be in_progress. HTTP 201 means the session and first input were accepted, not that the turn succeeded; use the turn's terminal state or the SSE agent.session.idle event to determine the end of the turn.

idstring

Session ID; reuse it for follow-up turns

objectstring

Session object type, fixed as agent.session

created_atinteger

Creation time in Unix seconds

last_active_atinteger

Last activity time in Unix seconds; not a version number or lock

statusstring

Session status: idle, in_progress, requires_action, or failed

agentobject

Effective agent snapshot.

Properties

idstring

Agent ID; inline configurations return a session snapshot ID, not a reusable saved agent, and it cannot be retrieved through Agent GET

modelstring

Model ID

instructionsstring / null

Custom instructions

namestring / null

Display name

reasoningobject / null

Reasoning configuration, contains effort and summary

textobject / null

Text output configuration; contains format and verbosity

toolsarray

Tool configuration

multi_agentobject / null

Subagent configuration; contains enabled and max_concurrent_subagents

environmentobject

Safe environment summary; only type for none.

Properties

typestring

Environment type; none or openai_hosted

idstring

Environment ID, omitted when there is no authoritative value

statusstring

Environment status: omitted when there is no authoritative value

environment_template_idstring

Environment template ID, omitted when there is no authoritative value

workspace_directorystring

Workspace directory, omitted when there is no authoritative value

errorstring / null

Environment error description, omitted when there is no authoritative value

desktopobject / null

Desktop settings; contains enabled

capability_directoriesarray<string> / null

Capability discovery directories

networkobject / null

Network policy; contains access and allowed_domains

packagesobject / null

Package lists; contains npm, python, and system

filesarray

Safe environment file metadata

skillsarray

Safe skill metadata

pluginsarray

Plugin information; [] for managed environments

metadataobject

Session metadata; an empty value is {}

vault_idsarray<string>

Vault IDs recorded at creation

required_actionsarray

Function calls that need client handling; [] when empty.

Properties

typestring

Item type, fixed as function_call

turn_idstring

Public turn ID

call_idstring

Function call ID

namestring

Function name

argumentsobject

Parsed call arguments

errorstring / null

Session-level error message, different from a turn's structured error

usageobject / null

Token usage.

Properties

input_tokensinteger

Number of input tokens

input_tokens_detailsobject

Input token details.

Properties

cached_tokensinteger

Number of input tokens that hit the cache

output_tokensinteger

Number of output tokens

output_tokens_detailsobject

Output token details.

Properties

reasoning_tokensinteger

Number of reasoning tokens

total_tokensinteger

Total number of tokens

spend_controlobject

Spend control; returned only when a historical record has a value; creation and update do not accept writes.

Properties

limitinteger

Spending limit in cents

consumedinteger / null

Consumed amount in cents

Response example

{
  "id": "sess_xxx",
  "object": "agent.session",
  "created_at": 1794118835,
  "last_active_at": 1794118835,
  "status": "in_progress",
  "agent": {
    "id": "agent_xxx",
    "model": "qwen3.8-max",
    "instructions": "Answer briefly.",
    "reasoning": {"effort": "none", "summary": "auto"},
    "text": {"format": {"type": "text"}, "verbosity": "medium"},
    "tools": [],
    "multi_agent": {"enabled": false, "max_concurrent_subagents": null},
    "name": null
  },
  "environment": {"type": "none"},
  "metadata": {},
  "required_actions": [],
  "vault_ids": [],
  "error": null,
  "usage": {
    "input_tokens": 0,
    "input_tokens_details": {"cached_tokens": 0},
    "output_tokens": 0,
    "output_tokens_details": {"reasoning_tokens": 0},
    "total_tokens": 0
  }
}

Error codes

Business errors return an error object with type, code, message, and param. Common errors:

HTTP statusError type / codeSolution
400invalid_request_error / missing_required_parameterProvide environment, for example {"type":"none"} or {"type":"openai_hosted"}
400invalid_request_error / specific code depends on the fieldProvide input for the applicable case; provide agent.model when there is no agent_id
400invalid_request_error / invalid_type, invalid_value, unknown_parameter, invalid_jsonRemove unknown fields, fix field types and enum values, and send valid JSON
400invalid_request_error / specific code depends on the fieldShorten metadata, vault_ids, or the string field as described
401authentication_error / invalid_api_keySend a valid Authorization: Bearer $DASHSCOPE_API_KEY header
404not_found_error / not_found_errorUse a resource ID that exists in the current workspace
502server_error / agents_api_upstream_unavailableRetry later. If it keeps failing, submit a ticket with the x-request-id from the response headers
503server_error / specific service error codeRetry later. If it keeps failing, submit a ticket with x-request-id