dashscope 1.16.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 (53) hide show
  1. dashscope/__init__.py +25 -3
  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/http_request.py +18 -9
  10. dashscope/api_entities/websocket_request.py +3 -0
  11. dashscope/app/application.py +16 -23
  12. dashscope/assistants/__init__.py +14 -0
  13. dashscope/assistants/assistant_types.py +164 -0
  14. dashscope/assistants/assistants.py +280 -0
  15. dashscope/assistants/files.py +189 -0
  16. dashscope/audio/asr/asr_phrase_manager.py +27 -5
  17. dashscope/audio/asr/recognition.py +10 -2
  18. dashscope/audio/asr/transcription.py +21 -3
  19. dashscope/audio/tts/speech_synthesizer.py +3 -0
  20. dashscope/cli.py +7 -7
  21. dashscope/client/base_api.py +303 -68
  22. dashscope/common/base_type.py +130 -0
  23. dashscope/common/constants.py +1 -0
  24. dashscope/common/error.py +4 -0
  25. dashscope/common/utils.py +22 -6
  26. dashscope/deployment.py +40 -6
  27. dashscope/embeddings/batch_text_embedding.py +24 -7
  28. dashscope/embeddings/multimodal_embedding.py +3 -0
  29. dashscope/embeddings/text_embedding.py +8 -1
  30. dashscope/files.py +107 -0
  31. dashscope/finetune.py +31 -7
  32. dashscope/model.py +9 -2
  33. dashscope/models.py +47 -0
  34. dashscope/nlp/understanding.py +2 -2
  35. dashscope/threads/__init__.py +24 -0
  36. dashscope/threads/messages/__init__.py +0 -0
  37. dashscope/threads/messages/files.py +111 -0
  38. dashscope/threads/messages/messages.py +218 -0
  39. dashscope/threads/runs/__init__.py +0 -0
  40. dashscope/threads/runs/runs.py +408 -0
  41. dashscope/threads/runs/steps.py +110 -0
  42. dashscope/threads/thread_types.py +571 -0
  43. dashscope/threads/threads.py +210 -0
  44. dashscope/tokenizers/tokenization.py +3 -0
  45. dashscope/utils/oss_utils.py +11 -0
  46. dashscope/version.py +1 -1
  47. {dashscope-1.16.0.dist-info → dashscope-1.17.0.dist-info}/METADATA +2 -3
  48. dashscope-1.17.0.dist-info/RECORD +84 -0
  49. dashscope-1.16.0.dist-info/RECORD +0 -68
  50. {dashscope-1.16.0.dist-info → dashscope-1.17.0.dist-info}/LICENSE +0 -0
  51. {dashscope-1.16.0.dist-info → dashscope-1.17.0.dist-info}/WHEEL +0 -0
  52. {dashscope-1.16.0.dist-info → dashscope-1.17.0.dist-info}/entry_points.txt +0 -0
  53. {dashscope-1.16.0.dist-info → dashscope-1.17.0.dist-info}/top_level.txt +0 -0
dashscope/__init__.py CHANGED
@@ -1,12 +1,14 @@
1
1
  import logging
2
2
  from logging import NullHandler
3
3
 
4
+ from dashscope.app.application import Application
4
5
  from dashscope.aigc.code_generation import CodeGeneration
5
6
  from dashscope.aigc.conversation import Conversation, History, HistoryItem
6
7
  from dashscope.aigc.generation import Generation
7
8
  from dashscope.aigc.image_synthesis import ImageSynthesis
8
9
  from dashscope.aigc.multimodal_conversation import MultiModalConversation
9
- from dashscope.app.application import Application
10
+ from dashscope.assistants import Assistant, AssistantList, Assistants
11
+ from dashscope.assistants.assistant_types import AssistantFile, DeleteResponse
10
12
  from dashscope.audio.asr.transcription import Transcription
11
13
  from dashscope.audio.tts.speech_synthesizer import SpeechSynthesizer
12
14
  from dashscope.common.api_key import save_api_key
@@ -20,11 +22,14 @@ from dashscope.embeddings.multimodal_embedding import (
20
22
  MultiModalEmbedding, MultiModalEmbeddingItemAudio,
21
23
  MultiModalEmbeddingItemImage, MultiModalEmbeddingItemText)
22
24
  from dashscope.embeddings.text_embedding import TextEmbedding
23
- from dashscope.file import File
25
+ from dashscope.files import Files
24
26
  from dashscope.finetune import FineTune
25
27
  from dashscope.model import Model
26
28
  from dashscope.nlp.understanding import Understanding
27
29
  from dashscope.rerank.text_rerank import TextReRank
30
+ from dashscope.threads import (MessageFile, Messages, Run, RunList, Runs,
31
+ RunStep, RunStepList, Steps, Thread,
32
+ ThreadMessage, ThreadMessageList, Threads)
28
33
  from dashscope.tokenizers import (Tokenization, Tokenizer, get_tokenizer,
29
34
  list_tokenizers)
