Get the full Managed Agents workflow running in five minutes: create an Agent and Environment, open a Session, submit a task, and stream the results.
Workflow
Prerequisites
- You have activated Model Studio and created an API Key (
sk-xxx), and obtained your workspace ID (ws_xxxxxxxxxxxx). For details, see Overview and authentication. - Export the API Key and Endpoint as environment variables. Replace the placeholders with your own values; use the same workspace throughout:
curl and jq. The Java example uses Map.of, so it requires JDK 9 or later. The examples below use Python SDK 1.27.7 and Java SDK 2.23.2.
Install the SDK
Before using the Python or Java SDK, install the corresponding DashScope package. The Managed Agents module requires Python SDK v1.26.2 or later, and Java SDK v2.22.24 or later. If you have an older version installed, upgrade it.
Session-level agent configuration overrides (agent object and patch) and session-level MCP request headers (mcp_configs) require Python SDK v1.27.7 or later and Java SDK v2.23.2 or later; direct REST calls are not affected by this requirement. For version requirements, see Overview and authentication. Pin the versions below to use these examples:
End-to-end example
Create a code-generation Agent, open a Session, and ask it to write a Python function that returns a sorted list of unique integers. Choose curl or one SDK; do not run all variants to create duplicate resources.
1. Create an Agent
Set name, model, and the system prompt (system in REST, system_prompt in Python, systemPrompt in Java). This example uses quickstart-coder and qwen-plus and returns an agent_xxx. An Agent is typically created once and reused.
2. Create an Environment
Create quickstart-env with config.type=cloud to obtain an env_xxx. An Environment is independently managed and is typically created once and reused.
This example does not configure pre-installed packages. If you add apt, pip, or npm packages, installation can take several minutes or longer. Creating a Session before warm-up completes is rejected with invalid_parameter: The environment is still being prepared. Please wait until it is ready and try again. See Environment warm-up.
3. Create a Session
Bind agent={"type":"agent","id":AGENT_ID} and environment_id=ENV_ID to obtain a sesn_xxx. Keep the conversation-to-Session-ID mapping: the same Session supports multiple turns and retains context. Returning to idle does not delete the Session.
4. Connect to SSE
Subscribe to GET /sessions/{id}/events/stream with Accept: text/event-stream, and confirm the HTTP connection is ready before submitting the task. SSE pushes live events and does not replay history. For reconnects and history reconciliation, see Client streaming and recovery.
Python SDK 1.27.7 opens the HTTP stream synchronously before stream() returns. Enter the stream context first, then call send(). Java SDK 2.23.2 starts AgentStudioEventStream asynchronously and exposes no connection-readiness barrier. The Java example below therefore uses the standard HttpURLConnection SSE transport to check the response headers before sending through the SDK. Message and ClientEvents belong to .message; the SDK stream class belongs to .resource, not .model.
5. Submit an Event and read the result
Send POST /sessions/{id}/events with input containing a user message and a text content block. HTTP 200 means the input was queued; execution enters running asynchronously. Results arrive on the already-connected SSE subscription, not in the POST response.
Use the session_status event's content[].data.session_status and content[].data.stop_reason to determine the outcome. Python exposes them as an optional string event.session_status and optional dictionary event.stop_reason. The Message envelope's status=completed is not the Session state.
| Session state | Stop reason | Meaning and next action |
|---|---|---|
running | null | Keep receiving events. |
idle | null | A newly created Session may be idle; this is not evidence that the submitted task completed. |
idle | end_turn | The turn completed normally. Reuse this Session for the next turn. |
idle | requires_action | Waiting for tool approval; handle the request or interrupt the turn. This is not successful completion. |
idle | retries_exhausted | The turn failed after exhausting retries. Inspect errors before starting another turn. |
terminated | Not interpreted | The Session has ended and cannot continue. |
curl: two terminals
Create resources in terminal B. Each response ID is printed and reused by the next operation. Stop if a request fails; do not submit a task yet.
DASHSCOPE_API_KEY and AGENTSTUDIO_URL from the prerequisites in this new terminal; shell variables are not shared between terminals. Copy the Session ID printed in terminal B into SESSION_ID below. Keep terminal A running. Wait until its output shows a successful HTTP response (2xx) and Content-Type: text/event-stream; on an error, stop instead of sending.
SESSION_ID and environment variables. Read events in terminal A and use the outcome table above. Ctrl+C closes this subscription; it does not terminate the Session.
SDK: choose Python or Java
The Python Client context closes its HTTP client. Save the Java example as ManagedAgentQuickstart.java; runTurn opens the subscription, sends one task, and closes the subscription on normal completion, pending approval, or failure. Closing the subscription does not call terminateSession.
The Java example does not guarantee an exact 120-second wall-clock deadline. On timeout, the outcome remains UNKNOWN: query Session state and event history, without automatic resubmission.
python
Java timeout and recovery details
Java timeout and recovery details
Java retains the 120000 ms business-event wait: start a
System.nanoTime() clock when consumption begins, check before and after each readLine(), and reset only when a complete SSE frame parses into a non-null Message with a non-null type. Comments, heartbeats, and incomplete frames do not reset it. Separately, setReadTimeout(120_000) bounds socket inactivity. The blocking reader has no watchdog, so this is not an exact 120-second wall-clock guarantee; standard complete heartbeat lines trigger SocketTimeoutException at the first line check after expiry instead of keeping the loop alive indefinitely. Exceptions close the reader and disconnect. The task outcome remains UNKNOWN: query Session state (Java client.sessions().retrieve(sessionId)) and event history, without automatic resubmission.Result and Session management
Expect generated Python code followed by
session_status=idle with stop_reason.type=end_turn. requires_action means waiting, and retries_exhausted means failure. An interrupted connection or read timeout alone does not establish the task outcome, which remains UNKNOWN: query Session state (Java client.sessions().retrieve(sessionId)) and event history before deciding what to do; do not automatically resubmit the task.running, not while idle; see Billing.