Gerar texto
Faça sua primeira chamada de geração de texto
Modelos de geração de texto pegam entrada de linguagem natural e geram texto para tarefas como resposta a perguntas, escrita, síntese, tradução e geração de saída estruturada.
Solicitar estrutura.
Pedidos de geração de texto são normalmente enviados como um messages Array. Cada mensagem inclui um role e content.
- Fornece instruções de alto nível ou define o comportamento do modelo.
- Mensagem do usuário: contém a entrada ou tarefa do usuário.
- Mensagem de assistente contém a resposta do modelo.
Um pedido típico inclui um user - Mensagem e pode incluir opcionalmente um system Mensagem para uma saída mais estável ou mais controlável.
O system A mensagem é opcional, mas recomendada quando você want comportamento mais consistente.
[
{"role": "system", "content": "You are a helpful assistant. Answer clearly and concisely."},
{"role": "user", "content": "Summarize the benefits of solar energy in three bullet points."}
]
O modelo retorna sua resposta como um assistant Mensagem.
{
"role": "assistant",
"content": "- Reduces reliance on fossil fuels.\n- Lowers long-term electricity costs.\n- Produces electricity with minimal operating emissions."
}
Faça sua primeira ligação.
Antes de começar, pegue uma chave API (/api-reference/preparation/api-key(Colocar como variável de ambiente) (/api-reference/preparation/export-api-key-env), e, se necessário, [instalar o OpenAI ou DashScope SDK] (/api-reference/preparation/install-sdk).
Escolha o estilo de API que combina com sua pilha:
- Comece com OpenAI Compatível -- API de respostas para novas integrações.
- Use OpenAI Compatível -- Chat Completions API se você estiver migrando código existente compatível com OpenAI.
- Use **[A API de Mensagens Antrópicas] (/api-reference/chat/anthropicSe você está migrando de Antrópico. Suporta características como pensar e chamar ferramentas.
- Use o DashScope se preferir o SDK nativo.
OpenAI Compatible -- Responses API
Para notas de uso, exemplos de código e orientação de migração, veja [OpenAI compatível - Respostas] (/api-reference/chat/openai-responses).
```python Python
import os
from openai import OpenAI
try:
client = OpenAI(
# If you have not set an environment variable, replace the next line with your API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
)
response = client.responses.create(
model="qwen3.7-plus",
input="Summarize the benefits of solar energy in three bullet points."
)
print(response)
except Exception as e:
print(f"Error message: {e}")
```
```javascript Node.js
// Requires Node.js v18+. Run in an ES Module environment.
import OpenAI from "openai";
const openai = new OpenAI({
// If you have not set an environment variable, replace the next line with your API key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://maas.qwencloudapi.com/compatible-mode/v1"
});
async function main() {
try {
const response = await openai.responses.create({
model: "qwen3.7-plus",
input: "Summarize the benefits of solar energy in three bullet points."
});
// Get model response
console.log(response);
} catch (error) {
console.error("Error:", error);
}
}
main();
```
```bash curl
curl -X POST https://maas.qwencloudapi.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.7-plus",
"input": "Summarize the benefits of solar energy in three bullet points.",
"enable_thinking": true
}'
```
? Responder ?
A resposta inclui estes campos principais:
- `id`A identificação de resposta.
- `output`A lista de saída. Inclusões `reasoning` e `message`.
O `reasoning` O campo só aparece quando [pensamento profundo] (/developer-guides/text-generation/thinking) está habilitado (por exemplo, ele está habilitado por padrão no Qwen3.5 e Qwen3.6 Série).
- `usage` Estatísticas de uso de token.
Exemplo de saída de texto:
```text
- Reduces reliance on fossil fuels.
- Lowers long-term electricity costs.
- Produces electricity with minimal operating emissions.
```
Resposta completa do JSON
```json
{
"created_at": 1772249518,
"id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
"model": "qwen3.7-plus",
"object": "response",
"output": [
{
"id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
"summary": [
{
"text": "The user wants a concise answer in exactly three bullet points. Focus on the most broadly useful benefits of solar energy: reduced reliance on fossil fuels, long-term cost savings, and lower operating emissions. Keep the wording simple and direct.\n",
"type": "summary_text"
}
],
"type": "reasoning"
},
{
"content": [
{
"annotations": [],
"text": "- Reduces reliance on fossil fuels.\n- Lowers long-term electricity costs.\n- Produces electricity with minimal operating emissions.",
"type": "output_text"
}
],
"id": "msg_35be06c6-ca4d-4f2b-9677-7897e488dxxx",
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"parallel_tool_calls": false,
"status": "completed",
"tool_choice": "auto",
"tools": [],
"usage": {
"input_tokens": 54,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 662,
"output_tokens_details": {
"reasoning_tokens": 447
},
"total_tokens": 716,
"x_details": [
{
"input_tokens": 54,
"output_tokens": 662,
"output_tokens_details": {
"reasoning_tokens": 447
},
"total_tokens": 716,
"x_billing_type": "response_api"
}
]
}
}
```
OpenAI Compatible -- Chat Completions API
```python Python
import os
from openai import OpenAI
try:
client = OpenAI(
# If you have not set an environment variable, replace the next line with your API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.7-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Summarize the benefits of solar energy in three bullet points."},
],
)
print(completion.choices[0].message.content)
# To view the full response, uncomment the following line
# print(completion.model_dump_json())
except Exception as e:
print(f"Error message: {e}")
```
```java Java
// OpenAI Java SDK version >= 3.5.0 recommended
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class Main {
public static void main(String[] args) {
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
// If you have not set an environment variable, replace the next line with .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://maas.qwencloudapi.com/compatible-mode/v1")
.build();
// Create ChatCompletion parameters
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen3.7-plus")
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("Summarize the benefits of solar energy in three bullet points.")
.build();
// Send request and get response
ChatCompletion chatCompletion = client.chat().completions().create(params);
String content = chatCompletion.choices().get(0).message().content().orElse("No content returned");
System.out.println(content);
} catch (Exception e) {
System.err.println("Error message: " + e.getMessage());
}
}
}
```
```javascript Node.js
// Requires Node.js v18+. Run in an ES Module environment.
import OpenAI from "openai";
const openai = new OpenAI(
{
// If you have not set an environment variable, replace the next line with: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://maas.qwencloudapi.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.7-plus",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Summarize the benefits of solar energy in three bullet points." }
],
});
console.log(completion.choices[0].message.content);
// To view the full response, uncomment the following line
// console.log(JSON.stringify(completion, null, 4));
```
```go Go
// OpenAI Go SDK version >= v2.4.0
package main
import (
"context"
// To view the full response, uncomment the following line
// "encoding/json"
"fmt"
"os"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
client := openai.NewClient(
option.WithAPIKey(apiKey),
option.WithBaseURL("https://maas.qwencloudapi.com/compatible-mode/v1"),
)
chatCompletion, err := client.Chat.Completions.New(
context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("Summarize the benefits of solar energy in three bullet points."),
},
Model: "qwen3.7-plus",
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
if len(chatCompletion.Choices) > 0 {
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
// To view the full response, uncomment the following line
// jsonData, _ := json.MarshalIndent(chatCompletion, "", " ")
// fmt.Println(string(jsonData))
}
```
```csharp C#
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// If you have not set an environment variable, replace the next line with: string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
string url = "https://maas.qwencloudapi.com/compatible-mode/v1/chat/completions";
string jsonContent = @"{
""model"": ""qwen3.7-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Summarize the benefits of solar energy in three bullet points.""
}
]
}";
// Send request and get response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// To view the full response, uncomment the following line
// Console.WriteLine(result);
// Parse JSON and output only the content field
using JsonDocument doc = JsonDocument.Parse(result);
JsonElement root = doc.RootElement;
if (root.TryGetProperty("choices", out JsonElement choices) &&
choices.GetArrayLength() > 0)
{
JsonElement firstChoice = choices[0];
if (firstChoice.TryGetProperty("message", out JsonElement message) &&
message.TryGetProperty("content", out JsonElement content))
{
Console.WriteLine(content.GetString());
}
}
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
```
```php PHP
<?php
// Set the request URL
$url = 'https://maas.qwencloudapi.com/compatible-mode/v1/chat/completions';
// If you have not set an environment variable, replace the next line with: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Set request body
$data = [
"model" => "qwen3.7-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Summarize the benefits of solar energy in three bullet points."
]
]
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close cURL resources
curl_close($ch);
// Output response
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// To view the full response, uncomment the following line
//echo $response;
?>
```
```bash curl
curl -X POST https://maas.qwencloudapi.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.7-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Summarize the benefits of solar energy in three bullet points."
}
]
}'
```
? Responder ?
```text
- Reduces reliance on fossil fuels.
- Lowers long-term electricity costs.
- Produces electricity with minimal operating emissions.
```
Resposta completa do JSON
```json
{
"choices": [
{
"message": {
"role": "assistant",
"content": "- Reduces reliance on fossil fuels.\n- Lowers long-term electricity costs.\n- Produces electricity with minimal operating emissions."
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 26,
"completion_tokens": 66,
"total_tokens": 92
},
"created": 1726127645,
"system_fingerprint": null,
"model": "qwen3.7-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}
```
DashScope
qwen3.7-max e qwen3.7-max-2026-05-20 Só suporta a interface de texto (`Generation`). qwen3.8-max, qwen3.8-max-0902, e qwen3.7-max-2026-06-08 Suportar a interface multimodal. O Qwen3.6 e Qwen3.5 Séries requerem a interface multimodal (`MultiModalConversation`). Os exemplos nesta aba usam `qwen-plus` através da interface de texto. Para modelos que exigem a interface multimodal, veja a guia **Multimodal API**.
```python Python
import json
import os
from dashscope import Generation
import dashscope
dashscope.base_http_api_url = "https://maas.qwencloudapi.com/api/v1"
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Summarize the benefits of solar energy in three bullet points."},
]
response = Generation.call(
# If you have not set an environment variable, replace the next line with: api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message",
)
if response.status_code == 200:
print(response.output.choices[0].message.content)
# To view the full response, uncomment the following line
# print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
print(f"HTTP status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
```
```java Java
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://maas.qwencloudapi.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Summarize the benefits of solar energy in three bullet points.")
.build();
GenerationParam param = GenerationParam.builder()
// If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
// To view the full response, uncomment the following line
// System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message:"+e.getMessage());
}
}
}
```
```javascript Node.js
// Requires Node.js v18+
// If you have not set an environment variable, replace the next line with: const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Summarize the benefits of solar energy in three bullet points."
}
]
},
parameters: {
result_format: "message"
}
};
async function callApi() {
try {
const response = await fetch('https://maas.qwencloudapi.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
console.log(result.output.choices[0].message.content);
// To view the full response, uncomment the following line
// console.log(JSON.stringify(result));
} catch (error) {
console.error('Call failed:', error.message);
}
}
callApi();
```
```go Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
requestBody := map[string]interface{}{
"model": "qwen-plus",
"input": map[string]interface{}{
"messages": []map[string]string{
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": "Summarize the benefits of solar energy in three bullet points.",
},
},
},
"parameters": map[string]string{
"result_format": "message",
},
}
// Serialize to JSON
jsonData, _ := json.Marshal(requestBody)
// Create HTTP client and request
client := &http.Client{}
req, _ := http.NewRequest("POST", "https://maas.qwencloudapi.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
// Set request headers
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read response body
bodyText, _ := io.ReadAll(resp.Body)
// Parse JSON and output content
var result map[string]interface{}
json.Unmarshal(bodyText, &result)
content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
fmt.Println(content)
// To view the full response, uncomment the following line
// fmt.Printf("%s\n", bodyText)
}
```
```csharp C#
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// If you have not set an environment variable, replace the next line with: string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// Set request URL and content
string url = "https://maas.qwencloudapi.com/api/v1/services/aigc/text-generation/generation";
string jsonContent = @"{
""model"": ""qwen-plus"",
""input"": {
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Summarize the benefits of solar energy in three bullet points.""
}
]
},
""parameters"": {
""result_format"": ""message""
}
}";
// Send request and get response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
var jsonResult = System.Text.Json.JsonDocument.Parse(result);
var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
Console.WriteLine(content);
// To view the full response, uncomment the following line
// Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// Set request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send request and get response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Handle response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
```
```php PHP
<?php
$url = "https://maas.qwencloudapi.com/api/v1/services/aigc/text-generation/generation";
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
"model" => "qwen-plus",
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Summarize the benefits of solar energy in three bullet points."
]
]
],
"parameters" => [
"result_format" => "message"
]
];
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
$jsonResult = json_decode($response, true);
$content = $jsonResult['output']['choices'][0]['message']['content'];
echo $content;
// To view the full response, uncomment the following line
// echo "Model response: " . $response;
} else {
echo "Request error: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>
```
```bash curl
curl --location "https://maas.qwencloudapi.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Summarize the benefits of solar energy in three bullet points."
}
]
},
"parameters": {
"result_format": "message"
}
}'
```
? Responder ?
```text
- Reduces reliance on fossil fuels.
- Lowers long-term electricity costs.
- Produces electricity with minimal operating emissions.
```
Resposta completa do JSON
```json
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "- Reduces reliance on fossil fuels.\n- Lowers long-term electricity costs.\n- Produces electricity with minimal operating emissions."
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx",
"model": "qwen-plus"
}
```
DashScope -- Multimodal API
qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, e qwen3.7-max-2026-06-08 Suporte a API multimodal. O Qwen3.6 e Qwen3.5 Séries exigem a API multimodal DashScope (`MultiModalConversation` Não é a interface de texto.`Generation`). Executando os exemplos da aba anterior diretamente resultará em um erro de url. O conteúdo da mensagem do usuário deve ser uma variedade de objetos.
```python Python
import os
import dashscope
from dashscope import MultiModalConversation
dashscope.base_http_api_url = "https://maas.qwencloudapi.com/api/v1"
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": [{"text": "Summarize the benefits of solar energy in three bullet points."}],
},
]
response = MultiModalConversation.call(
# If you have not set an environment variable, replace the next line with: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.7-plus",
messages=messages,
)
if response.status_code == 200:
print(response.output.choices[0].message.content[0]["text"])
# To view the full response, uncomment the following line
# import json; print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
print(f"HTTP status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
```
```java Java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
}
public static void main(String[] args) {
try {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(List.of(Collections.singletonMap("text", "Summarize the benefits of solar energy in three bullet points.")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.7-plus")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.err.println("Error message: " + e.getMessage());
}
}
}
```
```bash curl
curl -X POST https://maas.qwencloudapi.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.7-plus",
"input": {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": [{"text": "Summarize the benefits of solar energy in three bullet points."}]
}
]
}
}'
```
? Responder ?
```text
- Reduces reliance on fossil fuels.
- Lowers long-term electricity costs.
- Produces electricity with minimal operating emissions.
```
Resposta completa do JSON
```json
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"text": "- Reduces reliance on fossil fuels.\n- Lowers long-term electricity costs.\n- Produces electricity with minimal operating emissions."
}
]
}
}
]
},
"usage": {
"input_tokens": 25,
"output_tokens": 613,
"total_tokens": 638
},
"request_id": "1486945b-ebc7-93a1-af4d-651f8e18e76f"
}
```
Lidar com pedidos assincronicamente
Uma vez que um pedido síncrono básico está funcionando, chamadas assíncronas podem melhorar o rendimento para cargas de trabalho de alta concorrência.
OpenAI Compatible -- Chat Completions API
```python Python
import os
import asyncio
from openai import AsyncOpenAI
import platform
# Create an asynchronous client instance
client = AsyncOpenAI(
# If you have not set an environment variable, replace the line below with: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1"
)
# Define an asynchronous task list
async def task(question):
print(f"Send question: {question}")
response = await client.chat.completions.create(
messages=[
{"role": "user", "content": question}
],
model="qwen3.7-plus",
)
print(f"Model response: {response.choices[0].message.content}")
# Main asynchronous function
async def main():
questions = [
"Summarize the benefits of solar energy in three bullet points.",
"Write a subject line for a product launch email.",
"Translate \"Welcome to our platform\" into Spanish."
]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# Set event loop policy
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Run the main coroutine
asyncio.run(main(), debug=False)
```
```java Java
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
// Create an OpenAI client connected to DashScope's compatibility endpoint
OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
// If you have not set an environment variable, replace the line below with .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://maas.qwencloudapi.com/compatible-mode/v1")
.build();
// Define a list of questions
List<String> questions = Arrays.asList(
"Summarize the benefits of solar energy in three bullet points.",
"Write a subject line for a product launch email.",
"Translate \"Welcome to our platform\" into Spanish."
);
// Create a list of asynchronous tasks
CompletableFuture<?>[] futures = questions.stream()
.map(question -> CompletableFuture.supplyAsync(() -> {
System.out.println("Send question: " + question);
// Create ChatCompletion parameters
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen3.7-plus")
.addSystemMessage("You are a helpful assistant.")
.addUserMessage(question)
.build();
// Send asynchronous request and handle response
return client.chat().completions().create(params)
.thenAccept(chatCompletion -> {
String content = chatCompletion.choices().get(0).message().content().orElse("No response content");
System.out.println("Model response: " + content);
})
.exceptionally(e -> {
System.err.println("Error: " + e.getMessage());
return null;
});
}).thenCompose(future -> future))
.toArray(CompletableFuture[]::new);
// Wait for all asynchronous operations to complete
CompletableFuture.allOf(futures).join();
}
}
```
DashScope
O SDK DashScope suporta chamadas de geração de texto assíncronas apenas em Python.
```python
# DashScope Python SDK version must be at least 1.19.0
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'
# Define an asynchronous task list
async def task(question):
print(f"Send question: {question}")
response = await AioGeneration.call(
# If you have not set an environment variable, replace the line below with: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question}],
result_format="message",
)
if response.status_code == 200:
print(f"Model response: {response.output.choices[0].message.content}")
else:
print(f"Request failed: code={response.status_code}, message={response.message}")
# Main asynchronous function
async def main():
questions = [
"Summarize the benefits of solar energy in three bullet points.",
"Write a subject line for a product launch email.",
"Translate \"Welcome to our platform\" into Spanish."
]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# Set event loop policy
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Run the main coroutine
asyncio.run(main(), debug=False)
```
? Responder ?
Como a chamada é assíncrona, a ordem das respostas pode diferir do exemplo.
Send question: Summarize the benefits of solar energy in three bullet points.
Send question: Write a subject line for a product launch email.
Send question: Translate "Welcome to our platform" into Spanish.
Model response: - Reduces reliance on fossil fuels.
- Lowers long-term electricity costs.
- Produces electricity with minimal operating emissions.
Model response: Meet our newest product launch
Model response: Bienvenido a nuestra plataforma.
Indo ao vivo
Construir um contexto melhor
Dar dados brutos diretamente a um modelo de linguagem grande aumenta os custos e reduz a qualidade devido aos limites de duração do contexto. Engenharia de contexto melhora a qualidade e eficiência da saída carregando dinamicamente conhecimento preciso. Técnicas principais:
- Engenharia de ponta: Design e refinar instruções de texto (prompts) para guiar o modelo em direção às saídas desejadas. Para mais informações, veja [texto-para-texto guia prompt] (/developer-guides/accuracy-tuning/text-generation).
- Use esta técnica quando o modelo deve responder perguntas usando bases de conhecimento externas, como documentação de produto ou manuais técnicos.
- ** Chamada de ferramentas**: Permite que o modelo obtenha dados em tempo real, como tempo ou tráfego, ou execute ações, como chamar uma API ou enviar um e-mail.
- Mecanismos de memória: fornecer o modelo com memória de curto prazo e longo prazo para entender a história da conversa.
Explore mais recursos de geração de texto.
Para cenários complexos:
- [Conversas multi-virar] (/developer-guides/run-and-scale/multi-turnUse esta característica para perguntas de acompanhamento ou coleta de informações que requerem diálogo contínuo.
- [Streaming saída] (/developer-guides/run-and-scale/streamingUse esta funcionalidade para chatbots ou geração de código em tempo real para melhorar a experiência do usuário e evitar os intervalos de tempo causados por longas respostas.
- [Pensamento profundo] (/developer-guides/text-generation/thinkingUse esta característica para raciocínio complexo ou análise política que requer respostas estruturadas e de alta qualidade.
- [Estruturada saída] (/developer-guides/text-generation/structured-outputUse este recurso quando precisar do modelo para responder em um formato JSON estável para uso programático ou análise de dados.
- [Modo parcial] (/developer-guides/text-generation/partial-modeUse esta característica para completar código ou escrever em forma longa onde o modelo continua do texto existente.
Referência
Para uma lista completa de parâmetros de invocação do modelo, veja OpenAI Referência API compatível, [Anthropic Compatível API Reference] (/api-reference/chat/anthropic), e [DashScope API Reference] (/api-reference/chat/dashscope).
FAQ
Por que a contagem de fichas é maior que a contagem de fichas do texto que enviei?
Ao processar uma conversa, o sistema usa um modelo de bate-papo para embrulhar o texto de entrada bruto, adicionando marcadores de controle, como identificadores de papéis e limites de mensagens. Esses marcadores gerados pelo sistema também são contados como fichas.
Por exemplo, quando você envia a mensagem {"role": "user", "content": "Hi"} para qwen3.8-maxO texto "Oi" corresponde a apenas 1 token após a tokenização. No entanto, durante o processamento do sistema, o texto completo é formatado da seguinte forma: <|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>. Após a tokenização, este texto completo aumenta a contagem total de tokens para 11.
Por que não pode Qwen API analisa links web?
O Qwen API não pode acessar diretamente ou processar links web. Você pode usar [Function chamando] (/developer-guides/tool-calling/function-calling), ou combiná-los com ferramentas de raspagem web como a sopa bonita de Python para ler conteúdo de página web.
Por que não? Qwen O aplicativo da web e a API diferem?
O Qwen O aplicativo web inclui otimizações de engenharia adicionais além do Qwen API, recursos habilitados, como análise de páginas, pesquisa na web, desenho de imagens e criação de PPT. Essas capacidades não são parte do modelo de linguagem grande da API. Você pode replicar usando [Function chamando] (/developer-guides/tool-calling/function-calling) para melhorar o desempenho do modelo.
O modelo pode gerar arquivos Word, Excel, PDF ou PPT?
Não, eles não podem. QwenCloud Modelos de geração de texto produzem apenas texto simples. Você pode converter o texto para o formato desejado usando código ou bibliotecas de terceiros.