30
35
 
@@ -40,7 +45,7 @@ __all__ = [
40
45
  HistoryItem,
41
46
  ImageSynthesis,
42
47
  Transcription,
43
- File,
48
+ Files,
44
49
  Deployment,
45
50
  FineTune,
46
51
  Model,
@@ -61,6 +66,23 @@ __all__ = [
61
66
  list_tokenizers,
62
67
  Application,
63
68
  TextReRank,
69
+ Assistants,
70
+ Threads,
71
+ Messages,
72
+ Runs,
73
+ Assistant,
74
+ ThreadMessage,
75
+ Run,
76
+ Steps,
77
+ AssistantList,
78
+ ThreadMessageList,
79
+ RunList,
80
+ RunStepList,
81
+ Thread,
82
+ DeleteResponse,
83
+ RunStep,
84
+ MessageFile,
85
+ AssistantFile,
64
86
  ]
65
87
 
66
88
  logging.getLogger(__name__).addHandler(NullHandler())
@@ -68,6 +68,7 @@ class CodeGeneration(BaseApi):
68
68
  scene: str = None,
69
69
  api_key: str = None,
70
70
  message: List[MessageParam] = None,
71
+ workspace: str = None,
71
72
  **kwargs
72
73
  ) -> Union[DashScopeAPIResponse, Generator[DashScopeAPIResponse, None,
73
74
  None]]:
@@ -89,23 +90,24 @@ class CodeGeneration(BaseApi):
89
90
  if None, will get by default rule(TODO: api key doc).
90
91
  message (list): The generation messages.
91
92
  scene == custom, examples:
92
- [{"role": "user", "content": "根据下面的功能描述生成一个python函数。代码的功能是计算给定路径下所有文件的总大小。"}]
93
+ [{"role": "user", "content": "根据下面的功能描述生成一个python函数。代码的功能是计算给定路径下所有文件的总大小。"}] # noqa E501
93
94
  scene == nl2code, examples:
94
- [{"role": "user", "content": "计算给定路径下所有文件的总大小"}, {"role": "attachment", "meta": {"language": "java"}}]
95
+ [{"role": "user", "content": "计算给定路径下所有文件的总大小"}, {"role": "attachment", "meta": {"language": "java"}}] # noqa E501
95
96
  scene == code2comment, examples:
96
- [{"role": "user", "content": "1. 生成中文注释\n2. 仅生成代码部分,不需要额外解释函数功能\n"}, {"role": "attachment", "meta": {"code": "\t\t@Override\n\t\tpublic CancelExportTaskResponse cancelExportTask(\n\t\t\t\tCancelExportTask cancelExportTask) {\n\t\t\tAmazonEC2SkeletonInterface ec2Service = ServiceProvider.getInstance().getServiceImpl(AmazonEC2SkeletonInterface.class);\n\t\t\treturn ec2Service.cancelExportTask(cancelExportTask);\n\t\t}", "language": "java"}}]
97
+ [{"role": "user", "content": "1. 生成中文注释\n2. 仅生成代码部分,不需要额外解释函数功能\n"}, {"role": "attachment", "meta": {"code": "\t\t@Override\n\t\tpublic CancelExportTaskResponse cancelExportTask(\n\t\t\t\tCancelExportTask cancelExportTask) {\n\t\t\tAmazonEC2SkeletonInterface ec2Service = ServiceProvider.getInstance().getServiceImpl(AmazonEC2SkeletonInterface.class);\n\t\t\treturn ec2Service.cancelExportTask(cancelExportTask);\n\t\t}", "language": "java"}}] # noqa E501
97
98
  scene == code2explain, examples:
98
- [{"role": "user", "content": "要求不低于200字"}, {"role": "attachment", "meta": {"code": "@Override\n public int getHeaderCacheSize()\n {\n return 0;\n }\n\n", "language": "java"}}]
99
+ [{"role": "user", "content": "要求不低于200字"}, {"role": "attachment", "meta": {"code": "@Override\n public int getHeaderCacheSize()\n {\n return 0;\n }\n\n", "language": "java"}}] # noqa E501
99
100
  scene == commit2msg, examples:
