# 创建上下文缓存 API

> 全部文档的索引见 [llms.txt](https://ark.volcengine.com/llms.txt)；在任一文档页面地址后追加 `.md` 可获取该页的 Markdown 版本。

` POST https://ark.cn-beijing.volces.com/api/v3/context/create`   [运行](https://api.volcengine.com/api-explorer/?action=ContextCreate&data=%7B%7D&groupName=%E4%B8%8A%E4%B8%8B%E6%96%87%E7%BC%93%E5%AD%98&query=%7B%7D&serviceCode=ark&version=2024-01-01)
上下文缓存（Context API）是方舟提供的一个高效的缓存机制。它通过缓存上下文数据，减少重复加载或处理，提高响应速度和一致性。本文介绍上下文缓存 API 的输入输出参数，供您使用接口时查阅字段含义。

**选项：快速入口**

<span>![图片](https://portal.volccdn.com/obj/volcfe/cloud-universal-doc/upload_a5fdd3028d35cc512a10bd71b982b6eb.png) </span>[计费说明](/docs/model-pricing#%E4%B8%8A%E4%B8%8B%E6%96%87%E7%BC%93%E5%AD%98%E8%AE%A1%E8%B4%B9)       <span>![图片](https://portal.volccdn.com/obj/volcfe/cloud-universal-doc/upload_afbcf38bdec05c05089d5de5c3fd8fc8.png) </span>[API Key](https://ark.volcengine.com/region:cn-beijing/apiKey?apikey=%7B%7D)        <span>![图片](https://portal.volccdn.com/obj/volcfe/cloud-universal-doc/upload_2abecd05ca2779567c6d32f0ddc7874d.png) </span>[支持模型](/docs/model-list#e6772192)
<span>![图片](https://portal.volccdn.com/obj/volcfe/cloud-universal-doc/upload_57d0bca8e0d122ab1191b40101b5df75.png) </span>[调用教程](/docs/context-api)       <span>![图片](https://portal.volccdn.com/obj/volcfe/cloud-universal-doc/upload_bef4bc3de3535ee19d0c5d6c37b0ffdd.png) </span>[开通模型](https://ark.volcengine.com/region:cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false)

**选项：鉴权说明**

本接口支持 API Key / Access Key鉴权，详见 [鉴权认证方式](/docs/base-url-and-authentication)。

---

<span id="RxN8G2nH"></span>
## 请求参数
> 跳转 [响应参数](/docs/create-context-cache-api#Qu59cel0)

<span id="pjuiBZGA"></span>
### 请求体

---

**model** `string` `必选`
通过 Endpoint ID 来调用模型，获得限流、计费类型（前付费/后付费）、运行状态查询、监控、安全等高级能力，可参考 [获取 Endpoint ID](https://ark.volcengine.com/region:cn-beijing/docs/create-standard-inference-endpoint)。
> 暂不支持通过 Model ID 来调用。

---

**messages**  `object[]` `必选`
对话组成的消息列表。您希望缓存的信息。
注意：初始化的信息如系统人设，背景信息等，请使用系统消息（System message）放在消息列表最前。这部分信息在2种缓存模式下，均会一直存储在缓存中，直到缓存到期（触达最大生命周期）释放。

属性

---

**系统消息**  `object`
系统消息，开发人员提供的指令，模型应遵循这些指令。如模型扮演的角色或者目标等。

属性

---

messages.**role** `string` `必选`
发送消息的角色，此处应为`system`。

---

messages.**content** `string` `必选`
系统信息内容。

---

**用户消息**`object`
用户发送的消息，包含提示或附加上下文信息。

属性

---

messages.**role** `string` `必选`
发送消息的角色，此处应为`user`。

---

messages.**content** `string` `必选`
用户信息内容。

---

messages.**name** `string`
发送此消息的角色的姓名。用于区别同一个角色但是不同主体发送的消息。

---

**模型消息**  `object`
模型响应用户消息而回复的消息。

> **说明**
>
> messages.**content** 与 messages.**tool_calls** 字段二者至少填写其一。

---

messages.**role** `string` `必选`
发送消息的角色，此处应为`assistant`。

---

messages.**content** `string`
模型回复的消息。

---

messages.**tool_calls** `object[]`
模型回复的工具调用信息。

属性

---

messages.tool_calls.**function** `object` `必选`
模型调用工具对应的函数信息。

属性

---

messages.tool_calls.function.**name** `string` `必选`
模型需要调用的函数名称。

---

messages.tool_calls.function.**arguments** `string` `必选`
模型生成的用于调用函数的参数，JSON 格式。

> **说明**
>
> 模型并不总是生成有效的 JSON，并且可能会虚构出一些您的函数参数规范中未定义的参数。在调用函数之前，请在您的代码中验证这些参数是否有效。

---

messages.tool_calls.**id** `string` `必选`
调用的工具的 ID。

---

messages.tool_calls.**type** `string` `必选`
工具类型，当前仅支持`function`。

---

**mode** `string` `默认值 session`
本次请求创建的上下文缓存的类型。[点此](/docs/context-cache) 了解类型介绍。[点此](/docs/model-list#e6772192) 了解支持的模型 。
* `session` ：Session 缓存。
* `common_prefix` ：前缀缓存。

---

**ttl** `integer / null` `默认值 86400`
过期时长，单位为秒，设置范围：[3600, 604800]，即1小时到7天。
信息在创建后即开始计时，每次使用则重置为0。计时超过ttl，信息会被从缓存中删除。每次调用chat均根据ttl更新过期时间。

---

**truncation_strategy** `object / null` `默认值 null`
缓存的上下文长度的窗口长度策略配置，只在当 **mode** 字段设置为`session`，该字段可设置。
支持 Session 缓存的模型能且只能支持 1 种 Session 缓存模式。如不配置该字段，方舟会根据您调用的模型自动适配合适的 Session 缓存模式。

属性
**last_history_tokens 模式** `object`
触发缓存上限不会重新计算。

属性

---

truncation_strategy.**type** `string` `必选`
此处应为 `last_history_tokens`。

---

truncation_strategy.**last_history_tokens** `integer` `默认值 4096`
取值范围：` (0,32768)`。
缓存上下文窗口大小，即可缓存的上下文的最大 token 数。触发该上限将根据缓存上下文窗口大小对缓存内容进行清除。清除顺序按照信息被缓存时间长短排序，先清除缓存时间长的信息 。

**rolling_tokens 模式** `object`
触发缓存上限会进行重新计算。

属性

---

truncation_strategy.**type** `string` `必选`
此处应为 `rolling_tokens`。

---

truncation_strategy.**rolling_tokens** `boolean` `默认值 true`
在缓存中历史消息长度接近 **max_window_tokens** 字段值时，是否自动对历史上下文进行裁剪（按照 message 元素粒度裁剪，按照 message 元素取整，即删除的信息的长度在 **rolling_window_tokens** 范围内，不会截断任意信息）。
* `false`：在历史消息长度超过上下文长度时模型会停止输出（返回字段 **finish_reason** 为`length`)。
* `true`：在历史消息长度接近上下文长度时模型按照先进先出的顺序，自动删除定量（**rolling_window_tokens** 字段值 token 数）的内容，为新对话内容腾挪缓存空间；同时对缓存中的信息进行重新计算和读入，保障内容理解一致性。具体的计算逻辑，请参见 [rolling_tokens 模式](/docs/context-api#a0e4efde)。

---

truncation_strategy.**max_window_tokens** `integer / null` `默认值 32768`
在缓存中可存储的历史消息长度最大值。
取值满足下面条件：0 < **rolling_window_tokens** < **max_window_tokens** < **context window**（模型最大上下文）。

---

truncation_strategy.**rolling_window_tokens** `integer / null` `默认值 4096`
当缓存触发了**max_window_tokens** 上限，则会裁剪滚动窗口长度。
取值满足下面条件：0 < **rolling_window_tokens** < **max_window_tokens** < **context window**（模型最大上下文）。

<span id="Qu59cel0"></span>
## 响应参数
> 跳转 [请求参数](/docs/create-context-cache-api#RxN8G2nH)

---

**id** `string`
本次请求创建的上下文缓存的ID，在后续创建带缓存的 [上下文缓存对话 API](/docs/context-cache-conversation-api) 需要使用。

---

**model** `string`
本次请求使用的推理接入点的 ID 。

---

**mode** `string`
本次请求创建的上下文缓存的类型。[点此](/docs/model-list#e6772192) 了解支持的模型 。
* `session` ：Session 缓存。
* `common_prefix` ：前缀缓存。

---

**ttl** `integer`
本次请求创建的上下文缓存过期时长，单位为秒。信息在创建后即开始计时，每次使用则重置为0。计时超过ttl，信息会被从缓存中删除。每次调用chat均根据ttl更新过期时间。
过期时间可以设置的范围在1小时到7天，即[3600, 604800]。

---

**truncation_strategy** `object`
本次请求创建的 Session 缓存使用的截断策略信息。

属性

---

**last_history_tokens 模式** `object`
触发缓存上限，自动滚动缓存内容，无需重新计算。

属性

---

truncation_strategy.**type** `string`
本次请求创建的 Session 缓存的截断策略，此处应为 `last_history_tokens`。

---

truncation_strategy.**last_history_tokens** `integer`
本次请求创建的 Session 缓存可缓存的最大 token 数。

---

**rolling_tokens 模式** `object`
触发缓存上限，进行重新计算。

属性

---

truncation_strategy.**type** `string`
本次请求创建的 Session 缓存的截断策略，此处应为 `rolling_tokens`。

---

truncation_strategy.**rolling_tokens** `boolean`
本次请求创建的 Session 缓存，当缓存的信息量达到最大缓存窗口时，是否自动处理。

---

**usage** `object`
本次请求的 token 用量。

属性

---

usage.**prompt_tokens** `integer`
输入的 prompt token 数量。

---

usage.**completion_tokens** `integer`
模型生成的 token 数量。

---

usage.**total_tokens** `integer`
本次请求消耗的总 token 数量（输入 + 输出）。

---

usage.**prompt_tokens_details** `object`
命中上下文缓存的 token 细节。

属性

---

usage.prompt_tokens_details.**cached_tokens** `integer`
命中上下文缓存的 token 数。


## 代码示例

## 创建前缀缓存

### cURL

#### Request

```bash
curl https://ark.cn-beijing.volces.com/api/v3/context/create \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ARK_API_KEY" \
  -d $'{
    "messages": [
        {
            "content": "你是李雷，你只会说“我是李雷”",
            "role": "system"
        }
    ],
    "mode": "common_prefix",
    "model": "ep-20250410*****-*****"
}'
```
#### Response

```
{
  "id": "ctx-20250410175333-lkjq2",
  "model": "ep-20250410*****-*****",
  "ttl": 86400,
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "common_prefix"
}
```

### Python

#### Request

```python
import os
import datetime

from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

if __name__ == "__main__":
    print("----- create context -----")
    response = client.context.create(
        model="ep-202504101*****-*****",
        mode="common_prefix",
        messages=[{"content":"你是李雷，你只会说“我是李雷”","role":"system"}],
    )
    print(response)
```
#### Response

```
{
  "id": "ctx-20250410175333-lkjq2",
  "model": "ep-20250410*****-*****",
  "ttl": 86400,
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "common_prefix"
}
```

### Go

#### Request

```go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/volcengine/volcengine-go-sdk/service/arkruntime"
	"github.com/volcengine/volcengine-go-sdk/service/arkruntime/model"
	"github.com/volcengine/volcengine-go-sdk/volcengine"
)


func main() {
	client := arkruntime.NewClientWithApiKey(os.Getenv("ARK_API_KEY"))
	ctx := context.Background()
	fmt.Println("----- create context -----")
	req := model.CreateContextRequest{
		Model: "ep-202504101*****-*****",
		Mode:  "common_prefix",
		Messages: []*model.ChatCompletionMessage{
			&model.ChatCompletionMessage{
				Role: "system",
				Content: &model.ChatCompletionMessageContent{
					StringValue: volcengine.String("你是李雷，你只会说“我是李雷”"),
				},
			},
		},
	}

	resp, err := client.CreateContext(ctx, req)
	if err != nil {
		fmt.Printf("standard chat error: %v\n", err)
		return
	}
	fmt.Printf("create context response: %v\n", resp)
}
```
#### Response

```
{
  "id": "ctx-20250410175333-lkjq2",
  "model": "ep-20250410*****-*****",
  "ttl": 86400,
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "common_prefix"
}
```

### Java

#### Request

```java
package com.volcengine.sample;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.volcengine.ark.runtime.model.completion.chat.*;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest.*;
import com.volcengine.ark.runtime.model.context.*;
import com.volcengine.ark.runtime.model.context.CreateContextRequest;
import com.volcengine.ark.runtime.model.context.chat.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

/*
# pom.xml
<dependency>
  <groupId>com.volcengine</groupId>
  <artifactId>volcengine-java-sdk-ark-runtime</artifactId>
  // 替换正式版本号
  <version>LATEST</version>
</dependency>
*/

public class Sample {

    static String apiKey = System.getenv("ARK_API_KEY");

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                    .build();

    public static void main(String[] args) throws JsonProcessingException {

        List<ChatMessage> messagesForReqList = new ArrayList<>();

        ChatMessage elementForMessagesForReqList0 =
                ChatMessage.builder()
                        .role(ChatMessageRole.SYSTEM)
                        .content("你是李雷，你只会说“我是李雷”")
                        .build();
        messagesForReqList.add(elementForMessagesForReqList0);

        CreateContextRequest req =
                CreateContextRequest.builder()
                        .model("ep-202504101*****-*****")
                        .mode("common_prefix")
                        .messages(messagesForReqList)
                        .build();

        service.createContext(req).toString();

        // shutdown service after all requests is finished
        service.shutdownExecutor();
    }
}
```
#### Response

```
{
  "id": "ctx-20250410175333-lkjq2",
  "model": "ep-20250410*****-*****",
  "ttl": 86400,
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "common_prefix"
}
```

## 创建 Session 缓存

### cURL

#### Request

```bash
curl https://ark.cn-beijing.volces.com/api/v3/context/create \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ARK_API_KEY" \
  -d $'{
    "messages": [
        {
            "content": "你是李雷，你只会说“我是李雷”",
            "role": "system"
        }
    ],
    "mode": "session",
    "model": "ep-202504101*****-*****"
}'
```
#### Response

```
{
  "id": "ctx-20250410175644-824s6",
  "model": "ep-202504101*****-*****”,
  "ttl": 86400,
  "truncation_strategy": {
    "type": "rolling_tokens",
    "rolling_tokens": true
  },
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "session"
}
```

### Python

#### Request

```python
import os
import datetime

from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

if __name__ == "__main__":
    print("----- create context -----")
    response = client.context.create(
        model="ep-202504101*****-*****",
        mode="session",
        messages=[{"content":"你是李雷，你只会说“我是李雷”","role":"system"}],
    )
    print(response)
```
#### Response

```
{
  "id": "ctx-20250410175644-824s6",
  "model": "ep-202504101*****-*****”,
  "ttl": 86400,
  "truncation_strategy": {
    "type": "rolling_tokens",
    "rolling_tokens": true
  },
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "session"
}
```

### Go

#### Request

```go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/volcengine/volcengine-go-sdk/service/arkruntime"
	"github.com/volcengine/volcengine-go-sdk/service/arkruntime/model"
	"github.com/volcengine/volcengine-go-sdk/volcengine"
)


func main() {
	client := arkruntime.NewClientWithApiKey(os.Getenv("ARK_API_KEY"))
	ctx := context.Background()
	fmt.Println("----- create context -----")
	req := model.CreateContextRequest{
		Model: "ep-202504101*****-*****",
		Mode:  "session",
		Messages: []*model.ChatCompletionMessage{
			&model.ChatCompletionMessage{
				Role: "system",
				Content: &model.ChatCompletionMessageContent{
					StringValue: volcengine.String("你是李雷，你只会说“我是李雷”"),
				},
			},
		},
	}

	resp, err := client.CreateContext(ctx, req)
	if err != nil {
		fmt.Printf("standard chat error: %v\n", err)
		return
	}
	fmt.Printf("create context response: %v\n", resp)
}
```
#### Response

```
{
  "id": "ctx-20250410175644-824s6",
  "model": "ep-202504101*****-*****”,
  "ttl": 86400,
  "truncation_strategy": {
    "type": "rolling_tokens",
    "rolling_tokens": true
  },
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "session"
}
```

### Java

#### Request

```java
package com.volcengine.sample;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.volcengine.ark.runtime.model.completion.chat.*;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest.*;
import com.volcengine.ark.runtime.model.context.*;
import com.volcengine.ark.runtime.model.context.CreateContextRequest;
import com.volcengine.ark.runtime.model.context.chat.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

/*
# pom.xml
<dependency>
  <groupId>com.volcengine</groupId>
  <artifactId>volcengine-java-sdk-ark-runtime</artifactId>
  // 替换正式版本号
  <version>LATEST</version>
</dependency>
*/

public class Sample {

    static String apiKey = System.getenv("ARK_API_KEY");

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                    .build();

    public static void main(String[] args) throws JsonProcessingException {

        List<ChatMessage> messagesForReqList = new ArrayList<>();

        ChatMessage elementForMessagesForReqList0 =
                ChatMessage.builder()
                        .role(ChatMessageRole.SYSTEM)
                        .content("你是李雷，你只会说“我是李雷”")
                        .build();
        messagesForReqList.add(elementForMessagesForReqList0);

        CreateContextRequest req =
                CreateContextRequest.builder()
                        .model("ep-202504101*****-*****")
                        .mode("session")
                        .messages(messagesForReqList)
                        .build();

        service.createContext(req).toString();

        // shutdown service after all requests is finished
        service.shutdownExecutor();
    }
}
```
#### Response

```
{
  "id": "ctx-20250410175644-824s6",
  "model": "ep-202504101*****-*****”,
  "ttl": 86400,
  "truncation_strategy": {
    "type": "rolling_tokens",
    "rolling_tokens": true
  },
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 0,
    "total_tokens": 18,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "mode": "session"
}
```
