dashscope 1.8.0__py3-none-any.whl → 1.25.6__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.
Files changed (110) hide show
  1. dashscope/__init__.py +61 -14
  2. dashscope/aigc/__init__.py +10 -3
  3. dashscope/aigc/chat_completion.py +282 -0
  4. dashscope/aigc/code_generation.py +145 -0
  5. dashscope/aigc/conversation.py +71 -12
  6. dashscope/aigc/generation.py +288 -16
  7. dashscope/aigc/image_synthesis.py +473 -31
  8. dashscope/aigc/multimodal_conversation.py +299 -14
  9. dashscope/aigc/video_synthesis.py +610 -0
  10. dashscope/api_entities/aiohttp_request.py +8 -5
  11. dashscope/api_entities/api_request_data.py +4 -2
  12. dashscope/api_entities/api_request_factory.py +68 -20
  13. dashscope/api_entities/base_request.py +20 -3
  14. dashscope/api_entities/chat_completion_types.py +344 -0
  15. dashscope/api_entities/dashscope_response.py +243 -15
  16. dashscope/api_entities/encryption.py +179 -0
  17. dashscope/api_entities/http_request.py +216 -62
  18. dashscope/api_entities/websocket_request.py +43 -34
  19. dashscope/app/__init__.py +5 -0
  20. dashscope/app/application.py +203 -0
  21. dashscope/app/application_response.py +246 -0
  22. dashscope/assistants/__init__.py +16 -0
  23. dashscope/assistants/assistant_types.py +175 -0
  24. dashscope/assistants/assistants.py +311 -0
  25. dashscope/assistants/files.py +197 -0
  26. dashscope/audio/__init__.py +4 -2
  27. dashscope/audio/asr/__init__.py +17 -1
  28. dashscope/audio/asr/asr_phrase_manager.py +203 -0
  29. dashscope/audio/asr/recognition.py +167 -27
  30. dashscope/audio/asr/transcription.py +107 -14
  31. dashscope/audio/asr/translation_recognizer.py +1006 -0
  32. dashscope/audio/asr/vocabulary.py +177 -0
  33. dashscope/audio/qwen_asr/__init__.py +7 -0
  34. dashscope/audio/qwen_asr/qwen_transcription.py +189 -0
  35. dashscope/audio/qwen_omni/__init__.py +11 -0
  36. dashscope/audio/qwen_omni/omni_realtime.py +524 -0
  37. dashscope/audio/qwen_tts/__init__.py +5 -0
  38. dashscope/audio/qwen_tts/speech_synthesizer.py +77 -0
  39. dashscope/audio/qwen_tts_realtime/__init__.py +10 -0
  40. dashscope/audio/qwen_tts_realtime/qwen_tts_realtime.py +355 -0
  41. dashscope/audio/tts/__init__.py +2 -0
  42. dashscope/audio/tts/speech_synthesizer.py +5 -0
  43. dashscope/audio/tts_v2/__init__.py +12 -0
  44. dashscope/audio/tts_v2/enrollment.py +179 -0
  45. dashscope/audio/tts_v2/speech_synthesizer.py +886 -0
  46. dashscope/cli.py +157 -37
  47. dashscope/client/base_api.py +652 -87
  48. dashscope/common/api_key.py +2 -0
  49. dashscope/common/base_type.py +135 -0
  50. dashscope/common/constants.py +13 -16
  51. dashscope/common/env.py +2 -0
  52. dashscope/common/error.py +58 -22
  53. dashscope/common/logging.py +2 -0
  54. dashscope/common/message_manager.py +2 -0
  55. dashscope/common/utils.py +276 -46
  56. dashscope/customize/__init__.py +0 -0
  57. dashscope/customize/customize_types.py +192 -0
  58. dashscope/customize/deployments.py +146 -0
  59. dashscope/customize/finetunes.py +234 -0
  60. dashscope/embeddings/__init__.py +5 -1
  61. dashscope/embeddings/batch_text_embedding.py +208 -0
  62. dashscope/embeddings/batch_text_embedding_response.py +65 -0
  63. dashscope/embeddings/multimodal_embedding.py +118 -10
  64. dashscope/embeddings/text_embedding.py +13 -1
  65. dashscope/{file.py → files.py} +19 -4
  66. dashscope/io/input_output.py +2 -0
  67. dashscope/model.py +11 -2
  68. dashscope/models.py +43 -0
  69. dashscope/multimodal/__init__.py +20 -0
  70. dashscope/multimodal/dialog_state.py +56 -0
  71. dashscope/multimodal/multimodal_constants.py +28 -0
  72. dashscope/multimodal/multimodal_dialog.py +648 -0
  73. dashscope/multimodal/multimodal_request_params.py +313 -0
  74. dashscope/multimodal/tingwu/__init__.py +10 -0
  75. dashscope/multimodal/tingwu/tingwu.py +80 -0
  76. dashscope/multimodal/tingwu/tingwu_realtime.py +579 -0
  77. dashscope/nlp/__init__.py +0 -0
  78. dashscope/nlp/understanding.py +64 -0
  79. dashscope/protocol/websocket.py +3 -0
  80. dashscope/rerank/__init__.py +0 -0
  81. dashscope/rerank/text_rerank.py +69 -0
  82. dashscope/resources/qwen.tiktoken +151643 -0
  83. dashscope/threads/__init__.py +26 -0
  84. dashscope/threads/messages/__init__.py +0 -0
  85. dashscope/threads/messages/files.py +113 -0
  86. dashscope/threads/messages/messages.py +220 -0
  87. dashscope/threads/runs/__init__.py +0 -0
  88. dashscope/threads/runs/runs.py +501 -0
  89. dashscope/threads/runs/steps.py +112 -0
  90. dashscope/threads/thread_types.py +665 -0
  91. dashscope/threads/threads.py +212 -0
  92. dashscope/tokenizers/__init__.py +7 -0
  93. dashscope/tokenizers/qwen_tokenizer.py +111 -0
  94. dashscope/tokenizers/tokenization.py +125 -0
  95. dashscope/tokenizers/tokenizer.py +45 -0
  96. dashscope/tokenizers/tokenizer_base.py +32 -0
  97. dashscope/utils/__init__.py +0 -0
  98. dashscope/utils/message_utils.py +838 -0
  99. dashscope/utils/oss_utils.py +243 -0
  100. dashscope/utils/param_utils.py +29 -0
  101. dashscope/version.py +3 -1
  102. {dashscope-1.8.0.dist-info → dashscope-1.25.6.dist-info}/METADATA +53 -50
  103. dashscope-1.25.6.dist-info/RECORD +112 -0
  104. {dashscope-1.8.0.dist-info → dashscope-1.25.6.dist-info}/WHEEL +1 -1
  105. {dashscope-1.8.0.dist-info → dashscope-1.25.6.dist-info}/entry_points.txt +0 -1
  106. {dashscope-1.8.0.dist-info → dashscope-1.25.6.dist-info/licenses}/LICENSE +2 -4
  107. dashscope/deployment.py +0 -129
  108. dashscope/finetune.py +0 -149
  109. dashscope-1.8.0.dist-info/RECORD +0 -49
  110. {dashscope-1.8.0.dist-info → dashscope-1.25.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,203 @@
1
+ # Copyright (c) Alibaba, Inc. and its affiliates.
2
+ """
3
+ @File : application.py
4
+ @Date : 2024-02-24
5
+ @Desc : Application calls for both http and http sse
6
+ """
7
+ import copy
8
+ from typing import Generator, List, Union
9
+
10
+ from dashscope.api_entities.api_request_factory import _build_api_request
11
+ from dashscope.api_entities.dashscope_response import Message, Role
12
+ from dashscope.app.application_response import ApplicationResponse
13
+ from dashscope.client.base_api import BaseApi
14
+ from dashscope.common.api_key import get_default_api_key
15
+ from dashscope.common.constants import (DEPRECATED_MESSAGE, HISTORY, MESSAGES,
16
+ PROMPT)
17
+ from dashscope.common.error import InputRequired, InvalidInput
18
+ from dashscope.common.logging import logger
19
+
20
+
21
+ class Application(BaseApi):
22
+ task_group = 'apps'
23
+ function = 'completion'
24
+ """API for app completion calls.
25
+
26
+ """
27
+ class DocReferenceType:
28
+ """ doc reference type for rag completion """
29
+
30
+ simple = 'simple'
31
+
32
+ indexed = 'indexed'
33
+
34
+ @classmethod
35
+ def _validate_params(cls, api_key, app_id):
36
+ if api_key is None:
37
+ api_key = get_default_api_key()
38
+
39
+ if app_id is None or not app_id:
40
+ raise InputRequired('App id is required!')
41
+
42
+ return api_key, app_id
43
+
44
+ @classmethod
45
+ def call(
46
+ cls,
47
+ app_id: str,
48
+ prompt: str = None,
49
+ history: list = None,
50
+ workspace: str = None,
51
+ api_key: str = None,
52
+ messages: List[Message] = None,
53
+ **kwargs
54
+ ) -> Union[ApplicationResponse, Generator[ApplicationResponse, None,
55
+ None]]:
56
+ """Call app completion service.
57
+
58
+ Args:
59
+ app_id (str): Id of bailian application
60
+ prompt (str): The input prompt.
61
+ history (list):The user provided history
62
+ examples:
63
+ [{'user':'The weather is fine today.',
64
+ 'bot': 'Suitable for outings'}].
65
+ Defaults to None.
66
+ workspace(str, `optional`): Workspace for app completion call
67
+ api_key (str, optional): The api api_key, can be None,
68
+ if None, will get by default rule(TODO: api key doc).
69
+ messages(list): The generation messages.
70
+
71
+ **kwargs:
72
+ stream(bool, `optional`): Enable server-sent events
73
+ (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501
74
+ the result will back partially[qwen-turbo,bailian-v1].
75
+ temperature(float, `optional`): Used to control the degree
76
+ of randomness and diversity. Specifically, the temperature
77
+ value controls the degree to which the probability distribution
78
+ of each candidate word is smoothed when generating text.
79
+ A higher temperature value will reduce the peak value of
80
+ the probability, allowing more low-probability words to be
81
+ selected, and the generated results will be more diverse;
82
+ while a lower temperature value will enhance the peak value
83
+ of the probability, making it easier for high-probability
84
+ words to be selected, the generated results are more
85
+ deterministic, range(0, 2) .[qwen-turbo,qwen-plus].
86
+ top_p(float, `optional`): A sampling strategy, called nucleus
87
+ sampling, where the model considers the results of the
88
+ tokens with top_p probability mass. So 0.1 means only
89
+ the tokens comprising the top 10% probability mass are
90
+ considered[qwen-turbo,bailian-v1].
91
+ top_k(int, `optional`): The size of the sample candidate set when generated. # noqa E501
92
+ For example, when the value is 50, only the 50 highest-scoring tokens # noqa E501
93
+ in a single generation form a randomly sampled candidate set. # noqa E501
94
+ The larger the value, the higher the randomness generated; # noqa E501
95
+ the smaller the value, the higher the certainty generated. # noqa E501
96
+ The default value is 0, which means the top_k policy is # noqa E501
97
+ not enabled. At this time, only the top_p policy takes effect. # noqa E501
98
+ seed(int, `optional`): When generating, the seed of the random number is used to control the
99
+ randomness of the model generation. If you use the same seed, each run will generate the same results;
100
+ you can use the same seed when you need to reproduce the model's generated results.
101
+ The seed parameter supports unsigned 64-bit integer types. Default value 1234
102
+ session_id(str, `optional`): Session if for multiple rounds call.
103
+ biz_params(dict, `optional`): The extra parameters for flow or plugin.
104
+ has_thoughts(bool, `optional`): Flag to return rag or plugin process details. Default value false.
105
+ doc_tag_codes(list[str], `optional`): Tag code list for doc retrival.
106
+ doc_reference_type(str, `optional`): The type of doc reference.
107
+ simple: simple format of doc retrival which not include index in response text but in doc reference list.
108
+ indexed: include both index in response text and doc reference list
109
+ memory_id(str, `optional`): Used to store long term context summary between end users and assistant.
110
+ image_list(list, `optional`): Used to pass image url list.
111
+ rag_options(dict, `optional`): Rag options for retrieval augmented generation options.
112
+ Raises:
113
+ InvalidInput: The history and auto_history are mutually exclusive.
114
+
115
+ Returns:
116
+ Union[CompletionResponse,
117
+ Generator[CompletionResponse, None, None]]: If
118
+ stream is True, return Generator, otherwise GenerationResponse.
119
+ """
120
+
121
+ api_key, app_id = Application._validate_params(api_key, app_id)
122
+
123
+ if (prompt is None or not prompt) and (messages is None
124
+ or len(messages) == 0):
125
+ raise InputRequired('prompt or messages is required!')
126
+
127
+ if workspace is not None and workspace:
128
+ headers = kwargs.pop('headers', {})
129
+ headers['X-DashScope-WorkSpace'] = workspace
130
+ kwargs['headers'] = headers
131
+
132
+ input, parameters = cls._build_input_parameters(
133
+ prompt, history, messages, **kwargs)
134
+ request = _build_api_request(model='',
135
+ input=input,
136
+ task_group=Application.task_group,
137
+ task=app_id,
138
+ function=Application.function,
139
+ workspace=workspace,
140
+ api_key=api_key,
141
+ is_service=False,
142
+ **parameters)
143
+ # call request service.
144
+ response = request.call()
145
+ is_stream = kwargs.get('stream', False)
146
+
147
+ if is_stream:
148
+ return (ApplicationResponse.from_api_response(rsp)
149
+ for rsp in response)
150
+ else:
151
+ return ApplicationResponse.from_api_response(response)
152
+
153
+ @classmethod
154
+ def _build_input_parameters(cls, prompt, history, messages, **kwargs):
155
+ parameters = {}
156
+
157
+ input_param = {}
158
+ if messages is not None:
159
+ msgs = copy.deepcopy(messages)
160
+ if prompt is not None and prompt:
161
+ msgs.append({'role': Role.USER, 'content': prompt})
162
+ input_param = {MESSAGES: msgs}
163
+ elif history is not None and history:
164
+ logger.warning(DEPRECATED_MESSAGE)
165
+ input_param[HISTORY] = history
166
+ if prompt is not None and prompt:
167
+ input_param[PROMPT] = prompt
168
+ else:
169
+ input_param[PROMPT] = prompt
170
+
171
+ session_id = kwargs.pop('session_id', None)
172
+ if session_id is not None and session_id:
173
+ input_param['session_id'] = session_id
174
+
175
+ doc_reference_type = kwargs.pop('doc_reference_type', None)
176
+ if doc_reference_type is not None and doc_reference_type:
177
+ input_param['doc_reference_type'] = doc_reference_type
178
+
179
+ doc_tag_codes = kwargs.pop('doc_tag_codes', None)
180
+ if doc_tag_codes is not None:
181
+ if isinstance(doc_tag_codes, list) and all(
182
+ isinstance(item, str) for item in doc_tag_codes):
183
+ input_param['doc_tag_codes'] = doc_tag_codes
184
+ else:
185
+ raise InvalidInput('doc_tag_codes is not a List[str]')
186
+
187
+ memory_id = kwargs.pop('memory_id', None)
188
+ if memory_id is not None:
189
+ input_param['memory_id'] = memory_id
190
+
191
+ biz_params = kwargs.pop('biz_params', None)
192
+ if biz_params is not None and biz_params:
193
+ input_param['biz_params'] = biz_params
194
+
195
+ image_list = kwargs.pop('image_list', None)
196
+ if image_list is not None and image_list:
197
+ input_param['image_list'] = image_list
198
+
199
+ file_list = kwargs.pop('file_list', None)
200
+ if file_list is not None and file_list:
201
+ input_param['file_list'] = file_list
202
+
203
+ return input_param, {**parameters, **kwargs}
@@ -0,0 +1,246 @@
1
+ # Copyright (c) Alibaba, Inc. and its affiliates.
2
+ """
3
+ @File : application_response.py
4
+ @Date : 2024-02-24
5
+ @Desc : application call response
6
+ """
7
+ from dataclasses import dataclass
8
+ from http import HTTPStatus
9
+ from typing import Dict, List, Optional
10
+
11
+ from dashscope.api_entities.dashscope_response import (DashScopeAPIResponse,
12
+ DictMixin)
13
+
14
+
15
+ @dataclass(init=False)
16
+ class ApplicationThought(DictMixin):
17
+ thought: str
18
+ action_type: str
19
+ response: str
20
+ action_name: str
21
+ action: str
22
+ action_input_stream: str
23
+ action_input: Dict
24
+ observation: str
25
+
26
+ def __init__(self,
27
+ thought: str = None,
28
+ action_type: str = None,
29
+ response: str = None,
30
+ action_name: str = None,
31
+ action: str = None,
32
+ action_input_stream: str = None,
33
+ action_input: Dict = None,
34
+ observation: str = None,
35
+ **kwargs):
36
+ """ Thought of app completion call result which describe model planning and doc retrieval
37
+ or plugin calls details.
38
+
39
+ Args:
40
+ thought (str, optional): Model's inference thought for doc retrieval or plugin process.
41
+ action_type (str, optional): Action type. response : final response; api: to run api calls.
42
+ response (str, optional): Model's results.
43
+ action_name (str, optional): Action name, e.g. searchDocument、api.
44
+ action (str, optional): Code of action, means which plugin or action to be run.
45
+ action_input_stream (str, optional): Input param with stream.
46
+ action_input (dict, optional): Api or plugin input parameters.
47
+ observation (str, optional): Result of api call or doc retrieval.
48
+ """
49
+
50
+ super().__init__(thought=thought,
51
+ action_type=action_type,
52
+ response=response,
53
+ action_name=action_name,
54
+ action=action,
55
+ action_input_stream=action_input_stream,
56
+ action_input=action_input,
57
+ observation=observation,
58
+ **kwargs)
59
+
60
+
61
+ @dataclass(init=False)
62
+ class ApplicationDocReference(DictMixin):
63
+ index_id: str
64
+ title: str
65
+ doc_id: str
66
+ doc_name: str
67
+ doc_url: str
68
+ text: str
69
+ biz_id: str
70
+ images: List[str]
71
+ page_number: List[int]
72
+
73
+ def __init__(self,
74
+ index_id: str = None,
75
+ title: str = None,
76
+ doc_id: str = None,
77
+ doc_name: str = None,
78
+ doc_url: str = None,
79
+ text: str = None,
80
+ biz_id: str = None,
81
+ images: List[str] = None,
82
+ page_number: List[int] = None,
83
+ **kwargs):
84
+ """ Doc references for retrieval result.
85
+
86
+ Args:
87
+ index_id (str, optional): Index id of doc retrival result reference.
88
+ title (str, optional): Title of original doc that retrieved.
89
+ doc_id (str, optional): Id of original doc that retrieved.
90
+ doc_name (str, optional): Name of original doc that retrieved.
91
+ doc_url (str, optional): Url of original doc that retrieved.
92
+ text (str, optional): Text in original doc that retrieved.
93
+ biz_id (str, optional): Biz id that caller is able to associated for biz logic.
94
+ images (list, optional): List of referenced image URLs
95
+ """
96
+
97
+ super().__init__(index_id=index_id,
98
+ title=title,
99
+ doc_id=doc_id,
100
+ doc_name=doc_name,
101
+ doc_url=doc_url,
102
+ text=text,
103
+ biz_id=biz_id,
104
+ images=images,
105
+ page_number=page_number,
106
+ **kwargs)
107
+
108
+ @dataclass(init=False)
109
+ class WorkflowMessage(DictMixin):
110
+ node_id: str
111
+ node_name: str
112
+ node_type: str
113
+ node_status: str
114
+ node_is_completed: str
115
+ node_msg_seq_id: int
116
+ message: str
117
+
118
+ class Message(DictMixin):
119
+ role: str
120
+ content: str
121
+
122
+ def __init__(self,
123
+ node_id: str = None,
124
+ node_name: str = None,
125
+ node_type: str = None,
126
+ node_status: str = None,
127
+ node_is_completed: str = None,
128
+ node_msg_seq_id: int = None,
129
+ message: Message = None,
130
+ **kwargs):
131
+ """ Workflow message.
132
+
133
+ Args:
134
+ node_id (str, optional): .
135
+ node_name (str, optional): .
136
+ node_type (str, optional): .
137
+ node_status (str, optional): .
138
+ node_is_completed (str, optional): .
139
+ node_msg_seq_id (int, optional): .
140
+ message (Message, optional): .
141
+ """
142
+
143
+ super().__init__(node_id=node_id,
144
+ node_name=node_name,
145
+ node_type=node_type,
146
+ node_status=node_status,
147
+ node_is_completed=node_is_completed,
148
+ node_msg_seq_id=node_msg_seq_id,
149
+ message=message,
150
+ **kwargs)
151
+
152
+
153
+ @dataclass(init=False)
154
+ class ApplicationOutput(DictMixin):
155
+ text: str
156
+ finish_reason: str
157
+ session_id: str
158
+ thoughts: List[ApplicationThought]
159
+ doc_references: List[ApplicationDocReference]
160
+ workflow_message: WorkflowMessage
161
+
162
+ def __init__(self,
163
+ text: str = None,
164
+ finish_reason: str = None,
165
+ session_id: str = None,
166
+ thoughts: List[ApplicationThought] = None,
167
+ doc_references: List[ApplicationDocReference] = None,
168
+ workflow_message: WorkflowMessage = None,
169
+ **kwargs):
170
+
171
+ ths = None
172
+ if thoughts is not None:
173
+ ths = []
174
+ for thought in thoughts:
175
+ ths.append(ApplicationThought(**thought))
176
+
177
+ refs = None
178
+ if doc_references is not None:
179
+ refs = []
180
+ for ref in doc_references:
181
+ refs.append(ApplicationDocReference(**ref))
182
+
183
+ super().__init__(text=text,
184
+ finish_reason=finish_reason,
185
+ session_id=session_id,
186
+ thoughts=ths,
187
+ doc_references=refs,
188
+ workflow_message=workflow_message,
189
+ **kwargs)
190
+
191
+
192
+ @dataclass(init=False)
193
+ class ApplicationModelUsage(DictMixin):
194
+ model_id: str
195
+ input_tokens: int
196
+ output_tokens: int
197
+
198
+ def __init__(self,
199
+ model_id: str = None,
200
+ input_tokens: int = 0,
201
+ output_tokens: int = 0,
202
+ **kwargs):
203
+ super().__init__(model_id=model_id,
204
+ input_tokens=input_tokens,
205
+ output_tokens=output_tokens,
206
+ **kwargs)
207
+
208
+
209
+ @dataclass(init=False)
210
+ class ApplicationUsage(DictMixin):
211
+ models: List[ApplicationModelUsage]
212
+
213
+ def __init__(self, models: List[ApplicationModelUsage] = None, **kwargs):
214
+ model_usages = None
215
+ if models is not None:
216
+ model_usages = []
217
+ for model_usage in models:
218
+ model_usages.append(ApplicationModelUsage(**model_usage))
219
+
220
+ super().__init__(models=model_usages, **kwargs)
221
+
222
+
223
+ @dataclass(init=False)
224
+ class ApplicationResponse(DashScopeAPIResponse):
225
+ output: ApplicationOutput
226
+ usage: ApplicationUsage
227
+
228
+ @staticmethod
229
+ def from_api_response(api_response: DashScopeAPIResponse):
230
+ if api_response.status_code == HTTPStatus.OK:
231
+ usage = {}
232
+ if api_response.usage:
233
+ usage = api_response.usage
234
+
235
+ return ApplicationResponse(
236
+ status_code=api_response.status_code,
237
+ request_id=api_response.request_id,
238
+ code=api_response.code,
239
+ message=api_response.message,
240
+ output=ApplicationOutput(**api_response.output),
241
+ usage=ApplicationUsage(**usage))
242
+ else:
243
+ return ApplicationResponse(status_code=api_response.status_code,
244
+ request_id=api_response.request_id,
245
+ code=api_response.code,
246
+ message=api_response.message)
@@ -0,0 +1,16 @@
1
+ # Copyright (c) Alibaba, Inc. and its affiliates.
2
+
3
+ # yapf: disable
4
+
5
+ from dashscope.assistants.assistant_types import (Assistant, AssistantFile,
6
+ AssistantList,
7
+ DeleteResponse)
8
+ from dashscope.assistants.assistants import Assistants
9
+
10
+ __all__ = [
11
+ Assistant,
12
+ Assistants,
13
+ AssistantList,
14
+ AssistantFile,
15
+ DeleteResponse,
16
+ ]
@@ -0,0 +1,175 @@
1
+ # Copyright (c) Alibaba, Inc. and its affiliates.
2
+
3
+ # adapter from openai sdk
4
+ from dataclasses import dataclass
5
+ from typing import Dict, List, Optional, Union
6
+
7
+ from dashscope.common.base_type import BaseList, BaseObjectMixin
8
+
9
+ __all__ = [
10
+ 'Assistant', 'AssistantFile', 'ToolCodeInterpreter', 'ToolSearch',
11
+ 'ToolWanX', 'FunctionDefinition', 'ToolFunction', 'AssistantFileList',
12
+ 'AssistantList', 'DeleteResponse'
13
+ ]
14
+
15
+
16
+ @dataclass(init=False)
17
+ class AssistantFile(BaseObjectMixin):
18
+ id: str
19
+ assistant_id: str
20
+ created_at: int
21
+ object: str
22
+
23
+ def __init__(self, **kwargs):
24
+ super().__init__(**kwargs)
25
+
26
+
27
+ @dataclass(init=False)
28
+ class ToolCodeInterpreter(BaseObjectMixin):
29
+ type: str = 'code_interpreter'
30
+
31
+ def __init__(self, **kwargs):
32
+ super().__init__(**kwargs)
33
+
34
+
35
+ @dataclass(init=False)
36
+ class ToolSearch(BaseObjectMixin):
37
+ type: str = 'search'
38
+
39
+ def __init__(self, **kwargs):
40
+ super().__init__(**kwargs)
41
+
42
+
43
+ @dataclass(init=False)
44
+ class ToolWanX(BaseObjectMixin):
45
+ type: str = 'wanx'
46
+
47
+ def __init__(self, **kwargs):
48
+ super().__init__(**kwargs)
49
+
50
+
51
+ @dataclass(init=False)
52
+ class FunctionDefinition(BaseObjectMixin):
53
+ name: str
54
+ description: Optional[str] = None
55
+ parameters: Optional[Dict[str, object]] = None
56
+
57
+ def __init__(self, **kwargs):
58
+ super().__init__(**kwargs)
59
+
60
+
61
+ @dataclass(init=False)
62
+ class ToolFunction(BaseObjectMixin):
63
+ function: FunctionDefinition
64
+ type: str = 'function'
65
+
66
+ def __init__(self, **kwargs):
67
+ self.function = FunctionDefinition(**kwargs.pop('function', {}))
68
+ super().__init__(**kwargs)
69
+
70
+
71
+ Tool = Union[ToolCodeInterpreter, ToolSearch, ToolFunction, ToolWanX]
72
+ ASSISTANT_SUPPORT_TOOL = {
73
+ 'code_interpreter': ToolCodeInterpreter,
74
+ 'search': ToolSearch,
75
+ 'wanx': ToolWanX,
76
+ 'function': ToolFunction
77
+ }
78
+
79
+
80
+ def convert_tools_dict_to_objects(tools):
81
+ tools_object = []
82
+ for tool in tools:
83
+ if 'type' in tool:
84
+ tool_type = ASSISTANT_SUPPORT_TOOL.get(tool['type'], None)
85
+ if tool_type:
86
+ tools_object.append(tool_type(**tool))
87
+ else:
88
+ tools_object.append(tool)
89
+ else:
90
+ tools_object.append(tool)
91
+ return tools_object
92
+
93
+
94
+ @dataclass(init=False)
95
+ class Assistant(BaseObjectMixin):
96
+ status_code: int
97
+ """The call response status_code, 200 indicate create success.
98
+ """
99
+ code: str
100
+ """The request failed, this is the error code.
101
+ """
102
+ message: str
103
+ """The request failed, this is the error message.
104
+ """
105
+ id: str
106
+ """ID of the assistant.
107
+ """
108
+ model: str
109
+ name: Optional[str] = None
110
+ created_at: int
111
+ """The Unix timestamp (in seconds) for when the assistant was created.
112
+ """
113
+ description: Optional[str] = None
114
+
115
+ file_ids: List[str]
116
+
117
+ instructions: Optional[str] = None
118
+ metadata: Optional[object] = None
119
+ tools: List[Tool]
120
+
121
+ object: Optional[str] = None
122
+
123
+ top_p: Optional[float] = None
124
+ top_k: Optional[int] = None
125
+ temperature: Optional[float] = None
126
+ max_tokens: Optional[int] = None
127
+
128
+ request_id: Optional[str] = None
129
+
130
+ def __init__(self, **kwargs):
131
+ self.tools = convert_tools_dict_to_objects(kwargs.pop('tools', []))
132
+ super().__init__(**kwargs)
133
+
134
+
135
+ @dataclass(init=False)
136
+ class AssistantList(BaseList):
137
+ data: List[Assistant]
138
+
139
+ def __init__(self,
140
+ has_more: bool = None,
141
+ last_id: Optional[str] = None,
142
+ first_id: Optional[str] = None,
143
+ data: List[Assistant] = [],
144
+ **kwargs):
145
+ super().__init__(has_more=has_more,
146
+ last_id=last_id,
147
+ first_id=first_id,
148
+ data=data,
149
+ **kwargs)
150
+
151
+
152
+ @dataclass(init=False)
153
+ class AssistantFileList(BaseList):
154
+ data: List[AssistantFile]
155
+
156
+ def __init__(self,
157
+ has_more: bool = None,
158
+ last_id: Optional[str] = None,
159
+ first_id: Optional[str] = None,
160
+ data: List[AssistantFile] = [],
161
+ **kwargs):
162
+ super().__init__(has_more=has_more,
163
+ last_id=last_id,
164
+ first_id=first_id,
165
+ data=data,
166
+ **kwargs)
167
+
168
+
169
+ @dataclass(init=False)
170
+ class DeleteResponse(BaseObjectMixin):
171
+ id: str
172
+ deleted: bool
173
+
174
+ def __init__(self, **kwargs):
175
+ super().__init__(**kwargs)