QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Cache de contexto

Corte o custo com o prefixo reutilizado.

O cache de contexto armazena o prefixo comum de pedidos sobrepostos para evitar computação redundante. Isso melhora a velocidade de resposta e reduz os custos sem afetar a qualidade da resposta.

O cache de contexto fornece três modos para atender cenários diferentes. Escolha com base em seus requisitos para conveniência, certeza e custo:

Item Cache explícito Cache implícito Cache de sessão
Impacto na qualidade da resposta Sem impacto. Sem impacto. Sem impacto.
Cobrança de fichas usadas para criar o cache Normalmente, 125% do preço padrão do token 100% do preço padrão do token de entrada. Normalmente, 125% do preço padrão do token
Cobrando fichas de entrada em cache que são atingidas. Normalmente 10% do preço padrão do token de entrada (verContagem) Normalmente 20% do preço padrão do token de entrada (verContagem) Normalmente 10% do preço padrão do token de entrada (verContagem)
Mínimas fichas para caching 1024 1024 1024
Período de validade do cache 5 minutos (retomando o sucesso) Indeterminado. O sistema periodicamente limpa dados antigos e não utilizados. 5 minutos (retomando o sucesso)

Embora a contagem mínima de fichas seja a mesma para ambos os modos, o significado difere: cache explícito é criado e gerenciado ativamente pelo usuário; cache implícito é criado automaticamente e gerenciado pelo sistema. Alcançar 1.024 fichas só significa que o pedido atende às condições técnicas para um sucesso no cache, mas não garante um sucesso real.

Cache explícito

Comparado com o cache implícito, o cache explícito requer criação explícita e incorre em cima, mas oferece uma taxa de acesso mais alta e menor latência de acesso.

Modelos apoiados.

Categoria Modelos
Qwen Max. qwen3.8-max,qwen3.8-max-0902,qwen3.7-max,qwen3.7-max-2026-06-08,qwen3.7-max-2026-05-20
Qwen Mais. qwen3.7-plus,qwen3.7-plus-2026-05-26,qwen3.6-plus,qwen3.5-plus,qwen3.5-plus-2026-04-20,qwen-plus
Qwen Flash qwen3.8-flash,qwen3.7-flash,qwen3.7-flash-2026-07-15,qwen3.6-flash,qwen3.5-flash,qwen-flash
Qwen Code aberto. qwen3.8-2.4t-a95b,qwen3.8-27b
Qwen Codificador qwen3-coder-flash
Qwen VL qwen3-vl-plus

Uso

Adicione o "cache_control": {"type": "ephemeral"} - Marcador no... messages Array. O sistema então procura para trás de cada um. cache_control Marca e examina até 20 precedentes. content Blocos para encontrar um esconderijo contra blocos existentes.

Um único pedido suporta no máximo quatro marcadores de cache.

Exemplo:

Envie o primeiro pedido.

 Envie uma mensagem do sistema que contenha texto A com mais de 1024 fichas e adicione um marcador de cache.

```json
[{"role": "system", "content": [{"type": "text", "text": "A", "cache_control": {"type": "ephemeral"}}]}]
```

O sistema cria o primeiro bloco de cache, que é chamado de bloco de cache A.

Envie o segundo pedido.

 Envie um pedido com a seguinte estrutura:

```json
[
  {"role": "system", "content": "A"},
  // <Other messages>
  {"role": "user","content": [{"type": "text", "text": "B", "cache_control": {"type": "ephemeral"}}]}
]
```

- Se "outras mensagens" não contém mais de 20 mensagens, o bloco A é atingido, e seu período de validade é reposto para 5 minutos. O sistema também cria um novo bloco de cache baseado em A, as outras mensagens, e B.
- Se "outras mensagens" contém mais de 20 mensagens, o bloco A não é atingido. O sistema cria um novo bloco de cache baseado no contexto completo (A + outras mensagens + B).

Começando.

Os exemplos a seguir mostram como blocos de cache são criados e atingidos.

from openai import OpenAI
import os

client = OpenAI(
  # If the environment variable is not set, replace the following line with: api_key="sk-xxx"
  api_key=os.getenv("DASHSCOPE_API_KEY"),
  base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
)

# Mock code repository content. The minimum cacheable prompt length is 1024 tokens.
long_text_content = "<Your Code Here>" * 400

# Function to send the request
def get_completion(user_input):
  messages = [
    {
      "role": "system",
      "content": [
        {
          "type": "text",
          "text": long_text_content,
          # Place the cache_control marker here to create a cache block containing all content from the beginning of the messages array to this content block.
          "cache_control": {"type": "ephemeral"},
        }
      ],
    },
    # The question content is different for each request.
    {
      "role": "user",
      "content": user_input,
    },
  ]
  completion = client.chat.completions.create(
    # Select a model that supports explicit cache.
    model="qwen3.7-max",
    messages=messages,
  )
  return completion

