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

dashscope/cli.py CHANGED
@@ -47,7 +47,7 @@ class FineTunes:
47
47
  if args.params:
48
48
  params.update(args.params)
49
49
 
50
- rsp = dashscope.FineTune.call(
50
+ rsp = dashscope.FineTunes.call(
51
51
  model=args.model,
52
52
  training_file_ids=args.training_file_ids,
53
53
  validation_file_ids=args.validation_file_ids,
@@ -64,7 +64,7 @@ class FineTunes:
64
64
  def wait(cls, job_id):
65
65
  try:
66
66
  while True:
67
- rsp = dashscope.FineTune.get(job_id)
67
+ rsp = dashscope.FineTunes.get(job_id)
68
68
  if rsp.status_code == HTTPStatus.OK:
69
69
  if rsp.output['status'] == TaskStatus.FAILED:
70
70
  print('Fine-tune FAILED!')
@@ -93,7 +93,7 @@ class FineTunes:
93
93
 
94
94
  @classmethod
95
95
  def get(cls, args):
96
- rsp = dashscope.FineTune.get(args.job)
96
+ rsp = dashscope.FineTunes.get(args.job)
97
97
  if rsp.status_code == HTTPStatus.OK:
98
98
  if rsp.output['status'] == TaskStatus.FAILED:
99
99
  print('Fine-tune failed!')
@@ -109,8 +109,8 @@ class FineTunes:
109
109
 
110
110
  @classmethod
111
111
  def list(cls, args):
112
- rsp = dashscope.FineTune.list(page=args.start_page,
113
- page_size=args.page_size)
112
+ rsp = dashscope.FineTunes.list(page=args.start_page,
113
+ page_size=args.page_size)
114
114
  if rsp.status_code == HTTPStatus.OK:
115
115
  if rsp.output is not None:
116
116
  for job in rsp.output['jobs']:
@@ -131,7 +131,7 @@ class FineTunes:
131
131
  @classmethod
132
132
  def stream_events(cls, job_id):
133
133
  # check job status if job is completed, get log.
134
- rsp = dashscope.FineTune.get(job_id)
134
+ rsp = dashscope.FineTunes.get(job_id)
135
135
  if rsp.status_code == HTTPStatus.OK:
136
136
  if rsp.output['status'] in [
137
137
  TaskStatus.FAILED, TaskStatus.CANCELED,
@@ -146,7 +146,7 @@ class FineTunes:
146
146
  return
147
147
  # start streaming events.
148
148
  try:
149
- stream_events = dashscope.FineTune.stream_events(job_id)
149
+ stream_events = dashscope.FineTunes.stream_events(job_id)
150
150
  for rsp in stream_events:
151
151
  if rsp.status_code == HTTPStatus.OK:
152
152
  print(rsp.output)
@@ -166,7 +166,7 @@ class FineTunes:
166
166
  start = 1
167
167
  n_line = 1000 # 1000 line per request
168
168
  while True:
169
- rsp = dashscope.FineTune.logs(job_id, start, n_line)
169
+ rsp = dashscope.FineTunes.logs(job_id, offset=start, line=n_line)
170
170
  if rsp.status_code == HTTPStatus.OK:
171
171
  for line in rsp.output['logs']:
172
172
  print(line)
@@ -179,7 +179,7 @@ class FineTunes:
179
179
 
180
180
  @classmethod
181
181
  def cancel(cls, args):
182
- rsp = dashscope.FineTune.cancel(args.job)
182
+ rsp = dashscope.FineTunes.cancel(args.job)
183
183
  if rsp.status_code == HTTPStatus.OK:
184
184
  print('Cancel fine-tune job: %s success!')
185
185
  else:
@@ -187,7 +187,7 @@ class FineTunes:
187
187
 
188
188
  @classmethod
189
189
  def delete(cls, args):
190
- rsp = dashscope.FineTune.delete(args.job)
190
+ rsp = dashscope.FineTunes.delete(args.job)
191
191
  if rsp.status_code == HTTPStatus.OK:
192
192
  print('fine_tune job: %s delete success' % args.job)
193
193
  else:
@@ -244,15 +244,15 @@ class Files:
244
244
  class Deployments:
245
245
  @classmethod
246
246
  def call(cls, args):
247
- rsp = dashscope.Deployment.call(model=args.model,
248
- capacity=args.capacity,
249
- suffix=args.suffix)
247
+ rsp = dashscope.Deployments.call(model=args.model,
248
+ capacity=args.capacity,
249
+ suffix=args.suffix)
250
250
  if rsp.status_code == HTTPStatus.OK:
251
251
  deployed_model = rsp.output['deployed_model']
252
252
  print('Create model: %s deployment' % deployed_model)
253
253
  try:
254
254
  while True: # wait for deployment ok.
255
- status = dashscope.Deployment.get(deployed_model)
255
+ status = dashscope.Deployments.get(deployed_model)
256
256
  if status.status_code == HTTPStatus.OK:
257
257
  if status.output['status'] in [
258
258
  DeploymentStatus.PENDING,
@@ -276,7 +276,7 @@ class Deployments:
276
276
 
277
277
  @classmethod
278
278
  def get(cls, args):
279
- rsp = dashscope.Deployment.get(args.deploy)
279
+ rsp = dashscope.Deployments.get(args.deploy)
280
280
  if rsp.status_code == HTTPStatus.OK:
281
281
  print('Deployed model: %s capacity: %s status: %s' %
282
282
  (rsp.output['deployed_model'], rsp.output['capacity'],
@@ -286,11 +286,12 @@ class Deployments:
286
286
 
287
287
  @classmethod
288
288
  def list(cls, args):
289
- rsp = dashscope.Deployment.list(page_no=args.start_page,
290
- page_size=args.page_size)
289
+ rsp = dashscope.Deployments.list(page_no=args.start_page,
290
+ page_size=args.page_size)
291
291
  if rsp.status_code == HTTPStatus.OK:
292
292
  if rsp.output is not None:
293
- if 'deployments' not in rsp.output:
293
+ if 'deployments' not in rsp.output or len(
294
+ rsp.output['deployments']) == 0:
294
295
  print('There is no deployed model!')
295
296
  return
296
297
  for deployment in rsp.output['deployments']:
@@ -304,7 +305,7 @@ class Deployments:
304
305
 
305
306
  @classmethod
306
307
  def update(cls, args):
307
- rsp = dashscope.Deployment.update(args.deployed_model, args.version)
308
+ rsp = dashscope.Deployments.update(args.deployed_model, args.version)
308
309
  if rsp.status_code == HTTPStatus.OK:
309
310
  if rsp.output is not None:
310
311
  if 'deployments' not in rsp.output:
@@ -321,7 +322,7 @@ class Deployments:
321
322
 
322
323
  @classmethod
323
324
  def scale(cls, args):
324
- rsp = dashscope.Deployment.scale(args.deployed_model, args.capacity)
325
+ rsp = dashscope.Deployments.scale(args.deployed_model, args.capacity)
325
326
  if rsp.status_code == HTTPStatus.OK:
326
327
  if rsp.output is not None:
327
328
  print('Deployed_model: %s, model: %s, status: %s' %
@@ -334,7 +335,7 @@ class Deployments:
334
335
 
335
336
  @classmethod
336
337
  def delete(cls, args):
337
- rsp = dashscope.Deployment.delete(args.deploy)
338
+ rsp = dashscope.Deployments.delete(args.deploy)
338
339
  if rsp.status_code == HTTPStatus.OK:
339
340
  print('Deployed model: %s delete success' % args.deploy)
340
341
  else:
@@ -33,15 +33,15 @@ class BaseAioApi():
33
33
  return api_key, model
34
34
 
35
35
  @classmethod
36
- def aio_call(cls,
37
- model: str,
38
- input: object,
39
- task_group: str,
40
- task: str = None,
41
- function: str = None,
42
- api_key: str = None,
43
- workspace: str = None,
44
- **kwargs) -> DashScopeAPIResponse:
36
+ async def call(cls,
37
+ model: str,
38
+ input: object,
39
+ task_group: str,
40
+ task: str = None,
41
+ function: str = None,
42
+ api_key: str = None,
43
+ workspace: str = None,
44
+ **kwargs) -> DashScopeAPIResponse:
45
45
  """Call service and get result.
46
46
 
47
47
  Args:
@@ -80,7 +80,7 @@ class BaseAioApi():
80
80
  api_key=api_key,
81
81
  **kwargs)
82
82
  # call request service.
83
- return request.aio_call()
83
+ return await request.aio_call()
84
84
 
85
85
 
86
86
  class BaseApi():
@@ -1006,7 +1006,7 @@ class StreamEventMixin():
1006
1006
  output=json_content,
1007
1007
  usage=None)
1008
1008
  else:
1009
- _handle_http_failed_response(response)
1009
+ yield _handle_http_failed_response(response)
1010
1010
 
1011
1011
  @classmethod
1012
1012
  def stream_events(cls,
@@ -27,7 +27,7 @@ class BaseObjectMixin(object):
27
27
  field_type_map = self._get_fields_type()
28
28
  for k, v in kwargs.items():
29
29
  field = field_type_map.get(k, None)
30
- if field:
30
+ if field and v is not None:
31
31
  if dataclasses.is_dataclass(field.type): # process dataclasses
32
32
  self.__setattr__(k, field.type(**v))
33
33
  continue
@@ -88,6 +88,9 @@ class BaseObjectMixin(object):
88
88
  def __getitem__(self, __key: Any) -> Any:
89
89
  return self.__getattribute__(__key)
90
90
 
91
+ def __contains__(self, item):
92
+ return hasattr(self, item)
93
+
91
94
  def __delitem__(self, key):
92
95
  self.__delattr__(key)
93
96
 
dashscope/common/utils.py CHANGED
@@ -2,6 +2,8 @@ import asyncio
2
2
  import json
3
3
  import os
4
4
  import platform
5
+ import queue
6
+ import threading
5
7
  from dataclasses import dataclass
6
8
  from http import HTTPStatus
7
9
  from typing import Dict
@@ -75,7 +77,8 @@ def is_url(url: str):
75
77
  return False
76
78
 
77
79
 
78
- def iter_over_async(ait, loop):
80
+ def iter_over_async(ait):
81
+ loop = asyncio.get_event_loop_policy().new_event_loop()
79
82
  ait = ait.__aiter__()
80
83
 
81
84
  async def get_next():
@@ -85,18 +88,41 @@ def iter_over_async(ait, loop):
85
88
  except StopAsyncIteration:
86
89
  return True, None
87
90
 
91
+ def iter_thread(loop, message_queue):
92
+ while True:
93
+ try:
94
+ done, obj = loop.run_until_complete(get_next())
95
+ if done:
96
+ message_queue.put((True, None, None))
97
+ break
98
+ message_queue.put((False, None, obj))
99
+ except BaseException as e: # noqa E722
100
+ logger.exception(e)
101
+ message_queue.put((True, e, None))
102
+ break
103
+
104
+ message_queue = queue.Queue()
105
+ x = threading.Thread(target=iter_thread,
106
+ args=(loop, message_queue),
107
+ name='iter_async_thread')
108
+ x.start()
88
109
  while True:
89
- done, obj = loop.run_until_complete(get_next())
90
- if done:
91
- loop.close()
110
+ finished, error, obj = message_queue.get()
111
+ if finished:
112
+ if error is not None:
113
+ yield DashScopeAPIResponse(
114
+ -1,
115
+ '',
116
+ 'Unknown',
117
+ message='Error type: %s, message: %s' %
118
+ (type(error), error))
92
119
  break
93
- yield obj
120
+ else:
121
+ yield obj
94
122
 
95
123
 
96
124
  def async_to_sync(async_generator):
97
- loop = asyncio.get_event_loop_policy().new_event_loop()
98
- asyncio.set_event_loop(loop)
99
- for message in iter_over_async(async_generator, loop):
125
+ for message in iter_over_async(async_generator):
100
126
  yield message
101
127
 
102
128
 
@@ -211,29 +237,46 @@ def _handle_stream(response: requests.Response):
211
237
  continue # ignore heartbeat...
212
238
 
213
239
 
240
+ def _handle_error_message(error, status_code, flattened_output):
241
+ code = None
242
+ msg = ''
243
+ request_id = ''
244
+ if flattened_output:
245
+ error['status_code'] = status_code
246
+ return error
247
+ if 'message' in error:
248
+ msg = error['message']
249
+ if 'msg' in error:
250
+ msg = error['msg']
251
+ if 'code' in error:
252
+ code = error['code']
253
+ if 'request_id' in error:
254
+ request_id = error['request_id']
255
+ return DashScopeAPIResponse(request_id=request_id,
256
+ status_code=status_code,
257
+ code=code,
258
+ message=msg)
259
+
260
+
214
261
  def _handle_http_failed_response(
215
262
  response: requests.Response,
216
263
  flattened_output: bool = False) -> DashScopeAPIResponse:
217
- msg = ''
218
- code = None
219
264
  request_id = ''
220
265
  if 'application/json' in response.headers.get('content-type', ''):
221
266
  error = response.json()
222
- if flattened_output:
223
- error['status_code'] = response.status_code
224
- return error
225
- if 'message' in error:
226
- msg = error['message']
227
- if 'msg' in error:
228
- msg = error['msg']
229
- if 'code' in error:
230
- code = error['code']
231
- if 'request_id' in error:
232
- request_id = error['request_id']
267
+ return _handle_error_message(error, response.status_code,
268
+ flattened_output)
269
+ elif SSE_CONTENT_TYPE in response.headers.get('content-type', ''):
270
+ msgs = response.content.decode('utf-8').split('\n')
271
+ for msg in msgs:
272
+ if msg.startswith('data:'):
273
+ error = json.loads(msg.replace('data:', '').strip())
274
+ return _handle_error_message(error, response.status_code,
275
+ flattened_output)
233
276
  return DashScopeAPIResponse(request_id=request_id,
234
277
  status_code=response.status_code,
235
- code=code,
236
- message=msg)
278
+ code='Unknown',
279
+ message=msgs)
237
280
  else:
238
281
  msg = response.content.decode('utf-8')
239
282
  if flattened_output:
@@ -244,6 +287,49 @@ def _handle_http_failed_response(
244
287
  message=msg)
245
288
 
246
289
 
290
+ async def _handle_aio_stream(response):
291
+ # TODO define done message.
292
+ is_error = False
293
+ status_code = HTTPStatus.BAD_REQUEST
294
+ async for line in response.content:
295
+ if line:
296
+ line = line.decode('utf8')
297
+ line = line.rstrip('\n').rstrip('\r')
298
+ if line.startswith('event:error'):
299
+ is_error = True
300
+ elif line.startswith('status:'):
301
+ status_code = line[len('status:'):]
302
+ status_code = int(status_code.strip())
303
+ elif line.startswith('data:'):
304
+ line = line[len('data:'):]
305
+ yield (is_error, status_code, line)
306
+ if is_error:
307
+ break
308
+ else:
309
+ continue # ignore heartbeat...
310
+
311
+
312
+ async def _handle_aiohttp_failed_response(
313
+ response: requests.Response,
314
+ flattened_output: bool = False) -> DashScopeAPIResponse:
315
+ request_id = ''
316
+ if 'application/json' in response.content_type:
317
+ error = await response.json()
318
+ return _handle_error_message(error, response.status, flattened_output)
319
+ elif SSE_CONTENT_TYPE in response.content_type:
320
+ async for _, _, data in _handle_aio_stream(response):
321
+ error = json.loads(data)
322
+ return _handle_error_message(error, response.status, flattened_output)
323
+ else:
324
+ msg = response.content.decode('utf-8')
325
+ if flattened_output:
326
+ return {'status_code': response.status, 'message': msg}
327
+ return DashScopeAPIResponse(request_id=request_id,
328
+ status_code=response.status,
329
+ code='Unknown',
330
+ message=msg)
331
+
332
+
247
333
  def _handle_http_response(response: requests.Response,
248
334
  flattened_output: bool = False):
249
335
  response = _handle_http_stream_response(response, flattened_output)
File without changes
@@ -0,0 +1,190 @@
1
+ from dataclasses import dataclass
2
+ from http import HTTPStatus
3
+ from typing import Dict, List
4
+
5
+ from dashscope.common.base_type import BaseObjectMixin
6
+
7
+ __all__ = ['Deployment', 'FineTune', 'DeploymentList', 'FineTuneList']
8
+
9
+
10
+ @dataclass(init=False)
11
+ class DashScopeBaseList(BaseObjectMixin):
12
+ page_no: int
13
+ page_size: int
14
+ total: int
15
+
16
+ def __init__(self, **kwargs):
17
+ super().__init__(**kwargs)
18
+
19
+
20
+ @dataclass(init=False)
21
+ class DashScopeBase(BaseObjectMixin):
22
+ status_code: int
23
+ request_id: str
24
+ code: str
25
+ message: str
26
+
27
+ def __init__(self, **kwargs):
28
+ super().__init__(**kwargs)
29
+
30
+
31
+ @dataclass(init=False)
32
+ class FineTuneOutput(BaseObjectMixin):
33
+ job_id: str
34
+ job_name: str
35
+ status: str
36
+ model: str
37
+ base_model: str
38
+ finetuned_output: str
39
+ training_file_ids: List[str]
40
+ validation_file_ids: List[str]
41
+ hyper_parameters: Dict
42
+ training_type: str
43
+ create_time: str
44
+ end_time: str
45
+ user_identity: str
46
+ modifier: str
47
+ creator: str
48
+ group: str
49
+ usage: int
50
+
51
+ def __init__(self, **kwargs):
52
+ super().__init__(**kwargs)
53
+
54
+
55
+ @dataclass(init=False)
56
+ class FineTune(DashScopeBase):
57
+ output: FineTuneOutput
58
+ usage: Dict
59
+
60
+ def __init__(self, **kwargs):
61
+ status_code = kwargs.get('status_code', None)
62
+ if status_code == HTTPStatus.OK:
63
+ self.output = FineTuneOutput(**kwargs.pop('output', {}))
64
+ super().__init__(**kwargs)
65
+
66
+
67
+ @dataclass(init=False)
68
+ class FineTuneListOutput(DashScopeBaseList):
69
+ jobs: List[FineTuneOutput]
70
+
71
+ def __init__(self, **kwargs):
72
+ self.jobs = []
73
+ for job in kwargs.pop('jobs', []):
74
+ self.jobs.append(FineTuneOutput(**job))
75
+ super().__init__(**kwargs)
76
+
77
+
78
+ @dataclass(init=False)
79
+ class FineTuneList(DashScopeBase):
80
+ output: FineTuneListOutput
81
+
82
+ def __init__(self, **kwargs):
83
+ status_code = kwargs.get('status_code', None)
84
+ if status_code == HTTPStatus.OK:
85
+ self.output = FineTuneListOutput(**kwargs.pop('output', {}))
86
+ super().__init__(**kwargs)
87
+
88
+
89
+ @dataclass(init=False)
90
+ class CancelDeleteStatus(BaseObjectMixin):
91
+ status: str
92
+
93
+
94
+ @dataclass(init=False)
95
+ class FineTuneCancel(DashScopeBase):
96
+ output: CancelDeleteStatus
97
+
98
+ def __init__(self, **kwargs):
99
+ status_code = kwargs.get('status_code', None)
100
+ if status_code == HTTPStatus.OK:
101
+ self.output = CancelDeleteStatus(**kwargs.pop('output', {}))
102
+ super().__init__(**kwargs)
103
+
104
+
105
+ @dataclass(init=False)
106
+ class FineTuneDelete(DashScopeBase):
107
+ output: CancelDeleteStatus
108
+
109
+ def __init__(self, **kwargs):
110
+ status_code = kwargs.get('status_code', None)
111
+ if status_code == HTTPStatus.OK:
112
+ self.output = CancelDeleteStatus(**kwargs.pop('output', {}))
113
+ super().__init__(**kwargs)
114
+
115
+
116
+ @dataclass(init=False)
117
+ class FineTuneEvent(DashScopeBase):
118
+ output: str
119
+
120
+ def __init__(self, **kwargs):
121
+ status_code = kwargs.get('status_code', None)
122
+ if status_code == HTTPStatus.OK:
123
+ self.output = kwargs.pop('output', {})
124
+ super().__init__(**kwargs)
125
+
126
+
127
+ @dataclass(init=False)
128
+ class DeploymentOutput(BaseObjectMixin):
129
+ deployed_model: str
130
+ gmt_create: str
131
+ gmt_modified: str
132
+ status: str
133
+ model_name: str
134
+ base_model: str
135
+ base_capacity: int
136
+ capacity: int
137
+ ready_capacity: int
138
+ workspace_id: str
139
+ charge_type: str
140
+ modifier: str
141
+ creator: str
142
+
143
+ def __init__(self, **kwargs):
144
+ super().__init__(**kwargs)
145
+
146
+
147
+ @dataclass(init=False)
148
+ class Deployment(DashScopeBase):
149
+ output: DeploymentOutput
150
+
151
+ def __init__(self, **kwargs):
152
+ output = kwargs.pop('output', {})
153
+ if output:
154
+ self.output = DeploymentOutput(**output)
155
+ else:
156
+ self.output = None
157
+ super().__init__(**kwargs)
158
+
159
+
160
+ @dataclass(init=False)
161
+ class DeploymentListOutput(DashScopeBaseList):
162
+ deployments: List[DeploymentOutput]
163
+
164
+ def __init__(self, **kwargs):
165
+ self.deployments = []
166
+ for job in kwargs.pop('deployments', []):
167
+ self.deployments.append(DeploymentOutput(**job))
168
+ super().__init__(**kwargs)
169
+
170
+
171
+ @dataclass(init=False)
172
+ class DeploymentList(BaseObjectMixin):
173
+ output: DeploymentListOutput
174
+
175
+ def __init__(self, **kwargs):
176
+ status_code = kwargs.get('status_code', None)
177
+ if status_code == HTTPStatus.OK:
178
+ self.output = DeploymentListOutput(**kwargs.pop('output', {}))
179
+ super().__init__(**kwargs)
180
+
181
+
182
+ @dataclass(init=False)
183
+ class DeploymentDelete(DashScopeBase):
184
+ output: CancelDeleteStatus
185
+
186
+ def __init__(self, **kwargs):
187
+ status_code = kwargs.get('status_code', None)
188
+ if status_code == HTTPStatus.OK:
189
+ self.output = CancelDeleteStatus(**kwargs.pop('output', {}))
190
+ super().__init__(**kwargs)