cnblogs/dashscope-sdk
关于
An unofficial DashScope( SDK for .NET maintained by Cnblogs.
开发工具实测星标增长
- 24小时
- 0
- 7天
- 正在收集历史
- 15天
- 正在收集历史
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文Cnblogs.DashScopeSDK
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
Console Application
Install NuGet package Cnblogs.DashScope.Sdk
// The SDK defaults to the Beijing region, pass region if your API key belongs to another region
var client = new DashScopeClient("your-api-key", region: DashScopeRegion.Singapore);
var completion = await client.GetTextCompletionAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput()
{
Messages = new List<TextChatMessage>()
{
TextChatMessage.System("You are a helpful assistant"),
TextChatMessage.User("你是谁?")
}
},
Parameters = new TextGenerationParameters() { ResultFormat = "message" }
});
Console.WriteLine(completion.Output.Choices![0].Message.Content)
ASP.NET Core Application
Install NuGet package Cnblogs.DashScope.AspNetCore
Program.cs
builder.AddDashScopeClient(builder.Configuration);
appsettings.json
{
"DashScope": {
"ApiKey": "your-api-key",
"RegionId": "ap-southeast-1"
}
}
Application class:
public class YourService(IDashScopeClient client)
{
public async Task<string> CompletePromptAsync(string prompt)
{
var completion = await client.GetTextCompletionAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput()
{
Messages = new List<TextChatMessage>()
{
TextChatMessage.System("You are a helpful assistant"),
TextChatMessage.User("你是谁?")
}
},
Parameters = new TextGenerationParameters() { ResultFormat = "message" }
});
return completion.Output.Choices![0].Message.Content
}
}
Using Microsoft.Extensions.AI Interface
Install NuGet package Cnblogs.DashScope.AI
var client = new DashScopeClient("your-api-key", region: DashScopeRegion.Singapore).AsChatClient("qwen-max");
var completion = await client.GetResponseAsync("hello");
Console.WriteLine(completion.Text);
IChatClient picks the endpoint and the max token parameter by the model of each request (ChatOptions.ModelId, or the model passed to AsChatClient()):
- Endpoint: the models of the multimodal whitelist (qwen3.5 / qwen3.6 series, qwen3.7-plus / qwen3.7-flash, qwen3.8 and later series, qwen3-vl, qwen3-omni, gui-plus, kimi-k2.5 and later kimi models, deepseek-v4.1 and later deepseek models) are called via the multimodal API (
MultimodalParameters), all the other models (e.g. qwen-plus, qwen-max, qwen3.7-max, deepseek-v4-pro, glm-5.3) via the text API (TextGenerationParameters), including the models supplied directly by third parties (e.g.xiaomi/mimo-v2.6-pro-ultraspeed) even when they accept images. Calling the wrong one fails with 400 "url error", and the endpoint does not follow the model version: qwen3.7-max is a text model, qwen3.8-max is a multimodal one. ChatOptions.MaxOutputTokensis sent asmax_completion_tokensfor the models that read it (qwen3.5 and later series, qwen-mt, tongyi-xiaomi-analysis, deepseek-v4-pro and later deepseek models, glm-5.x, kimi-k2.5 and later kimi models, MiniMax-M2.5), which limits the reasoning output and the answer together. It is sent asmax_tokensfor all the other models (e.g. qwen-plus, qwen-max, qwen3-vl-plus, gui-plus), because they silently ignoremax_completion_tokens;max_tokenslimits the answer only on thinking models.
Set AdditionalProperties["useVl"] / AdditionalProperties["useMaxCompletionTokens"] to true / false to force the mapping, e.g. when a new model appears before the whitelist is updated.
The endpoint can also be fixed for every request of a chat client: AsChatClient(modelId, useVl) takes a non-nullable bool, true for the multimodal API and false for the text API. Leave the argument out, or pass null as the options of AsChatClient(modelId, options), to decide it by the model.
The endpoint whitelist is shipped with the SDK, so it can lag behind the models the service releases. To pick the endpoint by what the service reports instead, turn on AutoSyncModelList through AsChatClient(modelId, options): a model is looked up in the model list (GET /api/v1/models?model=<modelId>) the first time it is used, and it goes to the multimodal API when the service lists it with the VU or Multimodal-Omni capability and Bailian hosts it (except for qwen3.8-2.4t-a95b: the service lists it as a text model although the multimodal API serves it, the SDK corrects that). The looked up models are cached for the lifetime of the process and shared by every chat client of it, so each model costs one extra request per process. When the service does not list the model, or the lookup fails, the chat requests go on with the whitelist and the model is not looked up again for a minute. Nothing is requested when the option is off, or when useVl already decides the endpoint.
var chatClient = dashScopeClient.AsChatClient(
"qwen3.7-plus",
new DashScopeChatClientOptions(AutoSyncModelList: true));
Telemetry
The chat client, the embedding generator, the text-to-speech client, the speech-to-text client, the realtime client and the image generator describe themselves to the M.E.AI telemetry and logging pipelines with a ChatClientMetadata / EmbeddingGeneratorMetadata / TextToSpeechClientMetadata / SpeechToTextClientMetadata / ChatClientMetadata / ImageGeneratorMetadata (the realtime client has no metadata type of its own, its sessions answer GetService<ChatClientMetadata>() as well): the provider name dashscope, the endpoint of the client, the default model and, for embeddings, the default dimensions. They are also returned by GetService<ChatClientMetadata>() / GetService<EmbeddingGeneratorMetadata>() / GetService<TextToSpeechClientMetadata>() / GetService<SpeechToTextClientMetadata>() / GetService<ImageGeneratorMetadata>(). A pipeline built with UseOpenTelemetry() reports them as gen_ai.provider.name, gen_ai.request.model, server.address and server.port (plus gen_ai.embeddings.dimension.count for embeddings):
var chatClient = client.AsChatClient("qwen-plus").AsBuilder().UseOpenTelemetry().Build();
var generator = client.AsEmbeddingGenerator("text-embedding-v4", 1024).AsBuilder().UseOpenTelemetry().Build();
var ttsClient = client.AsTextToSpeechClient("cosyvoice-v2").AsBuilder().UseOpenTelemetry().Build();
var sttClient = client.AsSpeechToTextClient("paraformer-realtime-v2").AsBuilder().UseOpenTelemetry().Build();
var realtimeClient = client.AsRealtimeClient("qwen3.8-omni-flash-realtime").AsBuilder().UseOpenTelemetry().Build();
var imageGenerator = client.AsImageGenerator("qwen-image-3.0").AsBuilder().UseOpenTelemetry().Build();
ToolCall
var chatClient = client.AsChatClient("qwen-turbo").AsBuilder().UseFunctionInvocation().Build();
var options = new ChatOptions()
{
Tools = [AIFunctionFactory.Create(GetWeather)],
ToolMode = new AutoChatToolMode(),
AllowMultipleToolCalls = true,
};
var stream = chatClient.GetStreamingResponseAsync("What's weather today?", options);
await foreach (var chatResponseUpdate in stream)
{
Console.Write(chatResponseUpdate);
}
Web search
Add a HostedWebSearchTool to Tools to let the model search the web (the enable_search parameter, billed per search). The search results come back as CitationAnnotations on the first TextContent of the message, on a dedicated TextContent when the answer has no text:
var options = new ChatOptions { Tools = [new HostedWebSearchTool()] };
var response = await chatClient.GetResponseAsync("杭州西湖最近有什么新闻?", options);
foreach (var citation in response.Messages[0].Contents.OfType<TextContent>().First().Annotations?.OfType<CitationAnnotation>() ?? [])
{
Console.WriteLine($"{citation.Title}: {citation.Url}");
}
The service returns the sources only when asked (search_options.enable_source), so the SDK asks for them unless SearchOptions.EnableSource is false. To refine the search, pass a SearchOptions in the SearchOptions additional property of the tool, the way other providers read the settings of a hosted tool; the options are sent as search_options (strategy, forced search, sites, time range ...):
var options = new ChatOptions
{
Tools =
[
new HostedWebSearchTool(new Dictionary<string, object?>
{
["SearchOptions"] = new SearchOptions { SearchStrategy = SearchStrategies.Max, ForcedSearch = true }
})
]
};
With SearchOptions.EnableCitation on, the model marks the passages it draws from a search result with [1] or [ref_1] (the index of the result), and the citations carry AnnotatedRegions pointing at those markers. In the streaming mode the citations arrive with the first update that carries the search results; with EnableCitation on they arrive in an update after the last text update instead, because a marker may be split across updates and its position in the answer is only known then.
HostedWebSearchTool and its SearchOptions are not mapped when the raw parameters (see below) are set: the raw parameters are sent as they are.
Hosted files
AsHostedFileClient() returns an IHostedFileClient over the OpenAI compatible file API of DashScope (/compatible-mode/v1/files). The hosted file client of Microsoft.Extensions.AI is experimental, suppress the MEAI001 diagnostic to use it:
var fileClient = dashScopeClient.AsHostedFileClient();
using var stream = File.OpenRead("doc.pdf");
var file = await fileClient.UploadAsync(stream, "application/pdf", "doc.pdf");
foreach (var hostedFile in await fileClient.ListFilesAsync(new HostedFileClientOptions { Limit = 10 }))
{
Console.WriteLine($"{hostedFile.FileId}: {hostedFile.Name} ({hostedFile.Purpose})");
}
await using var content = await fileClient.DownloadAsync(file.FileId);
await fileClient.DeleteAsync(file.FileId);
- An upload needs a purpose,
file-extractis used whenHostedFileClientOptions.Purposeis left out (the other ones arebatchandfine-tune). The stream passed toUploadAsyncis left open, and the service detects the type of the file itself: the media type only names the result and the extension of a generated file name. IHostedFileClient.DownloadAsynccallsDownloadFileAsync, which serves every stored file: the result files of batch jobs (batch_output) come from the content endpoint, every other file from the download link of its detail (GetFileAsync), which the native file API serves in the Beijing region only. The link is a signed url of the file storage, it is requested by an HTTP client of its own that carries no api key (the named clientCnblogs.DashScope.FileStoragewith ASP.NET Core).- DashScope keeps the files of an account in one storage,
HostedFileClientOptions.Scopehas no effect. The storage holds at most 10000 files and 100 GB, files that are not deleted count against both.
Reference an uploaded file in a chat request with a HostedFileContent. Only qwen-long and qwen-doc-turbo read a hosted file: the chat client sends the file ids as a system message (fileid://{id}) right before the message that carries them, the way the service injects the file into the context. A leading system message (e.g. ChatOptions.Instructions) keeps the model from taking the file for its instructions.
var chatClient = dashScopeClient.AsChatClient("qwen-long");
var response = await chatClient.GetResponseAsync(
new ChatMessage(ChatRole.User, [new HostedFileContent(file.FileId), new TextContent("总结这个文件")]),
new ChatOptions { Instructions = "You are a helpful assistant." });
The service answers a request of any other model without the file, so the chat client throws a NotSupportedException for a HostedFileContent in a request that goes to the multimodal API. A PDF passed inline goes to the multimodal API instead, see PDF understanding; any other document passed inline (a DataContent or UriContent with anything but an image, a video, an audio or a PDF) throws a NotSupportedException on both endpoints: upload it first and pass its id as a HostedFileContent. All of them used to be dropped silently.
Text to speech client
AsTextToSpeechClient() returns an ITextToSpeechClient over the speech synthesizer websocket API (CreateSpeechSynthesizerSocketSessionAsync), which serves the cosyvoice models and the qwen-audio-tts models. The text-to-speech client of Microsoft.Extensions.AI is experimental as well, suppress the MEAI001 diagnostic to use it:
var ttsClient = dashScopeClient.AsTextToSpeechClient("cosyvoice-v2");
// streaming: the audio arrives in DataContent chunks, the last update carries the usage
await foreach (var update in ttsClient.GetStreamingAudioAsync(
"博客园成立于2004年,代码改变世界。",
new TextToSpeechOptions { VoiceId = "longxiaochun_v2", AudioFormat = "mp3", Speed = 1.1f }))
{
foreach (var audio in update.Contents.OfType<DataContent>())
{
await stream.WriteAsync(audio.Data); // audio/mpeg, one update per audio frame of the service
}
}
// not streaming: the whole audio in one DataContent
var response = await ttsClient.GetAudioAsync("欢迎来到博客园。", new TextToSpeechOptions { VoiceId = "longxiaochun_v2", AudioFormat = "wav" });
- Every call runs a synthesis of its own on a session rented from the socket pool, so a client can be shared and called concurrently.
TextToSpeechOptions.ModelIdoverrides the model passed toAsTextToSpeechClient(). VoiceIdis required, the API has no default voice.AudioFormatis the format of the API (pcm,wav,mp3oropus; a media type such asaudio/mpegis accepted too) and names the media type of the audio. Without it the service picks the format, which is pcm today (the documentation names mp3), so the media type is read from the first bytes of the audio then.SpeedandPitchare multipliers around 1.0 likerateandpitchof the API,Volumeis a multiplier from 0.0 (silent) to 1.0 (full volume) for the volume of the API (0 to 100), andLanguageis sent as the language hint with its primary subtag (en-USbecomesen).- The settings the options don't expose (sample rate, bit rate, seed, instruction, word timestamps, SSML ...) go into a
SpeechSynthesizerParametersreturned byRawRepresentationFactoryor passed asAdditionalProperties["raw"]. The members it leaves unset are filled from the options, and the instance is never edited in place. - The streaming updates are of the kind
AudioUpdatingwith oneDataContenteach, the audio of one message of the service: an mp3 frame is 3360 bytes, a longer one (the 8000 bytes of a pcm frame for example) arrives in parts of at most 4096 bytes. They are followed by aSessionCloseupdate that carries the usage: the characters of the task inAdditionalCounts["Characters"], plus the token counts the qwen-audio-tts models report. A task the service fails (an unknown voice, a wrong format ...) throws aDashScopeException, so does a connection that breaks or an event the SDK can not read. - The Sambert models synthesize with another calling mode and are not served by the text-to-speech client, use the session API below for them.
Speech to text client
AsSpeechToTextClient() returns an ISpeechToTextClient over the real-time speech recognition websocket API (CreateSpeechRecognitionSocketSessionAsync), which serves the paraformer-realtime models, fun-asr-realtime and the qwen-audio-*-asr-flash models. The speech-to-text client of Microsoft.Extensions.AI is experimental as well, suppress the MEAI001 diagnostic to use it:
var sttClient = dashScopeClient.AsSpeechToTextClient("paraformer-realtime-v2");
// streaming: the recognized sentences arrive while the audio is still being sent
await using (var audio = File.OpenRead("speech.wav"))
{
await foreach (var update in sttClient.GetStreamingTextAsync(audio, new SpeechToTextOptions { SpeechLanguage = "zh" }))
{
if (update.Kind == SpeechToTextResponseUpdateKind.TextUpdated)
{
Console.WriteLine($"{update.StartTime} - {update.EndTime}: {update.Text}");
}
}
}
// not streaming: one TextContent per recognized sentence
await using var file = File.OpenRead("speech.wav");
var response = await sttClient.GetTextAsync(file, new SpeechToTextOptions { SpeechLanguage = "zh" });
Console.WriteLine(response.Text);
- Every call runs a recognition of its own on a session rented from the socket pool, so a client can be shared and called concurrently.
SpeechToTextOptions.ModelIdoverrides the model passed toAsSpeechToTextClient(). SpeechLanguageis sent as the language hint with its primary subtag (en-USbecomesen),SpeechSampleRateas the sample rate.TextLanguagehas no mapping, the API transcribes in the language of the audio and does not translate: asking for the text in another language throws aNotSupportedException.- The options name no audio format, so it is read from the first bytes of the audio when the stream can rewind to its start: a RIFF/WAVE header names
wavalong with the sample rate of the file, an ID3 tag or an MPEG frame headermp3, an Ogg pageopus. The sample rate matters: the service takes the audio by the one it is given, an 8 kHz pcm declared as 16000 Hz is recognized at double speed, with half the timestamps and the billing duration. Without such a header, or for a stream that cannot rewind (a live source), theformatof the raw parameters applies,pcmby default. - The settings the options don't expose (disfluency removal, punctuation, sentence splitting, hot words, the sensitive word filter ...) go into a
SpeechRecognitionParametersreturned byRawRepresentationFactoryor passed asAdditionalProperties["raw"], the conversation context of the qwen-audio models into aSpeechRecognitionInputpassed asAdditionalProperties["input"]. The members the parameters leave unset are filled from the options, and the instances are never edited in place. - An intermediate result of the service (its text may still be revised) is an update of the kind
TextUpdatingwith the text so far, the final result of a sentence one of the kindTextUpdatedwith the text and its start and end time, the message of the service being theRawRepresentationof each. They are followed by aSessionCloseupdate that carries the usage: the audio duration in seconds inAdditionalCounts["Duration"]for the paraformer and fun-asr models, plus the token counts the qwen-audio-3.1 models report. A task the service fails (an unsupported format ...) throws aDashScopeException, so does a connection that breaks before the task finished. GetTextAsyncleaves the intermediate results out and answers oneTextContentper recognized sentence, the start of the first and the end of the last one asStartTime/EndTime, and the messages of the task as itsRawRepresentation.- The recorded speech recognition APIs (
qwen3-asr-flash, the file transcription models) take a file url instead of a stream and are not served by the speech-to-text client, useGetMultimodalGenerationAsync/CreateSpeechTranscriptionTaskAsyncfor them.
Realtime client
AsRealtimeClient() returns an IRealtimeClient over the omni realtime websocket API (CreateOmniRealtimeSocketSessionAsync), which serves the qwen3.8-omni-flash-realtime, qwen3.5-omni-plus-realtime and qwen3.5-omni-flash-realtime models: a session understands speech, images and text and answers in speech and text, with function calling, remote MCP tools and web search on top (see Real-Time Multimodal Conversation for the protocol). The realtime client of Microsoft.Extensions.AI is experimental as well, suppress the MEAI001 diagnostic to use it:
// UseFunctionInvocation runs the functions the model asks for and writes their results back
var realtimeClient = dashScopeClient.AsRealtimeClient("qwen3.8-omni-flash-realtime").AsBuilder().UseFunctionInvocation().Build();
await using var session = await realtimeClient.CreateSessionAsync(
new RealtimeSessionOptions
{
Instructions = "你是个人助理小云,请你准确且友好地解答用户的问题。",
Voice = "Tina",
Tools = [AIFunctionFactory.Create(GetCurrentTime, "get_current_time")],
// push-to-talk: the client commits the audio and requests the response
VoiceActivityDetection = new VoiceActivityDetectionOptions { Enabled = false }
});
// the messages arrive on their own stream: read them from one place while the audio goes out
var answering = Task.Run(async () =>
{
await foreach (var message in session.GetStreamingResponseAsync())
{
switch (message)
{
case OutputTextAudioRealtimeServerMessage audio when audio.Type == RealtimeServerMessageType.OutputAudioDelta:
await speaker.WriteAsync(Convert.FromBase64String(audio.Audio!)); // 24kHz 16bit mono pcm
break;
case ResponseCreatedRealtimeServerMessage done when done.Type == RealtimeServerMessageType.ResponseDone:
Console.WriteLine($"{done.Status}, {done.Usage?.TotalTokenCount} tokens");
break;
}
}
});
await session.SendAsync(new InputAudioBufferAppendRealtimeClientMessage(new DataContent(chunk, "audio/pcm"))); // 16kHz 16bit mono
await session.SendAsync(new InputAudioBufferCommitRealtimeClientMessage());
await session.SendAsync(new CreateResponseRealtimeClientMessage());
- Every session runs over a websocket connection of its own: the connection is established and the
session.createdevent awaited before the session is returned, the session ends when it is disposed.RealtimeSessionOptions.Modeloverrides the model passed toAsRealtimeClient()for the session to create; the model of a session cannot change afterwards. CreateSessionAsync(options)and aSessionUpdateRealtimeClientMessagesend asession.updateevent and wait for the confirmation:Optionsis the configuration the server applied afterwards, a configuration the server rejects throws aDashScopeExceptionand ends the session.InputAudioFormat/OutputAudioFormat(a media type such asaudio/pcmoraudio/wav, plus the sample rate) become the format of the audio configuration,TranscriptionOptionsturns the input audio transcription on (the model is fixed toqwen3-asr-flash-realtime),MaxOutputTokensthe maximal token count of a response.VoiceActivityDetection.Enabledleft attrueis the VAD mode, the server detects the end of the speech and answers on its own;falseswitches to the manual mode (push-to-talk), where the audio is committed with anInputAudioBufferCommitRealtimeClientMessageand the response requested with aCreateResponseRealtimeClientMessage.ToolstakesAIFunctions, which the client executes - theUseFunctionInvocation()pipeline invokes them and writes the results back - andHostedMcpServerTools, remote MCP servers the server executes (answer theToolApprovalRequestContentof aConversationItemAddedmessage with aCreateConversationItemRealtimeClientMessagecarrying itsCreateResponse(), qwen3.8-omni-flash-realtime). The API has no tool choice:ToolModeis limited toChatToolMode.Auto, anything else throws aNotSupportedException, so does the transcription session kind - use the speech-to-text client for transcription.- The settings the options don't expose (the type of the turn detection and its thresholds, the web search, the video input, the sampling parameters ...) go into an
OmniRealtimeSessionreturned byRawRepresentationFactory. The options that are set replace the members of it, and the instance is never edited in place. - A
CreateResponseRealtimeClientMessagecreates itsItemsbefore it triggers the response; its per-response overrides (instructions, voice, ...) have no counterpart and are ignored. ACreateConversationItemRealtimeClientMessagetakes text messages, function call results and MCP approval responses, other content throws aNotSupportedException: audio goes in through the input audio buffer, video frames withAppendImageAsyncof theOmniRealtimeSocketSessionthe session hands out byGetService<OmniRealtimeSocketSession>(), the client events the abstraction has no message for (response.cancel...) through theRawRepresentationof aRealtimeClientMessage, as the JSON of the event. - Of the server messages: the recognized speech is
InputAudioTranscriptionDelta/InputAudioTranscriptionCompleted, the reply isOutputAudioTranscriptionDelta/OutputTextDeltawith the text andOutputAudioDeltawith base64 audio inAudio, a turn ends withResponseDonecarrying the output items and the usage (the video tokens and the web searches inAdditionalCounts), anerrorevent isError. The function call the model asks for is theFunctionCallContentof aResponseOutputItemDonemessage, an MCP call is reported asMcpCallInProgress/McpCallCompleted/McpCallFailed. Every other event (speech started / stopped, argument deltas ...) isRawContentOnly, and every message carries itsOmniRealtimeServerEventas theRawRepresentation. SendAsynctakes messages from several threads at once;GetStreamingResponseAsyncis enumerated from one place at a time.
Image generator
AsImageGenerator() returns an IImageGenerator over the image generation APIs of DashScope. The image generator of Microsoft.Extensions.AI is experimental as well, suppress the MEAI001 diagnostic to use it:
var imageGenerator = dashScopeClient.AsImageGenerator("qwen-image-3.0");
// text to image: one UriContent per image, the urls are valid for 24 hours
var response = await imageGenerator.GenerateImagesAsync(
"一只在月球上骑自行车的熊猫,水彩风格",
new ImageGenerationOptions { ImageSize = new Size(1024, 1024) });
foreach (var image in response.Contents.OfType<UriContent>())
{
Console.WriteLine(image.Uri);
}
// image editing: the original images and the prompt
var edited = await imageGenerator.EditImageAsync(
new DataContent(await File.ReadAllBytesAsync("cat.png"), "image/png"),
"给猫戴上一顶红色的帽子");
// the images as bytes instead of urls
var downloaded = await imageGenerator.GenerateImagesAsync(
"a lighthouse at dawn",
new ImageGenerationOptions { ResponseFormat = ImageGenerationResponseFormat.Data });
foreach (var image in downloaded.Contents.OfType<DataContent>())
{
await File.WriteAllBytesAsync("lighthouse.png", image.Data.ToArray());
}
GenerateImagesAsync/EditImagesAsyncalways answer the finished images. The API is picked by the model of the request (ImageGenerationOptions.ModelId, or the model passed toAsImageGenerator()): the models with a synchronous API (the qwen-image models including the edit ones, the wan2.6 / wan2.7 image models, z-image) are called viaGetMultimodalGenerationAsync; the models that are served asynchronously only create a task that the generator queries until it ends: the kling and vidu image models (CreateImageGenerationTaskAsync), the wanx2.0 / wanx2.1 / wan2.2 / wan2.5 text-to-image models (CreateImageSynthesisTaskAsync) and wan2.5-i2i-preview / wanx2.1-imageedit (CreateImage2ImageSynthesisTaskAsync). An unknown model goes to the synchronous API, where the service rejects the models it does not serve. Fix the API withAsImageGenerator(modelId, new DashScopeImageGeneratorOptions { Endpoint = DashScopeImageGenerationEndpoint.ImageGenerationTask })when the SDK picks wrong, e.g. for a model released after the version of the SDK.- A task is queried every 5 seconds (
PollingInterval). A task that fails, is cancelled or produces no image throws aDashScopeExceptionwith the code and the message of the service.TaskTimeoutbounds the wait (aTimeoutException) and the cancellation token cancels it (anOperationCanceledException); the task keeps running on the service in both cases. Countis sent asn, 1 when it is left out (the service would default to 4 for the wan text-to-image models, which costs four times as much), andImageSizeassize(width*height). The service answers png images only, soMediaTypehas no mapping. LeaveImageSizeout and qwen-image picks the resolution itself: an edit of qwen-image-3.0 came back with 2048*2048 (5.5 MB, billed by the pixel area) on 2026-12-03, so set it to control the price.- The original images are sent the way the service takes them: the url of a
UriContent, the bytes of aDataContentas a base64 data uri. Any other content throws aNotSupportedException. wanx2.1-imageedit edits one image by function: it getsdescription_editas the function unless the raw input names one. - The settings the options don't expose (prompt_extend, seed, watermark, enable_thinking, aspect_ratio, a size tier such as
1K...) go into the parameters of the API the request goes to (MultimodalParameters,ImageSynthesisParametersorImage2ImageSynthesisParameters) returned byRawRepresentationFactoryor passed asAdditionalProperties["raw"]. The members the asynchronous text-to-image and image-to-image APIs read from their input instead (negative_prompt, function, mask_image_url ...) go into anImageSynthesisInput/Image2ImageSynthesisInputpassed asAdditionalProperties["input"]. The members they leave unset are filled from the options, and the instances are never edited in place.
var response = await imageGenerator.GenerateImagesAsync("a panda riding a bicycle", new ImageGenerationOptions
{
ImageSize = new Size(1664, 928),
RawRepresentationFactory = _ => new MultimodalParameters { PromptExtend = false, Watermark = true }
});
// wanx2.1-t2i-turbo is served asynchronously only: the generator polls the task, the negative prompt goes into the raw input
var drawn = await dashScopeClient.AsImageGenerator("wanx2.1-t2i-turbo").GenerateImagesAsync(
"a lighthouse at dawn",
new ImageGenerationOptions
{
AdditionalProperties = new AdditionalPropertiesDictionary { { "input", new ImageSynthesisInput { NegativePrompt = "低分辨率" } } }
});
- The images come back as
UriContents. WithResponseFormat = ImageGenerationResponseFormat.Datathey are downloaded intoDataContents byDownloadFromUrlAsync: the urls are signed, so the download is made by the HTTP client that carries no api key, and the media type is the one the storage answered, else the one the extension of the url names;ImageGenerationResponseFormat.Hostedthrows aNotSupportedException. The message content or the result that carried an image is theRawRepresentationof the content, the response of the call (or the last task query) theRawRepresentationof theImageGenerationResponse. The usage counts the images inAdditionalCounts["ImageCount"], plus the input images, the width, the height and the token counts the model reports. - The models that edit by other means than a prompt (the functions of wanx2.1-imageedit other than
description_edit, sketch-to-image, style repaint, image translation ...) and the models that output text and images interleaved are not served by the image generator, useGetMultimodalGenerationAsync/CreateImage2ImageSynthesisTaskAsyncfor them.
Message roles and author names
The chat client sends the roles system, user, assistant and tool, which the DashScope API matches case sensitively. A message of the developer role (new ChatRole("developer"), the role OpenAI's reasoning models read in place of a system message, which Microsoft.Extensions.AI passes on as a custom role) is sent as a system message. A message of any other role throws a NotSupportedException instead of being dropped silently, which is what used to happen to the developer message.
var response = await chatClient.GetResponseAsync(
[
new ChatMessage(new ChatRole("developer"), "You are a professional translator."),
new ChatMessage(ChatRole.User, "hello")
]);
The AuthorName of a message is not sent: the DashScope API has no name for a message. The service answers a name field without an error, but the documentation does not list it and the model does not see it (the prompt tokens are the same with and without it), so the field is ignored like any unknown one and the chat client leaves it out. Put a name into the text of the message when the model is meant to know it.
Fallback to raw messages
If you need to use input data or parameters not supported by Microsoft.Extensions.AI, you can directly invoke the underlying SDK by passing a raw TextChatMessage or MultimodalMessage via RawRepresentation.
Similarly, to pass unsupported parameters, you can also do so directly by setting the raw property within AdditionalProperties.
Example(Using qwen-doc-turbo)
var messages = new List<TextChatMessage>()
{
TextChatMessage.DocUrl(
"从这两份产品手册中,提取所有产品信息,并整理成一个标准的JSON数组。每个对象需要包含:model(产品的型号)、name(产品的名称)、price(价格(去除货币符号和逗号))",
[
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251107/jockge/%E7%A4%BA%E4%BE%8B%E4%BA%A7%E5%93%81%E6%89%8B%E5%86%8CA.docx",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251107/ztwxzr/%E7%A4%BA%E4%BE%8B%E4%BA%A7%E5%93%81%E6%89%8B%E5%86%8CB.docx"
])
};
var parameters = new TextGenerationParameters()
{
ResultFormat = "message", IncrementalOutput = true,
};
var response = client
.AsChatClient("qwen-doc-turbo")
.GetStreamingResponseAsync(
messages.Select(x => new ChatMessage() { RawRepresentation = x }),
new ChatOptions()
{
AdditionalProperties = new AdditionalPropertiesDictionary() { { "raw", parameters } }
});
await foreach (var chunk in response)
{
Console.Write(chunk.Text);
}
Similarly, you can also retrieve the raw message from the RawRepresentation in the message returned by the model.
Example (Getting the token count for an image when calling qwen3-vl-plus):
var response = client
.AsChatClient("qwen3-vl-plus")
.GetStreamingResponseAsync(
new List<ChatMessage>()
{
new(
ChatRole.User,
new List<AIContent>()
{
new UriContent(
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg",
MediaTypeNames.Image.Jpeg),
new UriContent(
"https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png",
MediaTypeNames.Image.Jpeg),
new TextContent("这些图展现了什么内容?")
})
},
new ChatOptions());
var lastChunk = (ChatResponseUpdate?)null;
await foreach (var chunk in response)
{
Console.Write(chunk.Text);
lastChunk = chunk;
}
Console.WriteLine();
// Access underlying raw response
var raw = lastChunk?.RawRepresentation as ModelResponse<MultimodalOutput, MultimodalTokenUsage>;
Console.WriteLine($"Image token usage: {raw?.Usage?.ImageTokens}");
Workspace and Region
Bailian serves different regions with different endpoints. The SDK defaults to the Beijing region (cn-beijing). If your API key belongs to another region, specify it via the region parameter (or RegionId in configuration):
DashScopeRegion |
Region ID | Endpoint without workspace |
|---|---|---|
Beijing (default) |
cn-beijing |
https://dashscope.aliyuncs.com |
Singapore |
ap-southeast-1 |
https://dashscope-intl.aliyuncs.com |
HongKong |
cn-hongkong |
https://cn-hongkong.dashscope.aliyuncs.com |
UsEast |
us-east-1 |
workspace required |
Germany |
eu-central-1 |
workspace required |
Japan |
ap-northeast-1 |
workspace required |
Console application:
var client = new DashScopeClient("your-api-key", region: DashScopeRegion.Singapore);
ASP.NET Core:
builder.Services.AddDashScopeClient("your-api-key", region: DashScopeRegion.Singapore);
Workspace
If you are using a Bailian workspace (业务空间), pass the workspace id together with its region. The SDK then switches to the workspace-specific endpoint {workspaceId}.{regionId}.maas.aliyuncs.com and appends the X-DashScope-WorkSpace header automatically. Note that the UsEast, Germany and Japan regions do not provide a shared endpoint, a workspace id is required for them:
var client = new DashScopeClient(
"your-api-key",
workspaceId: "your-workspace-id",
region: DashScopeRegion.Singapore);
// requests are sent to https://{workspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/
appsettings.json
{
"DashScope": {
"ApiKey": "your-api-key",
"WorkspaceId": "your-workspace-id",
"RegionId": "ap-southeast-1"
}
}
If you access Bailian through a proxy, set BaseAddress/WebsocketBaseAddress (or the baseAddress parameter) instead. An explicit base address always takes precedence over region and workspace.
Content Inspection (AI Safety Guardrail)
Bailian supports the X-DashScope-DataInspection request header, which further inspects input and output content for violations using the AI safety guardrail. The inspection is disabled by default (the header is not sent). The guardrail service needs to be enabled on your account first, otherwise the API returns 403 Header.AccessDenied. Not available for Qwen-Audio models.
Enable it for all requests on the client:
// Console application
var client = new DashScopeClient("your-api-key")
{
DataInspection = DataInspectionOptions.CipInputAndOutput
};
// ASP.NET Core
builder.Services.AddDashScopeClient("your-api-key");
builder.Services.Configure<DashScopeOptions>(o => o.DataInspection = DataInspectionOptions.CipInputAndOutput);
Or enable/override it on a single request:
var completion = await client.GetTextCompletionAsync(new ModelRequest<TextGenerationInput, ITextGenerationParameters>
{
Model = "qwen-plus",
Input = new TextGenerationInput { Messages = new List<TextChatMessage> { TextChatMessage.User("你好") } },
Parameters = new TextGenerationParameters { ResultFormat = "message" },
DataInspection = DataInspectionOptions.CipInput
});
Available values are Disabled (default), CipInput, CipOutput and CipInputAndOutput. Request level configuration takes precedence over client level configuration, and setting DataInspectionOptions.Disabled on a request disables client level inspection for that request.
Client level configuration also applies to the WebSocket API (e.g. CosyVoice), which only supports enabling inspection for both directions at once, so any enabled direction turns on the X-DashScope-DataInspection header for WebSocket connections. The header is not sent by default. For a single WebSocket session, pass the dataInspection parameter when creating the session; when it differs from the client level configuration, a temporary connection is created for that session only and disposed afterwards.
Not Covered by This SDK
The SDK covers the DashScope API of Bailian. The APIs below are not covered: each of them belongs to a protocol or a product with a client library of its own, which takes the base URL of the workspace instead (cn-beijing is the region id, the workspace id is described in Workspace and Region):
| API | Use instead |
|---|---|
| OpenAI compatible Responses API | The OpenAI library, through Microsoft.Extensions.AI.OpenAI |
| Anthropic compatible Messages API | The Anthropic library, the official .NET SDK |
| OpenAI compatible Agents API (Beta) | The OpenAI library has no client for it (2.15.0), the requests go to https://{workspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 |
| Token Plan API | The Alibaba Cloud SDK: it authenticates with an AccessKey signed by ACS3-HMAC-SHA256, API keys are not accepted |
OpenAI compatible Responses API
Install NuGet package Microsoft.Extensions.AI.OpenAI, which brings the OpenAI library.
// OPENAI001: the Responses client of the OpenAI library is experimental
#pragma warning disable OPENAI001
using System.ClientModel;
using System.ClientModel.Primitives;
using Microsoft.Extensions.AI;
using OpenAI;
var workspaceId = "your-workspace-id";
var options = new OpenAIClientOptions
{
Endpoint = new Uri($"https://{workspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
};
// without the workspace header the service rejects an API key that is not bound to a business workspace
options.AddPolicy(new WorkspaceHeaderPolicy(workspaceId), PipelinePosition.PerCall);
IChatClient chatClient = new OpenAIClient(new ApiKeyCredential("your-api-key"), options)
.GetResponsesClient()
.AsIChatClient("qwen-plus");
Console.WriteLine((await chatClient.GetResponseAsync("用一句话介绍博客园。")).Text);
sealed class WorkspaceHeaderPolicy(string workspaceId) : PipelinePolicy
{
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
{
message.Request.Headers.Add("X-DashScope-WorkSpace", workspaceId);
ProcessNext(message, pipeline, currentIndex);
}
public override ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
{
message.Request.Headers.Add("X-DashScope-WorkSpace", workspaceId);
return ProcessNextAsync(message, pipeline, currentIndex);
}
}
Anthropic compatible Messages API
Install NuGet package Anthropic.
using Anthropic;
using Anthropic.Core;
using Microsoft.Extensions.AI;
var anthropic = new AnthropicClient(new ClientOptions
{
ApiKey = "your-api-key",
BaseUrl = "https://your-workspace-id.cn-beijing.maas.aliyuncs.com/apps/anthropic"
});
// the model to call, and the maximum number of tokens it may output
IChatClient chatClient = anthropic.AsIChatClient("qwen3.7-plus", 1024);
Console.WriteLine((await chatClient.GetResponseAsync("用一句话介绍博客园。")).Text);
Supported APIs
- Model Calls - Call the Bailian models, grouped by modality as in the Bailian docs
- Text Generation and Visual Understanding - QWen3, DeepSeek, etc. Supports reasoning/tool calling/web search/translation scenarios
- Image and Video Understanding - QWen-VL, QVQ, etc. Understands images and videos, with reasoning
- Conversation
- Thinking Models
- Structured Output (JSON Output)
- Prefix Completion
- Tool Calling - Function calling, web search, code interpreter and PDF understanding
- Function Calling
- Web Search
- Code Interpreter
- PDF understanding - qwen4-max, qwen3.8-max, qwen3.8-flash etc. read a PDF of a user message (url or bytes)
- Agents (Microsoft Agent Framework)
- Specialized Models - The models built for one task: long context, document mining, OCR and GUI
- Vision - Image, video, 3D and world generation
- Image Generation - qwen-image-2.0-pro, wanx2.1, etc. For text-to-image, image editing, portrait style transfer and image translation
- Video Generation - wan2.7/wan3.0, PixVerse, Kling, Vidu, etc. For text-to-video, image-to-video and video editing
- 3D Generation (Tripo) - Tripo-H3.1/P1.0 3D generation, Gaussian Splat, mesh post-processing and animation
- HappyOyster (World Model) - The interactive world model: create and manage worlds, hand out travel tickets, follow the travels and fetch their videos
- Speech - Speech recognition, speech synthesis and real-time voice conversation
- Speech Recognition - Real-time and recorded speech recognition, and custom hotword vocabularies
- Real-Time Speech Recognition - Paraformer, Qwen-Audio ASR. For streaming ASR applications
- Recorded Speech Recognition - qwen3-asr-flash, Fun-ASR-Flash, Qwen-Audio ASR. For recorded audio files
- Custom Hotword Vocabularies
- Text-to-Speech - CosyVoice, Sambert, etc. For TTS applications
- Audio Understanding
- Real-Time Voice Conversation (Qwen-Audio-Realtime)
- Speech Recognition - Real-time and recorded speech recognition, and custom hotword vocabularies
- Embedding and Rerank - Vectorize texts, images and videos, and rerank the documents a vector search recalled
- Text Embeddings
- Multimodal Embedding - tongyi-embedding-vision-plus/flash, qwen3-vl-embedding, qwen2.5-vl-embedding, multimodal-embedding-v1. For embedding texts, images and videos into one vector space
- Text Rerank - qwen3-rerank, qwen3.7-text-rerank, gte-rerank-v2, qwen3-vl-rerank. For refining the documents recalled by a vector search
- Omni-Modal - Qwen-Omni and Qwen-Livetranslate: understand text, images, audio and video, answer in text or speech, translate live
- Decision Model (System One) - decision-model. For classification, yes/no judgement and scoring with a single forward pass, without generating text
- Omni-Modal Translation (Qwen-MT-Uni) - qwen-mt-uni. For translating texts, documents, images and audio
- Text Generation and Visual Understanding - QWen3, DeepSeek, etc. Supports reasoning/tool calling/web search/translation scenarios
- Model Inference - Throughput reservation, batch inference and model deployment
- Throughput Reservation - Buy input and output throughput for a model under its own model code: capacity instances, scaling, renewal, release and the overflow strategy
- Batch
- Model Deployment - Publish a model as an online service: the catalog of deployable models, the model unit, LoRA, preset and dedicated throughput plans, scale, rate limits, stop, start and delete
- Model Training - Fine-tune, compress and import models, and manage their checkpoints
- Fine-Tuning - Create and manage fine-tune jobs of the text, image, video and speech models: datasets, hyper parameters, training log, cancel and delete
- Checkpoints - The checkpoints of a fine-tune job: list them, export one as a deployable model, read the validation previews of the image and video models
- Model Compression - Compress a full parameter tuned model by quantization: the templates, the job and its log, cancel and delete
- Model Import - Import a LoRA model stored in OSS, to deploy it like a fine-tuned one
- Application Call
- Model Management - Query the model list, and configure the rate limits and the permissions
- Model List - Query the models of Bailian: capabilities, modalities, features, prices and token limits
- Model Rate Limits
- Model Permissions
- Temporary API Key - A short-lived key for calling the models from an untrusted environment (browser, mobile app) without exposing the permanent key
- Async Task Callback (EventBridge) - Receive the
dashscope:System:AsyncTaskFinishevent on an HTTP callback url instead of polling a task
Model Calls
Text Generation and Visual Understanding
Use dashScopeClient.GetTextCompletionAsync and dashScopeClient.GetTextCompletionStreamAsync() to access text generation APIs.
Common models: qwen-max qwen-plus qwen-flush etc.
Basic example (see Workspace and Region for client configuration):
var client = new DashScopeClient("your-api-key", region: DashScopeRegion.Singapore);
var completion = await client.GetTextCompletionAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput()
{
Messages = new List<TextChatMessage>()
{
TextChatMessage.System("You are a helpful assistant"),
TextChatMessage.User("Who are you?")
}
},
Parameters = new TextGenerationParameters() { ResultFormat = "message" }
});
Console.WriteLine(completion.Output.Choices![0].Message.Content)
Image and Video Understanding
Use GetMultimodalGenerationAsync/GetMultimodalGenerationStreamAsync
Official Documentation
Upload file for multimodal usage
You can upload file to get an oss link before multimodal usage.
await using var video = File.OpenRead("sample.mp4");
var ossLink = await client.UploadTemporaryFileAsync("qwen3-vl-plus", video, "sample.mp4");
Console.WriteLine($"File uploaded: {ossLink}");
var messages = new List<MultimodalMessage>();
messages.Add(
MultimodalMessage.User(
[
MultimodalMessageContent.VideoContent(ossLink, fps: 2),
// MultimodalMessageContent.VideoFrames(links),
// MultimodalMessageContent.ImageContent(link)
MultimodalMessageContent.TextContent("这段视频的内容是什么?")
]));
The form is posted to the file storage of DashScope, which authenticates it by the fields of the upload grant. The HTTP client that posts it carries no api key, like the one that follows the download links of DownloadFileAsync: DashScopeClient keeps one for all of its instances, and with ASP.NET Core it is the named client Cnblogs.DashScope.FileStorage.
Limit Upload Speed
You can limit the upload speed for all file upload APIs (UploadTemporaryFileAsync, OpenAiCompatibleUploadFileAsync, UploadFilesAsync) by setting MaximumUploadSpeed. The default value is -1 (no limit).
Console application:
var client = new DashScopeClient("your-api-key", region: DashScopeRegion.Singapore);
client.MaximumUploadSpeed = 1024 * 1024; // 1 MB/s
ASP.NET Core application (appsettings.json):
{
"DashScope": {
"ApiKey": "your-api-key",
"MaximumUploadSpeed": 1048576
}
}
Image recognition/thinking
var image = await File.ReadAllBytesAsync("Lenna.jpg");
var response = dashScopeClient.GetMultimodalGenerationStreamAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qvq-plus",
Input = new MultimodalInput()
{
Messages =
[
MultimodalMessage.User(
[
MultimodalMessageContent.ImageContent(image, "image/jpeg"),
MultimodalMessageContent.TextContent("她是谁?")
])
]
},
Parameters =
new MultimodalParameters
{
IncrementalOutput = true,
// EnableThinking = true,
VlHighResolutionImages = false
}
});
// output
var reasoning = false;
await foreach (var modelResponse in response)
{
var choice = 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);
}
}
Conversation
Quick Start
The key is maintaining a TextChatMessage array as conversation history.
var messages = new List<TextChatMessage>();
messages.Add(TextChatMessage.System("You are a helpful assistant"));
while (true)
{
Console.Write("User > ");
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("Using default input: Who are you?");
input = "Who are you?";
}
messages.Add(TextChatMessage.User(input));
var completion = await client.GetTextCompletionAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters() { ResultFormat = "message" }
});
Console.WriteLine("Assistant > " + completion.Output.Choices![0].Message.Content);
var usage = completion.Usage;
if (usage != null)
{
Console.WriteLine($"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/total({usage.TotalTokens})");
}
messages.Add(TextChatMessage.Assistant(completion.Output.Choices[0].Message.Content));
}
Thinking Models
The model's thinking process is stored in a separate ReasoningContent property. When saving to conversation history, ignore it and only keep the model's reply Content.
Some models accept EnableThinking to control deep thinking, which can be set in Parameters.
var messages = new List<TextChatMessage>();
messages.Add(TextChatMessage.System("You are a helpful assistant"));
while (true)
{
Console.Write("User > ");
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("Please enter a user input.");
return;
}
messages.Add(TextChatMessage.User(input));
var completion = await client.GetTextCompletionAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters() { ResultFormat = "message", EnableThinking = true }
});
Console.WriteLine("Reasoning > " + completion.Output.Choices![0].Message.ReasoningContent);
Console.WriteLine("Assistant > " + completion.Output.Choices![0].Message.Content);
var usage = completion.Usage;
if (usage != null)
{
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/reasoning({usage.OutputTokensDetails?.ReasoningTokens})/total({usage.TotalTokens})");
}
messages.Add(TextChatMessage.Assistant(completion.Output.Choices[0].Message.Content));
}
Streaming Output
var request = new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = true,
IncrementalOutput = true
}
}
Use client.GetTextCompletionStreamAsync for streaming output. It's recommended to enable IncrementalOutput in Parameters for incremental output.
Incremental output:
Example: ["I love","eating","apples"]
Non-incremental output:
Example: ["I love","I love eating","I love eating apples"]
Streaming output returns an IAsyncEnumerable. Use await foreach to iterate, record incremental content, then save to conversation history.
var messages = new List(); messages.Add(TextChatMessage.System("You are a helpful assistant")); while (true) { Console.Write("User > "); var input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) { Console.WriteLine("Please enter a user input."); return; }
messages.Add(TextChatMessage.User(input));
var completion = client.GetTextCompletionStreamAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = true,
IncrementalOutput = true
}
});
var reply = new StringBuilder();
var reasoning = false;
TextGenerationTokenUsage? usage = null;
await foreach (var chunk in completion)
{
var choice = chunk.Output.Choices![0];
if (string.IsNullOrEmpty(choice.Message.ReasoningContent) == false)
{
// reasoning
if (reasoning == false)
{
Console.Write("Reasoning > ");
reasoning = true;
}
Console.Write(choice.Message.ReasoningContent);
continue;
}
if (reasoning)
{
reasoning = false;
Console.WriteLine();
Console.Write("Assistant > ");
}
Console.Write(choice.Message.Content);
reply.Append(choice.Message.Content);
usage = chunk.Usage;
}
Console.WriteLine();
messages.Add(TextChatMessage.Assistant(reply.ToString()));
if (usage != null)
{
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/reasoning({usage.OutputTokensDetails?.ReasoningTokens})/total({usage.TotalTokens})");
}
}
Limiting Thinking Length
Use ThinkingBudget in Parameters to limit the model's thinking length.
const int budget = 10;
Console.WriteLine($"Set thinking budget to {budget} tokens");
var messages = new List<TextChatMessage>();
messages.Add(TextChatMessage.System("You are a helpful assistant"));
while (true)
{
Console.Write("User > ");
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("Please enter a user input.");
return;
}
messages.Add(TextChatMessage.User(input));
var completion = client.GetTextCompletionStreamAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = true,
ThinkingBudget = budget,
IncrementalOutput = true
}
});
var reply = new StringBuilder();
var reasoning = false;
TextGenerationTokenUsage? usage = null;
await foreach (var chunk in completion)
{
var choice = chunk.Output.Choices![0];
if (string.IsNullOrEmpty(choice.Message.ReasoningContent) == false)
{
// reasoning
if (reasoning == false)
{
Console.Write("Reasoning > ");
reasoning = true;
}
Console.Write(choice.Message.ReasoningContent);
continue;
}
if (reasoning)
{
reasoning = false;
Console.WriteLine();
Console.Write("Assistant > ");
}
Console.Write(choice.Message.Content);
reply.Append(choice.Message.Content);
usage = chunk.Usage;
}
Console.WriteLine();
messages.Add(TextChatMessage.Assistant(reply.ToString()));
if (usage != null)
{
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/reasoning({usage.OutputTokensDetails?.ReasoningTokens})/total({usage.TotalTokens})");
}
}
Structured Output (JSON Output)
Set ResponseFormat (remarks: not ResultFormat) in Parameters to JSON to force JSON output.
var request = new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-plus",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
ResponseFormat = DashScopeResponseFormat.JsonObject,
IncrementalOutput = true
}
}
To make the model strictly follow a given JSON Schema, use DashScopeResponseFormat.JsonSchema() with a DashScopeJsonSchema (Strict is recommended to be true).
var request = new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen3.8-flash",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters()
{
ResponseFormat = DashScopeResponseFormat.JsonSchema(new DashScopeJsonSchema(
"calculation",
new JsonObject
{
["type"] = "object",
["properties"] = new JsonObject
{
["result"] = new JsonObject { ["type"] = "number" }
},
["required"] = new JsonArray("result"),
["additionalProperties"] = false
},
Strict: true))
}
}
Notes on using json_schema:
- Only a few models support
json_schema(e.g. qwen3.7/qwen3.8 series). Check the structured output doc before using it, otherwise fall back tojson_object. - Among them, qwen3.7-plus / qwen3.7-flash and the qwen3.8 series are called via the multimodal API (
MultimodalParameters), while qwen3.7-max is called via the text API (TextGenerationParameters): the endpoint does not follow the model version. - Unlike
json_object,json_schemadoes not require the prompt to contain the word "json". - In the
IChatClient(Microsoft.Extensions.AI) integration, whenChatResponseFormat.ForJsonSchema(...)is used: whitelisted models (qwen3.7/qwen3.8 series) are automatically mapped tojson_schema; other models fall back tojson_object(the schema is ignored). SetAdditionalProperties["useJsonSchema"]totrue/falseto force the mapping (similar touseVl), e.g. when a new model supportsjson_schemabefore the whitelist is updated.ChatResponseFormat.Jsonis always mapped tojson_object.
Prefix Completion
Place the prefix to complete as an assistant message at the end of the messages array with Partial set to true. The model will complete the remaining content based on this prefix.
Deep thinking cannot be enabled in this mode.
var messages = new List<TextChatMessage>
{
TextChatMessage.User("Complete following C# method."),
TextChatMessage.Assistant("public int Fibonacci(int n)", partial: true)
};
var completion = client.GetTextCompletionStreamAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
IncrementalOutput = true
}
});
Tool Calling
Function Calling
Provide available tools to the model via Tools in Parameters. The model returns messages with ToolCall properties to invoke tools.
After receiving the message, the server needs to call the corresponding tools and insert results as Tool role messages into the conversation history before making another request. The model will summarize the tool call results.
By default, the model calls tools once per turn. To enable multiple tool calls, enable ParallelToolCalls in Parameters.
var tools = new List<ToolDefinition>
{
new(
ToolTypes.Function,
new FunctionDefinition(
nameof(GetWeather),
"Get current weather",
new JsonSchemaBuilder().FromType<WeatherReportParameters>().Build()))
};
var request = new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = true,
IncrementalOutput = true,
Tools = tools,
ToolChoice = ToolChoice.AutoChoice,
ParallelToolCalls = true // Model can call multiple tools at once
}
}
Web Search
Controlled mainly through EnableSearch and SearchOptions in Parameters.
Example request:
var request = new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = true,
EnableSearch = true,
SearchOptions = new TextGenerationSearchOptions()
{
SearchStrategy = "max", // max/turbo - controls number of search results
EnableCitation = true, // Add source citations to model reply
CitationFormat = "[ref_<number>]", // Citation format
EnableSource = true, // Return search source list in SearchInfo
ForcedSearch = true, // Force model to search
EnableSearchExtension = true, // Enable vertical domain search, results in SearchInfo.Extra
PrependSearchResult = true // First packet contains only search results
}
}
};
Code Interpreter
This capability is mutually exclusive with Function Call and cannot be used simultaneously.
Use the EnableCodeInterpreter parameter in Parameters to allow the model to write code and call an internal code interpreter for calculations.
Example Request:
var completion = client.GetTextCompletionStreamAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen3-max-preview",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = true,
EnableCodeInterpreter = true,
IncrementalOutput = true
}
});
The code that model generated will be included in chunk.Output.ToolInfo.CodeInterpreter. The invocation process can be considered part of the reasoning process.
Full example,
var messages = new List<TextChatMessage>();
const string input = "123的21次方是多少?";
Console.Write($"User > {input}");
messages.Add(TextChatMessage.User(input));
var completion = client.GetTextCompletionStreamAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>
{
Model = "qwen3-max-preview",
Input = new TextGenerationInput { Messages = messages },
Parameters = new TextGenerationParameters
{
ResultFormat = "message",
EnableThinking = true,
EnableCodeInterpreter = true,
IncrementalOutput = true
}
});
var reply = new StringBuilder();
var codeGenerated = false;
var reasoning = false;
TextGenerationTokenUsage? usage = null;
await foreach (var chunk in completion)
{
var choice = chunk.Output.Choices![0];
var tool = chunk.Output.ToolInfo?.FirstOrDefault();
if (codeGenerated == false && tool?.CodeInterpreter != null)
{
Console.WriteLine($"Code > {tool.CodeInterpreter.Code}");
codeGenerated = true;
}
if (string.IsNullOrEmpty(choice.Message.ReasoningContent) == false)
{
// reasoning
if (reasoning == false)
{
Console.WriteLine();
Console.Write("Reasoning > ");
reasoning = true;
}
Console.Write(choice.Message.ReasoningContent);
continue;
}
if (reasoning && string.IsNullOrEmpty(choice.Message.Content.Text) == false)
{
reasoning = false;
Console.WriteLine();
Console.Write("Assistant > ");
}
Console.Write(choice.Message.Content);
reply.Append(choice.Message.Content);
usage = chunk.Usage;
}
Console.WriteLine();
messages.Add(TextChatMessage.Assistant(reply.ToString()));
if (usage != null)
{
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/reasoning({usage.OutputTokensDetails?.ReasoningTokens})/plugins({usage.Plugins?.CodeInterpreter?.Count})/total({usage.TotalTokens})");
}
/*
User > 123的21次方是多少?
Reasoning > 用户问的是123的21次方是多少。这是一个大数计算问题,我需要使用代码计算器来计算这个值。
我需要调用code_interpreter函数,传入计算123**21的Python代码。
123**21
用户询问123的21次方是多少,我使用代码计算器计算出了结果。结果是一个非常大的数字:77269364466549865653073473388030061522211723
我应该直接给出这个结果,因为这是一个精确的数学计算问题,不需要额外的解释或
Assistant > 123的21次方是:77269364466549865653073473388030061522211723
Usage: in(704)/out(234)/reasoning(142)/plugins(1)/total(938)
*/
PDF understanding
The models qwen4-max, qwen3.8-max, qwen3.8-flash, qwen3.8-27b and kimi-k3.1-pro read a PDF passed in a user message of the multimodal API, by a public url or as its bytes: at most 150 MB and 256 pages a file. Every page is parsed and billed (0.02 CNY a page in Beijing), the parsed text and images count as input tokens, and the number of parsed pages comes back in usage.plugins.pdf_page_parser.
// by url
var messages = new List<MultimodalMessage>
{
MultimodalMessage.User(
[
MultimodalMessageContent.FileContent("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"),
MultimodalMessageContent.TextContent("What is the title of this paper? One short sentence.")
])
};
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen3.8-flash",
Input = new MultimodalInput() { Messages = messages }
});
Console.WriteLine(completion.Output.Choices[0].Message.Content[0].Text);
Console.WriteLine($"Parsed pages: {completion.Usage?.Plugins?.PdfPageParser?.Count}");
// by bytes: sent as a base64 data uri (a third larger than the file) with the name of the document
var report = await File.ReadAllBytesAsync("report.pdf");
messages[0] = MultimodalMessage.User(
[
MultimodalMessageContent.FileContent(report, "report.pdf"),
MultimodalMessageContent.TextContent("What is the release codename written in the document?")
]);
FileContent takes the oss:// link of UploadTemporaryFileAsync as well, the SDK asks the service to resolve it. A fileid:// id is no url for it (file_url must be a valid HTTP or HTTPS URL) and no other document is read (Input file must be a valid PDF): upload those with the purpose file-extract and pass the id to qwen-long / qwen-doc-turbo as TextChatMessage.File, see Long Context (Qwen-Long).
With Microsoft.Extensions.AI the chat client maps a DataContent of the media type application/pdf to the bytes form (its Name names the document, document.pdf when it has none) and a UriContent to the url form:
var chatClient = dashScopeClient.AsChatClient("qwen3.8-flash");
var report = await DataContent.LoadFromAsync("report.pdf");
var response = await chatClient.GetResponseAsync(
new ChatMessage(ChatRole.User, [report, new TextContent("What is the release codename written in the document?")]));
Console.WriteLine($"{response.Text} (parsed pages: {response.Usage?.AdditionalCounts.GetValueOrDefault("Plugins.PdfPageParser.Count")})");
Agents (Microsoft Agent Framework)
The IChatClient returned by AsChatClient() works with Microsoft Agent Framework (Microsoft.Agents.AI NuGet package). The agent keeps the conversation history itself and passes the agent-level persona via ChatOptions.Instructions, which this SDK maps to a leading system message; tool calls are executed by the agent loop automatically.
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
var chatClient = dashScopeClient.AsChatClient("qwen-plus");
var agent = new ChatClientAgent(
chatClient,
instructions: "你是智能助理,可以查询天气和当前时间,回答要简洁。",
name: "assistant",
tools: [AIFunctionFactory.Create(GetWeather), AIFunctionFactory.Create(GetNow)]);
// The session carries the conversation history across runs.
var session = await agent.CreateSessionAsync();
while (true)
{
Console.Write("User > ");
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
return;
}
var response = await agent.RunAsync(input, session);
Console.WriteLine($"Assistant > {response.Text}");
}
See sample/Cnblogs.DashScope.Sample/MsExtensionsAI/AgentExample.cs for a runnable sample. If you prefer no extra dependency, ChatOptions.Instructions + tool messages (FunctionCallContent/FunctionResultContent) are enough to build a minimal agent loop by hand, see Function Calling.
Specialized Models
Long Context (Qwen-Long)
For Qwen-Long models:
var file = new FileInfo("test.txt");
var uploadedFile = await dashScopeClient.OpenAiCompatibleUploadFileAsync(file.OpenRead(), file.Name);
var history = new List<ChatMessage> { ChatMessage.File(uploadedFile.Id) };
var completion = await client.client.GetTextCompletionAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-long",
Input = new TextGenerationInput() { Messages = history },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
EnableThinking = false,
}
});
Console.WriteLine(completion.Output.Choices[0].Message.Content);
// Cleanup
await dashScopeClient.OpenAiCompatibleDeleteFileAsync(uploadedFile.Id);
With Microsoft.Extensions.AI, pass the id of an uploaded file as a HostedFileContent and upload it with AsHostedFileClient(), see Hosted files.
DownloadFileAsync downloads the content of a stored file whatever its purpose: the result files of batch jobs come from GET /compatible-mode/v1/files/{file_id}/content, which serves no other file, every other file from the download link of its detail. OpenAiCompatibleGetFileContentAsync calls that content endpoint alone.
await using var content = await dashScopeClient.DownloadFileAsync(uploadedFile.Id);
DownloadFromUrlAsync downloads any resource by the url the service answered, e.g. a generated image. The urls are signed, so the request is made by the HTTP client that carries no api key, the one DownloadFileAsync follows the download links with (the named client Cnblogs.DashScope.FileStorage with ASP.NET Core). The content comes back as a DashScopeDownloadStream, a stream that also tells the media type the response named:
await using var image = await dashScopeClient.DownloadFromUrlAsync(response.Output.Choices[0].Message.Content[0].Image);
Console.WriteLine(image.MediaType); // image/png
await image.CopyToAsync(File.Create("image.png"));
PPT Generation (Qwen-doc-turbo)
Use qwen-doc-turbo with the PPT skill to generate a presentation from a document URL or prompt. Pass the document link via TextChatMessage.DocUrl and enable the PPT skill through Parameters.Skill.
DashScopeModelSkill.PptCreative— generate a presentation in creative mode (no template required).DashScopeModelSkill.PptGeneral(templateId)— generate in general mode using the given template.
The model emits the slide storyboard in ReasoningContent, and the final reply Content contains a download URL for the generated .pptx file.
var messages = new List<TextChatMessage>
{
TextChatMessage.System("You are a helpful assistant"),
TextChatMessage.DocUrl("生成一个ppt", ["https://example.com/product-manual.docx"]),
};
var completion = client.GetTextCompletionStreamAsync(
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
{
Model = "qwen-doc-turbo",
Input = new TextGenerationInput() { Messages = messages },
Parameters = new TextGenerationParameters()
{
ResultFormat = "message",
IncrementalOutput = true,
Skill = [DashScopeModelSkill.PptCreative]
}
});
var reply = new StringBuilder();
var reasoning = false;
TextGenerationTokenUsage? usage = null;
await foreach (var chunk in completion)
{
var choice = chunk.Output.Choices![0];
if (string.IsNullOrEmpty(choice.Message.ReasoningContent) == false)
{
if (reasoning == false)
{
reasoning = true;
Console.Write("Reasoning > ");
}
Console.Write(choice.Message.ReasoningContent);
continue;
}
if (reasoning && string.IsNullOrEmpty(choice.Message.Content.Text) == false)
{
reasoning = false;
Console.WriteLine();
Console.Write("Assistant > ");
}
Console.Write(choice.Message.Content);
reply.Append(choice.Message.Content);
usage = chunk.Usage;
}
Console.WriteLine();
if (usage != null)
{
Console.WriteLine($"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/total({usage.TotalTokens})");
}
// reply.ToString() contains the .pptx download URL
OCR
Base example of OCR
// upload file
await using var tilted = File.OpenRead("tilted.png");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", tilted, "tilted.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages = new List<MultimodalMessage>();
messages.Add(
MultimodalMessage.User(
[
// set enableRotate to true if your source image is tilted.
MultimodalMessageContent.ImageContent(ossLink, enableRotate: true),
]));
var completion = client.GetMultimodalGenerationStreamAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters()
{
IncrementalOutput = true,
}
});
var reply = new StringBuilder();
var first = false;
MultimodalTokenUsage? usage = null;
await foreach (var chunk in completion)
{
var choice = chunk.Output.Choices[0];
if (first)
{
first = false;
Console.Write("Assistant > ");
}
if (choice.Message.Content.Count == 0)
{
continue;
}
Console.Write(choice.Message.Content[0].Text);
reply.Append(choice.Message.Content[0].Text);
usage = chunk.Usage;
}
Console.WriteLine();
messages.Add(MultimodalMessage.Assistant([MultimodalMessageContent.TextContent(reply.ToString())]));
if (usage != null)
{
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/image({usage.ImageTokens})/total({usage.TotalTokens})");
}
Advanced Recognition
When using this task, do not enable streaming. Otherwise, completion.Output.Choices[0].Message.Content[0].OcrResult.WordsInfo will be null.
In addition to the standard text content, this task also returns the coordinates of the text.
To call this built-in task, set Parameters.OcrOptions.Task to advanced_recognition. No additional prompt is required.

