dashscope 1.15.0__py3-none-any.whl → 1.17.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 +21 -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 +18 -9
  11. dashscope/api_entities/websocket_request.py +3 -0
  12. dashscope/app/application.py +16 -23
  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 +303 -68
  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 +22 -6
  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 +408 -0
  44. dashscope/threads/runs/steps.py +110 -0
  45. dashscope/threads/thread_types.py +571 -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.17.0.dist-info}/METADATA +2 -3
  51. dashscope-1.17.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.17.0.dist-info}/LICENSE +0 -0
  54. {dashscope-1.15.0.dist-info → dashscope-1.17.0.dist-info}/WHEEL +0 -0
  55. {dashscope-1.15.0.dist-info → dashscope-1.17.0.dist-info}/entry_points.txt +0 -0
  56. {dashscope-1.15.0.dist-info → dashscope-1.17.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,130 @@
1
+ import dataclasses
2
+ from dataclasses import dataclass
3
+ from typing import Any, List
4
+
5
+ import dashscope
6
+
7
+
8
+ def get_object_type(name: str):
9
+ dashscope_objects = {
10
+ 'assistant': dashscope.Assistant,
11
+ 'assistant.deleted': dashscope.DeleteResponse,
12
+ 'thread.message': dashscope.ThreadMessage,
13
+ 'thread.run': dashscope.Run,
14
+ 'thread.run.step': dashscope.RunStep,
15
+ 'thread.message.file': dashscope.MessageFile,
16
+ 'assistant.file': dashscope.AssistantFile,
17
+ 'thread': dashscope.Thread,
18
+ }
19
+ return dashscope_objects.get(name, None)
20
+
21
+
22
+ @dataclass(init=False)
23
+ class BaseObjectMixin(object):
24
+ __slots__ = ()
25
+
26
+ def __init__(self, **kwargs):
27
+ field_type_map = self._get_fields_type()
28
+ for k, v in kwargs.items():
29
+ field = field_type_map.get(k, None)
30
+ if field:
31
+ if dataclasses.is_dataclass(field.type): # process dataclasses
32
+ self.__setattr__(k, field.type(**v))
33
+ continue
34
+
35
+ if isinstance(v, dict):
36
+ object_name = v.get('object', None)
37
+ if object_name:
38
+ object_type = get_object_type(object_name)
39
+ if object_type:
40
+ self.__setattr__(k, object_type(**v))
41
+ else:
42
+ self.__setattr__(k, v)
43
+ else:
44
+ self.__setattr__(k, v)
45
+ elif isinstance(v, list):
46
+ obj_list = self._init_list_element_recursive(field, v)
47
+ self.__setattr__(k, obj_list)
48
+ else:
49
+ self.__setattr__(k, v)
50
+
51
+ def _init_list_element_recursive(self, field, items: list) -> List[Any]:
52
+ obj_list = []
53
+ for item in items:
54
+ if field:
55
+ # current only support List[cls_name],
56
+ # not support List[cls_nam1, cls_name2]
57
+ element_type = field.type.__args__[0]
58
+ if dataclasses.is_dataclass(element_type):
59
+ obj_list.append(element_type(**item))
60
+ continue
61
+
62
+ if isinstance(item, dict):
63
+ object_name = item.get('object', None)
64
+ if object_name:
65
+ object_type = get_object_type(object_name)
66
+ if object_type:
67
+ obj_list.append(object_type(**item))
68
+ else:
69
+ obj_list.append(item)
70
+ else:
71
+ obj_list.append(item)
72
+ elif isinstance(item, list):
73
+ obj_list.append(self._init_list_element_recursive(item))
74
+ else:
75
+ obj_list.append(item)
76
+ return obj_list
77
+
78
+ def _get_fields_type(self):
79
+ field_type_map = {}
80
+ if dataclasses.is_dataclass(self):
81
+ for field in dataclasses.fields(self):
82
+ field_type_map[field.name] = field
83
+ return field_type_map
84
+
85
+ def __setitem__(self, __key: Any, __value: Any) -> None:
86
+ return self.__setattr__(__key, __value)
87
+
88
+ def __getitem__(self, __key: Any) -> Any:
89
+ return self.__getattribute__(__key)
90
+
91
+ def __delitem__(self, key):
92
+ self.__delattr__(key)
93
+
94
+ def _recursive_to_str__(self, input_object) -> Any:
95
+ if isinstance(input_object, list):
96
+ output_object = []
97
+ for item in input_object:
98
+ output_object.append(self._recursive_to_str__(item))
99
+ return output_object
100
+ elif dataclasses.is_dataclass(input_object):
101
+ output_object = {}
102
+ for field in dataclasses.fields(input_object):
103
+ if hasattr(input_object, field.name):
104
+ output_object[field.name] = self._recursive_to_str__(
105
+ getattr(input_object, field.name))
106
+ return output_object
107
+ else:
108
+ return input_object
109
+
110
+ def __str__(self) -> str:
111
+ real_dict = self.__dict__
112
+ self_fields = dataclasses.fields(self)
113
+ for field in self_fields:
114
+ if hasattr(self, field.name):
115
+ real_dict[field.name] = getattr(self, field.name)
116
+ output_object = {}
117
+ for key, value in real_dict.items():
118
+ output_object[key] = self._recursive_to_str__(value)
119
+ return str(output_object)
120
+
121
+
122
+ @dataclass(init=False)
123
+ class BaseList(BaseObjectMixin):
124
+ status_code: int
125
+ has_more: bool
126
+ last_id: str
127
+ first_id: str
128
+
129
+ def __init__(self, **kwargs):
130
+ super().__init__(**kwargs)
@@ -42,6 +42,7 @@ REPEATABLE_STATUS = [
42
42
 
43
43
  class FilePurpose:
44
44
  fine_tune = 'fine_tune'
45
+ assistants = 'assistants'
45
46
 
46
47
 
47
48
  class DeploymentStatus:
dashscope/common/error.py CHANGED
@@ -106,3 +106,7 @@ class AsyncTaskCreateFailed(DashScopeException):
106
106
 
107
107
  class UploadFileException(DashScopeException):
108
108
  pass
109
+
110
+
111
+ class TimeoutException(DashScopeException):
112
+ pass
dashscope/common/utils.py CHANGED
@@ -8,6 +8,7 @@ from urllib.parse import urlparse
8
8
 
9
9
  import aiohttp
10
10
  import requests
11
+
11
12
  from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
12
13
  from dashscope.common.api_key import get_default_api_key
13
14
  from dashscope.version import __version__
@@ -126,7 +127,7 @@ def join_url(base_url, *args):
126
127
  base_url = base_url + '/'
127
128
  url = base_url
128
129
  for arg in args:
129
- if arg:
130
+ if arg is not None:
130
131
  url += arg + '/'
131
132
  return url[:-1]
132
133
 
@@ -163,12 +164,16 @@ async def _handle_aiohttp_response(response: aiohttp.ClientResponse):
163
164
 
164
165
 
165
166
  def _handle_http_failed_response(
166
- response: requests.Response) -> DashScopeAPIResponse:
167
+ response: requests.Response,
168
+ flattened_output: bool = False) -> DashScopeAPIResponse:
167
169
  msg = ''
168
170
  code = None
169
171
  request_id = ''
170
172
  if 'application/json' in response.headers.get('content-type', ''):
171
173
  error = response.json()
174
+ if flattened_output:
175
+ error['status_code'] = response.status_code
176
+ return error
172
177
  if 'message' in error:
173
178
  msg = error['message']
174
179
  if 'msg' in error:
@@ -183,20 +188,26 @@ def _handle_http_failed_response(
183
188
  message=msg)
184
189
  else:
185
190
  msg = response.content.decode('utf-8')
191
+ if flattened_output:
192
+ return {'status_code': response.status_code, 'message': msg}
186
193
  return DashScopeAPIResponse(request_id=request_id,
187
194
  status_code=response.status_code,
188
195
  code='Unknown',
189
196
  message=msg)
190
197
 
191
198
 
192
- def _handle_http_response(response: requests.Response):
199
+ def _handle_http_response(response: requests.Response,
200
+ flattened_output: bool = False):
193
201
  request_id = ''
194
- if response.status_code == HTTPStatus.OK:
202
+ if response.status_code == HTTPStatus.OK or response.status_code == HTTPStatus.CREATED:
203
+ json_content = response.json()
204
+ if flattened_output:
205
+ json_content['status_code'] = response.status_code
206
+ return json_content
195
207
  output = None
196
208
  usage = None
197
209
  code = None
198
210
  msg = ''
199
- json_content = response.json()
200
211
  if 'data' in json_content:
201
212
  output = json_content['data']
202
213
  if 'code' in json_content:
@@ -209,6 +220,11 @@ def _handle_http_response(response: requests.Response):
209
220
  usage = json_content['usage']
210
221
  if 'request_id' in json_content:
211
222
  request_id = json_content['request_id']
223
+ json_content.pop('request_id', None)
224
+
225
+ if 'data' not in json_content and 'output' not in json_content:
226
+ output = json_content
227
+
212
228
  return DashScopeAPIResponse(request_id=request_id,
213
229
  status_code=response.status_code,
214
230
  code=code,
@@ -216,4 +232,4 @@ def _handle_http_response(response: requests.Response):
216
232
  usage=usage,
217
233
  message=msg)
218
234
  else:
219
- return _handle_http_failed_response(response)
235
+ return _handle_http_failed_response(response, flattened_output)
dashscope/deployment.py CHANGED
@@ -15,6 +15,7 @@ class Deployment(CreateMixin, DeleteMixin, ListMixin, GetMixin,
15
15
  version: str = None,
16
16
  suffix: str = None,
17
17
  api_key: str = None,
18
+ workspace: str = None,
18
19
  **kwargs) -> DashScopeAPIResponse:
19
20
  """Call to deployment a model service.
20
21
 
@@ -27,6 +28,7 @@ class Deployment(CreateMixin, DeleteMixin, ListMixin, GetMixin,
27
28
  Defaults to None.
28
29
  capacity (int, optional): The model service capacity.
29
30
  api_key (str, optional): The api-key. Defaults to None.
31
+ workspace (str): The dashscope workspace id.
30
32
 
31
33
  Returns:
32
34
  DashScopeAPIResponse: _description_
@@ -37,13 +39,17 @@ class Deployment(CreateMixin, DeleteMixin, ListMixin, GetMixin,
37
39
  req['model_version'] = version
38
40
  if suffix is not None:
39
41
  req['suffix'] = suffix
40
- return super().call(req, api_key, **kwargs)
42
+ return super().call(req,
43
+ api_key=api_key,
44
+ workspace=workspace,
45
+ **kwargs)
41
46
 
42
47
  @classmethod
43
48
  def list(cls,
44
49
  page_no=1,
45
50
  page_size=10,
46
51
  api_key: str = None,
52
+ workspace: str = None,
47
53
  **kwargs) -> DashScopeAPIResponse:
48
54
  """List deployments.
49
55
 
@@ -52,49 +58,65 @@ class Deployment(CreateMixin, DeleteMixin, ListMixin, GetMixin,
52
58
  will get by default rule(TODO: api key doc). Defaults to None.
53
59
  page_no (int, optional): Page number. Defaults to 1.
54
60
  page_size (int, optional): Items per page. Defaults to 10.
61
+ workspace (str): The dashscope workspace id.
55
62
 
56
63
  Returns:
57
64
  DashScopeAPIResponse: The deployment list.
58
65
  """
59
- return super().list(page_no, page_size, api_key, **kwargs)
66
+ return super().list(page_no,
67
+ page_size,
68
+ api_key,
69
+ workspace=workspace,
70
+ **kwargs)
60
71
 
61
72
  @classmethod
62
73
  def get(cls,
63
74
  deployed_model: str,
64
75
  api_key: str = None,
76
+ workspace: str = None,
65
77
  **kwargs) -> DashScopeAPIResponse:
66
78
  """Get model deployment information.
67
79
 
68
80
  Args:
69
81
  deployed_model (str): The deployment_id.
70
82
  api_key (str, optional): The api key. Defaults to None.
83
+ workspace (str): The dashscope workspace id.
71
84
 
72
85
  Returns:
73
86
  DashScopeAPIResponse: The deployment information.
74
87
  """
75
- return super().get(deployed_model, api_key, **kwargs)
88
+ return super().get(deployed_model,
89
+ api_key,
90
+ workspace=workspace,
91
+ **kwargs)
76
92
 
77
93
  @classmethod
78
94
  def delete(cls,
79
95
  deployment_id: str,
80
96
  api_key: str = None,
97
+ workspace: str = None,
81
98
  **kwargs) -> DashScopeAPIResponse:
82
99
  """Delete model deployment.
83
100
 
84
101
  Args:
85
102
  deployment_id (str): The deployment id.
86
103
  api_key (str, optional): The api key. Defaults to None.
104
+ workspace (str): The dashscope workspace id.
87
105
 
88
106
  Returns:
89
107
  DashScopeAPIResponse: The delete result.
90
108
  """
91
- return super().delete(deployment_id, api_key, **kwargs)
109
+ return super().delete(deployment_id,
110
+ api_key,
111
+ workspace=workspace,
112
+ **kwargs)
92
113
 
93
114
  @classmethod
94
115
  def update(cls,
95
116
  deployment_id: str,
96
117
  version: str,
97
118
  api_key: str = None,
119
+ workspace: str = None,
98
120
  **kwargs) -> DashScopeAPIResponse:
99
121
  """Update model deployment.
100
122
 
@@ -102,18 +124,24 @@ class Deployment(CreateMixin, DeleteMixin, ListMixin, GetMixin,
102
124
  deployment_id (str): The deployment id.
103
125
  version (str): The target model version.
104
126
  api_key (str, optional): The api key. Defaults to None.
127
+ workspace (str): The dashscope workspace id.
105
128
 
106
129
  Returns:
107
130
  DashScopeAPIResponse: The delete result.
108
131
  """
109
132
  req = {'deployment_model': deployment_id, 'model_version': version}
110
- return super().put(deployment_id, req, api_key, **kwargs)
133
+ return super().put(deployment_id,
134
+ req,
135
+ api_key,
136
+ workspace=workspace,
137
+ **kwargs)
111
138
 
112
139
  @classmethod
113
140
  def scale(cls,
114
141
  deployment_id: str,
115
142
  capacity: int,
116
143
  api_key: str = None,
144
+ workspace: str = None,
117
145
  **kwargs) -> DashScopeAPIResponse:
118
146
  """Scaling model deployment.
119
147
 
@@ -126,4 +154,10 @@ class Deployment(CreateMixin, DeleteMixin, ListMixin, GetMixin,
126
154
  DashScopeAPIResponse: The delete result.
127
155
  """
128
156
  req = {'deployed_model': deployment_id, 'capacity': capacity}
129
- return super().put(deployment_id, req, 'scale', api_key, **kwargs)
157
+ path = '%s/%s/scale' % (cls.SUB_PATH.lower(), deployment_id)
158
+ return super().put(deployment_id,
159
+ req,
160
+ path=path,
161
+ api_key=api_key,
162
+ workspace=workspace,
163
+ **kwargs)
@@ -22,6 +22,7 @@ class BatchTextEmbedding(BaseAsyncApi):
22
22
  model: str,
23
23
  url: str,
24
24
  api_key: str = None,
25
+ workspace: str = None,
25
26
  **kwargs) -> BatchTextEmbeddingResponse:
26
27
  """Call async text embedding service and get result.
27
28
 
@@ -30,6 +31,7 @@ class BatchTextEmbedding(BaseAsyncApi):
30
31
  url (Any): The async request file url, which contains text
31
32
  to embedding line by line.
32
33
  api_key (str, optional): The api api_key. Defaults to None.
34
+ workspace (str): The dashscope workspace id.
33
35
  **kwargs:
34
36
  text_type(str, `optional`): [query|document], After the
35
37
  text is converted into a vector, it can be applied to
@@ -47,13 +49,18 @@ class BatchTextEmbedding(BaseAsyncApi):
47
49
  Returns:
48
50
  AsyncTextEmbeddingResponse: The async text embedding task result.
49
51
  """
50
- return super().call(model, url, api_key=api_key, **kwargs)
52
+ return super().call(model,
53
+ url,
54
+ api_key=api_key,
55
+ workspace=workspace,
56
+ **kwargs)
51
57
 
52
58
  @classmethod
53
59
  def async_call(cls,
54
60
  model: str,
55
61
  url: str,
56
62
  api_key: str = None,
63
+ workspace: str = None,
57
64
  **kwargs) -> BatchTextEmbeddingResponse:
58
65
  """Create a async text embedding task, and return task information.
59
66
 
@@ -62,6 +69,7 @@ class BatchTextEmbedding(BaseAsyncApi):
62
69
  url (Any): The async request file url, which contains text
63
70
  to embedding line by line.
64
71
  api_key (str, optional): The api api_key. Defaults to None.
72
+ workspace (str): The dashscope workspace id.
65
73
  **kwargs:
66
74
  text_type(str, `optional`): [query|document], After the
67
75
  text is converted into a vector, it can be applied to
@@ -91,47 +99,53 @@ class BatchTextEmbedding(BaseAsyncApi):
91
99
  function=BatchTextEmbedding.function,
92
100
  api_key=api_key,
93
101
  input=input,
102
+ workspace=workspace,
94
103
  **kwargs)
95
104
  return BatchTextEmbeddingResponse.from_api_response(response)
96
105
 
97
106
  @classmethod
98
107
  def fetch(cls,
99
108
  task: Union[str, BatchTextEmbeddingResponse],
100
- api_key: str = None) -> BatchTextEmbeddingResponse:
109
+ api_key: str = None,
110
+ workspace: str = None) -> BatchTextEmbeddingResponse:
101
111
  """Fetch async text embedding task status or result.
102
112
 
103
113
  Args:
104
114
  task (Union[str, AsyncTextEmbeddingResponse]): The task_id or
105
115
  AsyncTextEmbeddingResponse return by async_call().
106
116
  api_key (str, optional): The api api_key. Defaults to None.
117
+ workspace (str): The dashscope workspace id.
107
118
 
108
119
  Returns:
109
120
  AsyncTextEmbeddingResponse: The task status or result.
110
121
  """
111
- response = super().fetch(task, api_key)
122
+ response = super().fetch(task, api_key, workspace=workspace)
112
123
  return BatchTextEmbeddingResponse.from_api_response(response)
113
124
 
114
125
  @classmethod
115
126
  def wait(cls,
116
127
  task: Union[str, BatchTextEmbeddingResponse],
117
- api_key: str = None) -> BatchTextEmbeddingResponse:
128
+ api_key: str = None,
129
+ workspace: str = None) -> BatchTextEmbeddingResponse:
118
130
  """Wait for async text embedding task to complete, and return the result.
119
131
 
120
132
  Args:
121
133
  task (Union[str, AsyncTextEmbeddingResponse]): The task_id or
122
134
  AsyncTextEmbeddingResponse return by async_call().
123
135
  api_key (str, optional): The api api_key. Defaults to None.
136
+ workspace (str): The dashscope workspace id.
124
137
 
125
138
  Returns:
126
139
  AsyncTextEmbeddingResponse: The task result.
127
140
  """
128
- response = super().wait(task, api_key)
141
+ response = super().wait(task, api_key, workspace=workspace)
129
142
  return BatchTextEmbeddingResponse.from_api_response(response)
130
143
 
131
144
  @classmethod
132
145
  def cancel(cls,
133
146
  task: Union[str, BatchTextEmbeddingResponse],
134
- api_key: str = None) -> DashScopeAPIResponse:
147
+ api_key: str = None,
148
+ workspace: str = None) -> DashScopeAPIResponse:
135
149
  """Cancel async text embedding task.
136
150
  Only tasks whose status is PENDING can be canceled.
137
151
 
@@ -139,11 +153,12 @@ class BatchTextEmbedding(BaseAsyncApi):
139
153
  task (Union[str, AsyncTextEmbeddingResponse]): The task_id or
140
154
  AsyncTextEmbeddingResponse return by async_call().
141
155
  api_key (str, optional): The api api_key. Defaults to None.
156
+ workspace (str): The dashscope workspace id.
142
157
 
143
158
  Returns:
144
159
  DashScopeAPIResponse: The response data.
145
160
  """