# First request
first_completion = get_completion("What is the content of this code?")
print(f"First request cache creation tokens: {first_completion.usage.prompt_tokens_details.cache_creation_input_tokens}")
print(f"First request cached hit tokens: {first_completion.usage.prompt_tokens_details.cached_tokens}")
print("=" * 20)
# Second request, the code content is the same, only the question is changed.
second_completion = get_completion("How can this code be optimized?")
print(f"Second request cache creation tokens: {second_completion.usage.prompt_tokens_details.cache_creation_input_tokens}")
print(f"Second request cached hit tokens: {second_completion.usage.prompt_tokens_details.cached_tokens}")
import os
import dashscope
from dashscope import Generation
dashscope.base_http_api_url = "https://maas.qwencloudapi.com/api/v1"

# Mock code repository content. The minimum cacheable prompt length is 1024 tokens.
long_text_content = "<Your Code Here>" * 400

# Function to send the request
def get_completion(user_input):
  messages = [
    {
      "role": "system",
      "content": [
        {
          "type": "text",
          "text": long_text_content,
          # Place the cache_control marker here to create a cache block containing all content from the beginning of the messages array to this content block.
          "cache_control": {"type": "ephemeral"},
        }
      ],
    },
    # The question content is different for each request.
    {
      "role": "user",
      "content": user_input,
    },
  ]
  response = Generation.call(
    # If the environment variable is not set, replace the following line with your API key: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.7-max",
    messages=messages,
    result_format="message"
  )
  return response

# First request
first_completion = get_completion("What is the content of this code?")
print(f"First request cache creation tokens: {first_completion.usage.prompt_tokens_details['cache_creation_input_tokens']}")
print(f"First request cached hit tokens: {first_completion.usage.prompt_tokens_details['cached_tokens']}")
print("=" * 20)
# Second request, the code content is the same, only the question is changed.
second_completion = get_completion("How can this code be optimized?")
print(f"Second request cache creation tokens: {second_completion.usage.prompt_tokens_details['cache_creation_input_tokens']}")
print(f"Second request cached hit tokens: {second_completion.usage.prompt_tokens_details['cached_tokens']}")
// The minimum Java SDK version is 2.21.6
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.MessageContentText;
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 java.util.Arrays;
import java.util.Collections;

public class Main {
  private static final String MODEL = "qwen3.7-max";
  // Mock code repository content (repeated 400 times to ensure it exceeds 1024 tokens)
  private static final String LONG_TEXT_CONTENT = generateLongText(400);
  private static String generateLongText(int repeatCount) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < repeatCount; i++) {
      sb.append("<Your Code Here>");
    }
    return sb.toString();
  }
  private static GenerationResult getCompletion(String userQuestion)
      throws NoApiKeyException, ApiException, InputRequiredException {
    Generation gen = new Generation("http", "https://maas.qwencloudapi.com/api/v1");

    // Build the system message with cache control
    MessageContentText systemContent = MessageContentText.builder()
        .type("text")
        .text(LONG_TEXT_CONTENT)
        .cacheControl(MessageContentText.CacheControl.builder()
            .type("ephemeral") // Set the cache type
            .build())
        .build();

    Message systemMsg = Message.builder()
        .role(Role.SYSTEM.getValue())
        .contents(Collections.singletonList(systemContent))
        .build();
    Message userMsg = Message.builder()
        .role(Role.USER.getValue())
        .content(userQuestion)
        .build();

    // Build the request parameters
    GenerationParam param = GenerationParam.builder()
        .model(MODEL)
        .messages(Arrays.asList(systemMsg, userMsg))
        .resultFormat(GenerationParam.ResultFormat.MESSAGE)
        .build();
    return gen.call(param);
  }

  private static void printCacheInfo(GenerationResult result, String requestLabel) {
    System.out.printf("%s cache creation tokens: %d%n", requestLabel, result.getUsage().getPromptTokensDetails().getCacheCreationInputTokens());
    System.out.printf("%s cached hit tokens: %d%n", requestLabel, result.getUsage().getPromptTokensDetails().getCachedTokens());
  }

  public static void main(String[] args) {
    try {
      // First request
      GenerationResult firstResult = getCompletion("What is the content of this code?");
      printCacheInfo(firstResult, "First request");
      System.out.println(new String(new char[20]).replace('\0', '='));
      // Second request
      GenerationResult secondResult = getCompletion("How can this code be optimized?");
      printCacheInfo(secondResult, "Second request");
    } catch (NoApiKeyException | ApiException | InputRequiredException e) {
      System.err.println("API call failed: " + e.getMessage());
      e.printStackTrace();
    }
  }
}
import anthropic
import os

api_key = os.getenv("DASHSCOPE_API_KEY")
client = anthropic.Anthropic(
  # If the environment variable is not set, replace the following line with: api_key="sk-xxx"
  api_key=api_key,
  base_url="https://maas.qwencloudapi.com/apps/anthropic",
  default_headers={"Authorization": f"Bearer {api_key}"},
)

# Mock code repository content. The minimum cacheable prompt length is 1024 tokens.
long_text_content = "<Your Code Here>" * 400

