dashscope 1.15.0__py3-none-any.whl → 1.18.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.
- dashscope/__init__.py +57 -10
- dashscope/aigc/code_generation.py +12 -9
- dashscope/aigc/conversation.py +3 -0
- dashscope/aigc/generation.py +3 -0
- dashscope/aigc/image_synthesis.py +26 -6
- dashscope/aigc/multimodal_conversation.py +3 -0
- dashscope/api_entities/aiohttp_request.py +1 -0
- dashscope/api_entities/api_request_factory.py +28 -12
- dashscope/api_entities/dashscope_response.py +63 -0
- dashscope/api_entities/http_request.py +21 -31
- dashscope/api_entities/websocket_request.py +3 -0
- dashscope/app/application.py +16 -18
- dashscope/assistants/__init__.py +14 -0
- dashscope/assistants/assistant_types.py +164 -0
- dashscope/assistants/assistants.py +280 -0
- dashscope/assistants/files.py +189 -0
- dashscope/audio/asr/asr_phrase_manager.py +27 -5
- dashscope/audio/asr/recognition.py +10 -2
- dashscope/audio/asr/transcription.py +21 -3
- dashscope/audio/tts/speech_synthesizer.py +3 -0
- dashscope/cli.py +7 -7
- dashscope/client/base_api.py +317 -70
- dashscope/common/base_type.py +130 -0
- dashscope/common/constants.py +1 -0
- dashscope/common/error.py +4 -0
- dashscope/common/utils.py +159 -27
- dashscope/deployment.py +40 -6
- dashscope/embeddings/batch_text_embedding.py +24 -7
- dashscope/embeddings/multimodal_embedding.py +3 -0
- dashscope/embeddings/text_embedding.py +8 -1
- dashscope/files.py +107 -0
- dashscope/finetune.py +31 -7
- dashscope/model.py +9 -2
- dashscope/models.py +47 -0
- dashscope/nlp/understanding.py +2 -2
- dashscope/rerank/__init__.py +0 -0
- dashscope/rerank/text_rerank.py +67 -0
- dashscope/threads/__init__.py +24 -0
- dashscope/threads/messages/__init__.py +0 -0
- dashscope/threads/messages/files.py +111 -0
- dashscope/threads/messages/messages.py +218 -0
- dashscope/threads/runs/__init__.py +0 -0
- dashscope/threads/runs/runs.py +483 -0
- dashscope/threads/runs/steps.py +110 -0
- dashscope/threads/thread_types.py +651 -0
- dashscope/threads/threads.py +210 -0
- dashscope/tokenizers/tokenization.py +3 -0
- dashscope/utils/oss_utils.py +11 -0
- dashscope/version.py +1 -1
- {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/METADATA +2 -3
- dashscope-1.18.0.dist-info/RECORD +84 -0
- dashscope-1.15.0.dist-info/RECORD +0 -66
- {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/LICENSE +0 -0
- {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/WHEEL +0 -0
- {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/entry_points.txt +0 -0
- {dashscope-1.15.0.dist-info → dashscope-1.18.0.dist-info}/top_level.txt +0 -0
dashscope/__init__.py
CHANGED
|
@@ -1,11 +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
|
|
10
|
+
from dashscope.assistants import Assistant, AssistantList, Assistants
|
|
11
|
+
from dashscope.assistants.assistant_types import AssistantFile, DeleteResponse
|
|
9
12
|
from dashscope.audio.asr.transcription import Transcription
|
|
10
13
|
from dashscope.audio.tts.speech_synthesizer import SpeechSynthesizer
|
|
11
14
|
from dashscope.common.api_key import save_api_key
|
|
@@ -19,23 +22,67 @@ from dashscope.embeddings.multimodal_embedding import (
|
|
|
19
22
|
MultiModalEmbedding, MultiModalEmbeddingItemAudio,
|
|
20
23
|
MultiModalEmbeddingItemImage, MultiModalEmbeddingItemText)
|
|
21
24
|
from dashscope.embeddings.text_embedding import TextEmbedding
|
|
22
|
-
from dashscope.
|
|
25
|
+
from dashscope.files import Files
|
|
23
26
|
from dashscope.finetune import FineTune
|
|
24
27
|
from dashscope.model import Model
|
|
25
28
|
from dashscope.nlp.understanding import Understanding
|
|
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)
|
|
26
33
|
from dashscope.tokenizers import (Tokenization, Tokenizer, get_tokenizer,
|
|
27
34
|
list_tokenizers)
|
|
28
|
-
from dashscope.app.application import Application
|
|
29
35
|
|
|
30
36
|
__all__ = [
|
|
31
|
-
base_http_api_url,
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
base_http_api_url,
|
|
38
|
+
base_websocket_api_url,
|
|
39
|
+
api_key,
|
|
40
|
+
api_key_file_path,
|
|
41
|
+
save_api_key,
|
|
42
|
+
Conversation,
|
|
43
|
+
Generation,
|
|
44
|
+
History,
|
|
45
|
+
HistoryItem,
|
|
46
|
+
ImageSynthesis,
|
|
47
|
+
Transcription,
|
|
48
|
+
Files,
|
|
49
|
+
Deployment,
|
|
50
|
+
FineTune,
|
|
51
|
+
Model,
|
|
52
|
+
TextEmbedding,
|
|
53
|
+
MultiModalEmbedding,
|
|
54
|
+
MultiModalEmbeddingItemAudio,
|
|
55
|
+
MultiModalEmbeddingItemImage,
|
|
56
|
+
MultiModalEmbeddingItemText,
|
|
57
|
+
SpeechSynthesizer,
|
|
58
|
+
MultiModalConversation,
|
|
59
|
+
BatchTextEmbedding,
|
|
60
|
+
BatchTextEmbeddingResponse,
|
|
61
|
+
Understanding,
|
|
62
|
+
CodeGeneration,
|
|
63
|
+
Tokenization,
|
|
64
|
+
Tokenizer,
|
|
65
|
+
get_tokenizer,
|
|
66
|
+
list_tokenizers,
|
|
67
|
+
Application,
|
|
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,
|
|
39
86
|
]
|
|
40
87
|
|
|
41
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)
|
dashscope/aigc/conversation.py
CHANGED
|
@@ -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)
|
dashscope/aigc/generation.py
CHANGED
|
@@ -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,8 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
24
24
|
images: List[str] = None,
|
|
25
25
|
api_key: str = None,
|
|
26
26
|
sketch_image_url: str = None,
|
|
27
|
+
ref_img: str = None,
|
|
28
|
+
workspace: str = None,
|
|
27
29
|
**kwargs) -> ImageSynthesisResponse:
|
|
28
30
|
"""Call image(s) synthesis service and get result.
|
|
29
31
|
|
|
@@ -36,6 +38,7 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
36
38
|
api_key (str, optional): The api api_key. Defaults to None.
|
|
37
39
|
sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1.
|
|
38
40
|
Defaults to None.
|
|
41
|
+
workspace (str): The dashscope workspace id.
|
|
39
42
|
**kwargs:
|
|
40
43
|
n(int, `optional`): Number of images to synthesis.
|
|
41
44
|
size(str, `optional`): The output image(s) size(width*height).
|
|
@@ -59,6 +62,8 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
59
62
|
images,
|
|
60
63
|
api_key=api_key,
|
|
61
64
|
sketch_image_url=sketch_image_url,
|
|
65
|
+
ref_img=ref_img,
|
|
66
|
+
workspace=workspace,
|
|
62
67
|
**kwargs)
|
|
63
68
|
|
|
64
69
|
@classmethod
|
|
@@ -69,6 +74,8 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
69
74
|
images: List[str] = None,
|
|
70
75
|
api_key: str = None,
|
|
71
76
|
sketch_image_url: str = None,
|
|
77
|
+
ref_img: str = None,
|
|
78
|
+
workspace: str = None,
|
|
72
79
|
**kwargs) -> ImageSynthesisResponse:
|
|
73
80
|
"""Create a image(s) synthesis task, and return task information.
|
|
74
81
|
|
|
@@ -80,6 +87,7 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
80
87
|
api_key (str, optional): The api api_key. Defaults to None.
|
|
81
88
|
sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1.
|
|
82
89
|
Defaults to None.
|
|
90
|
+
workspace (str): The dashscope workspace id.
|
|
83
91
|
**kwargs(wanx-v1):
|
|
84
92
|
n(int, `optional`): Number of images to synthesis.
|
|
85
93
|
size: The output image(s) size, Default 1024*1024
|
|
@@ -108,53 +116,61 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
108
116
|
input[IMAGES] = images
|
|
109
117
|
if sketch_image_url is not None and sketch_image_url:
|
|
110
118
|
input['sketch_image_url'] = sketch_image_url
|
|
119
|
+
if ref_img is not None and ref_img:
|
|
120
|
+
input['ref_img'] == ref_img
|
|
111
121
|
response = super().async_call(model=model,
|
|
112
122
|
task_group=task_group,
|
|
113
123
|
task=ImageSynthesis.task,
|
|
114
124
|
function=function,
|
|
115
125
|
api_key=api_key,
|
|
116
126
|
input=input,
|
|
127
|
+
workspace=workspace,
|
|
117
128
|
**kwargs)
|
|
118
129
|
return ImageSynthesisResponse.from_api_response(response)
|
|
119
130
|
|
|
120
131
|
@classmethod
|
|
121
132
|
def fetch(cls,
|
|
122
133
|
task: Union[str, ImageSynthesisResponse],
|
|
123
|
-
api_key: str = None
|
|
134
|
+
api_key: str = None,
|
|
135
|
+
workspace: str = None) -> ImageSynthesisResponse:
|
|
124
136
|
"""Fetch image(s) synthesis task status or result.
|
|
125
137
|
|
|
126
138
|
Args:
|
|
127
139
|
task (Union[str, ImageSynthesisResponse]): The task_id or
|
|
128
140
|
ImageSynthesisResponse return by async_call().
|
|
129
141
|
api_key (str, optional): The api api_key. Defaults to None.
|
|
142
|
+
workspace (str): The dashscope workspace id.
|
|
130
143
|
|
|
131
144
|
Returns:
|
|
132
145
|
ImageSynthesisResponse: The task status or result.
|
|
133
146
|
"""
|
|
134
|
-
response = super().fetch(task, api_key)
|
|
147
|
+
response = super().fetch(task, api_key=api_key, workspace=workspace)
|
|
135
148
|
return ImageSynthesisResponse.from_api_response(response)
|
|
136
149
|
|
|
137
150
|
@classmethod
|
|
138
151
|
def wait(cls,
|
|
139
152
|
task: Union[str, ImageSynthesisResponse],
|
|
140
|
-
api_key: str = None
|
|
153
|
+
api_key: str = None,
|
|
154
|
+
workspace: str = None) -> ImageSynthesisResponse:
|
|
141
155
|
"""Wait for image(s) synthesis task to complete, and return the result.
|
|
142
156
|
|
|
143
157
|
Args:
|
|
144
158
|
task (Union[str, ImageSynthesisResponse]): The task_id or
|
|
145
159
|
ImageSynthesisResponse return by async_call().
|
|
146
160
|
api_key (str, optional): The api api_key. Defaults to None.
|
|
161
|
+
workspace (str): The dashscope workspace id.
|
|
147
162
|
|
|
148
163
|
Returns:
|
|
149
164
|
ImageSynthesisResponse: The task result.
|
|
150
165
|
"""
|
|
151
|
-
response = super().wait(task, api_key)
|
|
166
|
+
response = super().wait(task, api_key, workspace=workspace)
|
|
152
167
|
return ImageSynthesisResponse.from_api_response(response)
|
|
153
168
|
|
|
154
169
|
@classmethod
|
|
155
170
|
def cancel(cls,
|
|
156
171
|
task: Union[str, ImageSynthesisResponse],
|
|
157
|
-
api_key: str = None
|
|
172
|
+
api_key: str = None,
|
|
173
|
+
workspace: str = None) -> DashScopeAPIResponse:
|
|
158
174
|
"""Cancel image synthesis task.
|
|
159
175
|
Only tasks whose status is PENDING can be canceled.
|
|
160
176
|
|
|
@@ -162,11 +178,12 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
162
178
|
task (Union[str, ImageSynthesisResponse]): The task_id or
|
|
163
179
|
ImageSynthesisResponse return by async_call().
|
|
164
180
|
api_key (str, optional): The api api_key. Defaults to None.
|
|
181
|
+
workspace (str): The dashscope workspace id.
|
|
165
182
|
|
|
166
183
|
Returns:
|
|
167
184
|
DashScopeAPIResponse: The response data.
|
|
168
185
|
"""
|
|
169
|
-
return super().cancel(task, api_key)
|
|
186
|
+
return super().cancel(task, api_key, workspace=workspace)
|
|
170
187
|
|
|
171
188
|
@classmethod
|
|
172
189
|
def list(cls,
|
|
@@ -179,6 +196,7 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
179
196
|
page_no: int = 1,
|
|
180
197
|
page_size: int = 10,
|
|
181
198
|
api_key: str = None,
|
|
199
|
+
workspace: str = None,
|
|
182
200
|
**kwargs) -> DashScopeAPIResponse:
|
|
183
201
|
"""List async tasks.
|
|
184
202
|
|
|
@@ -196,6 +214,7 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
196
214
|
page_no (int, optional): The page number. Defaults to 1.
|
|
197
215
|
page_size (int, optional): The page size. Defaults to 10.
|
|
198
216
|
api_key (str, optional): The user api-key. Defaults to None.
|
|
217
|
+
workspace (str): The dashscope workspace id.
|
|
199
218
|
|
|
200
219
|
Returns:
|
|
201
220
|
DashScopeAPIResponse: The response data.
|
|
@@ -209,4 +228,5 @@ class ImageSynthesis(BaseAsyncApi):
|
|
|
209
228
|
page_no=page_no,
|
|
210
229
|
page_size=page_size,
|
|
211
230
|
api_key=api_key,
|
|
231
|
+
workspace=workspace,
|
|
212
232
|
**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,
|
|
32
|
-
|
|
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
|
-
|
|
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
|
|
39
|
-
|
|
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 =
|
|
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
|
-
|
|
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]' %
|
|
@@ -493,3 +493,66 @@ class ImageSynthesisResponse(DashScopeAPIResponse):
|
|
|
493
493
|
request_id=api_response.request_id,
|
|
494
494
|
code=api_response.code,
|
|
495
495
|
message=api_response.message)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
@dataclass(init=False)
|
|
499
|
+
class ReRankResult(DictMixin):
|
|
500
|
+
index: int
|
|
501
|
+
relevance_score: float
|
|
502
|
+
document: Dict = None
|
|
503
|
+
|
|
504
|
+
def __init__(self,
|
|
505
|
+
index: int,
|
|
506
|
+
relevance_score: float,
|
|
507
|
+
document: Dict = None,
|
|
508
|
+
**kwargs):
|
|
509
|
+
super().__init__(index=index,
|
|
510
|
+
relevance_score=relevance_score,
|
|
511
|
+
document=document,
|
|
512
|
+
**kwargs)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
@dataclass(init=False)
|
|
516
|
+
class ReRankOutput(DictMixin):
|
|
517
|
+
results: List[ReRankResult]
|
|
518
|
+
|
|
519
|
+
def __init__(self, results: List[ReRankResult] = None, **kwargs):
|
|
520
|
+
ress = None
|
|
521
|
+
if results is not None:
|
|
522
|
+
ress = []
|
|
523
|
+
for res in results:
|
|
524
|
+
ress.append(ReRankResult(**res))
|
|
525
|
+
super().__init__(results=ress, **kwargs)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
@dataclass(init=False)
|
|
529
|
+
class ReRankUsage(DictMixin):
|
|
530
|
+
total_tokens: int
|
|
531
|
+
|
|
532
|
+
def __init__(self, total_tokens=None, **kwargs):
|
|
533
|
+
super().__init__(total_tokens=total_tokens, **kwargs)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
@dataclass(init=False)
|
|
537
|
+
class ReRankResponse(DashScopeAPIResponse):
|
|
538
|
+
output: ReRankOutput
|
|
539
|
+
usage: GenerationUsage
|
|
540
|
+
|
|
541
|
+
@staticmethod
|
|
542
|
+
def from_api_response(api_response: DashScopeAPIResponse):
|
|
543
|
+
if api_response.status_code == HTTPStatus.OK:
|
|
544
|
+
usage = {}
|
|
545
|
+
if api_response.usage:
|
|
546
|
+
usage = api_response.usage
|
|
547
|
+
|
|
548
|
+
return ReRankResponse(status_code=api_response.status_code,
|
|
549
|
+
request_id=api_response.request_id,
|
|
550
|
+
code=api_response.code,
|
|
551
|
+
message=api_response.message,
|
|
552
|
+
output=ReRankOutput(**api_response.output),
|
|
553
|
+
usage=ReRankUsage(**usage))
|
|
554
|
+
else:
|
|
555
|
+
return ReRankResponse(status_code=api_response.status_code,
|
|
556
|
+
request_id=api_response.request_id,
|
|
557
|
+
code=api_response.code,
|
|
558
|
+
message=api_response.message)
|
|
@@ -2,12 +2,14 @@ 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,
|
|
8
9
|
SSE_CONTENT_TYPE, HTTPMethod)
|
|
9
10
|
from dashscope.common.error import UnsupportedHTTPMethod
|
|
10
11
|
from dashscope.common.logging import logger
|
|
12
|
+
from dashscope.common.utils import _handle_stream
|
|
11
13
|
|
|
12
14
|
|
|
13
15
|
class HttpRequest(BaseRequest):
|
|
@@ -19,7 +21,8 @@ class HttpRequest(BaseRequest):
|
|
|
19
21
|
async_request: bool = False,
|
|
20
22
|
query: bool = False,
|
|
21
23
|
timeout: int = DEFAULT_REQUEST_TIMEOUT_SECONDS,
|
|
22
|
-
task_id: str = None
|
|
24
|
+
task_id: str = None,
|
|
25
|
+
flattened_output: bool = False) -> None:
|
|
23
26
|
"""HttpSSERequest, processing http server sent event stream.
|
|
24
27
|
|
|
25
28
|
Args:
|
|
@@ -33,6 +36,7 @@ class HttpRequest(BaseRequest):
|
|
|
33
36
|
|
|
34
37
|
super().__init__()
|
|
35
38
|
self.url = url
|
|
39
|
+
self.flattened_output = flattened_output
|
|
36
40
|
self.async_request = async_request
|
|
37
41
|
self.headers = {
|
|
38
42
|
'Accept': 'application/json',
|
|
@@ -80,34 +84,14 @@ class HttpRequest(BaseRequest):
|
|
|
80
84
|
pass
|
|
81
85
|
return output
|
|
82
86
|
|
|
83
|
-
def _handle_stream(self, response: requests.Response):
|
|
84
|
-
# TODO define done message.
|
|
85
|
-
is_error = False
|
|
86
|
-
status_code = HTTPStatus.INTERNAL_SERVER_ERROR
|
|
87
|
-
for line in response.iter_lines():
|
|
88
|
-
if line:
|
|
89
|
-
line = line.decode('utf8')
|
|
90
|
-
line = line.rstrip('\n').rstrip('\r')
|
|
91
|
-
if line.startswith('event:error'):
|
|
92
|
-
is_error = True
|
|
93
|
-
elif line.startswith('status:'):
|
|
94
|
-
status_code = line[len('status:'):]
|
|
95
|
-
status_code = int(status_code.strip())
|
|
96
|
-
elif line.startswith('data:'):
|
|
97
|
-
line = line[len('data:'):]
|
|
98
|
-
yield (is_error, status_code, line)
|
|
99
|
-
if is_error:
|
|
100
|
-
break
|
|
101
|
-
else:
|
|
102
|
-
continue # ignore heartbeat...
|
|
103
|
-
|
|
104
87
|
def _handle_response(self, response: requests.Response):
|
|
105
88
|
request_id = ''
|
|
106
89
|
if (response.status_code == HTTPStatus.OK and self.stream
|
|
107
90
|
and SSE_CONTENT_TYPE in response.headers.get(
|
|
108
91
|
'content-type', '')):
|
|
109
|
-
for is_error, status_code,
|
|
92
|
+
for is_error, status_code, event in _handle_stream(response):
|
|
110
93
|
try:
|
|
94
|
+
data = event.data
|
|
111
95
|
output = None
|
|
112
96
|
usage = None
|
|
113
97
|
msg = json.loads(data)
|
|
@@ -137,10 +121,13 @@ class HttpRequest(BaseRequest):
|
|
|
137
121
|
message=msg['message']
|
|
138
122
|
if 'message' in msg else None) # noqa E501
|
|
139
123
|
else:
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
124
|
+
if self.flattened_output:
|
|
125
|
+
yield msg
|
|
126
|
+
else:
|
|
127
|
+
yield DashScopeAPIResponse(request_id=request_id,
|
|
128
|
+
status_code=HTTPStatus.OK,
|
|
129
|
+
output=output,
|
|
130
|
+
usage=usage)
|
|
144
131
|
elif response.status_code == HTTPStatus.OK:
|
|
145
132
|
json_content = response.json()
|
|
146
133
|
logger.debug('Response: %s' % json_content)
|
|
@@ -154,10 +141,13 @@ class HttpRequest(BaseRequest):
|
|
|
154
141
|
usage = json_content['usage']
|
|
155
142
|
if 'request_id' in json_content:
|
|
156
143
|
request_id = json_content['request_id']
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
144
|
+
if self.flattened_output:
|
|
145
|
+
yield json_content
|
|
146
|
+
else:
|
|
147
|
+
yield DashScopeAPIResponse(request_id=request_id,
|
|
148
|
+
status_code=HTTPStatus.OK,
|
|
149
|
+
output=output,
|
|
150
|
+
usage=usage)
|
|
161
151
|
else:
|
|
162
152
|
if 'application/json' in response.headers.get('content-type', ''):
|
|
163
153
|
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:
|