100
- [{"role": "attachment", "meta": {"diff_list": [{"diff": "--- src/com/siondream/core/PlatformResolver.java\n+++ src/com/siondream/core/PlatformResolver.java\n@@ -1,11 +1,8 @@\npackage com.siondream.core;\n-\n-import com.badlogic.gdx.files.FileHandle;\n\npublic interface PlatformResolver {\npublic void openURL(String url);\npublic void rateApp();\npublic void sendFeedback();\n-\tpublic FileHandle[] listFolder(String path);\n}\n", "old_file_path": "src/com/siondream/core/PlatformResolver.java", "new_file_path": "src/com/siondream/core/PlatformResolver.java"}]}}]
101
+ [{"role": "attachment", "meta": {"diff_list": [{"diff": "--- src/com/siondream/core/PlatformResolver.java\n+++ src/com/siondream/core/PlatformResolver.java\n@@ -1,11 +1,8 @@\npackage com.siondream.core;\n-\n-import com.badlogic.gdx.files.FileHandle;\n\npublic interface PlatformResolver {\npublic void openURL(String url);\npublic void rateApp();\npublic void sendFeedback();\n-\tpublic FileHandle[] listFolder(String path);\n}\n", "old_file_path": "src/com/siondream/core/PlatformResolver.java", "new_file_path": "src/com/siondream/core/PlatformResolver.java"}]}}] # noqa E501
101
102
  scene == unittest, examples:
102
- [{"role": "attachment", "meta": {"code": "public static <T> TimestampMap<T> parseTimestampMap(Class<T> typeClass, String input, DateTimeZone timeZone) throws IllegalArgumentException {\n if (typeClass == null) {\n throw new IllegalArgumentException(\"typeClass required\");\n }\n\n if (input == null) {\n return null;\n }\n\n TimestampMap result;\n\n typeClass = AttributeUtils.getStandardizedType(typeClass);\n if (typeClass.equals(String.class)) {\n result = new TimestampStringMap();\n } else if (typeClass.equals(Byte.class)) {\n result = new TimestampByteMap();\n } else if (typeClass.equals(Short.class)) {\n result = new TimestampShortMap();\n } else if (typeClass.equals(Integer.class)) {\n result = new TimestampIntegerMap();\n } else if (typeClass.equals(Long.class)) {\n result = new TimestampLongMap();\n } else if (typeClass.equals(Float.class)) {\n result = new TimestampFloatMap();\n } else if (typeClass.equals(Double.class)) {\n result = new TimestampDoubleMap();\n } else if (typeClass.equals(Boolean.class)) {\n result = new TimestampBooleanMap();\n } else if (typeClass.equals(Character.class)) {\n result = new TimestampCharMap();\n } else {\n throw new IllegalArgumentException(\"Unsupported type \" + typeClass.getClass().getCanonicalName());\n }\n\n if (input.equalsIgnoreCase(EMPTY_VALUE)) {\n return result;\n }\n\n StringReader reader = new StringReader(input + ' ');// Add 1 space so\n // reader.skip\n // function always\n // works when\n // necessary (end of\n // string not\n // reached).\n\n try {\n int r;\n char c;\n while ((r = reader.read()) != -1) {\n c = (char) r;\n switch (c) {\n case LEFT_BOUND_SQUARE_BRACKET:\n case LEFT_BOUND_BRACKET:\n parseTimestampAndValue(typeClass, reader, result, timeZone);\n break;\n default:\n // Ignore other chars outside of bounds\n }\n }\n } catch (IOException ex) {\n throw new RuntimeException(\"Unexpected expection while parsing timestamps\", ex);\n }\n\n return result;\n }", "language": "java"}}]
103
+ [{"role": "attachment", "meta": {"code": "public static <T> TimestampMap<T> parseTimestampMap(Class<T> typeClass, String input, DateTimeZone timeZone) throws IllegalArgumentException {\n if (typeClass == null) {\n throw new IllegalArgumentException(\"typeClass required\");\n }\n\n if (input == null) {\n return null;\n }\n\n TimestampMap result;\n\n typeClass = AttributeUtils.getStandardizedType(typeClass);\n if (typeClass.equals(String.class)) {\n result = new TimestampStringMap();\n } else if (typeClass.equals(Byte.class)) {\n result = new TimestampByteMap();\n } else if (typeClass.equals(Short.class)) {\n result = new TimestampShortMap();\n } else if (typeClass.equals(Integer.class)) {\n result = new TimestampIntegerMap();\n } else if (typeClass.equals(Long.class)) {\n result = new TimestampLongMap();\n } else if (typeClass.equals(Float.class)) {\n result = new TimestampFloatMap();\n } else if (typeClass.equals(Double.class)) {\n result = new TimestampDoubleMap();\n } else if (typeClass.equals(Boolean.class)) {\n result = new TimestampBooleanMap();\n } else if (typeClass.equals(Character.class)) {\n result = new TimestampCharMap();\n } else {\n throw new IllegalArgumentException(\"Unsupported type \" + typeClass.getClass().getCanonicalName());\n }\n\n if (input.equalsIgnoreCase(EMPTY_VALUE)) {\n return result;\n }\n\n StringReader reader = new StringReader(input + ' ');// Add 1 space so\n // reader.skip\n // function always\n // works when\n // necessary (end of\n // string not\n // reached).\n\n try {\n int r;\n char c;\n while ((r = reader.read()) != -1) {\n c = (char) r;\n switch (c) {\n case LEFT_BOUND_SQUARE_BRACKET:\n case LEFT_BOUND_BRACKET:\n parseTimestampAndValue(typeClass, reader, result, timeZone);\n break;\n default:\n // Ignore other chars outside of bounds\n }\n }\n } catch (IOException ex) {\n throw new RuntimeException(\"Unexpected expection while parsing timestamps\", ex);\n }\n\n return result;\n }", "language": "java"}}] # noqa E501
103
104
  scene == codeqa, examples:
104
- [{"role": "user", "content": "I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?\nWhat I'm doing now:\nclass MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n def doGET\n [...]\n\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer): \n pass\n\nserver = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)\nserver.serve_forever()"}]
105
+ [{"role": "user", "content": "I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?\nWhat I'm doing now:\nclass MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n def doGET\n [...]\n\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer): \n pass\n\nserver = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)\nserver.serve_forever()"}] # noqa E501
105
106
  scene == nl2sql, examples:
106
- [{"role": "user", "content": "小明的总分数是多少"}, {"role": "attachment", "meta": {"synonym_infos": {"学生姓名": "姓名|名字|名称", "学生分数": "分数|得分"}, "recall_infos": [{"content": "student_score.id='小明'", "score": "0.83"}], "schema_infos": [{"table_id": "student_score", "table_desc": "学生分数表", "columns": [{"col_name": "id", "col_caption": "学生id", "col_desc": "例值为:1,2,3", "col_type": "string"}, {"col_name": "name", "col_caption": "学生姓名", "col_desc": "例值为:张三,李四,小明", "col_type": "string"}, {"col_name": "score", "col_caption": "学生分数", "col_desc": "例值为:98,100,66", "col_type": "string"}]}]}}]
107
+ [{"role": "user", "content": "小明的总分数是多少"}, {"role": "attachment", "meta": {"synonym_infos": {"学生姓名": "姓名|名字|名称", "学生分数": "分数|得分"}, "recall_infos": [{"content": "student_score.id='小明'", "score": "0.83"}], "schema_infos": [{"table_id": "student_score", "table_desc": "学生分数表", "columns": [{"col_name": "id", "col_caption": "学生id", "col_desc": "例值为:1,2,3", "col_type": "string"}, {"col_name": "name", "col_caption": "学生姓名", "col_desc": "例值为:张三,李四,小明", "col_type": "string"}, {"col_name": "score", "col_caption": "学生分数", "col_desc": "例值为:98,100,66", "col_type": "string"}]}]}}] # noqa E501
108
+ workspace (str): The dashscope workspace id.
107
109
  **kwargs:
108
- n(int, `optional`): The number of output results, currently only supports 1, with a default value of 1
110
+ n(int, `optional`): The number of output results, currently only supports 1, with a default value of 1 # noqa E501
109
111
 
110
112
  Returns:
111
113
  Union[DashScopeAPIResponse,
@@ -125,6 +127,7 @@ class CodeGeneration(BaseApi):
125
127
  function=CodeGeneration.function,
126
128
  api_key=api_key,
127
129
  input=input,
130
+ workspace=workspace,
128
131
  **parameters)
129
132
 
130
133
  is_stream = kwargs.get('stream', False)
@@ -127,6 +127,7 @@ class Conversation(BaseApi):
127
127
  api_key: str = None,
128
128
  messages: List[Message] = None,
129
129
  plugins: Union[str, Dict[str, Any]] = None,
130
+ workspace: str = None,
130
131
  **kwargs
131
132
  ) -> Union[ConversationResponse, Generator[ConversationResponse, None,
132
133
  None]]:
@@ -203,6 +204,7 @@ class Conversation(BaseApi):
203
204
  repetition_penalty(float, `optional`): Used to control the repeatability when generating models. # noqa E501
204
205
  Increasing repetition_penalty can reduce the duplication of model generation. # noqa E501
205
206
  1.0 means no punishment.
207
+ workspace (str): The dashscope workspace id.
206
208
  Raises:
207
209
  InputRequired: The prompt cannot be empty.
208
210
  InvalidInput: The history and auto_history are mutually exclusive.
@@ -235,6 +237,7 @@ class Conversation(BaseApi):
235
237
  function='generation',
236
238
  api_key=api_key,
237
239
  input=input,
240
+ workspace=workspace,
238
241
  **parameters)
239
242
  is_stream = kwargs.get('stream', False)
240
243
  return self._handle_response(prompt, response, is_stream)
@@ -39,6 +39,7 @@ class Generation(BaseApi):
39
39
  api_key: str = None,
40
40
  messages: List[Message] = None,
41
41
  plugins: Union[str, Dict[str, Any]] = None,
42
+ workspace: str = None,
42
43
  **kwargs
43
44
  ) -> Union[GenerationResponse, Generator[GenerationResponse, None, None]]:
