AgentStudio
dashscope.applications.agentstudio is the sub-SDK for the AgentStudio
managed-agent API: agents, sessions, events, environments, deployments,
memory, skills, vaults, security and webhooks. All resources are reached
through its own client:
from dashscope.applications.agentstudio import Client
from dashscope.applications.agentstudio import user_message
client = Client ( api_key = "sk-xxx" )
agent = client . agents . create ( name = "demo" , model = "qwen-plus" )
session = client . sessions . create ( agent = agent . id )
client . sessions . events . send ( session . id , [ user_message ( "Hello!" )])
with client . sessions . events . stream ( session . id ) as stream :
for event in stream :
print ( event . type )
# session_status may also report running; stop only on a terminal state
if event . session_status in ( "idle" , "terminated" ):
break
Session status and text consumption
A session_status event may report running (still working) as well
as terminal states such as idle / terminated — do not treat the
first session_status as the end of the run. When you only need the
text reply, use stream.text_stream: it yields the text of agent
messages and stops automatically once the session reaches a terminal
state. If the agent uses tools that require approval, the session
pauses at idle with stop_reason.type == "requires_action"; submit
the decision with user_tool_approval_response and the session
resumes.
Every resource class has an async twin (AsyncAgents, AsyncSessions, ...)
used the same way through AsyncClient.
Clients
Client
Client (
* ,
api_key : Optional [ str ] = None ,
workspace : Optional [ str ] = None ,
region : Optional [ str ] = None ,
base_url : Optional [ str ] = None ,
uid : Optional [ str ] = None ,
timeout : Optional [
Union [ float , Timeout , Tuple [ float , float ]]
] = None ,
max_retries : int = AGENTSTUDIO_MAX_RETRIES ,
http_client : Optional [ Client ] = None ,
_exceptions_module : Any = _default_exceptions ,
_api_key_resolver : Any = _default_api_key ,
_transport_cls : Any = SyncTransport ,
_event_stream_cls : Any = EventStream
)
Synchronous AgentStudio client.
Usage::
from dashscope.applications.agentstudio import Client, ModelConfig
client = Client(api_key="sk-xxx", workspace="my-ws")
agent = client.agents.create(
name="demo",
model=ModelConfig(
id="qwen-max",
temperature=0.7,
enable_thinking=True,
thinking_budget=2048,
),
)
session = client.sessions.create(agent=agent.id)
with client.sessions.events.stream(session.id) as stream:
for event in stream:
print(event.type)
Source code in dashscope/applications/agentstudio/client.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234 def __init__ (
self ,
* ,
api_key : Optional [ str ] = None ,
workspace : Optional [ str ] = None ,
region : Optional [ str ] = None ,
base_url : Optional [ str ] = None ,
uid : Optional [ str ] = None ,
timeout : Optional [
Union [ float , httpx . Timeout , Tuple [ float , float ]]
] = None ,
max_retries : int = AGENTSTUDIO_MAX_RETRIES ,
http_client : Optional [ httpx . Client ] = None ,
_exceptions_module : Any = _default_exceptions ,
_api_key_resolver : Any = _default_api_key ,
_transport_cls : Any = SyncTransport ,
_event_stream_cls : Any = EventStream ,
) -> None :
resolved_workspace = workspace or os . environ . get ( "DASHSCOPE_WORKSPACE" )
resolved_base = _resolve_base_url (
base_url ,
resolved_workspace ,
region ,
)
self . _event_stream_cls = _event_stream_cls
self . transport = _transport_cls (
base_url = resolved_base ,
api_key = api_key or _api_key_resolver (),
workspace = resolved_workspace ,
uid = uid or os . environ . get ( "DASHSCOPE_UID" ),
user_agent = _user_agent ( resolved_base ),
timeout = timeout or AGENTSTUDIO_DEFAULT_TIMEOUT ,
max_retries = max_retries ,
http_client = http_client ,
exceptions_module = _exceptions_module ,
)
self . agents = Agents ( self )
self . dynamic_workflows = DynamicWorkflows ( self )
self . deployments = Deployments ( self )
self . deployment_runs = DeploymentRuns ( self )
self . sessions = Sessions ( self )
self . environments = Environments ( self )
self . files = Files ( self )
self . skills = Skills ( self )
self . vaults = Vaults ( self )
self . memory_stores = MemoryStores ( self )
self . webhook_endpoints = WebhookEndpoints ( self )
self . security = Security ( self )
self . usage = Usage ( self )
self . _sandbox = None
transport
instance-attribute
transport = _transport_cls (
base_url = resolved_base ,
api_key = api_key or _api_key_resolver (),
workspace = resolved_workspace ,
uid = uid or os . environ . get ( "DASHSCOPE_UID" ),
user_agent = _user_agent ( resolved_base ),
timeout = timeout or AGENTSTUDIO_DEFAULT_TIMEOUT ,
max_retries = max_retries ,
http_client = http_client ,
exceptions_module = _exceptions_module ,
)
agents
instance-attribute
dynamic_workflows
instance-attribute
dynamic_workflows = DynamicWorkflows ( self )
deployments
instance-attribute
deployments = Deployments ( self )
deployment_runs
instance-attribute
deployment_runs = DeploymentRuns ( self )
sessions
instance-attribute
sessions = Sessions ( self )
environments
instance-attribute
environments = Environments ( self )
skills
instance-attribute
vaults
instance-attribute
memory_stores
instance-attribute
memory_stores = MemoryStores ( self )
webhook_endpoints
instance-attribute
webhook_endpoints = WebhookEndpoints ( self )
security
instance-attribute
security = Security ( self )
sandbox
property
Sandbox lifecycle and Harness Agent APIs, mounted on first use.
close
Source code in dashscope/applications/agentstudio/client.py
def close ( self ) -> None :
try :
if self . _sandbox is not None :
self . _sandbox . close ()
finally :
self . transport . close ()
AsyncClient
AsyncClient (
* ,
api_key : Optional [ str ] = None ,
workspace : Optional [ str ] = None ,
region : Optional [ str ] = None ,
base_url : Optional [ str ] = None ,
uid : Optional [ str ] = None ,
timeout : Optional [
Union [ float , Timeout , Tuple [ float , float ]]
] = None ,
max_retries : int = AGENTSTUDIO_MAX_RETRIES ,
http_client : Optional [ AsyncClient ] = None ,
_exceptions_module : Any = _default_exceptions ,
_api_key_resolver : Any = _default_api_key ,
_transport_cls : Any = AsyncTransport ,
_event_stream_cls : Any = AsyncEventStream
)
Asynchronous AgentStudio client.
Usage::
from dashscope.applications.agentstudio import AsyncClient, ModelConfig
client = AsyncClient(api_key="sk-xxx", workspace="my-ws")
agent = await client.agents.create(
name="demo",
model=ModelConfig(id="qwen-max", max_tokens=4096),
)
session = await client.sessions.create(agent=agent.id)
async with client.sessions.events.stream(session.id) as stream:
async for event in stream:
print(event.type)
Source code in dashscope/applications/agentstudio/client.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339 def __init__ (
self ,
* ,
api_key : Optional [ str ] = None ,
workspace : Optional [ str ] = None ,
region : Optional [ str ] = None ,
base_url : Optional [ str ] = None ,
uid : Optional [ str ] = None ,
timeout : Optional [
Union [ float , httpx . Timeout , Tuple [ float , float ]]
] = None ,
max_retries : int = AGENTSTUDIO_MAX_RETRIES ,
http_client : Optional [ httpx . AsyncClient ] = None ,
_exceptions_module : Any = _default_exceptions ,
_api_key_resolver : Any = _default_api_key ,
_transport_cls : Any = AsyncTransport ,
_event_stream_cls : Any = AsyncEventStream ,
) -> None :
resolved_workspace = workspace or os . environ . get ( "DASHSCOPE_WORKSPACE" )
resolved_base = _resolve_base_url (
base_url ,
resolved_workspace ,
region ,
)
self . _event_stream_cls = _event_stream_cls
self . transport = _transport_cls (
base_url = resolved_base ,
api_key = api_key or _api_key_resolver (),
workspace = resolved_workspace ,
uid = uid or os . environ . get ( "DASHSCOPE_UID" ),
user_agent = _user_agent ( resolved_base ),
timeout = timeout or AGENTSTUDIO_DEFAULT_TIMEOUT ,
max_retries = max_retries ,
http_client = http_client ,
exceptions_module = _exceptions_module ,
)
self . agents = AsyncAgents ( self )
self . dynamic_workflows = AsyncDynamicWorkflows ( self )
self . deployments = AsyncDeployments ( self )
self . deployment_runs = AsyncDeploymentRuns ( self )
self . sessions = AsyncSessions ( self )
self . environments = AsyncEnvironments ( self )
self . files = AsyncFiles ( self )
self . skills = AsyncSkills ( self )
self . vaults = AsyncVaults ( self )
self . memory_stores = AsyncMemoryStores ( self )
self . webhook_endpoints = AsyncWebhookEndpoints ( self )
self . security = AsyncSecurity ( self )
self . usage = AsyncUsage ( self )
self . _sandbox = None
transport
instance-attribute
transport = _transport_cls (
base_url = resolved_base ,
api_key = api_key or _api_key_resolver (),
workspace = resolved_workspace ,
uid = uid or os . environ . get ( "DASHSCOPE_UID" ),
user_agent = _user_agent ( resolved_base ),
timeout = timeout or AGENTSTUDIO_DEFAULT_TIMEOUT ,
max_retries = max_retries ,
http_client = http_client ,
exceptions_module = _exceptions_module ,
)
agents
instance-attribute
agents = AsyncAgents ( self )
dynamic_workflows
instance-attribute
dynamic_workflows = AsyncDynamicWorkflows ( self )
deployments
instance-attribute
deployments = AsyncDeployments ( self )
deployment_runs
instance-attribute
deployment_runs = AsyncDeploymentRuns ( self )
sessions
instance-attribute
sessions = AsyncSessions ( self )
environments
instance-attribute
environments = AsyncEnvironments ( self )
skills
instance-attribute
skills = AsyncSkills ( self )
vaults
instance-attribute
vaults = AsyncVaults ( self )
memory_stores
instance-attribute
memory_stores = AsyncMemoryStores ( self )
webhook_endpoints
instance-attribute
webhook_endpoints = AsyncWebhookEndpoints ( self )
security
instance-attribute
security = AsyncSecurity ( self )
sandbox
property
Asynchronous Sandbox sub-client, sharing this client's HTTP pool.
aclose
async
Source code in dashscope/applications/agentstudio/client.py
async def aclose ( self ) -> None :
try :
if self . _sandbox is not None :
await self . _sandbox . aclose ()
finally :
await self . transport . aclose ()
Agents & sessions
Agents
Agent CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/agents.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
call
class-attribute
instance-attribute
create
create (
* ,
name : str ,
model : Union [ str , ModelConfig ],
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Agent
Source code in dashscope/applications/agentstudio/resources/agents.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 def create (
self ,
* ,
name : str ,
model : Union [ str , ModelConfig ],
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Agent :
body = AgentCreateParams (
name = name ,
model = model ,
description = description ,
system_prompt = system_prompt ,
tools = tools ,
mcp_servers = mcp_servers ,
skills = skills ,
multiagent = multiagent ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request ( "POST" , _PATH_AGENTS , json = body )
return _coerce_agent ( resp . data )
retrieve
retrieve (
agent_id : str , * , version : Optional [ int ] = None
) -> Agent
Source code in dashscope/applications/agentstudio/resources/agents.py
66
67
68
69
70
71
72
73
74
75
76
77
78 def retrieve (
self ,
agent_id : str ,
* ,
version : Optional [ int ] = None ,
) -> Agent :
params = { "version" : version } if version is not None else None
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_AGENTS } / { agent_id } " ,
params = params ,
)
return _coerce_agent ( resp . data )
update
update (
agent_id : str ,
* ,
version : int ,
name : Optional [ str ] = None ,
model : Optional [ Union [ str , ModelConfig ]] = None ,
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Agent
Update the latest version of an agent.
version must equal the server's current version;
the server rejects mismatches with HTTP 409.
Retrieve the agent first to obtain the current version.
name is required too (AGENT_005 without it).
Source code in dashscope/applications/agentstudio/resources/agents.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125 def update (
self ,
agent_id : str ,
* ,
version : int ,
name : Optional [ str ] = None ,
model : Optional [ Union [ str , ModelConfig ]] = None ,
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Agent :
"""Update the latest version of an agent.
``version`` must equal the server's current version;
the server rejects mismatches with HTTP 409.
Retrieve the agent first to obtain the current version.
``name`` is required too (``AGENT_005`` without it).
"""
body = AgentUpdateParams (
version = version ,
name = name ,
model = model ,
description = description ,
system_prompt = system_prompt ,
tools = tools ,
mcp_servers = mcp_servers ,
skills = skills ,
multiagent = multiagent ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_AGENTS } / { agent_id } " ,
json = body ,
)
return _coerce_agent ( resp . data )
archive
archive ( agent_id : str ) -> Agent
Source code in dashscope/applications/agentstudio/resources/agents.py
def archive ( self , agent_id : str ) -> Agent :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_AGENTS } / { agent_id } /archive" ,
)
return _coerce_agent ( resp . data )
list
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None
) -> CursorPage [ Agent ]
Source code in dashscope/applications/agentstudio/resources/agents.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160 def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
) -> CursorPage [ Agent ]:
params = AgentListParams (
limit = limit ,
page = page ,
include_archived = include_archived ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_AGENTS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_agent ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
limit = limit ,
page = nxt ,
include_archived = include_archived ,
),
)
list_versions
list_versions (
agent_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ AgentVersion ]
Source code in dashscope/applications/agentstudio/resources/agents.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184 def list_versions (
self ,
agent_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ AgentVersion ]:
params = AgentVersionListParams ( limit = limit , page = page ) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_AGENTS } / { agent_id } /versions" ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_agent_version ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list_versions (
agent_id ,
limit = limit ,
page = nxt ,
),
)
AsyncAgents
Async Agent CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/agents.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
call
class-attribute
instance-attribute
create
async
create (
* ,
name : str ,
model : Union [ str , ModelConfig ],
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Agent
Source code in dashscope/applications/agentstudio/resources/agents.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 async def create (
self ,
* ,
name : str ,
model : Union [ str , ModelConfig ],
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Agent :
body = AgentCreateParams (
name = name ,
model = model ,
description = description ,
system_prompt = system_prompt ,
tools = tools ,
mcp_servers = mcp_servers ,
skills = skills ,
multiagent = multiagent ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_AGENTS ,
json = body ,
)
return _coerce_agent ( resp . data )
retrieve
async
retrieve (
agent_id : str , * , version : Optional [ int ] = None
) -> Agent
Source code in dashscope/applications/agentstudio/resources/agents.py
224
225
226
227
228
229
230
231
232
233
234
235
236 async def retrieve (
self ,
agent_id : str ,
* ,
version : Optional [ int ] = None ,
) -> Agent :
params = { "version" : version } if version is not None else None
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_AGENTS } / { agent_id } " ,
params = params ,
)
return _coerce_agent ( resp . data )
update
async
update (
agent_id : str ,
* ,
version : int ,
name : Optional [ str ] = None ,
model : Optional [ Union [ str , ModelConfig ]] = None ,
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Agent
Update the latest version of an agent.
version must equal the server's current version;
the server rejects mismatches with HTTP 409.
Retrieve the agent first to obtain the current version.
name is required too (AGENT_005 without it).
Source code in dashscope/applications/agentstudio/resources/agents.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283 async def update (
self ,
agent_id : str ,
* ,
version : int ,
name : Optional [ str ] = None ,
model : Optional [ Union [ str , ModelConfig ]] = None ,
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Agent :
"""Update the latest version of an agent.
``version`` must equal the server's current version;
the server rejects mismatches with HTTP 409.
Retrieve the agent first to obtain the current version.
``name`` is required too (``AGENT_005`` without it).
"""
body = AgentUpdateParams (
version = version ,
name = name ,
model = model ,
description = description ,
system_prompt = system_prompt ,
tools = tools ,
mcp_servers = mcp_servers ,
skills = skills ,
multiagent = multiagent ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_AGENTS } / { agent_id } " ,
json = body ,
)
return _coerce_agent ( resp . data )
archive
async
archive ( agent_id : str ) -> Agent
Source code in dashscope/applications/agentstudio/resources/agents.py
async def archive ( self , agent_id : str ) -> Agent :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_AGENTS } / { agent_id } /archive" ,
)
return _coerce_agent ( resp . data )
list
async
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None
) -> AsyncCursorPage [ Agent ]
Source code in dashscope/applications/agentstudio/resources/agents.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323 async def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
) -> AsyncCursorPage [ Agent ]:
params = AgentListParams (
limit = limit ,
page = page ,
include_archived = include_archived ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_AGENTS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ Agent ]:
return await self . list (
limit = limit ,
page = nxt ,
include_archived = include_archived ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_agent ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
list_versions
async
list_versions (
agent_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ AgentVersion ]
Source code in dashscope/applications/agentstudio/resources/agents.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352 async def list_versions (
self ,
agent_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ AgentVersion ]:
params = AgentVersionListParams ( limit = limit , page = page ) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_AGENTS } / { agent_id } /versions" ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ AgentVersion ]:
return await self . list_versions (
agent_id ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_agent_version ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
Sessions
Session CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/sessions.py
def __init__ ( self , client ) -> None :
self . _client = client
self . events = SessionEvents ( client )
self . resources = SessionResources ( client )
self . threads = SessionThreads ( client )
events
instance-attribute
events = SessionEvents ( client )
resources
instance-attribute
resources = SessionResources ( client )
threads
instance-attribute
threads = SessionThreads ( client )
get
class-attribute
instance-attribute
call
class-attribute
instance-attribute
create
create (
* ,
agent : Any ,
environment_id : Optional [ str ] = None ,
title : Optional [ str ] = None ,
resources : Optional [ Sequence [ ResourceInput ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
mcp_configs : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Session
Create a session (POST /sessions).
agent is the Agent id string or an
{"type": "agent_with_overrides", ...} mapping. resources
entries are wire-format mappings (or
:class:~dashscope.agentstudio.types.Mount objects, which
serialize to the same mappings)::
client.sessions.create(
agent=agent_id,
resources=[
{"type": "memory_store", "memory_store_id": store_id,
"access": "read_write"},
{"type": "oss", "region": "cn-beijing", "bucket": "bkt",
"oss_path": "datasets/", "mount_path": "/data",
"access": "read_only"},
],
)
Source code in dashscope/applications/agentstudio/resources/sessions.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99 def create (
self ,
* ,
agent : Any ,
environment_id : Optional [ str ] = None ,
title : Optional [ str ] = None ,
resources : Optional [ Sequence [ ResourceInput ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
mcp_configs : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Session :
"""Create a session (``POST /sessions``).
``agent`` is the Agent id string or an
``{"type": "agent_with_overrides", ...}`` mapping. ``resources``
entries are wire-format mappings (or
:class:`~dashscope.agentstudio.types.Mount` objects, which
serialize to the same mappings)::
client.sessions.create(
agent=agent_id,
resources=[
{"type": "memory_store", "memory_store_id": store_id,
"access": "read_write"},
{"type": "oss", "region": "cn-beijing", "bucket": "bkt",
"oss_path": "datasets/", "mount_path": "/data",
"access": "read_only"},
],
)
"""
body = SessionCreateParams (
agent = agent ,
environment_id = environment_id ,
title = title ,
resources = resources ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
mcp_configs = mcp_configs ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_PATH_SESSIONS ,
json = body ,
)
return _coerce_session ( resp . data )
retrieve
retrieve ( session_id : str ) -> Session
Source code in dashscope/applications/agentstudio/resources/sessions.py
def retrieve ( self , session_id : str ) -> Session :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_SESSIONS } / { session_id } " ,
)
return _coerce_session ( resp . data )
update
update (
session_id : str ,
* ,
title : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
agent : Any = None ,
mcp_configs : Optional [
Sequence [ Mapping [ str , Any ]]
] = None
) -> Session
Source code in dashscope/applications/agentstudio/resources/sessions.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138 def update (
self ,
session_id : str ,
* ,
title : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
agent : Any = None ,
mcp_configs : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
) -> Session :
body = SessionUpdateParams (
title = title ,
metadata = metadata ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
agent = agent ,
mcp_configs = mcp_configs ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_SESSIONS } / { session_id } " ,
json = body ,
)
return _coerce_session ( resp . data )
list
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
agent_id : Optional [ str ] = None ,
statuses : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None
) -> CursorPage [ Session ]
Source code in dashscope/applications/agentstudio/resources/sessions.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
agent_id : Optional [ str ] = None ,
statuses : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
) -> CursorPage [ Session ]:
params = SessionListParams (
limit = limit ,
page = page ,
agent_id = agent_id ,
statuses = statuses ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_SESSIONS ,
params = params ,
)
def fetch_next ( nxt : str ) -> CursorPage [ Session ]:
return self . list (
limit = limit ,
page = nxt ,
agent_id = agent_id ,
statuses = statuses ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_session ,
request_id = resp . request_id ,
fetch_next = fetch_next ,
)
archive
archive ( session_id : str ) -> Session
Source code in dashscope/applications/agentstudio/resources/sessions.py
def archive ( self , session_id : str ) -> Session :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_SESSIONS } / { session_id } /archive" ,
)
return _coerce_session ( resp . data )
delete
delete ( session_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/sessions.py
def delete ( self , session_id : str ) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
f " { _PATH_SESSIONS } / { session_id } " ,
)
return DeleteResponse ( ** resp . data )
AsyncSessions
Async Session CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/sessions.py
def __init__ ( self , client ) -> None :
self . _client = client
self . events = AsyncSessionEvents ( client )
self . resources = AsyncSessionResources ( client )
self . threads = AsyncSessionThreads ( client )
events
instance-attribute
events = AsyncSessionEvents ( client )
resources
instance-attribute
resources = AsyncSessionResources ( client )
threads
instance-attribute
threads = AsyncSessionThreads ( client )
get
class-attribute
instance-attribute
call
class-attribute
instance-attribute
create
async
create (
* ,
agent : Any ,
environment_id : Optional [ str ] = None ,
title : Optional [ str ] = None ,
resources : Optional [ Sequence [ ResourceInput ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
mcp_configs : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Session
Create a session (POST /sessions).
agent is the Agent id string or an
{"type": "agent_with_overrides", ...} mapping. resources
entries are wire-format mappings (or
:class:~dashscope.agentstudio.types.Mount objects, which
serialize to the same mappings)::
client.sessions.create(
agent=agent_id,
resources=[
{"type": "memory_store", "memory_store_id": store_id,
"access": "read_write"},
{"type": "oss", "region": "cn-beijing", "bucket": "bkt",
"oss_path": "datasets/", "mount_path": "/data",
"access": "read_only"},
],
)
Source code in dashscope/applications/agentstudio/resources/sessions.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257 async def create (
self ,
* ,
agent : Any ,
environment_id : Optional [ str ] = None ,
title : Optional [ str ] = None ,
resources : Optional [ Sequence [ ResourceInput ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
mcp_configs : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Session :
"""Create a session (``POST /sessions``).
``agent`` is the Agent id string or an
``{"type": "agent_with_overrides", ...}`` mapping. ``resources``
entries are wire-format mappings (or
:class:`~dashscope.agentstudio.types.Mount` objects, which
serialize to the same mappings)::
client.sessions.create(
agent=agent_id,
resources=[
{"type": "memory_store", "memory_store_id": store_id,
"access": "read_write"},
{"type": "oss", "region": "cn-beijing", "bucket": "bkt",
"oss_path": "datasets/", "mount_path": "/data",
"access": "read_only"},
],
)
"""
body = SessionCreateParams (
agent = agent ,
environment_id = environment_id ,
title = title ,
resources = resources ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
mcp_configs = mcp_configs ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_SESSIONS ,
json = body ,
)
return _coerce_session ( resp . data )
retrieve
async
retrieve ( session_id : str ) -> Session
Source code in dashscope/applications/agentstudio/resources/sessions.py
async def retrieve ( self , session_id : str ) -> Session :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_SESSIONS } / { session_id } " ,
)
return _coerce_session ( resp . data )
update
async
update (
session_id : str ,
* ,
title : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
agent : Any = None ,
mcp_configs : Optional [
Sequence [ Mapping [ str , Any ]]
] = None
) -> Session
Source code in dashscope/applications/agentstudio/resources/sessions.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296 async def update (
self ,
session_id : str ,
* ,
title : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
agent : Any = None ,
mcp_configs : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
) -> Session :
body = SessionUpdateParams (
title = title ,
metadata = metadata ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
agent = agent ,
mcp_configs = mcp_configs ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_SESSIONS } / { session_id } " ,
json = body ,
)
return _coerce_session ( resp . data )
list
async
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
agent_id : Optional [ str ] = None ,
statuses : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None
) -> AsyncCursorPage [ Session ]
Source code in dashscope/applications/agentstudio/resources/sessions.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344 async def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
agent_id : Optional [ str ] = None ,
statuses : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
) -> AsyncCursorPage [ Session ]:
params = SessionListParams (
limit = limit ,
page = page ,
agent_id = agent_id ,
statuses = statuses ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_SESSIONS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ Session ]:
return await self . list (
limit = limit ,
page = nxt ,
agent_id = agent_id ,
statuses = statuses ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_session ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
archive
async
archive ( session_id : str ) -> Session
Source code in dashscope/applications/agentstudio/resources/sessions.py
async def archive ( self , session_id : str ) -> Session :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_SESSIONS } / { session_id } /archive" ,
)
return _coerce_session ( resp . data )
delete
async
delete ( session_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/sessions.py
async def delete ( self , session_id : str ) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_SESSIONS } / { session_id } " ,
)
return DeleteResponse ( ** resp . data )
SessionEvents
Session event send / list / stream.
Source code in dashscope/applications/agentstudio/resources/session_events.py
def __init__ ( self , client ) -> None :
self . _client = client
send
send (
session_id : str , events : Sequence [ Mapping [ str , Any ]]
) -> Dict [ str , Any ]
Send events to a session.
Source code in dashscope/applications/agentstudio/resources/session_events.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83 def send (
self ,
session_id : str ,
events : Sequence [ Mapping [ str , Any ]],
) -> Dict [ str , Any ]:
"""Send events to a session."""
if not events :
raise ValueError ( "events must contain at least 1 entry" )
body = SessionEventSendParams ( input = events ) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_events_path ( session_id ),
json = body ,
)
return resp . data
list
list (
session_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ ServerEvent ]
Source code in dashscope/applications/agentstudio/resources/session_events.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132 def list (
self ,
session_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ ServerEvent ]:
params = SessionEventListParams (
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_events_path ( session_id ),
params = params ,
)
def fetch_next ( nxt : str ) -> CursorPage [ ServerEvent ]:
return self . list (
session_id ,
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_event ,
request_id = resp . request_id ,
fetch_next = fetch_next ,
)
stream
stream (
session_id : str ,
* ,
event_deltas : Optional [ Sequence [ str ]] = None ,
timeout : Optional [ float ] = None
) -> "_TypedEventStream"
Open the SSE stream and return an iterator of typed events.
event_deltas opts into incremental streaming for the given event
types ("message" and/or "reasoning"; aliases "agent.message"
/ "agent.thinking"); anything else the server rejects. The stream is
read once, so text_deltas can be taken from it only; a second pass
raises rather than returning nothing. A chunk stream is not a reliable
source for final text: a reconnect replays only persisted events, so use
text_stream.
Source code in dashscope/applications/agentstudio/resources/session_events.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167 def stream (
self ,
session_id : str ,
* ,
event_deltas : Optional [ Sequence [ str ]] = None ,
timeout : Optional [ float ] = None ,
) -> "_TypedEventStream" :
"""Open the SSE stream and return an iterator of typed events.
``event_deltas`` opts into incremental streaming for the given event
types (``"message"`` and/or ``"reasoning"``; aliases ``"agent.message"``
/ ``"agent.thinking"``); anything else the server rejects. The stream is
read once, so ``text_deltas`` can be taken from it only; a second pass
raises rather than returning nothing. A chunk stream is not a reliable
source for final text: a reconnect replays only persisted events, so use
``text_stream``.
"""
params : Optional [ Dict [ str , Any ]] = None
if event_deltas :
params = { "event_deltas[]" : list ( event_deltas )}
resp = self . _client . transport . request (
"GET" ,
_stream_path ( session_id ),
extra_headers = { "Accept" : "text/event-stream" },
params = params ,
stream = True ,
timeout = timeout or AGENTSTUDIO_DEFAULT_TIMEOUT ,
)
return _TypedEventStream (
self . _client . _event_stream_cls (
response = resp ,
exceptions_module = self . _client . transport . exceptions ,
),
)
AsyncSessionEvents
AsyncSessionEvents ( client )
Async session event operations.
Source code in dashscope/applications/agentstudio/resources/session_events.py
def __init__ ( self , client ) -> None :
self . _client = client
send
async
send (
session_id : str , events : Sequence [ Mapping [ str , Any ]]
) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/session_events.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281 async def send (
self ,
session_id : str ,
events : Sequence [ Mapping [ str , Any ]],
) -> Dict [ str , Any ]:
if not events :
raise ValueError ( "events must contain at least 1 entry" )
body = SessionEventSendParams ( input = events ) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_events_path ( session_id ),
json = body ,
)
return resp . data
list
async
list (
session_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ ServerEvent ]
Source code in dashscope/applications/agentstudio/resources/session_events.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333 async def list (
self ,
session_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ ServerEvent ]:
params = SessionEventListParams (
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_events_path ( session_id ),
params = params ,
)
async def fetch_next (
nxt : str ,
) -> AsyncCursorPage [ ServerEvent ]:
return await self . list (
session_id ,
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_event ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
stream
async
stream (
session_id : str ,
* ,
event_deltas : Optional [ Sequence [ str ]] = None ,
timeout : Optional [ float ] = None
) -> "_AioTypedEventStream"
Source code in dashscope/applications/agentstudio/resources/session_events.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358 async def stream (
self ,
session_id : str ,
* ,
event_deltas : Optional [ Sequence [ str ]] = None ,
timeout : Optional [ float ] = None ,
) -> "_AioTypedEventStream" :
params : Optional [ Dict [ str , Any ]] = None
if event_deltas :
params = { "event_deltas[]" : list ( event_deltas )}
resp = await self . _client . transport . request (
"GET" ,
_stream_path ( session_id ),
extra_headers = { "Accept" : "text/event-stream" },
params = params ,
stream = True ,
timeout = timeout or AGENTSTUDIO_DEFAULT_TIMEOUT ,
)
return _AioTypedEventStream (
self . _client . _event_stream_cls (
response = resp ,
exceptions_module = self . _client . transport . exceptions ,
),
)
SessionThreads
Sub-agent threads within a session.
Source code in dashscope/applications/agentstudio/resources/session_threads.py
def __init__ ( self , client ) -> None :
self . _client = client
self . events = SessionThreadEvents ( client )
events
instance-attribute
events = SessionThreadEvents ( client )
get
class-attribute
instance-attribute
list
list (
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ SessionThread ]
Source code in dashscope/applications/agentstudio/resources/session_threads.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179 def list (
self ,
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ SessionThread ]:
params = SessionThreadListParams ( limit = limit , page = page ) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_session_threads_path ( session_id ),
params = params ,
)
def fetch_next ( token : str ) -> CursorPage [ SessionThread ]:
return self . list ( session_id , limit = limit , page = token )
return build_page (
payload = resp . data ,
item_factory = _coerce_session_thread ,
request_id = resp . request_id ,
fetch_next = fetch_next ,
)
retrieve
retrieve ( session_id : str , thread_id : str ) -> SessionThread
Source code in dashscope/applications/agentstudio/resources/session_threads.py
def retrieve ( self , session_id : str , thread_id : str ) -> SessionThread :
resp = self . _client . transport . request (
"GET" ,
_session_thread_item_path ( session_id , thread_id ),
)
return _coerce_session_thread ( resp . data )
archive
archive ( session_id : str , thread_id : str ) -> SessionThread
Source code in dashscope/applications/agentstudio/resources/session_threads.py
def archive ( self , session_id : str , thread_id : str ) -> SessionThread :
resp = self . _client . transport . request (
"POST" ,
_session_thread_archive_path ( session_id , thread_id ),
)
return _coerce_session_thread ( resp . data )
AsyncSessionThreads
AsyncSessionThreads ( client )
Async sub-agent threads within a session.
Source code in dashscope/applications/agentstudio/resources/session_threads.py
def __init__ ( self , client ) -> None :
self . _client = client
self . events = AsyncSessionThreadEvents ( client )
events
instance-attribute
events = AsyncSessionThreadEvents ( client )
get
class-attribute
instance-attribute
list
async
list (
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ SessionThread ]
Source code in dashscope/applications/agentstudio/resources/session_threads.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229 async def list (
self ,
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ SessionThread ]:
params = SessionThreadListParams ( limit = limit , page = page ) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_session_threads_path ( session_id ),
params = params ,
)
async def fetch_next ( token : str ) -> AsyncCursorPage [ SessionThread ]:
return await self . list ( session_id , limit = limit , page = token )
return build_page (
payload = resp . data ,
item_factory = _coerce_session_thread ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
retrieve
async
retrieve ( session_id : str , thread_id : str ) -> SessionThread
Source code in dashscope/applications/agentstudio/resources/session_threads.py
231
232
233
234
235
236
237
238
239
240 async def retrieve (
self ,
session_id : str ,
thread_id : str ,
) -> SessionThread :
resp = await self . _client . transport . request (
"GET" ,
_session_thread_item_path ( session_id , thread_id ),
)
return _coerce_session_thread ( resp . data )
archive
async
archive ( session_id : str , thread_id : str ) -> SessionThread
Source code in dashscope/applications/agentstudio/resources/session_threads.py
async def archive ( self , session_id : str , thread_id : str ) -> SessionThread :
resp = await self . _client . transport . request (
"POST" ,
_session_thread_archive_path ( session_id , thread_id ),
)
return _coerce_session_thread ( resp . data )
SessionThreadEvents
SessionThreadEvents ( client )
Events scoped to a single sub-agent thread (list only).
Source code in dashscope/applications/agentstudio/resources/session_threads.py
def __init__ ( self , client ) -> None :
self . _client = client
list
list (
session_id : str ,
thread_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ ServerEvent ]
Source code in dashscope/applications/agentstudio/resources/session_threads.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88 def list (
self ,
session_id : str ,
thread_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ ServerEvent ]:
params = SessionEventListParams (
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_session_thread_events_path ( session_id , thread_id ),
params = params ,
)
def fetch_next ( nxt : str ) -> CursorPage [ ServerEvent ]:
return self . list (
session_id ,
thread_id ,
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_event ,
request_id = resp . request_id ,
fetch_next = fetch_next ,
)
AsyncSessionThreadEvents
AsyncSessionThreadEvents ( client )
Async events scoped to a single sub-agent thread (list only).
Source code in dashscope/applications/agentstudio/resources/session_threads.py
def __init__ ( self , client ) -> None :
self . _client = client
list
async
list (
session_id : str ,
thread_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ ServerEvent ]
Source code in dashscope/applications/agentstudio/resources/session_threads.py
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147 async def list (
self ,
session_id : str ,
thread_id : str ,
* ,
types : Optional [ Sequence [ str ]] = None ,
created_at_gt : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lt : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
order : Optional [ str ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ ServerEvent ]:
params = SessionEventListParams (
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_session_thread_events_path ( session_id , thread_id ),
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ ServerEvent ]:
return await self . list (
session_id ,
thread_id ,
types = types ,
created_at_gt = created_at_gt ,
created_at_gte = created_at_gte ,
created_at_lt = created_at_lt ,
created_at_lte = created_at_lte ,
limit = limit ,
order = order ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_event ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
SessionResources
Runtime resource mount/unmount on a session.
Source code in dashscope/applications/agentstudio/resources/session_resources.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
add
add (
session_id : str ,
* ,
resource_type : str = "file" ,
file_id : str ,
mount_path : Optional [ str ] = None
) -> SessionResource
Mount a file into a running session (POST /sessions/{id}/resources).
mount_path must be an absolute path under /uploads/. The
returned file_id is the session-scoped copy id and may differ
from the source file_id passed in.
Source code in dashscope/applications/agentstudio/resources/session_resources.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 def add (
self ,
session_id : str ,
* ,
resource_type : str = "file" ,
file_id : str ,
mount_path : Optional [ str ] = None ,
) -> SessionResource :
"""Mount a file into a running session (``POST /sessions/{id}/resources``).
``mount_path`` must be an absolute path under ``/uploads/``. The
returned ``file_id`` is the session-scoped copy id and may differ
from the source ``file_id`` passed in.
"""
body = SessionResourceAddParams (
type = resource_type ,
file_id = file_id ,
mount_path = mount_path ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_session_resources_path ( session_id ),
json = body ,
)
return _coerce_session_resource ( resp . data )
retrieve
retrieve (
session_id : str , resource_id : str
) -> SessionResource
Source code in dashscope/applications/agentstudio/resources/session_resources.py
65
66
67
68
69
70
71
72
73
74 def retrieve (
self ,
session_id : str ,
resource_id : str ,
) -> SessionResource :
resp = self . _client . transport . request (
"GET" ,
_session_resource_item_path ( session_id , resource_id ),
)
return _coerce_session_resource ( resp . data )
list
list (
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ SessionResource ]
Source code in dashscope/applications/agentstudio/resources/session_resources.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101 def list (
self ,
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ SessionResource ]:
params = SessionResourceListParams ( limit = limit , page = page ) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_session_resources_path ( session_id ),
params = params ,
)
def fetch_next ( token : str ) -> CursorPage [ SessionResource ]:
return self . list ( session_id , limit = limit , page = token )
return build_page (
payload = resp . data ,
item_factory = _coerce_session_resource ,
request_id = resp . request_id ,
fetch_next = fetch_next ,
)
delete
delete ( session_id : str , resource_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/session_resources.py
103
104
105
106
107
108
109
110
111
112 def delete (
self ,
session_id : str ,
resource_id : str ,
) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
_session_resource_item_path ( session_id , resource_id ),
)
return DeleteResponse ( ** resp . data )
AsyncSessionResources
AsyncSessionResources ( client )
Async runtime resource mount/unmount on a session.
Source code in dashscope/applications/agentstudio/resources/session_resources.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
add
async
add (
session_id : str ,
* ,
resource_type : str = "file" ,
file_id : str ,
mount_path : Optional [ str ] = None
) -> SessionResource
Source code in dashscope/applications/agentstudio/resources/session_resources.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139 async def add (
self ,
session_id : str ,
* ,
resource_type : str = "file" ,
file_id : str ,
mount_path : Optional [ str ] = None ,
) -> SessionResource :
body = SessionResourceAddParams (
type = resource_type ,
file_id = file_id ,
mount_path = mount_path ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_session_resources_path ( session_id ),
json = body ,
)
return _coerce_session_resource ( resp . data )
retrieve
async
retrieve (
session_id : str , resource_id : str
) -> SessionResource
Source code in dashscope/applications/agentstudio/resources/session_resources.py
141
142
143
144
145
146
147
148
149
150 async def retrieve (
self ,
session_id : str ,
resource_id : str ,
) -> SessionResource :
resp = await self . _client . transport . request (
"GET" ,
_session_resource_item_path ( session_id , resource_id ),
)
return _coerce_session_resource ( resp . data )
list
async
list (
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ SessionResource ]
Source code in dashscope/applications/agentstudio/resources/session_resources.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178 async def list (
self ,
session_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ SessionResource ]:
params = SessionResourceListParams ( limit = limit , page = page ) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_session_resources_path ( session_id ),
params = params ,
)
async def fetch_next ( token : str ) -> AsyncCursorPage [ SessionResource ]:
return await self . list ( session_id , limit = limit , page = token )
return build_page (
payload = resp . data ,
item_factory = _coerce_session_resource ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
delete
async
delete ( session_id : str , resource_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/session_resources.py
180
181
182
183
184
185
186
187
188
189 async def delete (
self ,
session_id : str ,
resource_id : str ,
) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
_session_resource_item_path ( session_id , resource_id ),
)
return DeleteResponse ( ** resp . data )
Dynamic Workflows
client.dynamic_workflows creates, retrieves, updates, lists and archives
published JavaScript Workflow definitions. Use list_versions and
retrieve_version to read fixed published versions. Creation and updates
publish automatically; execution is initiated by Agent Workflow tools.
Configure inline creation with multiagent.workflows and fixed-version
reuse with multiagent.reuse_workflows on Agent creation or update.
Send all nested configuration you want to retain when updating an Agent;
new Sessions must use the returned Agent version.
Workflow updates preserve omitted fields. Pass description=None to clear
the description or input_schema=None (or {}) to clear input constraints.
An empty update does not publish a new version. Archived definitions remain
readable, including their published versions. list accepts limit, page
and include_archived; list_versions accepts limit and page. Both
return auto-paginating cursor pages. AsyncClient.dynamic_workflows
provides the same operations asynchronously.
See the Dynamic Workflow recipe
for a runnable lifecycle example and an Agent fixed-version binding example.
DynamicWorkflows
Manage published definitions; execution is initiated by Agent tools.
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
def __init__ ( self , client ) -> None :
self . _client = client
create
create (
* ,
name : str ,
script : str ,
description : Optional [ str ] = None ,
input_schema : Optional [ Mapping [ str , Any ]] = None
) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 def create (
self ,
* ,
name : str ,
script : str ,
description : Optional [ str ] = None ,
input_schema : Optional [ Mapping [ str , Any ]] = None ,
) -> DynamicWorkflow :
body = DynamicWorkflowCreateParams (
name = name ,
script = script ,
description = description ,
input_schema = input_schema ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_PATH_DYNAMIC_WORKFLOWS ,
json = body ,
)
return _coerce_dynamic_workflow ( resp . data )
retrieve
retrieve ( workflow_id : str ) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
def retrieve ( self , workflow_id : str ) -> DynamicWorkflow :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } " ,
)
return _coerce_dynamic_workflow ( resp . data )
update
update (
workflow_id : str ,
* ,
name : Optional [ str ] = None ,
script : Optional [ str ] = None ,
description : Any = _NOT_GIVEN ,
input_schema : Any = _NOT_GIVEN
) -> DynamicWorkflow
Omitted fields stay unchanged; None clears description or schema.
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85 def update (
self ,
workflow_id : str ,
* ,
name : Optional [ str ] = None ,
script : Optional [ str ] = None ,
description : Any = _NOT_GIVEN ,
input_schema : Any = _NOT_GIVEN ,
) -> DynamicWorkflow :
"""Omitted fields stay unchanged; None clears description or schema."""
body = DynamicWorkflowUpdateParams (
name = name ,
script = script ,
description = description ,
input_schema = input_schema ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } " ,
json = body ,
)
return _coerce_dynamic_workflow ( resp . data )
archive
archive ( workflow_id : str ) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
def archive ( self , workflow_id : str ) -> DynamicWorkflow :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } /archive" ,
)
return _coerce_dynamic_workflow ( resp . data )
list
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None
) -> CursorPage [ DynamicWorkflow ]
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
) -> CursorPage [ DynamicWorkflow ]:
params = DynamicWorkflowListParams (
limit = limit ,
page = page ,
include_archived = include_archived ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_DYNAMIC_WORKFLOWS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_dynamic_workflow ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
limit = limit ,
page = nxt ,
include_archived = include_archived ,
),
)
list_versions
list_versions (
workflow_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ DynamicWorkflow ]
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147 def list_versions (
self ,
workflow_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ DynamicWorkflow ]:
params = DynamicWorkflowVersionListParams (
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } /versions" ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_dynamic_workflow ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list_versions (
workflow_id ,
limit = limit ,
page = nxt ,
),
)
retrieve_version
retrieve_version (
workflow_id : str , version : int
) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
149
150
151
152
153
154
155
156
157
158 def retrieve_version (
self ,
workflow_id : str ,
version : int ,
) -> DynamicWorkflow :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } /versions/ { version } " ,
)
return _coerce_dynamic_workflow ( resp . data )
AsyncDynamicWorkflows
AsyncDynamicWorkflows ( client )
Async management of published definitions and fixed versions.
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
def __init__ ( self , client ) -> None :
self . _client = client
create
async
create (
* ,
name : str ,
script : str ,
description : Optional [ str ] = None ,
input_schema : Optional [ Mapping [ str , Any ]] = None
) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186 async def create (
self ,
* ,
name : str ,
script : str ,
description : Optional [ str ] = None ,
input_schema : Optional [ Mapping [ str , Any ]] = None ,
) -> DynamicWorkflow :
body = DynamicWorkflowCreateParams (
name = name ,
script = script ,
description = description ,
input_schema = input_schema ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_DYNAMIC_WORKFLOWS ,
json = body ,
)
return _coerce_dynamic_workflow ( resp . data )
retrieve
async
retrieve ( workflow_id : str ) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
async def retrieve ( self , workflow_id : str ) -> DynamicWorkflow :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } " ,
)
return _coerce_dynamic_workflow ( resp . data )
update
async
update (
workflow_id : str ,
* ,
name : Optional [ str ] = None ,
script : Optional [ str ] = None ,
description : Any = _NOT_GIVEN ,
input_schema : Any = _NOT_GIVEN
) -> DynamicWorkflow
Omitted fields stay unchanged; None clears description or schema.
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216 async def update (
self ,
workflow_id : str ,
* ,
name : Optional [ str ] = None ,
script : Optional [ str ] = None ,
description : Any = _NOT_GIVEN ,
input_schema : Any = _NOT_GIVEN ,
) -> DynamicWorkflow :
"""Omitted fields stay unchanged; None clears description or schema."""
body = DynamicWorkflowUpdateParams (
name = name ,
script = script ,
description = description ,
input_schema = input_schema ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } " ,
json = body ,
)
return _coerce_dynamic_workflow ( resp . data )
archive
async
archive ( workflow_id : str ) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
async def archive ( self , workflow_id : str ) -> DynamicWorkflow :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } /archive" ,
)
return _coerce_dynamic_workflow ( resp . data )
list
async
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None
) -> AsyncCursorPage [ DynamicWorkflow ]
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256 async def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
) -> AsyncCursorPage [ DynamicWorkflow ]:
params = DynamicWorkflowListParams (
limit = limit ,
page = page ,
include_archived = include_archived ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_DYNAMIC_WORKFLOWS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ DynamicWorkflow ]:
return await self . list (
limit = limit ,
page = nxt ,
include_archived = include_archived ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_dynamic_workflow ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
list_versions
async
list_versions (
workflow_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ DynamicWorkflow ]
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284 async def list_versions (
self ,
workflow_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ DynamicWorkflow ]:
params = DynamicWorkflowVersionListParams (
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } /versions" ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ DynamicWorkflow ]:
return await self . list_versions ( workflow_id , limit = limit , page = nxt )
return build_page (
payload = resp . data ,
item_factory = _coerce_dynamic_workflow ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
retrieve_version
async
retrieve_version (
workflow_id : str , version : int
) -> DynamicWorkflow
Source code in dashscope/applications/agentstudio/resources/dynamic_workflows.py
286
287
288
289
290
291
292
293
294
295 async def retrieve_version (
self ,
workflow_id : str ,
version : int ,
) -> DynamicWorkflow :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_DYNAMIC_WORKFLOWS } / { workflow_id } /versions/ { version } " ,
)
return _coerce_dynamic_workflow ( resp . data )
Environments & deployments
Environments
Environment CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/environments.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
create (
* ,
name : str ,
config : Mapping [ str , Any ],
description : Optional [ str ] = None ,
scope : Optional [ str ] = "organization" ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None
) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 def create (
self ,
* ,
name : str ,
config : Mapping [ str , Any ],
description : Optional [ str ] = None ,
scope : Optional [ str ] = "organization" ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None ,
) -> Environment :
body = EnvironmentCreateParams (
name = name ,
config = config ,
description = description ,
scope = scope ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_PATH_ENVIRONMENTS ,
json = body ,
extra_headers = extra_headers ,
)
return _coerce_env ( resp . data )
retrieve
retrieve ( environment_id : str ) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
def retrieve ( self , environment_id : str ) -> Environment :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } " ,
)
return _coerce_env ( resp . data )
update
update (
environment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
config : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92 def update (
self ,
environment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
config : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Environment :
body = EnvironmentUpdateParams (
name = name ,
description = description ,
config = config ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } " ,
json = body ,
)
return _coerce_env ( resp . data )
list
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None
) -> CursorPage [ Environment ]
Source code in dashscope/applications/agentstudio/resources/environments.py
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
) -> CursorPage [ Environment ]:
params = EnvironmentListParams (
limit = limit ,
page = page ,
include_archived = include_archived ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_ENVIRONMENTS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_env ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
limit = limit ,
page = nxt ,
include_archived = include_archived ,
),
)
archive
archive ( environment_id : str ) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
def archive ( self , environment_id : str ) -> Environment :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } /archive" ,
)
return _coerce_env ( resp . data )
delete
delete ( environment_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/environments.py
def delete ( self , environment_id : str ) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } " ,
)
return DeleteResponse ( ** resp . data )
AsyncEnvironments
AsyncEnvironments ( client )
Async Environment CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/environments.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
async
create (
* ,
name : str ,
config : Mapping [ str , Any ],
description : Optional [ str ] = None ,
scope : Optional [ str ] = "organization" ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None
) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 async def create (
self ,
* ,
name : str ,
config : Mapping [ str , Any ],
description : Optional [ str ] = None ,
scope : Optional [ str ] = "organization" ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None ,
) -> Environment :
body = EnvironmentCreateParams (
name = name ,
config = config ,
description = description ,
scope = scope ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_ENVIRONMENTS ,
json = body ,
extra_headers = extra_headers ,
)
return _coerce_env ( resp . data )
retrieve
async
retrieve ( environment_id : str ) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
async def retrieve ( self , environment_id : str ) -> Environment :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } " ,
)
return _coerce_env ( resp . data )
update
async
update (
environment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
config : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198 async def update (
self ,
environment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
config : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Environment :
body = EnvironmentUpdateParams (
name = name ,
description = description ,
config = config ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } " ,
json = body ,
)
return _coerce_env ( resp . data )
list
async
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None
) -> AsyncCursorPage [ Environment ]
Source code in dashscope/applications/agentstudio/resources/environments.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231 async def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
) -> AsyncCursorPage [ Environment ]:
params = EnvironmentListParams (
limit = limit ,
page = page ,
include_archived = include_archived ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_ENVIRONMENTS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ Environment ]:
return await self . list (
limit = limit ,
page = nxt ,
include_archived = include_archived ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_env ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
archive
async
archive ( environment_id : str ) -> Environment
Source code in dashscope/applications/agentstudio/resources/environments.py
async def archive ( self , environment_id : str ) -> Environment :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } /archive" ,
)
return _coerce_env ( resp . data )
delete
async
delete ( environment_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/environments.py
async def delete ( self , environment_id : str ) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_ENVIRONMENTS } / { environment_id } " ,
)
return DeleteResponse ( ** resp . data )
Deployments
Managed Agent deployment lifecycle and execution.
Source code in dashscope/applications/agentstudio/resources/deployments.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
create (
* ,
name : str ,
agent : Any ,
initial_events : Sequence [ Mapping [ str , Any ]],
description : Optional [ str ] = None ,
environment_id : Optional [ str ] = None ,
schedule : Any = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
metadata : Optional [ Mapping [ str , str ]] = None
) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 def create (
self ,
* ,
name : str ,
agent : Any ,
initial_events : Sequence [ Mapping [ str , Any ]],
description : Optional [ str ] = None ,
environment_id : Optional [ str ] = None ,
schedule : Any = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
metadata : Optional [ Mapping [ str , str ]] = None ,
) -> Deployment :
body = DeploymentCreateParams (
name = name ,
agent = agent ,
initial_events = initial_events ,
description = description ,
environment_id = environment_id ,
schedule = schedule ,
resources = resources ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_PATH_DEPLOYMENTS ,
json = body ,
)
return _coerce_deployment ( resp . data )
retrieve
retrieve ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
def retrieve ( self , deployment_id : str ) -> Deployment :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } " ,
)
return _coerce_deployment ( resp . data )
update
update (
deployment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
agent : Any = None ,
environment_id : Any = _NOT_GIVEN ,
schedule : Any = _NOT_GIVEN ,
initial_events : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
metadata : Optional [ Mapping [ str , str ]] = None
) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111 def update (
self ,
deployment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
agent : Any = None ,
environment_id : Any = _NOT_GIVEN ,
schedule : Any = _NOT_GIVEN ,
initial_events : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
metadata : Optional [ Mapping [ str , str ]] = None ,
) -> Deployment :
body = DeploymentUpdateParams (
name = name ,
description = description ,
agent = agent ,
environment_id = environment_id ,
schedule = schedule ,
initial_events = initial_events ,
resources = resources ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } " ,
json = body ,
)
return _coerce_deployment ( resp . data )
list
list (
* ,
agent_id : Optional [ str ] = None ,
keyword : Optional [ str ] = None ,
status : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None
) -> CursorPage [ Deployment ]
Source code in dashscope/applications/agentstudio/resources/deployments.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154 def list (
self ,
* ,
agent_id : Optional [ str ] = None ,
keyword : Optional [ str ] = None ,
status : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
) -> CursorPage [ Deployment ]:
params = DeploymentListParams (
agent_id = agent_id ,
keyword = keyword ,
status = status ,
include_archived = include_archived ,
limit = limit ,
page = page ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_DEPLOYMENTS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_deployment ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
agent_id = agent_id ,
keyword = keyword ,
status = status ,
include_archived = include_archived ,
limit = limit ,
page = nxt ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
),
)
pause
pause ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
def pause ( self , deployment_id : str ) -> Deployment :
return self . _lifecycle ( deployment_id , "pause" )
unpause
unpause ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
def unpause ( self , deployment_id : str ) -> Deployment :
return self . _lifecycle ( deployment_id , "unpause" )
archive
archive ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
def archive ( self , deployment_id : str ) -> Deployment :
return self . _lifecycle ( deployment_id , "archive" )
run
run ( deployment_id : str ) -> DeploymentRun
Source code in dashscope/applications/agentstudio/resources/deployments.py
def run ( self , deployment_id : str ) -> DeploymentRun :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } /run" ,
)
return _coerce_deployment_run ( resp . data )
list_runs
list_runs (
deployment_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ DeploymentRun ]
Source code in dashscope/applications/agentstudio/resources/deployments.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201 def list_runs (
self ,
deployment_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ DeploymentRun ]:
params = DeploymentRunListParams ( limit = limit , page = page ) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } /runs" ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_deployment_run ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list_runs (
deployment_id ,
limit = limit ,
page = nxt ,
),
)
AsyncDeployments
Asynchronous Managed Agent deployment lifecycle and execution.
Source code in dashscope/applications/agentstudio/resources/deployments.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
async
create (
* ,
name : str ,
agent : Any ,
initial_events : Sequence [ Mapping [ str , Any ]],
description : Optional [ str ] = None ,
environment_id : Optional [ str ] = None ,
schedule : Any = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
metadata : Optional [ Mapping [ str , str ]] = None
) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276 async def create (
self ,
* ,
name : str ,
agent : Any ,
initial_events : Sequence [ Mapping [ str , Any ]],
description : Optional [ str ] = None ,
environment_id : Optional [ str ] = None ,
schedule : Any = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
metadata : Optional [ Mapping [ str , str ]] = None ,
) -> Deployment :
body = DeploymentCreateParams (
name = name ,
agent = agent ,
initial_events = initial_events ,
description = description ,
environment_id = environment_id ,
schedule = schedule ,
resources = resources ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_DEPLOYMENTS ,
json = body ,
)
return _coerce_deployment ( resp . data )
retrieve
async
retrieve ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
async def retrieve ( self , deployment_id : str ) -> Deployment :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } " ,
)
return _coerce_deployment ( resp . data )
update
async
update (
deployment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
agent : Any = None ,
environment_id : Any = _NOT_GIVEN ,
schedule : Any = _NOT_GIVEN ,
initial_events : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
metadata : Optional [ Mapping [ str , str ]] = None
) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319 async def update (
self ,
deployment_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
agent : Any = None ,
environment_id : Any = _NOT_GIVEN ,
schedule : Any = _NOT_GIVEN ,
initial_events : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
metadata : Optional [ Mapping [ str , str ]] = None ,
) -> Deployment :
body = DeploymentUpdateParams (
name = name ,
description = description ,
agent = agent ,
environment_id = environment_id ,
schedule = schedule ,
initial_events = initial_events ,
resources = resources ,
vault_ids = vault_ids ,
environment_variables = environment_variables ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } " ,
json = body ,
)
return _coerce_deployment ( resp . data )
list
async
list (
* ,
agent_id : Optional [ str ] = None ,
keyword : Optional [ str ] = None ,
status : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None
) -> AsyncCursorPage [ Deployment ]
Source code in dashscope/applications/agentstudio/resources/deployments.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367 async def list (
self ,
* ,
agent_id : Optional [ str ] = None ,
keyword : Optional [ str ] = None ,
status : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
) -> AsyncCursorPage [ Deployment ]:
params = DeploymentListParams (
agent_id = agent_id ,
keyword = keyword ,
status = status ,
include_archived = include_archived ,
limit = limit ,
page = page ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_DEPLOYMENTS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ Deployment ]:
return await self . list (
agent_id = agent_id ,
keyword = keyword ,
status = status ,
include_archived = include_archived ,
limit = limit ,
page = nxt ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_deployment ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
pause
async
pause ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
async def pause ( self , deployment_id : str ) -> Deployment :
return await self . _lifecycle ( deployment_id , "pause" )
unpause
async
unpause ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
async def unpause ( self , deployment_id : str ) -> Deployment :
return await self . _lifecycle ( deployment_id , "unpause" )
archive
async
archive ( deployment_id : str ) -> Deployment
Source code in dashscope/applications/agentstudio/resources/deployments.py
async def archive ( self , deployment_id : str ) -> Deployment :
return await self . _lifecycle ( deployment_id , "archive" )
run
async
run ( deployment_id : str ) -> DeploymentRun
Source code in dashscope/applications/agentstudio/resources/deployments.py
async def run ( self , deployment_id : str ) -> DeploymentRun :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } /run" ,
)
return _coerce_deployment_run ( resp . data )
list_runs
async
list_runs (
deployment_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ DeploymentRun ]
Source code in dashscope/applications/agentstudio/resources/deployments.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423 async def list_runs (
self ,
deployment_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ DeploymentRun ]:
params = DeploymentRunListParams ( limit = limit , page = page ) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_DEPLOYMENTS } / { deployment_id } /runs" ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ DeploymentRun ]:
return await self . list_runs (
deployment_id ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_deployment_run ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
DeploymentRuns
Workspace-wide deployment run history.
Source code in dashscope/applications/agentstudio/resources/deployments.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
retrieve
retrieve ( deployment_run_id : str ) -> DeploymentRun
Source code in dashscope/applications/agentstudio/resources/deployments.py
def retrieve ( self , deployment_run_id : str ) -> DeploymentRun :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_DEPLOYMENT_RUNS } / { deployment_run_id } " ,
)
return _coerce_deployment_run ( resp . data )
list
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ DeploymentRun ]
Source code in dashscope/applications/agentstudio/resources/deployments.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236 def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ DeploymentRun ]:
params = DeploymentRunListParams ( limit = limit , page = page ) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_DEPLOYMENT_RUNS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_deployment_run ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list ( limit = limit , page = nxt ),
)
AsyncDeploymentRuns
AsyncDeploymentRuns ( client )
Asynchronous workspace-wide deployment run history.
Source code in dashscope/applications/agentstudio/resources/deployments.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
retrieve
async
retrieve ( deployment_run_id : str ) -> DeploymentRun
Source code in dashscope/applications/agentstudio/resources/deployments.py
async def retrieve ( self , deployment_run_id : str ) -> DeploymentRun :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_DEPLOYMENT_RUNS } / { deployment_run_id } " ,
)
return _coerce_deployment_run ( resp . data )
list
async
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ DeploymentRun ]
Source code in dashscope/applications/agentstudio/resources/deployments.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463 async def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ DeploymentRun ]:
params = DeploymentRunListParams ( limit = limit , page = page ) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_DEPLOYMENT_RUNS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ DeploymentRun ]:
return await self . list ( limit = limit , page = nxt )
return build_page (
payload = resp . data ,
item_factory = _coerce_deployment_run ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
Files
Files
File upload / download / list / delete.
Source code in dashscope/applications/agentstudio/resources/files.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
upload
upload (
file : Union [
str ,
"os.PathLike[str]" ,
BinaryIO ,
Tuple [ str , BinaryIO ],
],
* ,
mime_type : Optional [ str ] = None ,
progress : Optional [ ProgressCallback ] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None
) -> File
Source code in dashscope/applications/agentstudio/resources/files.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178 def upload (
self ,
file : Union [ str , "os.PathLike[str]" , BinaryIO , Tuple [ str , BinaryIO ]],
* ,
mime_type : Optional [ str ] = None ,
progress : Optional [ ProgressCallback ] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None ,
) -> File :
filename , fileobj , must_close = _open_file ( file )
try :
payload_obj : Any
if progress is not None :
size = _file_size ( fileobj )
if size > 0 :
payload_obj = _ProgressFile ( fileobj , size , progress )
else :
payload_obj = fileobj
else :
payload_obj = fileobj
multipart : Dict [ str , Any ] = {
"file" : (
filename ,
payload_obj ,
mime_type or "application/octet-stream" ,
),
}
resp = self . _client . transport . request (
"POST" ,
_PATH_FILES ,
files = multipart ,
extra_headers = extra_headers ,
)
return _coerce_file ( resp . data )
finally :
if must_close :
try :
fileobj . close ()
except Exception :
pass
retrieve
retrieve ( file_id : str ) -> File
Source code in dashscope/applications/agentstudio/resources/files.py
def retrieve ( self , file_id : str ) -> File :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_FILES } / { file_id } " ,
)
return _coerce_file ( resp . data )
download
download (
file_id : str , * , timeout : Optional [ float ] = None
) -> FileContent
Return the file content as a :class:FileContent.
Only files whose downloadable flag is true can be fetched; the
service answers 403 otherwise. Use :meth:FileContent.write_to_file
to persist the bytes to disk.
content = client.files.download("file_xxx")
content.write_to_file("output.txt")
Source code in dashscope/applications/agentstudio/resources/files.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220 def download (
self ,
file_id : str ,
* ,
timeout : Optional [ float ] = None ,
) -> FileContent :
"""Return the file content as a :class:`FileContent`.
Only files whose ``downloadable`` flag is true can be fetched; the
service answers 403 otherwise. Use :meth:`FileContent.write_to_file`
to persist the bytes to disk.
content = client.files.download("file_xxx")
content.write_to_file("output.txt")
"""
resp = self . _open_content ( file_id , timeout )
try :
resp . read ()
return FileContent ( resp . content )
finally :
resp . close ()
list
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
scope_id : Optional [ str ] = None
) -> CursorPage [ File ]
Source code in dashscope/applications/agentstudio/resources/files.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253 def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
scope_id : Optional [ str ] = None ,
) -> CursorPage [ File ]:
params = FileListParams (
limit = limit ,
page = page ,
scope_id = scope_id ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_FILES ,
params = params ,
)
def fetch_next ( token : str ) -> CursorPage [ File ]:
return self . list (
limit = limit ,
page = token ,
scope_id = scope_id ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_file ,
request_id = resp . request_id ,
page_cls = CursorPage ,
fetch_next = fetch_next ,
)
delete
delete ( file_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/files.py
def delete ( self , file_id : str ) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
f " { _PATH_FILES } / { file_id } " ,
)
return DeleteResponse ( ** resp . data )
AsyncFiles
Async file upload / download / list / delete.
Source code in dashscope/applications/agentstudio/resources/files.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
upload
async
upload (
file : Union [
str ,
"os.PathLike[str]" ,
BinaryIO ,
Tuple [ str , BinaryIO ],
],
* ,
mime_type : Optional [ str ] = None ,
progress : Optional [ ProgressCallback ] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None
) -> File
Source code in dashscope/applications/agentstudio/resources/files.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307 async def upload (
self ,
file : Union [ str , "os.PathLike[str]" , BinaryIO , Tuple [ str , BinaryIO ]],
* ,
mime_type : Optional [ str ] = None ,
progress : Optional [ ProgressCallback ] = None ,
extra_headers : Optional [ Mapping [ str , str ]] = None ,
) -> File :
filename , fileobj , must_close = _open_file ( file )
try :
payload_obj : Any
if progress is not None :
size = _file_size ( fileobj )
if size > 0 :
payload_obj = _ProgressFile ( fileobj , size , progress )
else :
payload_obj = fileobj
else :
payload_obj = fileobj
multipart : Dict [ str , Any ] = {
"file" : (
filename ,
payload_obj ,
mime_type or "application/octet-stream" ,
),
}
resp = await self . _client . transport . request (
"POST" ,
_PATH_FILES ,
files = multipart ,
extra_headers = extra_headers ,
)
return _coerce_file ( resp . data )
finally :
if must_close :
try :
fileobj . close ()
except Exception :
pass
retrieve
async
retrieve ( file_id : str ) -> File
Source code in dashscope/applications/agentstudio/resources/files.py
async def retrieve ( self , file_id : str ) -> File :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_FILES } / { file_id } " ,
)
return _coerce_file ( resp . data )
download
async
download (
file_id : str , * , timeout : Optional [ float ] = None
) -> FileContent
Return the file content as a :class:FileContent.
Only files whose downloadable flag is true can be fetched; the
service answers 403 otherwise. Use :meth:FileContent.write_to_file
to persist the bytes to disk.
content = await client.files.download("file_xxx")
content.write_to_file("output.txt")
Source code in dashscope/applications/agentstudio/resources/files.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349 async def download (
self ,
file_id : str ,
* ,
timeout : Optional [ float ] = None ,
) -> FileContent :
"""Return the file content as a :class:`FileContent`.
Only files whose ``downloadable`` flag is true can be fetched; the
service answers 403 otherwise. Use :meth:`FileContent.write_to_file`
to persist the bytes to disk.
content = await client.files.download("file_xxx")
content.write_to_file("output.txt")
"""
resp = await self . _open_content ( file_id , timeout )
try :
await resp . aread ()
return FileContent ( resp . content )
finally :
await resp . aclose ()
list
async
list (
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
scope_id : Optional [ str ] = None
) -> AsyncCursorPage [ File ]
Source code in dashscope/applications/agentstudio/resources/files.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382 async def list (
self ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
scope_id : Optional [ str ] = None ,
) -> AsyncCursorPage [ File ]:
params = FileListParams (
limit = limit ,
page = page ,
scope_id = scope_id ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_FILES ,
params = params ,
)
async def fetch_next ( token : str ) -> AsyncCursorPage [ File ]:
return await self . list (
limit = limit ,
page = token ,
scope_id = scope_id ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_file ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
delete
async
delete ( file_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/files.py
async def delete ( self , file_id : str ) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_FILES } / { file_id } " ,
)
return DeleteResponse ( ** resp . data )
FileContent
Bases: bytes
Binary content of a downloaded file.
A bytes subclass so it drops into any code expecting raw bytes,
with a :meth:write_to_file helper that mirrors the Anthropic SDK
(client.beta.files.download(...).write_to_file(path)).
write_to_file
write_to_file ( path : Union [ str , 'os.PathLike[str]' ]) -> Path
Write the content to path and return it.
Missing parent directories are created.
Source code in dashscope/applications/agentstudio/resources/files.py
47
48
49
50
51
52
53
54
55
56
57
58 def write_to_file (
self ,
path : Union [ str , "os.PathLike[str]" ],
) -> Path :
"""Write the content to ``path`` and return it.
Missing parent directories are created.
"""
dest = Path ( os . fspath ( path ))
dest . parent . mkdir ( parents = True , exist_ok = True )
dest . write_bytes ( self )
return dest
Memory
MemoryStores
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def __init__ ( self , client ) -> None :
self . _client = client
self . memories = Memories ( client )
self . memory_versions = MemoryVersions ( client )
memories
instance-attribute
memories = Memories ( client )
memory_versions
instance-attribute
memory_versions = MemoryVersions ( client )
get
class-attribute
instance-attribute
create
create (
* ,
name : str ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> MemoryStore
Create a memory store (POST /memory_stores).
description is passed to the agent so it knows what the
store contains — write it for the model, not for humans.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386 def create (
self ,
* ,
name : str ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> MemoryStore :
"""Create a memory store (``POST /memory_stores``).
``description`` is passed to the agent so it knows what the
store contains — write it for the model, not for humans.
"""
body = MemoryStoreCreateParams (
name = name ,
description = description ,
metadata = dict ( metadata ) if metadata is not None else None ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_memory_stores_path (),
json = body ,
)
return _coerce_memory_store ( resp . data )
retrieve
retrieve ( store_id : str ) -> MemoryStore
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def retrieve ( self , store_id : str ) -> MemoryStore :
resp = self . _client . transport . request (
"GET" ,
_memory_store_item_path ( store_id ),
)
return _coerce_memory_store ( resp . data )
update
update (
store_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> MemoryStore
Update a store (POST /memory_stores/{store_id}).
Mutate name / description / metadata — at least one
must be given. metadata is replaced wholesale (unlike
CMA's merge-patch): keys not included in the request are
dropped; a key set to null deletes it.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427 def update (
self ,
store_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> MemoryStore :
"""Update a store (``POST /memory_stores/{store_id}``).
Mutate ``name`` / ``description`` / ``metadata`` — at least one
must be given. ``metadata`` is **replaced wholesale** (unlike
CMA's merge-patch): keys not included in the request are
dropped; a key set to ``null`` deletes it.
"""
if name is None and description is None and metadata is None :
raise TypeError (
"memory_stores.update() requires at least one of "
"'name', 'description' or 'metadata'" ,
)
body = MemoryStoreUpdateParams (
name = name ,
description = description ,
metadata = dict ( metadata ) if metadata is not None else None ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_memory_store_item_path ( store_id ),
json = body ,
)
return _coerce_memory_store ( resp . data )
list
list (
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ MemoryStore ]
List stores (GET /memory_stores).
The public API has no keyword filter (that is a
console-only capability).
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460 def list (
self ,
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ MemoryStore ]:
"""List stores (``GET /memory_stores``).
The public API has no ``keyword`` filter (that is a
console-only capability).
"""
params = MemoryStoreListParams (
include_archived = include_archived ,
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_memory_stores_path (),
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_memory_store ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
include_archived = include_archived ,
limit = limit ,
page = nxt ,
),
)
delete
delete ( store_id : str ) -> DeleteResponse
Delete a store (DELETE /memory_stores/{id}).
Accepted immediately; items are removed asynchronously. The
response is a marker (type="memory_store_deleted").
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
462
463
464
465
466
467
468
469
470
471
472 def delete ( self , store_id : str ) -> DeleteResponse :
"""Delete a store (``DELETE /memory_stores/{id}``).
Accepted immediately; items are removed asynchronously. The
response is a marker (``type="memory_store_deleted"``).
"""
resp = self . _client . transport . request (
"DELETE" ,
_memory_store_item_path ( store_id ),
)
return DeleteResponse ( ** resp . data )
archive
archive ( store_id : str ) -> MemoryStore
Archive a store (POST /memory_stores/{id}/archive).
Read-only afterwards: existing session attachments continue,
new sessions cannot reference it. Irreversible.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
474
475
476
477
478
479
480
481
482
483
484 def archive ( self , store_id : str ) -> MemoryStore :
"""Archive a store (``POST /memory_stores/{id}/archive``).
Read-only afterwards: existing session attachments continue,
new sessions cannot reference it. Irreversible.
"""
resp = self . _client . transport . request (
"POST" ,
_memory_store_archive_path ( store_id ),
)
return _coerce_memory_store ( resp . data )
AsyncMemoryStores
AsyncMemoryStores ( client )
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def __init__ ( self , client ) -> None :
self . _client = client
self . memories = AsyncMemories ( client )
self . memory_versions = AsyncMemoryVersions ( client )
memories
instance-attribute
memories = AsyncMemories ( client )
memory_versions
instance-attribute
memory_versions = AsyncMemoryVersions ( client )
get
class-attribute
instance-attribute
create
async
create (
* ,
name : str ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> MemoryStore
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709 async def create (
self ,
* ,
name : str ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> MemoryStore :
body = MemoryStoreCreateParams (
name = name ,
description = description ,
metadata = dict ( metadata ) if metadata is not None else None ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_memory_stores_path (),
json = body ,
)
return _coerce_memory_store ( resp . data )
retrieve
async
retrieve ( store_id : str ) -> MemoryStore
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
async def retrieve ( self , store_id : str ) -> MemoryStore :
resp = await self . _client . transport . request (
"GET" ,
_memory_store_item_path ( store_id ),
)
return _coerce_memory_store ( resp . data )
update
async
update (
store_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> MemoryStore
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743 async def update (
self ,
store_id : str ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> MemoryStore :
if name is None and description is None and metadata is None :
raise TypeError (
"memory_stores.update() requires at least one of "
"'name', 'description' or 'metadata'" ,
)
body = MemoryStoreUpdateParams (
name = name ,
description = description ,
metadata = dict ( metadata ) if metadata is not None else None ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_memory_store_item_path ( store_id ),
json = body ,
)
return _coerce_memory_store ( resp . data )
list
async
list (
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ MemoryStore ]
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776 async def list (
self ,
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ MemoryStore ]:
params = MemoryStoreListParams (
include_archived = include_archived ,
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_memory_stores_path (),
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ MemoryStore ]:
return await self . list (
include_archived = include_archived ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_memory_store ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
delete
async
delete ( store_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
async def delete ( self , store_id : str ) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
_memory_store_item_path ( store_id ),
)
return DeleteResponse ( ** resp . data )
archive
async
archive ( store_id : str ) -> MemoryStore
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
async def archive ( self , store_id : str ) -> MemoryStore :
resp = await self . _client . transport . request (
"POST" ,
_memory_store_archive_path ( store_id ),
)
return _coerce_memory_store ( resp . data )
Memories
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
create ( store_id : str , * , path : str , content : str ) -> Memory
Create a memory at path (POST .../memories).
A memory already existing at path returns 409
memory_path_conflict_error.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141 def create (
self ,
store_id : str ,
* ,
path : str ,
content : str ,
) -> Memory :
"""Create a memory at ``path`` (``POST .../memories``).
A memory already existing at ``path`` returns 409
``memory_path_conflict_error``.
"""
body = MemoryCreateParams ( path = path , content = content ) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_memories_path ( store_id ),
json = body ,
)
return _coerce_memory ( resp . data )
list
list (
store_id : str ,
* ,
path_prefix : Optional [ str ] = None ,
depth : Optional [ int ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ Memory ]
List memories (GET .../memories).
path_prefix scopes the listing (server-validated: must
start and end with / — segment-aligned, so /notes/
matches /notes/a.md but not /notes_backup/old.md; a
bare "/" lists the whole store). File items land in
data; directory nodes come back as page.prefixes
(per page; merge across pages manually for a full tree).
view="full" includes content per item but caps
limit at 20 — the backend rejects higher values with
400 (CMA silently clamps); the default "basic" returns
metadata only with limit up to 100.
depth bounds the tree walk below path_prefix; the
backend implements 0/1 natively and larger values are derived
client-side (see _MAX_WIRE_DEPTH). With view="full" the
derivation still transfers the content of files the depth cut
discards — prefer view="basic" for deep walks.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201 def list (
self ,
store_id : str ,
* ,
path_prefix : Optional [ str ] = None ,
depth : Optional [ int ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ Memory ]:
"""List memories (``GET .../memories``).
``path_prefix`` scopes the listing (server-validated: must
start and end with ``/`` — segment-aligned, so ``/notes/``
matches ``/notes/a.md`` but not ``/notes_backup/old.md``; a
bare ``"/"`` lists the whole store). File items land in
``data``; directory nodes come back as ``page.prefixes``
(per page; merge across pages manually for a full tree).
``view="full"`` includes ``content`` per item but caps
``limit`` at 20 — the backend rejects higher values with
400 (CMA silently clamps); the default ``"basic"`` returns
metadata only with ``limit`` up to 100.
``depth`` bounds the tree walk below ``path_prefix``; the
backend implements 0/1 natively and larger values are derived
client-side (see ``_MAX_WIRE_DEPTH``). With ``view="full"`` the
derivation still transfers the content of files the depth cut
discards — prefer ``view="basic"`` for deep walks.
"""
depth_emulated = depth is not None and depth > _MAX_WIRE_DEPTH
wire_depth = None if depth_emulated else depth
params = MemoryListParams (
path_prefix = path_prefix ,
depth = wire_depth ,
view = view ,
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_memories_path ( store_id ),
params = params ,
)
result = build_page (
payload = resp . data ,
item_factory = _coerce_memory ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
store_id ,
path_prefix = path_prefix ,
depth = depth ,
view = view ,
limit = limit ,
page = nxt ,
),
)
if depth_emulated :
result = _apply_depth_emulation ( result , depth , path_prefix )
return result
retrieve
retrieve ( store_id : str , memory_id : str ) -> Memory
Retrieve a memory with content (GET .../memories/{id}).
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
203
204
205
206
207
208
209
210
211
212
213 def retrieve (
self ,
store_id : str ,
memory_id : str ,
) -> Memory :
"""Retrieve a memory with content (``GET .../memories/{id}``)."""
resp = self . _client . transport . request (
"GET" ,
_memory_item_path ( store_id , memory_id ),
)
return _coerce_memory ( resp . data )
update
update (
store_id : str ,
memory_id : str ,
* ,
path : Optional [ str ] = None ,
content : Optional [ str ] = None ,
content_sha256 : Optional [ str ] = None
) -> Memory
Update a memory (POST .../memories/{id}).
Mutate content, rename via path, or both — at least one
must be given. Pass the sha from the previously retrieved
memory as content_sha256 for optimistic concurrency; a
mismatch returns 409 memory_precondition_failed_error.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248 def update (
self ,
store_id : str ,
memory_id : str ,
* ,
path : Optional [ str ] = None ,
content : Optional [ str ] = None ,
content_sha256 : Optional [ str ] = None ,
) -> Memory :
"""Update a memory (``POST .../memories/{id}``).
Mutate ``content``, rename via ``path``, or both — at least one
must be given. Pass the sha from the previously retrieved
memory as ``content_sha256`` for optimistic concurrency; a
mismatch returns 409 ``memory_precondition_failed_error``.
"""
if path is None and content is None :
raise TypeError (
"memories.update() requires at least one of "
"'path' or 'content'" ,
)
body = MemoryUpdateParams (
path = path ,
content = content ,
content_sha256 = content_sha256 ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_memory_item_path ( store_id , memory_id ),
json = body ,
)
return _coerce_memory ( resp . data )
delete
delete ( store_id : str , memory_id : str ) -> DeleteResponse
Delete a memory (DELETE .../memories/{id}).
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
250
251
252
253
254
255
256
257
258
259
260 def delete (
self ,
store_id : str ,
memory_id : str ,
) -> DeleteResponse :
"""Delete a memory (``DELETE .../memories/{id}``)."""
resp = self . _client . transport . request (
"DELETE" ,
_memory_item_path ( store_id , memory_id ),
)
return DeleteResponse ( ** resp . data )
AsyncMemories
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
async
create ( store_id : str , * , path : str , content : str ) -> Memory
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509 async def create (
self ,
store_id : str ,
* ,
path : str ,
content : str ,
) -> Memory :
body = MemoryCreateParams ( path = path , content = content ) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_memories_path ( store_id ),
json = body ,
)
return _coerce_memory ( resp . data )
list
async
list (
store_id : str ,
* ,
path_prefix : Optional [ str ] = None ,
depth : Optional [ int ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ Memory ]
Async variant of :meth:Memories.list (depth >= 2 is
emulated client-side the same way).
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557 async def list (
self ,
store_id : str ,
* ,
path_prefix : Optional [ str ] = None ,
depth : Optional [ int ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ Memory ]:
"""Async variant of :meth:`Memories.list` (depth >= 2 is
emulated client-side the same way)."""
depth_emulated = depth is not None and depth > _MAX_WIRE_DEPTH
wire_depth = None if depth_emulated else depth
params = MemoryListParams (
path_prefix = path_prefix ,
depth = wire_depth ,
view = view ,
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_memories_path ( store_id ),
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ Memory ]:
return await self . list (
store_id ,
path_prefix = path_prefix ,
depth = depth ,
view = view ,
limit = limit ,
page = nxt ,
)
result = build_page (
payload = resp . data ,
item_factory = _coerce_memory ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
if depth_emulated :
result = _apply_depth_emulation ( result , depth , path_prefix )
return result
retrieve
async
retrieve ( store_id : str , memory_id : str ) -> Memory
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
559
560
561
562
563
564
565
566
567
568 async def retrieve (
self ,
store_id : str ,
memory_id : str ,
) -> Memory :
resp = await self . _client . transport . request (
"GET" ,
_memory_item_path ( store_id , memory_id ),
)
return _coerce_memory ( resp . data )
update
async
update (
store_id : str ,
memory_id : str ,
* ,
path : Optional [ str ] = None ,
content : Optional [ str ] = None ,
content_sha256 : Optional [ str ] = None
) -> Memory
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596 async def update (
self ,
store_id : str ,
memory_id : str ,
* ,
path : Optional [ str ] = None ,
content : Optional [ str ] = None ,
content_sha256 : Optional [ str ] = None ,
) -> Memory :
if path is None and content is None :
raise TypeError (
"memories.update() requires at least one of "
"'path' or 'content'" ,
)
body = MemoryUpdateParams (
path = path ,
content = content ,
content_sha256 = content_sha256 ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_memory_item_path ( store_id , memory_id ),
json = body ,
)
return _coerce_memory ( resp . data )
delete
async
delete ( store_id : str , memory_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
598
599
600
601
602
603
604
605
606
607 async def delete (
self ,
store_id : str ,
memory_id : str ,
) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
_memory_item_path ( store_id , memory_id ),
)
return DeleteResponse ( ** resp . data )
MemoryVersions
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
list
list (
store_id : str ,
* ,
memory_id : Optional [ str ] = None ,
operation : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ MemoryVersion ]
List versions, newest-first (GET .../memory_versions).
Filters: memory_id, operation (created / modified
/ deleted), created_at_gte / created_at_lte (ISO-8601
timestamps; sent on the wire as created_at.gte /
created_at.lte), and view (basic / full).
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319 def list (
self ,
store_id : str ,
* ,
memory_id : Optional [ str ] = None ,
operation : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ MemoryVersion ]:
"""List versions, newest-first (``GET .../memory_versions``).
Filters: ``memory_id``, ``operation`` (``created`` / ``modified``
/ ``deleted``), ``created_at_gte`` / ``created_at_lte`` (ISO-8601
timestamps; sent on the wire as ``created_at.gte`` /
``created_at.lte``), and ``view`` (``basic`` / ``full``).
"""
params = MemoryVersionListParams (
memory_id = memory_id ,
operation = operation ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
view = view ,
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_memory_versions_path ( store_id ),
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_memory_version ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
store_id ,
memory_id = memory_id ,
operation = operation ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
view = view ,
limit = limit ,
page = nxt ,
),
)
retrieve
retrieve ( store_id : str , version_id : str ) -> MemoryVersion
Retrieve a version snapshot (GET .../memory_versions/{id}).
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
321
322
323
324
325
326
327
328
329
330
331 def retrieve (
self ,
store_id : str ,
version_id : str ,
) -> MemoryVersion :
"""Retrieve a version snapshot (``GET .../memory_versions/{id}``)."""
resp = self . _client . transport . request (
"GET" ,
_memory_version_item_path ( store_id , version_id ),
)
return _coerce_memory_version ( resp . data )
redact
redact ( store_id : str , version_id : str ) -> MemoryVersion
Redact a version (POST .../memory_versions/{id}/redact).
Scrubs path / content / content_sha256 /
content_size_bytes while preserving the audit trail
(created_at, ids). Idempotent and irreversible.
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350 def redact (
self ,
store_id : str ,
version_id : str ,
) -> MemoryVersion :
"""Redact a version (``POST .../memory_versions/{id}/redact``).
Scrubs ``path`` / ``content`` / ``content_sha256`` /
``content_size_bytes`` while preserving the audit trail
(``created_at``, ids). Idempotent and irreversible.
"""
resp = self . _client . transport . request (
"POST" ,
_memory_version_redact_path ( store_id , version_id ),
)
return _coerce_memory_version ( resp . data )
AsyncMemoryVersions
AsyncMemoryVersions ( client )
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
list
async
list (
store_id : str ,
* ,
memory_id : Optional [ str ] = None ,
operation : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ MemoryVersion ]
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659 async def list (
self ,
store_id : str ,
* ,
memory_id : Optional [ str ] = None ,
operation : Optional [ str ] = None ,
created_at_gte : Optional [ str ] = None ,
created_at_lte : Optional [ str ] = None ,
view : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ MemoryVersion ]:
params = MemoryVersionListParams (
memory_id = memory_id ,
operation = operation ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
view = view ,
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_memory_versions_path ( store_id ),
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ MemoryVersion ]:
return await self . list (
store_id ,
memory_id = memory_id ,
operation = operation ,
created_at_gte = created_at_gte ,
created_at_lte = created_at_lte ,
view = view ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_memory_version ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
retrieve
async
retrieve ( store_id : str , version_id : str ) -> MemoryVersion
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
661
662
663
664
665
666
667
668
669
670 async def retrieve (
self ,
store_id : str ,
version_id : str ,
) -> MemoryVersion :
resp = await self . _client . transport . request (
"GET" ,
_memory_version_item_path ( store_id , version_id ),
)
return _coerce_memory_version ( resp . data )
redact
async
redact ( store_id : str , version_id : str ) -> MemoryVersion
Source code in dashscope/applications/agentstudio/resources/memory_stores.py
674
675
676
677
678
679
680
681
682
683 async def redact (
self ,
store_id : str ,
version_id : str ,
) -> MemoryVersion :
resp = await self . _client . transport . request (
"POST" ,
_memory_version_redact_path ( store_id , version_id ),
)
return _coerce_memory_version ( resp . data )
Skills
Skills
Skill CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/skills.py
def __init__ ( self , client ) -> None :
self . _client = client
self . versions = SkillVersions ( client )
versions
instance-attribute
versions = SkillVersions ( client )
get
class-attribute
instance-attribute
call
class-attribute
instance-attribute
create
create (
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None
) -> Skill
Source code in dashscope/applications/agentstudio/resources/skills.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 def create (
self ,
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None ,
) -> Skill :
resolved = _resolve_file_id_sync (
client = self . _client ,
file_id = file_id ,
file = file ,
mime_type = mime_type ,
)
body = SkillCreateParams ( file_id = resolved ) . to_dict ()
resp = self . _client . transport . request ( "POST" , _PATH_SKILLS , json = body )
return _coerce_skill ( resp . data )
retrieve
retrieve ( skill_id : str ) -> Skill
Source code in dashscope/applications/agentstudio/resources/skills.py
def retrieve ( self , skill_id : str ) -> Skill :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } " ,
)
return _coerce_skill ( resp . data )
list
list (
* ,
source : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ Skill ]
Source code in dashscope/applications/agentstudio/resources/skills.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 def list (
self ,
* ,
source : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ Skill ]:
params = SkillListParams (
source = source ,
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_SKILLS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_skill ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
source = source ,
limit = limit ,
page = nxt ,
),
)
delete
delete ( skill_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/skills.py
def delete ( self , skill_id : str ) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
f " { _PATH_SKILLS } / { skill_id } " ,
)
return DeleteResponse ( ** resp . data )
AsyncSkills
Async Skill CRUD — instance methods backed by a shared client.
Source code in dashscope/applications/agentstudio/resources/skills.py
def __init__ ( self , client ) -> None :
self . _client = client
self . versions = AsyncSkillVersions ( client )
versions
instance-attribute
versions = AsyncSkillVersions ( client )
get
class-attribute
instance-attribute
call
class-attribute
instance-attribute
create
async
create (
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None
) -> Skill
Source code in dashscope/applications/agentstudio/resources/skills.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206 async def create (
self ,
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None ,
) -> Skill :
resolved = await _resolve_file_id_async (
client = self . _client ,
file_id = file_id ,
file = file ,
mime_type = mime_type ,
)
body = SkillCreateParams ( file_id = resolved ) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_SKILLS ,
json = body ,
)
return _coerce_skill ( resp . data )
retrieve
async
retrieve ( skill_id : str ) -> Skill
Source code in dashscope/applications/agentstudio/resources/skills.py
async def retrieve ( self , skill_id : str ) -> Skill :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } " ,
)
return _coerce_skill ( resp . data )
list
async
list (
* ,
source : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ Skill ]
Source code in dashscope/applications/agentstudio/resources/skills.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252 async def list (
self ,
* ,
source : Optional [ str ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ Skill ]:
params = SkillListParams (
source = source ,
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_SKILLS ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ Skill ]:
return await self . list (
source = source ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_skill ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
delete
async
delete ( skill_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/skills.py
async def delete ( self , skill_id : str ) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_SKILLS } / { skill_id } " ,
)
return DeleteResponse ( ** resp . data )
SkillVersions
Skill version sub-resource.
Source code in dashscope/applications/agentstudio/resources/skills.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
create (
skill_id : str ,
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None
) -> SkillVersion
Source code in dashscope/applications/agentstudio/resources/skills.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136 def create (
self ,
skill_id : str ,
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None ,
) -> SkillVersion :
resolved = _resolve_file_id_sync (
client = self . _client ,
file_id = file_id ,
file = file ,
mime_type = mime_type ,
)
body = SkillVersionCreateParams ( file_id = resolved ) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_SKILLS } / { skill_id } /versions" ,
json = body ,
)
return _coerce_skill_version ( resp . data )
list
list (
skill_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ SkillVersion ]
Source code in dashscope/applications/agentstudio/resources/skills.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160 def list (
self ,
skill_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ SkillVersion ]:
params = SkillVersionListParams ( limit = limit , page = page ) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } /versions" ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_skill_version ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
skill_id ,
limit = limit ,
page = nxt ,
),
)
retrieve
retrieve ( skill_id : str , version : str ) -> SkillVersion
Source code in dashscope/applications/agentstudio/resources/skills.py
def retrieve ( self , skill_id : str , version : str ) -> SkillVersion :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } /versions/ { version } " ,
)
return _coerce_skill_version ( resp . data )
download
download ( skill_id : str , version : str ) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/skills.py
def download ( self , skill_id : str , version : str ) -> Dict [ str , Any ]:
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } /versions/ { version } /content" ,
)
return dict ( resp . data )
AsyncSkillVersions
AsyncSkillVersions ( client )
Async skill version sub-resource.
Source code in dashscope/applications/agentstudio/resources/skills.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
async
create (
skill_id : str ,
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None
) -> SkillVersion
Source code in dashscope/applications/agentstudio/resources/skills.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288 async def create (
self ,
skill_id : str ,
* ,
file_id : Optional [ str ] = None ,
file : Optional [ FileSource ] = None ,
mime_type : Optional [ str ] = None ,
) -> SkillVersion :
resolved = await _resolve_file_id_async (
client = self . _client ,
file_id = file_id ,
file = file ,
mime_type = mime_type ,
)
body = SkillVersionCreateParams ( file_id = resolved ) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_SKILLS } / { skill_id } /versions" ,
json = body ,
)
return _coerce_skill_version ( resp . data )
list
async
list (
skill_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ SkillVersion ]
Source code in dashscope/applications/agentstudio/resources/skills.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317 async def list (
self ,
skill_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ SkillVersion ]:
params = SkillVersionListParams ( limit = limit , page = page ) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } /versions" ,
params = params ,
)
async def fetch_next ( nxt : str ) -> AsyncCursorPage [ SkillVersion ]:
return await self . list (
skill_id ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_skill_version ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
retrieve
async
retrieve ( skill_id : str , version : str ) -> SkillVersion
Source code in dashscope/applications/agentstudio/resources/skills.py
async def retrieve ( self , skill_id : str , version : str ) -> SkillVersion :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } /versions/ { version } " ,
)
return _coerce_skill_version ( resp . data )
download
async
download ( skill_id : str , version : str ) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/skills.py
async def download ( self , skill_id : str , version : str ) -> Dict [ str , Any ]:
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_SKILLS } / { skill_id } /versions/ { version } /content" ,
)
return dict ( resp . data )
Vaults & credentials
Vaults
Source code in dashscope/applications/agentstudio/resources/vaults.py
def __init__ ( self , client ) -> None :
self . _client = client
self . credentials = Credentials ( client )
credentials
instance-attribute
credentials = Credentials ( client )
get
class-attribute
instance-attribute
create
create (
* ,
display_name : str ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178 def create (
self ,
* ,
display_name : str ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Vault :
body = VaultCreateParams (
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
_PATH_VAULTS ,
json = body ,
)
return _coerce_vault ( resp . data )
retrieve
retrieve ( vault_id : str ) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
def retrieve ( self , vault_id : str ) -> Vault :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_VAULTS } / { vault_id } " ,
)
return _coerce_vault ( resp . data )
update
update (
vault_id : str ,
* ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205 def update (
self ,
vault_id : str ,
* ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Vault :
body = VaultUpdateParams (
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } " ,
json = body ,
)
return _coerce_vault ( resp . data )
list
list (
* ,
keyword : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ Vault ]
Source code in dashscope/applications/agentstudio/resources/vaults.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236 def list (
self ,
* ,
keyword : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ Vault ]:
params = VaultListParams (
keyword = keyword ,
include_archived = include_archived ,
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_VAULTS ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_vault ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
keyword = keyword ,
include_archived = include_archived ,
limit = limit ,
page = nxt ,
),
)
delete
delete ( vault_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/vaults.py
def delete ( self , vault_id : str ) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
f " { _PATH_VAULTS } / { vault_id } " ,
)
return DeleteResponse ( ** resp . data )
archive
archive ( vault_id : str ) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
def archive ( self , vault_id : str ) -> Vault :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /archive" ,
)
return _coerce_vault ( resp . data )
AsyncVaults
Source code in dashscope/applications/agentstudio/resources/vaults.py
def __init__ ( self , client ) -> None :
self . _client = client
self . credentials = AsyncCredentials ( client )
credentials
instance-attribute
credentials = AsyncCredentials ( client )
get
class-attribute
instance-attribute
create
async
create (
* ,
display_name : str ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397 async def create (
self ,
* ,
display_name : str ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Vault :
body = VaultCreateParams (
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
_PATH_VAULTS ,
json = body ,
)
return _coerce_vault ( resp . data )
retrieve
async
retrieve ( vault_id : str ) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
async def retrieve ( self , vault_id : str ) -> Vault :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_VAULTS } / { vault_id } " ,
)
return _coerce_vault ( resp . data )
update
async
update (
vault_id : str ,
* ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424 async def update (
self ,
vault_id : str ,
* ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Vault :
body = VaultUpdateParams (
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } " ,
json = body ,
)
return _coerce_vault ( resp . data )
list
async
list (
* ,
keyword : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ Vault ]
Source code in dashscope/applications/agentstudio/resources/vaults.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462 async def list (
self ,
* ,
keyword : Optional [ str ] = None ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ Vault ]:
params = VaultListParams (
keyword = keyword ,
include_archived = include_archived ,
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_VAULTS ,
params = params ,
)
async def fetch_next (
nxt : str ,
) -> AsyncCursorPage [ Vault ]:
return await self . list (
keyword = keyword ,
include_archived = include_archived ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_vault ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
delete
async
delete ( vault_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/vaults.py
async def delete ( self , vault_id : str ) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_VAULTS } / { vault_id } " ,
)
return DeleteResponse ( ** resp . data )
archive
async
archive ( vault_id : str ) -> Vault
Source code in dashscope/applications/agentstudio/resources/vaults.py
async def archive ( self , vault_id : str ) -> Vault :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /archive" ,
)
return _coerce_vault ( resp . data )
Credentials
Source code in dashscope/applications/agentstudio/resources/vaults.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
create (
vault_id : str ,
* ,
auth : Any ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 def create (
self ,
vault_id : str ,
* ,
auth : Any ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Credential :
body = CredentialCreateParams (
auth = auth ,
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" ,
json = body ,
)
return _coerce_credential ( resp . data )
retrieve
retrieve ( vault_id : str , credential_id : str ) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
65
66
67
68
69
70
71
72
73
74 def retrieve (
self ,
vault_id : str ,
credential_id : str ,
) -> Credential :
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" f "/ { credential_id } " ,
)
return _coerce_credential ( resp . data )
update
update (
vault_id : str ,
credential_id : str ,
* ,
auth : Any = None ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97 def update (
self ,
vault_id : str ,
credential_id : str ,
* ,
auth : Any = None ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Credential :
body = CredentialUpdateParams (
auth = auth ,
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" f "/ { credential_id } " ,
json = body ,
)
return _coerce_credential ( resp . data )
list
list (
vault_id : str ,
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ Credential ]
Source code in dashscope/applications/agentstudio/resources/vaults.py
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127 def list (
self ,
vault_id : str ,
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ Credential ]:
params = CredentialListParams (
include_archived = include_archived ,
limit = limit ,
page = page ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" ,
params = params ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_credential ,
request_id = resp . request_id ,
fetch_next = lambda nxt : self . list (
vault_id ,
include_archived = include_archived ,
limit = limit ,
page = nxt ,
),
)
delete
delete ( vault_id : str , credential_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/vaults.py
129
130
131
132
133
134
135
136
137
138 def delete (
self ,
vault_id : str ,
credential_id : str ,
) -> DeleteResponse :
resp = self . _client . transport . request (
"DELETE" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" f "/ { credential_id } " ,
)
return DeleteResponse ( ** resp . data )
archive
archive ( vault_id : str , credential_id : str ) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
140
141
142
143
144
145
146
147
148
149
150 def archive (
self ,
vault_id : str ,
credential_id : str ,
) -> Credential :
resp = self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /credentials"
f "/ { credential_id } /archive" ,
)
return _coerce_credential ( resp . data )
AsyncCredentials
Source code in dashscope/applications/agentstudio/resources/vaults.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
async
create (
vault_id : str ,
* ,
auth : Any ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280 async def create (
self ,
vault_id : str ,
* ,
auth : Any ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Credential :
body = CredentialCreateParams (
auth = auth ,
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" ,
json = body ,
)
return _coerce_credential ( resp . data )
retrieve
async
retrieve ( vault_id : str , credential_id : str ) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
282
283
284
285
286
287
288
289
290
291 async def retrieve (
self ,
vault_id : str ,
credential_id : str ,
) -> Credential :
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" f "/ { credential_id } " ,
)
return _coerce_credential ( resp . data )
update
async
update (
vault_id : str ,
credential_id : str ,
* ,
auth : Any = None ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314 async def update (
self ,
vault_id : str ,
credential_id : str ,
* ,
auth : Any = None ,
display_name : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Credential :
body = CredentialUpdateParams (
auth = auth ,
display_name = display_name ,
metadata = metadata ,
) . to_dict ()
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" f "/ { credential_id } " ,
json = body ,
)
return _coerce_credential ( resp . data )
list
async
list (
vault_id : str ,
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ Credential ]
Source code in dashscope/applications/agentstudio/resources/vaults.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351 async def list (
self ,
vault_id : str ,
* ,
include_archived : Optional [ bool ] = None ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ Credential ]:
params = CredentialListParams (
include_archived = include_archived ,
limit = limit ,
page = page ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" ,
params = params ,
)
async def fetch_next (
nxt : str ,
) -> AsyncCursorPage [ Credential ]:
return await self . list (
vault_id ,
include_archived = include_archived ,
limit = limit ,
page = nxt ,
)
return build_page (
payload = resp . data ,
item_factory = _coerce_credential ,
request_id = resp . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
delete
async
delete ( vault_id : str , credential_id : str ) -> DeleteResponse
Source code in dashscope/applications/agentstudio/resources/vaults.py
353
354
355
356
357
358
359
360
361
362 async def delete (
self ,
vault_id : str ,
credential_id : str ,
) -> DeleteResponse :
resp = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_VAULTS } / { vault_id } /credentials" f "/ { credential_id } " ,
)
return DeleteResponse ( ** resp . data )
archive
async
archive ( vault_id : str , credential_id : str ) -> Credential
Source code in dashscope/applications/agentstudio/resources/vaults.py
364
365
366
367
368
369
370
371
372
373
374 async def archive (
self ,
vault_id : str ,
credential_id : str ,
) -> Credential :
resp = await self . _client . transport . request (
"POST" ,
f " { _PATH_VAULTS } / { vault_id } /credentials"
f "/ { credential_id } /archive" ,
)
return _coerce_credential ( resp . data )
Security & webhooks
Security
Security center read interface (overview + agent logs).
Source code in dashscope/applications/agentstudio/resources/security.py
def __init__ ( self , client ) -> None :
self . _client = client
overview
overview () -> SecurityOverview
24h protection dashboard (GET /security/overview).
Source code in dashscope/applications/agentstudio/resources/security.py
def overview ( self ) -> SecurityOverview :
"""24h protection dashboard (``GET /security/overview``)."""
resp = self . _client . transport . request (
"GET" ,
_PATH_SECURITY_OVERVIEW ,
)
return _overview_from_payload ( resp . data )
list_agent_logs
list_agent_logs (
* ,
current_page : Optional [ int ] = None ,
page_size : Optional [ int ] = None ,
risk_level : Optional [ str ] = None ,
status : Optional [ str ] = None ,
risk_name : Optional [ str ] = None ,
app_name : Optional [ str ] = None ,
asset_type : Optional [ str ] = None ,
vendor : Optional [ str ] = None ,
order_by : Optional [ str ] = None ,
order : Optional [ str ] = None ,
lang : Optional [ str ] = None ,
status_list : Optional [ Sequence [ str ]] = None
) -> SecurityAlertList
Alert list (GET /security/agent_logs).
Page-number pagination: pass current_page + 1 for the next
page, or use the returned next_page cursor if non-null.
check_time / handle_time on rows are millisecond strings.
Source code in dashscope/applications/agentstudio/resources/security.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90 def list_agent_logs (
self ,
* ,
current_page : Optional [ int ] = None ,
page_size : Optional [ int ] = None ,
risk_level : Optional [ str ] = None ,
status : Optional [ str ] = None ,
risk_name : Optional [ str ] = None ,
app_name : Optional [ str ] = None ,
asset_type : Optional [ str ] = None ,
vendor : Optional [ str ] = None ,
order_by : Optional [ str ] = None ,
order : Optional [ str ] = None ,
lang : Optional [ str ] = None ,
status_list : Optional [ Sequence [ str ]] = None ,
) -> SecurityAlertList :
"""Alert list (``GET /security/agent_logs``).
Page-number pagination: pass ``current_page + 1`` for the next
page, or use the returned ``next_page`` cursor if non-null.
``check_time`` / ``handle_time`` on rows are millisecond strings.
"""
params = SecurityListAgentLogsParams (
current_page = current_page ,
page_size = page_size ,
risk_level = risk_level ,
status = status ,
risk_name = risk_name ,
app_name = app_name ,
asset_type = asset_type ,
vendor = vendor ,
order_by = order_by ,
order = order ,
lang = lang ,
status_list = status_list ,
) . to_dict ()
resp = self . _client . transport . request (
"GET" ,
_PATH_SECURITY_AGENT_LOGS ,
params = params ,
)
return _alert_list_from_payload ( resp . data )
AsyncSecurity
Async security center read interface.
Source code in dashscope/applications/agentstudio/resources/security.py
def __init__ ( self , client ) -> None :
self . _client = client
overview
async
overview () -> SecurityOverview
Source code in dashscope/applications/agentstudio/resources/security.py
async def overview ( self ) -> SecurityOverview :
resp = await self . _client . transport . request (
"GET" ,
_PATH_SECURITY_OVERVIEW ,
)
return _overview_from_payload ( resp . data )
list_agent_logs
async
list_agent_logs (
* ,
current_page : Optional [ int ] = None ,
page_size : Optional [ int ] = None ,
risk_level : Optional [ str ] = None ,
status : Optional [ str ] = None ,
risk_name : Optional [ str ] = None ,
app_name : Optional [ str ] = None ,
asset_type : Optional [ str ] = None ,
vendor : Optional [ str ] = None ,
order_by : Optional [ str ] = None ,
order : Optional [ str ] = None ,
lang : Optional [ str ] = None ,
status_list : Optional [ Sequence [ str ]] = None
) -> SecurityAlertList
Source code in dashscope/applications/agentstudio/resources/security.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141 async def list_agent_logs (
self ,
* ,
current_page : Optional [ int ] = None ,
page_size : Optional [ int ] = None ,
risk_level : Optional [ str ] = None ,
status : Optional [ str ] = None ,
risk_name : Optional [ str ] = None ,
app_name : Optional [ str ] = None ,
asset_type : Optional [ str ] = None ,
vendor : Optional [ str ] = None ,
order_by : Optional [ str ] = None ,
order : Optional [ str ] = None ,
lang : Optional [ str ] = None ,
status_list : Optional [ Sequence [ str ]] = None ,
) -> SecurityAlertList :
params = SecurityListAgentLogsParams (
current_page = current_page ,
page_size = page_size ,
risk_level = risk_level ,
status = status ,
risk_name = risk_name ,
app_name = app_name ,
asset_type = asset_type ,
vendor = vendor ,
order_by = order_by ,
order = order ,
lang = lang ,
status_list = status_list ,
) . to_dict ()
resp = await self . _client . transport . request (
"GET" ,
_PATH_SECURITY_AGENT_LOGS ,
params = params ,
)
return _alert_list_from_payload ( resp . data )
WebhookEndpoints
Synchronous Managed Agent webhook endpoint APIs.
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
create (
* ,
url : str ,
events : Sequence [ str ],
description : Optional [ str ] = None
) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 def create (
self ,
* ,
url : str ,
events : Sequence [ str ],
description : Optional [ str ] = None ,
) -> WebhookEndpoint :
body = WebhookEndpointCreateParams (
url = url ,
events = list ( events ),
description = description ,
) . to_dict ()
response = self . _client . transport . request (
"POST" ,
_PATH_WEBHOOK_ENDPOINTS ,
json = body ,
)
return _coerce_webhook_endpoint ( response . data )
retrieve
retrieve ( webhook_id : str ) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def retrieve ( self , webhook_id : str ) -> WebhookEndpoint :
response = self . _client . transport . request (
"GET" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } " ,
)
return _coerce_webhook_endpoint ( response . data )
list
list () -> WebhookEndpointList
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def list ( self ) -> WebhookEndpointList :
response = self . _client . transport . request (
"GET" ,
_PATH_WEBHOOK_ENDPOINTS ,
)
return WebhookEndpointList ( ** response . data )
update
update (
webhook_id : str ,
* ,
description : Optional [ str ] = None ,
url : Optional [ str ] = None ,
events : Optional [ Sequence [ str ]] = None
) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95 def update (
self ,
webhook_id : str ,
* ,
description : Optional [ str ] = None ,
url : Optional [ str ] = None ,
events : Optional [ Sequence [ str ]] = None ,
) -> WebhookEndpoint :
body = WebhookEndpointUpdateParams (
description = description ,
url = url ,
events = list ( events ) if events is not None else None ,
) . to_dict ()
response = self . _client . transport . request (
"PUT" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } " ,
json = body ,
)
return _coerce_webhook_endpoint ( response . data )
delete
delete ( webhook_id : str ) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def delete ( self , webhook_id : str ) -> Dict [ str , Any ]:
response = self . _client . transport . request (
"DELETE" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } " ,
)
return response . data
enable
enable ( webhook_id : str ) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def enable ( self , webhook_id : str ) -> WebhookEndpoint :
response = self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /enable" ,
)
return _coerce_webhook_endpoint ( response . data )
disable
disable ( webhook_id : str ) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def disable ( self , webhook_id : str ) -> WebhookEndpoint :
response = self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /disable" ,
)
return _coerce_webhook_endpoint ( response . data )
test
test ( webhook_id : str ) -> WebhookEvent
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def test ( self , webhook_id : str ) -> WebhookEvent :
response = self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /test" ,
)
return _coerce_webhook_event ( response . data )
reset_secret
reset_secret ( webhook_id : str ) -> WebhookSecretReset
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def reset_secret ( self , webhook_id : str ) -> WebhookSecretReset :
response = self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /reset_secret" ,
)
return _coerce_webhook_secret_reset ( response . data )
list_events
list_events (
webhook_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> CursorPage [ WebhookEvent ]
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154 def list_events (
self ,
webhook_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> CursorPage [ WebhookEvent ]:
params = WebhookEventListParams ( limit = limit , page = page ) . to_dict ()
response = self . _client . transport . request (
"GET" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /events" ,
params = params ,
)
return build_page (
payload = response . data ,
item_factory = _coerce_webhook_event ,
request_id = response . request_id ,
fetch_next = lambda cursor : self . list_events (
webhook_id ,
limit = limit ,
page = cursor ,
),
)
AsyncWebhookEndpoints
AsyncWebhookEndpoints ( client )
Asynchronous Managed Agent webhook endpoint APIs.
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
def __init__ ( self , client ) -> None :
self . _client = client
get
class-attribute
instance-attribute
create
async
create (
* ,
url : str ,
events : Sequence [ str ],
description : Optional [ str ] = None
) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180 async def create (
self ,
* ,
url : str ,
events : Sequence [ str ],
description : Optional [ str ] = None ,
) -> WebhookEndpoint :
body = WebhookEndpointCreateParams (
url = url ,
events = list ( events ),
description = description ,
) . to_dict ()
response = await self . _client . transport . request (
"POST" ,
_PATH_WEBHOOK_ENDPOINTS ,
json = body ,
)
return _coerce_webhook_endpoint ( response . data )
retrieve
async
retrieve ( webhook_id : str ) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def retrieve ( self , webhook_id : str ) -> WebhookEndpoint :
response = await self . _client . transport . request (
"GET" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } " ,
)
return _coerce_webhook_endpoint ( response . data )
list
async
list () -> WebhookEndpointList
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def list ( self ) -> WebhookEndpointList :
response = await self . _client . transport . request (
"GET" ,
_PATH_WEBHOOK_ENDPOINTS ,
)
return WebhookEndpointList ( ** response . data )
update
async
update (
webhook_id : str ,
* ,
description : Optional [ str ] = None ,
url : Optional [ str ] = None ,
events : Optional [ Sequence [ str ]] = None
) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216 async def update (
self ,
webhook_id : str ,
* ,
description : Optional [ str ] = None ,
url : Optional [ str ] = None ,
events : Optional [ Sequence [ str ]] = None ,
) -> WebhookEndpoint :
body = WebhookEndpointUpdateParams (
description = description ,
url = url ,
events = list ( events ) if events is not None else None ,
) . to_dict ()
response = await self . _client . transport . request (
"PUT" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } " ,
json = body ,
)
return _coerce_webhook_endpoint ( response . data )
delete
async
delete ( webhook_id : str ) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def delete ( self , webhook_id : str ) -> Dict [ str , Any ]:
response = await self . _client . transport . request (
"DELETE" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } " ,
)
return response . data
enable
async
enable ( webhook_id : str ) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def enable ( self , webhook_id : str ) -> WebhookEndpoint :
response = await self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /enable" ,
)
return _coerce_webhook_endpoint ( response . data )
disable
async
disable ( webhook_id : str ) -> WebhookEndpoint
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def disable ( self , webhook_id : str ) -> WebhookEndpoint :
response = await self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /disable" ,
)
return _coerce_webhook_endpoint ( response . data )
test
async
test ( webhook_id : str ) -> WebhookEvent
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def test ( self , webhook_id : str ) -> WebhookEvent :
response = await self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /test" ,
)
return _coerce_webhook_event ( response . data )
reset_secret
async
reset_secret ( webhook_id : str ) -> WebhookSecretReset
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
async def reset_secret ( self , webhook_id : str ) -> WebhookSecretReset :
response = await self . _client . transport . request (
"POST" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /reset_secret" ,
)
return _coerce_webhook_secret_reset ( response . data )
list_events
async
list_events (
webhook_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None
) -> AsyncCursorPage [ WebhookEvent ]
Source code in dashscope/applications/agentstudio/resources/webhook_endpoints.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280 async def list_events (
self ,
webhook_id : str ,
* ,
limit : Optional [ int ] = None ,
page : Optional [ str ] = None ,
) -> AsyncCursorPage [ WebhookEvent ]:
params = WebhookEventListParams ( limit = limit , page = page ) . to_dict ()
response = await self . _client . transport . request (
"GET" ,
f " { _PATH_WEBHOOK_ENDPOINTS } / { webhook_id } /events" ,
params = params ,
)
async def fetch_next ( cursor : str ) -> AsyncCursorPage [ WebhookEvent ]:
return await self . list_events (
webhook_id ,
limit = limit ,
page = cursor ,
)
return build_page (
payload = response . data ,
item_factory = _coerce_webhook_event ,
request_id = response . request_id ,
page_cls = AsyncCursorPage ,
fetch_next = fetch_next ,
)
Usage
client.usage — workspace, agent and session usage summaries and trends.
Usage
Read workspace, agent, and session usage.
Source code in dashscope/applications/agentstudio/resources/usage.py
def __init__ ( self , client ) -> None :
self . _client = client
summary
summary ( ** params : Any ) -> Dict [ str , Any ]
Query usage totals and model/tool breakdowns (POST /usage/summary).
Pass the API's snake_case body fields as keyword arguments. The
service validates dimension-specific parameter combinations.
Source code in dashscope/applications/agentstudio/resources/usage.py
21
22
23
24
25
26
27
28
29
30
31
32 def summary ( self , ** params : Any ) -> Dict [ str , Any ]:
"""Query usage totals and model/tool breakdowns (``POST /usage/summary``).
Pass the API's snake_case body fields as keyword arguments. The
service validates dimension-specific parameter combinations.
"""
resp = self . _client . transport . request (
"POST" ,
_PATH_USAGE_SUMMARY ,
json = dict ( params ),
)
return resp . data
trend
trend ( ** params : Any ) -> Dict [ str , Any ]
Query paginated usage buckets (POST /usage/trend).
Pass the API's snake_case body fields as keyword arguments. To fetch
another page, pass the returned next_page_token as page_token.
Source code in dashscope/applications/agentstudio/resources/usage.py
34
35
36
37
38
39
40
41
42
43
44
45 def trend ( self , ** params : Any ) -> Dict [ str , Any ]:
"""Query paginated usage buckets (``POST /usage/trend``).
Pass the API's snake_case body fields as keyword arguments. To fetch
another page, pass the returned ``next_page_token`` as ``page_token``.
"""
resp = self . _client . transport . request (
"POST" ,
_PATH_USAGE_TREND ,
json = dict ( params ),
)
return resp . data
AsyncUsage
Async usage summary and trend queries.
Source code in dashscope/applications/agentstudio/resources/usage.py
def __init__ ( self , client ) -> None :
self . _client = client
summary
async
summary ( ** params : Any ) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/usage.py
async def summary ( self , ** params : Any ) -> Dict [ str , Any ]:
resp = await self . _client . transport . request (
"POST" ,
_PATH_USAGE_SUMMARY ,
json = dict ( params ),
)
return resp . data
trend
async
trend ( ** params : Any ) -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/resources/usage.py
async def trend ( self , ** params : Any ) -> Dict [ str , Any ]:
resp = await self . _client . transport . request (
"POST" ,
_PATH_USAGE_TREND ,
json = dict ( params ),
)
return resp . data
Client event helpers
user_message
user_message (
text_or_blocks : Any ,
* ,
session_thread_id : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Dict [ str , Any ]
Build a message client event (AGENTSTUDIO wire format).
text_or_blocks may be a plain string (wrapped as a text block)
or a list of pre-built content block dicts.
Source code in dashscope/applications/agentstudio/types/models.py
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413 def user_message (
text_or_blocks : Any ,
* ,
session_thread_id : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Dict [ str , Any ]:
"""Build a ``message`` client event (AGENTSTUDIO wire format).
``text_or_blocks`` may be a plain string (wrapped as a text block)
or a list of pre-built content block dicts.
"""
if isinstance ( text_or_blocks , str ):
content : List [ Dict [ str , Any ]] = [
{ "type" : BlockType . TEXT , "text" : text_or_blocks },
]
else :
content = list ( text_or_blocks )
evt : Dict [ str , Any ] = {
"role" : MessageRole . USER ,
"type" : SSEEventType . MESSAGE ,
"content" : content ,
}
if session_thread_id :
evt [ "session_thread_id" ] = session_thread_id
if metadata :
evt [ "metadata" ] = dict ( metadata )
return evt
user_interrupt
user_interrupt (
* ,
session_thread_id : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
) -> Dict [ str , Any ]
Cancel the agent's current turn (best-effort).
Source code in dashscope/applications/agentstudio/types/models.py
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431 def user_interrupt (
* ,
session_thread_id : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> Dict [ str , Any ]:
"""Cancel the agent's current turn (best-effort)."""
evt : Dict [ str , Any ] = {
"role" : MessageRole . USER ,
"type" : SSEEventType . INTERRUPT ,
}
if session_thread_id :
evt [ "session_thread_id" ] = session_thread_id
if metadata :
evt [ "metadata" ] = dict ( metadata )
return evt
user_tool_result (
* ,
tool_use_id : str ,
content : Any ,
is_error : bool = False ,
session_thread_id : Optional [ str ] = None
) -> Dict [ str , Any ]
Self-hosted tool result (advanced; mirrors built-in tool execution).
Emits a tool_call_output event in the AGENTSTUDIO wire format.
Source code in dashscope/applications/agentstudio/types/models.py
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538 def user_tool_result (
* ,
tool_use_id : str ,
content : Any ,
is_error : bool = False ,
session_thread_id : Optional [ str ] = None ,
) -> Dict [ str , Any ]:
"""Self-hosted tool result (advanced; mirrors built-in tool execution).
Emits a ``tool_call_output`` event in the AGENTSTUDIO wire format.
"""
if isinstance ( content , str ):
output = content
elif isinstance ( content , Sequence ) and not isinstance ( content , str ):
output = list ( content )
else :
output = content
evt : Dict [ str , Any ] = {
"role" : MessageRole . TOOL ,
"type" : SSEEventType . TOOL_CALL_OUTPUT ,
"content" : [
{
"type" : "data" ,
"data" : {
"call_id" : tool_use_id ,
"output" : output ,
},
},
],
"is_error" : bool ( is_error ),
}
if session_thread_id :
evt [ "session_thread_id" ] = session_thread_id
return evt
user_custom_tool_result (
* ,
custom_tool_use_id : str ,
content : Any ,
is_error : bool = False ,
session_thread_id : Optional [ str ] = None
) -> Dict [ str , Any ]
Reply to an :class:AgentCustomToolUseEvent with a tool result.
Emits a function_call_output event in the AGENTSTUDIO wire format.
Source code in dashscope/applications/agentstudio/types/models.py
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501 def user_custom_tool_result (
* ,
custom_tool_use_id : str ,
content : Any ,
is_error : bool = False ,
session_thread_id : Optional [ str ] = None ,
) -> Dict [ str , Any ]:
"""Reply to an :class:`AgentCustomToolUseEvent` with a tool result.
Emits a ``function_call_output`` event in the AGENTSTUDIO wire format.
"""
if isinstance ( content , str ):
output = content
elif isinstance ( content , Sequence ) and not isinstance ( content , str ):
output = list ( content )
else :
output = content
evt : Dict [ str , Any ] = {
"role" : MessageRole . TOOL ,
"type" : SSEEventType . FUNCTION_CALL_OUTPUT ,
"content" : [
{
"type" : "data" ,
"data" : {
"call_id" : custom_tool_use_id ,
"output" : output ,
},
},
],
"is_error" : bool ( is_error ),
}
if session_thread_id :
evt [ "session_thread_id" ] = session_thread_id
return evt
user_tool_approval_response (
* ,
batch_id : str ,
call_id : str ,
result : str ,
deny_message : Optional [ str ] = None
) -> Dict [ str , Any ]
Submit a tool approval ruling for an always_ask tool call.
result must be "allow" or "deny"; deny_message is
optional and only meaningful when denying. The approval identity is the
(batch_id, call_id) composite key — call_id may be reused across
turns, so never match on call_id alone. Approval responses target
the primary thread only (no session_thread_id); the legacy
tool_confirmation type is rejected by the server (HTTP 400
bma_invalid_event).
Source code in dashscope/applications/agentstudio/types/models.py
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464 def user_tool_approval_response (
* ,
batch_id : str ,
call_id : str ,
result : str ,
deny_message : Optional [ str ] = None ,
) -> Dict [ str , Any ]:
"""Submit a tool approval ruling for an ``always_ask`` tool call.
``result`` must be ``"allow"`` or ``"deny"``; ``deny_message`` is
optional and only meaningful when denying. The approval identity is the
``(batch_id, call_id)`` composite key — ``call_id`` may be reused across
turns, so never match on ``call_id`` alone. Approval responses target
the primary thread only (no ``session_thread_id``); the legacy
``tool_confirmation`` type is rejected by the server (HTTP 400
``bma_invalid_event``).
"""
if result not in ( "allow" , "deny" ):
raise ValueError ( "result must be 'allow' or 'deny'" )
data : Dict [ str , Any ] = {
"batch_id" : batch_id ,
"call_id" : call_id ,
"result" : result ,
}
if deny_message and result == "deny" :
data [ "deny_message" ] = deny_message
return {
"role" : MessageRole . USER ,
"type" : SSEEventType . TOOL_APPROVAL_RESPONSE ,
"content" : [{ "type" : "data" , "data" : data }],
}
user_define_outcome
user_define_outcome (
* ,
description : str ,
rubric : Optional [ str ] = None ,
max_iterations : Optional [ int ] = None ,
session_thread_id : Optional [ str ] = None
) -> Dict [ str , Any ]
Steer the agent towards a measurable outcome.
Source code in dashscope/applications/agentstudio/types/models.py
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562 def user_define_outcome (
* ,
description : str ,
rubric : Optional [ str ] = None ,
max_iterations : Optional [ int ] = None ,
session_thread_id : Optional [ str ] = None ,
) -> Dict [ str , Any ]:
"""Steer the agent towards a measurable outcome."""
data : Dict [ str , Any ] = { "description" : description }
if rubric is not None :
data [ "rubric" ] = rubric
if max_iterations is not None :
data [ "max_iterations" ] = int ( max_iterations )
evt : Dict [ str , Any ] = {
"role" : MessageRole . USER ,
"type" : SSEEventType . DEFINE_OUTCOME ,
"content" : [{ "type" : "data" , "data" : data }],
}
if session_thread_id :
evt [ "session_thread_id" ] = session_thread_id
return evt
Core types
Message
Bases: BaseModel
Unified event/message model corresponding to the AgentStudio API
protocol Message structure.
All SSE stream events and history events share this structure.
The type field discriminates between event kinds::
message, tool_call, tool_call_output, function_call,
function_call_output, mcp_call, mcp_call_output, reasoning,
session_status, error, session_updated, thread_created,
thread_status, thread_message_sent, thread_message_received,
thread_context_compacted, model_request_start, model_request_end,
outcome_evaluation, interrupt, tool_confirmation, define_outcome
Legacy agent.* / session.* / span.* type strings are also
accepted transparently for backward compatibility.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
content = kwargs . get ( "content" )
if isinstance ( content , list ):
kwargs [ "content" ] = parse_content_blocks ( content )
super () . __init__ ( ** kwargs )
stop_reason
property
stop_reason : Optional [ Dict [ str , Any ]]
stop_reason carried by session_status idle events.
The server puts stop_reason inside the session_status event's
data block (not in session.retrieve()). Returns a dict like
{"type": "end_turn"} or None for non-session_status events.
session_status
property
session_status : Optional [ str ]
session_status value from session_status events.
Returns "idle", "running", "rescheduled",
"terminated", "deleted" or None for non-session_status
events.
tool_approval_request : Optional [ Dict [ str , Any ]]
tool_approval_request payload: batch_id / call_id /
name / arguments (JSON string) / tool_type /
server_label (MCP only).
Returns None for non-tool_approval_request events. The
approval identity is the (batch_id, call_id) composite key —
call_id may be reused across turns, so never match on
call_id alone.
error
property
error : Optional [ Dict [ str , Any ]]
{"code", "message"} from type: error events, else None.
Approval failures surface in the event stream as type: error
events (not as HTTP exceptions). Use :attr:pending_tool_approvals
to read the suspend signal alongside this.
pending_tool_approvals : Optional [ Dict [ str , Any ]]
Suspend signal {"batch_id", "call_ids"} carried in the
metadata of an error / response frame while the approval
barrier is up. None when the barrier is not up.
This is the reliable way to tell pending state — do NOT derive it
from request/response event diffs (the server emits it only while
the barrier stands).
event_start
property
event_start : Optional [ Dict [ str , Any ]]
{"id", "type"} from an event_start delta frame (a preview
of an upcoming message/reasoning event; carries no content).
None for other frames.
event_delta
property
event_delta : Optional [ Dict [ str , Any ]]
{"event_id", "delta": {"type", "index", "content"}} from an
event_delta frame. None for other frames.
delta_text
property
delta_text : Optional [ str ]
Incremental text chunk from an event_delta frame (the
delta.content.text of a content_delta), else None.
Use the :attr:text_deltas iterator on the stream for the full
sequence.
data
property
data : Optional [ Dict [ str , Any ]]
The first content block's data payload, for events that carry
one (tool_call / tool_call_output / mcp_call /
mcp_call_output / session_status / tool_approval_request
/ model_request_end / outcome_evaluation / thread_status
/ thread_created / session_updated). None otherwise.
outcome_evaluation
property
outcome_evaluation : Optional [ Dict [ str , Any ]]
outcome_evaluation payload: outcome_id, iteration,
phase (start/ongoing/end), result, explanation,
token usage, speed. None for other events.
thread_status
property
thread_status : Optional [ Dict [ str , Any ]]
thread_status payload: session_thread_id, agent_name,
thread_status (running/idle/terminated/rescheduled), and
stop_reason when idle. None for other events.
thread_created
property
thread_created : Optional [ Dict [ str , Any ]]
thread_created payload: session_thread_id, agent_name.
None for other events.
session_updated
property
session_updated : Optional [ Dict [ str , Any ]]
session_updated payload: title, session_metadata,
agent (only the changed fields, present when changed).
None for other events.
thread_message_routing
property
thread_message_routing : Optional [ Dict [ str , str ]]
Sub-agent routing from thread_message_sent / thread_message_received
metadata: to_session_thread_id / to_agent_name on sent,
from_session_thread_id / from_agent_name on received.
None for other events.
ServerEvent
module-attribute
SessionResource
SessionResource ( ** kwargs : Any )
Bases: BaseModel
A resource mounted into a session (file / memory_store / oss).
file: file_id is the session-scoped copy id (not the source
file id); mount_path resolves under /uploads/. Memory and
OSS mounts are create-only — sessions.resources.add accepts
files only.
memory_store: access (read_write default) and
instructions; name/description are server-snapshotted
for built-in (provider="default") mounts, which also carry the
server-generated mount_path (/mnt/memory/<name>);
agentstudio_memory (Bailian) mounts echo entity_id and the
configured project_ids/profile_schema/description, with
no mount_path.
oss: echoes region/bucket/oss_path and the
user-supplied logical mount_path (the sandbox resolves it under
/mnt/oss/).
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
StopReason
StopReason ( ** kwargs : Any )
Bases: BaseModel
Carried by session_status idle events (and Session.stop_reason).
A running Session's stop_reason is null. requires_action
carries pending_batch_id + pending_call_ids (only the calls not
yet adjudicated); do not derive pending from request/response diffs.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
Memory
Bases: BaseModel
One text document inside a memory store, addressed by path.
content appears only in retrieve responses and in list
responses with view="full"; create and update never return it.
content_sha256 identifies the content revision — pass it back
to memories.update for optimistic concurrency (a mismatch
returns 409 memory_precondition_failed_error).
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
MemoryStore
MemoryStore ( ** kwargs : Any )
Bases: BaseModel
A workspace-scoped store of small text documents.
Stores persist across sessions and are mounted into a session
container at /mnt/memory/<name>/ when attached via the session
resources[] array. archived_at is set once the store is
archived: read-only afterwards, existing session attachments keep
working, but new sessions cannot reference it.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
MemoryVersion
MemoryVersion ( ** kwargs : Any )
Bases: BaseModel
Immutable snapshot produced by every memory mutation; versions
are returned newest-first.
operation is created / modified / deleted. After
redact, path, content, content_sha256 and
content_size_bytes are cleared; the audit trail is preserved.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
PermissionPolicy
PermissionPolicy ( ** kwargs : Any )
Bases: BaseModel
Tool approval policy (permission_policy on tool configs).
Must be the object form {"type": "always_allow" | "always_ask"};
the string form is rejected (the server rejects it as well). Defaults
to always_allow when omitted.
Source code in dashscope/applications/agentstudio/types/models.py
242
243
244
245
246
247
248
249
250
251 def __init__ ( self , ** kwargs : Any ) -> None :
t = kwargs . get ( "type" )
if isinstance ( t , str ) and t not in ( "always_allow" , "always_ask" ):
raise ValueError (
"permission_policy.type must be 'always_allow' or "
"'always_ask'" ,
)
if t is None :
kwargs [ "type" ] = "always_allow"
super () . __init__ ( ** kwargs )
SecurityAlert
SecurityAlert ( ** kwargs : Any )
Bases: BaseModel
A single security alert row. check_time / handle_time are
millisecond-string timestamps (not ISO 8601).
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
SecurityAlertList
SecurityAlertList ( ** kwargs : Any )
Bases: BaseModel
Response of GET /security/agent_logs (page-number + cursor).
Source code in dashscope/applications/agentstudio/types/models.py
873
874
875
876
877
878
879
880
881
882
883 def __init__ ( self , ** kwargs : Any ) -> None :
stats = kwargs . get ( "stats" )
if isinstance ( stats , Mapping ):
kwargs [ "stats" ] = SecurityAlertStats ( ** dict ( stats ))
data = kwargs . get ( "data" )
if isinstance ( data , list ):
kwargs [ "data" ] = [
SecurityAlert ( ** dict ( it )) if isinstance ( it , Mapping ) else it
for it in data
]
super () . __init__ ( ** kwargs )
SecurityOverview
SecurityOverview ( ** kwargs : Any )
Bases: BaseModel
Response of GET /security/overview (last-24h dashboard).
Source code in dashscope/applications/agentstudio/types/models.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837 def __init__ ( self , ** kwargs : Any ) -> None :
for k in ( "capabilities" , "protection" ):
v = kwargs . get ( k )
if isinstance ( v , list ):
kwargs [ k ] = [
SecurityCapability ( ** dict ( it ))
if isinstance ( it , Mapping )
else it
for it in v
]
for k in ( "content_safety" , "file_scan" , "skill_scan" ):
v = kwargs . get ( k )
if isinstance ( v , Mapping ):
kwargs [ k ] = SecurityScanStat ( ** dict ( v ))
super () . __init__ ( ** kwargs )
Request parameter types
AgentCreateParams
AgentCreateParams (
* ,
name : str ,
model : Union [ str , ModelConfig ],
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
)
Bases: BaseModel
Request body for POST /agents.
Maps to :meth:Agents.create. The SDK method exposes model as a
:class:ModelConfig or a bare model id, and system_prompt as a
keyword arg; the wire format uses model: {"id": "…", …} and
system.
Source code in dashscope/applications/agentstudio/types/params.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211 def __init__ (
self ,
* ,
name : str ,
model : Union [ str , ModelConfig ],
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> None :
super () . __init__ (
name = name ,
model = _resolve_model ( model ),
description = description ,
system = system_prompt ,
tools = ([ dict ( t ) for t in tools ] if tools is not None else None ),
mcp_servers = (
[ dict ( s ) for s in mcp_servers ]
if mcp_servers is not None
else None
),
skills = ([ dict ( s ) for s in skills ] if skills is not None else None ),
multiagent = (
_to_mapping ( multiagent ) if multiagent is not None else None
),
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
AgentUpdateParams
AgentUpdateParams (
* ,
version : int ,
name : Optional [ str ] = None ,
model : Optional [ Union [ str , ModelConfig ]] = None ,
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
)
Bases: BaseModel
Request body for POST /agents/{id} (update latest version).
Source code in dashscope/applications/agentstudio/types/params.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261 def __init__ (
self ,
* ,
version : int ,
name : Optional [ str ] = None ,
model : Optional [ Union [ str , ModelConfig ]] = None ,
description : Optional [ str ] = None ,
system_prompt : Optional [ str ] = None ,
tools : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
mcp_servers : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
skills : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
multiagent : Optional [ Mapping [ str , Any ]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> None :
super () . __init__ (
version = version ,
name = name ,
model = ( _resolve_model ( model ) if model is not None else None ),
description = description ,
system = system_prompt ,
tools = ([ dict ( t ) for t in tools ] if tools is not None else None ),
mcp_servers = (
[ dict ( s ) for s in mcp_servers ]
if mcp_servers is not None
else None
),
skills = ([ dict ( s ) for s in skills ] if skills is not None else None ),
multiagent = (
_to_mapping ( multiagent ) if multiagent is not None else None
),
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
SessionCreateParams
SessionCreateParams (
* ,
agent : Any ,
environment_id : Optional [ str ] = None ,
title : Optional [ str ] = None ,
resources : Optional [ Sequence [ ResourceInput ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
mcp_configs : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
)
Bases: BaseModel
Request body for POST /sessions.
agent accepts the Agent ID string (backward compatible) or an
Agent reference/override object (a mapping with
type="agent_with_overrides") that establishes Session-level
overrides for system/tools/mcp_servers/skills.
environment_variables and mcp_configs are Session-level
settings independent of the agent. resources is create-only — it
cannot be modified via updateSession; each item is a mapping or
a :class:~dashscope.applications.agentstudio.types.models.Mount
(file / memory_store — built-in or Bailian
provider="agentstudio_memory" — / oss).
Source code in dashscope/applications/agentstudio/types/params.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442 def __init__ ( # pylint: disable=useless-parent-delegation
self ,
* ,
agent : Any ,
environment_id : Optional [ str ] = None ,
title : Optional [ str ] = None ,
resources : Optional [ Sequence [ ResourceInput ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
mcp_configs : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> None :
super () . __init__ (
agent = _to_mapping ( agent ),
environment_id = environment_id ,
title = title ,
resources = (
[ _to_mapping ( r ) for r in resources ]
if resources is not None
else None
),
vault_ids = ( list ( vault_ids ) if vault_ids is not None else None ),
environment_variables = (
dict ( environment_variables )
if environment_variables is not None
else None
),
mcp_configs = (
[ _to_mapping ( m ) for m in mcp_configs ]
if mcp_configs is not None
else None
),
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
SessionUpdateParams
SessionUpdateParams (
* ,
title : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
agent : Any = None ,
mcp_configs : Optional [
Sequence [ Mapping [ str , Any ]]
] = None
)
Bases: BaseModel
Request body for POST /sessions/{id}.
Omitted (None) fields are not sent — the existing value is kept;
[] / {} explicitly clear the value. agent is a Session-level
Agent config patch (a plain mapping carrying only system/tools/
mcp_servers/skills); the mapping is passed through verbatim so
an explicit None sub-field serializes to JSON null (delete the
override and re-inherit), an omitted sub-field stays absent (keep the
override), and [] / "" override to empty. The server enforces
the override principle; the SDK does not read or merge the agent source.
Source code in dashscope/applications/agentstudio/types/params.py
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492 def __init__ ( # pylint: disable=useless-parent-delegation
self ,
* ,
title : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
agent : Any = None ,
mcp_configs : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
) -> None :
super () . __init__ (
title = title ,
metadata = ( dict ( metadata ) if metadata is not None else None ),
vault_ids = ( list ( vault_ids ) if vault_ids is not None else None ),
environment_variables = (
dict ( environment_variables )
if environment_variables is not None
else None
),
agent = ( _to_mapping ( agent ) if agent is not None else None ),
mcp_configs = (
[ _to_mapping ( m ) for m in mcp_configs ]
if mcp_configs is not None
else None
),
)
SessionEventSendParams
SessionEventSendParams (
* , input : Sequence [ Mapping [ str , Any ]]
)
Bases: BaseModel
Request body for POST /sessions/{id}/events.
The input array must contain at least one event.
Source code in dashscope/applications/agentstudio/types/params.py
559
560
561
562
563
564
565
566
567
568 def __init__ ( # pylint: disable=useless-parent-delegation
self ,
* ,
input : Sequence [ # pylint: disable=redefined-builtin
Mapping [ str , Any ]
],
) -> None :
super () . __init__ (
input = [ dict ( e ) for e in input ],
)
EnvironmentCreateParams
EnvironmentCreateParams (
* ,
name : str ,
config : Mapping [ str , Any ],
description : Optional [ str ] = None ,
scope : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
)
Bases: BaseModel
Request body for POST /environments.
Source code in dashscope/applications/agentstudio/types/params.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323 def __init__ ( # pylint: disable=useless-parent-delegation
self ,
* ,
name : str ,
config : Mapping [ str , Any ],
description : Optional [ str ] = None ,
scope : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> None :
super () . __init__ (
name = name ,
config = dict ( config ),
description = description ,
scope = scope ,
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
EnvironmentUpdateParams
EnvironmentUpdateParams (
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
config : Optional [ Mapping [ str , Any ]] = None ,
scope : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None
)
Bases: BaseModel
Request body for POST /environments/{id}.
Source code in dashscope/applications/agentstudio/types/params.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346 def __init__ ( # pylint: disable=useless-parent-delegation
self ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
config : Optional [ Mapping [ str , Any ]] = None ,
scope : Optional [ str ] = None ,
metadata : Optional [ Mapping [ str , Any ]] = None ,
) -> None :
super () . __init__ (
name = name ,
description = description ,
config = ( dict ( config ) if config is not None else None ),
scope = scope ,
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
DeploymentCreateParams
DeploymentCreateParams (
* ,
name : str ,
agent : Any ,
initial_events : Sequence [ Mapping [ str , Any ]],
description : Optional [ str ] = None ,
environment_id : Optional [ str ] = None ,
schedule : Any = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
metadata : Optional [ Mapping [ str , str ]] = None
)
Bases: BaseModel
Request body for POST /deployments.
Source code in dashscope/applications/agentstudio/types/params.py
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767 def __init__ (
self ,
* ,
name : str ,
agent : Any ,
initial_events : Sequence [ Mapping [ str , Any ]],
description : Optional [ str ] = None ,
environment_id : Optional [ str ] = None ,
schedule : Any = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
metadata : Optional [ Mapping [ str , str ]] = None ,
) -> None :
BaseModel . __init__ (
self ,
name = name ,
description = description ,
agent = _to_mapping ( agent ),
environment_id = environment_id ,
schedule = ( _to_mapping ( schedule ) if schedule is not None else None ),
initial_events = [ dict ( event ) for event in initial_events ],
resources = (
[ _to_mapping ( resource ) for resource in resources ]
if resources is not None
else None
),
vault_ids = ( list ( vault_ids ) if vault_ids is not None else None ),
environment_variables = (
dict ( environment_variables )
if environment_variables is not None
else None
),
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
DeploymentUpdateParams
DeploymentUpdateParams (
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
agent : Any = None ,
environment_id : Any = _NOT_GIVEN ,
schedule : Any = _NOT_GIVEN ,
initial_events : Optional [
Sequence [ Mapping [ str , Any ]]
] = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [
Mapping [ str , str ]
] = None ,
metadata : Optional [ Mapping [ str , str ]] = None
)
Bases: BaseModel
Request body for POST /deployments/{deployment_id}.
environment_id and schedule preserve the distinction between an
omitted argument and an explicit None. Explicit None is emitted as
JSON null to clear the field.
Source code in dashscope/applications/agentstudio/types/params.py
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836 def __init__ (
self ,
* ,
name : Optional [ str ] = None ,
description : Optional [ str ] = None ,
agent : Any = None ,
environment_id : Any = _NOT_GIVEN ,
schedule : Any = _NOT_GIVEN ,
initial_events : Optional [ Sequence [ Mapping [ str , Any ]]] = None ,
resources : Optional [ Sequence [ Any ]] = None ,
vault_ids : Optional [ Sequence [ str ]] = None ,
environment_variables : Optional [ Mapping [ str , str ]] = None ,
metadata : Optional [ Mapping [ str , str ]] = None ,
) -> None :
self . _environment_id_given = environment_id is not _NOT_GIVEN
self . _schedule_given = schedule is not _NOT_GIVEN
super () . __init__ (
name = name ,
description = description ,
agent = ( _to_mapping ( agent ) if agent is not None else None ),
environment_id = (
environment_id if self . _environment_id_given else None
),
schedule = (
_to_mapping ( schedule )
if self . _schedule_given and schedule is not None
else None
),
initial_events = (
[ dict ( event ) for event in initial_events ]
if initial_events is not None
else None
),
resources = (
[ _to_mapping ( resource ) for resource in resources ]
if resources is not None
else None
),
vault_ids = ( list ( vault_ids ) if vault_ids is not None else None ),
environment_variables = (
dict ( environment_variables )
if environment_variables is not None
else None
),
metadata = ( dict ( metadata ) if metadata is not None else None ),
)
to_dict
Source code in dashscope/applications/agentstudio/types/params.py
838
839
840
841
842
843
844 def to_dict ( self ) -> dict :
body = super () . to_dict ()
if self . _environment_id_given and self . environment_id is None :
body [ "environment_id" ] = None
if self . _schedule_given and self . schedule is None :
body [ "schedule" ] = None
return body
WebhookEndpointCreateParams
WebhookEndpointCreateParams ( ** kwargs : Any )
Bases: BaseModel
Request body for POST /webhook_endpoints.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
WebhookEndpointUpdateParams
WebhookEndpointUpdateParams ( ** kwargs : Any )
Bases: BaseModel
Request body for PUT /webhook_endpoints/{id}.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
WebhookEventListParams
WebhookEventListParams ( ** kwargs : Any )
Bases: BaseModel
Query parameters for endpoint-specific webhook events.
Source code in dashscope/applications/agentstudio/types/models.py
def __init__ ( self , ** kwargs : Any ) -> None :
self . _raw : Dict [ str , Any ] = dict ( kwargs )
for name in self . _fields :
setattr ( self , name , kwargs . get ( name ))
self . extra : Dict [ str , Any ] = {
k : v for k , v in kwargs . items () if k not in set ( self . _fields )
}
Constants & enums
SessionStatus
Bases: StrEnum
Session run-status values (session_status).
Top-level Session.status ∈ {idle, running, terminated, rescheduled};
the session_status event data.session_status value set is the
same plus deleted (a delete returns a tombstone, not a Session with
status=deleted). idle also covers waiting for tool approval,
signalled by stop_reason.type=requires_action.
IDLE
class-attribute
instance-attribute
RUNNING
class-attribute
instance-attribute
RESCHEDULED
class-attribute
instance-attribute
RESCHEDULED = 'rescheduled'
TERMINATED
class-attribute
instance-attribute
TERMINATED = 'terminated'
DELETED
class-attribute
instance-attribute
SSEEventType
Bases: StrEnum
Server-sent event types (the value of event.type in SSE payloads).
Client-sendable: MESSAGE, INTERRUPT, TOOL_APPROVAL_RESPONSE,
FUNCTION_CALL_OUTPUT, TOOL_CALL_OUTPUT, DEFINE_OUTCOME.
Server-emitted: all types (23 total).
MESSAGE
class-attribute
instance-attribute
INTERRUPT
class-attribute
instance-attribute
TOOL_APPROVAL_RESPONSE = 'tool_approval_response'
FUNCTION_CALL_OUTPUT
class-attribute
instance-attribute
FUNCTION_CALL_OUTPUT = 'function_call_output'
TOOL_CALL_OUTPUT = 'tool_call_output'
DEFINE_OUTCOME
class-attribute
instance-attribute
DEFINE_OUTCOME = 'define_outcome'
FUNCTION_CALL
class-attribute
instance-attribute
FUNCTION_CALL = 'function_call'
REASONING
class-attribute
instance-attribute
MCP_CALL
class-attribute
instance-attribute
MCP_CALL_OUTPUT
class-attribute
instance-attribute
MCP_CALL_OUTPUT = 'mcp_call_output'
TOOL_APPROVAL_REQUEST = 'tool_approval_request'
THREAD_MESSAGE_SENT
class-attribute
instance-attribute
THREAD_MESSAGE_SENT = 'thread_message_sent'
THREAD_MESSAGE_RECEIVED
class-attribute
instance-attribute
THREAD_MESSAGE_RECEIVED = 'thread_message_received'
THREAD_CONTEXT_COMPACTED
class-attribute
instance-attribute
THREAD_CONTEXT_COMPACTED = 'thread_context_compacted'
SESSION_STATUS
class-attribute
instance-attribute
SESSION_STATUS = 'session_status'
ERROR
class-attribute
instance-attribute
SESSION_UPDATED
class-attribute
instance-attribute
SESSION_UPDATED = 'session_updated'
THREAD_CREATED
class-attribute
instance-attribute
THREAD_CREATED = 'thread_created'
THREAD_STATUS
class-attribute
instance-attribute
THREAD_STATUS = 'thread_status'
MODEL_REQUEST_START
class-attribute
instance-attribute
MODEL_REQUEST_START = 'model_request_start'
MODEL_REQUEST_END
class-attribute
instance-attribute
MODEL_REQUEST_END = 'model_request_end'
OUTCOME_EVALUATION
class-attribute
instance-attribute
OUTCOME_EVALUATION = 'outcome_evaluation'
StopReasonType
Bases: StrEnum
stop_reason.type carried by session_status idle events.
Only idle carries stop_reason; a running Session's
stop_reason is null.
END_TURN
class-attribute
instance-attribute
REQUIRES_ACTION
class-attribute
instance-attribute
REQUIRES_ACTION = 'requires_action'
RETRIES_EXHAUSTED
class-attribute
instance-attribute
RETRIES_EXHAUSTED = 'retries_exhausted'
PermissionPolicyType
Bases: StrEnum
Tool approval policy (permission_policy.type).
always_allow (default) executes the tool without asking;
always_ask produces a tool_approval_request per call.
Subagent/subthread always_ask degrades to always_allow.
ALWAYS_ALLOW
class-attribute
instance-attribute
ALWAYS_ALLOW = 'always_allow'
ALWAYS_ASK
class-attribute
instance-attribute
ALWAYS_ASK = 'always_ask'
WebhookStatus
Bases: StrEnum
Webhook endpoint activation status.
ACTIVE
class-attribute
instance-attribute
DISABLED
class-attribute
instance-attribute
WebhookEventType
Bases: StrEnum
Event types accepted by webhook endpoint subscriptions.
SESSION_CREATED
class-attribute
instance-attribute
SESSION_CREATED = 'session.created'
SESSION_UPDATED
class-attribute
instance-attribute
SESSION_UPDATED = 'session.updated'
SESSION_ARCHIVED
class-attribute
instance-attribute
SESSION_ARCHIVED = 'session.archived'
SESSION_DELETED
class-attribute
instance-attribute
SESSION_DELETED = 'session.deleted'
SESSION_STATUS_RUN_STARTED
class-attribute
instance-attribute
SESSION_STATUS_RUN_STARTED = 'session.status_run_started'
SESSION_STATUS_IDLED
class-attribute
instance-attribute
SESSION_STATUS_IDLED = 'session.status_idled'
SESSION_STATUS_TERMINATED
class-attribute
instance-attribute
SESSION_STATUS_TERMINATED = 'session.status_terminated'
SESSION_THREAD_CREATED
class-attribute
instance-attribute
SESSION_THREAD_CREATED = 'session.thread_created'
SESSION_THREAD_RUN_STARTED
class-attribute
instance-attribute
SESSION_THREAD_RUN_STARTED = 'session.thread_run_started'
SESSION_THREAD_IDLED
class-attribute
instance-attribute
SESSION_THREAD_IDLED = 'session.thread_idled'
SESSION_THREAD_TERMINATED
class-attribute
instance-attribute
SESSION_THREAD_TERMINATED = 'session.thread_terminated'
AGENT_CREATED
class-attribute
instance-attribute
AGENT_CREATED = 'agent.created'
AGENT_UPDATED
class-attribute
instance-attribute
AGENT_UPDATED = 'agent.updated'
AGENT_ARCHIVED
class-attribute
instance-attribute
AGENT_ARCHIVED = 'agent.archived'
DEPLOYMENT_CREATED
class-attribute
instance-attribute
DEPLOYMENT_CREATED = 'deployment.created'
DEPLOYMENT_UPDATED
class-attribute
instance-attribute
DEPLOYMENT_UPDATED = 'deployment.updated'
DEPLOYMENT_ARCHIVED
class-attribute
instance-attribute
DEPLOYMENT_ARCHIVED = 'deployment.archived'
DEPLOYMENT_PAUSED
class-attribute
instance-attribute
DEPLOYMENT_PAUSED = 'deployment.paused'
DEPLOYMENT_UNPAUSED
class-attribute
instance-attribute
DEPLOYMENT_UNPAUSED = 'deployment.unpaused'
DEPLOYMENT_RUN_STARTED
class-attribute
instance-attribute
DEPLOYMENT_RUN_STARTED = 'deployment_run.started'
DEPLOYMENT_RUN_FAILED
class-attribute
instance-attribute
DEPLOYMENT_RUN_FAILED = 'deployment_run.failed'
DEPLOYMENT_RUN_SUCCEEDED
class-attribute
instance-attribute
DEPLOYMENT_RUN_SUCCEEDED = 'deployment_run.succeeded'
ENVIRONMENT_CREATED
class-attribute
instance-attribute
ENVIRONMENT_CREATED = 'environment.created'
ENVIRONMENT_UPDATED
class-attribute
instance-attribute
ENVIRONMENT_UPDATED = 'environment.updated'
ENVIRONMENT_ARCHIVED
class-attribute
instance-attribute
ENVIRONMENT_ARCHIVED = 'environment.archived'
ENVIRONMENT_DELETED
class-attribute
instance-attribute
ENVIRONMENT_DELETED = 'environment.deleted'
VAULT_CREATED
class-attribute
instance-attribute
VAULT_CREATED = 'vault.created'
VAULT_ARCHIVED
class-attribute
instance-attribute
VAULT_ARCHIVED = 'vault.archived'
VAULT_DELETED
class-attribute
instance-attribute
VAULT_DELETED = 'vault.deleted'
VAULT_CREDENTIAL_CREATED
class-attribute
instance-attribute
VAULT_CREDENTIAL_CREATED = 'vault_credential.created'
VAULT_CREDENTIAL_ARCHIVED
class-attribute
instance-attribute
VAULT_CREDENTIAL_ARCHIVED = 'vault_credential.archived'
VAULT_CREDENTIAL_DELETED
class-attribute
instance-attribute
VAULT_CREDENTIAL_DELETED = 'vault_credential.deleted'
WebhookDeliveryStatus
Bases: StrEnum
Webhook delivery status.
PENDING
class-attribute
instance-attribute
DELIVERING
class-attribute
instance-attribute
DELIVERING = 'DELIVERING'
WAITING_RETRY
class-attribute
instance-attribute
WAITING_RETRY = 'WAITING_RETRY'
SUCCEEDED
class-attribute
instance-attribute
FAILED
class-attribute
instance-attribute
CANCELED
class-attribute
instance-attribute
WebhookDisabledReason
Bases: StrEnum
Reason why a webhook endpoint was disabled.
MANUAL
class-attribute
instance-attribute
CONSECUTIVE_DELIVERY_FAILURES
class-attribute
instance-attribute
CONSECUTIVE_DELIVERY_FAILURES = (
"CONSECUTIVE_DELIVERY_FAILURES"
)
REDIRECT_RESPONSE
class-attribute
instance-attribute
REDIRECT_RESPONSE = 'REDIRECT_RESPONSE'
SSRF_VALIDATION_FAILED
class-attribute
instance-attribute
SSRF_VALIDATION_FAILED = 'SSRF_VALIDATION_FAILED'
TLS_VALIDATION_FAILED
class-attribute
instance-attribute
TLS_VALIDATION_FAILED = 'TLS_VALIDATION_FAILED'
CursorPage
CursorPage (
* ,
data : List [ T ],
next_page : Optional [ str ],
request_id : Optional [ str ],
fetch_next : Optional [
Callable [[ str ], "CursorPage[T]" ]
] = None ,
extra : Optional [ Dict [ str , Any ]] = None
)
Bases: Generic [T ]
Synchronous page over an opaque page cursor.
extra preserves any additional top-level fields the list
envelope carried beyond data / next_page (forward
compatibility when the server adds fields); extra is per page
and does not participate in auto-pagination.
Source code in dashscope/applications/agentstudio/pagination.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49 def __init__ (
self ,
* ,
data : List [ T ],
next_page : Optional [ str ],
request_id : Optional [ str ],
fetch_next : Optional [ Callable [[ str ], "CursorPage[T]" ]] = None ,
extra : Optional [ Dict [ str , Any ]] = None ,
) -> None :
self . data = data
self . next_page = next_page
self . request_id = request_id
self . _fetch_next = fetch_next
self . extra : Dict [ str , Any ] = dict ( extra or {})
next_page
instance-attribute
request_id
instance-attribute
extra : Dict [ str , Any ] = dict ( extra or {})
prefixes
property
Directory prefixes of a tree-style listing (memory only).
has_next
Source code in dashscope/applications/agentstudio/pagination.py
def has_next ( self ) -> bool :
return bool ( self . next_page ) and self . _fetch_next is not None
get_next
get_next () -> Optional [ 'CursorPage[T]' ]
Source code in dashscope/applications/agentstudio/pagination.py
def get_next ( self ) -> Optional [ "CursorPage[T]" ]:
if not self . has_next ():
return None
assert self . _fetch_next is not None and self . next_page is not None
return self . _fetch_next ( self . next_page )
AsyncCursorPage
AsyncCursorPage (
* ,
data : List [ T ],
next_page : Optional [ str ],
request_id : Optional [ str ],
fetch_next : Optional [
Callable [[ str ], "AsyncCursorPage[T]" ]
] = None ,
extra : Optional [ Dict [ str , Any ]] = None
)
Bases: Generic [T ]
Asynchronous page over an opaque page cursor.
See :class:CursorPage for the extra forward-compatibility
bag.
Source code in dashscope/applications/agentstudio/pagination.py
92
93
94
95
96
97
98
99
100
101
102
103
104
105 def __init__ (
self ,
* ,
data : List [ T ],
next_page : Optional [ str ],
request_id : Optional [ str ],
fetch_next : Optional [ Callable [[ str ], "AsyncCursorPage[T]" ]] = None ,
extra : Optional [ Dict [ str , Any ]] = None ,
) -> None :
self . data = data
self . next_page = next_page
self . request_id = request_id
self . _fetch_next = fetch_next
self . extra : Dict [ str , Any ] = dict ( extra or {})
next_page
instance-attribute
request_id
instance-attribute
extra : Dict [ str , Any ] = dict ( extra or {})
prefixes
property
Directory prefixes of a tree-style listing (memory only).
has_next
Source code in dashscope/applications/agentstudio/pagination.py
def has_next ( self ) -> bool :
return bool ( self . next_page ) and self . _fetch_next is not None
get_next
async
get_next () -> Optional [ 'AsyncCursorPage[T]' ]
Source code in dashscope/applications/agentstudio/pagination.py
110
111
112
113
114
115
116
117 async def get_next ( self ) -> Optional [ "AsyncCursorPage[T]" ]:
if not self . has_next ():
return None
assert self . _fetch_next is not None and self . next_page is not None
result = self . _fetch_next ( self . next_page )
if hasattr ( result , "__await__" ):
result = await result # type: ignore[assignment]
return result # type: ignore[return-value]
RequestOptions
dataclass
RequestOptions (
method : str ,
path : str ,
json : Optional [ Dict [ str , Any ]] = None ,
params : Optional [ Dict [ str , Any ]] = None ,
data : Optional [ Union [ bytes , IO ]] = None ,
files : Optional [ Dict [ str , Any ]] = None ,
headers : Optional [ Dict [ str , str ]] = None ,
timeout : Optional [ float ] = None ,
max_retries : Optional [ int ] = None ,
stream : bool = False ,
)
method
instance-attribute
json
class-attribute
instance-attribute
json : Optional [ Dict [ str , Any ]] = None
params
class-attribute
instance-attribute
params : Optional [ Dict [ str , Any ]] = None
data
class-attribute
instance-attribute
data : Optional [ Union [ bytes , IO ]] = None
files
class-attribute
instance-attribute
files : Optional [ Dict [ str , Any ]] = None
headers : Optional [ Dict [ str , str ]] = None
timeout
class-attribute
instance-attribute
timeout : Optional [ float ] = None
max_retries
class-attribute
instance-attribute
max_retries : Optional [ int ] = None
stream
class-attribute
instance-attribute
APIResponse
dataclass
APIResponse (
data : Dict [ str , Any ],
request_id : Optional [ str ] = None ,
status_code : int = 200 ,
)
request_id
class-attribute
instance-attribute
request_id : Optional [ str ] = None
status_code
class-attribute
instance-attribute
from_http_response
classmethod
from_http_response ( response , exceptions_module )
Source code in dashscope/applications/agentstudio/transport.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72 @classmethod
def from_http_response ( cls , response , exceptions_module ):
content_type = response . headers . get ( "Content-Type" , "" )
if response . status_code < 400 and not content_type . startswith (
"application/json" ,
):
payload = {
"_binary" : response . content ,
"_content_type" : content_type ,
}
else :
try :
payload = response . json ()
except ValueError :
payload = { "raw" : response . text }
if response . status_code >= 400 or is_error_payload ( payload ):
raise exceptions_module . from_response (
status_code = response . status_code ,
body = payload ,
headers = response . headers ,
)
data , request_id = unwrap ( payload )
return cls (
data ,
request_id or response . headers . get ( "x-request-id" ),
response . status_code ,
)
AgentStudioError
module-attribute
AgentStudioError = DashScopeError
APIConnectionError
APIConnectionError (
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any
)
Bases: _CatalogSdkError
Network-level failure (connection refused, DNS, TLS...).
Backed by the catalog's sdk.ConnectionError entry: code /
solution / allow_retry default from it, so every raise site
is catalog-identical without repeating the wiring. Pass detail
instead of message to use the entry's message template.
Source code in dashscope/errors.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189 def __init__ (
self ,
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any ,
) -> None :
entry = _SDK_ERRORS [ self . _SDK_ERROR_NAME ]
if message is None :
message = entry . format_message ({ "detail" : detail or "" })
kwargs . setdefault ( "code" , entry . name )
kwargs . setdefault ( "solution" , entry . solution )
kwargs . setdefault ( "allow_retry" , entry . allow_retry )
super () . __init__ ( message , ** kwargs )
APITimeoutError
APITimeoutError (
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any
)
Bases: APIConnectionError
Request timed out; backed by the catalog's sdk.Timeout entry.
Source code in dashscope/errors.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189 def __init__ (
self ,
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any ,
) -> None :
entry = _SDK_ERRORS [ self . _SDK_ERROR_NAME ]
if message is None :
message = entry . format_message ({ "detail" : detail or "" })
kwargs . setdefault ( "code" , entry . name )
kwargs . setdefault ( "solution" , entry . solution )
kwargs . setdefault ( "allow_retry" , entry . allow_retry )
super () . __init__ ( message , ** kwargs )
APIStatusError
APIStatusError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None
)
Bases: DashScopeError
A failure the gateway declared, on either layer of the model.
Both a non-2xx HTTP status and an HTTP 200 whose body carries a
business code land here; the instance's status_code says
which one it was.
Source code in dashscope/errors.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None ,
) -> None :
super () . __init__ ( message )
self . message = message
self . code = code
self . status_code = status_code
self . request_id = request_id
self . body = body
self . headers = headers or {}
status_code
class-attribute
instance-attribute
status_code : Optional [ int ] = None
AuthenticationError
AuthenticationError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None
)
Bases: APIStatusError
Source code in dashscope/errors.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None ,
) -> None :
super () . __init__ ( message )
self . message = message
self . code = code
self . status_code = status_code
self . request_id = request_id
self . body = body
self . headers = headers or {}
status_code
class-attribute
instance-attribute
status_code = _CATALOG_STATUS [ 'AuthenticationError' ]
PermissionDeniedError
PermissionDeniedError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None
)
Bases: APIStatusError
Source code in dashscope/errors.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None ,
) -> None :
super () . __init__ ( message )
self . message = message
self . code = code
self . status_code = status_code
self . request_id = request_id
self . body = body
self . headers = headers or {}
status_code
class-attribute
instance-attribute
status_code = _CATALOG_STATUS [ 'PermissionDeniedError' ]
NotFoundError
NotFoundError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None
)
Bases: APIStatusError
Source code in dashscope/errors.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None ,
) -> None :
super () . __init__ ( message )
self . message = message
self . code = code
self . status_code = status_code
self . request_id = request_id
self . body = body
self . headers = headers or {}
status_code
class-attribute
instance-attribute
status_code = _CATALOG_STATUS [ 'NotFoundError' ]
ConflictError
module-attribute
ConflictError = APIStatusError
InvalidRequestError
module-attribute
InvalidRequestError = BadRequestError
RateLimitError
RateLimitError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None
)
Bases: APIStatusError
Source code in dashscope/errors.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None ,
) -> None :
super () . __init__ ( message )
self . message = message
self . code = code
self . status_code = status_code
self . request_id = request_id
self . body = body
self . headers = headers or {}
status_code
class-attribute
instance-attribute
status_code = _CATALOG_STATUS [ 'RateLimitError' ]
OverloadedError
module-attribute
OverloadedError = ServiceUnavailableError
InternalServerError
InternalServerError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None
)
Bases: APIStatusError
Source code in dashscope/errors.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
headers : Optional [ Mapping [ str , str ]] = None ,
) -> None :
super () . __init__ ( message )
self . message = message
self . code = code
self . status_code = status_code
self . request_id = request_id
self . body = body
self . headers = headers or {}
status_code
class-attribute
instance-attribute
status_code = _CATALOG_STATUS [ 'InternalServerError' ]
StreamError
StreamError (
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any
)
Bases: _CatalogSdkError
The SSE stream encountered a fatal protocol error.
Backed by the catalog's sdk.agentstudio.StreamError entry:
code / solution / allow_retry default from it.
Source code in dashscope/errors.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189 def __init__ (
self ,
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any ,
) -> None :
entry = _SDK_ERRORS [ self . _SDK_ERROR_NAME ]
if message is None :
message = entry . format_message ({ "detail" : detail or "" })
kwargs . setdefault ( "code" , entry . name )
kwargs . setdefault ( "solution" , entry . solution )
kwargs . setdefault ( "allow_retry" , entry . allow_retry )
super () . __init__ ( message , ** kwargs )
StreamClosedError
StreamClosedError (
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any
)
Bases: StreamError
Attempted I/O on an already-closed stream.
Backed by the catalog's sdk.agentstudio.StreamClosedError entry.
Source code in dashscope/errors.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189 def __init__ (
self ,
message : Optional [ str ] = None ,
* ,
detail : Optional [ str ] = None ,
** kwargs : Any ,
) -> None :
entry = _SDK_ERRORS [ self . _SDK_ERROR_NAME ]
if message is None :
message = entry . format_message ({ "detail" : detail or "" })
kwargs . setdefault ( "code" , entry . name )
kwargs . setdefault ( "solution" , entry . solution )
kwargs . setdefault ( "allow_retry" , entry . allow_retry )
super () . __init__ ( message , ** kwargs )
Sandbox
Use client.sandbox on an AgentStudio client, or create SandboxClient /
AsyncSandboxClient directly, to manage templates, instances, files, managed
Harness Agents and native Web UI previews.
Clients
SandboxClient
SandboxClient (
* ,
base_url : str ,
api_key : str ,
timeout : float = 30.0 ,
poll_interval : float = 0.35 ,
http_client : Optional [ Client ] = None
)
Synchronous Sandbox API; model credentials are configured separately.
close() closes local subscriptions and owned HTTP connections. Release
remote instances explicitly; close native previews before the client.
Source code in dashscope/applications/agentstudio/sandbox/client.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 def __init__ (
self ,
* ,
base_url : str ,
api_key : str ,
timeout : float = 30.0 ,
poll_interval : float = 0.35 ,
http_client : Optional [ httpx . Client ] = None ,
) -> None :
self . _transport = Transport (
base_url ,
api_key ,
timeout ,
poll_interval ,
http_client ,
)
self . agents = AgentsClient ( self . _transport )
self . sandboxes = SandboxesClient ( self . _transport )
self . templates = TemplatesClient ( self . _transport )
self . template_files = TemplateFilesClient ( self . _transport )
agents
instance-attribute
agents = AgentsClient ( self . _transport )
sandboxes
instance-attribute
sandboxes = SandboxesClient ( self . _transport )
templates
instance-attribute
templates = TemplatesClient ( self . _transport )
template_files
instance-attribute
template_files = TemplateFilesClient ( self . _transport )
close
Source code in dashscope/applications/agentstudio/sandbox/client.py
def close ( self ) -> None :
self . _transport . close ()
AsyncSandboxClient
AsyncSandboxClient (
* ,
base_url : str ,
api_key : str ,
timeout : float = 30.0 ,
poll_interval : float = 0.35 ,
http_client : Optional [ AsyncClient ] = None
)
Asynchronous equivalent of :class:SandboxClient.
Source code in dashscope/applications/agentstudio/sandbox/client.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 def __init__ (
self ,
* ,
base_url : str ,
api_key : str ,
timeout : float = 30.0 ,
poll_interval : float = 0.35 ,
http_client : Optional [ httpx . AsyncClient ] = None ,
) -> None :
self . _transport = AsyncTransport (
base_url ,
api_key ,
timeout ,
poll_interval ,
http_client ,
)
self . agents = AsyncAgentsClient ( self . _transport )
self . sandboxes = AsyncSandboxesClient ( self . _transport )
self . templates = AsyncTemplatesClient ( self . _transport )
self . template_files = AsyncTemplateFilesClient ( self . _transport )
agents
instance-attribute
agents = AsyncAgentsClient ( self . _transport )
sandboxes
instance-attribute
sandboxes = AsyncSandboxesClient ( self . _transport )
templates
instance-attribute
templates = AsyncTemplatesClient ( self . _transport )
template_files
instance-attribute
template_files = AsyncTemplateFilesClient ( self . _transport )
aclose
async
Source code in dashscope/applications/agentstudio/sandbox/client.py
async def aclose ( self ) -> None :
await self . _transport . aclose ()
Exceptions
SandboxAPIError
SandboxAPIError (
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
outcome_unknown : bool = False
)
Bases: DashScopeError
A platform error, including an unconfirmed mutating request.
Source code in dashscope/applications/agentstudio/sandbox/exceptions.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 def __init__ (
self ,
message : str ,
* ,
code : Optional [ str ] = None ,
status_code : Optional [ int ] = None ,
request_id : Optional [ str ] = None ,
body : Any = None ,
outcome_unknown : bool = False ,
) -> None :
super () . __init__ (
message ,
code = code ,
status_code = status_code ,
request_id = request_id ,
body = body ,
)
self . outcome_unknown = outcome_unknown
outcome_unknown
instance-attribute
outcome_unknown = outcome_unknown
SandboxWaitTimeoutError
SandboxWaitTimeoutError ( resource_id : str , status : str )
Bases: SandboxAPIError , TimeoutError
Waiting ended; the resource ID remains usable for a later query.
Source code in dashscope/applications/agentstudio/sandbox/exceptions.py
def __init__ ( self , resource_id : str , status : str ) -> None :
super () . __init__ (
"Sandbox resource wait timed out" ,
code = "WAIT_TIMEOUT" ,
)
self . resource_id = resource_id
self . status = status
resource_id
instance-attribute
resource_id = resource_id
status
instance-attribute
Models and requests
OfficialImage
Bases: str , Enum
CODE_INTERPRETER
class-attribute
instance-attribute
CODE_INTERPRETER = 'code-interpreter-v1'
BROWSER
class-attribute
instance-attribute
ALL_IN_ONE
class-attribute
instance-attribute
ALL_IN_ONE = 'all-in-one'
DEEPSEEK_HARNESS
class-attribute
instance-attribute
DEEPSEEK_HARNESS = 'deepseek-harness'
OPENCLAW
class-attribute
instance-attribute
ModelConfig
Bases: Input
base_url
class-attribute
instance-attribute
base_url : Optional [ str ] = None
api_key
class-attribute
instance-attribute
api_key : Optional [ str ] = Field ( default = None , repr = False )
trim_optional
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "base_url" , "model_id" , "api_key" , mode = "before" )
@classmethod
def trim_optional ( cls , value ):
if isinstance ( value , str ):
return value . strip () or None
return value
validate_model
Source code in dashscope/applications/agentstudio/sandbox/models.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118 @model_validator ( mode = "after" )
def validate_model ( self ):
if not self . base_url and ( self . model_id or self . api_key ):
raise ValueError ( "base_url is required when configuring a model" )
if self . base_url :
object . __setattr__ (
self ,
"base_url" ,
http_url ( self . base_url , "base_url" ),
)
object . __setattr__ (
self ,
"model_id" ,
self . model_id or "qwen3.7-plus" ,
)
return self
LaunchRequest
Bases: Input
image
class-attribute
instance-attribute
image : Optional [ OfficialImage ] = Field (
default = None , exclude = True
)
harness_type
class-attribute
instance-attribute
harness_type : Optional [ str ] = None
image_name
class-attribute
instance-attribute
image_name : Optional [ str ] = None
image_url
class-attribute
instance-attribute
image_url : Optional [ str ] = None
template_id
class-attribute
instance-attribute
template_id : Optional [ str ] = None
template_name
class-attribute
instance-attribute
template_name : Optional [ str ] = Field (
default = None , max_length = 128
)
compute
class-attribute
instance-attribute
compute : Optional [ Compute ] = None
model
class-attribute
instance-attribute
model : Optional [ ModelConfig ] = Field (
default = None , alias = "model_config"
)
runtime_budget_seconds
class-attribute
instance-attribute
runtime_budget_seconds : Optional [ int ] = None
validate_budget
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
137
138
139
140
141
142
143
144 @field_validator ( "runtime_budget_seconds" , mode = "before" )
@classmethod
def validate_budget ( cls , value ):
return (
None
if value is None
else seconds ( value , "runtime_budget_seconds" , 300 , 604800 )
)
validate_selection
Source code in dashscope/applications/agentstudio/sandbox/models.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173 @model_validator ( mode = "after" )
def validate_selection ( self ):
image = self . image
if image is not None and not image . supports_agent :
raise ValueError ( "This official image has no Harness Agent" )
harness = self . harness_type or ( image . value if image else None )
if harness not in ( "deepseek-harness" , "openclaw" ):
raise ValueError ( "Select DeepSeek Harness or OpenClaw" )
if image and harness != image . value :
raise ValueError ( "image and harness_type must match" )
object . __setattr__ ( self , "harness_type" , harness )
if self . template_id :
resource_id ( self . template_id )
if any (
value is not None
for value in (
self . image_name ,
self . image_url ,
self . template_name ,
self . compute ,
)
):
raise ValueError (
"template_id conflicts with new-template settings" ,
)
elif image is not None and self . image_name is None :
object . __setattr__ ( self , "image_name" , image . value )
return self
Compute
Bases: Record
cpu
class-attribute
instance-attribute
cpu : int = Field ( gt = 0 , strict = True )
memory_mib
class-attribute
instance-attribute
memory_mib : int = Field ( gt = 0 , strict = True )
FileMount
Bases: Input
origin_file_id
class-attribute
instance-attribute
origin_file_id : str = Field ( alias = 'originFileId' )
mount_path
class-attribute
instance-attribute
mount_path : str = Field ( alias = 'mountPath' )
origin_file_name
class-attribute
instance-attribute
origin_file_name : Optional [ str ] = Field (
default = None , alias = "originFileName"
)
validate_mount
Source code in dashscope/applications/agentstudio/sandbox/models.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197 @model_validator ( mode = "after" )
def validate_mount ( self ):
resource_id ( self . origin_file_id )
path = required ( self . mount_path , "mount_path" )
if (
not path . startswith ( "/home/user/workspace/uploads/" )
or path . endswith ( "/" )
or any ( part in ( "." , ".." ) for part in path . split ( "/" ))
or any ( ord ( c ) < 32 or ord ( c ) == 127 for c in path )
):
raise ValueError (
"mount_path must be a file under workspace/uploads" ,
)
return self
TemplateCreateRequest
Bases: Input
image
class-attribute
instance-attribute
image : Optional [ OfficialImage ] = Field (
default = None , exclude = True
)
from_image
class-attribute
instance-attribute
from_image : Optional [ str ] = Field (
default = None , alias = "fromImage"
)
image_name
class-attribute
instance-attribute
image_name : Optional [ str ] = Field (
default = None , alias = "imageName"
)
harness_type
class-attribute
instance-attribute
harness_type : Optional [
Literal [ "dsh" , "openclaw" , "codex" , "hermes" ]
] = Field ( default = None , alias = "harnessType" )
cpu_count
class-attribute
instance-attribute
cpu_count : int = Field ( alias = 'cpuCount' , gt = 0 , strict = True )
memory_mb
class-attribute
instance-attribute
memory_mb : int = Field ( alias = 'memoryMB' , gt = 0 , strict = True )
description
class-attribute
instance-attribute
description : Optional [ str ] = None
model
class-attribute
instance-attribute
model : Optional [ ModelConfig ] = Field (
default = None ,
alias = "modelConfig" ,
validation_alias = AliasChoices (
"model_config" , "modelConfig"
),
)
env_config
class-attribute
instance-attribute
env_config : Optional [ Dict [ str , str ]] = Field (
default = None , alias = "envConfig"
)
network_config
class-attribute
instance-attribute
network_config : Optional [ Dict [ str , Any ]] = Field (
default = None , alias = "networkConfig"
)
hook_config
class-attribute
instance-attribute
hook_config : Optional [ Dict [ str , Any ]] = Field (
default = None , alias = "hookConfig"
)
mounts
class-attribute
instance-attribute
mounts : Optional [ List [ FileMount ]] = Field (
default = None , alias = "mntConfig"
)
auto_pause_time
class-attribute
instance-attribute
auto_pause_time : Optional [ int ] = Field (
default = None , alias = "autoPauseTime"
)
max_running_timeout
class-attribute
instance-attribute
max_running_timeout : Optional [ int ] = Field (
default = None , alias = "maxRunningTimeout"
)
omit_empty_model
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "model" )
@classmethod
def omit_empty_model ( cls , model ):
return model if model is not None and model . base_url else None
serialize_template_model
serialize_template_model ( model )
Source code in dashscope/applications/agentstudio/sandbox/models.py
243
244
245
246
247
248
249
250
251
252
253
254
255 @field_serializer ( "model" , when_used = "json" )
def serialize_template_model ( self , model ):
if model is None :
return None
# 模板沿用管控台字段;托管 Agent 的 model_config 协议保持不变。
values = {
"modelName" : model . model_id ,
"baseUrl" : model . base_url ,
"apiKey" : model . api_key ,
}
return {
name : value for name , value in values . items () if value is not None
}
validate_name
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "name" )
@classmethod
def validate_name ( cls , value ):
return required ( value , "name" )
validate_harness_selection
validate_harness_selection ()
Source code in dashscope/applications/agentstudio/sandbox/models.py
262
263
264
265
266
267
268
269
270
271
272
273
274 @model_validator ( mode = "after" )
def validate_harness_selection ( self ):
if self . image is not None and self . harness_type is not None :
if not self . image . supports_agent :
raise ValueError ( "harness_type requires a Harness image" )
expected = (
"dsh"
if self . image is OfficialImage . DEEPSEEK_HARNESS
else "openclaw"
)
if self . harness_type != expected :
raise ValueError ( "harness_type must match the selected image" )
return self
validate_lifetime
classmethod
validate_lifetime ( value , info )
Source code in dashscope/applications/agentstudio/sandbox/models.py
276
277
278
279
280
281
282
283 @field_validator ( "auto_pause_time" , "max_running_timeout" , mode = "before" )
@classmethod
def validate_lifetime ( cls , value , info ):
return (
None
if value is None
else seconds ( value , info . field_name , 300 , 604800 )
)
TemplateUpdateRequest
Bases: Input
name
class-attribute
instance-attribute
name : Optional [ str ] = None
from_image
class-attribute
instance-attribute
from_image : Optional [ str ] = Field (
default = None , alias = "fromImage"
)
image_name
class-attribute
instance-attribute
image_name : Optional [ str ] = Field (
default = None , alias = "imageName"
)
harness_type
class-attribute
instance-attribute
harness_type : Optional [
Literal [ "dsh" , "openclaw" , "codex" , "hermes" ]
] = Field ( default = None , alias = "harnessType" )
cpu_count
class-attribute
instance-attribute
cpu_count : Optional [ int ] = Field (
default = None , alias = "cpuCount" , gt = 0 , strict = True
)
memory_mb
class-attribute
instance-attribute
memory_mb : Optional [ int ] = Field (
default = None , alias = "memoryMB" , gt = 0 , strict = True
)
description
class-attribute
instance-attribute
description : Optional [ str ] = None
env_config
class-attribute
instance-attribute
env_config : Optional [ Dict [ str , str ]] = Field (
default = None , alias = "envConfig"
)
network_config
class-attribute
instance-attribute
network_config : Optional [ Dict [ str , Any ]] = Field (
default = None , alias = "networkConfig"
)
hook_config
class-attribute
instance-attribute
hook_config : Optional [ Dict [ str , Any ]] = Field (
default = None , alias = "hookConfig"
)
mounts
class-attribute
instance-attribute
mounts : Optional [ List [ FileMount ]] = Field (
default = None , alias = "mntConfig"
)
auto_pause_time
class-attribute
instance-attribute
auto_pause_time : Optional [ int ] = Field (
default = None , alias = "autoPauseTime"
)
max_running_timeout
class-attribute
instance-attribute
max_running_timeout : Optional [ int ] = Field (
default = None , alias = "maxRunningTimeout"
)
validate_lifetime
classmethod
validate_lifetime ( value , info )
Source code in dashscope/applications/agentstudio/sandbox/models.py
328
329
330
331
332
333
334
335 @field_validator ( "auto_pause_time" , "max_running_timeout" , mode = "before" )
@classmethod
def validate_lifetime ( cls , value , info ):
return (
None
if value is None
else seconds ( value , info . field_name , 300 , 604800 )
)
paired_compute
Source code in dashscope/applications/agentstudio/sandbox/models.py
337
338
339
340
341
342
343
344
345 @model_validator ( mode = "after" )
def paired_compute ( self ):
if ( self . cpu_count is None ) != ( self . memory_mb is None ):
raise ValueError (
"cpu_count and memory_mb must be updated together" ,
)
if self . name is not None :
required ( self . name , "name" )
return self
SandboxCreateRequest
Bases: Input
template_id
class-attribute
instance-attribute
template_id : str = Field ( alias = 'templateID' )
timeout
class-attribute
instance-attribute
timeout : Optional [ int ] = None
env_vars
class-attribute
instance-attribute
env_vars : Optional [ Dict [ str , str ]] = Field (
default = None , alias = "envVars"
)
metadata : Optional [ Dict [ str , str ]] = None
allow_internet_access
class-attribute
instance-attribute
allow_internet_access : Optional [ bool ] = Field (
default = None , alias = "allowInternetAccess"
)
secure
class-attribute
instance-attribute
secure : Optional [ bool ] = None
auto_pause
class-attribute
instance-attribute
auto_pause : Optional [ bool ] = Field (
default = None , alias = "autoPause"
)
auto_pause_memory
class-attribute
instance-attribute
auto_pause_memory : Optional [ bool ] = Field (
default = None , alias = "autoPauseMemory"
)
auto_resume
class-attribute
instance-attribute
auto_resume : Optional [ bool ] = Field (
default = None , alias = "autoResume"
)
network
class-attribute
instance-attribute
network : Optional [ Dict [ str , Any ]] = None
volume_mounts
class-attribute
instance-attribute
volume_mounts : Optional [ List [ Dict [ str , Any ]]] = Field (
default = None , alias = "volumeMounts"
)
mcp
class-attribute
instance-attribute
mcp : Optional [ Dict [ str , Any ]] = None
validate_id
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "template_id" )
@classmethod
def validate_id ( cls , value ):
resource_id ( value )
return value
validate_lifetime
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "timeout" , mode = "before" )
@classmethod
def validate_lifetime ( cls , value ):
return None if value is None else seconds ( value , "timeout" )
ConnectionOptions
Bases: Input
timeout
class-attribute
instance-attribute
timeout : Optional [ int ] = None
validate_lifetime
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "timeout" , mode = "before" )
@classmethod
def validate_lifetime ( cls , value ):
return None if value is None else seconds ( value , "timeout" )
SandboxConnection
Bases: Record
domain
class-attribute
instance-attribute
domain : Optional [ str ] = None
envd_url
class-attribute
instance-attribute
envd_url : Optional [ str ] = Field (
default = None , alias = "envdUrl" , repr = False
)
envd_version
class-attribute
instance-attribute
envd_version : Optional [ str ] = Field (
default = None , alias = "envdVersion"
)
envd_access_token
class-attribute
instance-attribute
envd_access_token : Optional [ str ] = Field (
default = None , alias = "envdAccessToken" , repr = False
)
traffic_access_token
class-attribute
instance-attribute
traffic_access_token : Optional [ str ] = Field (
default = None , alias = "trafficAccessToken" , repr = False
)
SandboxInfo
Bases: Record
id
class-attribute
instance-attribute
id : str = Field (
validation_alias = AliasChoices (
"sandboxID" , "sandbox_id" , "id"
),
serialization_alias = "sandboxID" ,
)
template_id
class-attribute
instance-attribute
template_id : Optional [ str ] = Field (
default = None ,
validation_alias = AliasChoices (
"templateID" , "template_id"
),
serialization_alias = "templateID" ,
)
state
class-attribute
instance-attribute
state : Optional [ str ] = None
cpu_count
class-attribute
instance-attribute
cpu_count : Optional [ int ] = Field (
default = None , alias = "cpuCount"
)
memory_mb
class-attribute
instance-attribute
memory_mb : Optional [ int ] = Field (
default = None , alias = "memoryMB"
)
metadata : Dict [ str , str ] = Field ( default_factory = dict )
started_at
class-attribute
instance-attribute
started_at : Optional [ str ] = Field (
default = None , alias = "startedAt"
)
end_at
class-attribute
instance-attribute
end_at : Optional [ str ] = Field ( default = None , alias = 'endAt' )
connection
class-attribute
instance-attribute
connection : SandboxConnection = Field (
default_factory = SandboxConnection , repr = False
)
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "metadata" , mode = "before" )
@classmethod
def optional_metadata ( cls , value ):
return {} if value is None else value
connection_fields
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527 @model_validator ( mode = "before" )
@classmethod
def connection_fields ( cls , data ):
if isinstance ( data , Mapping ):
data = dict ( data )
data . setdefault (
"connection" ,
{
key : data [ key ]
for key in (
"domain" ,
"envdUrl" ,
"envdVersion" ,
"envdAccessToken" ,
"trafficAccessToken" ,
)
if key in data
},
)
return data
TemplateInfo
Bases: Record
id
class-attribute
instance-attribute
id : str = Field (
validation_alias = AliasChoices (
"templateID" , "templateCode" , "id"
),
serialization_alias = "templateID" ,
)
name
class-attribute
instance-attribute
name : Optional [ str ] = Field (
default = None , alias = "templateName"
)
cpu_count
class-attribute
instance-attribute
cpu_count : Optional [ int ] = Field (
default = None , alias = "cpuCount"
)
memory_mb
class-attribute
instance-attribute
memory_mb : Optional [ int ] = Field (
default = None , alias = "memoryMB"
)
build_id
class-attribute
instance-attribute
build_id : Optional [ str ] = Field (
default = None , alias = "buildID"
)
build_status
class-attribute
instance-attribute
build_status : Optional [ str ] = Field (
default = None , alias = "buildStatus"
)
version
class-attribute
instance-attribute
version : Optional [ int ] = None
description
class-attribute
instance-attribute
description : Optional [ str ] = None
from_image
class-attribute
instance-attribute
from_image : Optional [ str ] = Field (
default = None , alias = "fromImage"
)
image_name
class-attribute
instance-attribute
image_name : Optional [ str ] = Field (
default = None , alias = "imageName"
)
image_type
class-attribute
instance-attribute
image_type : Optional [ str ] = Field (
default = None , alias = "imageType"
)
env_config
class-attribute
instance-attribute
env_config : Dict [ str , str ] = Field (
default_factory = dict , alias = "envConfig"
)
mounts
class-attribute
instance-attribute
mounts : List [ TemplateMount ] = Field (
default_factory = list , alias = "mntConfig"
)
builds
class-attribute
instance-attribute
builds : List [ Dict [ str , Any ]] = Field ( default_factory = list )
optional_collections
classmethod
optional_collections ( value , info )
Source code in dashscope/applications/agentstudio/sandbox/models.py
438
439
440
441
442
443
444 @field_validator ( "env_config" , "mounts" , "builds" , mode = "before" )
@classmethod
def optional_collections ( cls , value , info ):
# 管控台历史模板可能返回 null,读取时与未配置的空集合保持一致。
if value is None :
return {} if info . field_name == "env_config" else []
return value
build_defaults
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463 @model_validator ( mode = "before" )
@classmethod
def build_defaults ( cls , data ):
if not isinstance ( data , Mapping ):
return data
data = dict ( data )
if not data . get ( "templateName" ) and data . get ( "names" ):
data [ "templateName" ] = data [ "names" ][ 0 ]
builds = data . get ( "builds" )
if (
isinstance ( builds , list )
and builds
and isinstance ( builds [ 0 ], Mapping )
):
first = builds [ 0 ]
data . setdefault ( "buildID" , first . get ( "buildID" ))
data . setdefault ( "buildStatus" , first . get ( "status" ))
return data
TemplateMount
Bases: Record
A stored mount; reading existing templates does not revalidate new mounts.
origin_file_id
class-attribute
instance-attribute
origin_file_id : Optional [ str ] = Field (
default = None , alias = "originFileId"
)
mount_path
class-attribute
instance-attribute
mount_path : Optional [ str ] = Field (
default = None , alias = "mountPath"
)
origin_file_name
class-attribute
instance-attribute
origin_file_name : Optional [ str ] = Field (
default = None , alias = "originFileName"
)
BuildStatus
Bases: Record
template_id
class-attribute
instance-attribute
template_id : Optional [ str ] = Field (
default = None , alias = "templateID"
)
build_id
class-attribute
instance-attribute
build_id : Optional [ str ] = Field (
default = None , alias = "buildID"
)
status
instance-attribute
logs
class-attribute
instance-attribute
log_entries
class-attribute
instance-attribute
log_entries : Any = Field ( default = None , alias = 'logEntries' )
reason
class-attribute
instance-attribute
AgentInstanceInfo
Bases: Record
instance_id
instance-attribute
harness_type
class-attribute
instance-attribute
harness_type : Optional [ str ] = None
image_name
class-attribute
instance-attribute
image_name : Optional [ str ] = None
image_url
class-attribute
instance-attribute
image_url : Optional [ str ] = None
template_id
class-attribute
instance-attribute
template_id : Optional [ str ] = None
build_id
class-attribute
instance-attribute
build_id : Optional [ str ] = None
default_session_id
class-attribute
instance-attribute
default_session_id : Optional [ str ] = None
sandbox_id
class-attribute
instance-attribute
sandbox_id : Optional [ str ] = None
model
class-attribute
instance-attribute
model : Optional [ Dict [ str , Any ]] = Field (
default = None , alias = "model_config" , repr = False
)
compute
class-attribute
instance-attribute
compute : Optional [ Compute ] = None
capabilities
class-attribute
instance-attribute
capabilities : Dict [ str , Any ] = Field ( default_factory = dict )
max_upload_bytes
class-attribute
instance-attribute
max_upload_bytes : Optional [ int ] = None
created_at
class-attribute
instance-attribute
created_at : Optional [ str ] = None
expires_at
class-attribute
instance-attribute
expires_at : Optional [ str ] = None
template_source
class-attribute
instance-attribute
template_source : Optional [ str ] = None
credential_source
class-attribute
instance-attribute
credential_source : Optional [ str ] = None
AgentOperationInfo
Bases: Record
operation_id
class-attribute
instance-attribute
operation_id : Optional [ str ] = None
instance_id
class-attribute
instance-attribute
instance_id : Optional [ str ] = None
status
instance-attribute
result
class-attribute
instance-attribute
result : Optional [ Dict [ str , Any ]] = None
error
class-attribute
instance-attribute
error : Optional [ Dict [ str , Any ]] = None
AgentPage
Bases: Record , Generic [T ]
next_cursor
class-attribute
instance-attribute
next_cursor : Optional [ str ] = None
AgentSessionInfo
Bases: Record
session_id
instance-attribute
instance_id
class-attribute
instance-attribute
instance_id : Optional [ str ] = None
state
class-attribute
instance-attribute
state : Optional [ str ] = None
created_at
class-attribute
instance-attribute
created_at : Optional [ str ] = None
AgentTurnInfo
Bases: Record
turn_id
instance-attribute
session_id
class-attribute
instance-attribute
session_id : Optional [ str ] = None
instance_id
class-attribute
instance-attribute
instance_id : Optional [ str ] = None
status
instance-attribute
created_at
class-attribute
instance-attribute
created_at : Optional [ str ] = None
error
class-attribute
instance-attribute
error : Optional [ Dict [ str , Any ]] = None
AgentTemplateConfig
Bases: Record
images
instance-attribute
resource_configs
instance-attribute
resource_configs : List [ Compute ]
default_compute
class-attribute
instance-attribute
default_compute : Optional [ Compute ] = None
TurnResult
Bases: Record
turn_id
instance-attribute
status
instance-attribute
session_id
class-attribute
instance-attribute
session_id : Optional [ str ] = None
output
class-attribute
instance-attribute
output : List [ Dict [ str , Any ]] = Field ( default_factory = list )
stop_reason
class-attribute
instance-attribute
stop_reason : Optional [ str ] = None
output_status
class-attribute
instance-attribute
output_status : Optional [ str ] = None
usage
class-attribute
instance-attribute
usage : Optional [ Dict [ str , Any ]] = None
error
class-attribute
instance-attribute
error : Optional [ Dict [ str , Any ]] = None
UploadedFile
Bases: Record
id
class-attribute
instance-attribute
id : str = Field ( alias = 'file_id' )
instance_id
instance-attribute
size_bytes
instance-attribute
created_at
class-attribute
instance-attribute
created_at : Optional [ str ] = None
TemplateFile
Bases: Record
type
class-attribute
instance-attribute
type : Optional [ str ] = None
filename
class-attribute
instance-attribute
filename : Optional [ str ] = None
mime_type
class-attribute
instance-attribute
mime_type : Optional [ str ] = None
size_bytes
class-attribute
instance-attribute
size_bytes : Optional [ int ] = None
downloadable
class-attribute
instance-attribute
downloadable : Optional [ bool ] = None
status
class-attribute
instance-attribute
status : Optional [ str ] = None
created_at
class-attribute
instance-attribute
request_id
class-attribute
instance-attribute
request_id : Optional [ str ] = None
UploadTicket
Bases: Record
status
class-attribute
instance-attribute
status : Optional [ str ] = None
upload_url
class-attribute
instance-attribute
upload_url : str = Field ( repr = False )
upload_expires_at
class-attribute
instance-attribute
upload_expires_at : Any = None
request_id
class-attribute
instance-attribute
request_id : Optional [ str ] = None
UploadRequest
Bases: Input
filename
instance-attribute
mime_type
class-attribute
instance-attribute
mime_type : Optional [ str ] = None
size_bytes
class-attribute
instance-attribute
size_bytes : Optional [ int ] = Field (
default = None , gt = 0 , strict = True
)
validate_filename
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
@field_validator ( "filename" )
@classmethod
def validate_filename ( cls , value ):
from ._validation import filename
return filename ( value )
Record
Bases: BaseModel
from_dict
classmethod
Source code in dashscope/applications/agentstudio/sandbox/models.py
41
42
43
44
45
46
47
48
49 @classmethod
def from_dict ( cls , data ):
try :
return cls . model_validate ( data )
except ValidationError :
raise SandboxAPIError (
"Invalid Sandbox response" ,
code = "INVALID_RESPONSE" ,
) from None
to_dict
to_dict () -> Dict [ str , Any ]
Source code in dashscope/applications/agentstudio/sandbox/models.py
def to_dict ( self ) -> Dict [ str , Any ]:
return self . model_dump ( mode = "json" , by_alias = True , exclude_none = True )
AgentImage
Bases: Record
image_url
instance-attribute
harness_type
instance-attribute
Harness Agents
AgentsClient
AgentsClient ( transport : Transport )
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def __init__ ( self , transport : Transport ):
self . _transport = transport
template_config
template_config () -> AgentTemplateConfig
Source code in dashscope/applications/agentstudio/sandbox/agents.py
223
224
225
226
227
228
229
230 def template_config ( self ) -> AgentTemplateConfig :
return AgentTemplateConfig . from_dict (
self . _transport . request (
"GET" ,
AGENT + "/template-config" ,
agent = True ,
),
)
launch_async
launch_async ( request : LaunchRequest ) -> LaunchOperation
Accept launch without waiting for the instance to become ready.
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def launch_async ( self , request : LaunchRequest ) -> LaunchOperation :
"""Accept launch without waiting for the instance to become ready."""
return self . _launch ( request )
launch
launch (
request : LaunchRequest , timeout : float = 600
) -> AgentHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
254
255
256
257
258
259
260
261
262
263
264
265
266 def launch (
self ,
request : LaunchRequest ,
timeout : float = 600 ,
) -> AgentHandle :
end = deadline ( timeout )
operation = self . _launch (
request ,
min ( self . _transport . timeout , remaining ( end , "launch" , "PENDING" )),
)
return operation . wait (
remaining ( end , operation . operation_id , "PENDING" ),
)
list_instances
list_instances (
limit : int = 50 , cursor : Optional [ str ] = None
) -> AgentPage [ AgentInstanceInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
268
269
270
271
272
273
274
275
276
277
278
279 def list_instances (
self ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentInstanceInfo ]:
data = self . _transport . request (
"GET" ,
AGENT + "/instances" ,
params = _page_params ( limit , cursor ),
agent = True ,
)
return AgentPage [ AgentInstanceInfo ] . from_dict ( data )
get_instance
get_instance ( instance_id : str ) -> AgentInstanceInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
281
282
283
284
285
286
287
288 def get_instance ( self , instance_id : str ) -> AgentInstanceInfo :
return AgentInstanceInfo . from_dict (
self . _transport . request (
"GET" ,
AGENT + "/instances/" + resource_id ( instance_id ),
agent = True ,
),
)
connect
connect ( instance_id : str ) -> AgentHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def connect ( self , instance_id : str ) -> AgentHandle :
return self . _connect ( instance_id )
release
release ( instance_id : str ) -> OperationHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
317
318
319
320
321
322
323 def release ( self , instance_id : str ) -> OperationHandle :
data = self . _transport . request (
"DELETE" ,
AGENT + "/instances/" + resource_id ( instance_id ),
agent = True ,
)
return self . operation ( _response_id ( data , "operation_id" ))
operation
operation ( operation_id : str ) -> OperationHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def operation ( self , operation_id : str ) -> OperationHandle :
return OperationHandle ( self . _transport , operation_id )
session
session ( session_id : str ) -> SessionHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def session ( self , session_id : str ) -> SessionHandle :
return SessionHandle ( self . _transport , session_id )
turn
turn ( turn_id : str ) -> TurnHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def turn ( self , turn_id : str ) -> TurnHandle :
return TurnHandle ( self . _transport , turn_id )
list_sessions
list_sessions (
instance_id : str ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentSessionInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
334
335
336
337
338
339
340
341
342
343
344
345
346 def list_sessions (
self ,
instance_id : str ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentSessionInfo ]:
data = self . _transport . request (
"GET" ,
AGENT + "/instances/" + resource_id ( instance_id ) + "/sessions" ,
params = _page_params ( limit , cursor ),
agent = True ,
)
return AgentPage [ AgentSessionInfo ] . from_dict ( data )
AsyncAgentsClient
AsyncAgentsClient ( transport : AsyncTransport )
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def __init__ ( self , transport : AsyncTransport ):
self . _transport = transport
template_config
async
template_config () -> AgentTemplateConfig
Source code in dashscope/applications/agentstudio/sandbox/agents.py
594
595
596
597
598
599
600
601 async def template_config ( self ) -> AgentTemplateConfig :
return AgentTemplateConfig . from_dict (
await self . _transport . request (
"GET" ,
AGENT + "/template-config" ,
agent = True ,
),
)
launch_async
async
launch_async (
request : LaunchRequest ,
) -> AsyncLaunchOperation
Accept a launch operation without waiting for instance readiness.
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def launch_async (
self ,
request : LaunchRequest ,
) -> AsyncLaunchOperation :
"""Accept a launch operation without waiting for instance readiness."""
return await self . _launch ( request )
launch
async
launch (
request : LaunchRequest , timeout : float = 600
) -> AsyncAgentHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
628
629
630
631
632
633
634
635
636
637
638
639
640 async def launch (
self ,
request : LaunchRequest ,
timeout : float = 600 ,
) -> AsyncAgentHandle :
end = deadline ( timeout )
operation = await self . _launch (
request ,
min ( self . _transport . timeout , remaining ( end , "launch" , "PENDING" )),
)
return await operation . wait (
remaining ( end , operation . operation_id , "PENDING" ),
)
list_instances
async
list_instances (
limit : int = 50 , cursor : Optional [ str ] = None
) -> AgentPage [ AgentInstanceInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
642
643
644
645
646
647
648
649
650
651
652
653 async def list_instances (
self ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentInstanceInfo ]:
data = await self . _transport . request (
"GET" ,
AGENT + "/instances" ,
params = _page_params ( limit , cursor ),
agent = True ,
)
return AgentPage [ AgentInstanceInfo ] . from_dict ( data )
get_instance
async
get_instance ( instance_id : str ) -> AgentInstanceInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
655
656
657
658
659
660
661
662 async def get_instance ( self , instance_id : str ) -> AgentInstanceInfo :
return AgentInstanceInfo . from_dict (
await self . _transport . request (
"GET" ,
AGENT + "/instances/" + resource_id ( instance_id ),
agent = True ,
),
)
connect
async
connect ( instance_id : str ) -> AsyncAgentHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def connect ( self , instance_id : str ) -> AsyncAgentHandle :
return await self . _connect ( instance_id )
release
async
release ( instance_id : str ) -> AsyncOperationHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
691
692
693
694
695
696
697 async def release ( self , instance_id : str ) -> AsyncOperationHandle :
data = await self . _transport . request (
"DELETE" ,
AGENT + "/instances/" + resource_id ( instance_id ),
agent = True ,
)
return self . operation ( _response_id ( data , "operation_id" ))
operation
operation ( operation_id : str ) -> AsyncOperationHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def operation ( self , operation_id : str ) -> AsyncOperationHandle :
return AsyncOperationHandle ( self . _transport , operation_id )
session
session ( session_id : str ) -> AsyncSessionHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def session ( self , session_id : str ) -> AsyncSessionHandle :
return AsyncSessionHandle ( self . _transport , session_id )
turn
turn ( turn_id : str ) -> AsyncTurnHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def turn ( self , turn_id : str ) -> AsyncTurnHandle :
return AsyncTurnHandle ( self . _transport , turn_id )
list_sessions
async
list_sessions (
instance_id : str ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentSessionInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
708
709
710
711
712
713
714
715
716
717
718
719
720 async def list_sessions (
self ,
instance_id : str ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentSessionInfo ]:
data = await self . _transport . request (
"GET" ,
AGENT + "/instances/" + resource_id ( instance_id ) + "/sessions" ,
params = _page_params ( limit , cursor ),
agent = True ,
)
return AgentPage [ AgentSessionInfo ] . from_dict ( data )
AgentHandle
AgentHandle (
transport : Transport ,
instance_id : str ,
default_session_id : str ,
info : Optional [ AgentInstanceInfo ] = None ,
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407 def __init__ (
self ,
transport : Transport ,
instance_id : str ,
default_session_id : str ,
info : Optional [ AgentInstanceInfo ] = None ,
):
resource_id ( instance_id )
self . id = instance_id
self . _transport = transport
self . _info = info
self . default_session = SessionHandle (
transport ,
default_session_id ,
instance_id ,
)
default_session
instance-attribute
default_session = SessionHandle (
transport , default_session_id , instance_id
)
get
get () -> AgentInstanceInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def get ( self ) -> AgentInstanceInfo :
self . _info = AgentsClient ( self . _transport ) . get_instance ( self . id )
return self . _info
get_info
get_info () -> AgentInstanceInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def get_info ( self ) -> AgentInstanceInfo :
return self . get ()
new_session
new_session () -> SessionHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
416
417
418
419
420
421
422
423
424
425
426
427 def new_session ( self ) -> SessionHandle :
data = self . _transport . request (
"POST" ,
AGENT + "/instances/" + resource_id ( self . id ) + "/sessions" ,
json = {},
agent = True ,
)
return SessionHandle (
self . _transport ,
_response_id ( data , "session_id" ),
self . id ,
)
list_sessions
list_sessions (
limit : int = 50 , cursor : Optional [ str ] = None
) -> AgentPage [ AgentSessionInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
429
430
431
432
433
434
435
436
437
438 def list_sessions (
self ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentSessionInfo ]:
return AgentsClient ( self . _transport ) . list_sessions (
self . id ,
limit ,
cursor ,
)
upload
upload (
name_or_path : Union [ str , Path ],
stream : Optional [ BinaryIO ] = None ,
size_bytes : int = - 1 ,
) -> UploadedFile
Stream a regular file or owned binary stream; the stream is always closed.
Source code in dashscope/applications/agentstudio/sandbox/agents.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470 def upload (
self ,
name_or_path : Union [ str , Path ],
stream : Optional [ BinaryIO ] = None ,
size_bytes : int = - 1 ,
) -> UploadedFile :
"""Stream a regular file or owned binary stream; the stream is always closed."""
name , source , size = _upload_source ( name_or_path , stream , size_bytes )
try :
info = self . _info if self . _info is not None else self . get ()
limit = (
info . max_upload_bytes
if info . max_upload_bytes is not None
else _DEFAULT_UPLOAD_LIMIT
)
if size > limit :
raise ValueError ( "upload exceeds the instance upload limit" )
headers = { "Content-Type" : "application/octet-stream" }
if size >= 0 :
headers [ "Content-Length" ] = str ( size )
data = self . _transport . request (
"POST" ,
AGENT + "/instances/" + resource_id ( self . id ) + "/files" ,
params = { "name" : name },
content = bounded_stream ( source , limit , size ),
headers = headers ,
agent = True ,
)
return _uploaded ( data , self . id , size )
finally :
source . close ()
release
release () -> OperationHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def release ( self ) -> OperationHandle :
return AgentsClient ( self . _transport ) . release ( self . id )
AsyncAgentHandle
AsyncAgentHandle (
transport : AsyncTransport ,
instance_id : str ,
default_session_id : str ,
info : Optional [ AgentInstanceInfo ] = None ,
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781 def __init__ (
self ,
transport : AsyncTransport ,
instance_id : str ,
default_session_id : str ,
info : Optional [ AgentInstanceInfo ] = None ,
):
resource_id ( instance_id )
self . id = instance_id
self . _transport = transport
self . _info = info
self . default_session = AsyncSessionHandle (
transport ,
default_session_id ,
instance_id ,
)
default_session
instance-attribute
default_session = AsyncSessionHandle (
transport , default_session_id , instance_id
)
get
async
get () -> AgentInstanceInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def get ( self ) -> AgentInstanceInfo :
self . _info = await AsyncAgentsClient ( self . _transport ) . get_instance (
self . id ,
)
return self . _info
get_info
async
get_info () -> AgentInstanceInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def get_info ( self ) -> AgentInstanceInfo :
return await self . get ()
new_session
async
new_session () -> AsyncSessionHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
792
793
794
795
796
797
798
799
800
801
802
803 async def new_session ( self ) -> AsyncSessionHandle :
data = await self . _transport . request (
"POST" ,
AGENT + "/instances/" + resource_id ( self . id ) + "/sessions" ,
json = {},
agent = True ,
)
return AsyncSessionHandle (
self . _transport ,
_response_id ( data , "session_id" ),
self . id ,
)
list_sessions
async
list_sessions (
limit : int = 50 , cursor : Optional [ str ] = None
) -> AgentPage [ AgentSessionInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
805
806
807
808
809
810
811
812
813
814 async def list_sessions (
self ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentSessionInfo ]:
return await AsyncAgentsClient ( self . _transport ) . list_sessions (
self . id ,
limit ,
cursor ,
)
upload
async
upload (
name_or_path : Union [ str , Path ],
stream : Optional [ BinaryIO ] = None ,
size_bytes : int = - 1 ,
) -> UploadedFile
Stream a regular file or owned binary stream; the stream is always closed.
Source code in dashscope/applications/agentstudio/sandbox/agents.py
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867 async def upload (
self ,
name_or_path : Union [ str , Path ],
stream : Optional [ BinaryIO ] = None ,
size_bytes : int = - 1 ,
) -> UploadedFile :
"""Stream a regular file or owned binary stream; the stream is always closed."""
name , source , size = _upload_source ( name_or_path , stream , size_bytes )
chunks = None
try :
info = self . _info if self . _info is not None else await self . get ()
limit = (
info . max_upload_bytes
if info . max_upload_bytes is not None
else _DEFAULT_UPLOAD_LIMIT
)
if size > limit :
raise ValueError ( "upload exceeds the instance upload limit" )
headers = { "Content-Type" : "application/octet-stream" }
if size >= 0 :
headers [ "Content-Length" ] = str ( size )
chunks = bounded_stream ( source , limit , size )
sentinel = object ()
async def content ():
while True :
read = asyncio . create_task (
asyncio . to_thread ( next , chunks , sentinel ),
)
try :
chunk = await asyncio . shield ( read )
except asyncio . CancelledError :
# Finish the running read before closing its owned stream.
await read
raise
if chunk is sentinel :
return
yield chunk
data = await self . _transport . request (
"POST" ,
AGENT + "/instances/" + resource_id ( self . id ) + "/files" ,
params = { "name" : name },
content = content (),
headers = headers ,
agent = True ,
)
return _uploaded ( data , self . id , size )
finally :
if chunks is not None :
chunks . close ()
source . close ()
release
async
release () -> AsyncOperationHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def release ( self ) -> AsyncOperationHandle :
return await AsyncAgentsClient ( self . _transport ) . release ( self . id )
SessionHandle
SessionHandle (
transport : Transport ,
session_id : str ,
instance_id : Optional [ str ] = None ,
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
477
478
479
480
481
482
483
484
485
486 def __init__ (
self ,
transport : Transport ,
session_id : str ,
instance_id : Optional [ str ] = None ,
):
self . id = session_id
self . _transport = transport
self . _instance_id = instance_id
self . _path = AGENT + "/sessions/" + resource_id ( session_id ) + "/turns"
submit
submit (
text : str , deadline_seconds : int = 120
) -> TurnHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def submit ( self , text : str , deadline_seconds : int = 120 ) -> TurnHandle :
return self . submit_with_files ( text , (), deadline_seconds )
submit_with_files
submit_with_files (
text : str ,
files : Sequence [ UploadedFile ],
deadline_seconds : int = 120 ,
) -> TurnHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504 def submit_with_files (
self ,
text : str ,
files : Sequence [ UploadedFile ],
deadline_seconds : int = 120 ,
) -> TurnHandle :
body = _prompt ( text , files , deadline_seconds , self . _instance_id )
data = self . _transport . request (
"POST" ,
self . _path ,
json = body ,
agent = True ,
)
return TurnHandle ( self . _transport , _response_id ( data , "turn_id" ))
list_turns
list_turns (
limit : int = 50 , cursor : Optional [ str ] = None
) -> AgentPage [ AgentTurnInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
506
507
508
509
510
511
512
513
514
515
516
517 def list_turns (
self ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentTurnInfo ]:
data = self . _transport . request (
"GET" ,
self . _path ,
params = _page_params ( limit , cursor ),
agent = True ,
)
return AgentPage [ AgentTurnInfo ] . from_dict ( data )
AsyncSessionHandle
AsyncSessionHandle (
transport : AsyncTransport ,
session_id : str ,
instance_id : Optional [ str ] = None ,
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
874
875
876
877
878
879
880
881
882
883 def __init__ (
self ,
transport : AsyncTransport ,
session_id : str ,
instance_id : Optional [ str ] = None ,
):
self . id = session_id
self . _transport = transport
self . _instance_id = instance_id
self . _path = AGENT + "/sessions/" + resource_id ( session_id ) + "/turns"
submit
async
submit (
text : str , deadline_seconds : int = 120
) -> AsyncTurnHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def submit (
self ,
text : str ,
deadline_seconds : int = 120 ,
) -> AsyncTurnHandle :
return await self . submit_with_files ( text , (), deadline_seconds )
submit_with_files
async
submit_with_files (
text : str ,
files : Sequence [ UploadedFile ],
deadline_seconds : int = 120 ,
) -> AsyncTurnHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905 async def submit_with_files (
self ,
text : str ,
files : Sequence [ UploadedFile ],
deadline_seconds : int = 120 ,
) -> AsyncTurnHandle :
body = _prompt ( text , files , deadline_seconds , self . _instance_id )
data = await self . _transport . request (
"POST" ,
self . _path ,
json = body ,
agent = True ,
)
return AsyncTurnHandle ( self . _transport , _response_id ( data , "turn_id" ))
list_turns
async
list_turns (
limit : int = 50 , cursor : Optional [ str ] = None
) -> AgentPage [ AgentTurnInfo ]
Source code in dashscope/applications/agentstudio/sandbox/agents.py
907
908
909
910
911
912
913
914
915
916
917
918 async def list_turns (
self ,
limit : int = 50 ,
cursor : Optional [ str ] = None ,
) -> AgentPage [ AgentTurnInfo ]:
data = await self . _transport . request (
"GET" ,
self . _path ,
params = _page_params ( limit , cursor ),
agent = True ,
)
return AgentPage [ AgentTurnInfo ] . from_dict ( data )
TurnHandle
TurnHandle ( transport : Transport , turn_id : str )
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def __init__ ( self , transport : Transport , turn_id : str ):
self . id = turn_id
self . _transport = transport
self . _path = AGENT + "/turns/" + resource_id ( turn_id )
get
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def get ( self ) -> TurnResult :
return TurnResult . from_dict (
self . _transport . request ( "GET" , self . _path , agent = True ),
)
wait
wait ( timeout : float = 180 ) -> TurnResult
Source code in dashscope/applications/agentstudio/sandbox/agents.py
555
556
557
558
559
560
561
562
563
564 def wait ( self , timeout : float = 180 ) -> TurnResult :
return TurnResult . from_dict (
_wait (
self . _transport ,
self . _path ,
self . id ,
timeout ,
_TURN_TERMINAL ,
),
)
cancel
Request cancellation; only returned CANCELLED confirms it.
Source code in dashscope/applications/agentstudio/sandbox/agents.py
566
567
568
569
570
571
572
573
574 def cancel ( self ) -> TurnResult :
"""Request cancellation; only returned CANCELLED confirms it."""
return TurnResult . from_dict (
self . _transport . request (
"POST" ,
self . _path + "/cancel" ,
agent = True ,
),
)
subscribe
subscribe (
callback = None , after_sequence : int = 0
) -> EventSubscription
Source code in dashscope/applications/agentstudio/sandbox/agents.py
576
577
578
579
580
581
582
583
584
585
586
587 def subscribe (
self ,
callback = None ,
after_sequence : int = 0 ,
) -> EventSubscription :
return EventSubscription (
self . _transport ,
self . _path ,
self . id ,
after_sequence ,
callback ,
)
AsyncTurnHandle
AsyncTurnHandle ( transport : AsyncTransport , turn_id : str )
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def __init__ ( self , transport : AsyncTransport , turn_id : str ):
self . id = turn_id
self . _transport = transport
self . _path = AGENT + "/turns/" + resource_id ( turn_id )
get
async
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def get ( self ) -> TurnResult :
return TurnResult . from_dict (
await self . _transport . request ( "GET" , self . _path , agent = True ),
)
wait
async
wait ( timeout : float = 180 ) -> TurnResult
Source code in dashscope/applications/agentstudio/sandbox/agents.py
956
957
958
959
960
961
962
963
964
965 async def wait ( self , timeout : float = 180 ) -> TurnResult :
return TurnResult . from_dict (
await _await (
self . _transport ,
self . _path ,
self . id ,
timeout ,
_TURN_TERMINAL ,
),
)
cancel
async
Request cancellation; only returned CANCELLED confirms it.
Source code in dashscope/applications/agentstudio/sandbox/agents.py
967
968
969
970
971
972
973
974
975 async def cancel ( self ) -> TurnResult :
"""Request cancellation; only returned CANCELLED confirms it."""
return TurnResult . from_dict (
await self . _transport . request (
"POST" ,
self . _path + "/cancel" ,
agent = True ,
),
)
subscribe
subscribe (
callback = None , after_sequence : int = 0
) -> AsyncEventSubscription
Source code in dashscope/applications/agentstudio/sandbox/agents.py
977
978
979
980
981
982
983
984
985
986
987
988 def subscribe (
self ,
callback = None ,
after_sequence : int = 0 ,
) -> AsyncEventSubscription :
return AsyncEventSubscription (
self . _transport ,
self . _path ,
self . id ,
after_sequence ,
callback ,
)
OperationHandle
OperationHandle ( transport : Transport , operation_id : str )
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def __init__ ( self , transport : Transport , operation_id : str ):
self . id = operation_id
self . _transport = transport
self . _path = AGENT + "/operations/" + resource_id ( operation_id )
get
get () -> AgentOperationInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def get ( self ) -> AgentOperationInfo :
return AgentOperationInfo . from_dict (
self . _transport . request ( "GET" , self . _path , agent = True ),
)
wait
wait ( timeout : float = 600 ) -> AgentOperationInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
531
532
533
534
535
536
537
538
539
540
541 def wait ( self , timeout : float = 600 ) -> AgentOperationInfo :
info = AgentOperationInfo . from_dict (
_wait (
self . _transport ,
self . _path ,
self . id ,
timeout ,
_OPERATION_TERMINAL ,
),
)
return _operation_result ( info )
AsyncOperationHandle
AsyncOperationHandle (
transport : AsyncTransport , operation_id : str
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
def __init__ ( self , transport : AsyncTransport , operation_id : str ):
self . id = operation_id
self . _transport = transport
self . _path = AGENT + "/operations/" + resource_id ( operation_id )
get
async
get () -> AgentOperationInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
async def get ( self ) -> AgentOperationInfo :
return AgentOperationInfo . from_dict (
await self . _transport . request ( "GET" , self . _path , agent = True ),
)
wait
async
wait ( timeout : float = 600 ) -> AgentOperationInfo
Source code in dashscope/applications/agentstudio/sandbox/agents.py
932
933
934
935
936
937
938
939
940
941
942 async def wait ( self , timeout : float = 600 ) -> AgentOperationInfo :
info = AgentOperationInfo . from_dict (
await _await (
self . _transport ,
self . _path ,
self . id ,
timeout ,
_OPERATION_TERMINAL ,
),
)
return _operation_result ( info )
LaunchOperation
LaunchOperation (
agents : AgentsClient ,
instance_id : str ,
operation_id : str ,
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
350
351
352
353
354
355
356
357
358 def __init__ (
self ,
agents : AgentsClient ,
instance_id : str ,
operation_id : str ,
):
self . _agents = agents
self . instance_id = instance_id
self . operation_id = operation_id
instance_id
instance-attribute
instance_id = instance_id
operation_id
instance-attribute
operation_id = operation_id
wait
wait ( timeout : float = 600 ) -> AgentHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388 def wait ( self , timeout : float = 600 ) -> AgentHandle :
end = deadline ( timeout )
self . _agents . operation ( self . operation_id ) . wait (
remaining ( end , self . operation_id , "PENDING" ),
)
budget = remaining ( end , self . operation_id , "SUCCEEDED" )
try :
# Internal SDK coordination preserves transport/resource ownership.
# pylint: disable-next=protected-access
handle = self . _agents . _connect (
self . instance_id ,
# Internal SDK coordination preserves transport/resource ownership.
# pylint: disable-next=protected-access
min ( self . _agents . _transport . timeout , budget ),
)
except SandboxAPIError as error :
if (
error . code == "REQUEST_TIMEOUT"
# Internal SDK coordination preserves transport/resource ownership.
# pylint: disable-next=protected-access
and budget <= self . _agents . _transport . timeout
):
raise SandboxWaitTimeoutError (
self . operation_id ,
"SUCCEEDED" ,
) from error
raise
remaining ( end , self . operation_id , "SUCCEEDED" )
return handle
AsyncLaunchOperation
AsyncLaunchOperation (
agents : AsyncAgentsClient ,
instance_id : str ,
operation_id : str ,
)
Source code in dashscope/applications/agentstudio/sandbox/agents.py
724
725
726
727
728
729
730
731
732 def __init__ (
self ,
agents : AsyncAgentsClient ,
instance_id : str ,
operation_id : str ,
):
self . _agents = agents
self . instance_id = instance_id
self . operation_id = operation_id
instance_id
instance-attribute
instance_id = instance_id
operation_id
instance-attribute
operation_id = operation_id
wait
async
wait ( timeout : float = 600 ) -> AsyncAgentHandle
Source code in dashscope/applications/agentstudio/sandbox/agents.py
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762 async def wait ( self , timeout : float = 600 ) -> AsyncAgentHandle :
end = deadline ( timeout )
await self . _agents . operation ( self . operation_id ) . wait (
remaining ( end , self . operation_id , "PENDING" ),
)
budget = remaining ( end , self . operation_id , "SUCCEEDED" )
try :
# Internal SDK coordination preserves transport/resource ownership.
# pylint: disable-next=protected-access
handle = await self . _agents . _connect (
self . instance_id ,
# Internal SDK coordination preserves transport/resource ownership.
# pylint: disable-next=protected-access
min ( self . _agents . _transport . timeout , budget ),
)
except SandboxAPIError as error :
if (
error . code == "REQUEST_TIMEOUT"
# Internal SDK coordination preserves transport/resource ownership.
# pylint: disable-next=protected-access
and budget <= self . _agents . _transport . timeout
):
raise SandboxWaitTimeoutError (
self . operation_id ,
"SUCCEEDED" ,
) from error
raise
remaining ( end , self . operation_id , "SUCCEEDED" )
return handle
Event subscriptions
EventSubscription
EventSubscription (
transport ,
path : str ,
turn_id : str ,
after_sequence : int = 0 ,
callback : Optional [ Callable [[ dict ], Any ]] = None ,
)
Iterate SSE events, or consume them on one callback reader thread.
wait waits for a callback subscription to finish and propagates callback
or stream failures. close only disconnects this HTTP subscription.
No reconnect or Turn resubmission is performed automatically.
Source code in dashscope/applications/agentstudio/sandbox/streaming.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158 def __init__ (
self ,
transport ,
path : str ,
turn_id : str ,
after_sequence : int = 0 ,
callback : Optional [ Callable [[ dict ], Any ]] = None ,
):
if callback is not None and not callable ( callback ):
raise ValueError ( "callback must be callable" )
self . _decoder = _EventDecoder ( turn_id , after_sequence )
self . _transport = transport
self . _path = path + "/events"
self . _callback = callback
self . _context = None
self . _response = None
self . _closed = False
self . _iterator : Optional [ Iterator [ dict ]] = None
self . _error : Optional [ BaseException ] = None
self . _completion = threading . Event ()
self . _thread : Optional [ threading . Thread ] = None
transport . register ( self )
if callback is not None :
self . _thread = threading . Thread (
target = self . _consume ,
name = "dashscope-sandbox-sse" ,
daemon = True ,
)
self . _thread . start ()
wait
wait ( timeout : Optional [ float ] = None ) -> None
Source code in dashscope/applications/agentstudio/sandbox/streaming.py
229
230
231
232
233
234
235
236
237
238
239 def wait ( self , timeout : Optional [ float ] = None ) -> None :
if self . _callback is None :
raise ValueError (
"wait requires a callback subscription; iterate events otherwise" ,
)
if timeout is not None :
timeout = positive ( timeout , "timeout" )
if not self . _completion . wait ( timeout ):
raise SandboxWaitTimeoutError ( self . _decoder . turn_id , "SUBSCRIBED" )
if self . _error is not None :
raise self . _error
close
Source code in dashscope/applications/agentstudio/sandbox/streaming.py
241
242
243
244
245
246
247
248
249
250
251
252 def close ( self ) -> None :
if self . _closed :
return
self . _closed = True
try :
if self . _response is not None :
self . _response . close ()
if self . _context is not None and self . _response is not None :
self . _context . __exit__ ( None , None , None )
self . _context = None
finally :
self . _transport . unregister ( self )
AsyncEventSubscription
AsyncEventSubscription (
transport ,
path : str ,
turn_id : str ,
after_sequence : int = 0 ,
callback : Optional [ Callable [[ dict ], Any ]] = None ,
)
Async iteration or one callback task, with local-only cancellation.
A callback may be synchronous or return an awaitable; callbacks run in event
order on the reader task. Avoid blocking work in synchronous callbacks.
Source code in dashscope/applications/agentstudio/sandbox/streaming.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297 def __init__ (
self ,
transport ,
path : str ,
turn_id : str ,
after_sequence : int = 0 ,
callback : Optional [ Callable [[ dict ], Any ]] = None ,
):
if callback is not None and not callable ( callback ):
raise ValueError ( "callback must be callable" )
self . _decoder = _EventDecoder ( turn_id , after_sequence )
self . _transport = transport
self . _path = path + "/events"
self . _callback = callback
self . _context = None
self . _response = None
self . _closed = False
self . _iterator : Optional [ AsyncIterator [ dict ]] = None
self . _task : Optional [ asyncio . Task ] = None
transport . register ( self )
if callback is not None :
try :
self . _task = asyncio . get_running_loop () . create_task (
self . _consume (),
)
except BaseException :
transport . unregister ( self )
raise
wait
async
wait ( timeout : Optional [ float ] = None ) -> None
Source code in dashscope/applications/agentstudio/sandbox/streaming.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381 async def wait ( self , timeout : Optional [ float ] = None ) -> None :
if self . _task is None :
raise ValueError (
"wait requires a callback subscription; iterate events otherwise" ,
)
if timeout is not None :
timeout = positive ( timeout , "timeout" )
try :
await asyncio . wait_for ( asyncio . shield ( self . _task ), timeout )
except asyncio . TimeoutError :
raise SandboxWaitTimeoutError (
self . _decoder . turn_id ,
"SUBSCRIBED" ,
) from None
except asyncio . CancelledError :
await self . aclose ()
raise
aclose
async
Source code in dashscope/applications/agentstudio/sandbox/streaming.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404 async def aclose ( self ) -> None :
if self . _closed :
return
self . _closed = True
try :
if self . _response is not None :
await self . _response . aclose ()
if self . _context is not None and self . _response is not None :
await self . _context . __aexit__ ( None , None , None )
self . _context = None
finally :
self . _transport . unregister ( self )
if (
self . _task is not None
and self . _task is not asyncio . current_task ()
and not self . _task . done ()
):
self . _task . cancel ()
try :
await self . _task
except asyncio . CancelledError :
pass
Sandbox instances
SandboxesClient
SandboxesClient ( transport : Transport )
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def __init__ ( self , transport : Transport ):
self . _http = transport
create
create ( request : SandboxCreateRequest ) -> SandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
48
49
50
51
52
53
54
55
56
57
58 def create ( self , request : SandboxCreateRequest ) -> "SandboxHandle" :
return SandboxHandle (
self ,
SandboxInfo . from_dict (
self . _http . request (
"POST" ,
SANDBOX + "/sandboxes" ,
json = request . to_dict (),
),
),
)
list
list (
template_id : Optional [ str ] = None ,
sandbox_id : Optional [ str ] = None ,
state : Optional [ str ] = None ,
limit : int = 100 ,
) -> List [ SandboxInfo ]
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73 def list (
self ,
template_id : Optional [ str ] = None ,
sandbox_id : Optional [ str ] = None ,
state : Optional [ str ] = None ,
limit : int = 100 ,
) -> List [ SandboxInfo ]:
return _list (
self . _http . request (
"GET" ,
SANDBOX + "/v2/sandboxes" ,
params = _query ( template_id , sandbox_id , state , limit ),
),
)
get
get ( sandbox_id : str ) -> SandboxInfo
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def get ( self , sandbox_id : str ) -> SandboxInfo :
return SandboxInfo . from_dict (
self . _http . request ( "GET" , _path ( sandbox_id )),
)
connect
connect (
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> SandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94 def connect (
self ,
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> "SandboxHandle" :
return SandboxHandle (
self ,
SandboxInfo . from_dict (
self . _http . request (
"POST" ,
_path ( sandbox_id ) + "/connect" ,
json = options . to_dict () if options is not None else {},
),
),
)
pause
pause ( sandbox_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def pause ( self , sandbox_id : str ) -> None :
self . _http . request ( "POST" , _path ( sandbox_id ) + "/pause" , json = {})
resume
resume (
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> SandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113 def resume (
self ,
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> "SandboxHandle" :
return SandboxHandle (
self ,
SandboxInfo . from_dict (
self . _http . request (
"POST" ,
_path ( sandbox_id ) + "/resume" ,
json = options . to_dict () if options is not None else {},
),
),
)
release
release ( sandbox_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def release ( self , sandbox_id : str ) -> None :
self . _http . request ( "DELETE" , _path ( sandbox_id ))
open_web_ui
open_web_ui ( image : OfficialImage , options = None )
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def open_web_ui ( self , image : OfficialImage , options = None ):
from .web_ui import open_web_ui
return open_web_ui ( self , self . _http , image , options )
AsyncSandboxesClient
AsyncSandboxesClient ( transport : AsyncTransport )
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def __init__ ( self , transport : AsyncTransport ):
self . _http = transport
create
async
create ( request : SandboxCreateRequest ) -> AsyncSandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195 async def create (
self ,
request : SandboxCreateRequest ,
) -> "AsyncSandboxHandle" :
return AsyncSandboxHandle (
self ,
SandboxInfo . from_dict (
await self . _http . request (
"POST" ,
SANDBOX + "/sandboxes" ,
json = request . to_dict (),
),
),
)
list
async
list (
template_id : Optional [ str ] = None ,
sandbox_id : Optional [ str ] = None ,
state : Optional [ str ] = None ,
limit : int = 100 ,
) -> List [ SandboxInfo ]
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210 async def list (
self ,
template_id : Optional [ str ] = None ,
sandbox_id : Optional [ str ] = None ,
state : Optional [ str ] = None ,
limit : int = 100 ,
) -> List [ SandboxInfo ]:
return _list (
await self . _http . request (
"GET" ,
SANDBOX + "/v2/sandboxes" ,
params = _query ( template_id , sandbox_id , state , limit ),
),
)
get
async
get ( sandbox_id : str ) -> SandboxInfo
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def get ( self , sandbox_id : str ) -> SandboxInfo :
return SandboxInfo . from_dict (
await self . _http . request ( "GET" , _path ( sandbox_id )),
)
connect
async
connect (
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> AsyncSandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231 async def connect (
self ,
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> "AsyncSandboxHandle" :
return AsyncSandboxHandle (
self ,
SandboxInfo . from_dict (
await self . _http . request (
"POST" ,
_path ( sandbox_id ) + "/connect" ,
json = options . to_dict () if options is not None else {},
),
),
)
pause
async
pause ( sandbox_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def pause ( self , sandbox_id : str ) -> None :
await self . _http . request ( "POST" , _path ( sandbox_id ) + "/pause" , json = {})
resume
async
resume (
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> AsyncSandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250 async def resume (
self ,
sandbox_id : str ,
options : Optional [ ConnectionOptions ] = None ,
) -> "AsyncSandboxHandle" :
return AsyncSandboxHandle (
self ,
SandboxInfo . from_dict (
await self . _http . request (
"POST" ,
_path ( sandbox_id ) + "/resume" ,
json = options . to_dict () if options is not None else {},
),
),
)
release
async
release ( sandbox_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def release ( self , sandbox_id : str ) -> None :
await self . _http . request ( "DELETE" , _path ( sandbox_id ))
open_web_ui
async
open_web_ui ( image : OfficialImage , options = None )
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def open_web_ui ( self , image : OfficialImage , options = None ):
from .web_ui import async_open_web_ui
return await async_open_web_ui ( self , self . _http , image , options )
SandboxHandle
SandboxHandle ( client : SandboxesClient , info : SandboxInfo )
A handle holds connection details; release is always explicit.
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def __init__ ( self , client : SandboxesClient , info : SandboxInfo ):
self . _client = client
self . _id = info . id
self . _template_id = info . template_id
self . _connection = info . connection
template_id
property
template_id : Optional [ str ]
connection
property
connection : Optional [ SandboxConnection ]
get
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def get ( self ) -> SandboxInfo :
info = self . _client . get ( self . id )
self . _connection = info . connection
return info
connect
connect (
options : Optional [ ConnectionOptions ] = None ,
) -> SandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def connect (
self ,
options : Optional [ ConnectionOptions ] = None ,
) -> "SandboxHandle" :
self . _connection = self . _client . connect ( self . id , options ) . connection
return self
pause
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def pause ( self ) -> None :
self . _client . pause ( self . id )
resume
resume (
options : Optional [ ConnectionOptions ] = None ,
) -> SandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def resume (
self ,
options : Optional [ ConnectionOptions ] = None ,
) -> "SandboxHandle" :
self . _connection = self . _client . resume ( self . id , options ) . connection
return self
release
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def release ( self ) -> None :
self . _client . release ( self . id )
AsyncSandboxHandle
AsyncSandboxHandle (
client : AsyncSandboxesClient , info : SandboxInfo
)
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
def __init__ ( self , client : AsyncSandboxesClient , info : SandboxInfo ):
self . _client = client
self . _id = info . id
self . _template_id = info . template_id
self . _connection = info . connection
template_id
property
template_id : Optional [ str ]
connection
property
connection : Optional [ SandboxConnection ]
get
async
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def get ( self ) -> SandboxInfo :
info = await self . _client . get ( self . id )
self . _connection = info . connection
return info
connect
async
connect (
options : Optional [ ConnectionOptions ] = None ,
) -> AsyncSandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
289
290
291
292
293
294
295
296 async def connect (
self ,
options : Optional [ ConnectionOptions ] = None ,
) -> "AsyncSandboxHandle" :
self . _connection = (
await self . _client . connect ( self . id , options )
) . connection
return self
pause
async
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def pause ( self ) -> None :
await self . _client . pause ( self . id )
resume
async
resume (
options : Optional [ ConnectionOptions ] = None ,
) -> AsyncSandboxHandle
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
301
302
303
304
305
306
307
308 async def resume (
self ,
options : Optional [ ConnectionOptions ] = None ,
) -> "AsyncSandboxHandle" :
self . _connection = (
await self . _client . resume ( self . id , options )
) . connection
return self
release
async
Source code in dashscope/applications/agentstudio/sandbox/sandboxes.py
async def release ( self ) -> None :
await self . _client . release ( self . id )
Templates
TemplatesClient
TemplatesClient ( transport : Transport )
Source code in dashscope/applications/agentstudio/sandbox/templates.py
def __init__ ( self , transport : Transport ):
self . _http = transport
create
create ( request : TemplateCreateRequest ) -> TemplateInfo
Source code in dashscope/applications/agentstudio/sandbox/templates.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 def create ( self , request : TemplateCreateRequest ) -> TemplateInfo :
resolved = None
if request . image is not None :
# 先解析官方目录,避免在多版本或目录异常时创建错误模板。
params = (
{ "imageUrl" : request . from_image }
if request . from_image is not None
else None
)
resolved = self . _http . request (
"GET" ,
SANDBOX + "/images/" + request . image . image_name ,
params = params ,
)
return TemplateInfo . from_dict (
self . _http . request (
"POST" ,
SANDBOX + "/v3/templates" ,
json = _creation_fields ( request , resolved ),
),
)
list
list (
limit : int = 100 , page_no : int = 1
) -> List [ TemplateInfo ]
Source code in dashscope/applications/agentstudio/sandbox/templates.py
104
105
106
107
108
109
110
111
112
113
114 def list ( self , limit : int = 100 , page_no : int = 1 ) -> List [ TemplateInfo ]:
return _list (
self . _http . request (
"GET" ,
SANDBOX + "/v2/templates" ,
params = {
"limit" : seconds ( limit , "limit" ),
"pageNo" : seconds ( page_no , "page_no" ),
},
),
)
get
get ( template_id : str ) -> TemplateInfo
Source code in dashscope/applications/agentstudio/sandbox/templates.py
def get ( self , template_id : str ) -> TemplateInfo :
return TemplateInfo . from_dict (
self . _http . request ( "GET" , _path ( template_id )),
)
update
update (
template_id : str , request : TemplateUpdateRequest
) -> TemplateInfo
Source code in dashscope/applications/agentstudio/sandbox/templates.py
121
122
123
124
125
126
127
128
129
130
131
132 def update (
self ,
template_id : str ,
request : TemplateUpdateRequest ,
) -> TemplateInfo :
return TemplateInfo . from_dict (
self . _http . request (
"PUT" ,
_path ( template_id ),
json = request . to_dict (),
),
)
build_status
build_status (
template_id : str , build_id : str
) -> BuildStatus
Source code in dashscope/applications/agentstudio/sandbox/templates.py
134
135
136
137
138
139
140
141
142
143 def build_status ( self , template_id : str , build_id : str ) -> BuildStatus :
return BuildStatus . from_dict (
self . _http . request (
"GET" ,
_path ( template_id )
+ "/builds/"
+ resource_id ( build_id )
+ "/status" ,
),
)
wait_ready
wait_ready (
template_id : str , build_id : str , timeout : float = 600
) -> BuildStatus
Source code in dashscope/applications/agentstudio/sandbox/templates.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 def wait_ready (
self ,
template_id : str ,
build_id : str ,
timeout : float = 600 ,
) -> BuildStatus :
path = (
_path ( template_id ) + "/builds/" + resource_id ( build_id ) + "/status"
)
end = deadline ( timeout )
last_status = None
while True :
budget = remaining ( end , template_id , last_status )
try :
status = BuildStatus . from_dict (
self . _http . request (
"GET" ,
path ,
timeout = min ( self . _http . timeout , budget ),
),
)
except SandboxAPIError as error :
if (
error . code == "REQUEST_TIMEOUT"
and budget <= self . _http . timeout
):
raise SandboxWaitTimeoutError (
template_id ,
last_status ,
) from error
raise
last_status = status . status
remaining ( end , template_id , last_status )
if _check_build ( status ):
return status
time . sleep (
min (
self . _http . poll_interval ,
remaining ( end , template_id , last_status ),
),
)
delete
delete ( template_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/templates.py
def delete ( self , template_id : str ) -> None :
self . _http . request ( "DELETE" , _path ( template_id ))
AsyncTemplatesClient
AsyncTemplatesClient ( transport : AsyncTransport )
Source code in dashscope/applications/agentstudio/sandbox/templates.py
def __init__ ( self , transport : AsyncTransport ):
self . _http = transport
create
async
create ( request : TemplateCreateRequest ) -> TemplateInfo
Source code in dashscope/applications/agentstudio/sandbox/templates.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214 async def create ( self , request : TemplateCreateRequest ) -> TemplateInfo :
resolved = None
if request . image is not None :
params = (
{ "imageUrl" : request . from_image }
if request . from_image is not None
else None
)
resolved = await self . _http . request (
"GET" ,
SANDBOX + "/images/" + request . image . image_name ,
params = params ,
)
return TemplateInfo . from_dict (
await self . _http . request (
"POST" ,
SANDBOX + "/v3/templates" ,
json = _creation_fields ( request , resolved ),
),
)
list
async
list (
limit : int = 100 , page_no : int = 1
) -> List [ TemplateInfo ]
Source code in dashscope/applications/agentstudio/sandbox/templates.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230 async def list (
self ,
limit : int = 100 ,
page_no : int = 1 ,
) -> List [ TemplateInfo ]:
return _list (
await self . _http . request (
"GET" ,
SANDBOX + "/v2/templates" ,
params = {
"limit" : seconds ( limit , "limit" ),
"pageNo" : seconds ( page_no , "page_no" ),
},
),
)
get
async
get ( template_id : str ) -> TemplateInfo
Source code in dashscope/applications/agentstudio/sandbox/templates.py
async def get ( self , template_id : str ) -> TemplateInfo :
return TemplateInfo . from_dict (
await self . _http . request ( "GET" , _path ( template_id )),
)
update
async
update (
template_id : str , request : TemplateUpdateRequest
) -> TemplateInfo
Source code in dashscope/applications/agentstudio/sandbox/templates.py
237
238
239
240
241
242
243
244
245
246
247
248 async def update (
self ,
template_id : str ,
request : TemplateUpdateRequest ,
) -> TemplateInfo :
return TemplateInfo . from_dict (
await self . _http . request (
"PUT" ,
_path ( template_id ),
json = request . to_dict (),
),
)
build_status
async
build_status (
template_id : str , build_id : str
) -> BuildStatus
Source code in dashscope/applications/agentstudio/sandbox/templates.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263 async def build_status (
self ,
template_id : str ,
build_id : str ,
) -> BuildStatus :
return BuildStatus . from_dict (
await self . _http . request (
"GET" ,
_path ( template_id )
+ "/builds/"
+ resource_id ( build_id )
+ "/status" ,
),
)
wait_ready
async
wait_ready (
template_id : str , build_id : str , timeout : float = 600
) -> BuildStatus
Source code in dashscope/applications/agentstudio/sandbox/templates.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305 async def wait_ready (
self ,
template_id : str ,
build_id : str ,
timeout : float = 600 ,
) -> BuildStatus :
path = (
_path ( template_id ) + "/builds/" + resource_id ( build_id ) + "/status"
)
end = deadline ( timeout )
last_status = None
while True :
budget = remaining ( end , template_id , last_status )
try :
status = BuildStatus . from_dict (
await self . _http . request (
"GET" ,
path ,
timeout = min ( self . _http . timeout , budget ),
),
)
except SandboxAPIError as error :
if (
error . code == "REQUEST_TIMEOUT"
and budget <= self . _http . timeout
):
raise SandboxWaitTimeoutError (
template_id ,
last_status ,
) from error
raise
last_status = status . status
remaining ( end , template_id , last_status )
if _check_build ( status ):
return status
await asyncio . sleep (
min (
self . _http . poll_interval ,
remaining ( end , template_id , last_status ),
),
)
delete
async
delete ( template_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/templates.py
async def delete ( self , template_id : str ) -> None :
await self . _http . request ( "DELETE" , _path ( template_id ))
Template files
TemplateFilesClient
TemplateFilesClient ( transport : Transport )
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
def __init__ ( self , transport : Transport ):
self . _http = transport
upload
upload ( path : PathLike ) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 def upload ( self , path : PathLike ) -> TemplateFile :
source = _upload_path ( path )
try :
with source . open ( "rb" ) as input_file :
# 直接将文件句柄交给 multipart 编码器,避免将整个文件读入内存。
data = self . _http . request (
"POST" ,
FILES ,
files = [
( "source" , ( None , _SOURCE )),
(
"file" ,
(
source . name ,
input_file ,
"application/octet-stream" ,
),
),
],
)
except OSError as error :
raise SandboxAPIError (
"Cannot read the upload file" ,
code = "FILE_IO_ERROR" ,
) from error
return TemplateFile . from_dict ( data )
get
get ( file_id : str ) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
def get ( self , file_id : str ) -> TemplateFile :
return TemplateFile . from_dict (
self . _http . request ( "GET" , _path ( file_id )),
)
wait_available
wait_available (
file_id : str , timeout : float = 600
) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115 def wait_available (
self ,
file_id : str ,
timeout : float = 600 ,
) -> TemplateFile :
path = _path ( file_id )
end = deadline ( timeout )
last_status = None
while True :
budget = remaining ( end , file_id , last_status )
try :
file = TemplateFile . from_dict (
self . _http . request (
"GET" ,
path ,
timeout = min ( self . _http . timeout , budget ),
),
)
except SandboxAPIError as error :
if (
error . code == "REQUEST_TIMEOUT"
and budget <= self . _http . timeout
):
raise SandboxWaitTimeoutError (
file_id ,
last_status ,
) from error
raise
last_status = file . status
remaining ( end , file_id , last_status )
if _check_file ( file ):
return file
time . sleep (
min (
self . _http . poll_interval ,
remaining ( end , file_id , last_status ),
),
)
prepare_upload
prepare_upload ( request : UploadRequest ) -> UploadTicket
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
def prepare_upload ( self , request : UploadRequest ) -> UploadTicket :
fields = request . to_dict ()
fields [ "source" ] = _SOURCE
return UploadTicket . from_dict (
self . _http . request ( "POST" , FILES , json = fields ),
)
upload_content
upload_content (
ticket : UploadTicket , path : PathLike
) -> None
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
124
125
126
127
128
129
130
131 def upload_content ( self , ticket : UploadTicket , path : PathLike ) -> None :
try :
self . _http . put_signed ( ticket . upload_url , _upload_path ( path ))
except OSError as error :
raise SandboxAPIError (
"Cannot read the upload file" ,
code = "FILE_IO_ERROR" ,
) from error
complete
complete ( file_id : str ) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
def complete ( self , file_id : str ) -> TemplateFile :
return TemplateFile . from_dict (
self . _http . request ( "POST" , _path ( file_id ) + "/complete" ),
)
download
download ( file_id : str , target : PathLike ) -> Path
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167 def download ( self , file_id : str , target : PathLike ) -> Path :
path = _path ( file_id ) + "/content"
target = Path ( target )
temporary = None
try :
descriptor , temporary_name = tempfile . mkstemp (
prefix = ".bailian-download-" ,
suffix = ".part" ,
dir = str ( target . absolute () . parent ),
)
temporary = Path ( temporary_name )
with os . fdopen ( descriptor , "wb" ) as output :
with self . _http . stream (
"GET" ,
path ,
headers = { "Accept" : "application/octet-stream" },
) as response :
for chunk in response . iter_bytes ( chunk_size = 64 * 1024 ):
output . write ( chunk )
# 同目录临时文件保证替换是原子操作,失败时保留原文件。
os . replace ( temporary , target )
return target
except OSError as error :
raise SandboxAPIError (
"Cannot save the downloaded file" ,
code = "FILE_IO_ERROR" ,
) from error
finally :
if temporary is not None :
temporary . unlink ( missing_ok = True )
delete
delete ( file_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
def delete ( self , file_id : str ) -> None :
self . _http . request ( "DELETE" , _path ( file_id ))
AsyncTemplateFilesClient
AsyncTemplateFilesClient ( transport : AsyncTransport )
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
def __init__ ( self , transport : AsyncTransport ):
self . _http = transport
upload
async
upload ( path : PathLike ) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201 async def upload ( self , path : PathLike ) -> TemplateFile :
source = _upload_path ( path )
try :
with source . open ( "rb" ) as input_file :
data = await self . _http . request (
"POST" ,
FILES ,
files = [
( "source" , ( None , _SOURCE )),
(
"file" ,
(
source . name ,
input_file ,
"application/octet-stream" ,
),
),
],
)
except OSError as error :
raise SandboxAPIError (
"Cannot read the upload file" ,
code = "FILE_IO_ERROR" ,
) from error
return TemplateFile . from_dict ( data )
get
async
get ( file_id : str ) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
async def get ( self , file_id : str ) -> TemplateFile :
return TemplateFile . from_dict (
await self . _http . request ( "GET" , _path ( file_id )),
)
wait_available
async
wait_available (
file_id : str , timeout : float = 600
) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245 async def wait_available (
self ,
file_id : str ,
timeout : float = 600 ,
) -> TemplateFile :
path = _path ( file_id )
end = deadline ( timeout )
last_status = None
while True :
budget = remaining ( end , file_id , last_status )
try :
file = TemplateFile . from_dict (
await self . _http . request (
"GET" ,
path ,
timeout = min ( self . _http . timeout , budget ),
),
)
except SandboxAPIError as error :
if (
error . code == "REQUEST_TIMEOUT"
and budget <= self . _http . timeout
):
raise SandboxWaitTimeoutError (
file_id ,
last_status ,
) from error
raise
last_status = file . status
remaining ( end , file_id , last_status )
if _check_file ( file ):
return file
await asyncio . sleep (
min (
self . _http . poll_interval ,
remaining ( end , file_id , last_status ),
),
)
prepare_upload
async
prepare_upload ( request : UploadRequest ) -> UploadTicket
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
async def prepare_upload ( self , request : UploadRequest ) -> UploadTicket :
fields = request . to_dict ()
fields [ "source" ] = _SOURCE
return UploadTicket . from_dict (
await self . _http . request ( "POST" , FILES , json = fields ),
)
upload_content
async
upload_content (
ticket : UploadTicket , path : PathLike
) -> None
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
254
255
256
257
258
259
260
261
262
263
264
265 async def upload_content (
self ,
ticket : UploadTicket ,
path : PathLike ,
) -> None :
try :
await self . _http . put_signed ( ticket . upload_url , _upload_path ( path ))
except OSError as error :
raise SandboxAPIError (
"Cannot read the upload file" ,
code = "FILE_IO_ERROR" ,
) from error
complete
async
complete ( file_id : str ) -> TemplateFile
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
async def complete ( self , file_id : str ) -> TemplateFile :
return TemplateFile . from_dict (
await self . _http . request ( "POST" , _path ( file_id ) + "/complete" ),
)
download
async
download ( file_id : str , target : PathLike ) -> Path
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302 async def download ( self , file_id : str , target : PathLike ) -> Path :
path = _path ( file_id ) + "/content"
target = Path ( target )
temporary = None
try :
descriptor , temporary_name = tempfile . mkstemp (
prefix = ".bailian-download-" ,
suffix = ".part" ,
dir = str ( target . absolute () . parent ),
)
temporary = Path ( temporary_name )
with os . fdopen ( descriptor , "wb" ) as output :
async with self . _http . stream (
"GET" ,
path ,
headers = { "Accept" : "application/octet-stream" },
) as response :
async for chunk in response . aiter_bytes (
chunk_size = 64 * 1024 ,
):
await asyncio . to_thread ( output . write , chunk )
os . replace ( temporary , target )
return target
except OSError as error :
raise SandboxAPIError (
"Cannot save the downloaded file" ,
code = "FILE_IO_ERROR" ,
) from error
finally :
if temporary is not None :
temporary . unlink ( missing_ok = True )
delete
async
delete ( file_id : str ) -> None
Source code in dashscope/applications/agentstudio/sandbox/template_files.py
async def delete ( self , file_id : str ) -> None :
await self . _http . request ( "DELETE" , _path ( file_id ))
Native Web UI
SandboxWebUi
SandboxWebUi (
preview_url , sandbox_id , template_id , resources
)
One-time browser entry. Keep the preview URL private; close after use.
Source code in dashscope/applications/agentstudio/sandbox/web_ui.py
def __init__ ( self , preview_url , sandbox_id , template_id , resources ):
self . preview_url = preview_url
self . sandbox_id = sandbox_id
self . template_id = template_id
self . _resources = resources
preview_url
instance-attribute
preview_url = preview_url
sandbox_id
instance-attribute
template_id
instance-attribute
template_id = template_id
close
Close the local proxy and release only resources created by this preview.
Source code in dashscope/applications/agentstudio/sandbox/web_ui.py
def close ( self ):
"""Close the local proxy and release only resources created by this preview."""
self . _resources . close ()
aclose
async
Source code in dashscope/applications/agentstudio/sandbox/web_ui.py
async def aclose ( self ):
await asyncio . to_thread ( self . close )
WebUiOptions
dataclass
WebUiOptions (
sandbox_id : str = None ,
ready_template_id : str = None ,
image_url : str = None ,
model_base_url : str = None ,
model_id : str = None ,
model_api_key : str = None ,
openclaw_model_api : str = None ,
auto_pair_openclaw : bool = True ,
)
Reuse a Sandbox/template or provision a fresh native Web UI.
Model settings apply only to a new Sandbox and never inherit the platform
API key. auto_pair_openclaw defaults to True and approves this preview
browser's first validated operator pairing request.
sandbox_id
class-attribute
instance-attribute
ready_template_id
class-attribute
instance-attribute
ready_template_id : str = None
image_url
class-attribute
instance-attribute
openclaw_model_api
class-attribute
instance-attribute
openclaw_model_api : str = None
auto_pair_openclaw
class-attribute
instance-attribute
auto_pair_openclaw : bool = True
Report a docs issue