dashscope 1.24.2__py3-none-any.whl → 1.24.3__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.

@@ -1,5 +1,6 @@
1
1
  # Copyright (c) Alibaba, Inc. and its affiliates.
2
-
2
+ import asyncio
3
+ import collections
3
4
  import time
4
5
  from http import HTTPStatus
5
6
  from typing import Any, Dict, Iterator, List, Union
@@ -13,7 +14,7 @@ from dashscope.common.api_key import get_default_api_key
13
14
  from dashscope.common.constants import (DEFAULT_REQUEST_TIMEOUT_SECONDS,
14
15
  REPEATABLE_STATUS,
15
16
  REQUEST_TIMEOUT_KEYWORD,
16
- SSE_CONTENT_TYPE, TaskStatus)
17
+ SSE_CONTENT_TYPE, TaskStatus, HTTPMethod)
17
18
  from dashscope.common.error import InvalidParameter, InvalidTask, ModelRequired
18
19
  from dashscope.common.logging import logger
19
20
  from dashscope.common.utils import (_handle_http_failed_response,
@@ -21,8 +22,299 @@ from dashscope.common.utils import (_handle_http_failed_response,
21
22
  _handle_http_stream_response,
22
23
  default_headers, join_url)
23
24
 
25
+ class AsyncAioTaskGetMixin:
26
+ @classmethod
27
+ async def _get(cls,
28
+ task_id: str,
29
+ api_key: str = None,
30
+ workspace: str = None,
31
+ **kwargs) -> DashScopeAPIResponse:
32
+ base_url = kwargs.pop('base_address', None)
33
+ url = _normalization_url(base_url, 'tasks', task_id)
34
+ kwargs = cls._handle_kwargs(api_key, workspace, **kwargs)
35
+ kwargs["base_address"] = url
36
+ if not api_key:
37
+ api_key = get_default_api_key()
38
+ request = _build_api_request("", "", "",
39
+ "", "", api_key=api_key,
40
+ is_service=False, **kwargs)
41
+ return await cls._handle_request(request)
42
+
43
+ @classmethod
44
+ def _handle_kwargs(cls, api_key: str = None ,workspace: str = None, **kwargs):
45
+ custom_headers = kwargs.pop('headers', None)
46
+ headers = {
47
+ **_workspace_header(workspace),
48
+ **default_headers(api_key),
49
+ }
50
+ if custom_headers:
51
+ headers = {
52
+ **custom_headers,
53
+ **headers,
54
+ }
55
+ if workspace is not None:
56
+ headers = {
57
+ 'X-DashScope-WorkSpace': workspace,
58
+ **kwargs.pop('headers', {})
59
+ }
60
+ kwargs['headers'] = headers
61
+ kwargs['http_method'] = HTTPMethod.GET
62
+ return kwargs
63
+
64
+ @classmethod
65
+ async def _handle_request(cls, request):
66
+ # 如果 aio_call 返回的是异步生成器,则需要从中获取响应
67
+ response = await request.aio_call()
68
+ # 处理异步生成器的情况
69
+ if isinstance(response, collections.abc.AsyncGenerator):
70
+ result = None
71
+ async for item in response:
72
+ result = item
73
+ return result
74
+ else:
75
+ return response
76
+
77
+ class BaseAsyncAioApi(AsyncAioTaskGetMixin):
78
+ """BaseApi, internal use only.
79
+
80
+ """
81
+ @classmethod
82
+ def _validate_params(cls, api_key, model):
83
+ if api_key is None:
84
+ api_key = get_default_api_key()
85
+ if model is None or not model:
86
+ raise ModelRequired('Model is required!')
87
+ return api_key, model
88
+
89
+ @classmethod
90
+ async def async_call(cls,
91
+ model: str,
92
+ input: object,
93
+ task_group: str,
94
+ task: str = None,
95
+ function: str = None,
96
+ api_key: str = None,
97
+ workspace: str = None,
98
+ **kwargs) -> DashScopeAPIResponse:
99
+ api_key, model = cls._validate_params(api_key, model)
100
+ if workspace is not None:
101
+ headers = {
102
+ 'X-DashScope-WorkSpace': workspace,
103
+ **kwargs.pop('headers', {})
104
+ }
105
+ kwargs['headers'] = headers
106
+ kwargs['async_request'] = True
107
+ request = _build_api_request(model=model,
108
+ input=input,
109
+ task_group=task_group,
110
+ task=task,
111
+ function=function,
112
+ api_key=api_key,
113
+ **kwargs)
114
+ # call request service.
115
+ return await request.aio_call()
116
+
117
+ @classmethod
118
+ async def call(cls,
119
+ model: str,
120
+ input: object,
121
+ task_group: str,
122
+ task: str = None,
123
+ function: str = None,
124
+ api_key: str = None,
125
+ workspace: str = None,
126
+ **kwargs) -> DashScopeAPIResponse:
127
+ # call request service.
128
+ response = await BaseAsyncAioApi.async_call(model, input, task_group, task,
129
+ function, api_key, workspace,
130
+ **kwargs)
131
+ response = await BaseAsyncAioApi.wait(response,
132
+ api_key=api_key,
133
+ workspace=workspace,
134
+ **kwargs)
135
+ return response
136
+
137
+
138
+ @classmethod
139
+ def _get_task_id(cls, task):
140
+ if isinstance(task, str):
141
+ task_id = task
142
+ elif isinstance(task, DashScopeAPIResponse):
143
+ if task.status_code == HTTPStatus.OK:
144
+ task_id = task.output['task_id']
145
+ else:
146
+ raise InvalidTask('Invalid task, task create failed: %s' %
147
+ task)
148
+ else:
149
+ raise InvalidParameter('Task invalid!')
150
+ if task_id is None or task_id == '':
151
+ raise InvalidParameter('Task id required!')
152
+ return task_id
153
+
154
+ @classmethod
155
+ async def wait(cls,
156
+ task: Union[str, DashScopeAPIResponse],
157
+ api_key: str = None,
158
+ workspace: str = None,
159
+ **kwargs) -> DashScopeAPIResponse:
160
+ """Wait for async task completion and return task result.
161
+
162
+ Args:
163
+ task (Union[str, DashScopeAPIResponse]): The task_id, or
164
+ async_call response.
165
+ api_key (str, optional): The api_key. Defaults to None.
166
+
167
+ Returns:
168
+ DashScopeAPIResponse: The async task information.
169
+ """
170
+ task_id = cls._get_task_id(task)
171
+ wait_seconds = 1
172
+ max_wait_seconds = 5
173
+ increment_steps = 3
174
+ step = 0
175
+ while True:
176
+ step += 1
177
+ # we start by querying once every second, and double
178
+ # the query interval after every 3(increment_steps)
179
+ # intervals, until we hit the max waiting interval
180
+ # of 5(seconds)
181
+ # (server side return immediately when ready)
182
+ if wait_seconds < max_wait_seconds and step % increment_steps == 0:
183
+ wait_seconds = min(wait_seconds * 2, max_wait_seconds)
184
+ rsp = await cls._get(task_id, api_key, workspace=workspace, **kwargs)
185
+ if rsp.status_code == HTTPStatus.OK:
186
+ if rsp.output is None:
187
+ return rsp
188
+
189
+ task_status = rsp.output['task_status']
190
+ if task_status in [
191
+ TaskStatus.FAILED, TaskStatus.CANCELED,
192
+ TaskStatus.SUCCEEDED, TaskStatus.UNKNOWN
193
+ ]:
194
+ return rsp
195
+ else:
196
+ logger.info('The task %s is %s' % (task_id, task_status))
197
+ await asyncio.sleep(wait_seconds) # 异步等待
198
+ elif rsp.status_code in REPEATABLE_STATUS:
199
+ logger.warn(
200
+ ('Get task: %s temporary failure, \
201
+ status_code: %s, code: %s message: %s, will try again.'
202
+ ) % (task_id, rsp.status_code, rsp.code, rsp.message))
203
+ await asyncio.sleep(wait_seconds) # 异步等待
204
+ else:
205
+ return rsp
206
+
207
+ @classmethod
208
+ async def cancel(
209
+ cls,
210
+ task: Union[str, DashScopeAPIResponse],
211
+ api_key: str = None,
212
+ workspace: str = None,
213
+ **kwargs,
214
+ ) -> DashScopeAPIResponse:
215
+ """Cancel PENDING task.
216
+
217
+ Args:
218
+ task (Union[str, DashScopeAPIResponse]): The task_id, or
219
+ async_call response.
220
+ api_key (str, optional): The api-key. Defaults to None.
221
+
222
+ Returns:
223
+ DashScopeAPIResponse: The cancel result.
224
+ """
225
+ task_id = cls._get_task_id(task)
226
+ base_url = kwargs.pop('base_address', None)
227
+ url = _normalization_url(base_url, 'tasks', task_id, 'cancel')
228
+ kwargs = cls._handle_kwargs(api_key, workspace, **kwargs)
229
+ kwargs["base_address"] = url
230
+ if not api_key:
231
+ api_key = get_default_api_key()
232
+ request = _build_api_request("", "", "",
233
+ "", "",api_key=api_key,
234
+ is_service=False, **kwargs)
235
+ return await cls._handle_request(request)
236
+
237
+ @classmethod
238
+ async def list(cls,
239
+ start_time: str = None,
240
+ end_time: str = None,
241
+ model_name: str = None,
242
+ api_key_id: str = None,
243
+ region: str = None,
244
+ status: str = None,
245
+ page_no: int = 1,
246
+ page_size: int = 10,
247
+ api_key: str = None,
248
+ workspace: str = None,
249
+ **kwargs) -> DashScopeAPIResponse:
250
+ """List async tasks.
251
+
252
+ Args:
253
+ start_time (str, optional): The tasks start time,
254
+ for example: 20230420000000. Defaults to None.
255
+ end_time (str, optional): The tasks end time,
256
+ for example: 20230420000000. Defaults to None.
257
+ model_name (str, optional): The tasks model name.
258
+ Defaults to None.
259
+ api_key_id (str, optional): The tasks api-key-id.
260
+ Defaults to None.
261
+ region (str, optional): The service region,
262
+ for example: cn-beijing. Defaults to None.
263
+ status (str, optional): The status of tasks[PENDING,
264
+ RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
265
+ page_no (int, optional): The page number. Defaults to 1.
266
+ page_size (int, optional): The page size. Defaults to 10.
267
+ api_key (str, optional): The user api-key. Defaults to None.
268
+
269
+ Returns:
270
+ DashScopeAPIResponse: The response data.
271
+ """
272
+ base_url = kwargs.pop('base_address', None)
273
+ url = _normalization_url(base_url, 'tasks')
274
+ params = {'page_no': page_no, 'page_size': page_size}
275
+ if start_time is not None:
276
+ params['start_time'] = start_time
277
+ if end_time is not None:
278
+ params['end_time'] = end_time
279
+ if model_name is not None:
280
+ params['model_name'] = model_name
281
+ if api_key_id is not None:
282
+ params['api_key_id'] = api_key_id
283
+ if region is not None:
284
+ params['region'] = region
285
+ if status is not None:
286
+ params['status'] = status
287
+ kwargs = cls._handle_kwargs(api_key, workspace, **kwargs)
288
+ kwargs["base_address"] = url
289
+ if not api_key:
290
+ api_key = get_default_api_key()
291
+ request = _build_api_request(model_name, "", "",
292
+ "", "", api_key=api_key,
293
+ is_service=False, extra_url_parameters=params,
294
+ **kwargs)
295
+ return await cls._handle_request(request)
296
+
297
+ @classmethod
298
+ async def fetch(cls,
299
+ task: Union[str, DashScopeAPIResponse],
300
+ api_key: str = None,
301
+ workspace: str = None,
302
+ **kwargs) -> DashScopeAPIResponse:
303
+ """Query async task status.
304
+
305
+ Args:
306
+ task (Union[str, DashScopeAPIResponse]): The task_id, or
307
+ async_call response.
308
+ api_key (str, optional): The api_key. Defaults to None.
309
+
310
+ Returns:
311
+ DashScopeAPIResponse: The async task information.
312
+ """
313
+ task_id = cls._get_task_id(task)
314
+ return await cls._get(task_id, api_key, workspace, **kwargs)
315
+
24
316
 
25
- class BaseAioApi():
317
+ class BaseAioApi:
26
318
  """BaseApi, internal use only.
27
319
 
28
320
  """
@@ -188,6 +188,6 @@ def check_and_upload(model, elem: dict, api_key):
188
188
  return has_upload
189
189
 
190
190
 
191
- def preprocess_message_element(model: str, elem: List[dict], api_key: str):
191
+ def preprocess_message_element(model: str, elem: dict, api_key: str):
192
192
  is_upload = check_and_upload(model, elem, api_key)
193
193
  return is_upload
dashscope/version.py CHANGED
@@ -1,3 +1,3 @@
1
1
  # Copyright (c) Alibaba, Inc. and its affiliates.
2
2
 
3
- __version__ = '1.24.2'
3
+ __version__ = '1.24.3'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dashscope
3
- Version: 1.24.2
3
+ Version: 1.24.3
4
4
  Summary: dashscope client sdk library
5
5
  Home-page: https://dashscope.aliyun.com/
6
6
  Author: Alibaba Cloud
@@ -23,6 +23,7 @@ Requires-Dist: aiohttp
23
23
  Requires-Dist: requests
24
24
  Requires-Dist: websocket-client
25
25
  Requires-Dist: cryptography
26
+ Requires-Dist: certifi
26
27
  Provides-Extra: tokenizer
27
28
  Requires-Dist: tiktoken; extra == "tokenizer"
28
29
  Dynamic: author
@@ -1,26 +1,26 @@
1
- dashscope/__init__.py,sha256=__BY0dzgFX5Bt50WL-2PJmI8EYOmnpXhABQntdqDtSM,3062
1
+ dashscope/__init__.py,sha256=MJI4PJmnevfQA_GA30_L3hmsq49hooZpg25k6w39dts,3120
2
2
  dashscope/cli.py,sha256=64oGkevgX0RHPPmMg0sevXDgaFLQNA_0vdtjQ7Z2pHM,26492
3
3
  dashscope/files.py,sha256=vRDQygm3lOqBZR73o7KNHs1iTBVuvLncuwJNxIYjzAU,3981
4
4
  dashscope/model.py,sha256=B5v_BtYLPqj6raClejBgdKg6WTGwhH_f-20pvsQqmsk,1491
5
5
  dashscope/models.py,sha256=dE4mzXkl85G343qVylSGpURPRdA5pZSqXlx6PcxqC_Q,1275
6
- dashscope/version.py,sha256=tFrHRbI2SJLqcZ_I7s27rempXOnJ1PnfN0UpyIemTGE,74
7
- dashscope/aigc/__init__.py,sha256=AuRhu_vA1K0tbs_C6DgcZYhTvxMuzDgpwHJNHzEPIHg,442
6
+ dashscope/version.py,sha256=V0YmAKw8G9I8NSRumZjDtPh52jnAd9OGCwh9X-oeC_M,74
7
+ dashscope/aigc/__init__.py,sha256=m51CHEKL3WPq-s14OF-G1Uk3rLj6B6KrU55bbCKU-Ak,500
8
8
  dashscope/aigc/chat_completion.py,sha256=ONlyyssIbfaKKcFo7cEKhHx5OCF2XX810HFzIExW1ho,14813
9
9
  dashscope/aigc/code_generation.py,sha256=p_mxDKJLQMW0IjFD46JRlZuEZCRESSVKEfLlAevBtqw,10936
10
10
  dashscope/aigc/conversation.py,sha256=95xEEY4ThZJysj5zy3aMw7ql9KLJVfD_1iHv9QZ17Ew,14282
11
11
  dashscope/aigc/generation.py,sha256=xMcMu16rICTdjZiD_sPqYV_Ltdp4ewGzzfC7JD9VApY,17948
12
- dashscope/aigc/image_synthesis.py,sha256=Jgqmyv4jRxikgX7J18QrKKQ4OZAMxs6Q6YXObae3DhI,13363
13
- dashscope/aigc/multimodal_conversation.py,sha256=1rZZRk_1lCdbVs7Rx1kJ5LvwWE1put5p_dQKdCX0ysY,5574
14
- dashscope/aigc/video_synthesis.py,sha256=XQ3-NKYFmj5cIbUbLTbI0-FyC_fQp8eds6QmD1ZHj_0,13015
12
+ dashscope/aigc/image_synthesis.py,sha256=Itx9h5brEwC-d3Mj_ntDHGd4qaitqDg9DeGHMJouhMk,28178
13
+ dashscope/aigc/multimodal_conversation.py,sha256=Kjg8Gtfhl_Ok8WVwD-AeT-VBN9hh6E74TfkCxkL5wbY,10821
14
+ dashscope/aigc/video_synthesis.py,sha256=RSPjar5-YiF9xclRmf9H7-5QbRxLcsNXO4zS7oTKi2I,24137
15
15
  dashscope/api_entities/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
16
  dashscope/api_entities/aiohttp_request.py,sha256=1L7XdIJ9L65cQmX8x9JCR4t5hNIMDrbiWADfKKp9yfo,10280
17
17
  dashscope/api_entities/api_request_data.py,sha256=04rpYPNK1HkT3iTPJmZpquH621xcBbe8R8EGrDJSLt0,5514
18
- dashscope/api_entities/api_request_factory.py,sha256=18A40aHL0t3s01VdbkIWRGNeVJyX0GXRHTZUxau7po4,5640
18
+ dashscope/api_entities/api_request_factory.py,sha256=ynpbFmxSne4dJkv5m40Vlwt4hJSxQPprAuUgMSQIQDg,5639
19
19
  dashscope/api_entities/base_request.py,sha256=W2SzrSAGFS6V8DErfSrayQtSL0T4iO7BrC8flr7nt1w,977
20
20
  dashscope/api_entities/chat_completion_types.py,sha256=1WMWPszhM3HaJBVz-ZXx-El4D8-RfVUL3ym65xsDRLk,11435
21
- dashscope/api_entities/dashscope_response.py,sha256=qNNB86h5Gb_4uHjBD_4lx6UckyQzSdaTgjze1prc12M,22073
21
+ dashscope/api_entities/dashscope_response.py,sha256=slc7o9jNS5yzv2giEPzz9CDOW6X797nkAocgZ1r84aU,22089
22
22
  dashscope/api_entities/encryption.py,sha256=rUCZx3wwVvS5oyKXEeWgyWPxM8Y5d4AaVdgxLhizBqA,5517
23
- dashscope/api_entities/http_request.py,sha256=p2xfmq79evNON4ctCVXCcrJo8jnKABn0XzdTkTDgbLM,14540
23
+ dashscope/api_entities/http_request.py,sha256=MTxYsbkK8oYWDp8ZPjrkdY9YbnQ9SEIy87riyJidMXo,16484
24
24
  dashscope/api_entities/websocket_request.py,sha256=PS0FU854-HjTbKa68f4GHa7-noFRMzKySJGfPkrrBjw,16146
25
25
  dashscope/app/__init__.py,sha256=xvSvU8O7m5u7vgIvJXTJektJZxmjT2Rpt_YwePH88XE,113
26
26
  dashscope/app/application.py,sha256=Whf_ij4RHOaY12_xdS8uj8HVNCwkTp_MRdrFTryF1Kg,9472
@@ -48,7 +48,7 @@ dashscope/audio/tts_v2/__init__.py,sha256=me9a3_7KsHQxcJ8hx4SeKlY1e_ThHVvGMw7Yn0
48
48
  dashscope/audio/tts_v2/enrollment.py,sha256=-nrlywYSOP73Bm9ETTSxNnlp-B8ezJcUmd59mVvyvgk,6361
49
49
  dashscope/audio/tts_v2/speech_synthesizer.py,sha256=jbTwybwJjhbgUa6TgeLUYnkDBkmk-tjzxta1FtYeWAk,20824
50
50
  dashscope/client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
51
- dashscope/client/base_api.py,sha256=aWNy_xm02GXuLKVgWnYJht2nI4ZHSGfYIcr52SML15A,41239
51
+ dashscope/client/base_api.py,sha256=znAJ65DeHiFw1H7FWK0YrkLz1CoNcyqUxF8EJ3gujeY,52523
52
52
  dashscope/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
53
  dashscope/common/api_key.py,sha256=yqFCAteq8CNQGnlLv6fxNFWsLqsQDbSzOpgAlUmDkaE,2037
54
54
  dashscope/common/base_type.py,sha256=2OQDqFlEH43wn54i-691cbarV_eKRLvRsPGfyb_GS0g,4670
@@ -98,10 +98,10 @@ dashscope/tokenizers/tokenization.py,sha256=ubQBJ_yw_MoHuHxZcK9NarZSSbyExloeSOLI
98
98
  dashscope/tokenizers/tokenizer.py,sha256=3FQVDvMNkCW9ccYeJdjrd_PIMMD3Xv7aNZkaYOE4XX4,1205
99
99
  dashscope/tokenizers/tokenizer_base.py,sha256=5EJIFuizMWESEmLmbd38yJnfeHmPnzZPwsO4aOGjpl4,707
100
100
  dashscope/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
101
- dashscope/utils/oss_utils.py,sha256=0BrMogT1PgNAWLYx947akgw_lcLsaVIIMAL1KUtaB88,7507
102
- dashscope-1.24.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
103
- dashscope-1.24.2.dist-info/METADATA,sha256=W7cXJ-appClSQXDftF5s2agUBHZHKaqrfPZ_oKZ35N4,7123
104
- dashscope-1.24.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
105
- dashscope-1.24.2.dist-info/entry_points.txt,sha256=e9C3sOf9zDYL0O5ROEGX6FT8w-QK_kaGRWmPZDHAFys,49
106
- dashscope-1.24.2.dist-info/top_level.txt,sha256=woqavFJK9zas5xTqynmALqOtlafghjsk63Xk86powTU,10
107
- dashscope-1.24.2.dist-info/RECORD,,
101
+ dashscope/utils/oss_utils.py,sha256=aZIHlMN2JOfVw6kp0SVrMw_N1MfoTcR_-wiRbJ7DgHw,7501
102
+ dashscope-1.24.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
103
+ dashscope-1.24.3.dist-info/METADATA,sha256=fLj2JRtUdQhu6TCj2GdodS2iFXLay7WWgMCcEq15jm4,7146
104
+ dashscope-1.24.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
105
+ dashscope-1.24.3.dist-info/entry_points.txt,sha256=e9C3sOf9zDYL0O5ROEGX6FT8w-QK_kaGRWmPZDHAFys,49
106
+ dashscope-1.24.3.dist-info/top_level.txt,sha256=woqavFJK9zas5xTqynmALqOtlafghjsk63Xk86powTU,10
107
+ dashscope-1.24.3.dist-info/RECORD,,