# Function to send the request
def get_completion(user_input):
  response = client.messages.create(
    # Select a model that supports explicit cache.
    model="qwen3.7-max",
    max_tokens=1024,
    system=[
      {
        "type": "text",
        "text": long_text_content,
        # Place the cache_control marker here to create a cache block containing the system text content.
        "cache_control": {"type": "ephemeral"},
      }
    ],
    messages=[
      # The question content is different for each request.
      {"role": "user", "content": user_input},
    ],
  )
  return response

# First request
first_completion = get_completion("What is the content of this code?")
print(f"First request cache creation tokens: {first_completion.usage.cache_creation_input_tokens}")
print(f"First request cached hit tokens: {first_completion.usage.cache_read_input_tokens}")
print("=" * 20)
# Second request, the code content is the same, only the question is changed.
second_completion = get_completion("How can this code be optimized?")
print(f"Second request cache creation tokens: {second_completion.usage.cache_creation_input_tokens}")
print(f"Second request cached hit tokens: {second_completion.usage.cache_read_input_tokens}")

Pedidos posteriores sobre o mesmo repositório de códigos reutilizam este bloco de cache, resultando em respostas mais rápidas e custos menores.

First request cache creation tokens: 1605
First request cached hit tokens: 0
====================
Second request cache creation tokens: 0
Second request cached hit tokens: 1605

Use vários marcadores de cache para controle de grãos finos.

Em cenários complexos, um prompt consiste em várias partes com diferentes frequências de reutilização. Você pode usar vários marcadores de cache para obter controle de grãos finos.

Por exemplo, o pedido para um agente inteligente de atendimento ao cliente normalmente inclui:

Se você armazenar todo o prompt como uma única unidade, qualquer pequena mudança, como uma mudança no conhecimento externo, invalida o cache.

Você pode configurar até quatro marcadores de cache em um pedido para criar blocos de cache separados para diferentes partes do prompt. Isso melhora a taxa de sucesso e fornece controle de grãos finos.

Contagem

O cache explícito afeta apenas o preço dos fichas de entrada. As regras são as seguintes:

Conteúdo cacheável

Apenas os seguintes tipos de mensagens no messages Suporte de array adicionando marcadores de cache:

Por exemplo, para uma mensagem do sistema, mude o content campo para um array e adicionar o cache_control Campo:

{
  "role": "system",
  "content": [
    {
      "type": "text",
      "text": "<Your specified prompt>",
      "cache_control": {
        "type": "ephemeral"
      }
    }
  ]
}

Esta estrutura também se aplica a outros tipos de mensagens no messages Array.

Limitações de cache

Otimize a estrutura de mensagens para chamadas paralelas de ferramentas.

Quando você usa chamadas de ferramentas paralelas, o modelo retorna várias tool_calls em uma única resposta. Se você enviar cada resultado de ferramenta como um separado tool mensagem, o número de blocos de conteúdo no messages O conjunto cresce rapidamente. Quando mais de 20 blocos de conteúdo separam o cache_control Marcador de conteúdo anterior, a janela de retrovisor não pode alcançar os blocos anteriores, causando uma falha no cache.

Para resolver isso, misture mensagens consecutivas de ferramentas do mesmo papel em uma única tool Mensagem com vários blocos de conteúdo antes de enviar o próximo pedido. Isso reduz a contagem total de blocos de conteúdo e mantém o conteúdo que você want para guardar dentro da janela de 20 quarteirões.

Antes da otimização (mensagens de ferramentas separadas - menor taxa de cache)

# After the model returns parallel tool_calls, send each result as a separate message
messages.append(assistant_message)  # assistant message containing parallel tool_calls
# Each tool result is its own message — increases content block count by N
messages.append({"role": "tool", "tool_call_id": "call_1", "content": "result_1"})
messages.append({"role": "tool", "tool_call_id": "call_2", "content": "result_2"})

Após otimização (mensagem de ferramenta fundida - taxa de cache mais alta)

# After the model returns parallel tool_calls, merge all results into one message
messages.append(assistant_message)  # assistant message containing parallel tool_calls
# Merge all tool results into a single message with multiple content blocks
messages.append({
  "role": "tool",
  "tool_call_id": "call_1",
  "content": [
    {"type": "text", "text": "result_1"},
    {"type": "text", "text": "result_2", "tool_call_id": "call_2"},
  ],
})

Para melhorar ainda mais a taxa de cache atingido, coloque cache_control Marcadores em posições estáveis na messages Array (por exemplo, na mensagem do sistema ou em outros conteúdos pouco frequentes). Um único pedido suporta até quatro marcadores de cache.

Exemplos de uso

Different questions for a long text

from openai import OpenAI
import os

client = OpenAI(
  api_key=os.getenv("DASHSCOPE_API_KEY"),
  base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
)

# Mock code repository content
long_text_content = "<Your Code Here>" * 400

