Skip to content

Commit 771993e

Browse files
author
zhansheng.lzs
committed
docs(examples): move agentstudio to the 2.0 tiers, add agentic RL quickref
AgentStudio and agentic RL are shared by the 1.x/2.0 generations, so they do not belong under legacy_1x. agentstudio examples now use the client.agentstudio entry; reinforcement_learning.py covers client.rl.
1 parent 3a2df48 commit 771993e

5 files changed

Lines changed: 135 additions & 30 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright (c) Alibaba, Inc. and its affiliates.
3+
"""dashscope 2.0 agentic RL example: list jobs, and (optionally) the
4+
full register-functions -> upload-data -> create -> wait lifecycle.
5+
6+
The read-only list/get sections run as-is. The training workflow is
7+
commented out: it registers real rollout/reward function instances,
8+
uploads datasets and submits a real training job (which trains and
9+
bills). Uncomment it once your function classes, data files and
10+
training config are ready.
11+
"""
12+
13+
import dashscope
14+
15+
# Authentication: the client reads the API key from the
16+
# DASHSCOPE_API_KEY environment variable by default; you can also
17+
# pass it explicitly via dashscope.Client(api_key="sk-xxx").
18+
19+
if __name__ == "__main__":
20+
client = dashscope.Client()
21+
22+
# List RL jobs (paged; RL jobs share the fine-tune wire contract)
23+
print("----- list RL jobs -----")
24+
page = client.rl.jobs.list(page_no=1, page_size=10)
25+
print(f"total: {page.total_count}")
26+
for job in page.jobs:
27+
print(
28+
f"job_id={job.job_id}, status={job.status}, "
29+
f"model={job.finetuned_model}",
30+
)
31+
32+
# Get one job by ID (uses the first job of the list above)
33+
if page.jobs:
34+
print("----- get RL job -----")
35+
job = client.rl.jobs.fetch(page.jobs[0].job_id)
36+
print(
37+
f"job_id={job.job_id}, status={job.status}, "
38+
f"finished={job.finished}",
39+
)
40+
41+
# Full lifecycle: register functions -> upload data -> create ->
42+
# wait -> delete. Uncomment once you have rollout/reward function
43+
# classes, training data files and a training config file.
44+
#
45+
# print("----- register functions -----")
46+
# registered = client.rl.register_functions(
47+
# rollout_classpaths=["my_rl.rollout.MyRollout"],
48+
# reward_classpaths=["my_rl.reward.MyReward"],
49+
# workspace_dir="./",
50+
# )
51+
# print(f"registered: {registered}")
52+
#
53+
# print("----- upload data -----")
54+
# data = client.rl.upload_data(
55+
# training_files=["train.jsonl"],
56+
# validation_files=["val.jsonl"],
57+
# )
58+
# print(f"training_file_ids={data.training_file_ids}")
59+
#
60+
# print("----- create RL job -----")
61+
# job = client.rl.jobs.create(
62+
# config_path="rl_config.yaml",
63+
# job_name="my-rl-job",
64+
# )
65+
# print(f"created job_id={job.job_id}")
66+
#
67+
# print("----- wait RL job -----")
68+
# final = client.rl.jobs.wait(job)
69+
# print(f"status={final.status}, succeeded={final.succeeded}")
70+
#
71+
# print("----- delete RL job -----")
72+
# client.rl.jobs.delete(job.job_id)
73+
74+
75+
# --- Production springboard (Best Practices & Patterns) -------
76+
# Minimal runnable atomic call above; to productionize it, see:
77+
# Offline mock debugging: 02_advanced_engineering/local_mock_debugging.py
78+
# Backoff + breaker DR: 02_advanced_engineering/circuit_breaker_retry.py
79+
# This capability is a long-running jobs flow; reuse the
80+
# generic patterns above for poll timeouts and retries.
81+
# client.rl wraps the async workflow with asyncio.run -- under a
82+
# running event loop (Jupyter, FastAPI) use dashscope.AsyncClient.rl.
83+
# -------------------------------------------------------------
Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,44 @@
11
# -*- coding: utf-8 -*-
22
# Copyright (c) Alibaba, Inc. and its affiliates.
3-
"""AgentStudio sync API example: end-to-end quickstart.
3+
"""dashscope 2.0 agent recipe: AgentStudio end-to-end quickstart.
44
55
Flow: create environment -> create agent -> create session ->
66
send message -> stream events -> archive session.
77
8+
AgentStudio is shared by the 1.x and 2.0 SDK generations: the 2.0
9+
client mounts it as ``client.agentstudio`` (workspace and region
10+
forward from the client config) and translates its errors into the
11+
``dashscope.v2`` exception family, so one ``client`` covers both the
12+
2.0 resources and AgentStudio.
13+
814
`memory_stores_demo` covers the memory store flow (create store ->
915
write memory -> list -> update -> list versions -> delete). It creates
1016
and deletes a real store, so it is opt-in: uncomment its call below.
17+
18+
Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the
19+
AgentStudio workspace (defaults to trial).
1120
"""
1221

1322
import os
1423

15-
from dashscope.agentstudio import Client, user_message
24+
import dashscope
25+
from dashscope.agentstudio import user_message
1626

1727

18-
def make_client() -> Client:
19-
# Authentication: set your Model Studio API key via the
20-
# DASHSCOPE_API_KEY environment variable, and the workspace via
21-
# DASHSCOPE_WORKSPACE (defaults to trial)
22-
return Client(
23-
api_key=os.environ["DASHSCOPE_API_KEY"],
28+
def make_client():
29+
# Authentication: the client reads the API key from the
30+
# DASHSCOPE_API_KEY environment variable by default.
31+
return dashscope.Client(
2432
workspace=os.environ.get("DASHSCOPE_WORKSPACE", "trial"),
2533
)
2634

2735

2836
def main() -> None:
2937
client = make_client()
38+
studio = client.agentstudio
3039

3140
print("==> creating environment")
32-
env = client.environments.create(
41+
env = studio.environments.create(
3342
name="quickstart-env",
3443
config={
3544
"type": "cloud",
@@ -39,7 +48,7 @@ def main() -> None:
3948
print(f" environment_id={env.id}")
4049

4150
print("==> creating agent")
42-
agent = client.agents.create(
51+
agent = studio.agents.create(
4352
name="quickstart-agent",
4453
system_prompt="You are a friendly demo agent. Reply briefly.",
4554
model="qwen3.8-max",
@@ -54,59 +63,59 @@ def main() -> None:
5463
print(f" agent_id={agent.id}")
5564

5665
print("==> creating session")
57-
session = client.sessions.create(
66+
session = studio.sessions.create(
5867
agent=agent.id,
5968
environment_id=env.id,
6069
title="quickstart",
6170
)
6271
print(f" session_id={session.id}")
6372

6473
print("==> sending user message")
65-
client.sessions.events.send(
74+
studio.sessions.events.send(
6675
session.id,
6776
[user_message("Hello! Tell me one fun fact about Hangzhou.")],
6877
)
6978

7079
print("==> streaming events")
71-
with client.sessions.events.stream(session.id) as stream:
80+
with studio.sessions.events.stream(session.id) as stream:
7281
for text in stream.text_stream:
7382
print(text, end="", flush=True)
7483
print() # newline after streaming
7584

7685
print("==> archiving session")
77-
client.sessions.archive(session.id)
86+
studio.sessions.archive(session.id)
7887
print("done.")
7988

8089

8190
def memory_stores_demo() -> None:
8291
"""Memory store flow: create store -> seed memory -> read back
8392
-> audit versions -> cleanup."""
84-
client = make_client()
93+
studio = make_client().agentstudio
8594

8695
print("==> creating memory store")
87-
store = client.memory_stores.create(
96+
store = studio.memory_stores.create(
8897
name="demo-preferences",
8998
description="Per-user preferences and project context.",
9099
)
91100
print(f" memory_store_id={store.id}")
92101

93102
print("==> seeding a memory")
94-
mem = client.memory_stores.memories.create(
103+
mem = studio.memory_stores.memories.create(
95104
store.id,
96105
path="/formatting_standards.md",
97106
content="All reports use GAAP formatting.",
98107
)
99108
print(f" memory_id={mem.id} size={mem.content_size_bytes}")
100109

101110
print("==> listing memories")
102-
page = client.memory_stores.memories.list(store.id, view="full")
111+
page = studio.memory_stores.memories.list(store.id, view="full")
103112
for item in page:
104113
print(f" {item.path} -> {item.content}")
105114
# Directory nodes ride the page's prefixes field (per page):
106115
print(f" prefixes={page.prefixes}")
107116

108117
print("==> updating with optimistic lock")
109-
updated = client.memory_stores.memories.update(
118+
updated = studio.memory_stores.memories.update(
110119
store.id,
111120
mem.id,
112121
content="All reports use GAAP formatting. ISO-8601 dates.",
@@ -115,11 +124,11 @@ def memory_stores_demo() -> None:
115124
print(f" new sha={updated.content_sha256[:12]}...")
116125

117126
print("==> listing versions")
118-
for v in client.memory_stores.memory_versions.list(store.id):
127+
for v in studio.memory_stores.memory_versions.list(store.id):
119128
print(f" {v.id}: {v.operation}")
120129

121130
print("==> deleting memory store")
122-
client.memory_stores.delete(store.id)
131+
studio.memory_stores.delete(store.id)
123132
print("done.")
124133

125134

examples/legacy_1x/agentstudio_deployments.py renamed to examples/03_agent_recipes/agentstudio_deployments.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
# -*- coding: utf-8 -*-
2-
"""Create and run a Managed Agent deployment.
2+
# Copyright (c) Alibaba, Inc. and its affiliates.
3+
"""dashscope 2.0 agent recipe: create and run a Managed Agent deployment.
34
4-
Set DASHSCOPE_API_KEY and DASHSCOPE_WORKSPACE before running this sample.
5+
Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the
6+
AgentStudio workspace (defaults to trial).
57
"""
68