44
45
  """Call generation model service.
@@ -110,6 +111,7 @@ class Generation(BaseApi):
110
111
  repetition_penalty(float, `optional`): Used to control the repeatability when generating models. # noqa E501
111
112
  Increasing repetition_penalty can reduce the duplication of model generation. # noqa E501
112
113
  1.0 means no punishment.
114
+ workspace (str): The dashscope workspace id.
113
115
  Raises:
114
116
  InvalidInput: The history and auto_history are mutually exclusive.
115
117
 
@@ -139,6 +141,7 @@ class Generation(BaseApi):
139
141
  function=function,
140
142
  api_key=api_key,
141
143
  input=input,
144
+ workspace=workspace,
142
145
  **parameters)
143
146
  is_stream = kwargs.get('stream', False)
144
147
  if is_stream:
@@ -24,6 +24,7 @@ class ImageSynthesis(BaseAsyncApi):
24
24
  images: List[str] = None,
25
25
  api_key: str = None,
26
26
  sketch_image_url: str = None,
27
+ workspace: str = None,
27
28
  **kwargs) -> ImageSynthesisResponse:
28
29
  """Call image(s) synthesis service and get result.
29
30
 
@@ -36,6 +37,7 @@ class ImageSynthesis(BaseAsyncApi):
36
37
  api_key (str, optional): The api api_key. Defaults to None.
37
38
  sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1.
38
39
  Defaults to None.
40
+ workspace (str): The dashscope workspace id.
39
41
  **kwargs:
40
42
  n(int, `optional`): Number of images to synthesis.
41
43
  size(str, `optional`): The output image(s) size(width*height).
@@ -59,6 +61,7 @@ class ImageSynthesis(BaseAsyncApi):
59
61
  images,
60
62
  api_key=api_key,
61
63
  sketch_image_url=sketch_image_url,
64
+ workspace=workspace,
62
65
  **kwargs)
63
66
 
64
67
  @classmethod
@@ -69,6 +72,7 @@ class ImageSynthesis(BaseAsyncApi):
69
72
  images: List[str] = None,
70
73
  api_key: str = None,
71
74
  sketch_image_url: str = None,
75
+ workspace: str = None,
72
76
  **kwargs) -> ImageSynthesisResponse:
73
77
  """Create a image(s) synthesis task, and return task information.
74
78
 
@@ -80,6 +84,7 @@ class ImageSynthesis(BaseAsyncApi):
80
84
  api_key (str, optional): The api api_key. Defaults to None.
81
85
  sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1.
82
86
  Defaults to None.
87
+ workspace (str): The dashscope workspace id.
83
88
  **kwargs(wanx-v1):
84
89
  n(int, `optional`): Number of images to synthesis.
85
90
  size: The output image(s) size, Default 1024*1024
@@ -114,47 +119,53 @@ class ImageSynthesis(BaseAsyncApi):
114
119
  function=function,
115
120
  api_key=api_key,
116
121
  input=input,
122
+ workspace=workspace,
117
123
  **kwargs)
118
124
  return ImageSynthesisResponse.from_api_response(response)
119
125
 
120
126
  @classmethod
121
127
  def fetch(cls,
122
128
  task: Union[str, ImageSynthesisResponse],
123
- api_key: str = None) -> ImageSynthesisResponse:
129
+ api_key: str = None,
130
+ workspace: str = None) -> ImageSynthesisResponse:
124
131
  """Fetch image(s) synthesis task status or result.
125
132
 
126
133
  Args:
127
134
  task (Union[str, ImageSynthesisResponse]): The task_id or
128
135
  ImageSynthesisResponse return by async_call().
129
136
  api_key (str, optional): The api api_key. Defaults to None.
137
+ workspace (str): The dashscope workspace id.
130
138
 
131
139
  Returns:
132
140
  ImageSynthesisResponse: The task status or result.
133
141
  """
134
- response = super().fetch(task, api_key)
142
+ response = super().fetch(task, api_key=api_key, workspace=workspace)
135
143
  return ImageSynthesisResponse.from_api_response(response)
136
144
 
137
145
  @classmethod
138
146
  def wait(cls,
139
147
  task: Union[str, ImageSynthesisResponse],
140
- api_key: str = None) -> ImageSynthesisResponse:
148
+ api_key: str = None,
149
+ workspace: str = None) -> ImageSynthesisResponse:
141
150
  """Wait for image(s) synthesis task to complete, and return the result.
142
151
 
143
152
  Args:
144
153
  task (Union[str, ImageSynthesisResponse]): The task_id or
145
154
  ImageSynthesisResponse return by async_call().
146
155
  api_key (str, optional): The api api_key. Defaults to None.
156
+ workspace (str): The dashscope workspace id.
147
157
 
148
158
  Returns:
149
159
  ImageSynthesisResponse: The task result.