# Function to send the request
def get_completion(user_input):
  messages = [
    {
      "role": "system",
      "content": [
        {
          "type": "text",
          "text": long_text_content,
          # Place the cache_control marker here to create a cache from the beginning of the prompt to the end of this content block (the mock code repository content).
          "cache_control": {"type": "ephemeral"},
        }
      ],
    },
    {
      "role": "user",
      "content": user_input,
    },
  ]
  completion = client.chat.completions.create(
    # Select a model that supports explicit cache
    model="qwen3.7-max",
    messages=messages,
  )
  return completion

# First request
first_completion = get_completion("What is the content of this code?")
created_cache_tokens = first_completion.usage.prompt_tokens_details.cache_creation_input_tokens
print(f"First request cache creation tokens: {created_cache_tokens}")
hit_cached_tokens = first_completion.usage.prompt_tokens_details.cached_tokens
print(f"First request cached hit tokens: {hit_cached_tokens}")
print(f"First request tokens not hit and not cached: {first_completion.usage.prompt_tokens-created_cache_tokens-hit_cached_tokens}")
print("=" * 20)
# Second request, the code content is the same, only the question is changed.
second_completion = get_completion("What are some areas for optimization in this code?")
created_cache_tokens = second_completion.usage.prompt_tokens_details.cache_creation_input_tokens
print(f"Second request cache creation tokens: {created_cache_tokens}")
hit_cached_tokens = second_completion.usage.prompt_tokens_details.cached_tokens
print(f"Second request cached hit tokens: {hit_cached_tokens}")
print(f"Second request tokens not hit and not cached: {second_completion.usage.prompt_tokens-created_cache_tokens-hit_cached_tokens}")

Este exemplo armazena o conteúdo do repositório de código como um prefixo. Pedidos posteriores fazem perguntas diferentes sobre o repositório.

