dashscope 1.15.0__py3-none-any.whl → 1.18.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dashscope might be problematic. Click here for more details.

Files changed (56) hide show
  1. dashscope/__init__.py +57 -10
  2. dashscope/aigc/code_generation.py +12 -9
  3. dashscope/aigc/conversation.py +3 -0
  4. dashscope/aigc/generation.py +3 -0
  5. dashscope/aigc/image_synthesis.py +26 -6
  6. dashscope/aigc/multimodal_conversation.py +3 -0
  7. dashscope/api_entities/aiohttp_request.py +1 -0
  8. dashscope/api_entities/api_request_factory.py +28 -12
  9. dashscope/api_entities/dashscope_response.py +63 -0
  10. dashscope/api_entities/http_request.py +21 -31
  11. dashscope/api_entities/websocket_request.py +3 -0
  12. dashscope/app/application.py +16 -18
  13. dashscope/assistants/__init__.py +14 -0
  14. dashscope/assistants/assistant_types.py +164 -0
  15. dashscope/assistants/assistants.py +280 -0
  16. dashscope/assistants/files.py +189 -0
  17. dashscope/audio/asr/asr_phrase_manager.py +27 -5
  18. dashscope/audio/asr/recognition.py +10 -2
  19. dashscope/audio/asr/transcription.py +21 -3
  20. dashscope/audio/tts/speech_synthesizer.py +3 -0
  21. dashscope/cli.py +7 -7
  22. dashscope/client/base_api.py +317 -70
  23. dashscope/common/base_type.py +130 -0
  24. dashscope/common/constants.py +1 -0
  25. dashscope/common/error.py +4 -0
  26. dashscope/common/utils.py +159 -27
  27. dashscope/deployment.py +40 -6
  28. dashscope/embeddings/batch_text_embedding.py +24 -7
  29. dashscope/embeddings/multimodal_embedding.py +3 -0
  30. dashscope/embeddings/text_embedding.py +8 -1
  31. dashscope/files.py +107 -0
  32. dashscope/finetune.py +31 -7
  33. dashscope/model.py +9 -2
  34. dashscope/models.py +47 -0
  35. dashscope/nlp/understanding.py +2 -2
  36. dashscope/rerank/__init__.py +0 -0
  37. dashscope/rerank/text_rerank.py +67 -0
  38. dashscope/threads/__init__.py +24 -0
  39. dashscope/threads/messages/__init__.py +0 -0
  40. dashscope/threads/messages/files.py +111 -0
  41. dashscope/threads/messages/messages.py +218 -0
  42. dashscope/threads/runs/__init__.py +0 -0
  43. dashscope/threads/runs/runs.py +483 -0
  44. dashscope/threads/runs/steps.py +110 -0
  45. dashscope/threads/thread_types.py +651 -0
  46. dashscope/threads/threads.py +210 -0
  47. dashscope/tokenizers/tokenization.py +3 -0
  48. dashscope/utils/oss_utils.py +11 -0
  49. dashscope/version.py +1 -1
  50. {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/METADATA +2 -3
  51. dashscope-1.18.0.dist-info/RECORD +84 -0
  52. dashscope-1.15.0.dist-info/RECORD +0 -66
  53. {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/LICENSE +0 -0
  54. {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/WHEEL +0 -0
  55. {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/entry_points.txt +0 -0
  56. {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,218 @@
1
+ from typing import Dict, List, Optional
2
+
3
+ from dashscope.client.base_api import (CreateMixin, GetStatusMixin,
4
+ ListObjectMixin, UpdateMixin)
5
+ from dashscope.common.error import InputRequired
6
+ from dashscope.threads.thread_types import ThreadMessage, ThreadMessageList
7
+
8
+ __all__ = ['Messages']
9
+
10
+
11
+ class Messages(CreateMixin, ListObjectMixin, GetStatusMixin, UpdateMixin):
12
+ SUB_PATH = 'messages' # useless
13
+
14
+ @classmethod
15
+ def call(cls,
16
+ thread_id: str,
17
+ *,
18
+ content: str,
19
+ role: str = 'user',
20
+ file_ids: List[str] = [],
21
+ metadata: Optional[object] = None,
22
+ workspace: str = None,
23
+ api_key: str = None,
24
+ **kwargs) -> ThreadMessage:
25
+ """Create message of thread.
26
+
27
+ Args:
28
+ thread_id (str): The thread id.
29
+ content (str): The message content.
30
+ role (str, optional): The message role. Defaults to 'user'.
31
+ file_ids (List[str], optional): The file_ids include in message. Defaults to [].
32
+ metadata (Optional[object], optional): The custom key/value pairs. Defaults to None.
33
+ workspace (str, optional): The DashScope workspace id. Defaults to None.
34
+ api_key (str, optional): The DashScope api key. Defaults to None.
35
+
36
+ Returns:
37
+ ThreadMessage: The `ThreadMessage` object.
38
+ """
39
+ return cls.create(thread_id,
40
+ content=content,
41
+ role=role,
42
+ file_ids=file_ids,
43
+ metadata=metadata,
44
+ workspace=workspace,
45
+ **kwargs)
46
+
47
+ @classmethod
48
+ def create(cls,
49
+ thread_id: str,
50
+ *,
51
+ content: str,
52
+ role: str = 'user',
53
+ file_ids: List[str] = [],
54
+ metadata: Optional[object] = None,
55
+ workspace: str = None,
56
+ api_key: str = None,
57
+ **kwargs) -> ThreadMessage:
58
+ """Create message of thread.
59
+
60
+ Args:
61
+ thread_id (str): The thread id.
62
+ content (str): The message content.
63
+ role (str, optional): The message role. Defaults to 'user'.
64
+ file_ids (List[str], optional): The file_ids include in message. Defaults to [].
65
+ metadata (Optional[object], optional): The custom key/value pairs. Defaults to None.
66
+ workspace (str, optional): The DashScope workspace id. Defaults to None.
67
+ api_key (str, optional): The DashScope api key. Defaults to None.
68
+
69
+ Returns:
70
+ ThreadMessage: The `ThreadMessage` object.
71
+ """
72
+ cls.SUB_PATH = '%s/messages' % thread_id
73
+ data = {}
74
+ if not thread_id or not content:
75
+ raise InputRequired('thread_id and content are required!')
76
+ data['content'] = content
77
+ data['role'] = role
78
+ if metadata:
79
+ data['metadata'] = metadata
80
+ if file_ids:
81
+ data['file_ids'] = file_ids
82
+ response = super().call(data=data,
83
+ path=f'threads/{thread_id}/messages',
84
+ api_key=api_key,
85
+ flattened_output=True,
86
+ workspace=workspace,
87
+ **kwargs)
88
+ return ThreadMessage(**response)
89
+
90
+ @classmethod
91
+ def retrieve(cls,
92
+ message_id: str,
93
+ *,
94
+ thread_id: str,
95
+ workspace: str = None,
96
+ api_key: str = None,
97
+ **kwargs) -> ThreadMessage:
98
+ """Get the `ThreadMessage`.
99
+
100
+ Args:
101
+ thread_id (str): The thread id.
102
+ message_id (str): The message id.
103
+ workspace (str): The dashscope workspace id.
104
+ api_key (str, optional): The api key. Defaults to None.
105
+
106
+ Returns:
107
+ ThreadMessage: The `ThreadMessage` object.
108
+ """
109
+ return cls.get(message_id,
110
+ thread_id=thread_id,
111
+ workspace=workspace,
112
+ api_key=api_key,
113
+ **kwargs)
114
+
115
+ @classmethod
116
+ def get(cls,
117
+ message_id: str,
118
+ *,
119
+ thread_id: str,
120
+ workspace: str = None,
121
+ api_key: str = None,
122
+ **kwargs) -> ThreadMessage:
123
+ """Get the `ThreadMessage`.
124
+
125
+ Args:
126
+ thread_id (str): The thread id.
127
+ message_id (str): The message id.
128
+ workspace (str): The dashscope workspace id.
129
+ api_key (str, optional): The api key. Defaults to None.
130
+
131
+ Returns:
132
+ ThreadMessage: The `ThreadMessage` object.
133
+ """
134
+ if not message_id or not thread_id:
135
+ raise InputRequired('thread id, message id are required!')
136
+ response = super().get(
137
+ message_id,
138
+ path=f'threads/{thread_id}/messages/{message_id}',
139
+ workspace=workspace,
140
+ api_key=api_key,
141
+ flattened_output=True,
142
+ **kwargs)
143
+ return ThreadMessage(**response)
144
+
145
+ @classmethod
146
+ def list(cls,
147
+ thread_id: str,
148
+ *,
149
+ limit: int = None,
150
+ order: str = None,
151
+ after: str = None,
152
+ before: str = None,
153
+ workspace: str = None,
154
+ api_key: str = None,
155
+ **kwargs) -> ThreadMessageList:
156
+ """List message of the thread.
157
+
158
+ Args:
159
+ thread_id (str): The thread id.
160
+ limit (int, optional): How many assistant to retrieve. Defaults to None.
161
+ order (str, optional): Sort order by created_at. Defaults to None.
162
+ after (str, optional): Assistant id after. Defaults to None.
163
+ before (str, optional): Assistant id before. Defaults to None.
164
+ workspace (str, optional): The DashScope workspace id. Defaults to None.
165
+ api_key (str, optional): Your DashScope api key. Defaults to None.
166
+
167
+ Returns:
168
+ ThreadMessageList: The `ThreadMessageList` object.
169
+ """
170
+ if not thread_id:
171
+ raise InputRequired('thread id is required!')
172
+ response = super().list(limit=limit,
173
+ order=order,
174
+ after=after,
175
+ before=before,
176
+ path=f'threads/{thread_id}/messages',
177
+ workspace=workspace,
178
+ api_key=api_key,
179
+ flattened_output=True,
180
+ **kwargs)
181
+ return ThreadMessageList(**response)
182
+
183
+ @classmethod
184
+ def update(cls,
185
+ message_id: str,
186
+ *,
187
+ thread_id: str,
188
+ metadata: Dict = None,
189
+ workspace: str = None,
190
+ api_key: str = None,
191
+ **kwargs) -> ThreadMessage:
192
+ """Update an message of the thread.
193
+
194
+ Args:
195
+ thread_id (str): The thread id.
196
+ message_id (str): The message id.
197
+ content (str): The message content.
198
+ role (str, optional): The message role. Defaults to 'user'.
199
+ file_ids (List[str], optional): The file_ids include in message. Defaults to [].
200
+ metadata (Optional[object], optional): The custom key/value pairs. Defaults to None.
201
+ workspace (str, optional): The DashScope workspace id. Defaults to None.
202
+ api_key (str, optional): The DashScope api key. Defaults to None.
203
+
204
+ Returns:
205
+ ThreadMessage: The `ThreadMessage` object.
206
+ """
207
+ if not thread_id or not message_id:
208
+ raise InputRequired('thread id and message id are required!')
209
+ response = super().update(target=message_id,
210
+ json={'metadata': metadata},
211
+ path='threads/%s/messages/%s' %
212
+ (thread_id, message_id),
213
+ api_key=api_key,
214
+ workspace=workspace,
215
+ flattened_output=True,
216
+ method='post',
217
+ **kwargs)
218
+ return ThreadMessage(**response)
File without changes
@@ -0,0 +1,483 @@
1
+ import time
2
+ from http import HTTPStatus
3
+ from typing import Dict, List, Optional
4
+
5
+ from dashscope.client.base_api import (CancelMixin, CreateMixin,
6
+ GetStatusMixin, ListObjectMixin,
7
+ UpdateMixin)
8
+ from dashscope.common.error import InputRequired, TimeoutException
9
+ from dashscope.common.logging import logger
10
+ from dashscope.threads.thread_types import (Run, RunList, RunStep,
11
+ RunStepDelta, Thread,
12
+ ThreadMessage, ThreadMessageDelta)
13
+
14
+ __all__ = ['Runs']
15
+
16
+
17
+ class Runs(CreateMixin, CancelMixin, ListObjectMixin, GetStatusMixin,
18
+ UpdateMixin):
19
+ SUB_PATH = 'RUNS' # useless
20
+
21
+ @classmethod
22
+ def create_thread_and_run(cls,
23
+ *,
24
+ assistant_id: str,
25
+ thread: Optional[Dict] = None,
26
+ model: Optional[str] = None,
27
+ instructions: Optional[str] = None,
28
+ additional_instructions: Optional[str] = None,
29
+ tools: Optional[List[Dict]] = None,
30
+ stream: Optional[bool] = False,
31
+ metadata: Optional[Dict] = None,
32
+ workspace: str = None,
33
+ extra_body: Optional[Dict] = None,
34
+ api_key: str = None,
35
+ **kwargs) -> Run:
36
+ if not assistant_id:
37
+ raise InputRequired('assistant_id is required')
38
+ data = {'assistant_id': assistant_id}
39
+ if thread:
40
+ data['thread'] = thread
41
+ if model:
42
+ data['model'] = model
43
+ if instructions:
44
+ data['instructions'] = instructions
45
+ if additional_instructions:
46
+ data['additional_instructions'] = additional_instructions
47
+ if tools:
48
+ data['tools'] = tools
49
+ if metadata:
50
+ data['metadata'] = metadata
51
+ data['stream'] = stream
52
+ if extra_body is not None and extra_body:
53
+ data = {**data, **extra_body}
54
+
55
+ response = super().call(data=data,
56
+ path='threads/runs',
57
+ api_key=api_key,
58
+ flattened_output=True,
59
+ stream=stream,
60
+ workspace=workspace,
61
+ **kwargs)
62
+ if stream:
63
+ return ((event_type, cls.convert_stream_object(event_type, item))
64
+ for event_type, item in response)
65
+ else:
66
+ return Run(**response)
67
+
68
+ @classmethod
69
+ def create(cls,
70
+ thread_id: str,
71
+ *,
72
+ assistant_id: str,
73
+ model: Optional[str] = None,
74
+ instructions: Optional[str] = None,
75
+ additional_instructions: Optional[str] = None,
76
+ tools: Optional[List[Dict]] = None,
77
+ metadata: Optional[Dict] = None,
78
+ stream: Optional[bool] = False,
79
+ workspace: str = None,
80
+ extra_body: Optional[Dict] = None,
81
+ api_key: str = None,
82
+ **kwargs) -> Run:
83
+ """Create a run.
84
+
85
+ Args:
86
+ thread_id (str): The thread to run.
87
+ assistant_id (str): The assistant id to run.
88
+ model (str): The model to use.
89
+ instructions (str, optional): The system instructions this assistant uses. Defaults to None.
90
+ additional_instructions (Optional[str], optional): Appends additional
91
+ instructions at the end of the instructions for the run. This is
92
+ useful for modifying the behavior on a per-run basis without
93
+ overriding other instructions.. Defaults to None.
94
+ tools (Optional[str], optional): List of tools to use.. Defaults to [].
95
+ metadata (Dict, optional): Custom key-value pairs associate with run. Defaults to None.
96
+ workspace (str): The DashScope workspace id.
97
+ api_key (str, optional): The DashScope workspace id. Defaults to None.
98
+
99
+ Raises:
100
+ InputRequired: thread and assistant is required.
101
+
102
+ Returns:
103
+ Run: The `Run` object.
104
+ """
105
+ if not thread_id or not assistant_id:
106
+ raise InputRequired('thread_id and assistant_id is required')
107
+ data = {'assistant_id': assistant_id}
108
+ if model:
109
+ data['model'] = model
110
+ if instructions:
111
+ data['instructions'] = instructions
112
+ if additional_instructions:
113
+ data['additional_instructions'] = additional_instructions
114
+ if tools:
115
+ data['tools'] = tools
116
+ if metadata:
117
+ data['metadata'] = metadata
118
+ data['stream'] = stream
119
+ if extra_body is not None and extra_body:
120
+ data = {**data, **extra_body}
121
+
122
+ response = super().call(data=data,
123
+ path=f'threads/{thread_id}/runs',
124
+ api_key=api_key,
125
+ flattened_output=True,
126
+ stream=stream,
127
+ workspace=workspace,
128
+ **kwargs)
129
+ if stream:
130
+ return ((event_type, cls.convert_stream_object(event_type, item))
131
+ for event_type, item in response)
132
+ else:
133
+ return Run(**response)
134
+
135
+ @classmethod
136
+ def convert_stream_object(cls, event, item):
137
+ event_object_map = {
138
+ 'thread.created': Thread,
139
+ 'thread.run.created': Run,
140
+ 'thread.run.queued': Run,
141
+ 'thread.run.in_progress': Run,
142
+ 'thread.run.requires_action': Run,
143
+ 'thread.run.completed': Run,
144
+ 'thread.run.failed': Run,
145
+ 'thread.run.cancelled': Run,
146
+ 'thread.run.expired': Run,
147
+ 'thread.run.step.created': RunStep,
148
+ 'thread.run.step.in_progress': RunStep,
149
+ 'thread.run.step.delta': RunStepDelta,
150
+ 'thread.run.step.completed': RunStep,
151
+ 'thread.run.step.failed': RunStep,
152
+ 'thread.run.step.cancelled': RunStep,
153
+ 'thread.run.step.expired': RunStep,
154
+ 'thread.message.created': ThreadMessage,
155
+ 'thread.message.in_progress': ThreadMessage,
156
+ 'thread.message.delta': ThreadMessageDelta,
157
+ 'thread.message.completed': ThreadMessage,
158
+ 'thread.message.incomplete': ThreadMessage,
159
+ 'error': item,
160
+ }
161
+ if (event in event_object_map):
162
+ return event_object_map[event](**item)
163
+ else:
164
+ return item
165
+
166
+ @classmethod
167
+ def call(cls,
168
+ thread_id: str,
169
+ *,
170
+ assistant_id: str,
171
+ model: Optional[str] = None,
172
+ instructions: Optional[str] = None,
173
+ additional_instructions: Optional[str] = None,
174
+ tools: Optional[List[Dict]] = None,
175
+ stream: Optional[bool] = False,
176
+ metadata: Optional[Dict] = None,
177
+ workspace: str = None,
178
+ extra_body: Optional[Dict] = None,
179
+ api_key: str = None,
180
+ **kwargs) -> Run:
181
+ """Create a run.
182
+
183
+ Args:
184
+ thread_id (str): The thread to run.
185
+ assistant_id (str): The assistant id to run.
186
+ model (str): The model to use.
187
+ instructions (str, optional): The system instructions this assistant uses. Defaults to None.
188
+ additional_instructions (Optional[str], optional): Appends additional
189
+ instructions at the end of the instructions for the run. This is
190
+ useful for modifying the behavior on a per-run basis without
191
+ overriding other instructions.. Defaults to None.
192
+ tools (Optional[str], optional): List of tools to use.. Defaults to [].
193
+ metadata (Dict, optional): Custom key-value pairs associate with run. Defaults to None.
194
+ workspace (str): The DashScope workspace id.
195
+ api_key (str, optional): The DashScope workspace id. Defaults to None.
196
+
197
+ Raises:
198
+ InputRequired: thread and assistant is required.
199
+
200
+ Returns:
201
+ Run: The `Run` object.
202
+ """
203
+ return cls.create(thread_id,
204
+ assistant_id=assistant_id,
205
+ model=model,
206
+ instructions=instructions,
207
+ additional_instructions=additional_instructions,
208
+ tools=tools,
209
+ stream=stream,
210
+ metadata=metadata,
211
+ workspace=workspace,
212
+ extra_body=extra_body,
213
+ api_key=api_key,
214
+ **kwargs)
215
+
216
+ @classmethod
217
+ def list(cls,
218
+ thread_id: str,
219
+ *,
220
+ limit: int = None,
221
+ order: str = None,
222
+ after: str = None,
223
+ before: str = None,
224
+ workspace: str = None,
225
+ api_key: str = None,
226
+ **kwargs) -> RunList:
227
+ """List `Run`.
228
+
229
+ Args:
230
+ thread_id (str): The thread id.
231
+ limit (int, optional): How many assistant to retrieve. Defaults to None.
232
+ order (str, optional): Sort order by created_at. Defaults to None.
233
+ after (str, optional): Assistant id after. Defaults to None.
234
+ before (str, optional): Assistant id before. Defaults to None.
235
+ workspace (str, optional): The DashScope workspace id. Defaults to None.
236
+ api_key (str, optional): Your DashScope api key. Defaults to None.
237
+
238
+ Returns:
239
+ RunList: The list of runs.
240
+ """
241
+ if not thread_id:
242
+ raise InputRequired('thread_id is required!')
243
+ response = super().list(limit=limit,
244
+ order=order,
245
+ after=after,
246
+ before=before,
247
+ path=f'threads/{thread_id}/runs',
248
+ workspace=workspace,
249
+ api_key=api_key,
250
+ flattened_output=True,
251
+ **kwargs)
252
+ return RunList(**response)
253
+
254
+ @classmethod
255
+ def retrieve(cls,
256
+ run_id: str,
257
+ *,
258
+ thread_id: str,
259
+ workspace: str = None,
260
+ api_key: str = None,
261
+ **kwargs) -> Run:
262
+ """Retrieve the `Run`.
263
+
264
+ Args:
265
+ thread_id (str): The thread id.
266
+ run_id (str): The run id.
267
+ workspace (str): The dashscope workspace id.
268
+ api_key (str, optional): The api key. Defaults to None.
269
+
270
+ Returns:
271
+ Run: The `Run` object.
272
+ """
273
+ if not thread_id or not run_id:
274
+ raise InputRequired('thread_id and run_id are required!')
275
+ response = super().get(run_id,
276
+ path=f'threads/{thread_id}/runs/{run_id}',
277
+ workspace=workspace,
278
+ api_key=api_key,
279
+ flattened_output=True,
280
+ **kwargs)
281
+ return Run(**response)
282
+
283
+ @classmethod
284
+ def get(cls,
285
+ run_id: str,
286
+ *,
287
+ thread_id: str,
288
+ workspace: str = None,
289
+ api_key: str = None,
290
+ **kwargs) -> Run:
291
+ """Retrieve the `Run`.
292
+
293
+ Args:
294
+ thread_id (str): The thread id.
295
+ run_id (str): The run id.
296
+ workspace (str): The dashscope workspace id.
297
+ api_key (str, optional): The api key. Defaults to None.
298
+
299
+ Returns:
300
+ Run: The `Run` object.
301
+ """
302
+ return cls.retrieve(run_id,
303
+ thread_id=thread_id,
304
+ workspace=workspace,
305
+ api_key=api_key,
306
+ **kwargs)
307
+
308
+ @classmethod
309
+ def submit_tool_outputs(cls,
310
+ run_id: str,
311
+ *,
312
+ thread_id: str,
313
+ tool_outputs: List[Dict],
314
+ stream: Optional[bool] = False,
315
+ workspace: str = None,
316
+ extra_body: Optional[Dict] = None,
317
+ api_key: str = None,
318
+ **kwargs) -> Run:
319
+ """_summary_
320
+
321
+ Args:
322
+ thread_id (str): The thread id.
323
+ run_id (str): The run id.
324
+ tool_outputs (List[Dict]): The tool outputs.
325
+ workspace (str): The dashscope workspace id.
326
+ api_key (str, optional): The api key. Defaults to None.
327
+
328
+ Raises:
329
+ InputRequired: The tool output thread id run id
330
+ are required.
331
+
332
+ Returns:
333
+ Run: The 'Run`.
334
+ """
335
+ if not tool_outputs:
336
+ raise InputRequired('tool_outputs is required!')
337
+ if not thread_id or not run_id:
338
+ raise InputRequired('thread_id and run_id are required!')
339
+
340
+ data = {'tool_outputs': tool_outputs}
341
+ data['stream'] = stream
342
+ if extra_body is not None and extra_body:
343
+ data = {**data, **extra_body}
344
+
345
+ response = super().call(
346
+ data,
347
+ path=f'threads/{thread_id}/runs/{run_id}/submit_tool_outputs',
348
+ workspace=workspace,
349
+ api_key=api_key,
350
+ stream=stream,
351
+ flattened_output=True,
352
+ **kwargs)
353
+ if stream:
354
+ return ((event_type, cls.convert_stream_object(event_type, item))
355
+ for event_type, item in response)
356
+ else:
357
+ return Run(**response)
358
+
359
+ @classmethod
360
+ def wait(cls,
361
+ run_id: str,
362
+ *,
363
+ thread_id: str,
364
+ timeout_seconds: float = float('inf'),
365
+ workspace: str = None,
366
+ api_key: str = None,
367
+ **kwargs) -> Run:
368
+ """Wait for run to complete.
369
+
370
+ Args:
371
+ thread_id (str): The thread id.
372
+ run_id (str): The run id.
373
+ timeout_seconds (int): The timeout seconds. Defaults inf.
374
+ workspace (str): The dashscope workspace id.
375
+ api_key (str, optional): The api key. Defaults to None.
376
+
377
+ Returns:
378
+ Run: The run final status.
379
+ """
380
+ if not run_id or not thread_id:
381
+ raise InputRequired('run_id and thread_id are required!')
382
+ start_time = time.perf_counter()
383
+ while True:
384
+ run = cls.get(run_id,
385
+ thread_id=thread_id,
386
+ workspace=workspace,
387
+ api_key=api_key)
388
+ import json
389
+ print(
390
+ json.dumps(run,
391
+ default=lambda o: o.__dict__,
392
+ sort_keys=True,
393
+ indent=4))
394
+ if run.status_code == HTTPStatus.OK:
395
+ if hasattr(run, 'status'):
396
+ if run.status in [
397
+ 'cancelled', 'failed', 'completed', 'expired',
398
+ 'requires_action'
399
+ ]:
400
+ break
401
+ else:
402
+ time_eclipsed = time.perf_counter() - start_time
403
+ if time_eclipsed > timeout_seconds:
404
+ raise TimeoutException('Wait run complete timeout')
405
+ time.sleep(1)
406
+ else:
407
+ logger.error('run has no status')
408
+ break
409
+ else:
410
+ logger.error(
411
+ 'Get run thread_id: %s, run_id: %s failed, message: %s' %
412
+ (thread_id, run_id, run.message))
413
+ break
414
+ return run
415
+
416
+ @classmethod
417
+ def update(cls,
418
+ run_id: str,
419
+ *,
420
+ thread_id: str,
421
+ metadata: Optional[Dict] = None,
422
+ workspace: str = None,
423
+ api_key: str = None,
424
+ **kwargs) -> Run:
425
+ """Create a run.
426
+
427
+ Args:
428
+ thread_id (str): The thread of the run id to be updated.
429
+ run_id (str): The run id to update.
430
+ model (str): The model to use.
431
+ metadata (Dict, optional): Custom key-value pairs associate with run. Defaults to None.
432
+ workspace (str): The DashScope workspace id.
433
+ api_key (str, optional): The DashScope workspace id. Defaults to None.
434
+
435
+ Raises:
436
+ InputRequired: thread id and run is required.
437
+
438
+ Returns:
439
+ Run: The `Run` object.
440
+ """
441
+ if not thread_id or not run_id:
442
+ raise InputRequired('thread id and run id are required!')
443
+ response = super().update(run_id,
444
+ json={'metadata': metadata},
445
+ path='threads/%s/runs/%s' %
446
+ (thread_id, run_id),
447
+ api_key=api_key,
448
+ workspace=workspace,
449
+ flattened_output=True,
450
+ method='post',
451
+ **kwargs)
452
+ return Run(**response)
453
+
454
+ @classmethod
455
+ def cancel(cls,
456
+ run_id: str,
457
+ *,
458
+ thread_id: str,
459
+ workspace: str = None,
460
+ api_key: str = None,
461
+ **kwargs) -> Run:
462
+ """Cancel the `Run`.
463
+
464
+ Args:
465
+ thread_id (str): The thread id.
466
+ run_id (str): The run id.
467
+ workspace (str): The dashscope workspace id.
468
+ api_key (str, optional): The api key. Defaults to None.
469
+
470
+ Returns:
471
+ Run: The `Run` object.
472
+ """
473
+ if not thread_id or not run_id:
474
+ raise InputRequired('thread id and run id are required!')
475
+ response = super().cancel(run_id,
476
+ path='threads/%s/runs/%s/cancel' %
477
+ (thread_id, run_id),
478
+ api_key=api_key,
479
+ workspace=workspace,
480
+ flattened_output=True,
481
+ **kwargs)
482
+
483
+ return Run(**response)