Quickstart
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:
export DASHSCOPE_API_KEY="sk-xxx"
export AGENTSTUDIO_URL="https://ws_xxxxxxxxxxxx.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio"
The curl example requires 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:
pip install dashscope==1.27.7
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.23.2</version>
</dependency>
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.
set -euo pipefail
# 1. Create an Agent
AGENT_ID=$(curl -fsS -X POST "$AGENTSTUDIO_URL/agents" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "quickstart-coder",
"model": {"id": "qwen-plus"},
"system": "You are a Python expert. When the user submits a coding task, output concise, runnable Python code directly."
}' | jq -er '.id')
printf 'Agent: %s\n' "$AGENT_ID"
# 2. Create an Environment
ENV_ID=$(curl -fsS -X POST "$AGENTSTUDIO_URL/environments" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "quickstart-env", "config": {"type": "cloud"}}' | jq -er '.id')
printf 'Environment: %s\n' "$ENV_ID"
# 3. Create a Session
SESSION_ID=$(curl -fsS -X POST "$AGENTSTUDIO_URL/sessions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"agent\": {\"type\": \"agent\", \"id\": \"$AGENT_ID\"}, \"environment_id\": \"$ENV_ID\"}" | jq -er '.id')
export SESSION_ID
printf 'Session: %s\n' "$SESSION_ID"
Connect in terminal A. Export the same 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.
export SESSION_ID="sesn_xxx"
# 4. Connect to SSE and display the response headers
curl -N -i "$AGENTSTUDIO_URL/sessions/$SESSION_ID/events/stream" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Accept: text/event-stream"
Submit in terminal B only after terminal A is connected. Use the same 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.
# 5. Submit the task
curl -fsS -X POST "$AGENTSTUDIO_URL/sessions/$SESSION_ID/events" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input": [
{"role": "user", "type": "message",
"content": [{"type": "text", "text": "Write a Python function that takes a list of integers and returns a sorted list with duplicates removed."}]}
]
}'
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.
import os
from dashscope.agentstudio import Client
from dashscope.agentstudio.types import user_message
with Client(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url=os.environ["AGENTSTUDIO_URL"],
workspace="ws_xxxxxxxxxxxx",
region="cn-beijing",
) as client:
# 1. Create an Agent
agent = client.agents.create(
name="quickstart-coder",
model="qwen-plus",
system_prompt="You are a Python expert. When the user submits a coding task, output concise, runnable Python code directly.",
)
# 2. Create an Environment
env = client.environments.create(name="quickstart-env", config={"type": "cloud"})
# 3. Create a Session
session = client.sessions.create(
agent={"type": "agent", "id": agent.id}, environment_id=env.id
)
print(f"Agent: {agent.id}, Environment: {env.id}, Session: {session.id}")
# 4. Open the HTTP stream before sending
with client.sessions.events.stream(session.id, timeout=120.0) as stream:
# 5. Submit the task, then receive events
client.sessions.events.send(
session.id,
events=[user_message("Write a Python function that takes a list of integers and returns a sorted list with duplicates removed.")],
)
for event in stream:
print(event, flush=True)
if event.type != "session_status":
continue
state = event.session_status
reason = (event.stop_reason or {}).get("type")
if state == "terminated":
print("Session terminated; it cannot continue.")
break
if state == "idle" and reason in (
"end_turn", "requires_action", "retries_exhausted"
):
print({
"end_turn": "Turn completed normally.",
"requires_action": "Waiting for tool approval; handle approval or interrupt.",
"retries_exhausted": "Turn failed; inspect the error events.",
}[reason])
break
import com.alibaba.dashscope.agentstudio.AgentStudioClient;
import com.alibaba.dashscope.agentstudio.model.Agent;
import com.alibaba.dashscope.agentstudio.model.Environment;
import com.alibaba.dashscope.agentstudio.model.Session;
import com.alibaba.dashscope.agentstudio.param.AgentCreateParam;
import com.alibaba.dashscope.agentstudio.param.EnvironmentCreateParam;
import com.alibaba.dashscope.agentstudio.param.SessionCreateParam;
import com.alibaba.dashscope.agentstudio.message.ClientEvents;
import com.alibaba.dashscope.agentstudio.message.ContentBlock;
import com.alibaba.dashscope.agentstudio.message.Message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
public class ManagedAgentQuickstart {
public static void main(String[] args) throws Exception {
AgentStudioClient client = AgentStudioClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl(System.getenv("AGENTSTUDIO_URL"))
.workspace("ws_xxxxxxxxxxxx").region("cn-beijing").build();
// 1. Create an Agent
Agent agent = client.agents().create(AgentCreateParam.builder()
.name("quickstart-coder").model("qwen-plus")
.systemPrompt("You are a Python expert. When the user submits a coding task, output concise, runnable Python code directly.")
.build());
// 2. Create an Environment
Environment env = client.environments().create(EnvironmentCreateParam.builder()
.name("quickstart-env").config(Map.of("type", "cloud")).build());
// 3. Create a Session
Session session = client.sessions().create(SessionCreateParam.builder()
.agent(Map.of("type", "agent", "id", agent.getId()))
.environmentId(env.getId()).build());
System.out.println("Agent: " + agent.getId() + ", Environment: " + env.getId()
+ ", Session: " + session.getId());
runTurn(client, session.getId(),
"Write a Python function that takes a list of integers and returns a sorted list with duplicates removed.");
}
public static void runTurn(AgentStudioClient client, String sessionId, String prompt)
throws Exception {
String baseUrl = System.getenv("AGENTSTUDIO_URL").replaceAll("/+$", "");
HttpURLConnection connection = (HttpURLConnection) new URL(
baseUrl + "/sessions/" + sessionId + "/events/stream").openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Authorization", "Bearer " + System.getenv("DASHSCOPE_API_KEY"));
connection.setRequestProperty("Accept", "text/event-stream");
connection.setConnectTimeout(30_000);
connection.setReadTimeout(120_000);
try {
// 4. Await response headers, not the first business event
int status = connection.getResponseCode();
String contentType = connection.getContentType();
if (status < 200 || status >= 300 || contentType == null
|| !contentType.toLowerCase(java.util.Locale.ROOT).startsWith("text/event-stream")) {
throw new IllegalStateException("SSE connection failed: HTTP " + status + ", " + contentType);
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), StandardCharsets.UTF_8))) {
// 5. Send through a separate SDK connection after SSE is ready
client.sessions().events().send(sessionId,
Collections.singletonList(ClientEvents.userMessage(prompt)));
Gson gson = new GsonBuilder()
.registerTypeAdapter(ContentBlock.class, new ContentBlock.Deserializer()).create();
StringBuilder payload = new StringBuilder();
long lastBusinessEventNanos = System.nanoTime();
while (true) {
checkBusinessEventTimeout(lastBusinessEventNanos);
String line = reader.readLine();
checkBusinessEventTimeout(lastBusinessEventNanos);
if (line == null) break;
if (line.startsWith("data:")) {
String value = line.substring(5);
if (value.startsWith(" ")) value = value.substring(1);
payload.append(value).append('\n');
} else if (line.isEmpty() && payload.length() > 0) {
Message event = gson.fromJson(payload.toString(), Message.class);
payload.setLength(0);
if (event == null || event.getType() == null) continue;
lastBusinessEventNanos = System.nanoTime();
if ("message".equals(event.getType()) && event.getContent() != null) {
for (ContentBlock block : event.getContent()) {
if (block instanceof ContentBlock.Text)
System.out.print(((ContentBlock.Text) block).getText());
}
} else {
System.out.println(event);
}
if (!"session_status".equals(event.getType())) continue;
JsonObject data = event.getData();
if (data == null || !data.has("session_status")
|| data.get("session_status").isJsonNull()) continue;
String state = data.get("session_status").getAsString();
if ("terminated".equals(state)) {
System.out.println("Session terminated; it cannot continue.");
break;
}
Session.StopReason stop = event.getStopReason();
String reason = stop == null ? null : stop.getType();
if (!"idle".equals(state)) continue;
if ("end_turn".equals(reason)) {
System.out.println("Turn completed normally.");
break;
} else if ("requires_action".equals(reason)) {
System.out.println("Waiting for tool approval; handle approval or interrupt.");
break;
} else if ("retries_exhausted".equals(reason)) {
System.out.println("Turn failed; inspect the error events.");
break;
}
}
}
}
} finally {
connection.disconnect();
}
}
private static void checkBusinessEventTimeout(long lastBusinessEventNanos)
throws SocketTimeoutException {
if (System.nanoTime() - lastBusinessEventNanos >= 120_000L * 1_000_000L) {
throw new SocketTimeoutException("No complete business event within 120000 ms; outcome UNKNOWN. "
+ "Query Session state and event history; do not automatically resubmit.");
}
}
}
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
NoteExpect 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.
Keep the returned Agent, Environment, and Session IDs. Reuse the Agent and Environment across Sessions and reuse this Session for further turns after normal completion. Open a new subscription before sending the next turn. For pending approvals, interrupts, and termination, see Session operations. For input files, see File upload and mounting; for output artifact retrieval, see Data analysis: retrieve artifacts.
Closing SSE only closes the subscription. Archiving a Session terminates it while retaining history; deleting a Session irreversibly removes its metadata and history. Environment archive/delete is managed separately. Session runtime charges apply while running, not while idle; see Billing.