146
- return super().cancel(task, api_key)
161
+ return super().cancel(task, api_key, workspace=workspace)
147
162
 
148
163
  @classmethod
149
164
  def list(cls,
@@ -156,6 +171,7 @@ class BatchTextEmbedding(BaseAsyncApi):
156
171
  page_no: int = 1,
157
172
  page_size: int = 10,
158
173
  api_key: str = None,
174
+ workspace: str = None,
159
175
  **kwargs) -> DashScopeAPIResponse:
160
176
  """List async tasks.
161
177
 
@@ -186,4 +202,5 @@ class BatchTextEmbedding(BaseAsyncApi):
186
202
  page_no=page_no,
187
203
  page_size=page_size,
188
204
  api_key=api_key,
205
+ workspace=workspace,
189
206
  **kwargs)
@@ -55,6 +55,7 @@ class MultiModalEmbedding(BaseApi):
55
55
  model: str,
56
56
  input: List[MultiModalEmbeddingItemBase],
57
57
  api_key: str = None,
58
+ workspace: str = None,
58
59
  **kwargs) -> DashScopeAPIResponse:
59
60
  """Get embedding multimodal contents..
60
61
 
@@ -62,6 +63,7 @@ class MultiModalEmbedding(BaseApi):
62
63
  model (str): The embedding model name.