var messages = new List<MultimodalMessage>();
messages.Add(
MultimodalMessage.User(
[
MultimodalMessageContent.ImageContent(ossLink),
]));
var completion = client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "advanced_recognition"
}
}
});
Output usage:
Console.WriteLine("Text:");
Console.WriteLine(completion.Output.Choices[0].Message.Content[0].Text);
Console.WriteLine("WordsInfo:");
foreach (var info in completion.Output.Choices[0].Message.Content[0].OcrResult!.WordsInfo!)
{
var location = $"[{string.Join(',', info.Location)}]";
var rect = $"[{string.Join(',', info.RotateRect)}]";
Console.WriteLine(info.Text);
Console.WriteLine($"Location: {location}");
Console.WriteLine($"RotateRect: {rect}");
Console.WriteLine();
}
Output:
Text:
```json
[
{"rotate_rect": [236, 254, 115, 299, 90], "text": "OpenAI 兼容"},
{"rotate_rect": [646, 254, 115, 269, 90], "text": "DashScope"},
{"rotate_rect": [236, 684, 115, 163, 90], "text": "Python"},
{"rotate_rect": [492, 684, 115, 105, 90], "text": "Java"},
{"rotate_rect": [712, 684, 115, 85, 90], "text": "curl"}
]
```
WordsInfo:
OpenAI 兼容
Location: [46,55,205,55,205,87,46,87]
RotateRect: [125,71,159,32,0]
DashScope
Location: [272,55,415,55,415,87,272,87]
RotateRect: [344,71,32,143,90]
Python
Location: [82,175,169,175,169,207,82,207]
RotateRect: [126,191,32,87,90]
Java
Location: [234,175,289,175,289,207,234,207]
RotateRect: [262,191,55,32,0]
curl
Location: [356,175,401,175,401,207,356,207]
RotateRect: [378,191,32,45,90]
Key Information Extraction
When using built-in tasks, it is not recommended to enable streaming; otherwise, completion.Output.Choices[0].Message.Content[0].OcrResult.KvResult will be null.
To invoke this built-in task, set Parameters.OcrOptions.Task to key_information_extraction. No additional text information needs to be provided.
You can customize the output JSON format via Parameters.OcrOptions.TaskConfig.ResultSchema (with a maximum of 3 levels of nesting). If left blank, all fields will be output by default.
For example, suppose we want to extract objects of the following type from an image (JSON property names should, as much as possible, be based on the text present in the image):

