- Notifications
You must be signed in to change notification settings - Fork8
An unofficial DashScope SDK for .NET maintained by Cnblogs.
License
cnblogs/dashscope-sdk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
English |简体中文
A non-official DashScope (Bailian) service SDK maintained by Cnblogs.
Note: This project is actively under development. Breaking changes may occur even in minor versions. Please review the Release Notes before upgrading.
Install NuGet packageCnblogs.DashScope.AI
varclient=newDashScopeClient("your-api-key").AsChatClient("qwen-max");varcompletion=awaitclient.CompleteAsync("hello");Console.WriteLine(completion)
Install NuGet packageCnblogs.DashScope.Sdk
varclient=newDashScopeClient("your-api-key");varcompletion=awaitclient.GetQWenCompletionAsync(QWenLlm.QWenMax,prompt);// Or use model name string// var completion = await client.GetQWenCompletionAsync("qwen-max", prompt);Console.WriteLine(completion.Output.Text);
Install NuGet packageCnblogs.DashScope.AspNetCore
Program.cs
builder.AddDashScopeClient(builder.Configuration);
appsettings.json
{"DashScope": {"ApiKey":"your-api-key" }}Application class:
publicclassYourService(IDashScopeClientclient){publicasyncTask<string>CompletePromptAsync(stringprompt){varcompletion=awaitclient.GetQWenCompletionAsync(QWenLlm.QWenMax,prompt);returncompletion.Output.Text;}}
- Chat - QWen3, DeepSeek, etc. Supports reasoning, tool calling, web search, translation
- Multimodal - QWen-VL, QVQ, etc. Supports reasoning, visual understanding, OCR, audio understanding
- Text-to-Speech (TTS) - CosyVoice, Sambert
- Image Generation - Wanx2.1 (text-to-image, portrait style transfer)
- Application Call
- Text Vectorization
UseGetTextCompletionAsync/GetTextCompletionStreamAsync for direct text generation.For QWen and DeepSeek, use shortcuts:GetQWenChatCompletionAsync/GetDeepSeekChatCompletionAsync
varhistory=newList<ChatMessage>{ChatMessage.User("Please remember this number, 42"),ChatMessage.Assistant("I have remembered this number."),ChatMessage.User("What was the number I metioned before?")}varparameters=newTextGenerationParameters(){ResultFormat=ResultFormats.Message};varcompletion=awaitclient.GetQWenChatCompletionAsync(QWenLlm.QWenMax,history,parameters);Console.WriteLine(completion.Output.Choices[0].Message.Content);// The number is 42
Access model thoughts viaReasoningContent property
varhistory=newList<TextChatMessage>{TextChatMessage.User("Calculate 1+1")};varcompletion=awaitclient.GetDeepSeekChatCompletionAsync(DeepSeekLlm.DeepSeekR1,history);Console.WriteLine(completion.Output.Choices[0]!.Message.ReasoningContent);
For QWen3 models, enable reasoning withTextGenerationParameters.EnableThinking
varstream=dashScopeClient.GetQWenChatStreamAsync(QWenLlm.QWenPlusLatest,history,newTextGenerationParameters{IncrementalOutput=true,ResultFormat=ResultFormats.Message,EnableThinking=true});
Define a function for model to use:
stringGetCurrentWeather(GetCurrentWeatherParametersparameters){return"Sunny";}publicrecordGetCurrentWeatherParameters([property:Required][property:Description("City and state, e.g. San Francisco, CA")]stringLocation,[property:JsonConverter(typeof(EnumStringConverter<TemperatureUnit>))]TemperatureUnitUnit=TemperatureUnit.Celsius);publicenumTemperatureUnit{Celsius,Fahrenheit}
Invoke with tool definitions. We usingJsonSchema.Net for example, you could use any other library to generate JSON schema)
vartools=newList<ToolDefinition>{new(ToolTypes.Function,newFunctionDefinition(nameof(GetCurrentWeather),"Get current weather",newJsonSchemaBuilder().FromType<GetCurrentWeatherParameters>().Build()))};varhistory=newList<ChatMessage>{ChatMessage.User("What's the weather in CA?")};varparameters=newTextGenerationParameters{ResultFormat=ResultFormats.Message,Tools=tools};// request modelvarcompletion=awaitclient.GetQWenChatCompletionAsync(QWenLlm.QWenMax,history,parameters);Console.WriteLine(completion.Output.Choice[0].Message.ToolCalls[0].Function.Name);// GetCurrentWeatherhistory.Add(completion.Output.Choice[0].Message);// calls toolvarresult=GetCurrentWeather(new(){Location="CA"});history.Add(new("tool",result,nameof(GetCurrentWeather)));// Get final answercompletion=awaitclient.GetQWenChatCompletionAsync(QWenLlm.QWenMax,history,parameters);Console.WriteLine(completion.Output.Choices[0].Message.Content);// "Current weather in California: Sunny"
For Qwen-Long models:
varfile=newFileInfo("test.txt");varuploadedFile=awaitdashScopeClient.UploadFileAsync(file.OpenRead(),file.Name);varhistory=newList<ChatMessage>{ChatMessage.File(uploadedFile.Id)};varcompletion=awaitclient.GetQWenChatCompletionAsync(QWenLlm.QWenLong,history);Console.WriteLine(completion.Output.Choices[0].Message.Content);// CleanupawaitdashScopeClient.DeleteFileAsync(uploadedFile.Id);
UseGetMultimodalGenerationAsync/GetMultimodalGenerationStreamAsyncOfficial Documentation
varimage=awaitFile.ReadAllBytesAsync("Lenna.jpg");varresponse=dashScopeClient.GetMultimodalGenerationStreamAsync(newModelRequest<MultimodalInput,IMultimodalParameters>(){Model="qvq-plus",Input=newMultimodalInput(){Messages=[MultimodalMessage.User([MultimodalMessageContent.ImageContent(image,"image/jpeg"),MultimodalMessageContent.TextContent("她是谁?")])]},Parameters=newMultimodalParameters{IncrementalOutput=true,VlHighResolutionImages=false}});// outputvarreasoning=false;awaitforeach(varmodelResponseinresponse){varchoice=modelResponse.Output.Choices.FirstOrDefault();if(choice!=null){if(choice.FinishReason!="null"){break;}if(string.IsNullOrEmpty(choice.Message.ReasoningContent)==false){if(reasoning==false){reasoning=true;Console.WriteLine("<think>");}Console.Write(choice.Message.ReasoningContent);continue;}if(reasoning){reasoning=false;Console.WriteLine("</think>");}Console.Write(choice.Message.Content[0].Text);}}
Create a speech synthesis session usingdashScopeClient.CreateSpeechSynthesizerSocketSessionAsync().
Note: Use the using statement to automatically dispose the session, or manually call Dispose() to release resources. Avoid reusing sessions.
Create a synthesis session:
usingvartts=awaitdashScopeClient.CreateSpeechSynthesizerSocketSessionAsync("cosyvoice-v2");vartaskId=awaittts.RunTaskAsync(newSpeechSynthesizerParameters{Voice="longxiaochun_v2",Format="mp3"});awaittts.ContinueTaskAsync(taskId,"Cnblogs");awaittts.ContinueTaskAsync(taskId,"Code changes the world");awaittts.FinishTaskAsync(taskId);varfile=newFileInfo("tts.mp3");usingvarstream=file.OpenWrite();awaitforeach(varbintts.GetAudioAsync()){stream.WriteByte(b);}Console.WriteLine($"Audio saved to{file.FullName}");
Use shortcuts for Wanx models:
vartask=awaitdashScopeClient.CreateWanxImageSynthesisTaskAsync(WanxModel.WanxV21Turbo,"A futuristic cityscape at sunset",newImageSynthesisParameters{Style=ImageStyles.OilPainting});// Pull statuswhile(true){varresult=awaitdashScopeClient.GetWanxImageSynthesisTaskAsync(task.TaskId);if(result.Output.TaskStatus==DashScopeTaskStatus.Succeeded){Console.WriteLine($"Image URL:{result.Output.Results[0].Url}");break;}awaitTask.Delay(500);}
UseCreateWanxImageGenerationTaskAsync andGetWanxImageGenerationTaskAsync
UseCreateWanxBackgroundGenerationTaskAsync andGetWanxBackgroundGenerationTaskAsync
varrequest=newApplicationRequest(){Input=newApplicationInput(){Prompt="Summarize this file."},Parameters=newApplicationParameters(){TopK=100,TopP=0.8f,Seed=1234,Temperature=0.85f,RagOptions=newApplicationRagOptions(){PipelineIds=["thie5bysoj"],FileIds=["file_d129d632800c45aa9e7421b30561f447_10207234"]}}};varresponse=awaitclient.GetApplicationResponseAsync("your-application-id",request);Console.WriteLine(response.Output.Text);
ApplicationRequest usesDictionary<string, object?> as the default type forBizParams.
varrequest=newApplicationRequest(){Input=newApplicationInput(){Prompt="Summarize this file.",BizParams=newDictionary<string,object?>(){{"customKey1","custom-value"}}}};varresponse=awaitclient.GetApplicationResponseAsync("your-application-id",request);Console.WriteLine(response.Output.Text);
For strong typing support, you can use the generic classApplicationRequest<TBizParams>.Note that the SDK usessnake_case for JSON serialization. If your application uses different naming conventions, manually specify the serialized property names using[JsonPropertyName("camelCase")].
publicrecordTestApplicationBizParam([property:JsonPropertyName("sourceCode")]stringSourceCode);varrequest=newApplicationRequest<TestApplicationBizParam>(){Input=newApplicationInput<TestApplicationBizParam>(){Prompt="Summarize this file.",BizParams=newTestApplicationBizParam("test")}};varresponse=awaitclient.GetApplicationResponseAsync("your-application-id",request);Console.WriteLine(response.Output.Text);
vartext="Sample text for embedding";varresponse=awaitdashScopeClient.GetTextEmbeddingsAsync(TextEmbeddingModel.TextEmbeddingV4,[text],newTextEmbeddingParameters{Dimension=512});varembedding=response.Output.Embeddings.First().Embedding;Console.WriteLine($"Embedding vector length:{embedding.Length}");
SeeSnapshot Files for API parameter examples.
ReviewTests for comprehensive usage examples.
About
An unofficial DashScope SDK for .NET maintained by Cnblogs.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.