150
160
  """
151
- response = super().wait(task, api_key)
161
+ response = super().wait(task, api_key, workspace=workspace)
152
162
  return ImageSynthesisResponse.from_api_response(response)
153
163
 
154
164
  @classmethod
155
165
  def cancel(cls,
156
166
  task: Union[str, ImageSynthesisResponse],
157
- api_key: str = None) -> DashScopeAPIResponse:
167
+ api_key: str = None,
168
+ workspace: str = None) -> DashScopeAPIResponse:
158
169
  """Cancel image synthesis task.
159
170
  Only tasks whose status is PENDING can be canceled.
160
171
 
@@ -162,11 +173,12 @@ class ImageSynthesis(BaseAsyncApi):
162
173
  task (Union[str, ImageSynthesisResponse]): The task_id or
163
174
  ImageSynthesisResponse return by async_call().
164
175
  api_key (str, optional): The api api_key. Defaults to None.
176
+ workspace (str): The dashscope workspace id.
165
177
 
166
178
  Returns:
167
179
  DashScopeAPIResponse: The response data.
168
180
  """
169
- return super().cancel(task, api_key)
181
+ return super().cancel(task, api_key, workspace=workspace)
170
182
 
171
183
  @classmethod
172
184
  def list(cls,
@@ -179,6 +191,7 @@ class ImageSynthesis(BaseAsyncApi):
179
191
  page_no: int = 1,
180
192
  page_size: int = 10,
181
193
  api_key: str = None,
194
+ workspace: str = None,
182
195
  **kwargs) -> DashScopeAPIResponse:
183
196
  """List async tasks.
184
197
 
@@ -196,6 +209,7 @@ class ImageSynthesis(BaseAsyncApi):
196
209
  page_no (int, optional): The page number. Defaults to 1.
197
210
  page_size (int, optional): The page size. Defaults to 10.
198
211
  api_key (str, optional): The user api-key. Defaults to None.
212
+ workspace (str): The dashscope workspace id.
199
213
 
200
214
  Returns:
201
215
  DashScopeAPIResponse: The response data.
@@ -209,4 +223,5 @@ class ImageSynthesis(BaseAsyncApi):
209
223
  page_no=page_no,
210
224
  page_size=page_size,
211
225
  api_key=api_key,
226
+ workspace=workspace,
212
227
  **kwargs)
@@ -24,6 +24,7 @@ class MultiModalConversation(BaseApi):
24
24
  model: str,
25
25
  messages: List,
26
26
  api_key: str = None,
27
+ workspace: str = None,
27
28
  **kwargs
28
29
  ) -> Union[MultiModalConversationResponse, Generator[
29
30
  MultiModalConversationResponse, None, None]]:
@@ -51,6 +52,7 @@ class MultiModalConversation(BaseApi):
51
52
  api_key (str, optional): The api api_key, can be None,
52
53
  if None, will retrieve by rule [1].
53
54
  [1]: https://help.aliyun.com/zh/dashscope/developer-reference/api-key-settings. # noqa E501
55
+ workspace (str): The dashscope workspace id.
54
56
  **kwargs:
55
57
  stream(bool, `optional`): Enable server-sent events
56
58
  (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501
@@ -92,6 +94,7 @@ class MultiModalConversation(BaseApi):
92
94
  function=MultiModalConversation.function,
93
95
  api_key=api_key,
94
96
  input=input,
97
+ workspace=workspace,
95
98
  **kwargs)
96
99
  is_stream = kwargs.get('stream', False)
97
100
  if is_stream:
@@ -2,6 +2,7 @@ import json
2
2
  from http import HTTPStatus
3
3
 
4
4
  import aiohttp
5
+
5
6
  from dashscope.api_entities.base_request import AioBaseRequest
6
7
  from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
7
8
  from dashscope.common.constants import (DEFAULT_REQUEST_TIMEOUT_SECONDS,
@@ -24,22 +24,33 @@ def _get_protocol_params(kwargs):
24
24
  request_timeout = kwargs.pop(REQUEST_TIMEOUT_KEYWORD, None)
25
25
  form = kwargs.pop('form', None)
26
26
  resources = kwargs.pop('resources', None)
27
+ base_address = kwargs.pop('base_address', None)
28
+ flattened_output = kwargs.pop('flattened_output', False)
27
29
  return (api_protocol, ws_stream_mode, is_binary_input, http_method, stream,
28
- async_request, query, headers, request_timeout, form, resources)
30
+ async_request, query, headers, request_timeout, form, resources,
31
+ base_address, flattened_output)
29
32
 
30
33
 
31
- def _build_api_request(model: str, input: object, task_group: str, task: str,
32
- function: str, api_key: str, is_service=True, **kwargs):
34
+ def _build_api_request(model: str,
35
+ input: object,
36
+ task_group: str,
37
+ task: str,
38
+ function: str,
39
+ api_key: str,
40
+ is_service=True,
41
+ **kwargs):
33
42
  (api_protocol, ws_stream_mode, is_binary_input, http_method, stream,
34
- async_request, query, headers, request_timeout, form,
35
- resources) = _get_protocol_params(kwargs)
43
+ async_request, query, headers, request_timeout, form, resources,
44
+ base_address, flattened_output) = _get_protocol_params(kwargs)
36
45
  task_id = kwargs.pop('task_id', None)
