Qwen4-Max devuelve un resumen para mostrar y el razonamiento completo cifrado para restaurar el historial en conversaciones de varios turnos.
Modelo compatible: qwen4-max.
Funcionamiento
De forma predeterminada se devuelve el razonamiento completo. Al activar la función, el razonamiento original deja de devolverse en texto sin cifrar: el resumen sirve para mostrarlo y el contenido cifrado para restaurar el historial.
El resumen y el cifrado se activan juntos. El contenido cifrado puede faltar si no se genera razonamiento o falla el cifrado. El resumen puede faltar o estar incompleto; el razonamiento original sigue sin devolverse en texto sin cifrar.
Active esta función en cada solicitud y reenvíe el contenido cifrado histórico sin cambios para restaurar el razonamiento correspondiente.
Las entradas de texto y multimodales usan los mismos parámetros. El cifrado solo conserva el razonamiento; guarde también imágenes, videos y otras entradas históricas. Conserve cada segmento cifrado con su mensaje assistant, incluidos los turnos con herramientas.
Active enable_thinking=true para Chat Completions y DashScope y use preserve_thinking=true para continuar con el historial cifrado. Responses y Anthropic Messages usan sus propios parámetros de razonamiento.
Activación
Los ejemplos usan Singapore. Sustituya WorkspaceId por el ID de su espacio de trabajo y configure DASHSCOPE_API_KEY.
| API | Parámetro de activación | Campo del resumen | Campo cifrado |
|---|---|---|---|
| Chat Completions | thinking_display="summarized" | choices[i].message.reasoning_content | choices[i].message.encrypted_content |
| Responses | reasoning.summary="auto" | summary[].text | encrypted_content |
| Anthropic Messages | thinking.display="summarized" | thinking | signature |
| DashScope | parameters.thinking_display="summarized" | output.choices[i].message.reasoning_content | output.choices[i].message.encrypted_content |
Chat Completions
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"messages": [
{
"role": "user",
"content": "Calcula 17×23."
}
],
"enable_thinking": true,
"thinking_display": "summarized",
"preserve_thinking": true
}'
Responses
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"input": "Calcula 17×23.",
"reasoning": {
"summary": "auto"
}
}'
Anthropic Messages
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
-H "x-api-key: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"max_tokens": 2048,
"thinking": {
"type": "enabled",
"budget_tokens": 1024,
"display": "summarized"
},
"messages": [
{
"role": "user",
"content": "Calcula 17×23."
}
]
}'
DashScope
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"text": "Calcula 17×23."
}
]
}
]
},
"parameters": {
"result_format": "message",
"incremental_output": false,
"enable_thinking": true,
"thinking_display": "summarized",
"preserve_thinking": true
}
}'
Respuestas y streaming
Chat Completions transmite incrementos del resumen en choices[i].delta.reasoning_content, después un evento completo y separado de encrypted_content, texto o llamadas a herramientas y la finalización. Sin streaming, los campos están en choices[i].message. No descarte el evento cifrado porque su texto esté vacío ni cree un mensaje assistant separado para él.
Un elemento reasoning de Responses contiene summary (elementos summary_text) y encrypted_content. El resumen llega de forma incremental; el contenido cifrado llega en el evento de finalización del elemento y en la response final. Use la instantánea final para recuperar el cifrado sin agregar el resumen dos veces.
Un bloque thinking de Anthropic Messages contiene el resumen thinking y la signature cifrada. El streaming devuelve primero thinking_delta y después signature_delta completo; el texto o las herramientas llegan tras cerrar el bloque. La signature puede estar vacía si falla el cifrado o no hay razonamiento.
Los campos de DashScope están en output.choices[i].message, en el mismo orden que Chat Completions. Coloque el contenido cifrado en encrypted_content, no en content[].text. El finish_reason intermedio es la cadena "null" y el final es "stop". usage es acumulativo; no lo sume repetidamente.
Conversaciones de varios turnos
Conserve el contenido cifrado completo al reenviar el historial. Puede omitir el resumen; el arreglo summary de Responses puede estar vacío.
Chat Completions
Envíe los parámetros no estándar del SDK de Python de OpenAI enable_thinking, thinking_display y preserve_thinking mediante extra_body.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
questions = [
"Calcula 17×23.",
"Ahora suma 9."
]
history = []
for turn, question in enumerate(questions, start=1):
history.append({"role": "user", "content": question})
response = client.chat.completions.create(
model="qwen4-max",
messages=history,
max_tokens=8192,
stream=False,
extra_body={
"enable_thinking": True,
"thinking_display": "summarized",
"preserve_thinking": True,
},
)
assistant_message = response.choices[0].message.model_dump(exclude_none=True)
history.append(assistant_message)
print(f"Turn {turn}")
print("Summary:", assistant_message.get("reasoning_content", ""))
print("Answer:", assistant_message["content"])
const questions = [
"Calcula 17×23.",
"Ahora suma 9."
];
const history = [];
const endpoint = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
for (const [index, question] of questions.entries()) {
history.push({ role: "user", content: question });
const httpResponse = await fetch(endpoint, {
method: "POST",
headers: { "Authorization": `Bearer ${process.env.DASHSCOPE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ model: "qwen4-max", messages: history, max_tokens: 8192, stream: false, enable_thinking: true, thinking_display: "summarized", preserve_thinking: true }),
});
if (!httpResponse.ok) throw new Error(await httpResponse.text());
const response = await httpResponse.json();
const assistantMessage = response.choices[0].message;
history.push(assistantMessage);
console.log(`Turn ${index + 1}`);
console.log("Summary:", assistantMessage.reasoning_content ?? "");
console.log("Answer:", assistantMessage.content);
}
set -euo pipefail
history='[]'
questions=(
'Calcula 17×23.'
'Ahora suma 9.'
)
for question in "${questions[@]}"; do
history=$(jq --arg question "$question" '. + [{role: "user", content: $question}]' <<< "$history")
request=$(jq -n --argjson history "$history" '{model: "qwen4-max", messages: $history, max_tokens: 8192, stream: false, enable_thinking: true, thinking_display: "summarized", preserve_thinking: true}')
response=$(curl --fail-with-body -sS "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
--data "$request")
history=$(jq -n --argjson history "$history" --argjson response "$response" \
'$history + [$response.choices[0].message]')
printf '%s\n' "$response" | jq '.choices[0].message | {summary: .reasoning_content, answer: .content}'
done
Responses
Configure reasoning.summary="auto" para activar el resumen y el cifrado. Este ejemplo usa store=false y guarda el historial en el cliente.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
questions = [
"Calcula 17×23.",
"Ahora suma 9."
]
history = []
for turn, question in enumerate(questions, start=1):
history.append({"role": "user", "content": question})
response = client.responses.create(
model="qwen4-max",
input=history,
reasoning={"effort": "medium", "summary": "auto"},
max_output_tokens=8192,
store=False,
stream=False,
)
output_items = [item.model_dump(exclude_none=True) for item in response.output]
history.extend(output_items)
print(f"Turn {turn}")
for item in output_items:
if item["type"] == "reasoning":
print("Summary:", "".join(part["text"] for part in (item.get("summary") or [])))
print("Answer:", response.output_text)
const questions = [
"Calcula 17×23.",
"Ahora suma 9."
];
const history = [];
const endpoint = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses";
for (const [index, question] of questions.entries()) {
history.push({ role: "user", content: question });
const httpResponse = await fetch(endpoint, {
method: "POST",
headers: { "Authorization": `Bearer ${process.env.DASHSCOPE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ model: "qwen4-max", input: history, reasoning: { effort: "medium", summary: "auto" }, max_output_tokens: 8192, store: false, stream: false }),
});
if (!httpResponse.ok) throw new Error(await httpResponse.text());
const response = await httpResponse.json();
history.push(...response.output);
console.log(`Turn ${index + 1}`);
for (const item of response.output) {
if (item.type === "reasoning") console.log("Summary:", (item.summary ?? []).map(part => part.text).join(""));
if (item.type === "message") console.log("Answer:", item.content.filter(part => part.type === "output_text").map(part => part.text).join(""));
}
}
set -euo pipefail
history='[]'
questions=(
'Calcula 17×23.'
'Ahora suma 9.'
)
for question in "${questions[@]}"; do
history=$(jq --arg question "$question" '. + [{role: "user", content: $question}]' <<< "$history")
request=$(jq -n --argjson history "$history" '{model: "qwen4-max", input: $history, reasoning: {effort: "medium", summary: "auto"}, max_output_tokens: 8192, store: false, stream: false}')
response=$(curl --fail-with-body -sS "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
--data "$request")
history=$(jq -n --argjson history "$history" --argjson response "$response" \
'$history + $response.output')
printf '%s\n' "$response" | jq '{summary: [.output[] | select(.type == "reasoning") | .summary[].text], answer: [.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text]}'
done
Anthropic Messages
import os
import anthropic
client = anthropic.Anthropic(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)
questions = [
"Calcula 17×23.",
"Ahora suma 9."
]
history = []
for turn, question in enumerate(questions, start=1):
history.append({"role": "user", "content": question})
response = client.messages.create(
model="qwen4-max",
messages=history,
max_tokens=8192,
thinking={"type": "enabled", "budget_tokens": 4096, "display": "summarized"},
stream=False,
)
content_blocks = [block.model_dump(exclude_none=True) for block in response.content]
history.append({"role": "assistant", "content": content_blocks})
print(f"Turn {turn}")
for block in content_blocks:
if block["type"] == "thinking":
print("Summary:", block["thinking"])
elif block["type"] == "text":
print("Answer:", block["text"])
const questions = [
"Calcula 17×23.",
"Ahora suma 9."
];
const history = [];
const endpoint = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages";
for (const [index, question] of questions.entries()) {
history.push({ role: "user", content: question });
const httpResponse = await fetch(endpoint, {
method: "POST",
headers: { "x-api-key": process.env.DASHSCOPE_API_KEY, "anthropic-version": "2023-06-01", "Content-Type": "application/json" },
body: JSON.stringify({ model: "qwen4-max", messages: history, max_tokens: 8192, thinking: { type: "enabled", budget_tokens: 4096, display: "summarized" }, stream: false }),
});
if (!httpResponse.ok) throw new Error(await httpResponse.text());
const response = await httpResponse.json();
history.push({ role: "assistant", content: response.content });
console.log(`Turn ${index + 1}`);
for (const block of response.content) {
if (block.type === "thinking") console.log("Summary:", block.thinking);
if (block.type === "text") console.log("Answer:", block.text);
}
}
set -euo pipefail
history='[]'
questions=(
'Calcula 17×23.'
'Ahora suma 9.'
)
for question in "${questions[@]}"; do
history=$(jq --arg question "$question" '. + [{role: "user", content: $question}]' <<< "$history")
request=$(jq -n --argjson history "$history" '{model: "qwen4-max", messages: $history, max_tokens: 8192, thinking: {type: "enabled", budget_tokens: 4096, display: "summarized"}, stream: false}')
response=$(curl --fail-with-body -sS "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
-H "x-api-key: $DASHSCOPE_API_KEY" -H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
--data "$request")
history=$(jq -n --argjson history "$history" --argjson response "$response" \
'$history + [{role: "assistant", content: $response.content}]')
printf '%s\n' "$response" | jq '{summary: [.content[] | select(.type == "thinking") | .thinking], answer: [.content[] | select(.type == "text") | .text]}'
done
DashScope
import json
import os
from urllib.request import Request, urlopen
questions = [
"Calcula 17×23.",
"Ahora suma 9."
]
history = []
for turn, question in enumerate(questions, start=1):
history.append({"role": "user", "content": [{"text": question}]})
body = {
"model": "qwen4-max",
"input": {"messages": history},
"parameters": {
"result_format": "message",
"incremental_output": False,
"enable_thinking": True,
"thinking_display": "summarized",
"preserve_thinking": True,
"max_tokens": 8192,
},
}
request = Request(
"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",
data=json.dumps(body).encode("utf-8"),
headers={
"Authorization": "Bearer " + os.environ["DASHSCOPE_API_KEY"],
"Content-Type": "application/json",
},
method="POST",
)
with urlopen(request, timeout=120) as http_response:
response = json.load(http_response)
assistant_message = response["output"]["choices"][0]["message"]
history.append(assistant_message)
print(f"Turn {turn}")
print("Summary:", assistant_message.get("reasoning_content", ""))
print("Answer:", "".join(part.get("text", "") for part in assistant_message["content"]))
const questions = [
"Calcula 17×23.",
"Ahora suma 9."
];
const history = [];
const endpoint = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
for (const [index, question] of questions.entries()) {
history.push({ role: "user", content: [{ text: question }] });
const httpResponse = await fetch(endpoint, {
method: "POST",
headers: { "Authorization": `Bearer ${process.env.DASHSCOPE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ model: "qwen4-max", input: { messages: history }, parameters: { result_format: "message", incremental_output: false, enable_thinking: true, thinking_display: "summarized", preserve_thinking: true, max_tokens: 8192 } }),
});
if (!httpResponse.ok) throw new Error(await httpResponse.text());
const response = await httpResponse.json();
const assistantMessage = response.output.choices[0].message;
history.push(assistantMessage);
console.log(`Turn ${index + 1}`);
console.log("Summary:", assistantMessage.reasoning_content ?? "");
console.log("Answer:", assistantMessage.content.map(part => part.text ?? "").join(""));
}
set -euo pipefail
history='[]'
questions=(
'Calcula 17×23.'
'Ahora suma 9.'
)
for question in "${questions[@]}"; do
history=$(jq --arg question "$question" '. + [{role: "user", content: [{text: $question}]}]' <<< "$history")
request=$(jq -n --argjson history "$history" '{model: "qwen4-max", input: {messages: $history}, parameters: {result_format: "message", incremental_output: false, enable_thinking: true, thinking_display: "summarized", preserve_thinking: true, max_tokens: 8192}}')
response=$(curl --fail-with-body -sS "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
--data "$request")
history=$(jq -n --argjson history "$history" --argjson response "$response" \
'$history + [$response.output.choices[0].message]')
printf '%s\n' "$response" | jq '.output.choices[0].message | {summary: .reasoning_content, answer: [.content[].text]}'
done
Facturación
Esta función no tiene cargos adicionales. Se aplican las reglas existentes de facturación de tokens de entrada y salida del modelo.