Skip to content

Commit cbaba4d

Browse files
docs: expand Sphinx API coverage, add Examples
1 parent 844fa09 commit cbaba4d

29 files changed

Lines changed: 669 additions & 38 deletions

‎dashscope/aigc/code_generation.py‎

Lines changed: 40 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -89,46 +89,55 @@ def call( # type: ignore[override]
8989
9090
Args:
9191
model (str): The requested model, such as tongyi-lingma-v1
92-
scene (str): Scene type, single choice, such as custom
93-
examples:
94-
custom:User defined prompt
95-
nl2code:Natural language generated code
96-
code2comment:annotation
97-
code2explain:explain
98-
commit2msg:Automatically generate commit
99-
uinttest:Generating Unit Tests
100-
codeqa:Code Q&A
101-
nl2sql:Generate SQL code using natural language
92+
scene (str): Task type, one of ``CodeGeneration.Scenes``:
93+
``custom`` (freeform prompt), ``nl2code`` (natural language
94+
to code), ``code2comment`` (add comments), ``code2explain``
95+
(explain code), ``commit2msg`` (generate a commit message
96+
from a diff), ``unittest`` (generate unit tests), ``codeqa``
97+
(code Q&A), ``nl2sql`` (natural language to SQL). Each scene
98+
expects a different ``message`` shape; see Examples below.
10299
api_key (str, optional): The api api_key, can be None,
103100
if None, will get by default rule(TODO: api key doc).
104-
message (list): The generation messages.
105-
scene == custom, examples:
106-
[{"role": "user", "content": "根据下面的功能描述生成一个python函数。代码的功能是计算给定路径下所有文件的总大小。"}] # noqa E501 # pylint: disable=line-too-long
107-
scene == nl2code, examples:
108-
[{"role": "user", "content": "计算给定路径下所有文件的总大小"}, {"role": "attachment", "meta": {"language": "java"}}] # noqa E501 # pylint: disable=line-too-long
109-
scene == code2comment, examples:
110-
[{"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 # pylint: disable=line-too-long
111-
scene == code2explain, examples:
112-
[{"role": "user", "content": "要求不低于200字"}, {"role": "attachment", "meta": {"code": "@Override\n public int getHeaderCacheSize()\n {\n return 0;\n }\n\n", "language": "java"}}] # noqa E501 # pylint: disable=line-too-long
113-
scene == commit2msg, examples:
114-
[{"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 # pylint: disable=line-too-long
115-
scene == unittest, examples:
116-
[{"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 # pylint: disable=line-too-long
117-
scene == codeqa, examples:
118-
[{"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 # pylint: disable=line-too-long
119-
scene == nl2sql, examples:
120-
[{"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 # pylint: disable=line-too-long
101+
message (list): The generation messages. Typically a ``user``
102+
message carrying the instruction, optionally followed by an
103+
``attachment`` message whose ``meta`` supplies the code,
104+
diff, or schema the scene operates on (see Examples below
105+
for the exact shape per scene).
121106
workspace (str): The dashscope workspace id.
122107
**kwargs:
123-
n(
124-
int,
125-
`optional`
126-
): The number of output results, currently only supports 1, with a default value of 1 # noqa E501
108+
n (int, `optional`): The number of output results,
109+
currently only supports 1, with a default value of 1.
127110
128111
Returns:
129112
Union[DashScopeAPIResponse,
130113
Generator[DashScopeAPIResponse, None, None]]: If
131114
stream is True, return Generator, otherwise DashScopeAPIResponse.
115+
116+
Examples:
117+
Natural language to code (``nl2code``):
118+
119+
>>> from dashscope import CodeGeneration
120+
>>> response = CodeGeneration.call(
121+
... model=CodeGeneration.Models.tongyi_lingma_v1,
122+
... scene=CodeGeneration.Scenes.nl2code,
123+
... message=[
124+
... {"role": "user", "content": "Compute the total size of all files under a given path"},
125+
... {"role": "attachment", "meta": {"language": "python"}},
126+
... ],
127+
... )
128+
>>> print(response.output)
129+
130+
Explain existing code (``code2explain``):
131+
132+
>>> response = CodeGeneration.call(
133+
... model=CodeGeneration.Models.tongyi_lingma_v1,
134+
... scene=CodeGeneration.Scenes.code2explain,
135+
... message=[
136+
... {"role": "user", "content": "Explain in at least 200 words"},
137+
... {"role": "attachment", "meta": {"code": "public int getHeaderCacheSize() { return 0; }", "language": "java"}},
138+
... ],
139+
... )
140+
>>> print(response.output)
132141
"""
133142
if (scene is None or not scene) or (message is None or not message):
134143
raise InputRequired("scene and message is required!")

‎dashscope/aigc/generation.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,30 @@ def call( # pylint: disable=arguments-renamed,too-many-branches,too-many-statem
131131
Union[GenerationResponse,
132132
Generator[GenerationResponse, None, None]]: If
133133
stream is True, return Generator, otherwise GenerationResponse.
134+
135+
Examples:
136+
>>> from dashscope import Generation
137+
>>> response = Generation.call(
138+
... model="qwen-plus",
139+
... messages=[
140+
... {"role": "system", "content": "You are a helpful assistant."},
141+
... {"role": "user", "content": "Who are you?"},
142+
... ],
143+
... result_format="message",
144+
... )
145+
>>> print(response.output.choices[0].message.content)
146+
147+
Streaming output, printing only the newly generated tokens:
148+
149+
>>> responses = Generation.call(
150+
... model="qwen-plus",
151+
... messages=[{"role": "user", "content": "Write a haiku about the sea."}],
152+
... result_format="message",
153+
... stream=True,
154+
... incremental_output=True,
155+
... )
156+
>>> for response in responses:
157+
... print(response.output.choices[0].message.content, end="")
134158
"""
135159
if (prompt is None or not prompt) and (
136160
messages is None or not messages

‎dashscope/aigc/image_synthesis.py‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,19 @@ def call( # type: ignore[override]
114114
115115
Returns:
116116
ImageSynthesisResponse: The image(s) synthesis result.
117+
118+
Examples:
119+
>>> from http import HTTPStatus
120+
>>> from dashscope import ImageSynthesis
121+
>>> rsp = ImageSynthesis.call(
122+
... model="wanx2.1-t2i-turbo",
123+
... prompt="a flower shop with delicate windows and a wooden door",
124+
... n=1,
125+
... size="1024*1024",
126+
... )
127+
>>> if rsp.status_code == HTTPStatus.OK:
128+
... for result in rsp.output.results:
129+
... print(result.url)
117130
"""
118131
if size is not None:
119132
kwargs["size"] = size
@@ -186,9 +199,23 @@ def sync_call(
186199
color_palette: str = None,
187200
**kwargs,
188201
) -> ImageSynthesisResponse:
189-
"""
202+
"""Call image(s) synthesis and block until the result is returned
203+
directly (no async task polling).
204+
190205
Note: This method currently now only supports wan2.2-t2i-flash and wan2.2-t2i-plus. # noqa: E501 # pylint: disable=line-too-long
191206
Using other models will result in an error,More raw image models may be added for use later # pylint: disable=line-too-long
207+
208+
Examples:
209+
>>> from http import HTTPStatus
210+
>>> from dashscope import ImageSynthesis
211+
>>> rsp = ImageSynthesis.sync_call(
212+
... model="wan2.2-t2i-flash",
213+
... prompt="a flower shop with delicate windows and a wooden door",
214+
... n=1,
215+
... size="1024*1024",
216+
... )
217+
>>> if rsp.status_code == HTTPStatus.OK:
218+
... print(rsp.output)
192219
"""
193220
if size is not None:
194221
kwargs["size"] = size
@@ -782,9 +809,23 @@ async def sync_call(
782809
color_palette: str = None, # pylint: disable=unused-argument
783810
**kwargs,
784811
) -> ImageSynthesisResponse:
785-
"""
812+
"""Async coroutine version of ``ImageSynthesis.sync_call``.
813+
786814
Note: This method currently now only supports wan2.2-t2i-flash and wan2.2-t2i-plus. # noqa: E501 # pylint: disable=line-too-long
787815
Using other models will result in an error,More raw image models may be added for use later # pylint: disable=line-too-long
816+
817+
Examples:
818+
>>> import asyncio
819+
>>> from dashscope import AioImageSynthesis
820+
>>> async def main():
821+
... rsp = await AioImageSynthesis.sync_call(
822+
... model="wan2.2-t2i-flash",
823+
... prompt="a flower shop with delicate windows and a wooden door",
824+
... n=1,
825+
... size="1024*1024",
826+
... )
827+
... print(rsp.output)
828+
>>> asyncio.run(main())
788829
"""
789830
if size is not None:
790831
kwargs["size"] = size

‎dashscope/aigc/multimodal_conversation.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,35 @@ def call( # pylint: disable=arguments-renamed,too-many-branches,too-many-statem
101101
Union[MultiModalConversationResponse,
102102
Generator[MultiModalConversationResponse, None, None]]: If
103103
stream is True, return Generator, otherwise
104+
105+
Examples:
106+
Vision understanding, describing an image:
107+
108+
>>> from dashscope import MultiModalConversation
109+
>>> messages = [{
110+
... "role": "user",
111+
... "content": [
112+
... {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},
113+
... {"text": "What does this picture describe?"},
114+
... ],
115+
... }]
116+
>>> response = MultiModalConversation.call(
117+
... model="qwen-vl-max",
118+
... messages=messages,
119+
... )
120+
>>> print(response.output.choices[0].message.content[0]["text"])
121+
122+
Text-to-speech with a Qwen-TTS model (this class also serves as
123+
the entry point for qwen-tts models, taking ``text``/``voice``
124+
instead of ``messages``):
125+
126+
>>> response = MultiModalConversation.call(
127+
... model="qwen3-tts-flash",
128+
... text="Today is a wonderful day to build something people love!",
129+
... voice="Cherry",
130+
... language_type="English",
131+
... )
132+
>>> print(response.output.audio.url)
104133
"""
105134
if stream is not None:
106135
kwargs["stream"] = stream

‎dashscope/aigc/video_synthesis.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,34 @@ def call( # type: ignore[override]
138138
139139
Returns:
140140
VideoSynthesisResponse: The video synthesis result.
141+
142+
Examples:
143+
Text-to-video, blocking until the task completes:
144+
145+
>>> from http import HTTPStatus
146+
>>> from dashscope import VideoSynthesis
147+
>>> rsp = VideoSynthesis.call(
148+
... model="wan2.7-t2v",
149+
... prompt="a kitten running under the moonlight",
150+
... audio=True,
151+
... watermark=True,
152+
... )
153+
>>> if rsp.status_code == HTTPStatus.OK:
154+
... print(rsp.output.video_url)
155+
156+
Image-to-video, driving generation from a first-frame image:
157+
158+
>>> media = [{
159+
... "type": VideoSynthesis.MediaType.FIRST_FRAME,
160+
... "url": "https://wanx.alicdn.com/material/20250318/first_frame.png",
161+
... }]
162+
>>> rsp = VideoSynthesis.call(
163+
... model="wan2.7-i2v",
164+
... prompt="a kitten running under the moonlight",
165+
... media=media,
166+
... )
167+
>>> if rsp.status_code == HTTPStatus.OK:
168+
... print(rsp.output.video_url)
141169
"""
142170
if size is not None:
143171
kwargs["size"] = size
@@ -453,6 +481,19 @@ def async_call( # pylint: disable=arguments-renamed # type: ignore[override] #
453481
Returns:
454482
DashScopeAPIResponse: The video synthesis
455483
task id in the response.
484+
485+
Examples:
486+
Submit a task without blocking, then poll for the result with
487+
``wait`` (or ``fetch`` for a single non-blocking status check):
488+
489+
>>> from dashscope import VideoSynthesis
490+
>>> task = VideoSynthesis.async_call(
491+
... model="wan2.7-t2v",
492+
... prompt="a kitten running under the moonlight",
493+
... )
494+
>>> print(task.output.task_id)
495+
>>> rsp = VideoSynthesis.wait(task)
496+
>>> print(rsp.output.video_url)
456497
"""
457498
if size is not None:
458499
kwargs["size"] = size

‎dashscope/app/application.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,22 @@ def call( # type: ignore[override]
153153
Union[CompletionResponse,
154154
Generator[CompletionResponse, None, None]]: If
155155
stream is True, return Generator, otherwise GenerationResponse.
156+
157+
Examples:
158+
>>> from http import HTTPStatus
159+
>>> from dashscope import Application
160+
>>> responses = Application.call(
161+
... app_id="YOUR-APP-ID",
162+
... prompt="Summarize this file",
163+
... stream=True,
164+
... incremental_output=True,
165+
... file_list=["https://example.com/document.pdf"],
166+
... )
167+
>>> for response in responses:
168+
... if response.status_code != HTTPStatus.OK:
169+
... print(f"code={response.code}, message={response.message}")
170+
... else:
171+
... print(response.output.text, end="")
156172
"""
157173

158174
api_key, app_id = Application._validate_params(api_key, app_id)

‎dashscope/assistants/assistants.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,21 @@ def create(
201201
202202
Returns:
203203
Assistant: The `Assistant` object.
204+
205+
Examples:
206+
>>> from dashscope import Assistants, Threads, Runs
207+
>>> assistant = Assistants.create(
208+
... model="qwen-max",
209+
... name="smart helper",
210+
... description="A tool helper.",
211+
... instructions="You are a helpful assistant.",
212+
... )
213+
>>> thread = Threads.create(
214+
... messages=[{"role": "user", "content": "How do I make beef stew?"}],
215+
... )
216+
>>> run = Runs.create(thread.id, assistant_id=assistant.id)
217+
>>> run_status = Runs.wait(run.id, thread_id=thread.id)
218+
>>> print(run_status)
204219
"""
205220
warnings.warn(
206221
_DEPRECATION_MSG,

0 commit comments

Comments
 (0)