63
64
  input (List[MultiModalEmbeddingElement]): The embedding elements,
64
65
  every element include data, modal, factor field.
66
+ workspace (str): The dashscope workspace id.
65
67
  **kwargs:
66
68
  auto_truncation(bool, `optional`): Automatically truncate
67
69
  audio longer than 15 seconds or text longer than 70 words.
@@ -89,6 +91,7 @@ class MultiModalEmbedding(BaseApi):
89
91
  task=MultiModalEmbedding.task,
90
92
  function=function,
91
93
  api_key=api_key,
94
+ workspace=workspace,
92
95
  **kwargs)
93
96
 
94
97
  @classmethod
@@ -14,7 +14,11 @@ class TextEmbedding(BaseApi):
14
14
  text_embedding_v2 = 'text-embedding-v2'
15
15
 
16
16
  @classmethod
17
- def call(cls, model: str, input: Union[str, List[str]],
17
+ def call(cls,
18
+ model: str,
19
+ input: Union[str, List[str]],
20
+ workspace: str = None,
21
+ api_key: str = None,
18
22
  **kwargs) -> DashScopeAPIResponse:
19
23
  """Get embedding of text input.
20
24
 
@@ -24,6 +28,7 @@ class TextEmbedding(BaseApi):
24
28
  can be a text or list of text or opened file object,
25
29
  if opened file object, will read all lines,
26
30
  one embedding per line.
31
+ workspace (str): The dashscope workspace id.
27
32
  **kwargs:
28
33
  text_type(str, `optional`): query or document.
29
34
 
@@ -42,4 +47,6 @@ class TextEmbedding(BaseApi):
42
47
  task_group=task_group,
43
48
  task=TextEmbedding.task,
44
49
  function=function,
50
+ api_key=api_key,
51
+ workspace=workspace,
45
52
  **kwargs)
dashscope/files.py ADDED
@@ -0,0 +1,107 @@
1
+ import os
2
+
3
+ from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
4
+ from dashscope.client.base_api import (DeleteMixin, FileUploadMixin, GetMixin,
5
+ ListMixin)
6
+ from dashscope.common.constants import FilePurpose
7
+ from dashscope.common.error import InvalidFileFormat
8
+ from dashscope.common.utils import is_validate_fine_tune_file
9
+
10
+
11
+ class Files(FileUploadMixin, ListMixin, DeleteMixin, GetMixin):
12
+ SUB_PATH = 'files'
13
+
14
+ @classmethod
15
+ def upload(cls,
16
+ file_path: str,
17
+ purpose: str = FilePurpose.fine_tune,
18
+ description: str = None,
19
+ api_key: str = None,
20
+ workspace: str = None,
21
+ **kwargs) -> DashScopeAPIResponse:
22
+ """Upload file for model fine-tune or other tasks.
23
+
24
+ Args:
25
+ file_path (str): The local file name to upload.
26
+ purpose (str): The purpose of the file[fine-tune|inference]
27
+ description (str, optional): The file description message.
28
+ api_key (str, optional): The api key. Defaults to None.
29
+ workspace (str): The dashscope workspace id.
30
+
31
+ Returns:
32
+ DashScopeAPIResponse: The upload information
33
+ """
34
+ if purpose == FilePurpose.fine_tune:
35
+ if not is_validate_fine_tune_file(file_path):
36
+ raise InvalidFileFormat(
37
+ 'The file %s is not in valid jsonl format' % file_path)
38
+ with open(file_path, 'rb') as f:
39
+ return super().upload(files=[('files', (os.path.basename(f.name),
40
+ f, None))],
41
+ descriptions=[description]
42
+ if description is not None else None,
43
+ api_key=api_key,
44
+ workspace=workspace,
45
+ **kwargs)
46
+
47
+ @classmethod
48
+ def list(cls,
49
+ page=1,
50
+ page_size=10,
51
+ api_key: str = None,
52
+ workspace: str = None,
53
+ **kwargs) -> DashScopeAPIResponse:
54
+ """List uploaded files.
55
+
56
+ Args:
57
+ api_key (str, optional):
58
+ The api api_key, can be None,
59
+ if None, will get by default rule(TODO: api key doc).
60
+ page (int, optional): Page number. Defaults to 1.
61
+ page_size (int, optional): Items per page. Defaults to 10.
62
+ workspace (str): The dashscope workspace id.
63
+
64
+ Returns:
65
+ DashScopeAPIResponse: The fine-tune jobs in the result.
66
+ """
67
+ return super().list(page,
68
+ page_size,
69
+ api_key,
70
+ workspace=workspace,
71
+ **kwargs)
72
+
73
+ @classmethod
74
+ def get(cls,
75
+ file_id: str,
76
+ api_key: str = None,
77
+ workspace: str = None,
78
+ **kwargs) -> DashScopeAPIResponse:
79
+ """Get the file info.
80
+
81
+ Args:
82
+ file_id (str): The file id.
83
+ api_key (str, optional): The api key. Defaults to None.
84
+ workspace (str): The dashscope workspace id.
85
+
86
+ Returns:
87
+ DashScopeAPIResponse: The job info
88
+ """
89
+ return super().get(file_id, api_key, workspace=workspace, **kwargs)
90
+
91
+ @classmethod
92
+ def delete(cls,
93
+ file_id: str,
94
+ api_key: str = None,
95
+ workspace: str = None,
96
+ **kwargs) -> DashScopeAPIResponse:
97
+ """Delete uploaded file.
98
+
99
+ Args:
100
+ file_id (str): The file id want to delete.
101
+ api_key (str, optional): The api key. Defaults to None.
102
+ workspace (str): The dashscope workspace id.
103
+
104
+ Returns:
105
+ DashScopeAPIResponse: Delete result.
106
+ """
107
+ return super().delete(file_id, api_key, workspace=workspace, **kwargs)