1
1
[ English] ( https://github.com/cnblogs/dashscope-sdk/blob/main/README.md ) | 简体中文
2
2
3
+ # Cnblogs.DashScopeSDK
4
+
3
5
[ ![ NuGet Version] ( https://img.shields.io/nuget/v/Cnblogs.DashScope.AI?style=flat&logo=nuget&label=Cnblogs.DashScope.AI )] ( https://www.nuget.org/packages/Cnblogs.DashScope.AI )
4
6
[ ![ NuGet Version] ( https://img.shields.io/nuget/v/Cnblogs.DashScope.Sdk?style=flat&logo=nuget&label=Cnblogs.DashScope.Sdk&link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FCnblogs.DashScope.Sdk )] ( https://www.nuget.org/packages/Cnblogs.DashScope.Sdk )
5
7
[ ![ NuGet Version] ( https://img.shields.io/nuget/v/Cnblogs.DashScope.AspNetCore?style=flat&logo=nuget&label=Cnblogs.DashScope.AspNetCore&link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FCnblogs.DashScope.AspNetCore )] ( https://www.nuget.org/packages/Cnblogs.DashScope.AspNetCore )
6
8
7
- # Cnblogs.DashScopeSDK
8
-
9
9
由博客园维护并使用的非官方灵积(百炼)服务 SDK。
10
10
11
11
使用前注意:当前项目正在积极开发中,小版本也可能包含破坏性更改,升级前请查看对应版本 Release Note 进行迁移。
12
12
13
- # 快速开始
13
+ ## 快速开始
14
14
15
- ## 使用 ` Microsoft.Extensions.AI ` 接口
15
+ ### 使用 ` Microsoft.Extensions.AI ` 接口
16
16
17
17
安装 NuGet 包 ` Cnblogs.DashScope.AI `
18
18
@@ -22,7 +22,7 @@ var completion = await client.CompleteAsync("hello");
22
22
Console .WriteLine (completion )
23
23
```
24
24
25
- ## 控制台应用
25
+ ### 控制台应用
26
26
27
27
安装 NuGet 包 ` Cnblogs.DashScope.Sdk ` 。
28
28
@@ -34,7 +34,7 @@ var completion = await client.GetQWenCompletionAsync(QWenLlm.QWenMax, prompt);
34
34
Console .WriteLine (completion .Output .Text );
35
35
```
36
36
37
- ## ASP.NET Core 应用
37
+ ### ASP.NET Core 应用
38
38
39
39
安装 NuGet 包 ` Cnblogs.DashScope.AspNetCore ` 。
40
40
@@ -64,70 +64,22 @@ public class YourService(IDashScopeClient client)
64
64
}
65
65
```
66
66
67
- # 支持的 API
67
+ ## 支持的 API
68
68
69
- - 通用文本向量 - ` GetTextEmbeddingsAsync() `
70
- - 通义千问(` qwen-turbo ` , ` qwen-max ` 等) - ` GetQWenCompletionAsync() ` 和 ` GetQWenCompletionStreamAsync() `
71
- - DeepSeek 系列模型(` deepseek-r1 ` ,` deepseek-v3 ` 等) - ` GetDeepSeekChatCompletionAsync() ` 和 ` GetDeepSeekChatCompletionStreamAsync() `
72
- - 百川开源大模型 - ` GetBaiChuanTextCompletionAsync() `
73
- - LLaMa2 大语言模型 - ` GetLlama2TextCompletionAsync() `
74
- - 通义千问 VL 和通义千问 Audio(` qwen-vl-max ` , ` qwen-audio ` ) - ` GetQWenMultimodalCompletionAsync() ` 和 ` GetQWenMultimodalCompletionStreamAsync() `
75
- - 通义万相系列
76
- - 文生图 - ` CreateWanxImageSynthesisTaskAsync() ` 和 ` GetWanxImageSynthesisTaskAsync() `
77
- - 人像风格重绘 - ` CreateWanxImageGenerationTaskAsync() ` 和 ` GetWanxImageGenerationTaskAsync() `
78
- - 图像背景生成 - ` CreateWanxBackgroundGenerationTaskAsync() ` 和 ` GetWanxBackgroundGenerationTaskAsync() `
79
- - 适用于 QWen-Long 的文件 API ` UploadFileAsync() ` 和 ` DeleteFileAsync `
80
- - 应用调用 ` GetApplicationResponseAsync ` 和 ` GetApplicationResponseStreamAsync() `
81
- - 其他使用相同 Endpoint 的模型
69
+ - [ 对话] ( #对话 ) - QWen3, DeepSeek 等,支持推理/工具调用/网络搜索/翻译等场景
70
+ - [ 多模态] ( #多模态 ) - QWen-VL,QVQ 等,支持推理/视觉理解/OCR/音频理解等场景
71
+ - [ 语音合成] ( #语音合成 ) - CosyVoice,Sambert 等,支持 TTS 等应用场景
72
+ - [ 图像生成] ( #图像生成 ) - wanx2.1 等,支持文生图,人像风格重绘等应用场景
73
+ - [ 应用调用] ( #应用调用 )
74
+ - [ 文本向量] ( #文本向量 )
82
75
83
- # 示例
84
-
85
- 查看 [ 快照文件] ( ./test/Cnblogs.DashScope.Tests.Shared/Utils/Snapshots.cs ) 获得 API 调用参数示例.
86
-
87
- 查看 [ 测试] ( ./test ) 获得更多 API 使用示例。
88
-
89
- ## 文本生成
76
+ ### 对话
90
77
91
78
使用 ` dashScopeClient.GetTextCompletionAsync ` 和 ` dashScopeClient.GetTextCompletionStreamAsync ` 来直接访问文本生成接口。
92
79
93
- 相关文档:https://help.aliyun.com/zh/model-studio/user-guide/text-generation/
94
-
95
- ``` csharp
96
- var completion = await dashScopeClient .GetTextCompletionAsync (
97
- new ModelRequest <TextGenerationInput , ITextGenerationParameters >
98
- {
99
- Model = " your-model-name" ,
100
- Input = new TextGenerationInput { Prompt = prompt },
101
- Parameters = new TextGenerationParameters ()
102
- {
103
- // control parameters as you wish.
104
- EnableSearch = true
105
- }
106
- });
107
-
108
- var completions = dashScopeClient .GetTextCompletionStreamAsync (
109
- new ModelRequest <TextGenerationInput , ITextGenerationParameters >
110
- {
111
- Model = " your-model-name" ,
112
- Input = new TextGenerationInput { Messages = [TextChatMessage .System (" you are a helpful assistant" ), TextChatMessage .User (" How are you?" )] },
113
- Parameters = new TextGenerationParameters ()
114
- {
115
- // control parameters as you wish.
116
- EnableSearch = true ,
117
- IncreamentalOutput = true
118
- }
119
- });
120
- ```
121
-
122
- ## 单轮对话
80
+ 针对通义千问和 DeekSeek,我们提供了快捷方法进行调用: ` GetQWenChatCompletionAsync ` /` GetDeepSeekChatCompletionAsync `
123
81
124
- ``` csharp
125
- var prompt = " 你好"
126
- var completion = await client .GetQWenCompletionAsync (QWenLlm .QWenMax , prompt );
127
- Console .WriteLine (completion .Output .Text );
128
- ```
129
-
130
- ## 多轮对话
82
+ 相关文档:https://help.aliyun.com/zh/model-studio/user-guide/text-generation/
131
83
132
84
``` csharp
133
85
var history = new List <ChatMessage >
@@ -144,7 +96,7 @@ var completion = await client.GetQWenChatCompletionAsync(QWenLlm.QWenMax, histor
144
96
Console .WriteLine (completion .Output .Choices [0 ].Message .Content ); // The number is 42
145
97
```
146
98
147
- ## 推理
99
+ #### 推理
148
100
149
101
使用推理模型时,模型的思考过程可以通过 ` ReasoningContent ` 属性获取。
150
102
@@ -157,9 +109,7 @@ var completion = await client.GetDeepSeekChatCompletionAsync(DeepSeekLlm.DeepSee
157
109
Console .WriteLine (completion .Output .Choices [0 ]! .Message .ReasoningContent );
158
110
```
159
111
160
- ### QWen3
161
-
162
- 使用 ` TextGenerationParameters.EnableThinking ` 决定是否使用模型的推理能力。
112
+ 对于支持的模型(例如 qwen3),可以使用 ` TextGenerationParameters.EnableThinking ` 决定是否使用模型的推理能力。
163
113
164
114
``` csharp
165
115
var stream = dashScopeClient
@@ -174,7 +124,7 @@ var stream = dashScopeClient
174
124
});
175
125
```
176
126
177
- ## 工具调用
127
+ #### 工具调用
178
128
179
129
创建一个可供模型使用的方法。
180
130
@@ -241,9 +191,9 @@ Console.WriteLine(completion.Output.Choice[0].Message.Content) // 现在浙江
241
191
242
192
当模型认为应当调用工具时,返回消息中 ` ToolCalls ` 会提供调用的详情,本地在调用完成后可以把结果以 ` tool ` 角色返回。
243
193
244
- ## 上传文件(QWen-Long )
194
+ #### 上传文件(qwen-long )
245
195
246
- 需要先提前将文件上传到 DashScope 来获得 Id。
196
+ 使用长上下文模型时, 需要先提前将文件上传到 DashScope 来获得 Id。
247
197
248
198
``` csharp
249
199
var file = new FileInfo (" test.txt" );
@@ -272,7 +222,162 @@ Console.WriteLine(completion.Output.Choices[0].Message.Content);
272
222
var deletionResult = await dashScopeClient .DeleteFileAsync (uploadedFile .Id );
273
223
```
274
224
275
- ## 应用调用
225
+ ### 多模态
226
+
227
+ 使用 ` dashScopeClient.GetMultimodalGenerationAsync ` 和 ` dashScopeClient.GetMultimodalGenerationStreamAsync ` 来访问多模态文本生成接口。
228
+
229
+ 相关文档:[ 多模态_大模型服务平台百炼(Model Studio)-阿里云帮助中心] ( https://help.aliyun.com/zh/model-studio/multimodal )
230
+
231
+ #### 视觉理解/推理
232
+
233
+ 使用 ` MultimodalMessage.User() ` 可以快速创建对应角色的消息。
234
+
235
+ 媒体内容可以通过公网 URL 或者 ` byte[] ` 传入。
236
+
237
+ ``` csharp
238
+ var image = await File .ReadAllBytesAsync (" Lenna.jpg" );
239
+ var response = dashScopeClient .GetMultimodalGenerationStreamAsync (
240
+ new ModelRequest <MultimodalInput , IMultimodalParameters >()
241
+ {
242
+ Model = " qvq-plus" ,
243
+ Input = new MultimodalInput ()
244
+ {
245
+ Messages =
246
+ [
247
+ MultimodalMessage .User (
248
+ [
249
+ MultimodalMessageContent .ImageContent (image , " image/jpeg" ),
250
+ MultimodalMessageContent .TextContent (" 她是谁?" )
251
+ ])
252
+ ]
253
+ },
254
+ Parameters = new MultimodalParameters { IncrementalOutput = true , VlHighResolutionImages = false }
255
+ });
256
+
257
+ // output
258
+ var reasoning = false ;
259
+ await foreach (var modelResponse in response )
260
+ {
261
+ var choice = modelResponse .Output .Choices .FirstOrDefault ();
262
+ if (choice != null )
263
+ {
264
+ if (choice .FinishReason != " null" )
265
+ {
266
+ break ;
267
+ }
268
+
269
+ if (string .IsNullOrEmpty (choice .Message .ReasoningContent ) == false )
270
+ {
271
+ if (reasoning == false )
272
+ {
273
+ reasoning = true ;
274
+ Console .WriteLine (" <think>" );
275
+ }
276
+
277
+ Console .Write (choice .Message .ReasoningContent );
278
+ continue ;
279
+ }
280
+
281
+ if (reasoning )
282
+ {
283
+ reasoning = false ;
284
+ Console .WriteLine (" </think>" );
285
+ }
286
+
287
+ Console .Write (choice .Message .Content [0 ].Text );
288
+ }
289
+ }
290
+ ```
291
+
292
+ ### 语音合成
293
+
294
+ 通过 ` dashScopeClient.CreateSpeechSynthesizerSocketSessionAsync() ` 来创建一个语音合成会话。
295
+
296
+ ** 注意:使用 using 语句来自动释放会话,或者手动 Dispose 会话,尽量不要重用会话。**
297
+
298
+ 相关文档:[ 语音合成-CosyVoice_大模型服务平台百炼(Model Studio)-阿里云帮助中心] ( https://help.aliyun.com/zh/model-studio/cosyvoice-large-model-for-speech-synthesis )
299
+
300
+ ``` csharp
301
+ using var tts = await dashScopeClient .CreateSpeechSynthesizerSocketSessionAsync (" cosyvoice-v2" );
302
+ var taskId = await tts .RunTaskAsync (
303
+ new SpeechSynthesizerParameters { Voice = " longxiaochun_v2" , Format = " mp3" });
304
+ await tts .ContinueTaskAsync (taskId , " 博客园" );
305
+ await tts .ContinueTaskAsync (taskId , " 代码改变世界" );
306
+ await tts .FinishTaskAsync (taskId );
307
+ var file = new FileInfo (" tts.mp3" );
308
+ using var stream = file .OpenWrite ();
309
+ await foreach (var b in tts .GetAudioAsync ())
310
+ {
311
+ stream .WriteByte (b );
312
+ }
313
+
314
+ stream .Close ();
315
+
316
+ var tokenUsage = 0 ;
317
+ await foreach (var message in tts .GetMessagesAsync ())
318
+ {
319
+ if (message .Payload .Usage ? .Characters > tokenUsage )
320
+ {
321
+ tokenUsage = message .Payload .Usage .Characters ;
322
+ }
323
+ }
324
+
325
+ Console .WriteLine ($" audio saved to {file .FullName }, token usage: {tokenUsage }" );
326
+ break ;
327
+ ```
328
+
329
+ ### 图像生成
330
+
331
+ #### 文生图
332
+
333
+ 我们针对通义万相提供了快捷 API ` dashScopeClient.CreateWanxImageSynthesisTaskAsync() ` 和 ` GetWanxImageSynthesisTaskAsync() ` 。
334
+
335
+ 图片生成需要数秒到数十秒不等,对于 HTTP 请求来说太长,需要通过任务方式生成。
336
+
337
+ 先使用 ` CreateWanxImageSynthesisTaskAsync() ` 创建任务,再轮询 ` GetWanxImageSynthesisTaskAsync() ` 检查任务完成状态。
338
+
339
+ 相关文档:[ 通义万相2.1文生图V2版API参考_大模型服务平台百炼(Model Studio)-阿里云帮助中心] ( https://help.aliyun.com/zh/model-studio/text-to-image-v2-api-reference )
340
+
341
+ ``` csharp
342
+ var prompt = Console .ReadLine ();
343
+ var task = await dashScopeClient .CreateWanxImageSynthesisTaskAsync (
344
+ WanxModel .WanxV21Turbo ,
345
+ prompt ,
346
+ null ,
347
+ new ImageSynthesisParameters { Style = ImageStyles .OilPainting });
348
+ Console .WriteLine ($" Task({task .TaskId }) submitted, checking status..." );
349
+ var watch = Stopwatch .StartNew ();
350
+ while (watch .Elapsed .TotalSeconds < 120 )
351
+ {
352
+ var result = await dashScopeClient .GetWanxImageSynthesisTaskAsync (task .TaskId );
353
+ Console .WriteLine ($" {watch .ElapsedMilliseconds }ms - Status: {result .Output .TaskStatus }" );
354
+ if (result .Output .TaskStatus == DashScopeTaskStatus .Succeeded )
355
+ {
356
+ Console .WriteLine ($" Image generation finished, URL: {result .Output .Results ! [0 ].Url }" );
357
+ return ;
358
+ }
359
+
360
+ if (result .Output .TaskStatus == DashScopeTaskStatus .Failed )
361
+ {
362
+ Console .WriteLine ($" Image generation failed, error message: {result .Output .Message }" );
363
+ return ;
364
+ }
365
+
366
+ await Task .Delay (500 );
367
+ }
368
+
369
+ Console .WriteLine ($" Task timout, taskId: {task .TaskId }" );
370
+ ```
371
+
372
+ #### 人像风格重绘和图像背景生成
373
+
374
+ 与文生图类似,先创建任务,再轮询状态。
375
+
376
+ 人像风格重绘 - ` CreateWanxImageGenerationTaskAsync ` 和 ` GetWanxImageGenerationTaskAsync `
377
+
378
+ 图像背景生成 - ` CreateWanxBackgroundGenerationTaskAsync ` 和 ` GetWanxBackgroundGenerationTaskAsync `
379
+
380
+ ### 应用调用
276
381
277
382
` GetApplicationResponseAsync ` 用于进行应用调用。
278
383
@@ -339,3 +444,25 @@ var request =
339
444
var response = await client .GetApplicationResponseAsync (" your-application-id" , request );
340
445
Console .WriteLine (response .Output .Text );
341
446
```
447
+
448
+ ### 文本向量
449
+
450
+ 使用 ` GetTextEmbeddingsAsync ` 来调用文本向量接口。
451
+
452
+ 相关文档:[ 通用文本向量同步接口API详情_大模型服务平台百炼(Model Studio)-阿里云帮助中心] ( https://help.aliyun.com/zh/model-studio/text-embedding-synchronous-api )
453
+
454
+ ``` csharp
455
+ var text = Console .ReadLine ();
456
+ var response = await dashScopeClient .GetTextEmbeddingsAsync (
457
+ TextEmbeddingModel .TextEmbeddingV4 ,
458
+ [text ],
459
+ new TextEmbeddingParameters () { Dimension = 512 , });
460
+ var array = response .Output .Embeddings .First ().Embedding ;
461
+ Console .WriteLine (" Embedding" );
462
+ Console .WriteLine (string .Join ('\n ' , array ));
463
+ Console .WriteLine ($" Token usage: {response .Usage ? .TotalTokens }" );
464
+ ```
465
+
466
+ 查看 [ 快照文件] ( ./test/Cnblogs.DashScope.Tests.Shared/Utils/Snapshots.cs ) 获得 API 调用参数示例.
467
+
468
+ 查看 [ 测试] ( ./test ) 获得更多 API 使用示例。
0 commit comments