37
46
  if api_protocol in [ApiProtocol.HTTP, ApiProtocol.HTTPS]:
38
- if not dashscope.base_http_api_url.endswith('/'):
39
- http_url = dashscope.base_http_api_url + '/'
47
+ if base_address is None:
48
+ base_address = dashscope.base_http_api_url
49
+ if not base_address.endswith('/'):
50
+ http_url = base_address + '/'
40
51
  else:
41
- http_url = dashscope.base_http_api_url
42
-
52
+ http_url = base_address
53
+
43
54
  if is_service:
44
55
  http_url = http_url + SERVICE_API_PATH + '/'
45
56
 
@@ -56,15 +67,20 @@ def _build_api_request(model: str, input: object, task_group: str, task: str,
56
67
  async_request=async_request,
57
68
  query=query,
58
69
  timeout=request_timeout,
59
- task_id=task_id)
70
+ task_id=task_id,
71
+ flattened_output=flattened_output)
60
72
  elif api_protocol == ApiProtocol.WEBSOCKET:
61
- websocket_url = dashscope.base_websocket_api_url
73
+ if base_address is not None:
74
+ websocket_url = base_address
75
+ else:
76
+ websocket_url = dashscope.base_websocket_api_url
62
77
  request = WebSocketRequest(url=websocket_url,
63
78
  api_key=api_key,
64
79
  stream=stream,
65
80
  ws_stream_mode=ws_stream_mode,
66
81
  is_binary_input=is_binary_input,
67
- timeout=request_timeout)
82
+ timeout=request_timeout,
83
+ flattened_output=flattened_output)
68
84
  else:
69
85
  raise UnsupportedApiProtocol(
70
86
  'Unsupported protocol: %s, support [http, https, websocket]' %
@@ -2,6 +2,7 @@ import json
2
2
  from http import HTTPStatus
3
3
 
4
4
  import requests
5
+
5
6
  from dashscope.api_entities.base_request import BaseRequest
6
7
  from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
7
8
  from dashscope.common.constants import (DEFAULT_REQUEST_TIMEOUT_SECONDS,
@@ -19,7 +20,8 @@ class HttpRequest(BaseRequest):
19
20
  async_request: bool = False,
20
21
  query: bool = False,
21
22
  timeout: int = DEFAULT_REQUEST_TIMEOUT_SECONDS,
22
- task_id: str = None) -> None:
23
+ task_id: str = None,
24
+ flattened_output: bool = False) -> None:
23
25
  """HttpSSERequest, processing http server sent event stream.
24
26
 
25
27
  Args:
@@ -33,6 +35,7 @@ class HttpRequest(BaseRequest):
33
35
 
34
36
  super().__init__()
35
37
  self.url = url
38
+ self.flattened_output = flattened_output
36
39
  self.async_request = async_request
37
40
  self.headers = {
38
41
  'Accept': 'application/json',
@@ -137,10 +140,13 @@ class HttpRequest(BaseRequest):
137
140
  message=msg['message']
138
141
  if 'message' in msg else None) # noqa E501
139
142
  else:
140
- yield DashScopeAPIResponse(request_id=request_id,
141
- status_code=HTTPStatus.OK,
142
- output=output,
143
- usage=usage)
143
+ if self.flattened_output:
144
+ yield msg
145
+ else:
146
+ yield DashScopeAPIResponse(request_id=request_id,
147
+ status_code=HTTPStatus.OK,
148
+ output=output,
149
+ usage=usage)
144
150
  elif response.status_code == HTTPStatus.OK:
145
151
  json_content = response.json()
146
152
  logger.debug('Response: %s' % json_content)
@@ -154,10 +160,13 @@ class HttpRequest(BaseRequest):
154
160
  usage = json_content['usage']
155
161
  if 'request_id' in json_content:
156
162
  request_id = json_content['request_id']
157
- yield DashScopeAPIResponse(request_id=request_id,
158
- status_code=HTTPStatus.OK,
159
- output=output,
160
- usage=usage)
163
+ if self.flattened_output:
164
+ yield json_content
165
+ else:
166
+ yield DashScopeAPIResponse(request_id=request_id,
167
+ status_code=HTTPStatus.OK,
168
+ output=output,
169
+ usage=usage)
161
170
  else:
162
171
  if 'application/json' in response.headers.get('content-type', ''):
163
172
  error = response.json()
@@ -5,6 +5,7 @@ from http import HTTPStatus
5
5
  from typing import Tuple, Union
6
6
 
7
7
  import aiohttp
8
+
8
9
  from dashscope.api_entities.base_request import AioBaseRequest
9
10
  from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
10
11
  from dashscope.common.constants import (DEFAULT_REQUEST_TIMEOUT_SECONDS,
@@ -29,6 +30,7 @@ class WebSocketRequest(AioBaseRequest):
29
30
  ws_stream_mode: str = WebsocketStreamingMode.OUT,
30
31
  is_binary_input: bool = False,
31
32
  timeout: int = DEFAULT_REQUEST_TIMEOUT_SECONDS,
33
+ flattened_output: bool = False,
32
34
  ) -> None:
33
35
  super().__init__()
34
36
  """HttpRequest.