internal class ReceiptModel()
{
[JsonPropertyName("乘车日期")]
public string? Date { get; init; }
[JsonPropertyName("发票")]
public ReceiptSerials? Serials { get; init; }
}
internal class ReceiptSerials
{
[JsonPropertyName("发票代码")]
public string? Code { get; init; }
[JsonPropertyName("发票号码")]
public string? Serial { get; init; }
}
Property could be null if model failed to extract value for it.
Example request:
await using var file = File.OpenRead("receipt.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", file, "receipt.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages =
new List<MultimodalMessage> { MultimodalMessage.User([MultimodalMessageContent.ImageContent(ossLink)]) };
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "key_information_extraction",
TaskConfig = new MultimodalOcrTaskConfig()
{
ResultSchema = new Dictionary<string, object>()
{
{
"发票",
new Dictionary<string, string>()
{
{ "发票代码", "提取图中的发票代码,通常为一组数字或字母组合" },
{ "发票号码", "提取发票上的号码,通常由纯数字组成。" }
}
},
{ "乘车日期", "对应图中乘车日期时间,格式为年-月-日,比如2025-03-05" }
}
}
}
}
});
Consume:
KvResult is JsonElement,you can deserialize it to any type you desire, or you could just use Dictionary<string, JsonElement?> .
Console.WriteLine("Text:");
Console.WriteLine(completion.Output.Choices[0].Message.Content[0].Text);
Console.WriteLine("KvResults:");
var model = completion.Output.Choices[0].Message.Content[0].OcrResult!.KvResult?.Deserialize<ReceiptModel>();
Console.WriteLine($"Date: {model?.Date}");
Console.WriteLine($"Code: {model?.Serials?.Code}");
Console.WriteLine($"Serial: {model?.Serials?.Serial}");
/*
Text:
```json
{
"乘车日期": "2013-06-29",
"发票": {
"发票代码": "221021325353",
"发票号码": "10283819"
}
}
```
KvResults:
Date: 2013-06-29
Code: 221021325353
Serial: 10283819
Usage: in(524)/out(65)/image(310)/total(589)
*/
Table Parsing
To invoke this built-in task, set Parameters.OcrOptions.Task to table_parsing. No additional text information needs to be provided.
This task will extract tables from images and return them in HTML format.
Example:

await using var file = File.OpenRead("table.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", file, "table.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages =
new List<MultimodalMessage> { MultimodalMessage.User([MultimodalMessageContent.ImageContent(ossLink)]) };
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "table_parsing",
}
}
});
Console.WriteLine(completion.Output.Choices[0].Message.Content[0].Text);
Return value(Model would wrap the html code in a markdown code fence):
```html
<table>
<tr>
<td>Record of test data</td>
</tr>
<tr>
<td>Project name:2B</td>
<td>Control No.CEPRI-D-JS1-JS-057-2022-003</td>
</tr>
<tr>
<td>Case name</td>
<td>Test No.3 Conductor rupture GL+GR(max angle)</td>
<td>Last load grade:</td>
<td>0%</td>
<td>Current load grade:</td>
</tr>
<tr>
<td>Measure</td>
<td>Load point</td>
<td>Load method</td>
<td>Actual Load(%)</td>
<td>Actual Load(kN)</td>
</tr>
<tr>
<td>channel</td>
<td>V1</td>
<td>活载荷</td>
<td>147.95</td>
<td>0.815</td>
</tr>
<tr>
<td>V03</td>
<td>V2</td>
<td>活载荷</td>
<td>111.75</td>
<td>0.615</td>
</tr>
<tr>
<td>V04</td>
<td>V3</td>
<td>活载荷</td>
<td>9.74</td>
<td>1.007</td>
</tr>
<tr>
<td>V05</td>
<td>V4</td>
<td>活载荷</td>
<td>7.88</td>
<td>0.814</td>
</tr>
<tr>
<td>V06</td>
<td>V5</td>
<td>活载荷</td>
<td>8.11</td>
<td>0.780</td>
</tr>
<tr>
<td>V07</td>
<td>V6</td>
<td>活载荷</td>
<td>8.54</td>
<td>0.815</td>
</tr>
<tr>
<td>V08</td>
<td>V7</td>
<td>活载荷</td>
<td>6.77</td>
<td>0.700</td>
</tr>
<tr>
<td>V09</td>
<td>V8</td>
<td>活载荷</td>
<td>8.59</td>
<td>0.888</td>
</tr>
<tr>
<td>L01</td>
<td>L1</td>
<td>活载荷</td>
<td>13.33</td>
<td>3.089</td>
</tr>
<tr>
<td>L02</td>
<td>L2</td>
<td>活载荷</td>
<td>9.69</td>
<td>2.247</td>
</tr>
<tr>
<td>L03</td>
<td>L3</td>
<td></td>
<td>2.96</td>
<td>1.480</td>
</tr>
<tr>
<td>L04</td>
<td>L4</td>
<td></td>
<td>3.40</td>
<td>1.700</td>
</tr>
<tr>
<td>L05</td>
<td>L5</td>
<td></td>
<td>2.45</td>
<td>1.224</td>
</tr>
<tr>
<td>L06</td>
<td>L6</td>
<td></td>
<td>2.01</td>
<td>1.006</td>
</tr>
<tr>
<td>L07</td>
<td>L7</td>
<td></td>
<td>2.38</td>
<td>1.192</td>
</tr>
<tr>
<td>L08</td>
<td>L8</td>
<td></td>
<td>2.10</td>
<td>1.050</td>
</tr>
<tr>
<td>T01</td>
<td>T1</td>
<td>活载荷</td>
<td>25.29</td>
<td>3.073</td>
</tr>
<tr>
<td>T02</td>
<td>T2</td>
<td>活载荷</td>
<td>27.39</td>
<td>3.327</td>
</tr>
<tr>
<td>T03</td>
<td>T3</td>
<td>活载荷</td>
<td>8.03</td>
<td>2.543</td>
</tr>
<tr>
<td>T04</td>
<td>T4</td>
<td>活载荷</td>
<td>11.19</td>
<td>3.542</td>
</tr>
<tr>
<td>T05</td>
<td>T5</td>
<td>活载荷</td>
<td>11.34</td>
<td>3.592</td>
</tr>
<tr>
<td>T06</td>
<td>T6</td>
<td>活载荷</td>
<td>16.47</td>
<td>5.217</td>
</tr>
<tr>
<td>T07</td>
<td>T7</td>
<td>活载荷</td>
<td>11.05</td>
<td>3.498</td>
</tr>
<tr>
<td>T08</td>
<td>T8</td>
<td>活载荷</td>
<td>8.66</td>
<td>2.743</td>
</tr>
<tr>
<td>T09</td>
<td>WT1</td>
<td>活载荷</td>
<td>36.56</td>
<td>2.365</td>
</tr>
<tr>
<td>T10</td>
<td>WT2</td>
<td>活载荷</td>
<td>24.55</td>
<td>2.853</td>
</tr>
<tr>
<td>T11</td>
<td>WT3</td>
<td>活载荷</td>
<td>38.06</td>
<td>4.784</td>
</tr>
<tr>
<td>T12</td>
<td>WT4</td>
<td>活载荷</td>
<td>37.70</td>
<td>5.030</td>
</tr>
<tr>
<td>T13</td>
<td>WT5</td>
<td>活载荷</td>
<td>30.48</td>
<td>4.524</td>
</tr>
</table>
```
Document Parsing
To invoke this built-in task, set Parameters.OcrOptions.Task to document_parsing. No additional text information needs to be provided.
This task read images(usually scanned PDF) and return them in LaTeX format.
Example:

await using var file = File.OpenRead("scanned.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", file, "scanned.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages =
new List<MultimodalMessage> { MultimodalMessage.User([MultimodalMessageContent.ImageContent(ossLink)]) };
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "document_parsing",
}
}
});
Returns:
```latex
\section*{Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution}
Peng Wang* \quad Shuai Bai* \quad Sinan Tan* \quad Shijie Wang* \quad Zhihao Fan* \quad Jinze Bai*? \\
Keqin Chen \quad Xuejing Liu \quad Jialin Wang \quad Wenbin Ge \quad Yang Fan \quad Kai Dang \quad Mengfei Du \\
Xuancheng Ren \quad Rui Men \quad Dayiheng Liu \quad Chang Zhou \quad Jingren Zhou \quad Junyang Lin*? \\
Qwen Team \quad Alibaba Group
\begin{abstract}
We present the Qwen2-VL Series, an advanced upgrade of the previous Qwen-VL models that redefines the conventional predetermined-resolution approach in visual processing. Qwen2-VL introduces the Naive Dynamic Resolution mechanism, which enables the model to dynamically process images of varying resolutions into different numbers of visual tokens. This approach allows the model to generate more efficient and accurate visual representations, closely aligning with human perceptual processes. The model also integrates Multimodal Rotary Position Embedding (M-RoPE), facilitating the effective fusion of positional information across text, images, and videos. We employ a unified paradigm for processing both images and videos, enhancing the model's visual perception capabilities. To explore the potential of large multimodal models, Qwen2-VL investigates the scaling laws for large vision-language models (LVLMS). By scaling both the model size-with versions at 2B, 8B, and 72B parameters-and the amount of training data, the Qwen2-VL Series achieves highly competitive performance. Notably, the Qwen2-VL-72B model achieves results comparable to leading models such as GPT-4o and Claude3.5-Sonnet across various multimodal benchmarks, outperforming other generalist models. Code is available at \url{https://github.com/QwenLM/Qwen2-VL}.
\end{abstract}
\section{Introduction}
In the realm of artificial intelligence, Large Vision-Language Models (LVLMS) represent a significant leap forward, building upon the strong textual processing capabilities of traditional large language models. These advanced models now encompass the ability to interpret and analyze a broader spectrum of data, including images, audio, and video. This expansion of capabilities has transformed LVLMS into indispensable tools for tackling a variety of real-world challenges. Recognized for their unique capacity to condense extensive and intricate knowledge into functional representations, LVLMS are paving the way for more comprehensive cognitive systems. By integrating diverse data forms, LVLMS aim to more closely mimic the nuanced ways in which humans perceive and interact with their environment. This allows these models to provide a more accurate representation of how we engage with and perceive our environment.
Recent advancements in large vision-language models (LVLMS) (Li et al., 2023c; Liu et al., 2023b; Dai et al., 2023; Zhu et al., 2023; Huang et al., 2023a; Bai et al., 2023b; Liu et al., 2023a; Wang et al., 2023b; OpenAI, 2023; Team et al., 2023) have led to significant improvements in a short span. These models (OpenAI, 2023; Touvron et al., 2023a,b; Chiang et al., 2023; Bai et al., 2023a) generally follow a common approach of \textit{visual encoder} $\rightarrow$ \textit{cross-modal connector} $\rightarrow$ \textit{LLM}. This setup, combined with next-token prediction as the primary training method and the availability of high-quality datasets (Liu et al., 2023a; Zhang et al., 2023; Chen et al., 2023b);
*Equal core contribution, ?Corresponding author
```
Formula Recognition
To invoke this built-in task, set Parameters.OcrOptions.Task to formula_recognition. No additional text information needs to be provided.
This task read images(like handwriting formulas) and return them in LaTeX format.
Example:

// upload file
await using var file = File.OpenRead("math.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", file, "math.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages =
new List<MultimodalMessage> { MultimodalMessage.User([MultimodalMessageContent.ImageContent(ossLink)]) };
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "formula_recognition",
}
}
});
Console.WriteLine("LaTeX:");
Console.WriteLine(completion.Output.Choices[0].Message.Content[0].Text);
if (completion.Usage != null)
{
var usage = completion.Usage;
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/image({usage.ImageTokens})/total({usage.TotalTokens})");
}
Returns:
```latex
\begin{align*}
\tilde{G}(x) &= \frac{\alpha}{\kappa}x, \quad \tilde{T}_i = T, \quad \tilde{H}_i = \tilde{\kappa}T, \quad \tilde{\lambda}_i = \frac{1}{\kappa}\sum_{j=1}^{m}\omega_j - z_i, \\
L(\{p_n\}; m^n) + L(\{x^n\}, m^n) + L(\{m^n\}; q_n) &= L(m^n; q_n) \\
I^{m_n} - (L+1) &= z + \int_0^1 I^{m_n} - (L)z \leq x_m | L^{m_n} - (L) |^3 \\
&\leq \kappa\partial_1\psi(x) + \frac{\kappa^3}{6}\partial_2^3\psi(x) - V(x) \psi(x) = \int d^3y K(x,y) \psi(y), \\
\int_{B_{\kappa}(0)} I^{m}(w)^2 d\gamma &= \lim_{n\to\infty} \int_{B_{\kappa}(0)} r\psi(w_n)^2 d\gamma = \lim_{n\to\infty} \int_{B_{\kappa}(y_n)} d\gamma \geq \beta > 0,
\end{align*}
```
$$ \begin{align*} \tilde{G}(x) &= \frac{\alpha}{\kappa}x, \quad \tilde{T}i = T, \quad \tilde{H}i = \tilde{\kappa}T, \quad \tilde{\lambda}i = \frac{1}{\kappa}\sum{j=1}^{m}\omega_j - z_i, \ L({p_n}; m^n) + L({x^n}, m^n) + L({m^n}; q_n) &= L(m^n; q_n) \ I^{m_n} - (L+1) &= z + \int_0^1 I^{m_n} - (L)z \leq x_m | L^{m_n} - (L) |^3 \ &\leq \kappa\partial_1\psi(x) + \frac{\kappa^3}{6}\partial_2^3\psi(x) - V(x) \psi(x) = \int d^3y K(x,y) \psi(y), \ \int{B{\kappa}(0)} I^{m}(w)^2 d\gamma &= \lim_{n\to\infty} \int_{B_{\kappa}(0)} r\psi(w_n)^2 d\gamma = \lim_{n\to\infty} \int_{B_{\kappa}(y_n)} d\gamma \geq \beta > 0, \end{align*} $$
Text Recognition
To invoke this built-in task, set Parameters.OcrOptions.Task to text_recognition. No additional text information needs to be provided.
This task read the images and returns content in plain text(Chinese and English only).
Example:

// upload file
await using var file = File.OpenRead("webpage.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", file, "webpage.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages =
new List<MultimodalMessage> { MultimodalMessage.User([MultimodalMessageContent.ImageContent(ossLink)]) };
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "text_recognition",
}
}
});
Returns
OpenAI 兼容 DashScope
Python Java curl
Multilanguage
To invoke this built-in task, set Parameters.OcrOptions.Task to multi_lan. No additional text information needs to be provided.
This task read the images and returns content in plain text(Support more languages).