First request cache creation tokens: 1605
First request cached hit tokens: 0
First request tokens not hit and not cached: 13
====================
Second request cache creation tokens: 0
Second request cached hit tokens: 1605
Second request tokens not hit and not cached: 15
Para garantir o desempenho do modelo, o sistema adiciona um pequeno número de fichas internas.  Esses símbolos são cobrados pelo preço padrão. Para mais informações, veja o [FAQ] (#faq).

Continuous multi-turn conversation

Em um bate-papo diário, você pode adicionar um marcador de cache ao último conteúdo do array de mensagens em cada pedido. A partir da segunda volta da conversa, cada pedido vai bater e atualizar o bloco de cache criado na volta anterior, e também vai criar um novo bloco de cache.

from openai import OpenAI
import os

client = OpenAI(
  api_key=os.getenv("DASHSCOPE_API_KEY"),
  base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
)

system_prompt = "You are a witty person." * 400
messages = [{"role": "system", "content": system_prompt}]

def get_completion(messages):
  completion = client.chat.completions.create(
    model="qwen3.7-max",
    messages=messages,
  )
  return completion

while True:
  user_input = input("Please enter: ")
  messages.append({"role": "user", "content": [{"type": "text", "text": user_input, "cache_control": {"type": "ephemeral"}}]})
  completion = get_completion(messages)
  print(f"[AI Response] {completion.choices[0].message.content}")
  messages.append(completion.choices[0].message)
  created_cache_tokens = completion.usage.prompt_tokens_details.cache_creation_input_tokens
  hit_cached_tokens = completion.usage.prompt_tokens_details.cached_tokens
  uncached_tokens = completion.usage.prompt_tokens - created_cache_tokens - hit_cached_tokens
  print(f"[Cache Info] Cache creation tokens: {created_cache_tokens}")
  print(f"[Cache Info] Cached hit tokens: {hit_cached_tokens}")
  print(f"[Cache Info] Tokens not hit and not cached: {uncached_tokens}")

Passe o código acima e digite perguntas para se comunicar com o modelo. Cada pergunta vai acertar o bloco de cache criado na curva anterior.

Cache implícito

Modelos apoiados.

** Modelos de geração de texto **

Categoria Modelos
Qwen Max. qwen3.8-max,qwen3.8-max-0902,qwen3.7-max,qwen3.7-max-2026-06-08,qwen-max
Qwen Mais. qwen3.7-plus,qwen3.7-plus-2026-05-26,qwen-plus
Qwen Code aberto. qwen3.8-2.4t-a95b,qwen3.8-27b
Qwen Flash qwen3.8-flash,qwen3.7-flash,qwen3.7-flash-2026-07-15,qwen-flash
Qwen Codificador qwen3-coder-flash
Qwen Carácter qwen-plus-character,qwen-flash-character,qwen-plus-character-ja
DeepSeek deepseek-v4.1-flash,deepseek-v4-pro-0813,deepseek-v4-pro,deepseek-v4-flash-0731
GLM ZHIPU/GLM-5.3,ZHIPU/GLM-5.2,glm-5.3,glm-5.2,glm-5.2-fast-preview,glm-5.1
Kimi kimi-k3,kimi/kimi-k3,kimi-k2.7-code

** Modelos de compreensão visual**: qwen3-vl-plus

Para modelos implantados no Alibaba Cloud Model Studio que suportam cache implícito, quando um prefixo comum de pelo menos 1.024 fichas existe em todos os pedidos, o prefixo atende às condições técnicas para gravação e hit do cache implícito. Para Zhipu-delegado GLM Modelos, o mínimo é 512.

Atingir a contagem mínima de fichas não garante um cache. Se um hit ocorre também é afetado por fatores como status de geração de cache, período de validade do cache e programação do sistema. Veja a contagem de fichas na resposta da API para resultados reais.

Como funciona

Quando você envia um pedido para um modelo que suporta cache implícito, o recurso de cache implícito é automaticamente ativado. O sistema funciona da seguinte forma:

  1. Ao receber um pedido, o sistema verifica o cache para um prefixo comum do conteúdo no pedido. messages Array baseado no princípio de "prefixo".
  2. Avalie
    • Se o cache for atingido, o sistema usa diretamente o resultado do cache para a parte subsequente do processo de inferência.
    • Se o cache for perdido, o sistema processa o pedido normalmente e armazena o prefixo do prompt atual no cache para as solicitações subsequentes a serem usadas.

O sistema periodicamente limpa dados em cache que não são usados há muito tempo. A probabilidade de sucesso do Contexto Cache não é 100%.

Aumente a probabilidade de sucesso do cache.

Um cache implícito ocorre quando os prefixos de diferentes pedidos têm conteúdo duplicado. Para aumentar a probabilidade de sucesso, coloque conteúdo estático no início do conteúdo rápido e variável no final.

<a id="billing-1" />

Contagem

Não cobram taxas adicionais por permitir o modo de cache implícito.

Quando um pedido atinge o cache, os símbolos de entrada são cobrados como cached_tokens Em 20% do input_token Preço unitário. Os símbolos de entrada que não atingem o tesouro são cobrados no padrão. input_token Preço. Os cartões de saída são cobrados pelo preço padrão.

Exemplo: um pedido contém 10.000 fichas de entrada, das quais 5.000 atingiram o cache:

O custo total de entrada é de 60% do custo em um modo não-cache: (50% × 100%) + (50% × 20%) = 60%.

[Imagem.Png] (https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/4439916571/p893561.png)

Você pode recuperar o número de fichas de cache do cached_tokens atributo do resultado retornado.

[OpenAI compatível-Batch (inserção de arquivo)] (/developer-guides/text-generation/batchO método não é elegível para descontos de cache.

Cache bateu exemplos

Geração de texto

Cheque fichas de cache. usage.prompt_tokens_details.cached_tokens (parte de usage.prompt_tokens para OpenAI compatível, ou usage.input_tokens para DashScope), ou usage.cache_read_input_tokens para Antrópico compatível.

{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "I am a super-large language model developed by Alibaba Cloud. My name is Qwen."
      },
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null
    }
  ],
  "object": "chat.completion",
  "usage": {
    "prompt_tokens": 3019,
    "completion_tokens": 104,
    "total_tokens": 3123,
    "prompt_tokens_details": {
      "cached_tokens": 2048
    }
  },
  "created": 1735120033,
  "system_fingerprint": null,
  "model": "qwen-plus",
  "id": "chatcmpl-6ada9ed2-7f33-9de2-8bb0-78bd4035025a"
}
{
  "status_code": 200,
  "request_id": "f3acaa33-e248-97bb-96d5-cbeed34699e1",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "I am a large-scale language model from Alibaba Cloud. My name is Qwen. I can generate various types of text, such as articles, stories, poems, and stories, and can transform and expand them according to different scenarios and needs. In addition, I can answer various questions, provide help and solutions. If you have any questions or need help, please feel free to let me know, and I will do my best to provide support. Please note that continuously repeating the same content may not yield more detailed answers. We recommend that you provide more specific information or vary your questions so that I can better understand your needs."
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 3019,
    "output_tokens": 101,
    "prompt_tokens_details": {
      "cached_tokens": 2048
    },
    "total_tokens": 3120
  }
}
{
    "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
    "type": "message",
    "role": "assistant",
    "content": [{"type": "text", "text": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."}],
    "model": "qwen3.7-max",
    "stop_reason": "end_turn",
    "usage": {
        "input_tokens": 82,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 1536,
        "output_tokens": 14
    }
}

Compreensão visual

Cheque fichas de cache. usage.prompt_tokens_details.cached_tokens (parte de usage.prompt_tokens para OpenAI compatível), usage.cached_tokens (parte de usage.input_tokens para DashScope), ou usage.cache_read_input_tokens para Antrópico compatível.

Modelos que atualmente usam usage.cached_tokens Será atualizado para usage.prompt_tokens_details.cached_tokens no futuro.

{
  "id": "chatcmpl-3f3bf7d0-b168-9637-a245-dd0f946c700f",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "This image shows a heartwarming scene of a woman and a dog interacting on a beach. The woman is wearing a plaid shirt and sitting on the sand, smiling as she interacts with the dog. The dog is a large, light-colored breed with a colorful collar, and its front paw is raised as if to shake hands or give a high-five to the woman. The background is a vast ocean and sky, with sunlight shining from the right side of the frame, adding a warm and peaceful atmosphere to the whole scene.",
        "refusal": null,
        "role": "assistant",
        "audio": null,
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1744956927,
  "model": "qwen3-vl-plus",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 93,
    "prompt_tokens": 1316,
    "total_tokens": 1409,
    "completion_tokens_details": null,
    "prompt_tokens_details": {
      "audio_tokens": null,
      "cached_tokens": 1152
    }
  }
}
{
  "status_code": 200,
  "request_id": "06a8f3bb-d871-9db4-857d-2c6eeac819bc",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "This image shows a heartwarming scene of a woman and a dog interacting on a beach. The woman is wearing a plaid shirt and sitting on the sand, smiling as she interacts with the dog. The dog is a large breed with a colorful collar, and its front paw is raised as if to shake hands or give a high-five to the woman. The background is a vast ocean and sky, with sunlight shining from the right side of the frame, adding a warm and peaceful atmosphere to the whole scene."
            }
          ]
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 1292,
    "output_tokens": 87,
    "input_tokens_details": {
      "text_tokens": 43,
      "image_tokens": 1249
    },
    "total_tokens": 1379,
    "output_tokens_details": {
      "text_tokens": 87
    },
    "image_tokens": 1249,
    "cached_tokens": 1152
  }
}
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [{"type": "text", "text": "This image shows a heartwarming scene of a woman and a dog interacting on a beach."}],
  "model": "qwen3-vl-plus",
  "stop_reason": "end_turn",
  "usage": {
      "input_tokens": 369,
      "cache_creation_input_tokens": 0,
      "cache_read_input_tokens": 896,
      "output_tokens": 28
  }
}