7-
from dashscope.agentstudio import Client, user_message
9+
import os
10+
11+
import dashscope
12+
from dashscope.agentstudio import user_message
813

914

1015
def main() -> None:
11-
with Client() as client:
12-
deployment = client.deployments.create(
16+
workspace = os.environ.get("DASHSCOPE_WORKSPACE", "trial")
17+
with dashscope.Client(workspace=workspace) as client:
18+
deployment = client.agentstudio.deployments.create(
1319
name="daily-summary",
1420
description="Generate a daily summary",
1521
agent={"id": "agent_xxx"},
@@ -23,10 +29,13 @@ def main() -> None:
2329
)
2430
print("deployment:", deployment.id, deployment.status)
2531

26-
run = client.deployments.run(deployment.id)
32+
run = client.agentstudio.deployments.run(deployment.id)
2733
print("run:", run.id, run.status)
2834

29-
for item in client.deployments.list_runs(deployment.id, limit=20):
35+
for item in client.agentstudio.deployments.list_runs(
36+
deployment.id,
37+
limit=20,
38+
):
3039
print(item.id, item.trigger_source, item.status)
3140

3241

‎examples/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ Uniform style: `client = dashscope.Client()` (reads the key from the `DASHSCOPE_
104104
| `files/files.py` | File management: upload / list / get / delete |
105105
| `applications/apps.py` | Model Studio application invocation (non-streaming + streaming) |
106106
| `fine_tuning/fine_tunes.py` | Fine-tune jobs: list / get, create / wait / delete (uncomment to run) |
107+
| `fine_tuning/reinforcement_learning.py` | Agentic RL: list / get jobs; register functions -> upload data -> create / wait / delete (uncomment to run) |
107108
| `models/models.py` | Model list and get |
108109

109110
## 02_advanced_engineering — Advanced engineering
@@ -121,6 +122,8 @@ Uniform style: `client = dashscope.Client()` (reads the key from the `DASHSCOPE_
121122
| `tool_call_loop.py` | Managed multi-turn tool-call state machine: declare `tools` schemas, execute locally when the model requests a call, feed the `role="tool"` result back, and loop until a final answer (with a `MAX_TURNS` backstop) | Yes |
122123
| `rag_expert_system.py` | Standard RAG: corpus embedding -> cosine top-k recall -> `client.rerank` refinement -> an "answer only from the sources" chat prompt -> an answer with citations | Yes |
123124
| `mcp_server_demo/` | Dependency-free MCP (Model Context Protocol) stdio server + client demo: `server.py` speaks JSON-RPC 2.0; `client_demo.py` spawns the subprocess and runs initialize -> tools/list -> tools/call. See its `README.md` | No |
125+
| `agentstudio.py` | AgentStudio end-to-end quickstart via `client.agentstudio`: environment -> agent -> session -> streamed reply (plus an opt-in memory-store demo); AgentStudio is shared by the 1.x/2.0 generations and mounts on the 2.0 client | Yes |
126+
| `agentstudio_deployments.py` | Managed Agent deployments: create a cron-scheduled deployment, trigger a run, list runs | Yes |
124127

125128
## 04_real_world_scenarios — Real-world scenarios
126129

@@ -146,7 +149,6 @@ The following use the old 1.x style (`dashscope.Generation`, `dashscope.MultiMod
146149
| `multimodal_conversation/` | MultiModalConversation multimodal chat: image, video, tool calls, OCR, ASR, deep thinking |
147150
| `aio_multimodal_conversation/` | Async versions of the above |
148151
| `application.py` | Model Studio application (Application) invocation |
149-
| `agentstudio.py` / `agentstudio_deployments.py` | AgentStudio sessions and managed deployments |
150152
| `assistant_api*.py` | Assistant agents: create / update, file attachment, end-to-end dialogue |
151153
| `image_generation.py` / `image_synthesis.py` / `aio_image_synthesis.py` | Image generation (wanx / wan2.x) |
152154
| `video_synthesis.py` / `aio_video_synthesis.py` | Video generation (wan series) |

‎examples/README_zh.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ examples/
104104
| `files/files.py` | 文件管理:上传 / 列表 / 查询 / 删除 |
105105
| `applications/apps.py` | 百炼应用调用(非流式 + 流式) |
106106
| `fine_tuning/fine_tunes.py` | 微调任务:list / get、create / wait / delete(取消注释即可运行) |
107+
| `fine_tuning/reinforcement_learning.py` | 智能体 RL:任务 list / get;注册函数 -> 上传数据 -> create / wait / delete(取消注释即可运行) |
107108
| `models/models.py` | 模型列表与详情 |
108109

109110
## 02_advanced_engineering —— 进阶工程
@@ -121,6 +122,8 @@ examples/
121122
| `tool_call_loop.py` | 受管多轮工具调用状态机:声明 `tools` schema,模型请求调用时本地执行,把 `role="tool"` 结果喂回,循环直到最终答案(带 `MAX_TURNS` 兜底) | 是 |
122123
| `rag_expert_system.py` | 标准 RAG:语料向量 -> 余弦 top-k 召回 -> `client.rerank` 精排 -> "仅依据资料作答"的聊天 prompt -> 带引用的答案 | 是 |
123124
| `mcp_server_demo/` | 零依赖 MCP(Model Context Protocol)stdio server + client 演示:`server.py` 讲 JSON-RPC 2.0;`client_demo.py` 拉起子进程并跑 initialize -> tools/list -> tools/call。见其 `README.md` | 否 |
125+
| `agentstudio.py` | AgentStudio 端到端 quickstart(经 `client.agentstudio`):环境 -> 智能体 -> 会话 -> 流式回复(另附可选的 memory store 演示);AgentStudio 为 1.x/2.0 两代共用模块,挂载在 2.0 客户端上 | 是 |
126+
| `agentstudio_deployments.py` | 托管智能体部署:创建 cron 定时部署、触发运行、列出运行记录 | 是 |
124127

125128
## 04_real_world_scenarios —— 真实场景
126129

@@ -146,7 +149,6 @@ examples/
146149
| `multimodal_conversation/` | MultiModalConversation 多模态对话:图像、视频、工具调用、OCR、ASR、深度思考 |
147150
| `aio_multimodal_conversation/` | 上述的异步版本 |
148151
| `application.py` | 百炼应用(Application)调用 |
149-
| `agentstudio.py` / `agentstudio_deployments.py` | AgentStudio 会话与托管部署 |
150152
| `assistant_api*.py` | Assistant 智能体:创建 / 更新、文件挂载、端到端对话 |
151153
| `image_generation.py` / `image_synthesis.py` / `aio_image_synthesis.py` | 图像生成(wanx / wan2.x) |
152154
| `video_synthesis.py` / `aio_video_synthesis.py` | 视频生成(wan 系列) |

0 commit comments

Comments
 (0)