await using var file = File.OpenRead("multilanguage.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-vl-ocr-latest", file, "multilanguage.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages =
new List<MultimodalMessage> { MultimodalMessage.User([MultimodalMessageContent.ImageContent(ossLink)]) };
var completion = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-vl-ocr-latest",
Input = new MultimodalInput { Messages = messages },
Parameters = new MultimodalParameters()
{
OcrOptions = new MultimodalOcrOptions()
{
Task = "multi_lan",
}
}
});
Returns
INTERNATIONAL
MOTHER LANGUAGE
DAY
你好!
Прив?т!
Bonjour!
Merhaba!
Ciao!
Hello!
Ola!
????
Salam!
GUI
Use gui-plus to generate standardized operational information based on screenshots and user intent.
Currently, the main capabilities are implemented through the System Prompt, where you can configure the model’s available capabilities and the output JSON format.
Sample system prompt:
## 1. Core Role
You are an expert AI Vision Operation Agent. Your task is to analyze computer screenshots, understand user instructions, and then break down the task into single, precise GUI atomic operations.
## 2. [CRITICAL] JSON Schema & Absolute Rules
Your output **must** be a JSON object that strictly adheres to the following rules. **Any deviation will result in failure**.
- **[R1] Strict JSON**: Your response **must** be *and only be* a JSON object. Do not add any text, comments, or explanations before or after the JSON code block.
- **[R2] Strict `thought` Structure**: The `thought` object must contain a single sentence briefly describing your thought process. For example: "The user wants to open the browser. I see the Chrome icon on the desktop, so the next step is to click it."
- **[R3] Precise `action` Value**: The value of the `action` field **must** be an uppercase string defined in `## 3. Toolset` (e.g., `"CLICK"`, `"TYPE"`). No leading/trailing spaces or case variations are allowed.
- **[R4] Strict `parameters` Structure**: The structure of the `parameters` object **must** be **perfectly identical** to the template defined for the selected Action in `## 3. Toolset`. Key names and value types must match exactly.
## 3. Toolset (Available Actions)
### CLICK
- **Description**: Click on the screen.
- **Parameters Template**:
{
"x": <integer>,
"y": <integer>,
"description": "<string, optional: A short string describing what you are clicking on, e.g., 'Chrome browser icon' or 'Login button'.>"
}
### TYPE
- **Description**: Type text.
- **Parameters Template**:
{
"text": "<string>",
"needs_enter": <boolean>
}
### SCROLL
- **Description**: Scroll the window.
- **Parameters Template**:
{
"direction": "<'up' or 'down'>",
"amount": "<'small', 'medium', or 'large'>"
}
### KEY_PRESS
- **Description**: Press a function key.
- **Parameters Template**:
{
"key": "<string: e.g., 'enter', 'esc', 'alt+f4'>"
}
### FINISH
- **Description**: Task completed successfully.
- **Parameters Template**:
{
"message": "<string: A summary of the task completion>"
}
### FAILE
- **Description**: Task cannot be completed.
- **Parameters Template**:
{
"reason": "<string: A clear explanation of the failure reason>"
}
## 4. Thinking and Decision Framework
Before generating each action, strictly follow the following thought-verification process:
**Goal Analysis**: What is the user's ultimate goal?
**Screen Observation (Grounded Observation)**: Carefully analyze the screenshot. Your decisions must be based on visual evidence present in the screenshot. If you cannot see an element, you cannot interact with it.
**Action Decision**: Based on the goal and visible elements, select the most appropriate tool.
**Construct Output**:
a. Record your thought process in the `thought` field.
b. Select an `action`.
c. Precisely copy the `parameters` template for that action and fill in the values.
**Final Verification (Self-Correction)**: Before outputting, perform a final check:
- Is my response pure JSON?
- Is the `action` value correct (uppercase, no spaces)?
- Is the `parameters` structure 100% identical to the template? For example, for `CLICK`, are there separate `x` and `y` keys, and are their values integers?
Request:
var messages = new List<MultimodalMessage>
{
MultimodalMessage.System([MultimodalMessageContent.TextContent(SystemPrompt)]),
MultimodalMessage.User(
[
MultimodalMessageContent.ImageContent(
"https://img.alicdn.com/imgextra/i2/O1CN016iJ8ob1C3xP1s2M6z_!!6000000000026-2-tps-3008-1758.png"),
MultimodalMessageContent.TextContent("Open browser")
])
};
var completion = client.GetMultimodalGenerationStreamAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "gui-plus",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters() { IncrementalOutput = true, }
});
Response:
{
"thought": "用户想打开浏览器,我看到了桌面上的Google Chrome图标,因此下一步是点击它。",
"action": "CLICK",
"parameters": {
"x": 1089,
"y": 123
}
}
Then you can execute the command that model returns, and reply the screenshot with next intension.
Vision
Image Generation
Text-to-Image
Use GetMultimodalGenerationAsync with model qwen-image-2.0-pro to generate images synchronously.
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-image-2.0-pro",
Input = new MultimodalInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("A futuristic cityscape at sunset")
})
}
},
Parameters = new MultimodalParameters()
{
NegativePrompt = "low resolution, low quality, deformed limbs, distorted fingers, oversaturated, wax figure, lack of facial detail, overly smooth, AI artifacts, chaotic composition, blurry or distorted text.",
N = 1,
PromptExtend = true,
Watermark = false,
Size = "2048*2048"
}
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
Wan models work the same way: wan2.6-t2i supports synchronous calls via the same API and allows free image size as long as total pixels stay in [12801280, 14401440] and aspect ratio stays in [1:4, 4:1]. Models at wan2.5-t2i-preview and below only support the async task API (see Text-to-Image (Async Task)).
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "wan2.6-t2i",
Input = new MultimodalInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
})
}
},
Parameters = new MultimodalParameters()
{
N = 1,
Size = "1280*1280",
PromptExtend = true,
Watermark = false,
Seed = 233
}
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
The wan2.7-image / wan2.7-image-pro models add thinking mode (ThinkingMode), color palette control (ColorPalette, ratios sum up to 100.00%), sequential image group generation (EnableSequential, n becomes the max count 1-12) and interactive editing with bounding boxes (BboxList, one list of [x1, y1, x2, y2] boxes per input image). wan2.7-image-pro supports 4K output for text-to-image (2K for editing and groups).
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "wan2.7-image",
Input = new MultimodalInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
})
}
},
Parameters = new MultimodalParameters()
{
Size = "1K",
N = 1,
Watermark = false,
ThinkingMode = true,
ColorPalette =
[
new MultimodalColorPalette("#C2D1E6", "50.00%"),
new MultimodalColorPalette("#CDD8E9", "30.00%"),
new MultimodalColorPalette("#B5C8DB", "20.00%")
]
}
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
The lightweight z-image-turbo model generates a single image fast over the same API, with Chinese/English text rendering. size defaults to 1024*1536 with total pixels in [512512, 20482048]; note that prompt_extend defaults to false and is billed higher when enabled — when set to true the response also carries the rewritten prompt and the reasoning process (ReasoningContent).
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "z-image-turbo",
Input = new MultimodalInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("一只坐着的橘黄色的猫,表情愉悦,活泼可爱,逼真准确。")
})
}
},
Parameters = new MultimodalParameters() { PromptExtend = false, Seed = 233, Size = "1120*1440" }
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
Image Editing
Qwen-image edit models (qwen-image-2.0-pro, qwen-image-2.0, and the unified generation-and-editing models qwen-image-3.0-pro, qwen-image-3.0, qwen-image-2.1-pro, qwen-image-2.1-turbo) edit images by instruction through the same multimodal API: 13 input images (up to 10 for the qwen-image-2.1 series) followed by one text instruction, generating 16 images. When multiple images are provided, the output aspect ratio follows the last one.
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-image-2.0-pro",
Input = new MultimodalInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
[
MultimodalMessageContent.ImageContent("<base-image-url>"),
MultimodalMessageContent.ImageContent("<style-image-url>"),
MultimodalMessageContent.TextContent("Use the city photo in image 1 as the base. Do not change the buildings, streets, vehicles or people. Draw three cartoon figures from image 2 around the building in a flat poster illustration style.")
])
}
},
Parameters = new MultimodalParameters()
{
NegativePrompt = "low resolution, low quality, chaotic composition",
N = 1,
PromptExtend = true,
PromptExtendMode = "direct",
Seed = 233,
Size = "1328*1328",
Watermark = false
}
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Edited image url: {url}");
PromptExtendMode controls how PromptExtend rewrites the prompt: direct (default, DPE) or agent (APE, text-to-image only, rejected for image editing). The unified models also accept the same message-based input as an async task via CreateImageGenerationTaskAsync / GetImageGenerationTaskAsync.
To edit a local image, upload it first and pass the returned OSS link:
await using var image = File.OpenRead("input.jpg");
var ossLink = await client.UploadTemporaryFileAsync("qwen-image-2.0-pro", image, "input.jpg");
Console.WriteLine($"File uploaded: {ossLink}");
var messages = new List<MultimodalMessage>
{
MultimodalMessage.User(
[
MultimodalMessageContent.ImageContent(ossLink),
MultimodalMessageContent.TextContent("Please enhance the clarity of this photo")
])
};
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-image-2.0-pro",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters()
{
NegativePrompt = "low resolution, low quality, deformed limbs, distorted fingers, oversaturated, wax figure, lack of facial detail, overly smooth, AI artifacts, chaotic composition, blurry or distorted text.",
N = 1,
PromptExtend = true,
Watermark = false,
Size = "2048*2048"
}
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
wan2.6-image supports image editing with 1~4 reference images, and interleaved text-image output when EnableInterleave is set to true (streaming only).
var response = await client.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "wan2.6-image",
Input = new MultimodalInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("参考图1的风格和图2的背景,生成番茄炒蛋"),
MultimodalMessageContent.ImageContent("<reference-image-1-url>"),
MultimodalMessageContent.ImageContent("<reference-image-2-url>")
})
}
},
Parameters = new MultimodalParameters() { N = 1, EnableInterleave = false, Size = "1K" }
});
var url = response.Output.Choices[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
The wan2.5-i2i-preview model edits images by instruction with up to 3 reference images, keeping subject consistency across images. It runs as an async task and reports the rewritten prompt in the result:
var response = await client.CreateImage2ImageSynthesisTaskAsync(
new ModelRequest<Image2ImageSynthesisInput, IImage2ImageSynthesisParameters>()
{
Model = "wan2.5-i2i-preview",
Input = new Image2ImageSynthesisInput()
{
Prompt = "将图1中的闹钟放置到图2的餐桌的花瓶旁边位置",
Images = ["<reference-image-1-url>", "<reference-image-2-url>"]
},
Parameters = new Image2ImageSynthesisParameters() { N = 1 }
});
var task = await client.GetImage2ImageSynthesisTaskAsync(response.Output.TaskId);
Console.WriteLine($"Edited image url: {task.Output.Results?[0].Url}, actual prompt: {task.Output.Results?[0].ActualPrompt}");
The classic wanx2.1-imageedit model edits images through predefined functions via an async task, using the same input type with a Function:
var response = await client.CreateImage2ImageSynthesisTaskAsync(
new ModelRequest<Image2ImageSynthesisInput, IImage2ImageSynthesisParameters>()
{
Model = "wanx2.1-imageedit",
Input = new Image2ImageSynthesisInput()
{
Function = "description_edit",
Prompt = "把她的头发修改为红色。",
BaseImageUrl = "<your-image-url>"
},
Parameters = new Image2ImageSynthesisParameters() { N = 1 }
});
var task = await client.GetImage2ImageSynthesisTaskAsync(response.Output.TaskId);
Console.WriteLine($"Edited image url: {task.Output.Results?[0].Url}");
Available functions include description_edit, description_edit_with_mask (requires MaskImageUrl), stylization_all, stylization_local, remove_watermark, expand, super_resolution, colorization, doodle and control_cartoon_feature; function-specific parameters like Strength, UpscaleFactor and the four *Scale properties live on Image2ImageSynthesisParameters.
The wanx-sketch-to-image-lite model turns a doodle/sketch into a complete image via the same task API, taking the sketch url on SketchImageUrl (aspect ratio should match the output, white background recommended). SketchWeight (0-10, defaults to 10) controls how close the output stays to the sketch; SketchExtraction = true extracts sketch edges from an RGB input; SketchColor lists the RGB pen-stroke colors when the sketch lines are colored (ignored with SketchExtraction):
var response = await client.CreateImage2ImageSynthesisTaskAsync(
new ModelRequest<Image2ImageSynthesisInput, IImage2ImageSynthesisParameters>()
{
Model = "wanx-sketch-to-image-lite",
Input = new Image2ImageSynthesisInput()
{
Prompt = "一棵参天大树",
SketchImageUrl = "<your-sketch-url>"
},
Parameters = new Image2ImageSynthesisParameters()
{
Size = "768*768",
N = 1,
SketchWeight = 3,
Style = "<watercolor>"
}
});
var task = await client.GetImage2ImageSynthesisTaskAsync(response.Output.TaskId);
Console.WriteLine($"Generated image url: {task.Output.Results?[0].Url}");
Text-to-Image (Async Task)
Use CreateImageSynthesisTaskAsync to create a task, then poll GetImageSynthesisTaskAsync to check completion status.
var response = await client.CreateImageSynthesisTaskAsync(
new ModelRequest<ImageSynthesisInput, IImageSynthesisParameters>()
{
Model = "qwen-image-plus",
Input = new ImageSynthesisInput() { Prompt = "A futuristic cityscape at sunset" },
Parameters = new ImageSynthesisParameters()
{
Size = "1664*928",
N = 1,
PromptExtend = true,
Watermark = false
}
});
var taskId = response.Output.TaskId;
Console.WriteLine($"Task Created: {taskId}");
var waited = 0;
var timeout = 300;
do
{
var task = await client.GetImageSynthesisTaskAsync(taskId);
if (task.Output.TaskStatus == DashScopeTaskStatus.Succeeded)
{
Console.WriteLine($"Image URL: {task.Output.Results?.FirstOrDefault()?.Url}");
break;
}
if (task.Output.TaskStatus == DashScopeTaskStatus.Failed)
{
Console.WriteLine($"Task failed: {task.Output.Message}");
break;
}
Console.WriteLine($"Task Status: {task.Output.TaskStatus}");
await Task.Delay(TimeSpan.FromSeconds(10));
waited += 10;
} while (waited < timeout);
wan2.6-t2i uses a new async protocol: create the task with CreateImageGenerationTaskAsync, filling the multimodal Messages on ImageGenerationInput (the legacy wanx style repaint models use ImageUrl + StyleIndex on the same type instead), then poll with GetImageGenerationTaskAsync:
var response = await client.CreateImageGenerationTaskAsync(
new ModelRequest<ImageGenerationInput, IMultimodalParameters>()
{
Model = "wan2.6-t2i",
Input = new ImageGenerationInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("一间有着精致窗户的花店,漂亮的木质门,摆放着花朵")
})
}
},
Parameters = new MultimodalParameters() { N = 1, Size = "1280*1280", Seed = 233 }
});
var task = await client.GetImageGenerationTaskAsync(response.Output.TaskId);
var url = task.Output.Choices?[0].Message.Content[0].Image;
Console.WriteLine($"Generated image url: {url}");
Kling (kling/kling-v3-image-generation, kling/kling-v3-omni-image-generation) and Vidu (vidu/vidu-image_reference2image, vidu/vidu-image-pro_reference2image, vidu/vidu-image-lite_reference2image, vidu/viduq3-fast_reference2image, vidu/viduq2-pro_reference2image, vidu/viduq2-fast_reference2image) image models run on the same task API with optional reference images in the message content. Kling takes AspectRatio (16:9 / 9:16 / 1:1) with Resolution (1k / 2k, 4k on omni) instead of Size; kling-v3-omni additionally generates a storyboard series with ResultType = "series" + SeriesAmount (2-9) and can keep subjects from the Kling subject list via ElementList on the input. Vidu takes Size / Seed and always returns one image (N = 1).
var response = await client.CreateImageGenerationTaskAsync(
new ModelRequest<ImageGenerationInput, IMultimodalParameters>()
{
Model = "kling/kling-v3-omni-image-generation",
Input = new ImageGenerationInput()
{
Messages = new List<MultimodalMessage>()
{
MultimodalMessage.User(
new List<MultimodalMessageContent>()
{
MultimodalMessageContent.TextContent("参考图1的风格和图2的背景,生成番茄炒蛋"),
MultimodalMessageContent.ImageContent("<reference-image-1-url>"),
MultimodalMessageContent.ImageContent("<reference-image-2-url>")
})
}
},
Parameters = new MultimodalParameters()
{
N = 4,
ResultType = "series",
SeriesAmount = 4,
AspectRatio = "1:1",
Resolution = "1k"
}
});
var task = await client.GetImageGenerationTaskAsync(response.Output.TaskId);
// series mode returns all images in the content of the single choice
var urls = task.Output.Choices?[0].Message.Content.Select(c => c.Image).ToList();
Console.WriteLine($"Usage: count({task.Usage?.ImageCount}) size({task.Usage?.Size}) tier({task.Usage?.SR})");
Image Translation
Translate the text within an image while preserving the original layout. With qwen-mt-image-2.0 you can call GetImage2ImageSynthesisAsync to translate synchronously - the call blocks until the translated image is ready. The 2.0 model has no language restrictions (any of the 55 supported languages works for both source and target).
var response = await client.GetImage2ImageSynthesisAsync(
new ModelRequest<Image2ImageSynthesisInput>()
{
Model = "qwen-mt-image-2.0",
Input = new Image2ImageSynthesisInput()
{
SourceLang = "zh",
TargetLang = "en",
ImageUrl = "<your-image-url>"
}
});
Console.WriteLine($"Translated image url: {response.Output.ImageUrl}");
For qwen-mt-image (which requires the source or target language to be Chinese or English), use the async task flow: create the task with CreateImage2ImageSynthesisTaskAsync and an Image2ImageSynthesisInput, then poll GetImage2ImageSynthesisTaskAsync for the result.
var response = await client.CreateImage2ImageSynthesisTaskAsync(
new ModelRequest<Image2ImageSynthesisInput, IImage2ImageSynthesisParameters>()
{
Model = "qwen-mt-image",
Input = new Image2ImageSynthesisInput()
{
SourceLang = "zh",
TargetLang = "en",
ImageUrl = "https://example.com/image-with-text.jpg",
Ext = new Image2ImageSynthesisInputExt()
{
// Hint for the scene and translation style of the source text
DomainHint = "These sentences are from seller-buyer conversations on a B2C ecommerce platform.",
// Terms that should be filtered out before translation
Sensitives = ["基础"],
// Predefined translations for specific terms
Terminologies = [new Image2ImageSynthesisInputExtTerm("一体化", "Unified")],
Config = new Image2ImageSynthesisConfig()
{
// Skip translation for the main subject in the image, like people/product/logo
ImageSegment = false
}
}
}
});
var taskId = response.Output.TaskId;
Console.WriteLine($"Task Created: {taskId}");
var waited = 0;
var timeout = 300;
do
{
var task = await client.GetImage2ImageSynthesisTaskAsync(taskId);
if (task.Output.TaskStatus == DashScopeTaskStatus.Succeeded)
{
Console.WriteLine($"Translated image URL: {task.Output.ImageUrl}");
break;
}
if (task.Output.TaskStatus == DashScopeTaskStatus.Failed)
{
Console.WriteLine($"Task failed: {task.Output.Message}");
break;
}
Console.WriteLine($"Task Status: {task.Output.TaskStatus}");
await Task.Delay(TimeSpan.FromSeconds(10));
waited += 10;
} while (waited < timeout);
Portrait Style Transfer
Use CreateImageGenerationTaskAsync and GetImageGenerationTaskAsync
Background Generation
Use CreateBackgroundGenerationTaskAsync and GetBackgroundGenerationTaskAsync
Portrait (FaceChain)
FaceChain trains a dedicated portrait model from 1~10 face images of a person (model facechain-finetune, billed per training run), then uses the trained model to generate portrait photos in various styles. Validate the images first with DetectFacesAsync (model facechain-facedetect, synchronous, currently free):
var response = await client.DetectFacesAsync(
new ModelRequest<FaceDetectionInput>()
{
Model = "facechain-facedetect",
Input = new FaceDetectionInput() { Images = ["<face-image-1-url>", "<face-image-2-url>"] }
});
foreach (var (isFace, reason) in response.Output.IsFace!.Zip(response.Output.FailedReason!))
{
Console.WriteLine($"{isFace}: {reason}");
}
Create the fine-tune job with the image urls (or file ids from UploadFilesAsync) and poll until it finishes; the trained model name is in FinetunedOutput:
var job = await client.CreateFineTuneJobAsync(
new DashScopeCreateFineTuneJobRequest()
{
Model = "facechain-finetune",
TrainingFileIds = ["<face-image-1-url>", "<face-image-2-url>"]
});
DashScopeFineTuneJob finished;
do
{
await Task.Delay(TimeSpan.FromSeconds(30));
finished = await client.GetFineTuneJobAsync(job.Output.JobId);
} while (finished.Output.Status is DashScopeTaskStatus.Pending or DashScopeTaskStatus.Running);
Console.WriteLine($"Trained model: {finished.Output.FinetunedOutput}");
The Bailian documentation does not cover a portrait generation API for the trained model yet, use FinetunedOutput with the generation API documented for your workspace once available.
Video Generation
Video generation and editing are async tasks: create the task with CreateVideoSynthesisTaskAsync and poll GetVideoSynthesisTaskAsync. The endpoint is shared by the HappyHorse, wan2.7, wan3.0, legacy wan2.1-2.6, wanx2.1-vace, PixVerse, Kling, Vidu and MiniMax models — one input type covers them all, the supported members depend on the model. Text-to-video (HappyHorse / wan2.7 / wan3.0):
var response = await client.CreateVideoSynthesisTaskAsync(
new ModelRequest<VideoSynthesisInput, IVideoSynthesisParameters>()
{
Model = "wan2.7-t2v",
Input = new VideoSynthesisInput() { Prompt = "一只猫在草地上奔跑", NegativePrompt = "低分辨率" },
Parameters = new VideoSynthesisParameters() { Resolution = "720P", Ratio = "16:9", Duration = 5, Seed = 42 }
});
var task = await client.GetVideoSynthesisTaskAsync(response.Output.TaskId);
Console.WriteLine($"Video url: {task.Output.VideoUrl}, billed duration: {task.Usage?.Duration}");
Media-driven generation passes Media items: first frame or first and last frames (image-to-video), reference images and videos (reference-to-video, optionally with a per-item reference_voice audio), a driving audio or a first clip (wan2.7 image-to-video), and a source video plus reference images (video editing). wan3.0 additionally accepts reference audio, files and web links, and can disable the audio track with Audio = false:
var response = await client.CreateVideoSynthesisTaskAsync(
new ModelRequest<VideoSynthesisInput, IVideoSynthesisParameters>()
{
Model = "wan2.7-i2v-2026-04-25",
Input = new VideoSynthesisInput()
{
Prompt = "让画面动起来",
Media =
[
new VideoSynthesisMedia("first_frame", "<first-frame-image-url>"),
new VideoSynthesisMedia("last_frame", "<last-frame-image-url>")
]
},
Parameters = new VideoSynthesisParameters() { Resolution = "720P", Duration = 5 }
});
Legacy wan2.1-2.6 models use the same input type, filling ImgUrl (first-frame image-to-video) or ReferenceUrls (wan2.6 reference-to-video) plus the Size ("1280*720") and ShotType parameters:
var response = await client.CreateVideoSynthesisTaskAsync(
new ModelRequest<VideoSynthesisInput, IVideoSynthesisParameters>()
{
Model = "wan2.6-i2v-flash",
Input = new VideoSynthesisInput() { Prompt = "让画面动起来", ImgUrl = "<first-frame-image-url>" },
Parameters = new VideoSynthesisParameters() { Resolution = "720P", Duration = 5, Audio = false }
});
wanx2.1-vace-plus also uses the same types, with a Function (image reference, video repainting, video editing, video extension and outpainting) selecting its input fields (reference images, video, frames/clips, masks) and parameters (control condition, strength, masks, expand and scale options).
The video-style-transform model (video style transform) fills only VideoUrl, its parameters carry Style (0 Japanese comic to 7 Chinese ink wash), VideoFps (15-25), AnimateEmotion (facial expression optimization), MinLen (720 or 540, affects billing) and UseSR (free super-resolution; with 540 it upscales to 1080P while billing at 540P), and the result video is in Output.OutputVideoUrl with the billed short edge in Usage.SR.
The PixVerse models (Beijing region only, activate the PixVerse service in the Bailian console first) cover text-to-video (pixverse-*-t2v), image-to-video by first frame (pixverse-*-it2v) or keyframes (pixverse-*-kf2v), reference-to-video (pixverse-*-r2v and pixverse-v6-r2v-omni), lipsync (pixverse-lipsync), motion control (pixverse-motioncontrol) and upscaling (pixverse-upscale). The t2v/r2v models (except omni) set Size + Duration, the others set Resolution (+ AspectRatio for omni) instead; Audio generates matching sound effects (billed, defaults to false), ShotType (multi-shot) is supported by the v6 t2v/it2v models, and omni requires Duration = 0 when a reference video is provided (the output follows the longest input video). Reference media are image_url / video_url media items, optionally named with RefName and referenced in the prompt as @ref_name (the server rewrites the references to @1, @2, ... in Output.OrigPrompt). The lipsync model takes a video_url plus either an audio_url media item or TTS via lip_sync_tts_speaker_id (voice Id, auto or a voice id) and lip_sync_tts_content (text Content) media items, without a prompt; motioncontrol takes an image_url character and a video_url motion clip; upscale takes a single video_url and always outputs 4K. PixVerse models report Usage.SR as a string ("720"/"4K", empty when not applicable). Reference-to-video with images, video and @ref_name references:
var response = await client.CreateVideoSynthesisTaskAsync(
new ModelRequest<VideoSynthesisInput, IVideoSynthesisParameters>()
{
Model = "pixverse/pixverse-v6-r2v-omni",
Input = new VideoSynthesisInput()
{
Prompt = "@男人 在@咖啡厅 中弹吉他 参考@参考视频",
Media =
[
new VideoSynthesisMedia("video_url", "https://example.com/motion.mp4", RefName: "参考视频"),
new VideoSynthesisMedia("image_url", "https://example.com/man.jpg", RefName: "男人"),
new VideoSynthesisMedia("image_url", "https://example.com/cafe.png", RefName: "咖啡厅")
]
},
Parameters = new VideoSynthesisParameters() { Resolution = "720P", AspectRatio = "16:9", Duration = 0 }
});
The Kling models (kling/kling-v3-turbo, kling/kling-v3 and kling/kling-v3-omni-video-generation) cover text-to-video, image-to-video (first frame or first+last frames), reference-to-video and video editing (omni only). Kling uses AspectRatio (16:9 / 9:16 / 1:1, required for text-to-video) plus a Mode parameter (std 720P, pro 1080P or 4k) instead of resolution tiers; media items use the types first_frame / last_frame / refer (reference image) / feature (reference video) / base (video to edit, the output keeps its duration) with KeepOriginalSound ("yes"/"no") on video items, and the omni prompt references media items in array order as <<<image_1>>> / <<<video_1>>> / <<<element_1>>> (subjects come from the Kling subject list and are passed via ElementList). Multi-shot is enabled with MultiShot plus an input-level ShotType (intelligence for AI storyboarding, or customize with per-shot MultiPrompt segments); watermark=true additionally returns Output.WatermarkVideoUrl. Reference-to-video with a feature video and a refer image:
var response = await client.CreateVideoSynthesisTaskAsync(
new ModelRequest<VideoSynthesisInput, IVideoSynthesisParameters>()
{
Model = "kling/kling-v3-omni-video-generation",
Input = new VideoSynthesisInput()
{
Prompt = "参考<<<video_1>>>中人物的动作,让<<<image_1>>>中的角色在街头随音乐起舞",
Media =
[
new VideoSynthesisMedia("feature", "https://example.com/motion.mp4", KeepOriginalSound: "no"),
new VideoSynthesisMedia("refer", "https://example.com/man.jpg")
]
},
Parameters = new VideoSynthesisParameters() { Mode = "std", AspectRatio = "16:9", Duration = 5 }
});
The Vidu models (vidu/viduq2* / viduq3* with the _text2video / _img2video / _start-end2video / _reference2video suffix selecting the calling mode) use plain image / video media items (ordered first/last frame for keyframe-to-video) and the existing resolution / duration / audio (q3 models) / watermark / seed parameters; viduq2-pro_reference2video also accepts reference videos and Duration = 0 (auto-planned duration, up to 10 seconds).
The MiniMax model (MiniMax/MiniMax-H3) supports text-to-video, image-to-video (first / last / both frames) and multimodal reference-to-video (image_url / feature video / driving_audio media items, not combinable with frame images). It uses Resolution (768P or 2K), Ratio (adaptive by default, text-to-video requires a concrete ratio) and reports the extra usage fields ImageCount, InputSeconds, OutputSeconds and TotalSeconds.
Wan2.2 keyframe image-to-video (first and last frames) and the animate models (wan2.2-animate-move image-to-motion, wan2.2-animate-mix subject replacement) live on a separate endpoint and share Image2VideoSynthesisInput / IImage2VideoSynthesisParameters, call them with CreateImage2VideoSynthesisTaskAsync:
var response = await client.CreateImage2VideoSynthesisTaskAsync(
new ModelRequest<Image2VideoSynthesisInput, IImage2VideoSynthesisParameters>()
{
Model = "wan2.2-kf2v-flash",
Input = new Image2VideoSynthesisInput()
{
Prompt = "镜头从平视逐渐上升",
FirstFrameUrl = "<first-frame-image-url>",
LastFrameUrl = "<last-frame-image-url>"
},
Parameters = new Image2VideoSynthesisParameters() { Resolution = "480P" }
});
The animate models fill ImageUrl/VideoUrl and a required Mode ("wan-std"/"wan-pro") instead, and take the watermark on the input rather than the parameters. The wan2.2-s2v digital human model fills ImageUrl plus an AudioUrl and generates a talking/performing video. The videoretalk lip sync model fills VideoUrl plus an AudioUrl, optionally RefImageUrl to pick the face when the video contains multiple faces, and takes VideoExtension (whether to extend the video to the audio length with a reverse-forward replay) and QueryFaceThreshold (face matching strictness, 120-200, requires RefImageUrl) on the parameters. Poll the task with GetImage2VideoSynthesisTaskAsync; kf2v and videoretalk tasks expose the video in Output.VideoUrl, animate and s2v tasks in Output.Results.VideoUrl.
Check whether an image is suitable for digital human generation with the synchronous GetFaceDetectAsync (model wan2.2-s2v-detect):
var response = await client.GetFaceDetectAsync(
new ModelRequest<FaceDetectInput>() { Model = "wan2.2-s2v-detect", Input = new FaceDetectInput() { ImageUrl = "<person-image-url>" } });
Console.WriteLine($"Check passed: {response.Output.CheckPass}, humanoid detected: {response.Output.Humanoid}");
3D Generation (Tripo)
The Tripo models are async tasks on the 3d-generation endpoint, create the task with CreateTripo3DTaskAsync and poll GetTripo3DTaskAsync. They are Beijing region only — activate the Tripo service in the Bailian console first. One input type covers the whole family, the supported members depend on the model:
- Generation:
Tripo/Tripo-H3.1(high precision, up to 2M faces) andTripo/Tripo-P1.0(fast, clean topology) support text-to-3d (Prompt), image-to-3d (Image) and multi-image-to-3d (Images, exactly four entries ordered front / left / back / right, an entry with null members marks an empty view). Tripo/Tripo-ImageToSplatgenerates a Gaussian Splat file (.splat) from a single image.- Post-processing:
Tripo/Tripo-Texture(texturing, guided byTexturePrompt),Tripo/Tripo-Segmentation(mesh segmentation),Tripo/Tripo-SmartSegmentation(end-to-end segmentation from an image or model),Tripo/Tripo-MeshCompletion(complete segmented parts),Tripo/Tripo-Retopology(decimation / low-poly retopology) andTripo/Tripo-ConvertFormat(export to GLTF / USDZ / FBX / OBJ / STL / 3MF viaFormat). Post-processing models take the source model viaOriginalModelTaskId(the task id of a preceding Tripo task from the same account) orModelUrl. - Animation:
Tripo/Tripo-RigCheck(free check whether a model is riggable, returns the recommendedRigType),Tripo/Tripo-AutoRig(skeleton binding) andTripo/Tripo-AnimationRetarget(retarget preset animations onto a rigged model, up to 5 per task).
Text-to-3d:
var response = await client.CreateTripo3DTaskAsync(
new ModelRequest<Tripo3DInput, ITripo3DParameters>()
{
Model = "Tripo/Tripo-P1.0",
Input = new Tripo3DInput { Prompt = "一只可爱的猫" },
Parameters = new Tripo3DParameters { TextureQuality = "standard" }
});
var task = await client.GetTripo3DTaskAsync(response.Output.TaskId);
// when task.Output.TaskStatus is Succeeded:
// model url: task.Output.Results[0].ModelUrl (or PbrModelUrl / BaseModelUrl, valid for 2 hours)
// preview: task.Output.Results[0].RenderedImageUrl
// credits used: task.Usage.CreditsConsumed
Multi-image-to-3d (front and back views):
var response = await client.CreateTripo3DTaskAsync(
new ModelRequest<Tripo3DInput, ITripo3DParameters>()
{
Model = "Tripo/Tripo-P1.0",
Input = new Tripo3DInput()
{
Images =
[
new Tripo3DImage("png", "<front-image-url>"),
new Tripo3DImage(), // empty view, serialized as {}
new Tripo3DImage("png", "<back-image-url>"),
new Tripo3DImage()
]
},
Parameters = new Tripo3DParameters { TextureQuality = "standard" }
});
Chain tasks by passing the preceding task id, e.g. texture the generated model (or any public model url):
var response = await client.CreateTripo3DTaskAsync(
new ModelRequest<Tripo3DInput, ITripo3DParameters>()
{
Model = "Tripo/Tripo-Texture",
Input = new Tripo3DInput { OriginalModelTaskId = generationTaskId },
Parameters = new Tripo3DParameters { TextureQuality = "detailed" }
});
A typical animation pipeline: Tripo-RigCheck (free, returns Riggable and the recommended RigType) → Tripo-AutoRig (RigType, non-biped animals need ModelVersion = "v2.5-20260210") → Tripo-AnimationRetarget (Animations, e.g. ["preset:walk"]; non-biped rigs use the preset:<rigType>:<name> form). The result urls are signed temporary links valid for 2 hours. See the Tripo3D group in Cnblogs.DashScope.Sample for a runnable pipeline.
HappyOyster (World Model)
HappyOyster is the interactive world model of Bailian: a prompt and a first frame make a digital world that is experienced as a real-time video stream. It has three experience modes, each one an independent deployment with the same Open API: Adventure (world exploration, driven by direction / view / action commands), Directing (real-time directing, a prompt or a structured script driven by text instructions, with pause / rewind / resume) and Acting (role acting, a portrait first frame driven by text instructions, with pause / resume). See the Bailian documentation.
The Open API is the server half of a split architecture: your backend manages the worlds and hands out the credentials, the real-time experience itself is up to the client SDKs of Alibaba (Android, iOS, Web). The SDK wraps this server half, every HappyOyster* method takes the HappyOysterMode as its first argument:
// the API is only served on the workspace domain, in the region of the API key
var client = new DashScopeClient("your-api-key", workspaceId: "your-workspace-id");
// 1. create a world, it is built in the background
var world = await client.HappyOysterCreateWorldAsync(HappyOysterMode.Adventure, new HappyOysterCreateWorldInput
{
Perspective = "third_person",
Prompt = "A rider on a black snowmobile heading for snowy mountains",
FirstFrameImage = new HappyOysterImage { Url = "https://example.com/first-frame.png" }
});
// 2. poll the build status every 3-5 seconds until the world is ready
var status = world.Data;
while (status.Status == "generating")
{
await Task.Delay(TimeSpan.FromSeconds(3));
status = (await client.HappyOysterGetWorldBuildStatusAsync(HappyOysterMode.Adventure, status.EncryptedWorldId)).Data;
}
// 3. exchange the ready world for a one-time ticket (valid for 30 minutes) and hand it to the
// client together with a temporary API key, the client SDK starts the travel with them
var ticket = (await client.HappyOysterGetTravelCredentialAsync(HappyOysterMode.Adventure, status.EncryptedWorldId)).Data.Ticket;
var temporaryApiKey = (await client.CreateTemporaryApiKeyAsync(1800)).Token;
// 4. follow the travels of the world and fetch the videos once a travel completed
var travels = await client.HappyOysterListTravelsAsync(HappyOysterMode.Adventure, encryptedWorldId: status.EncryptedWorldId);
var travel = await client.HappyOysterGetTravelStatusAsync(HappyOysterMode.Adventure, travels.Data.Items[0].EncryptedTravelId);
var artifacts = await client.HappyOysterGetTravelArtifactsAsync(HappyOysterMode.Adventure, travels.Data.Items[0].EncryptedTravelId);
// poll while artifacts.Data.ComposeStatus is not ready
var deliveryUrl = artifacts.Data.Video.WithInstructionAndWatermark.Url;
// 5. clean up
await client.HappyOysterDeleteWorldAsync(HappyOysterMode.Adventure, status.EncryptedWorldId);
Besides that, worlds can be listed with a build status filter (HappyOysterListWorldsAsync) and read in full (HappyOysterGetWorldDetailAsync), and a travel can be ended from the server (HappyOysterEndTravelAsync). HappyOysterCreateWorldInput carries the parameters of the three modes, which ones are required depends on the mode (see the XML documentation). The calls the client SDKs make with the ticket and the temporary key - entering the travel, sending instructions, pause / resume / rewind, updating the script - are not wrapped.
What the live API answered when tested:
- The API is only served on the workspace domain, create the client with a
WorkspaceId(see Workspace and Region); the shared domain answers400 UnsupportedDomain.Adventureis served in cn-beijing, ap-southeast-1 and us-east-1,DirectingandActingin ap-southeast-1 and us-east-1 only, the gateway of cn-beijing answers403 AccessDeniedfor them. - The response of every call is wrapped in the standard envelope (
request_id+output), the documentation shows the business envelope alone. A business failure comes with status 200: an invalid parameter (400000), an unknown or deleted world (403001), a travel that is not completed (404000) etc. throw aDashScopeException, the business code is inError.Code. - An encrypted id that does not decrypt (malformed or tampered) is rejected with
400000 invalid encryptedWorldId/invalid encryptedTravelId; the detail of a deleted world answered403001. - The documentation allows a temporary API key for the build status and the travel status, but the gateway rejected the temporary keys with
401 InvalidApiTokenwhen tested. Use the main key for theHappyOyster*calls and leave the temporary key to the client SDK. - In the capture, a travel that was entered but never played ended by itself after about 17 seconds (
completed, 13 billed seconds), and ending the ended travel again returned its final state. Some fields of the responses are not documented:billingDurationSecon the travel list items and the videos,resolutionon the build status / the world list items / the travel status / the artifacts,mediaIdon the images.
Speech
Speech Recognition
Real-Time Speech Recognition
Create a real-time speech recognition session using dashScopeClient.CreateSpeechRecognitionSocketSessionAsync().
Audio is sent to the server as binary websocket frames, and recognition results are continuously returned via GetMessagesAsync(). Results with SentenceEnd set to false are intermediate results of the sentence, and the one with true is the final result.
Note: Use the using statement to automatically dispose the session, or manually call Dispose() to release resources. Avoid reusing sessions.
using var asr = await dashScopeClient.CreateSpeechRecognitionSocketSessionAsync("paraformer-realtime-v2");
var taskId = await asr.RunTaskAsync(
new SpeechRecognitionParameters
{
Format = "wav",
SampleRate = 16000,
LanguageHints = ["zh"],
MaxSentenceSilence = 800
});
await using var audio = File.OpenRead("speech.wav");
await asr.SendAudioAsync(audio); // or send chunks yourself via SendAudioAsync(ReadOnlyMemory<byte>)
await asr.FinishTaskAsync(taskId);
var duration = 0;
await foreach (var message in asr.GetMessagesAsync())
{
var sentence = message.Payload.Output?.Sentence;
if (sentence?.SentenceEnd == true)
{
Console.WriteLine($"Recognized: {sentence.Text}");
duration = Math.Max(duration, message.Payload.Usage?.Duration ?? 0);
}
}
Console.WriteLine($"Billed duration: {duration}s");
The session is shared by the Fun-ASR-Realtime and Qwen-Audio ASR models as well, which support the conversation context, instant hot words and more (see SpeechRecognitionParameters for the members each model supports):
fun-asr-realtime: intermediate results are always returned, and the words of the final result carry settled timestamps (Fixed). Supports the conversation context,VocabularyIdandLanguageHints(one value takes effect).qwen-audio-3.1-asr-flash-message: returns the final result of each sentence only, setIntermediateResultEnabledto get intermediate results as well.DisfluencyRemovalEnabledalso removes repetitions and self-corrections from the final text. Finishing the task before any audio was sent fails withNO_VALID_AUDIO_ERROR.qwen-audio-3.1-asr-flash-streaming/qwen-audio-3.0-asr-flash-streaming: intermediate results are always returned.SpecialWordFilterreplaces or removes sensitive words. 3.1 reports token usage, 3.0 reports the audio duration it is billed by.
The conversation context (previous turns of the user's speech and the LLM's replies) improves the recognition of proper nouns: pass it in the input of RunTaskAsync and update it while the task is running with ContinueTaskAsync (message model only):
using var asr = await dashScopeClient.CreateSpeechRecognitionSocketSessionAsync("qwen-audio-3.1-asr-flash-message");
var taskId = await asr.RunTaskAsync(
new SpeechRecognitionParameters
{
Format = "wav",
SampleRate = 16000,
IntermediateResultEnabled = true, // off by default for this model
Vocabulary = new Dictionary<string, int> { ["博客园"] = 5 } // instant hot words, weight 1~5 or 50
},
new SpeechRecognitionInput
{
Context =
[
new SpeechRecognitionContext("user", [new SpeechRecognitionContextContent("input_text", "博客园是什么时候成立的")]),
new SpeechRecognitionContext("assistant", [new SpeechRecognitionContextContent("text", "博客园成立于2004年。")])
]
});
await using var audio = File.OpenRead("speech.wav");
await asr.SendAudioAsync(audio);
// the context can be updated while the task is running
await asr.ContinueTaskAsync(taskId, new SpeechRecognitionInput
{
Context = [new SpeechRecognitionContext("user", [new SpeechRecognitionContextContent("input_text", "代码改变世界")])]
});
await asr.FinishTaskAsync(taskId);
var duration = 0;
await foreach (var message in asr.GetMessagesAsync())
{
var sentence = message.Payload.Output?.Sentence;
if (sentence?.SentenceEnd == true)
{
Console.WriteLine($"Recognized: {sentence.Text}");
duration = Math.Max(duration, message.Payload.Usage?.Duration ?? 0);
}
else if (sentence?.Text?.Length > 0)
{
// intermediate results may be revised, update the text of the sentence identified by SentenceId instead of appending them
Console.WriteLine($"Interim result of sentence {sentence.SentenceId}: {sentence.Text}");
}
}
Console.WriteLine($"Billed duration: {duration}s");
Sensitive word filtering of the streaming models. The server expects the filter JSON-encoded as a string, the SDK takes care of it:
using var asr = await dashScopeClient.CreateSpeechRecognitionSocketSessionAsync("qwen-audio-3.1-asr-flash-streaming");
var taskId = await asr.RunTaskAsync(
new SpeechRecognitionParameters
{
Format = "pcm",
SampleRate = 16000,
SpecialWordFilter = new SpeechRecognitionSpecialWordFilter
{
SystemReservedFilter = true, // filtering is off by default
FilterWithSigned = new SpeechRecognitionSpecialWordList { WordList = ["代码"] }, // replaced with **
FilterWithEmpty = new SpeechRecognitionSpecialWordList { WordList = ["世界"] } // removed
}
});
// send audio and read the results the same way as above
Read the usage from the final result of each sentence, the task-finished event does not always carry it.
With Microsoft.Extensions.AI the same API is available as an ISpeechToTextClient (AsSpeechToTextClient(), see Speech to text client), which runs the session for each call.
Qwen3-ASR-Flash-Realtime
qwen3-asr-flash-realtime models use a separate realtime session (CreateAsrRealtimeSocketSessionAsync), which talks to the /api-ws/v1/realtime endpoint with event-based messages: configure the session (audio format, language, VAD) with UpdateSessionAsync, stream the audio with AppendAudioAsync (base64 encoded inside the messages, no binary frames) and end it with FinishAsync. The server closes the connection after session.finished, so a session cannot be reused.
The session starts in the VAD mode, where the server detects speech boundaries and submits the audio automatically, delivering incremental results in conversation.item.input_audio_transcription.text events (the accumulated text arrives in Stash, Text stays empty) and the final one in ...completed (with the token usage). Leave TurnDetection at its default to keep the server's VAD settings, or set a configuration to tune them. Setting it to null (sent as an explicit turn_detection null) switches to the manual mode, where you call CommitAudioAsync to submit the buffered audio:
using var asr = await dashScopeClient.CreateAsrRealtimeSocketSessionAsync("qwen3-asr-flash-realtime");
await asr.UpdateSessionAsync(
new AsrRealtimeSession
{
InputAudioFormat = "pcm", // or opus
SampleRate = 16000, // or 8000
InputAudioTranscription = new AsrRealtimeTranscription { Language = "zh" }, // unset to auto detect
// the VAD mode with custom settings; leave it unset to keep the server settings,
// null switches to the manual mode (commit below)
TurnDetection = new AsrRealtimeTurnDetection { Threshold = 0.0f, SilenceDurationMs = 400 }
});
await using var audio = File.OpenRead("speech.pcm");
await asr.AppendAudioAsync(audio); // sent as base64 chunks of 3200 bytes
// manual mode only: submit the buffered audio for recognition
// await asr.CommitAudioAsync();
// VAD mode only: give the server a moment after the audio, see below
await Task.Delay(TimeSpan.FromSeconds(1));
await asr.FinishAsync();
await foreach (var e in asr.GetEventsAsync())
{
switch (e.Type)
{
case "conversation.item.input_audio_transcription.text":
Console.WriteLine($"Interim: {e.Stash}");
break;
case "conversation.item.input_audio_transcription.completed":
Console.WriteLine($"Recognized: {e.Transcript} (language: {e.Language}, emotion: {e.Emotion})");
break;
}
}
In the VAD mode, do not call FinishAsync right after the last audio: input_audio_buffer.append has no acknowledgement, and a finish that arrives before the server has consumed the buffered audio ends the session without any transcription. Pushing a 4 second clip in one message lost it every time, in 3200 byte chunks (the Stream overload above) it takes about 300 ms, so wait a second to be safe. A live microphone stream delivers the audio continuously and does not run into this.
Recorded Speech Recognition
qwen3-asr-flash
Recognize an audio file (up to 5 minutes) with GetMultimodalGenerationAsync, passing the audio url (or a base64 data uri) as the audio content and the options in AsrOptions. A system message provides context (background text, entity word lists) that improves the recognition of proper nouns. The recognized text is in the message content, the language and emotion of the audio are in the annotations.
var response = await dashScopeClient.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen3-asr-flash",
Input = new MultimodalInput()
{
Messages =
[
MultimodalMessage.System([MultimodalMessageContent.TextContent("This is a recording of a classical Chinese poem")]),
MultimodalMessage.User([MultimodalMessageContent.AudioContent(audioUrl)])
]
},
Parameters = new MultimodalParameters()
{
AsrOptions = new AsrOptions { Language = "zh", EnableItn = true }
}
});
var choice = response.Output.Choices[0];
Console.WriteLine($"Recognized: {choice.Message.Content[0].Text}");
Console.WriteLine($"Language: {choice.Message.Annotations![0].Language}, emotion: {choice.Message.Annotations[0].Emotion}");
Console.WriteLine($"Audio duration: {response.Usage?.Seconds}s, tokens: {response.Usage?.TotalTokens}");
Fun-ASR-Flash / Qwen-Audio-3.x-ASR-Flash
Fun-ASR-Flash and Qwen-Audio-3.x-ASR-Flash models transcribe recorded audio files with sentence / word level timestamps on the same endpoint, but with typed contents and a sentence based response: call GetMultimodalGenerationAsync (or GetMultimodalGenerationStreamAsync, which returns intermediate results when the audio is at least 1 minute long; words with Fixed set to false may still be revised). The audio goes into an InputAudioContent (a publicly accessible url or a base64 data uri), previous turns of the conversation go into InputTextContent / AssistantTextContent as the context, and the result is in Output.Text / Output.Sentence instead of Output.Choices.
var response = await dashScopeClient.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen-audio-3.1-asr-flash",
Input = new MultimodalInput()
{
Messages =
[
MultimodalMessage.User([MultimodalMessageContent.InputTextContent("Please recite Cong Jun Xing")]),
MultimodalMessage.Assistant([MultimodalMessageContent.AssistantTextContent("Which one would you like to hear?")]),
MultimodalMessage.User([MultimodalMessageContent.InputAudioContent(audioUrl)])
]
},
Parameters = new MultimodalParameters()
{
Format = "mp3",
SampleRate = "16000",
Vocabulary = new Dictionary<string, int> { ["青海"] = 5, ["楼兰"] = 5 }, // instant hot words, weight 1~5 or 50
SpeakerDiarizationEnabled = true // qwen-audio-3.1-asr-flash only, returns Output.Sentences with SpeakerId
}
});
Console.WriteLine($"Recognized: {response.Output.Text}");
foreach (var sentence in response.Output.Sentences ?? [response.Output.Sentence!])
{
Console.WriteLine($"Speaker {sentence.SpeakerId}: {sentence.Text} [{sentence.BeginTime}ms ~ {sentence.EndTime}ms]");
}
Long audio files (file transcription)
Transcribe long audio files asynchronously with the file transcription models (qwen3-asr-flash-filetrans, qwen-audio-3.x-asr-flash-filetrans, fun-asr, paraformer-v2): submit a task with CreateSpeechTranscriptionTaskAsync, poll it with GetSpeechTranscriptionTaskAsync, and download the JSON result file from the TranscriptionUrl (valid for 24 hours) once the task succeeds. Which input members and parameters each model family supports varies, see SpeechTranscriptionParameters for the details — qwen3-asr-flash-filetrans takes a single FileUrl and returns Output.Result, while the other models take urls in FileUrls and return per-file results in Output.Results (Paraformer accepts multiple urls in one task).
var task = await dashScopeClient.CreateSpeechTranscriptionTaskAsync(
new ModelRequest<SpeechTranscriptionInput, SpeechTranscriptionParameters>()
{
Model = "paraformer-v2",
Input = new SpeechTranscriptionInput() { FileUrls = [audioUrl] },
Parameters = new SpeechTranscriptionParameters()
{
DisfluencyRemovalEnabled = true, // remove filler words
DiarizationEnabled = true, // speaker diarization, result carries speaker_id
SpeakerCount = 2 // optional reference count of speakers
}
});
DashScopeTask<SpeechTranscriptionOutput, SpeechTranscriptionUsage>? result;
do
{
await Task.Delay(TimeSpan.FromSeconds(2));
result = await dashScopeClient.GetSpeechTranscriptionTaskAsync(task.Output.TaskId);
}
while (result.Output.TaskStatus is DashScopeTaskStatus.Pending or DashScopeTaskStatus.Running);
// check SubTaskStatus when multiple files were submitted: the task status is SUCCEEDED
// as long as any subtask succeeded
foreach (var file in result.Output.Results!)
{
Console.WriteLine($"{file.FileUrl}: {file.SubTaskStatus} -> {file.TranscriptionUrl}");
}
Custom Hotword Vocabularies
Boost the recognition accuracy of domain terms with custom hotword vocabularies, managed with CustomizeVocabularyAsync (model speech-biasing, served on the workspace domain only — configure WorkspaceId as for the voice cloning API). The action picks the operation: create a vocabulary of hotwords (Action = "create_vocabulary"), then list / query / update / delete vocabularies. The returned id feeds the VocabularyId parameter of recognition requests and the vocabulary must be created with the same TargetModel as the recognition requests use:
var created = await dashScopeClient.CustomizeVocabularyAsync(
new ModelRequest<VocabularyCustomizationInput>
{
Model = "speech-biasing",
Input = new VocabularyCustomizationInput
{
Action = "create_vocabulary",
TargetModel = "fun-asr", // must match the model of the recognition requests
Prefix = "myvocab", // digits and lowercase letters, at most 10 characters
Vocabulary = [new VocabularyWord(Text: "博客园", Weight: 4, Lang: "zh")]
}
});
var vocabularyId = created.Output.VocabularyId; // vocab-{prefix}-{id}
// list (filter by prefix), query / update / delete by vocabulary id
var list = await dashScopeClient.CustomizeVocabularyAsync(
new ModelRequest<VocabularyCustomizationInput>
{
Model = "speech-biasing",
Input = new VocabularyCustomizationInput { Action = "list_vocabulary", Prefix = "myvocab" }
});
Hotwords are (Text, Weight, Lang) triples — weight range [1, 5] (commonly 4), and Lang is optional (detected automatically when unset). update_vocabulary replaces the whole hotword list; update_vocabulary and delete_vocabulary return an empty Output, the vocabulary detail (Status, TargetModel, hotwords) is returned by query_vocabulary.
Text-to-Speech
The non-realtime speech synthesis models - qwen3-tts (e.g. qwen3-tts-flash) and MiniMax speech (e.g. MiniMax/speech-2.8-hd) - use the multimodal generation HTTP API instead of a websocket session. The text and voice settings go into MultimodalInput; qwen3-tts answers with a downloadable wav url (base64 chunks in Audio.Data when streaming), MiniMax speech with hex encoded audio in Output.Data (or a url when OutputFormat is set to url):
// qwen3-tts, non-streaming: the response carries the download url of the complete wav file
var response = await dashScopeClient.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>
{
Model = "qwen3-tts-flash",
Input = new MultimodalInput
{
Text = "你好,我是千问。",
Voice = "Cherry",
LanguageType = "Chinese"
}
});
Console.WriteLine($"Audio url (valid for 24 hours): {response.Output.Audio!.Url}");
// qwen3-tts, streaming: intermediate frames carry base64 wav chunks for immediate playback
await foreach (var frame in dashScopeClient.GetMultimodalGenerationStreamAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>
{
Model = "qwen3-tts-flash",
Input = new MultimodalInput { Text = "你好,我是千问。", Voice = "Cherry" }
}))
{
if (frame.Output.Audio?.Data is { Length: > 0 } data)
{
PlayAudio(Convert.FromBase64String(data)); // e.g. wav, 24 kHz 16 bit mono
}
}
// MiniMax speech, non-streaming: the response carries the hex encoded mp3 audio
var minimaxResponse = await dashScopeClient.GetMultimodalGenerationAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>
{
Model = "MiniMax/speech-2.8-hd",
Input = new MultimodalInput
{
Text = "你好,我是千问。",
VoiceSetting = new MinimaxVoiceSetting { VoiceId = "male-qn-qingse", Emotion = "happy" },
AudioSetting = new MinimaxAudioSetting { Format = "mp3", SampleRate = 32000 }
}
});
File.WriteAllBytes("minimax-tts.mp3", Convert.FromHexString(minimaxResponse.Output.Data!.Audio!));
In MiniMax streaming mode the intermediate frames carry hex chunks in Output.Data (Status 1) and the last frame aggregates the whole synthesis (Status 2); set StreamOptions.ExcludeAggregatedAudio to omit the aggregated audio from the last frame. Mixed voices (TimbreWeights), pronunciation replacement (PronunciationDict), voice effects (VoiceModify) and more voice settings are available on MultimodalInput.
The qwen-audio-tts models (e.g. qwen-audio-3.0-tts-flash) also have an HTTP mode via GetSpeechSynthesisAsync / GetSpeechSynthesisStreamAsync, with all parameters (voice, format, sample rate, speech rate, pitch, seed, LanguageHints, Instruction, AIGC tag, HotFix etc.) on SpeechSynthesisInput. Unlike the APIs above, this one is only served on the workspace domain, so configure WorkspaceId (same region as the API key) on the client:
builder.Services.AddDashScopeClient("your-api-key", workspaceId: "your-workspace-id");
// non-streaming: the response carries the download url of the complete audio file
var response = await dashScopeClient.GetSpeechSynthesisAsync(
new ModelRequest<SpeechSynthesisInput>
{
Model = "qwen-audio-3.0-tts-flash",
Input = new SpeechSynthesisInput
{
Text = "我家的后面有一个很大的花园。",
Voice = "longanhuan_v3.6",
Format = "wav",
SampleRate = 24000
}
});
Console.WriteLine($"Audio url (valid for 24 hours): {response.Output.Audio!.Url}");
// streaming: sentence events with base64 audio chunks, the final frame carries the url
await foreach (var frame in dashScopeClient.GetSpeechSynthesisStreamAsync(
new ModelRequest<SpeechSynthesisInput>
{
Model = "qwen-audio-3.0-tts-flash",
Input = new SpeechSynthesisInput
{
Text = "我家的后面有一个很大的花园。",
Voice = "longanhuan_v3.6",
Format = "wav",
WordTimestampEnabled = true
}
}))
{
if (frame.Output.Audio?.Data is { Length: > 0 } data)
{
PlayAudio(Convert.FromBase64String(data));
}
if (frame.Output.Type == "sentence-end")
{
// word timestamps in frame.Output.Sentence.Words when enabled
}
}
The same endpoint also serves audio generation with the qwen-audio-*-tts-next models (e.g. qwen-audio-3.1-tts-next): describe the audio in TextPrompt (reference audios are referenced in order as @voice1 / @voice2 / @voice3) and optionally pass up to 3 References (a public url or a base64 data uri each, 30 seconds / 10 MB at most; wav, mp3 or ogg opus), generated podcasts run up to 240 seconds and other scenarios up to 120 seconds:
// generate a two-speaker dialogue with two reference audios
var response = await dashScopeClient.GetSpeechSynthesisAsync(
new ModelRequest<SpeechSynthesisInput>
{
Model = "qwen-audio-3.1-tts-next",
Input = new SpeechSynthesisInput
{
TextPrompt = "@voice1 says: \"What a sunny day!\" @voice2 answers: \"Let's go to the park.\"",
References = new List<SpeechSynthesisReference>
{
new() { AudioUrl = "https://your-reference-1.wav" },
new() { AudioUrl = "https://your-reference-2.wav" }
},
Format = "wav",
SampleRate = 48000,
Channels = 2
}
});
Console.WriteLine($"Audio url (24h): {response.Output.Audio!.Url}, duration: {response.Output.Audio.Duration}s");
Create a speech synthesis session using dashScopeClient.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:
using var tts = await dashScopeClient.CreateSpeechSynthesizerSocketSessionAsync("cosyvoice-v2");
var taskId = await tts.RunTaskAsync(new SpeechSynthesizerParameters { Voice = "longxiaochun_v2", Format = "mp3" });
await tts.ContinueTaskAsync(taskId, "Cnblogs");
await tts.ContinueTaskAsync(taskId, "Code changes the world");
await tts.FinishTaskAsync(taskId);
var file = new FileInfo("tts.mp3");
using var stream = file.OpenWrite();
await foreach (var b in tts.GetAudioAsync())
{
stream.WriteByte(b);
}
Console.WriteLine($"Audio saved to {file.FullName}");
GetAudioAsync() yields the audio one byte at a time; GetAudioChunksAsync() yields the same audio in chunks (one per message of the service, at most 4096 bytes), which is the faster way to write it to a stream. The streams of a session end with the error that broke the connection, e.g. a JsonException for an event the SDK can not read, once what was received before was read; a connection closed by the server, or a disposed session, ends them without an error.
The session is shared by the cosyvoice models and the qwen-audio-3.1-tts / qwen-audio-3.0-tts models (e.g. qwen-audio-3.1-tts-flash), which report token based usage (InputTokens / OutputTokens / TotalTokens alongside Characters) in sentence-end and task-finished events, and additionally support the opus output format. With Microsoft.Extensions.AI the same API is available as an ITextToSpeechClient (AsTextToSpeechClient(), see Text to speech client), which runs the session for each call.
The Sambert models (sambert-*-v1, Beijing region only, the voice is part of the model name) use the one-shot calling mode instead: the whole text is passed to SynthesizeAsync in a single run-task (streaming: out) and continue-task / finish-task are not supported. Sambert sentence events carry sentence level BeginTime/EndTime, word timestamps without index fields, and phoneme level timestamps (enable WordTimestampEnabled + PhonemeTimestampEnabled):
using var tts = await dashScopeClient.CreateSpeechSynthesizerSocketSessionAsync("sambert-zhichu-v1");
await tts.SynthesizeAsync(
new SpeechSynthesizerParameters { Format = "wav", WordTimestampEnabled = true, PhonemeTimestampEnabled = true },
"床前明月光,疑是地上霜");
// audio in tts.GetAudioAsync(), sentences with phoneme timestamps in tts.GetMessagesAsync()
The qwen3-tts-*-realtime models (e.g. qwen3-tts-flash-realtime) use a different realtime API (CreateTtsRealtimeSocketSessionAsync): the connection is established and session.created awaited before the session is returned, configure it with UpdateSessionAsync (voice, output format, and the server_commit / commit interaction mode), append text with AppendTextAsync, force the synthesis with CommitTextAsync and end it with FinishAsync. The audio is delivered as base64 chunks inside response.audio.delta events and exposed decoded via GetAudioAsync() or in chunks via GetAudioChunksAsync() (one chunk per event), the raw events (including response.done with the billing usage) via GetEventsAsync(). Unlike the speech synthesizer session, the server closes the connection after session.finished, so a realtime session cannot be reused for a second run:
using var tts = await dashScopeClient.CreateTtsRealtimeSocketSessionAsync("qwen3-tts-flash-realtime");
await tts.UpdateSessionAsync(new TtsRealtimeSession { Voice = "Cherry", ResponseFormat = "mp3", SampleRate = 24000 });
await tts.AppendTextAsync("你好,我是千问。");
await tts.CommitTextAsync();
await tts.FinishAsync();
var file = new FileInfo("tts-realtime.mp3");
using var stream = file.OpenWrite();
await foreach (var b in tts.GetAudioAsync())
{
stream.WriteByte(b);
}
Voice Cloning and Designing
Custom voices are managed with CustomizeVoiceAsync (model voice-enrollment, same workspace domain as the qwen-audio-tts HTTP API): clone a voice from a sample audio or design one from a text description (Action = "create_voice"), then list / query / update / delete voices. Which VoiceCustomizationInput members are required depends on the action; the preview audio of a designed voice comes back as base64 in Output.PreviewAudio:
// clone a voice from a sample audio (public url or base64 data uri)
var clone = await dashScopeClient.CustomizeVoiceAsync(
new ModelRequest<VoiceCustomizationInput, IVoiceCustomizationParameters>
{
Model = "voice-enrollment",
Input = new VoiceCustomizationInput
{
Action = "create_voice",
TargetModel = "qwen-audio-3.0-tts-flash",
Prefix = "myvoice",
Audio = "https://your-audio-url.wav",
LanguageHints = new List<string> { "zh" }
}
});
var clonedVoiceId = clone.Output.VoiceId; // use it as the voice of synthesis requests
// design a voice from a text description, the preview audio comes back as base64 wav
var design = await dashScopeClient.CustomizeVoiceAsync(
new ModelRequest<VoiceCustomizationInput, IVoiceCustomizationParameters>
{
Model = "voice-enrollment",
Input = new VoiceCustomizationInput
{
Action = "create_voice",
TargetModel = "cosyvoice-v3.5-plus",
VoicePrompt = "沉稳的中年男性,音色低沉浑厚",
PreviewText = "各位听众朋友们大家好,欢迎收听本期节目",
Prefix = "announcer",
LanguageHints = new List<string> { "zh" }
},
Parameters = new VoiceCustomizationParameters { SampleRate = 24000, ResponseFormat = "wav" }
});
File.WriteAllBytes(
"preview.wav",
Convert.FromBase64String(design.Output.PreviewAudio!.Data!));
// list voices (filter by prefix), query / update / delete by voice id
var list = await dashScopeClient.CustomizeVoiceAsync(
new ModelRequest<VoiceCustomizationInput, IVoiceCustomizationParameters>
{
Model = "voice-enrollment",
Input = new VoiceCustomizationInput { Action = "list_voice", Prefix = "myvoice" }
});
Created voices go through a review: Status is DEPLOYING while reviewing, OK when usable and UNDEPLOYED when rejected. MiniMax voices are cloned on the shared domain instead: call GetMultimodalGenerationAsync with MultimodalInput.Action = "voice_clone", the sample url (AudioUrl), a globally unique VoiceId, and the Text of the audition audio (billed at the synthesis price); the audition comes back in Output.DemoAudio. MiniMax voices cannot be managed (listed / updated / deleted) via these APIs.
Audio Understanding
Example(use Qwen3-Omni-Captioner)
// upload file
await using var audio = File.OpenRead("noise.wav");
var ossLink = await client.UploadTemporaryFileAsync("qwen3-omni-30b-a3b-captioner", audio, "noise.wav");
Console.WriteLine($"File uploaded: {ossLink}");
var messages = new List<MultimodalMessage>
{
MultimodalMessage.User(
[
// 也可以直接传入公网地址
MultimodalMessageContent.AudioContent(ossLink),
])
};
var completion = client.GetMultimodalGenerationStreamAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>()
{
Model = "qwen3-omni-30b-a3b-captioner",
Input = new MultimodalInput() { Messages = messages },
Parameters = new MultimodalParameters() { IncrementalOutput = true, }
});
var reply = new StringBuilder();
var first = true;
MultimodalTokenUsage? usage = null;
await foreach (var chunk in completion)
{
var choice = chunk.Output.Choices[0];
if (first)
{
first = false;
Console.WriteLine();
Console.Write("Assistant > ");
}
if (choice.Message.Content.Count == 0)
{
continue;
}
Console.Write(choice.Message.Content[0].Text);
reply.Append(choice.Message.Content[0].Text);
usage = chunk.Usage;
}
Console.WriteLine();
messages.Add(MultimodalMessage.Assistant([MultimodalMessageContent.TextContent(reply.ToString())]));
if (usage != null)
{
Console.WriteLine(
$"Usage: in({usage.InputTokens})/out({usage.OutputTokens})/audio({usage.InputTokensDetails?.AudioTokens})/total({usage.TotalTokens})");
}
Sample output
Assistant > The audio clip opens with a rapid, percussive metallic clatter, reminiscent of a typewriter or similar mechanical device, which continues in a steady rhythm throughout the recording. This clatter is slightly left-of-center in the stereo field and is accompanied by a faint, low-frequency hum, likely from a household appliance or HVAC system. The acoustic environment is a small, enclosed room with hard surfaces, indicated by the short, bright reverberation of both the clatter and the speaker’s voice. The audio quality is moderate, with a noticeable electronic hiss and some loss of high-frequency detail, but no digital distortion or clipping.
At the one-second mark, a male voice enters, positioned slightly right-of-center and closer to the microphone. He speaks in standard Mandarin, with a tone of weary exasperation: “哎 呀,这样我还怎么安静工作啊?” (“Aiyā, zěnyàng wǒ hái zěnme ānjìng gōngzuò a?”), which translates to “Oh, how can I possibly work quietly like this?” His speech is clear, with a slightly rising pitch on “安静” (“quietly”) and a falling pitch on “啊” (“a”), conveying a sense of complaint and fatigue. The accent is standard, with no regional inflection, and the voice is that of a young to middle-aged adult male.
Throughout the clip, the mechanical clatter remains constant and prominent, occasionally competing with the voice for clarity. There are no other sounds, such as footsteps, additional voices, or environmental noises, and the background is otherwise quiet. The interplay between the persistent mechanical noise and the speaker’s complaint creates a vivid sense of disruption and frustration, suggesting an environment where work is being impeded by an external, uncontrolled sound source.
Culturally, the use of Mandarin, standard pronunciation, and modern recording quality indicate a contemporary, urban Chinese setting. The language and tone are universally relatable, reflecting a common experience of being disturbed during work. The lack of regional markers or distinctive background noises suggests a generic, possibly domestic or office-like space, but with no clear indicators of a specific location or social context.
In summary, the audio portrays a modern Mandarin-speaking man, exasperated by a constant, distracting mechanical noise (likely a typewriter or similar device), attempting to work in a small, reverberant room. The recording’s technical and acoustic features reinforce the sense of disruption and frustration, while the language and setting suggest a contemporary, urban Chinese context.
Usage: in(160)/out(514)/audio(152)/total(674)
Real-Time Voice Conversation (Qwen-Audio-Realtime)
The qwen-audio-3.x-realtime models (plus / flash) are full-duplex voice assistants: stream the user audio in, the server runs VAD / ASR / LLM / TTS in a pipeline and streams back the response text and audio. Create a session with CreateAudioChatSocketSessionAsync (same /api-ws/v1/realtime endpoint, event-based messages):
using var chat = await dashScopeClient.CreateAudioChatSocketSessionAsync("qwen-audio-3.1-realtime-plus");
await chat.UpdateSessionAsync(
new AudioChatSession
{
Voice = "longanqian", // longanqian_v3.1 on 3.1 plus
Instructions = "You are a helpful assistant.", // system prompt of the session
TurnDetection = new AudioChatTurnDetection
{
Type = "server_vad", // or "smart_turn": meaningless sounds ("um") do not trigger a turn
Threshold = 0.5f,
SilenceDurationMs = 500
}
// set TurnDetection = null instead for the push-to-talk mode: commit the audio with
// CommitAudioAsync() and trigger the inference with CreateResponseAsync()
});
// consume the events while the audio streams in (see below), then send the audio
await using var audio = File.OpenRead("speech.pcm"); // raw pcm, 16kHz 16bit mono
await chat.AppendAudioAsync(audio);
In the server_vad / smart_turn mode the server detects the speech boundaries and triggers the inference automatically; the interim ASR results arrive as conversation.item.input_audio_transcription.delta events (Text is the confirmed part, Stash the tentative remainder), the streamed response text and audio as response.audio_transcript.delta / response.audio.delta (base64 pcm, 24kHz — also available decoded via GetAudioAsync(), or in chunks via GetAudioChunksAsync()), and a turn ends with response.done:
var consuming = Task.Run(async () =>
{
// ReSharper disable once AccessToDisposedClosure
await foreach (var e in chat.GetEventsAsync())
{
switch (e.Type)
{
case "conversation.item.input_audio_transcription.delta":
Console.WriteLine($"Heard: {e.Text}{e.Stash}");
break;
case "response.audio_transcript.delta":
Console.WriteLine($"Said: {e.Delta}");
break;
}
}
});
await using var file = File.Create("response.pcm");
await foreach (var b in chat.GetAudioAsync())
{
file.WriteByte(b);
}
Beyond the audio loop the session also supports text input and history injection (CreateItemAsync with message items), function calling (Tools in the session config, execute the call and write the result back with a function_call_output item, then trigger the next turn with CreateResponseAsync), interrupting the model (CancelResponseAsync), and managing the conversation (RetrieveItemAsync / DeleteItemAsync). The 3.1 plus model additionally takes InputAudioTranscription.Language / OutputAudio.Language (both directions of translation-like control) and MaxHistoryTurns; smart_turn accepts VoiceprintAudioUrls for speaker enhancement. The session ends when it is disposed — there is no session.finish.
Embedding and Rerank
Text Embeddings
Call the text embedding API via GetTextEmbeddingsAsync. Supported models are text-embedding-v1 ~ v4 plus the qwen3.7 series:
qwen3.7-text-embedding: 2560/2048/1536/1024(default)/768/512/256 dimensions, up to 128,000 tokens per text and 20 texts per request.qwen3.7-text-embedding-flash: 1024(default)/768/512/256 dimensions.
The qwen3.7 series also returns an extra prompt_tokens or input_tokens in usage (same value as total_tokens), and flash additionally returns a prompt_tokens_details breakdown.
var text = "Sample text for embedding";
var response = await dashScopeClient.GetTextEmbeddingsAsync(
"text-embedding-v4",
[text],
new TextEmbeddingParameters { Dimension = 512 });
var embedding = response.Output.Embeddings.First().Embedding;
Console.WriteLine($"Embedding vector length: {embedding.Length}");
Multimodal Embedding
Compute the embeddings of texts, images and videos in one vector space via GetMultimodalEmbeddingsAsync, e.g. to search images or videos by a text, or the other way round. Supported models (the Dimension values they accept, the first one is the default):
tongyi-embedding-vision-plus: 1152/1024/512/256/128/64 dimensions, also available as the-2026-03-06snapshot.tongyi-embedding-vision-flash: 768/512/256/128/64 dimensions, also available as the-2026-03-06snapshot.multimodal-embedding-v1: 1024 dimensions only.qwen3-vl-embedding: 2560/2048/1536/1024/768/512/256 dimensions.qwen2.5-vl-embedding: 1024/2048/768/512 dimensions.
Every element of Contents is a MultimodalEmbeddingContent: a Text (a string converts to it implicitly), an Image (a public url or a base64 data uri) or a Video (a public url). One embedding comes out of each, at its Index and with the Type of its modality:
List<MultimodalEmbeddingContent> candidates =
[
new(Image: imageUrl1),
new(Image: imageUrl2),
new(Video: videoUrl)
];
var response = await dashScopeClient.GetMultimodalEmbeddingsAsync(
new ModelRequest<MultimodalEmbeddingInput, MultimodalEmbeddingParameters>
{
Model = "tongyi-embedding-vision-plus",
// index the candidates once, then match the queries against them by the cosine similarity
Input = new MultimodalEmbeddingInput { Contents = candidates }
});
foreach (var embedding in response.Output.Embeddings)
{
Console.WriteLine($"{embedding.Index}: {embedding.Type}, {embedding.Embedding.Length} dimensions");
}
The models differ in how they fuse several contents into one embedding:
tongyi-embedding-vision-*-2026-03-06fuse the members of one content into one embedding of the typefused, e.g.new MultimodalEmbeddingContent(Text: "...", Image: imageUrl).qwen3-vl-embeddingfuses all the contents into one embedding of the typefusionwithEnableFusion = true.qwen2.5-vl-embeddingalways fuses all the contents into one embedding.- The other models expect one member per content.
var response = await dashScopeClient.GetMultimodalEmbeddingsAsync(
new ModelRequest<MultimodalEmbeddingInput, MultimodalEmbeddingParameters>
{
Model = "qwen3-vl-embedding",
Input = new MultimodalEmbeddingInput
{
Contents = ["白色运动鞋,轻量透气,适合跑步和日常穿着", new MultimodalEmbeddingContent(Image: imageUrl)]
},
Parameters = new MultimodalEmbeddingParameters { EnableFusion = true } // one fused embedding out of all the contents
});
Console.WriteLine(response.Output.Embeddings.Single().Type); // fusion
MultiImages (the images of a sequence, taken as one content) is accepted by the tongyi-embedding-vision models only. Instruct takes effect on qwen3-vl-embedding and qwen2.5-vl-embedding only, ResLevel and MaxVideoFrames on the 2026-03-06 snapshots only. Fps is documented, but it changed neither the vectors nor the usage of any model when tested. The Usage differs by model too. The tongyi-embedding-vision models count everything in InputTokens (with an InputTokensDetails breakdown) and return OutputTokens; the other models count the texts only in InputTokens and the images and videos in ImageTokens, multimodal-embedding-v1 also returns ImageCount and Duration, and neither it nor qwen2.5-vl-embedding returns TotalTokens. The API is served on the shared domain too, no WorkspaceId is needed although the official docs show the workspace domain url.
Text Rerank
Rank the documents recalled by a vector search (or any other candidates) by their relevance to the query via RerankDocumentsAsync, e.g. to pick the passages worth passing to the model. Supported models: qwen3.7-text-rerank, qwen3-rerank and gte-rerank-v2 for texts, and qwen3-vl-rerank which also ranks images and videos. The results are sorted by the score descending, each one carries the Index of its document in the input list and a RelevanceScore in [0, 1] (relative to the documents of the same request, do not compare it across requests):
var response = await dashScopeClient.RerankDocumentsAsync(
new ModelRequest<TextRerankInput, TextRerankParameters>
{
Model = "qwen3-rerank",
Input = new TextRerankInput
{
Query = "What is a text rerank model?",
Documents = ["passage a", "passage b", "passage c"]
},
Parameters = new TextRerankParameters
{
TopN = 2, // the top ranked documents to return, all when unset
ReturnDocuments = true, // echo each document in its result, false by default
Instruct = "Given a web search query, retrieve relevant passages that answer the query."
}
});
foreach (var result in response.Output.Results)
{
Console.WriteLine($"{result.Index}: {result.RelevanceScore} {result.Document?.Text}");
}
Query and every element of Documents are a TextRerankContent, a string converts to it implicitly (convert an existing chunk list element by element, e.g. chunks.Select(c => (TextRerankContent)c)). qwen3-vl-rerank also accepts images (a public url or a base64 data uri) and videos (a public url), as the query or as documents; the text documents are then sent as {"text": ...} objects along with them:
var response = await dashScopeClient.RerankDocumentsAsync(
new ModelRequest<TextRerankInput, TextRerankParameters>
{
Model = "qwen3-vl-rerank",
Input = new TextRerankInput
{
Query = new TextRerankContent(Image: imageUrl), // or a text query
Documents =
[
"passage",
new TextRerankContent(Image: imageUrl),
new TextRerankContent(Video: videoUrl)
]
},
Parameters = new TextRerankParameters { ReturnDocuments = true, Fps = 0.5f } // Fps: the ratio of the video frames to read
});
foreach (var result in response.Output.Results)
{
Console.WriteLine($"{result.RelevanceScore}: {result.Document?.Text ?? result.Document?.Image ?? result.Document?.Video}");
}
gte-rerank-v2 accepts texts only and ignores Instruct. qwen3.7-text-rerank also returns PromptTokens in Usage and qwen3-vl-rerank returns ImageTokens and InputTokens. The API is served on the shared domain too, no WorkspaceId is needed although the official docs show the workspace domain url.
Omni-Modal
Real-Time Multimodal Conversation (Qwen-Omni-Realtime)
The qwen3.8-omni-flash-realtime, qwen3.5-omni-plus-realtime and qwen3.5-omni-flash-realtime models understand speech, images (video frames) and text, and answer in speech and text - with function calling, remote MCP tools and web search on top. Create a session with CreateOmniRealtimeSocketSessionAsync (same /api-ws/v1/realtime endpoint, event-based messages). The Bailian documentation serves qwen3.8-omni-flash-realtime on the workspace domain only, configure WorkspaceId on the client for it:
using var chat = await dashScopeClient.CreateOmniRealtimeSocketSessionAsync("qwen3.8-omni-flash-realtime");
await chat.UpdateSessionAsync(
new OmniRealtimeSession
{
Voice = "Tina", // the default; the voices a model takes are listed in the Bailian documentation, an unsupported one fails the response
Instructions = "你是个人助理小云,请你准确且友好地解答用户的问题,始终以乐于助人的态度回应。", // system prompt of the session
TurnDetection = new OmniRealtimeTurnDetection
{
Type = "server_vad", // or "semantic_vad": backchannel responses and background noise do not end a turn
Threshold = 0.5f,
SilenceDurationMs = 800
}
// set TurnDetection = null instead for the manual mode (push-to-talk, see below)
});
// consume the events while the audio streams in (see below), then send the audio
await using var audio = File.OpenRead("speech.pcm"); // raw pcm, 16kHz 16bit mono
await chat.AppendAudioAsync(audio);
// the server only detects the end of the speech after some silence, which a live microphone keeps
// delivering: with a recorded clip keep appending silence until the response is done
// AppendImageAsync(frame) sends video frames as base64 jpg, about one per second
In the VAD mode the server detects the speech boundaries, commits the audio and triggers the response by itself: the recognized speech arrives as conversation.item.input_audio_transcription.delta events (Text is the confirmed part, Stash the tentative remainder), the response text as response.audio_transcript.delta events, the audio as response.audio.delta (base64 pcm, 24kHz — also available decoded via GetAudioAsync(), or in chunks via GetAudioChunksAsync()), and a turn ends with response.done carrying the usage:
var consuming = Task.Run(async () =>
{
// ReSharper disable once AccessToDisposedClosure
await foreach (var e in chat.GetEventsAsync())
{
switch (e.Type)
{
case "conversation.item.input_audio_transcription.delta":
Console.WriteLine($"Heard: {e.Text}{e.Stash}");
break;
case "response.audio_transcript.delta":
case "response.text.delta": // text only responses, see the modalities below
Console.WriteLine($"Said: {e.Delta}");
break;
case "conversation.item.created" when e.Item?.Type == "mcp_approval_request":
await chat.RespondToMcpApprovalAsync(e.Item.Id); // approve the MCP tool call the server waits for
break;
}
}
});
await using var file = File.Create("response.pcm");
await foreach (var b in chat.GetAudioAsync())
{
file.WriteByte(b);
}
In the manual mode (TurnDetection = null, sent as an explicit turn_detection null) nothing happens until the audio is committed and the response is requested, e.g. for a push-to-talk button. Text goes in the same way, as a user message item: CreateItemAsync with Type: "message", Role: "user" and an input_text content, followed by CreateResponseAsync():
await chat.UpdateSessionAsync(new OmniRealtimeSession { TurnDetection = null });
await using var audio = File.OpenRead("speech.pcm");
await chat.AppendAudioAsync(audio);
await chat.AppendImageAsync(await File.ReadAllBytesAsync("frame.jpg")); // optional: the frames of the turn, after its audio started
var itemId = await chat.CommitAudioAsync(); // turns the audio (and the images) into a user message item
var response = await chat.CreateResponseAsync(); // completes at response.done, after the streamed deltas
Console.WriteLine(response.Output![0].Content![0].Transcript);
Function calling and MCP tools
Configure Tools in the session: a function tool is executed by the client, a mcp tool is a remote MCP server (public https, streamable HTTP) whose tools the server discovers and executes. The two can be combined, neither with the web search (EnableSearch). A response that needs a function ends with function_call items in its output: execute them, write the results back and trigger the next response:
await chat.UpdateSessionAsync(
new OmniRealtimeSession
{
TurnDetection = null,
Tools = new List<OmniRealtimeTool>
{
new(
Type: "function",
Function: new OmniRealtimeFunction(
"get_current_weather",
"当你想查询指定城市的天气时非常有用。",
new { type = "object", properties = new { location = new { type = "string" } }, required = new[] { "location" } }))
}
});
// ... append and commit the audio asking for the weather, then:
var response = await chat.CreateResponseAsync();
var call = response.Output!.First(o => o.Type == "function_call");
// execute the function, then:
await chat.CreateItemAsync(
new OmniRealtimeItem { Type = "function_call_output", CallId = call.CallId, Output = "北京今天天气为霾转晴,气温4/-4℃,微风" });
var answer = await chat.CreateResponseAsync();
For an MCP tool use new OmniRealtimeTool(Type: "mcp", ServerLabel: "deepwiki", ServerUrl: "https://mcp.deepwiki.com/mcp", RequireApproval: "always") instead. The tools are discovered right after the session was updated (mcp_list_tools.* events; only responses created after mcp_list_tools.completed can use them). With RequireApproval set to always (the default) the server asks before each call with a conversation.item.created event carrying an mcp_approval_request item - answer it with RespondToMcpApprovalAsync(itemId, approve: true) while consuming the events, as in the loop above (never executes without asking). The CreateResponseAsync in flight then completes with a response whose output holds the mcp_call items (Output, or Error when the call failed); call CreateResponseAsync once more for the model to answer based on the tool results. qwen3.8-omni-flash-realtime only.
Beyond that the session takes the output modalities (Modalities = ["text"] answers in text only, delivered as response.text.delta events; the default ["text", "audio"] answers in both), the audio formats with their sample rates (Audio.Input.Format / Audio.Output.Format: pcm or wav, 8000 to 48000 Hz; qwen3.8-omni-flash-realtime also takes multichannel input via Channels and ChannelLayout), the voice of the audio configuration (Audio.Output.Voice, preferred over Voice by qwen3.8-omni-flash-realtime), the input transcription (InputAudioTranscription = null turns the conversation.item.input_audio_transcription.* events off), the web search (EnableSearch with SearchOptions.EnableSource, billed as Usage.Plugins.Search), the video frame aggregation (Video.Input.RepresentationCompact = "normal", a quarter of the image tokens) and the sampling parameters (Temperature, TopP, TopK, MaxTokens, RepetitionPenalty, PresencePenalty, Seed). Images are billed as Usage.InputTokensDetails.VideoTokens.
CancelResponseAsync interrupts the response in progress and returns the cancelled response; when no response is in progress the server answers nothing at all, so pass a cancellation token if that can happen. An error event makes the waiting method throw a DashScopeException: a rejected session.update (e.g. an unsupported combination of modalities) ends the session - the server closes the connection right after it - while the other errors (e.g. committing an empty buffer) leave it usable. The session ends when it is disposed, there is no session.finish. A connection that ends before the event a method waits for has arrived - the server closes it, or the network drops it - makes the method throw a DashScopeException instead of waiting forever; the same holds for the TTS realtime, audio chat and live translate sessions. A client event may go out without waiting for the answer of the server with SendEventAsync - the JSON of the event, or an object with the member names of the API - the answer arrives on GetEventsAsync like every event.
With Microsoft.Extensions.AI the same API is available as an IRealtimeClient (AsRealtimeClient(), see Realtime client), which maps the messages of the abstraction onto the events of the session.
Qwen-Omni (understanding and speech output)
The Qwen-Omni models understand text, images, audio and video within one request. Which endpoint to call depends on the output you need:
| Model | Input | Output |
|---|---|---|
qwen3.8-omni-flash |
text, image, audio, video | text, with thinking (on by default), function calling and web search |
qwen3.5-omni-flash, qwen3.5-omni-plus |
text, image, audio, video | text + audio |
qwen3-omni-flash |
text + one other modality | text + audio, either thinking (EnableThinking) or speech |
Understanding with a text answer works through the DashScope API, so GetMultimodalGenerationAsync (streaming or not) and the Microsoft.Extensions.AI integration apply as for every multimodal model. An audio goes in an AudioContent, a url or the bytes of a local file, and qwen3.8-omni-flash returns its thinking in ReasoningContent:
var response = await client.GetMultimodalGenerationAsync(new ModelRequest<MultimodalInput, IMultimodalParameters>
{
Model = "qwen3.8-omni-flash",
Input = new MultimodalInput
{
Messages =
[
MultimodalMessage.User(
[
MultimodalMessageContent.ImageContent(imageUrl),
// a local file: MultimodalMessageContent.AudioContent(File.ReadAllBytes("meeting.wav"), "audio/wav")
MultimodalMessageContent.AudioContent(audioUrl),
MultimodalMessageContent.TextContent("请描述图片内容,并告诉我音频在说什么。")
])
]
},
Parameters = new MultimodalParameters()
});
Console.WriteLine(response.Output.Choices[0].Message.ReasoningContent); // the thinking
Console.WriteLine(response.Output.Choices[0].Message.Content[0].Text);
With Microsoft.Extensions.AI the audio is a UriContent (the media type follows the extension of the url) or a DataContent with an audio/* media type:
var response = await chatClient.GetResponseAsync(new ChatMessage(ChatRole.User,
[
new UriContent(new Uri(audioUrl)), new TextContent("这段音频在说什么")
]));
Speech output is delivered by the OpenAI compatible endpoint (/compatible-mode/v1/chat/completions) only, and in the streaming mode only: a non-streaming request (OpenAiCompatibleGetChatCompletionAsync) answers with the text, the audio is dropped although its tokens are still billed. The model streams the answer part by part, the audio speaking a part right after its text. The payload of the audio deltas is raw PCM (24 kHz, signed 16 bit, mono):
var chunks = dashScopeClient.OpenAiCompatibleGetChatCompletionStreamAsync(
new OpenAiCompatibleChatRequest
{
Model = "qwen3.5-omni-flash",
Messages =
[
new OpenAiCompatibleChatMessage
{
Role = "user", Content = [new OpenAiCompatibleChatContentPart(Type: "text", Text: "用一句话介绍博客园。")]
}
],
Modalities = ["text", "audio"],
// the voices differ by model (Tina for Qwen3.5-Omni, Cherry for Qwen3-Omni),
// see the voice list of the Bailian docs
Audio = new OpenAiCompatibleChatAudioOptions(Voice: "Tina", Format: "wav"),
StreamOptions = new OpenAiCompatibleChatStreamOptions(IncludeUsage: true)
});
var text = new StringBuilder();
var audio = new MemoryStream();
await foreach (var chunk in chunks)
{
foreach (var choice in chunk.Choices)
{
text.Append(choice.Delta?.Content);
if (choice.Delta?.Audio?.Data is { } data)
{
audio.Write(Convert.FromBase64String(data));
}
}
var usage = chunk.Usage; // present in the last chunk
}
// a wav file is a 44 byte header in front of the pcm
using (var wav = new BinaryWriter(File.Create("answer.wav")))
{
var pcm = audio.ToArray();
wav.Write("RIFF"u8);
wav.Write(36 + pcm.Length);
wav.Write("WAVEfmt "u8);
wav.Write(16);
wav.Write((short)1); // pcm
wav.Write((short)1); // mono
wav.Write(24000);
wav.Write(48000); // bytes per second
wav.Write((short)2); // bytes per sample
wav.Write((short)16); // bits per sample
wav.Write("data"u8);
wav.Write(pcm.Length);
wav.Write(pcm);
}
The same request carries the other omni features of the OpenAI compatible endpoint: ReasoningEffort (none turns the thinking of qwen3.8-omni-flash off, low / medium / xhigh / max limit it) or ThinkingBudget, a video part (the frames of a video) and the Fps of a video, UseMultichannel for a spatial audio, ResponseFormat, and function calling with Tools / ToolChoice. The model asks for a tool in ToolCalls, answer it with a tool message and send the conversation again:
var messages = new List<OpenAiCompatibleChatMessage>
{
new() { Role = "user", Content = [new OpenAiCompatibleChatContentPart(Type: "text", Text: "北京今天天气怎么样?")] }
};
var request = new OpenAiCompatibleChatRequest
{
Model = "qwen3.8-omni-flash",
Messages = messages,
Tools =
[
new ToolDefinition("function", new FunctionDefinition("get_weather", "查询指定城市的实时天气",
new { type = "object", properties = new { city = new { type = "string" } }, required = new[] { "city" } }))
],
ToolChoice = ToolChoice.FunctionChoice("get_weather"), // force the call, AutoChoice lets the model decide
ReasoningEffort = "none"
};
var completion = await client.OpenAiCompatibleGetChatCompletionAsync(request);
var call = completion.Choices[0].Message.ToolCalls![0]; // finish reason "tool_calls", Arguments is a json string
messages.Add(new OpenAiCompatibleChatMessage { Role = "assistant", Content = [], ToolCalls = [call] });
messages.Add(new OpenAiCompatibleChatMessage
{
Role = "tool", ToolCallId = call.Id,
Content = [new OpenAiCompatibleChatContentPart(Type: "text", Text: "{\"weather\": \"晴\", \"temperature\": \"12℃\"}")]
});
request.ToolChoice = null; // let the model answer with the result of the tool
Console.WriteLine((await client.OpenAiCompatibleGetChatCompletionAsync(request)).Choices[0].Message.Content);
Function calling and web search also answered on the Qwen3.5-Omni models when tested, although the Bailian docs only describe them for Qwen3.8-Omni-Flash. The web search of qwen3.8-omni-flash (EnableSearch with the agent strategy, the only one it accepts) works in the streaming mode only and is served on the workspace domain only, so create the client with a WorkspaceId for it (see Workspace and Region). Its stream opens with a chunk whose choice carries no delta:
var workspaceClient = new DashScopeClient("your-api-key", workspaceId: "your-workspace-id");
var chunks = workspaceClient.OpenAiCompatibleGetChatCompletionStreamAsync(new OpenAiCompatibleChatRequest
{
Model = "qwen3.8-omni-flash",
Messages =
[
new OpenAiCompatibleChatMessage
{
Role = "user", Content = [new OpenAiCompatibleChatContentPart(Type: "text", Text: "请查询今天的日期和星期。")]
}
],
ReasoningEffort = "none",
EnableSearch = true,
SearchOptions = new SearchOptions { SearchStrategy = "agent" },
StreamOptions = new OpenAiCompatibleChatStreamOptions(IncludeUsage: true)
});
await foreach (var chunk in chunks)
{
Console.Write(chunk.Choices.FirstOrDefault()?.Delta?.Content);
}
Through the DashScope API the web search takes the EnableSearch / SearchOptions of the multimodal parameters, streaming only as well:
await foreach (var frame in workspaceClient.GetMultimodalGenerationStreamAsync(
new ModelRequest<MultimodalInput, IMultimodalParameters>
{
Model = "qwen3.8-omni-flash",
Input = new MultimodalInput
{
Messages = [MultimodalMessage.User([MultimodalMessageContent.TextContent("请查询今天的日期和星期。")])]
},
Parameters = new MultimodalParameters
{
IncrementalOutput = true,
EnableSearch = true,
SearchOptions = new SearchOptions { SearchStrategy = "agent" }
}
}))
{
Console.Write(frame.Output.Choices[0].Message.Content.FirstOrDefault()?.Text);
}
The gateway opens that stream with a default frame that only announces the assistant. The SDK reads it as any other frame, there is nothing to skip.
Real-Time Live Translation (Qwen-Livetranslate-Realtime)
The qwen3.5 / qwen3.8-livetranslate-flash-realtime models translate live speech (and video frames) into a target language. Create a session with CreateLiveTranslateSocketSessionAsync, configure the translation and stream the source audio:
using var translator = await dashScopeClient.CreateLiveTranslateSocketSessionAsync("qwen3.5-livetranslate-flash-realtime");
await translator.UpdateSessionAsync(
new LiveTranslateSession
{
InputAudioFormat = "pcm", // or opus
SampleRate = 16000,
InputAudioTranscription = new LiveTranslateTranscription(
Model: "qwen3-asr-flash-realtime", Language: "zh"), // Model = null disables the source echo
TurnDetection = new LiveTranslateTurnDetection { Threshold = 0.2f, SilenceDurationMs = 1000 },
Translation = new LiveTranslateTranslation
{
Language = "en", // target language, defaults to en
Corpus = new LiveTranslateCorpus
{
// hotwords: the source phrase always translates to the given target phrase
Phrases = new Dictionary<string, string> { ["博客园"] = "Cnblogs" }
}
}
});
// consume the events while the audio streams in (see below), then send the audio and finish
await using var audio = File.OpenRead("speech.pcm");
await translator.AppendAudioAsync(audio);
// AppendImageAsync(frame) sends video frames as base64 jpg (at most 2 per second, qwen3.8 only)
await translator.FinishAsync(); // the server finishes the remaining translation, then ends the session
The source text arrives as conversation.item.input_audio_transcription.* events and the translated text as response.audio_transcript.text / .delta events (Text + Stash accumulate the interim translation, the final one arrives in response.audio_transcript.done and response.done); the synthesized translation audio is available via GetAudioAsync(), or in chunks via GetAudioChunksAsync():
await foreach (var e in translator.GetEventsAsync())
{
switch (e.Type)
{
case "conversation.item.input_audio_transcription.completed":
Console.WriteLine($"Source: {e.Transcript} ({e.Language}, {e.Emotion})");
break;
case "response.audio_transcript.done":
Console.WriteLine($"Translated: {e.Transcript}");
break;
}
}
The qwen3.8 model takes a different shape: OutputModalities plus Audio.Input.TurnDetection (speaker_detection separates speakers, the source and the translation items are correlated via PreviousItemId), and voice cloning (EnableVoiceClone + VoiceCloneOptions.Frequency never / once / always, with Voice set to "default" or a pre-cloned voice id) works on both models. In the manual mode (TurnDetection = null) the buffered audio is submitted with CommitAudioAsync(), which triggers the translation automatically.
Non-realtime translation (qwen3-livetranslate-flash)
The qwen3-livetranslate-flash models translate an audio / video file in one shot. They cannot be called via the DashScope API - they are only served on the OpenAI compatible endpoint (/compatible-mode/v1/chat/completions), which the SDK exposes as the generic OpenAiCompatibleGetChatCompletionAsync / OpenAiCompatibleGetChatCompletionStreamAsync methods (the livetranslate models only support the streaming mode). Prefer the DashScope methods (or the Microsoft.Extensions.AI integration) whenever the model supports both styles; use the OpenAI compatible family only when it does not:
var chunks = dashScopeClient.OpenAiCompatibleGetChatCompletionStreamAsync(
new OpenAiCompatibleChatRequest
{
Model = "qwen3-livetranslate-flash",
Messages =
[
new OpenAiCompatibleChatMessage
{
Role = "user",
Content =
[
// an audio file; a video goes in a video_url part (Url)
new OpenAiCompatibleChatContentPart(
Type: "input_audio",
InputAudio: new OpenAiCompatibleChatInputAudio(Data: audioUrl, Format: "wav"))
]
}
],
Modalities = ["text", "audio"], // audio output is optional, ["text"] also works
Audio = new OpenAiCompatibleChatAudioOptions(Voice: "Cherry", Format: "wav"),
StreamOptions = new OpenAiCompatibleChatStreamOptions(IncludeUsage: true), // usage in the last chunk
TranslationOptions = new OpenAiCompatibleTranslationOptions(SourceLang: "zh", TargetLang: "en")
});
var text = new StringBuilder();
await foreach (var chunk in chunks)
{
text.Append(chunk.Choices[0].Delta?.Content); // the translated text, delta by delta
var audio = chunk.Choices[0].Delta?.Audio?.Data; // the base64 wav deltas, when audio output is on
var usage = chunk.Usage; // present in the last chunk with IncludeUsage
}
Decision Model (System One)
Get a structured decision from the decision model (decision-model, the preview decision-model-preview is accepted too) via OpenAiCompatibleGetSystemOneDecisionAsync: a single forward pass answers every question of the request with a choice, a yes / no probability or a score, together with the probability distribution and, for a choice / score answer, the confidence. No text is generated, so the latency and the cost do not depend on the output length. It fits the high frequency decisions like ticket triage, content moderation, agent routing or result verification.
The API is only served on the workspace domain, the client has to be created with a WorkspaceId (see Workspace and Region), otherwise the server answers 404.
// the decision model is only served on the workspace domain
var workspaceClient = new DashScopeClient("your-api-key", workspaceId: "your-workspace-id");
var decision = await workspaceClient.OpenAiCompatibleGetSystemOneDecisionAsync(
new SystemOneDecisionInput
{
Model = "decision-model",
State = new { ticket_id = "T-1001", content = "订单支付后超过 24 小时仍未到账,用户无法继续使用核心服务,要求立即处理。" }, // a text, a conversation (an array) or a structured object
Questions = new Dictionary<string, SystemOneQuestion>
{
// pick one of the options
["department"] = SystemOneQuestion.Choice(
"应该由哪个团队处理?",
new Dictionary<string, string>
{
["billing"] = "支付、退款和账单问题",
["technical"] = "产品故障和集成问题"
}),
// yes / no, the answer is the probability of yes
["escalate"] = SystemOneQuestion.Noul("是否需要立即通知值班人员?"),
// an ordered scale, from low to high
["severity"] = SystemOneQuestion.Score(
"这个问题有多严重?",
["轻微问题,不影响功能", "部分功能受影响,但存在替代方案", "核心功能不可用,没有替代方案", "造成严重业务或安全影响"])
}
});
var answers = decision.Answers; // keyed by the question id of the request
var department = answers["department"];
Console.WriteLine($"{department.Choice} {department.Confidence:F2}"); // e.g. billing 0.9956
Console.WriteLine(department.Probabilities!["technical"]); // e.g. 0.0022
Console.WriteLine(answers["escalate"].Noul); // P(yes), e.g. 0.9971
Console.WriteLine($"{answers["severity"].Score:F2}"); // the probability weighted level index, e.g. 2.02
The fields of an answer depend on the type of the question: a choice answer carries Choice, Confidence and Probabilities, a noul answer carries Noul only, a score answer carries Score, Confidence, Legend (the level index to level description map) and Probabilities. A request takes at most 16 questions, a choice question at most 255 options and a score question 2-255 levels. Although the endpoint lives under /compatible-mode, a failed request throws a DashScopeException with the usual DashScope error detail.
Omni-Modal Translation (Qwen-MT-Uni)
Translate texts, documents (pdf, docx, pptx, xlsx, txt, html, md), images (png, jpg) or audio (mp3, wav) with the omni-modal translation model qwen-mt-uni via GetUniTranslationAsync, the call blocks until the result is ready. Pass the texts in SourceTexts or a publicly accessible file url in FileUrl, exactly one of them. A texts input comes back in TranslatedTexts, in the order of the source texts:
var response = await dashScopeClient.GetUniTranslationAsync(
new ModelRequest<UniTranslationInput>
{
Model = "qwen-mt-uni",
Input = new UniTranslationInput
{
SourceTexts = ["机器学习正在改变世界。", "全场9折", "这款商品支持七天无理由退换。"],
SourceLang = "zh", // unset to detect the source language
TargetLang = "en",
Ext = new UniTranslationInputExt
{
// Hint for the scene and translation style
DomainHint = "These sentences are from seller-buyer conversations on a B2C ecommerce platform.",
// A source text equal to one of them is kept as it is
Sensitives = ["全场9折"],
// Terms the model is guided to translate as given
Glossary = [new UniTranslationGlossaryTerm("机器学习", "ML")]
}
}
});
foreach (var text in response.Output.Data.TranslatedTexts)
{
Console.WriteLine(text);
}
A file input comes back as a translated file of the same format (images as jpg, audio as mp3) in TranslatedFileUrl, a signed url valid for 24 hours:
var response = await dashScopeClient.GetUniTranslationAsync(
new ModelRequest<UniTranslationInput>
{
Model = "qwen-mt-uni",
Input = new UniTranslationInput
{
FileUrl = "https://example.com/image-with-text.jpg",
TargetLang = "zh",
Ext = new UniTranslationInputExt
{
// The format when the url has no recognizable extension: image, pdf, docx, audio, ...
FormatHint = "image",
Config = new UniTranslationConfig
{
// Skip translation for the main subject in the image, like people/product/logo
ImageSegment = true
}
}
}
});
Console.WriteLine(response.Output.Data.FileType); // strings, document, image or audio
Console.WriteLine($"Translated file url: {response.Output.Data.TranslatedFileUrl}");
Large documents and long audio take minutes, longer than the default HttpClient timeout: submit them as an asynchronous task with CreateUniTranslationTaskAsync (the same request) and poll GetUniTranslationTaskAsync:
var task = await dashScopeClient.CreateUniTranslationTaskAsync(
new ModelRequest<UniTranslationInput>
{
Model = "qwen-mt-uni",
Input = new UniTranslationInput
{
FileUrl = "https://example.com/document.pdf",
TargetLang = "en"
}
});
DashScopeTask<UniTranslationOutput, UniTranslationUsage>? result;
do
{
await Task.Delay(TimeSpan.FromSeconds(10));
result = await dashScopeClient.GetUniTranslationTaskAsync(task.Output.TaskId!);
}
while (result.Output.TaskStatus is DashScopeTaskStatus.Pending or DashScopeTaskStatus.Running);
// a translation that fails (e.g. the file cannot be downloaded) still ends with the status Succeeded
if (result.Output.Success == false)
{
Console.WriteLine($"Translation failed: {result.Output.Message}");
}
else
{
Console.WriteLine($"Translated file url: {result.Output.Data?.TranslatedFileUrl}");
}
SourceTexts takes at most 50 non-empty strings of at most 10,000 characters each and is always sent as an array, so TranslatedTexts is an array too. TargetLang takes a language code (e.g. en, zh-tw) or its English name (e.g. English), case insensitive; Sensitives takes at most 50 entries and Glossary at most 100 terms. A file is at most 100 MB, a document at most 200 pages and audio between 3 seconds and 60 minutes. The server also accepts the undocumented extensions .xls, .webp, .bmp, .m4a, .aac, .flac, .ogg, .opus and .mp4. The usage breaks the tokens down by content type in InputTokensDetails / OutputTokensDetails (CharacterTokens, ImageTokens, DocumentTokens, AudioTokens), it is empty when a task fails. Audio input could not be verified when tested: the server answered InternalError (ASR failed after 5 retries) for mp3 and wav inputs. The API is served on the shared domain too, no WorkspaceId is needed although the official docs show the workspace domain url.
Model Inference
Throughput Reservation
A throughput reservation buys input and output throughput for a base model under its own model code: the calls within the reserved throughput are not billed, what exceeds it follows the overflow strategy. It shares the routes of the deployments, so it is created with CreateDeploymentAsync and Plan = "ptu", and it is billed from its creation.
var reservation = await client.CreateDeploymentAsync(new DashScopeCreateDeploymentRequest
{
ModelName = "qwen3.7-flash-2026-07-15",
Plan = "ptu",
ServiceTier = "ptu_fast",
ChargeType = "post_paid",
PtuCapacity = new DashScopePtuCapacity(200000, 20000) // the minimum: 200 kTPM in, 20 kTPM out
});
var code = reservation.Output.DeployedModel; // call the model with this code
var instance = reservation.Output.InstanceId; // the capacity instance the throughput was bought as
var operation = reservation.Output.OperationId; // the purchase, poll it
// wait until the purchase finished, the reservation runs then
DashScopeCapacityOperation finished;
do
{
await Task.Delay(TimeSpan.FromSeconds(30));
finished = await client.GetCapacityOperationAsync(code, operation!);
} while (finished.Output.OperationStatus == "PROCESSING");
// release the instance: it stops the billing. The reservation has to be stopped and deleted afterwards.
await client.DeleteCapacityInstanceAsync(code, instance!, reason: "done");
- The capacity is counted in tokens a minute, with a minimum of 200,000 input and 20,000 output in steps of 10,000 and 1,000, although the documentation calls the unit kTPM:
200is rejected. - The post-paid fast tier is billed per minute from the creation until the instance is released. The standard tier and the 8 hours window are pre-paid only.
ListCapacityInstancesAsyncandGetCapacityInstanceAsyncanswer the instance with its effective, configured and target capacity and the operations it allows right now (CanScale,CanRenew,CanDelete). A released instance stays readable withDeletedtrue.- The writes on a capacity instance (adding, scaling, renewing, releasing) answer a
DashScopeCapacityOperation; poll it withGetCapacityOperationAsyncuntil its status isSUCCEEDEDorFAILED. ScaleDeploymentAsyncandRenewThroughputReservationAsyncare the older way to scale or renew through the model code; prefer the instance routes.UpdateOverflowStrategyAsyncdecides what happens to the traffic beyond the reserved throughput:enablebills it by the tokens,disableanswers it with 429.
What the live API answered when tested:
- The reservation is billed from its creation but only ran thirteen minutes later. The creation operation is
PROCESSINGuntil then, and the lookup rounds the times to seconds while the creation answered them with milliseconds. - The overflow strategy may only be changed once the reservation runs (400
InvalidParameterbefore). The response differs from the lookup: the plan is answered asptu_v2and the capacity under the member names of the quota. - The account may not buy more capacity: scaling the instance up and adding an instance were rejected with status 429
QuotaLimit(Deployments quota limit), a minute later as well. A post-paid instance cannot be renewed, on the instance route and on the reservation route alike (400CAPACITY_INSTANCE_OPERATION_UNSUPPORTED), and scaling it below the minimum is rejected withInvalidParameter(Capacity instance target violates PTUv2 capacity constraints). - An operation id with letters in it is not rejected as unknown but fails with status 500
InternalError, as the documentation warns. - The release succeeded at once and the model code stopped with it, but the first deletion of the stopped code did not finish: two minutes later the code was running again with no capacity left, and the deletion was rejected (
Model Code must be STOPPED before deletion). The stop route, documented for the model unit deployments only, stopped the code again, and the second deletion went through three minutes later.
The reservation of the capture cost about 13.4 CNY an hour at the minimum capacity; its fifteen minutes of capacity cost about 3.4 CNY.
Batch
Use OpenAiCompatibleUploadFileAsync, OpenAiCompatibleCreateBatchAsync, OpenAiCompatibleGetBatchAsync, OpenAiCompatibleListBatchesAsync, and OpenAiCompatibleCancelBatchAsync to manage batch jobs.
Batch API allows you to submit multiple requests in a single JSONL file for asynchronous processing, which is useful for large-scale tasks.
Upload File and Create Batch Job
var client = new DashScopeClient("your-api-key", region: DashScopeRegion.Singapore);
// Prepare JSONL content
var jsonl =
"""
{"custom_id":"1","method":"POST","url":"/v1/chat/ds-test","body":{"model":"batch-test-model","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"你好!有什么可以帮助你的吗?"}]}}
{"custom_id":"2","method":"POST","url":"/v1/chat/ds-test","body":{"model":"batch-test-model","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"What is 2+2?"}]}}
""";
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonl));
// Upload file with purpose "batch"
var inputFile = await client.OpenAiCompatibleUploadFileAsync(stream, "batch_input.jsonl", "batch");
// Create batch job
var batch = await client.OpenAiCompatibleCreateBatchAsync(new DashScopeCreateBatchRequest()
{
InputFileId = inputFile.Id.Value,
CompletionWindow = "24h", // Supports "h" (hours) and "d" (days), range: 24h to 336h
Endpoint = "/v1/chat/ds-test",
Metadata = new DashScopeBatchMetadata()
{
DsName = "My Batch Job", // Optional, max 100 characters
DsDescription = "Description", // Optional, max 200 characters
DsBatchFinishCallback = "https://example.com/callback" // Optional callback URL
}
});
Poll for Completion and Get Results
// Poll batch status
batch = await client.OpenAiCompatibleGetBatchAsync(batch.Id);
// When completed, download the output file
if (batch.Status == "completed" && batch.OutputFileId != null)
{
await using var result = await client.OpenAiCompatibleGetFileContentAsync(batch.OutputFileId);
using var streamReader = new StreamReader(result);
var content = await streamReader.ReadToEndAsync();
// or save to a jsonl file
// using var fileStream = new FileStream($"{batch.OutputFileId}.jsonl", FileMode.Create, FileAccess.Write, FileShare.None, 4096, true);
// await result.CopyToAsync(fileStream);
}
List and Cancel Batches
// List batches with optional filters
var batches = await client.OpenAiCompatibleListBatchesAsync(
limit: 20,
dsName: "keyword"); // Search by name
// Cancel a batch
var cancelled = await client.OpenAiCompatibleCancelBatchAsync(batchId);
Cleanup
// Delete uploaded files when no longer needed
var deletion = await client.OpenAiCompatibleDeleteFileAsync(fileId);
Console.WriteLine(deletion.Deleted ? $"Deleted: {deletion.Id}" : $"Deletion failed: {deletion.Id}");
Model Deployment
CreateDeploymentAsync (POST /api/v1/deployments) publishes a model as an online service. The Plan decides how it is served and billed: mu (model units, billed by the hour the deployment runs), lora (the shared LoRA deployment of an efficiently tuned model: the deployment is free, the calls are billed by their tokens), ptu (a throughput reservation, see Throughput Reservation), ptu_v2 (preset throughput) and dtu (dedicated throughput, pre-paid). Ask the catalog for the models and their templates first:
var catalog = await client.ListDeployableModelsAsync(
new DeployableModelsQuery { ModelSource = "custom", Version = "v1.0" });
// a model unit deployment takes the deploy spec of its catalog template (a LoRA deployment of
// a tuned model takes plan "lora" and capacity 1 instead, and is free)
var deployment = await client.CreateDeploymentAsync(new DashScopeCreateDeploymentRequest
{
ModelName = "text-embedding-v4",
Plan = "mu",
DeploySpec = "MU5",
Capacity = 1
});
// a deployment takes 5 to 10 minutes, poll it until it runs
DashScopeDeployment running;
do
{
await Task.Delay(TimeSpan.FromSeconds(30));
running = await client.GetDeploymentAsync(deployment.Output.DeployedModel);
} while (running.Output.Status is "PENDING" or "DEPLOYING" or "STARTING");
Console.WriteLine(running.Output.DeployedModel); // the model code to call
- One request type serves every plan, the members a plan needs are documented on the properties. A model unit deployment takes
DeploySpecandCapacity(or the prefill and decode capacities of a PD separated template); the DTU plan takes a stock keeping unit, a template code and the throughput; a video generation model tuned with LoRA takesAigcConfig. - The catalog answers every plan of a model with its templates. A model unit template is answered once per charge type it can be bought with, and names its nodes (
unified, orprefillanddecode) with the model unit type and the base capacity, whichCapacityhas to be a multiple of. The DTU templates name the stock keeping unit, the purchase range of the throughput (Maxzero means nothing can be bought) and the standard workload instead. - Pass the
DeploySpecof the catalog template for a model unit deployment, e.g.MU5. The documentation callsTemplateIdthe replacement of a deprecateddeploy_spec, but the live API refused every creation that carriedTemplateId, see below. - Manage a model unit deployment with
ScaleDeploymentAsync(the capacity after the change, a running deployment only),UpdateDeploymentAsync(the rate limits of a model unit deployment, or the model a DTU deployment serves),UpdateDeploymentConfigAsync(the rate limits, documented for the DTU deployments),StopDeploymentAsync,StartDeploymentAsyncandDeleteDeploymentAsync(the documentation wants a model unit deployment stopped first, the live API deleted a running one). Every route answers the deployment in its new status.
What the live API answered when tested:
- Creating a model unit deployment through the API was refused before the account activated the model unit commodity, with status 403
AccessDenied(Commodity not opened: Service not activated : sfm_modelunits_public_cn). After the activation and its agreement the creation was still refused as long as the request carriedTemplateId:No access to model '<model>' under plan 'mu', a message that blames the model although every model answered it, with and without the charge type, the display name and the suffix, while the console created a deployment of one of them. WithDeploySpecthe same request was accepted, with or withoutChargeType. The creation case was captured on a deployment created through the API afterwards; the lifecycle cases below on the one the console created before that was found, an embedding model on one MU5. - The deployment took ten minutes from its creation to
RUNNING. The capacity is answered on the deployment and once more per node inMuCapacity; nothing is ready before it runs. - Both rate limit routes work on a running model unit deployment and change the limits at once:
UpdateDeploymentAsynctakes the request limit asRpmLimitand the service answers it asQpmLimit;UpdateDeploymentConfigAsyncchanges the limits too, although the documentation reserves it for the DTU deployments. - Scaling a running deployment to two units was refused with status 429
StockLimit(Deployments insufficient resource) on the first deployment, the region held no spare unit then. On a second one, created through the API an hour later, the same request was accepted: answered with theSCALINGstatus and the capacity of 2 while one unit was ready, and running with both units nine minutes later. A stopped deployment cannot be scaled at all (UnsupportedOperation,Service is not running, cannot scale). - Stopping is answered with the
STOPPINGstatus and takes about a minute and a half; the stopped deployment answers a capacity of 0 and is not billed. Starting puts the capacity back at once (STARTING) and the deployment runs again four minutes later. Deleting the running deployment was accepted, although the documentation allows the deletion of a stopped or failed one only. - The change routes of a LoRA deployment reject the plan: stopping and scaling with status 400
UnsupportedOperation, the rate limit routes (/updateand/config) with status 500InternalError. - A LoRA deployment is created in the pending status; the lookup rounds the times to seconds and answers an empty throughput tier, unlike the creation. The deployment stayed pending for almost three hours without ever running; deleting it in that status was accepted and answered with the deleting status.
- An unknown model code is answered with status 404
NotFound(Not found.), the capacity routes of the throughput reservations withMODEL_CODE_NOT_FOUNDinstead.
Model Training
Fine-Tuning
CreateFineTuneJobAsync (POST /api/v1/fine-tunes) creates a fine-tune job. The endpoint serves the fine-tuning of the text generation, image generation, video generation and speech synthesis models, and the facechain portrait model (see Portrait (FaceChain)). Training is billed by the tokens it consumes, and only the Beijing region (cn-beijing) serves the API. The text generation and speech synthesis models take their datasets as TrainingDatasets, the image and video generation models and facechain take file ids or urls in TrainingFileIds. Upload the training file with UploadFilesAsync and the purpose fine-tune first:
var job = await client.CreateFineTuneJobAsync(new DashScopeCreateFineTuneJobRequest
{
Model = "qwen3-8b",
TrainingType = "sft",
TrainingDatasets = [new DashScopeFineTuneDataset("file_id", FileId: fileId)],
HyperParameters = new Dictionary<string, object?>
{
["n_epochs"] = 1, ["batch_size"] = 32, ["max_length"] = 8192, ["learning_rate"] = "1.6e-5"
},
FinetunedOutputSuffix = "suffix"
});
- An item of
TrainingDatasetsis either an uploaded file (DataSourceType = "file_id"withFileId) or a path of an OSS bucket (DataSourceType = "oss_mount"withMountStorage: region, bucket and file path).ValidationDatasetshas the same structure, the service splits the training data itself when it is left out. - The image and video generation models take their datasets as zips, one holding the training set and one the validation set, by their file ids in
TrainingFileIdsandValidationFileIds. TrainingTypeis the tuning method:cpt,sft,efficient_sft,dpo_fullordpo_lora.- The keys of
HyperParametersdepend on the model and the tuning method, the documentation lists them. The values are sent as they are, so pass a parameter documented as a string as a string (such aslearning_rate). For the text generation modelsn_epochs,batch_sizeandmax_lengthare required, they decide the cost. JobNamenames the job,FinetunedOutputSuffixends up in the id of the tuned model (qwen3-8b-sdkcnb-ft-202611291620-0c17).
Manage the job:
// poll until it leaves the pending, queuing, running and canceling states
DashScopeFineTuneJob finished;
do
{
await Task.Delay(TimeSpan.FromSeconds(30));
finished = await client.GetFineTuneJobAsync(job.Output.JobId);
} while (finished.Output.Status is DashScopeTaskStatus.Pending or DashScopeTaskStatus.Queuing
or DashScopeTaskStatus.Running or DashScopeTaskStatus.Canceling);
Console.WriteLine($"Tuned model: {finished.Output.FinetunedOutput}, tokens consumed: {finished.Output.Usage}");
// the training log: `line` lines from line `offset + 1` on, at most 1000 lines, 100 by default
var log = await client.GetFineTuneJobLogsAsync(job.Output.JobId, offset: 0, line: 100);
Console.WriteLine($"{log.Output.Logs.Count} of {log.Output.Total} lines");
// the jobs of the account, filtered by base model and paged
var page = await client.ListFineTuneJobsAsync(new FineTuneJobsQuery { Model = "qwen3-8b", PageNo = 1, PageSize = 10 });
// cancel a running job (the tokens consumed so far are still billed) and delete its record
await client.CancelFineTuneJobAsync(job.Output.JobId);
await client.DeleteFineTuneJobAsync(job.Output.JobId);
- A job is
Pendingwhen it was created,Runninga few seconds later, and ends upSucceeded,FailedorCanceled; a cancel passesCanceling.FinetunedOutputis the id of the tuned model once the job succeeded,Usagethe tokens it consumed. - The service answers the job with the datasets it was created with: a dataset based job carries them in
TrainingDatasetsandValidationDatasets, an image based job inTrainingFileIdsandValidationFileIds, anddeclaredMountSourcefalse on every dataset item. CancelFineTuneJobAsyncandDeleteFineTuneJobAsynccarry no payload,Output.Statusof the result issuccesswhen the operation was accepted.- The training log stays readable after the job finished: the log of a facechain job was still returned eight days after it succeeded.
What the live API answered when tested:
- A dataset file that does not exist is rejected when the job is created, with status 400
InvalidParameterandRetrieve file <file id> failed cause File not found.. No training starts, nothing is billed. - The create route is rate limited: the seventh request of a burst within a second was answered with status 429
Throttling.RateQuota(Route requests rate limit exceeded, please try again later.), a body without a request id. About two minutes later the same request went through. - An unknown job id is answered with status 404
NotFound(job <id> not found.) on the get, the cancel and the delete route. - Jobs of an account run in parallel: a second job created while the first one ran was running itself a few seconds later, the queuing status was never seen.
- The list answers the jobs newest first. A running job carries an estimated end time that keeps moving and the number of checkpoints it saved so far;
Usageand the final end time only appear in the final status. - The platform overhead dominates a small job: about 2.5 minutes of data processing, a training of 16 seconds (LoRA, 8,055 tokens) or 3 minutes (full SFT, two epochs, 16,860 tokens), then the model transfer. The jobs succeeded 34 and 50 minutes after they were created, the image job (24 images, two epochs, 198,912 tokens) after 37 minutes. The full parameter job on qwen3.5-flash (one epoch, one step, 5,349 tokens) trained for nine minutes after its data processing and succeeded 50 minutes after it was created too. The log is empty until the data processing finished.
- The hyper parameters of the job carry the learning rate it ran with (
1e-5forsft,3e-4forefficient_sfton qwen3-8b), and a float is echoed in the service's own notation:5.0E-5for5E-05. MaxOutputCntanswered 2 while the LoRA job ran and 1 once it succeeded.- The valid ranges of the hyper parameters depend on the model: qwen3.5-flash-2026-02-23 rejected a
batch_sizeof 8 with status 400InvalidParameter(Hyper parameters: batch_size need to be in range [64, 32768].), and echoed two more defaults than qwen3-8b,modalityandreasoning_mode; its lookups addis_vl(false) and never answer a start time. The model takes no LoRA:efficient_sftwas rejected withInvalidParameter(unsupported model qwen3.5-flash-2026-02-23), no job was created. - Only a running job can be cancelled, a finished one is rejected with status 400
UnsupportedOperation. The job stayed in the canceling status for about three minutes; cancelled before its training started it consumed no tokens. - A cancelled job can be deleted: it left the list at once and its checkpoints were gone, but its lookup by id kept answering it a minute later.
See Snapshot Files for API parameter examples.
Checkpoints
A checkpoint is a snapshot of the model parameters a fine-tune job saved while it trained. ListFineTuneJobCheckpointsAsync (GET /api/v1/fine-tunes/{jobId}/checkpoints) lists them, ordered by step, the highest first:
var checkpoints = await client.ListFineTuneJobCheckpointsAsync(job.Output.JobId);
foreach (var checkpoint in checkpoints.Output)
{
Console.WriteLine($"{checkpoint.Checkpoint}: {checkpoint.Status} {checkpoint.ModelName}");
}
// publish an intermediate checkpoint as a deployable model, then poll the list until it succeeded
await client.ExportFineTuneJobCheckpointAsync(job.Output.JobId, "checkpoint-12", "my-model");
- The final checkpoint of a succeeded job is published as the tuned model: its
ModelNameis theFinetunedOutputof the job. An intermediate checkpoint stays pending until it is exported, and answersModelNameonce it can be deployed. - The export runs in the background: the checkpoint goes through the processing status and gets its model id right away,
{tuned model id}-c{step}, and succeeds some time later (31 minutes in the capture).modelNameonly names the model in the console and has to be unique. - The checkpoints expire two weeks after they were saved (
ExpireTime). - The image and video generation models validate their checkpoints against the validation dataset after every evaluation interval.
ListFineTuneJobValidationResultsAsyncnames the checkpoints that produced a preview,GetFineTuneJobValidationDetailsAsyncreturns the previews page by page; the urls of the previews expire after 24 hours.
var results = await client.ListFineTuneJobValidationResultsAsync(job.Output.JobId);
var details = await client.GetFineTuneJobValidationDetailsAsync(job.Output.JobId, results.Output[0].Checkpoint);
foreach (var preview in details.Output.Items)
{
Console.WriteLine($"{preview.Prompt}: {preview.ImgPath ?? preview.VideoPath}");
}
What the live API answered when tested:
- An unknown job is not answered the same way on every route: the checkpoint list and the export answer it with status 200 and the
NotFoundcode, the validation routes with status 404. The SDK throws aDashScopeExceptionfor both. - The export of a checkpoint whose model name is taken is answered with status 200 and
Conflict(Model name already exists), not withoutputfalse as the documentation announces. An unknown checkpoint of a job that already published its maximum number of models is answered withInvalidParameter(Cannot publish more models: maximum limit reached.). - The checkpoints of the text generation models carry
CheckpointIdandModelDisplayNameand an undocumentedOutputModelDeleted; the facechain job answers neither id and joins its full name with a hyphen instead of a colon. - The name of a checkpoint depends on the model family: a full parameter job on qwen3.5-flash named its single checkpoint
iter_0000001(step 1), while the qwen3-8b jobs name theirs after the training step (checkpoint-11,checkpoint-24). - While a job ran, the checkpoint of its first epoch was pending and had no model; it stayed pending after the job succeeded until it was exported.
- An image job answered two validated checkpoints while it was still running. Its previews carry
ImgPath,Width,Height,Step,Epoch,Seedand the evaluation details, while the documentation only describes theVideoPathandFirstFramePathof the video models. - The validation results of the facechain job are an empty list, its validation details fail with status 500
InternalError.
See Snapshot Files for API parameter examples.
Model Compression
CreateModelCompressionJobAsync (POST /api/v1/fine-tunes/compress/jobs) compresses a custom model by quantization, which lowers its memory footprint and raises its throughput. A tuned model of a compressible base model can be compressed; a base model is rejected. The API is served in the Beijing region (cn-beijing) only.
Create the client with the workspace id (new DashScopeClient(apiKey, workspaceId: "...") or DashScopeOptions.WorkspaceId). The compression routes only answer the custom models of the workspace the X-DashScope-WorkSpace header names, even for the default business space of the key: without the header the templates list no custom model, and creating a job fails with InvalidParameter (Model <model> is not ready for compression. Only READY custom models can be compressed.) whatever the state of the model. Start with the templates:
var templates = await client.ListModelCompressionTemplatesAsync();
foreach (var custom in templates.Output.CustomModels)
{
Console.WriteLine($"{custom.Model}: {string.Join(", ", custom.Templates.Select(t => t.TemplateId))}");
}
var job = await client.CreateModelCompressionJobAsync(new DashScopeCreateModelCompressionJobRequest
{
Model = custom.Model,
TemplateId = template.TemplateId,
OutputModelSuffix = "sdk" // at most 8 lower case letters and digits
});
// poll until the job leaves the pending, queuing, running and canceling statuses
DashScopeModelCompressionJob finished;
do
{
await Task.Delay(TimeSpan.FromSeconds(30));
finished = await client.GetModelCompressionJobAsync(job.Output.JobId);
} while (finished.Output.Status is "PENDING" or "QUEUING" or "RUNNING" or "CANCELING");
Console.WriteLine($"Compressed model: {finished.Output.QuantizedOutput}");
// the log is paged like the one of a fine-tune job; cancel takes a running job, delete a finished one
var log = await client.GetModelCompressionJobLogsAsync(job.Output.JobId, offset: 0, line: 100);
await client.CancelModelCompressionJobAsync(job.Output.JobId); // Output is "success"
await client.DeleteModelCompressionJobAsync(job.Output.JobId); // keeps the compressed model
Output.BaseModelsnames the base models whose tuned models can be compressed,Output.CustomModelsthe compressible models of the workspace with their templates. Themodelfilter narrows both to one base model or to one custom model, and answers the id of a custom model in place of its display name.langpicks the language of the names and descriptions,zh-CN(the default) oren-US.- A template lists the hyper parameters that may be overridden, with their types, ranges and defaults, in
HyperParameters; an empty list means there is nothing to override. The NVFP4 template of qwen3.5-flash carries one,calib_input, of the typeselect. Output.QuantizedOutputis the id of the compressed model,{base model}-{suffix}-{job id}, answered from the creation of the job on; the model exists once the job succeeded, deploy it like any other model.Output.Usageis the GPU time the job consumed in seconds,Output.Errorthe reason of a failure,Output.WorkspaceIdthe workspace of the job.ListModelCompressionJobsAsyncpages through the jobs with the filters ofModelCompressionJobsQuery(status, model, template, times, paging).GetModelCompressionJobLogsAsyncreads the log like the log of a fine-tune job.CancelModelCompressionJobAsyncandDeleteModelCompressionJobAsynccarry no payload and answersuccessinOutput, a plain string where the fine-tune jobs answer an object with a status. Deleting a job keeps the compressed model.
What the live API answered when tested:
- The workspace header is the gate: with it the templates listed four custom models of the workspace, without it none, and every creation was rejected as not ready, a model whose job had succeeded long before included.
- The documentation excludes LoRA models; the live API listed a LoRA model among the compressible models and its job succeeded.
- The templates named six base models, among them qwen3-8b and qwen3.5-4b, while the API documentation only mentions qwen3.5-flash-2026-02-23 and the console guide adds qwen3.6-plus-2026-04-02. A base model is rejected by name:
Base model quantization is not supported, only custom (fine-tuned) models are supported: qwen3-8b. - A job is
PENDINGwhen it is created andRUNNINGfive seconds later. The start time keeps moving while the job runs, the log is empty untilquantization started, and the final log holds three lines. The LoRA job succeeded after ten minutes with a usage of 0; the flash job, the NVFP4 template of a far larger model, needed two hours and eight minutes and answered a usage of 0 too. - A cancel is accepted at once; the job stayed
CANCELINGfor four minutes and then answeredCANCELEDwith the end time. A running job cannot be deleted (UnsupportedOperation,The fine-tune job can not be deleted because it is not succeeded,failed or canceled., the message of the fine-tune jobs); deleting a cancelled or a succeeded job answerssuccess. A finished job cannot be cancelled either (UnsupportedOperation,The fine-tune job can not be canceled because it is succeeded or failed). - An unknown job id is answered with status 404
NotFoundon the lookup, the log, the cancel and the delete route. The sixth request of a burst on the compression routes was throttled with status 429Throttling.RateQuota(the delete route), like the fine-tune routes.
Model Import
CreateModelImportJobAsync (POST /api/v1/custom_models/import) imports a LoRA model stored in OSS, so it can be deployed like a fine-tuned one. Only the Beijing region (cn-beijing) serves the API. The bucket has to be tagged bailian-datahub-access=read and the Bailian service linked role has to be authorized for OSS first, both is done in the console, see the Bailian documentation:
var job = await client.CreateModelImportJobAsync(new DashScopeCreateModelImportJobRequest
{
ModelName = "qwen3-32b",
WeightType = "lora",
StorageInfo = new DashScopeModelImportStorage("my-model-bucket", "models/qwen3-32b-lora/")
});
ModelNameis the base model the imported model was tuned from, only some base models can be imported (Qwen3, Qwen3-VL, Qwen2.5 and Qwen2.5-VL).WeightTypeislora: only LoRA models can be imported.Sourceis alwaysoss.StorageInfo.ObjectKeyis the path prefix holdingadapter_model.safetensors,adapter_config.jsonandconfig.jsondirectly in it, ending with a slash.- Poll
GetModelImportJobAsyncuntilOutput.StatusisSUCCESSED(the model can be deployed withOutput.ModelName) orFAILED(the reason is inOutput.ErrorCode).WeightTypeis only answered when the job is created.
var page = await client.ListModelImportJobsAsync(new ModelImportJobsQuery { Status = "SUCCESSED" });
await client.DeleteModelImportJobAsync(job.Output.JobId); // only a job that succeeded or failed
What the live API answered when tested (a no-op LoRA adapter of qwen3-8b, rank 16):
- The success status is spelled
SUCCESSED, and the status filter of the list matches this exact text:SUCCEEDEDand any other unknown value are not rejected, they match no job.ModelNameof the filter matches the generated model id only, not the display name. - The creation answers
PENDING; the job wasRUNNINGwithin a second andSUCCESSEDabout seven minutes later. - The model files are validated after the creation, a bad directory still gets a job, which fails: a directory without weights with
Import.NoWeightFound, a path that does not exist and the root of the bucket (/) withImport.OssPathMissing. An adapter whose tensors are not keyed the way PEFT saves them (base_model.model.model.layers...lora_A.weight) fails withImport.LoraValidFail. - A base model that cannot be imported (
qwen3.5-flash-2026-02-23), a source other thanoss, an unknown weight type or a path without the trailing slash is rejected on the creation with status 400InvalidParameter. weight_type: fullis documented, but the live API refused it with status 403AccessDenied(No import access for base model: qwen3-8b).- A bucket the service cannot read is rejected on the creation with status 500
InternalErrorandFailed to access source OSS. No job is created in these cases. - Deleting a running job is refused with status 400
OperationDenied(Only jobs in SUCCESS or FAILED status can be deleted, current status: RUNNING), an unknown job id is answered with status 404NotFound(Job: <id> not found!). A deleted job is answered with its details, a failed one with its error code.
See Snapshot Files for API parameter examples.
Application Call
var request =
new ApplicationRequest()
{
Input = new ApplicationInput() { Prompt = "Summarize this file." },
Parameters = new ApplicationParameters()
{
TopK = 100,
TopP = 0.8f,
Seed = 1234,
Temperature = 0.85f,
RagOptions = new ApplicationRagOptions()
{
PipelineIds = ["thie5bysoj"],
FileIds = ["file_d129d632800c45aa9e7421b30561f447_10207234"]
}
}
};
var response = await client.GetApplicationResponseAsync("your-application-id", request);
Console.WriteLine(response.Output.Text);
ApplicationRequest uses Dictionary<string, object?> as the default type for BizParams.
var request =
new ApplicationRequest()
{
Input = new ApplicationInput()
{
Prompt = "Summarize this file.",
BizParams = new Dictionary<string, object?>()
{
{ "customKey1", "custom-value" }
}
}
};
var response = await client.GetApplicationResponseAsync("your-application-id", request);
Console.WriteLine(response.Output.Text);
For strong typing support, you can use the generic class ApplicationRequest<TBizParams>.
Note that the SDK uses snake_case for JSON serialization. If your application uses different naming conventions, manually specify the serialized property names using [JsonPropertyName("camelCase")].
public record TestApplicationBizParam(
[property: JsonPropertyName("sourceCode")]
string SourceCode);
var request =
new ApplicationRequest<TestApplicationBizParam>()
{
Input = new ApplicationInput<TestApplicationBizParam>()
{
Prompt = "Summarize this file.",
BizParams = new TestApplicationBizParam("test")
}
};
var response = await client.GetApplicationResponseAsync("your-application-id", request);
Console.WriteLine(response.Output.Text);
Agent applications take the model of this call and some switches in Parameters, which take precedence over the configuration of the console, and the urls of the files to answer questions upon in FileList:
var request =
new ApplicationRequest()
{
Input = new ApplicationInput()
{
Prompt = "What is the title of the attached file?",
FileList = ["https://example.com/report.pdf"]
},
Parameters = new ApplicationParameters()
{
ModelId = "qwen-plus",
EnableSystemTime = false,
EnableWebSearch = true,
DialogRound = 3,
EnableThinking = true,
HasThoughts = true
}
};
var response = await client.GetApplicationResponseAsync("your-application-id", request);
Console.WriteLine(response.Output.Text);
A workflow application streams the execution of its nodes in Output.WorkflowMessage when FlowStreamMode is ApplicationFlowStreamModes.MessageFormatPlus (every node, including the nodes inside loop and batch sub-canvases) or ApplicationFlowStreamModes.MessageFormat (the output node or the end node only). Nodes inside a sub-canvas name the loop or batch node in ParentNodeId. The last chunk carries the final Text and Usage instead of a workflow message:
var request =
new ApplicationRequest()
{
Input = new ApplicationInput() { Prompt = "Say hello to me." },
Parameters = new ApplicationParameters()
{
FlowStreamMode = ApplicationFlowStreamModes.MessageFormatPlus,
IncrementalOutput = true
}
};
await foreach (var chunk in client.GetApplicationResponseStreamAsync("your-application-id", request))
{
var message = chunk.Output.WorkflowMessage;
if (message != null)
{
Console.WriteLine($"{message.NodeName} ({message.NodeType}): {message.NodeStatus}, {message.Message.Content}");
}
}
Model Management
Model List
List the models of Bailian with ListModelsAsync (GET /api/v1/models). Every model carries its capabilities, the input / output modalities, the features, the prices and the token limits. One page is returned per call:
var page = await client.ListModelsAsync(new ModelListQuery
{
Capabilities = ["TG", "VU"], // text generation or visual understanding
PageSize = 100
});
foreach (var modelInfo in page.Output.Models)
{
Console.WriteLine($"{modelInfo.Model}: {string.Join(", ", modelInfo.Capabilities)}");
}
Console.WriteLine($"{page.Output.Total} models in total"); // increase PageNo to read the next pages
// look one model up
var qwen = (await client.ListModelsAsync(new ModelListQuery { Model = "qwen3.7-max" })).Output.Models[0];
Console.WriteLine($"{qwen.Name} takes up to {qwen.ModelInfo.MaxInputTokens} input tokens, published at {qwen.PublishedTime}");
- Every filter of
ModelListQueryis optional and is not sent when it is left unset:Name(fuzzy),Model(exact),Providers,InferenceProviders,Capabilities,Features,ContextWindow,ServiceSite,Supports,DeploymentMethods,DeploymentPtuServiceTiers,Language(zh-CNoren-US) and the paging. A model matches a list filter when it carries any of its values. PageSizeis at most 200 and defaults to 20. A page beyond the last one is an empty page, not an error.Modelmatches the id exactly and the letter case matters (Qwen3.7-Maxlists nothing). The service ignores an empty value and answers the whole list, leave it unset instead.- A model supplied directly by a third party carries the vendor in its id (
ZHIPU/GLM-5.3,xiaomi/mimo-v2.6-pro-ultraspeed) and inInferenceProvider, the models hosted by Bailian havealiyun-bailianthere. - A rejected parameter (e.g.
PageNo = 0) throws aDashScopeExceptionalthough the service answers with status 200, the detail is inDashScopeException.Error.
See Snapshot Files for API parameter examples.
Review Tests for comprehensive usage examples.
Model Rate Limits
Query the rate limit quotas of the models with ListModelLimitsAsync (GET /api/v1/models/limits). Every row carries the account level limit of the model (ModelLimit, the upper bound shared by every workspace of the account) and its workspace level limit (WorkspaceLimit, null when none was set):
var page = await client.ListModelLimitsAsync(new ModelLimitsQuery { Model = "wan2.6-i2v-flash" });
var quota = page.Output.Quotas[0];
Console.WriteLine($"{quota.Model}: {quota.ModelLimit.RequestLimit} requests / {quota.ModelLimit.RequestLimitPeriod}s");
- Every filter of
ModelLimitsQueryis optional and is not sent when it is left unset:Name(fuzzy),Model(exact) and the paging,PageSizedefaults to 20. A page beyond the last one is an empty page, not an error. - A
RequestLimitof 5 with aRequestLimitPeriodof 1 means 5 requests per second, 60 with 60 means 60 requests per minute (QPM). A nullUsageLimitmeans no usage limit,UsageLimitField(e.g.total_tokens) tells what is limited,UsageLimitPeriodis its period in seconds (TPM). - The asynchronous models carry
AsyncUserQueueLimitandAsyncUserConcurrencyLimitfor their task queues. - A rejected parameter (e.g.
PageNo = 0) throws aDashScopeExceptionalthough the service answers with status 200, the detail is inDashScopeException.Error.
Update the workspace level limits (QPM/TPM) with UpdateModelLimitsAsync (POST /api/v1/models/limits), 1 to 200 models per call. An overlay (the default) only changes the given members, a deletion clears every workspace level limit of the model:
// set QPM=60 and TPM=100000 in one overlay
await client.UpdateModelLimitsAsync(
[new DashScopeUpdateModelLimit("qwen-plus", RequestLimit: 60, UsageLimit: 100000)]);
// remove the workspace level limits of a model again
await client.UpdateModelLimitsAsync([new DashScopeUpdateModelLimit("qwen-plus", "DELETE")]);
- A member left null is not changed by an overlay, every member has to be left unset for a deletion.
- The service rejects a usage limit for a model without a request limit, set both in one overlay or delete the limits first, see the TPM exemption section of the documentation. The workspace limits of a model may not exceed its account level limit in total.
- A rejected update throws a
DashScopeExceptionalthough the service answers with status 200, the detail is inDashScopeException.Error.
What the live API answered when tested:
- Both endpoints are served on the shared domain although the documentation only lists the workspace domain. The workspace is the one the API key belongs to: neither the workspace domain (
DashScopeOptions.WorkspaceId) nor theX-DashScope-WorkSpaceheader switches it for these endpoints, use a key that was created in the workspace to read or update its limits. - An update with a key of the default workspace is rejected with status 200 and
Invalid request parameter: workspaceId(code10110400) currently, a key of a sub workspace is accepted. - After an overlay the list answers the new limits in
WorkspaceLimit, the service fillsUsageLimitFieldin (total_tokens). A usage limit without a request limit is rejected with status 200, code10110400and aCurrent operation is denied: Cannot set TPM without QPM ...message, not theInvalidParametercode of the failure example in the documentation. - Every rejection is wired as a
DashScopeException, the fixtures document both.
See Snapshot Files for API parameter examples.
Review Tests for comprehensive usage examples.
Model Permissions
Query the model authorizations of the workspace with ListModelPermissionsAsync (GET /api/v1/models/permissions). The default scope lists every model the workspace may authorize, AuthorizationScope = "AUTHORIZED" only the ones it is authorized for:
var page = await client.ListModelPermissionsAsync(new ModelPermissionsQuery
{
AuthorizationScope = "AUTHORIZED",
Name = "qwen"
});
foreach (var permission in page.Output.Permissions)
{
Console.WriteLine($"{permission.Model} ({permission.Name}): inference={permission.Permissions.Inference}");
}
- Every filter of
ModelPermissionsQueryis optional and is not sent when it is left unset:Name(fuzzy, matches the model names and ids),Model(exact),AuthorizationScope(AUTHORIZABLEby default) andAction(INFERENCEby default, only used with the authorized scope). The paging defaults to page 1 of 20 models,PageSizeis at most 200. Permissions.Inferenceistruefor an authorized model.FineTuneandDeployaretruewhen the workspace is authorized to fine tune or deploy the model, null when it is not.
Update the authorizations with UpdateModelPermissionsAsync (POST /api/v1/models/permissions), up to 20 models per call. A member left null keeps the current authorization:
// authorize qwen-plus for inference and fine tuning
await client.UpdateModelPermissionsAsync(
[new DashScopeUpdateModelPermission("qwen-plus", Inference: true, FineTune: true)]);
// revoke the inference authorization again
await client.UpdateModelPermissionsAsync([new DashScopeUpdateModelPermission("qwen-plus", Inference: false)]);
// one click authorization: every inference model of the workspace, including the ones added later
await client.UpdateModelPermissionsAsync(accessAllEntities: "OPEN");
accessAllEntitiesis the one click authorization switch:OPENauthorizes every inference model (including the ones added later),CLOSEturns it off and clears every inference authorization of the workspace,KEEP(the default) keeps the per model behavior. While it is on, the per modelInferencechanges are accepted but have no effect, turn it off first.FineTuneis sent asfinetunewhile the list answers it asfine_tune, the SDK maps both.- A rejected update (an unknown model, empty parameters) throws a
DashScopeExceptionalthough the service answers with status 200, the detail is inDashScopeException.Error. A series of updates within a short time is throttled with status 429 (Throttling.RateQuota), wait and retry.
What the live API answered when tested:
- Both endpoints only accept a key of a sub workspace. The default workspace of an API key is rejected with status 200 and
Invalid request parameter: workspaceId(code10110400), the query too. The workspace is the one the API key belongs to: neither the workspace domain (DashScopeOptions.WorkspaceId) nor theX-DashScope-WorkSpaceheader switches it. - An unknown model is rejected with code
10110438andModel is not authorized for this workspace: <model>, not theInvalidParametercode of the failure example in the documentation. - A revoked
FineTuneorDeploypermission is answered asnullby the list again, as if it was never granted.
See Snapshot Files for API parameter examples.
Review Tests for comprehensive usage examples.
Temporary API Key
Create a short-lived API key with CreateTemporaryApiKeyAsync (POST /api/v1/tokens) to call the models from an untrusted environment (browser, mobile app) without exposing the permanent key. The temporary key inherits all the permissions of the key signing the request, it cannot be revoked and stops working once it expired:
var temporaryApiKey = await client.CreateTemporaryApiKeyAsync(); // expires in 60 seconds
var temporaryApiKey = await client.CreateTemporaryApiKeyAsync(1800); // time to live in seconds, at most 1800
Console.WriteLine($"{temporaryApiKey.Token} expires at {temporaryApiKey.ExpiresAt}"); // Unix timestamp, in seconds
Hand the Token to the untrusted client through your own backend, see the Bailian documentation for the usage scenarios.
Async Task Callback (EventBridge)
Polling a task with the Get*TaskAsync methods costs a request per round, and the task query API is throttled at 20 QPS. Bailian reports every finished asynchronous task to EventBridge, whether it succeeded or failed, and EventBridge pushes a dashscope:System:AsyncTaskFinish event to the HTTP callback url you configure, see the Bailian documentation. DashScopeAsyncTaskFinishEvent maps the body of the callback:
// ASP.NET Core minimal API, the event binds with the default JSON options (Deserialize needs using System.Text.Json)
app.MapPost("/dashscope/task-callback", async (DashScopeAsyncTaskFinishEvent @event, IDashScopeClient client) =>
{
// other events may be routed to the same url
if (@event.Type != "dashscope:System:AsyncTaskFinish")
{
return Results.BadRequest();
}
var task = @event.Data;
ImageGenerationOutput output;
if (task.ContainResult)
{
// the event carries the result of the task query already, read it as the response type of
// the Get*TaskAsync method of the model api the task was created with
output = task.OutputResult!.Value
.Deserialize<ModelResponse<ImageGenerationOutput, MultimodalTokenUsage>>(DashScopeDefaults.SerializationOptions)!.Output;
}
else
{
// query once instead of polling, with the method of the model api the task was created with
output = (await client.GetImageGenerationTaskAsync(task.TaskId)).Output;
}
Console.WriteLine($"{task.TaskId} is {output.TaskStatus}, model api {task.UserApiUniqueKey}");
Console.WriteLine(output.TaskStatus == DashScopeTaskStatus.Failed
? $"Task failed: {output.Code} {output.Message}"
: $"Image URL: {output.Choices?[0].Message.Content[0].Image}");
return Results.Ok();
});
- Create the event rule once in the EventBridge console of the region the tasks run in (the bus
defaultofcn-beijing): event sourceacs.dashscope, event typedashscope:System:AsyncTaskFinish, and an HTTP event target with your url and the full event as the body. The pattern may filter bydata.user_api_unique_key, e.g. the suffix:wan2.6-t2ionly forwards the events of that model. Data.TaskIdis theOutput.TaskIdthe creation of the task returned,Data.UserApiUniqueKeyends with the model name.Data.TaskStatustells whether the taskSucceededorFailed, a failed task carries its error code and message inCodeandMessageof the output.- Every member carries its wire name, so the event binds with the default
JsonSerializerOptionsof ASP.NET Core model binding, and reads withrequest.ReadFromJsonAsync<DashScopeAsyncTaskFinishEvent>()orJsonSerializer.Deserialize<DashScopeAsyncTaskFinishEvent>(json, DashScopeDefaults.SerializationOptions).
What the live events answered when tested:
- The events carried the result of the task for both a succeeded and a failed one (
ContainResultis true,OutputResultholds theoutputandusageof the task query without itsrequest_id). The documentation shows events without a result too, so checkContainResultbefore readingOutputResult. OutputResulthas to be read withDashScopeDefaults.SerializationOptions: the output types rely on its snake case naming policy, the default options would leave their members empty.TimeandAliyunPublishTimeare RFC 3339 timestamps in UTC,Data.StartTimeandData.EndTimeare Beijing times without an offset.
探索相关项目
加载中…