Cenários típicos

  1. ** Q&A baseado em texto longo **

    Isso é aplicável a cenários que exigem múltiplos pedidos sobre um texto longo fixo, como um romance, livro didático ou documento legal.

    ** Matriz de mensagens para o primeiro pedido **

messages = [{"role": "system","content": "You are a language teacher and you can help students with reading comprehension."},
  {"role": "user","content": "<Article content> What is the author's main idea in this text?"}]

** Mensagem para pedidos subsequentes **

messages = [{"role": "system","content": "You are a language teacher and you can help students with reading comprehension."},
  {"role": "user","content": "<Article content> Please analyze the third paragraph of this text."}]

Embora as perguntas sejam diferentes, elas fazem referência ao mesmo artigo. Como o sistema de conteúdo de artigos e prompt permanecem inalterados, cada pedido compartilha um grande prefixo sobreposto, aumentando a probabilidade de um cache hit.

  1. ** Código auto-completação**

    Em cenários de auto-completação de código, o modelo completa o código baseado no contexto existente. Enquanto o usuário continua a codificar, a parte prefixa do código permanece inalterada. O cache de contexto pode armazenar o código anterior para melhorar a velocidade de conclusão.

  2. Conversa de turnos múltiplos

Em uma conversa multi-volta, o histórico de conversa de todas as voltas anteriores está incluído no conjunto de mensagens. O pedido de cada turno, portanto, compartilha o mesmo prefixo que o anterior, resultando em uma alta probabilidade de um cache hit.

? Lista de mensagens para a primeira volta da conversa ?

messages=[{"role": "system","content": "You are a helpful assistant."},
  {"role": "user","content": "Who are you?"}]

? Lista de mensagens para a segunda volta da conversa ?

messages=[{"role": "system","content": "You are a helpful assistant."},
  {"role": "user","content": "Who are you?"},
  {"role": "assistant","content": "I am Qwen, developed by Alibaba Cloud."},
  {"role": "user","content": "What can you do?"}]

À medida que o número de conversas aumenta, os benefícios do caching -- inferência mais rápida e menor custo -- tornam-se mais pronunciados.

  1. Role jogando ou aprendendo pouco

    Em cenários de interpretação de papéis ou de aprendizagem, você normalmente inclui uma grande quantidade de informações no prompt para guiar o formato de saída do modelo. Isso cria um grande prefixo compartilhado em diferentes pedidos.

    Por exemplo, se você want O modelo para atuar como especialista em marketing, o sistema de alerta contém uma grande quantidade de informações de texto. A seguir, são exemplos de mensagens para dois pedidos:

system_prompt = """You are an experienced marketing expert. Please provide detailed marketing suggestions for different products in the following format:

1. Target audience: xxx

2. Main selling points: xxx

3. Marketing channels: xxx
...
12. Long-term development strategy: xxx

Please ensure that your suggestions are specific, actionable, and highly relevant to the product features."""

# User message for the first request, asking about a smartwatch
messages_1=[
  {"role": "system", "content": system_prompt},
  {"role": "user", "content": "Please provide marketing suggestions for a newly launched smartwatch."}
]

# User message for the second request, asking about a laptop. Because the system_prompt is the same, there is a high probability of hitting the Cache.
messages_2=[
  {"role": "system", "content": system_prompt},
  {"role": "user", "content": "Please provide marketing suggestions for a newly launched laptop."}
]

Com o cache de contexto, o sistema pode responder rapidamente quando ocorre um hit de cache, mesmo que o usuário frequentemente mude o tipo de produto que está perguntando, como de um smartwatch para um laptop.

  1. #Encomenda de vídeo#

    Em cenários de entendimento de vídeo, se você fizer várias perguntas sobre o mesmo vídeo, colocando o video Antes de text aumenta a probabilidade de um cache. Se você fizer a mesma pergunta sobre diferentes vídeos, colocando o text Antes de video aumenta a probabilidade de um cache. O seguinte é um exemplo de mensagem para dois pedidos para o mesmo vídeo:

# User message for the first request, asking about the content of this video
messages1 = [
  {"role":"system","content":[{"text": "You are a helpful assistant."}]},
  {"role": "user",
    "content": [
      {"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250328/eepdcq/phase_change_480p.mov"},
      {"text": "What is the content of this video?"}
    ]
  }
]

# User message for the second request, asking about the video timestamp. Because the question is based on the same video, placing the video before the text has a high probability of hitting the Cache.
messages2 = [
  {"role":"system","content":[{"text": "You are a helpful assistant."}]},
  {"role": "user",
    "content": [
      {"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250328/eepdcq/phase_change_480p.mov"},
      {"text": "Please describe the series of events in the video, and output the start time (start_time), end time (end_time), and event (event) in JSON format. Do not output the ```Json.``` code segment."}
    ]
  }
]

Cache de sessão

Em cenários de conversação multi-turnos, habilitar o cache de sessão permite que o servidor cache automaticamente o contexto de conversação, reduzindo a latência de inferência e os custos de uso. Não precisa fazer caching manualmente, só fazer ligações como faria para uma conversa normal de várias voltas.

Uso

Adicione o seguinte campo ao cabeçalho da solicitação para controlar o cache da sessão:

Comportamento de cache.

Exemplos de código

import os
from openai import OpenAI

client = OpenAI(
  api_key=os.getenv("DASHSCOPE_API_KEY"),
  base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
  # Enable session cache via default_headers
  default_headers={"x-dashscope-session-cache": "enable"}
)

# Construct a long text exceeding 1024 tokens to ensure cache creation is triggered.
# (If it does not reach 1024 tokens, cache creation will be triggered when the accumulated conversation context exceeds 1024 tokens.)
long_context = "Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence." * 50

# First turn of conversation
response1 = client.responses.create(
  model="qwen3.7-plus",
  input=long_context + "\n\nBased on the background knowledge above, please briefly introduce the random forest algorithm in machine learning.",
)
print(f"First turn response: {response1.output_text}")

# Second turn of conversation: Associate the context via previous_response_id. The cache is handled automatically by the server-side.
response2 = client.responses.create(
  model="qwen3.7-plus",
  input="What are the main differences between it and GBDT?",
  extra_body={"previous_response_id": response1.id}
)
print(f"Second turn response: {response2.output_text}")

# Check the cache hit status
usage = response2.usage
print(f"Input tokens: {usage.input_tokens}")
print(f"Cached hit tokens: {usage.prompt_tokens_details.cached_tokens}")
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.DASHSCOPE_API_KEY,
  baseURL: "https://maas.qwencloudapi.com/compatible-mode/v1",
  // Enable session cache via defaultHeaders
  defaultHeaders: {"x-dashscope-session-cache": "enable"}
});

// Construct a long text exceeding 1024 tokens to ensure cache creation is triggered.
// (If it does not reach 1024 tokens, cache creation will be triggered when the accumulated conversation context exceeds 1024 tokens.)
const longContext = "Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence.".repeat(50);

async function main() {
  // First turn of conversation
  const response1 = await openai.responses.create({
    model: "qwen3.7-plus",
    input: longContext + "\n\nBased on the background knowledge above, please briefly introduce the random forest algorithm in machine learning, including its basic principles and application scenarios."
  });
  console.log(`First turn response: ${response1.output_text}`);

  // Second turn of conversation: Associate the context via previous_response_id. The cache is handled automatically by the server-side.
  const response2 = await openai.responses.create({
    model: "qwen3.7-plus",
    input: "What are the main differences between it and GBDT?",
    extra_body: { previous_response_id: response1.id }
  });
  console.log(`Second turn response: ${response2.output_text}`);

  // Check the cache hit status
  console.log(`Input tokens: ${response2.usage.input_tokens}`);
  console.log(`Cached hit tokens: ${response2.usage.prompt_tokens_details.cached_tokens}`);
}

