Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

An unofficial DashScope SDK for .NET maintained by Cnblogs.

License

NotificationsYou must be signed in to change notification settings

cnblogs/dashscope-sdk

Repository files navigation

English |简体中文

Cnblogs.DashScopeSDK

NuGet VersionNuGet VersionNuGet Version

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.

Quick Start

UsingMicrosoft.Extensions.AI Interface

Install NuGet packageCnblogs.DashScope.AI

varclient=newDashScopeClient("your-api-key").AsChatClient("qwen-max");varcompletion=awaitclient.CompleteAsync("hello");Console.WriteLine(completion)

Console Application

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);

ASP.NET Core Application

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;}}

Supported APIs

Chat

UseGetTextCompletionAsync/GetTextCompletionStreamAsync for direct text generation.For QWen and DeepSeek, use shortcuts:GetQWenChatCompletionAsync/GetDeepSeekChatCompletionAsync

Official Documentation

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

Reasoning

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});

Tool Calling

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"

File Upload (Long Context Models)

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);

Multimodal

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);}}

Text-to-Speech

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}");

Image Generation

Text-to-Image

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);}

Portrait Style Transfer

UseCreateWanxImageGenerationTaskAsync andGetWanxImageGenerationTaskAsync

Background Generation

UseCreateWanxBackgroundGenerationTaskAsync andGetWanxBackgroundGenerationTaskAsync

Application Call

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);

Text Vectorization

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

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp