> ## Documentation Index
> Fetch the complete documentation index at: https://platform.minimaxi.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Prompt 缓存

> 通过 Prompt 缓存，可以有效降低延迟和成本。

# 功能特性

* **自动缓存**：自动识别重复的上下文内容，无需更改接口调用方式
* **降低成本**：命中缓存的输入 Token 以更低价格计费，大幅节省成本
* **提升速度**：减少重复内容的处理时间，加快模型响应

这种机制特别适用于以下场景：

* 系统提示词复用：在多轮对话中，系统提示词通常保持不变；
* 固定的工具清单：在一类任务中使用的工具往往是固定的；
* 多轮对话历史：在复杂的对话中，历史消息往往包含大量重复信息；

满足以上条件的场景，均可利用缓存机制有效节约 tokens 消耗，加快响应速度。

# 代码示例

> [tab] Anthropic SDK 示例
>
> **安装 SDK**
>
> ```bash theme={null} theme={null}
> pip install anthropic
> ```
>
> **环境变量设置**
>
> ```bash theme={null} theme={null}
> export ANTHROPIC_BASE_URL=https://api.minimax.cn/anthropic
> export ANTHROPIC_API_KEY=${YOUR_API_KEY}
> ```
>
> 配置方法见[配置环境变量](https://platform.minimaxi.com/docs/guides/quickstart-preparation.md#env-vars)。
>
> **第一次请求 - 建立缓存**
>
> ```python theme={null} theme={null}
> import anthropic
>
> client = anthropic.Anthropic()
>
> response1 = client.messages.create(
>     model="MiniMax-M3.1-Flash",
>     system="You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n",
>     messages=[
>         {
>             "role": "user", 
>             "content": [
>                 {
>                     "type": "text",
>                     "text": "<the entire contents of 'Pride and Prejudice'>"
>                 }
>             ]
>         },
>     ],
>     max_tokens=10240,
> )
>
> print("第一次请求结果:")
> for block in response1.content:
>     if block.type == "thinking":
>         print(f"思考:\n{block.thinking}\n")
>     elif block.type == "text":
>         print(f"输出:\n{block.text}\n")
> print(f"输入 Token: {response1.usage.input_tokens}")
> print(f"输出 Token: {response1.usage.output_tokens}")
> print(f"命中缓存 Token: {response1.usage.cache_read_input_tokens}")
>
> ```
>
> **第二次请求 - 复用缓存**
>
> ```python theme={null} theme={null}
> response2 = client.messages.create(
>     model="MiniMax-M3.1-Flash",
>     system="You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n",
>     messages=[
>         {
>             "role": "user", 
>             "content": [
>                 {
>                     "type": "text",
>                     "text": "<the entire contents of 'Pride and Prejudice'>"
>                 }
>             ]
>         },
>     ],
>     max_tokens=10240,
> )
>
> print("\n第二次请求结果:")
> for block in response2.content:
>     if block.type == "thinking":
>         print(f"思考:\n{block.thinking}\n")
>     elif block.type == "text":
>         print(f"输出:\n{block.text}\n")
> print(f"输入 Token: {response2.usage.input_tokens}")
> print(f"输出 Token: {response2.usage.output_tokens}")
> print(f"命中缓存 Token: {response2.usage.cache_read_input_tokens}")
> ```
>
> **响应包含上下文缓存的 Token 使用信息：**
>
> ```json theme={null} theme={null}
> {
>     "usage": {
>         "input_tokens": 108,
>         "output_tokens": 91,
>         "cache_creation_input_tokens": 0,
>         "cache_read_input_tokens": 14813
>     }
> }
> ```

> [tab] OpenAI SDK 示例
>
> **安装 SDK**
>
> ```bash theme={null} theme={null}
> pip install openai
> ```
>
> **环境变量设置**
>
> ```bash theme={null} theme={null}
> export OPENAI_BASE_URL=https://api.minimax.cn/v1
> export OPENAI_API_KEY=${YOUR_API_KEY}
> ```
>
> 配置方法见[配置环境变量](https://platform.minimaxi.com/docs/guides/quickstart-preparation.md#env-vars)。
>
> **第一次请求 - 建立缓存**
>
> ```python theme={null} theme={null}
> from openai import OpenAI
>
> client = OpenAI()
>
> response1 = client.chat.completions.create(
>     model="MiniMax-M3.1-Flash",
>     messages=[
>         {"role": "system", "content": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"},
>         {"role": "user", "content": "<the entire contents of 'Pride and Prejudice'>"},
>     ],
> )
>
> print("第一次请求结果:")
> print(f"回复: {response1.choices[0].message.content}")
> print(f"总 Token: {response1.usage.total_tokens}")
> print(f"缓存 Token: {response1.usage.prompt_tokens_details.cached_tokens if hasattr(response1.usage, 'prompt_tokens_details') else 0}")
>
> ```
>
> **第二次请求 - 复用缓存**
>
> ```python theme={null} theme={null}
> response2 = client.chat.completions.create(
>     model="MiniMax-M3.1-Flash",
>     messages=[
>         {"role": "system", "content": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"},
>         {"role": "user", "content": "<the entire contents of 'Pride and Prejudice'>"},
>     ],
> )
>
> print("\n第二次请求结果:")
> print(f"回复: {response2.choices[0].message.content}")
> print(f"总 Token: {response2.usage.total_tokens}")
> print(f"缓存 Token: {response2.usage.prompt_tokens_details.cached_tokens if hasattr(response2.usage, 'prompt_tokens_details') else 0}")
> ```
>
> **响应包含上下文缓存的 Token 使用信息：**
>
> ```json theme={null} theme={null}
> {
>     "usage": {
>         "prompt_tokens": 1200,
>         "completion_tokens": 300,
>         "total_tokens": 1500,
>         "prompt_tokens_details": {
>             "cached_tokens": 800
>         }
>     }
> }
> ```

# 注意事项

* 缓存适用于包含 512 个及以上的输入 token 数量的 API 调用；
* 缓存采用前缀匹配的方式，以「系统提示词-工具定义-历史对话内容」为顺序构建，任意模块内容的变更，都可能会影响缓存的效果；
* 支持模型：MiniMax-M3.1-Flash、MiniMax-M3。

# 最佳实践

* 在对话的开头部分放置静态的或重复的内容（包括系统提示词、工具定义、历史对话内容），将动态的用户信息放在对话的最后，以最大程度利用 cache;
* 通过API返回的 usage tokens 数量，来监测缓存性能，定期分析以优化你的使用策略；

# 计费说明

prompt 缓存采用差异化的计费策略：

* 缓存命中 Token：按优惠价格计费
* 新增的输入 Token: 按标准输入价格计费
* 输出 Token：按标准输出价格计费

> 详见 [按量计费价格页](https://platform.minimaxi.com/docs/pricing/overview.md#models/text)

计费公式：

```
单次请求费用（元）= ( 新增输入 Token 数 × 输入单价
                   + 缓存命中 Token 数 × 缓存命中单价
                   + 输出 Token 数 × 输出单价 ) ÷ 1,000,000

其中：
- 新增输入 Token 数 = 总输入 Token 数 − 缓存命中 Token 数
- 各项单价以「元/百万 tokens」计，取值以按量计费价格页为准
```

以 `MiniMax-M3.1-Flash` 为例（输入 1.00 元、缓存读取 0.10 元、输出 4.00 元，均为每百万 tokens），一次请求总输入 1,200 tokens，其中缓存命中 800 tokens，输出 300 tokens：

```
费用 = ( 400 × 1.00 + 800 × 0.10 + 300 × 4.00 ) ÷ 1,000,000
     = ( 400 + 80 + 1,200 ) ÷ 1,000,000
     = 0.00168 元
```

缓存命中 Token 数可从响应的 `usage` 中获取：

* Anthropic 兼容接口：`usage.cache_read_input_tokens`；`usage.input_tokens` 即为新增输入 Token 数
* OpenAI 兼容接口：`usage.prompt_tokens_details.cached_tokens`；`usage.prompt_tokens` 为总输入 Token 数