main();
# First turn of conversation
# Please replace the input with a long text exceeding 1024 tokens to ensure cache creation is triggered.
curl -X POST https://maas.qwencloudapi.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "x-dashscope-session-cache: enable" \
-d '{
  "model": "qwen3.7-plus",
  "input": "Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence. Artificial intelligence is an important branch of computer science, dedicated to the research and development of theories, methods, technologies, and application systems that can simulate, extend, and expand human intelligence.\n\nBased on the background knowledge above, please briefly introduce the random forest algorithm in machine learning, including its basic principles and application scenarios."
}'

# Second turn of conversation - Use the id returned from the previous turn as previous_response_id
curl -X POST https://maas.qwencloudapi.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "x-dashscope-session-cache: enable" \
-d '{
  "model": "qwen3.7-plus",
  "input": "What are the main differences between it and GBDT?",
  "previous_response_id": "response_id_from_the_first_turn"
}'

O cached_tokens O campo mostra o número de fichas de cache:

{
  "id": "145584fd-3dce-4890-99dc-e3896d7f5a42",
  "created_at": 1772440976.0,
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "metadata": null,
  "model": "qwen3.7-plus",
  "object": "response",
  "output": [
    {
      "id": "msg_62a4e323-d78c-46c7-8469-2ad50f8af4b1",
      "type": "reasoning",
      "content": null
    },
    {
      "id": "msg_560e34a6-1bdf-42ae-993e-590b38249146",
      "content": [
        {
          "annotations": [],
          "text": "Although both Random Forest and GBDT (Gradient Boosting Decision Tree) are ensemble algorithms based on decision trees, they have the following main differences:\n\n1.  **Different Ensemble Strategies**\n    *   **Random Forest**: Based on the **Bagging** idea. Each tree is trained independently, with no dependency between them.\n    *   **GBDT**: Based on the **Boosting** idea. The trees have a strong dependency relationship, where the next tree aims to fit the residuals (negative gradient) of the previous tree's prediction.\n\n2.  **Different Training Methods**\n    *   **Random Forest**: Supports **parallel training** because the trees are independent, which usually results in higher computational efficiency.\n    *   **GBDT**: Must be **trained serially** because the next tree depends on the output of the previous one, making it inherently difficult to parallelize (although engineering implementations like XGBoost have made parallel optimizations at the feature level).\n\n3.  **Different Optimization Objectives**\n    *   **Random Forest**: Mainly reduces **variance** by averaging multiple models to prevent overfitting and improve stability.\n    *   **GBDT**: Mainly reduces **bias** by progressively correcting errors to improve the model's fitting ability and accuracy.\n\n4.  **Sensitivity to Outliers**\n    *   **Random Forest**: Relatively robust and not sensitive to outliers.\n    *   **GBDT**: More sensitive to outliers because outliers produce large residuals, which affect the fitting direction of subsequent trees.\n\nIn summary, Random Forest excels in stability and parallel efficiency, while GBDT usually performs better in terms of accuracy but is more complex to tune and slower to train.",
          "type": "output_text"
        }
      ],
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "parallel_tool_calls": false,
  "temperature": null,
  "tool_choice": "auto",
  "tools": [],
  "top_p": null,
  "status": "completed",
  "usage": {
    "input_tokens": 1524,
    "input_tokens_details": {
      "cached_tokens": 1305
    },
    "output_tokens": 1534,
    "output_tokens_details": {
      "reasoning_tokens": 1187
    },
    "total_tokens": 3058
  }
}

O input_tokens Para a segunda volta da conversa é 1524, dos quais o cached_tokens é 1305. Isso indica que o contexto da primeira volta foi um golpe de cache, que pode efetivamente reduzir a latência e o custo da inferência.

Contagem

A cobrança do cache de sessão depende do tipo de cache usado:

Limitações

FAQ

Quanto tempo o cache de contexto é mantido (período de validade)?

O período de validade do cache de contexto depende do tipo de cache:

Como desativo o cache implícito?

Você não pode desativá-lo. O cache implícito é automaticamente ativado para todos os modelos suportados porque não afeta a qualidade da resposta e reduz os custos, enquanto melhora a velocidade de resposta quando o cache é atingido.

Por que o cache explícito não foi atingido depois que eu o criei?

Há várias razões possíveis:

Bater no cache explícito repõe sua validade?

Sim. Cada batida repõe o período de validade do bloco de cache para 5 minutos.

O cache explícito é compartilhado entre diferentes contas?

Não. Os dados de cache implícitos e explícitos são isolados no nível da conta e não são compartilhados entre as contas.

O cache explícito é compartilhado entre diferentes modelos?

Não. Os dados de cache são isolados entre modelos e não são compartilhados.

Por que não? input_tokens igual cache_creation_input_tokens + cached_tokens?

Para garantir a qualidade de saída do modelo, o serviço de infraestrutura adiciona um pequeno número de fichas (geralmente menos de 10) após o prompt fornecido pelo usuário. Estes símbolos são colocados após o cache_control Marcador, então não são contados para criação de cache ou hits. No entanto, eles estão incluídos no total input_tokens.