@@ -43,6 +45,7 @@ class WebSocketRequest(AioBaseRequest):
43
45
  """
44
46
  self.url = url
45
47
  self.stream = stream
48
+ self.flattened_output = flattened_output
46
49
  if timeout is None:
47
50
  self.timeout = DEFAULT_REQUEST_TIMEOUT_SECONDS
48
51
  else:
@@ -1,6 +1,4 @@
1
1
  #!/usr/bin/env python3
2
- # -*-coding:utf-8 -*-
3
-
4
2
  """
5
3
  @File : application.py
6
4
  @Date : 2024-02-24
@@ -18,12 +16,10 @@ from dashscope.common.error import InputRequired, InvalidInput
18
16
 
19
17
  class Application(BaseApi):
20
18
  task_group = 'apps'
21
- function = "completion"
22
-
19
+ function = 'completion'
23
20
  """API for app completion calls.
24
21
 
25
22
  """
26
-
27
23
  class DocReferenceType:
28
24
  """ doc reference type for rag completion """
29
25
 
@@ -41,14 +37,15 @@ class Application(BaseApi):
41
37
 
42
38
  @classmethod
43
39
  def call(
44
- cls,
45
- app_id: str,
46
- prompt: str,
47
- history: list = None,
48
- workspace: str = None,
49
- api_key: str = None,
50
- **kwargs
51
- ) -> Union[ApplicationResponse, Generator[ApplicationResponse, None, None]]:
40
+ cls,
41
+ app_id: str,
42
+ prompt: str,
43
+ history: list = None,
44
+ workspace: str = None,
45
+ api_key: str = None,
46
+ **kwargs
47
+ ) -> Union[ApplicationResponse, Generator[ApplicationResponse, None,
48
+ None]]:
52
49
  """Call app completion service.
53
50
 
54
51
  Args:
@@ -115,17 +112,14 @@ class Application(BaseApi):
115
112
  if prompt is None or not prompt:
116
113
  raise InputRequired('prompt is required!')
117
114
 
118
- if workspace is not None and workspace:
119
- headers = kwargs.pop('headers', {})
120
- headers['X-DashScope-WorkSpace'] = workspace
121
- kwargs['headers'] = headers
122
-
123
- input, parameters = cls._build_input_parameters(prompt, history, **kwargs)
115
+ input, parameters = cls._build_input_parameters(
116
+ prompt, history, **kwargs)
124
117
  request = _build_api_request(model='',
125
118
  input=input,
126
119
  task_group=Application.task_group,
127
120
  task=app_id,
128
121
  function=Application.function,
122
+ workspace=workspace,
129
123
  api_key=api_key,
130
124
  is_service=False,
131
125
  **parameters)
@@ -143,9 +137,7 @@ class Application(BaseApi):
143
137
  def _build_input_parameters(cls, prompt, history, **kwargs):
144
138
  parameters = {}
145
139
 
146
- input_param = {HISTORY: history,
147
- PROMPT: prompt
148
- }
140
+ input_param = {HISTORY: history, PROMPT: prompt}
149
141
 
150
142
  session_id = kwargs.pop('session_id', None)
151
143
  if session_id is not None and session_id:
@@ -157,7 +149,8 @@ class Application(BaseApi):
157
149
 
158
150
  doc_tag_codes = kwargs.pop('doc_tag_codes', None)
159
151
  if doc_tag_codes is not None:
160
- if isinstance(doc_tag_codes, list) and all(isinstance(item, str) for item in doc_tag_codes):
152
+ if isinstance(doc_tag_codes, list) and all(
153
+ isinstance(item, str) for item in doc_tag_codes):
161
154
  input_param['doc_tag_codes'] = doc_tag_codes
162
155
  else:
163
156
  raise InvalidInput('doc_tag_codes is not a List[str]')
@@ -0,0 +1,14 @@
1
+ # yapf: disable
2
+
3
+ from dashscope.assistants.assistant_types import (Assistant, AssistantFile,
4
+ AssistantList,
5
+ DeleteResponse)
6
+ from dashscope.assistants.assistants import Assistants
7
+
8
+ __all__ = [
9
+ Assistant,
10
+ Assistants,
11
+ AssistantList,
12
+ AssistantFile,
13
+ DeleteResponse,
14
+ ]