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

# Gemini 显式上下文缓存 - 创建缓存

> 把 `contents`、`systemInstruction`、`tools`（至少一项，可另带 `toolConfig`）创建为一份缓存，返回缓存名 `name`。

- **模型**：`model` 写 `models/gemini-3.8-flash` 或 `gemini-3.8-flash` 都可以。支持 `gemini-3.8-flash`、`gemini-3.7-flash`、`gemini-3.6-flash`、`gemini-3.5-flash`、`gemini-3.5-flash-lite`、`gemini-3-flash-preview`、`gemini-3.1-flash-lite-preview`、`gemini-3.1-pro-preview`、`gemini-3.1-pro-preview-customtools`、`gemini-3-pro-preview`；Gemini 4 系列不支持显式缓存。
- **有效期**：`ttl` 形如 `"3600s"`，或 `expireTime`（RFC 3339 时间），两者只能给一个；都不填默认 1 小时。最短 60 秒，最长 168 小时（`604800s`），到期自动删除。
- **大小**：请求体不超过 10 MB；缓存内容需达到模型要求的最小 token 数（如 `gemini-3.8-flash` 为 4,096 token），不足返回 400。
- **字段**：只接受本接口列出的字段，传入其它字段返回 400。
- **tools**：只接受 `googleSearch`、`codeExecution`、`functionDeclarations`，其它工具返回 400。
- **返回的 `name`**：形如 `cachedContents/<id>`，`<id>` 就是本次请求的请求 ID。在控制台「日志」页按这个 id 搜索，就能看到创建缓存的扣费记录。
- **计费**：创建时收取「缓存写入费」（单价与输入相同），并按有效期一次收取「缓存存储费」（每百万 token 每小时）；引用缓存时，命中部分按缓存命中单价计费，缓存中声明了 `googleSearch` 时每次搜索另计。缩短、删除、到期都不退存储费；延长按新增时长补收。各模型单价见 [价格页](https://evolink.ai/pricing)。

认证使用 `Authorization: Bearer`，也接受 `x-goog-api-key` 请求头。

> [!NOTE]
>
> **BaseURL 说明**：默认 BaseURL 为 `https://direct.evolink.ai`，对文本模型支持更好，支持长连接；`https://api.evolink.ai` 是多模态主力地址，对文本模型作为备用地址使用。

> [!NOTE]
>
> **显式上下文缓存**：把反复使用的长前缀（长文档、系统指令、工具定义）创建为缓存，之后的生成请求只带缓存名和新问题。命中部分按缓存命中单价计费；另收缓存写入费和按时长计的存储费，存储费在创建时按有效期一次收取，不退。

> [!TIP]
>
> **引用缓存**：在 `generateContent` 或 `streamGenerateContent` 的请求体中加入 `"cachedContent": "<name>"`，`contents` 只放新问题。引用缓存的请求不能再携带 `systemInstruction`、`tools`、`toolConfig`，模型需与创建缓存时一致。


## OpenAPI

````yaml cn/api-manual/language-series/gemini/cached-contents/cached-contents.json POST /v1beta/cachedContents
openapi: 3.1.0
info:
  title: Gemini 显式上下文缓存（cachedContents）
  description: >-
    把反复使用的长前缀（长文档、系统指令、工具定义）一次创建成缓存，后续生成请求只带缓存名和新问题；缓存部分按「缓存命中」单价计费。接口格式与 Gemini
    原生 cachedContents 接口一致。
  license:
    name: MIT
  version: 1.0.0
servers:
  - url: https://direct.evolink.ai
    description: 生产环境（推荐）
  - url: https://api.evolink.ai
    description: 备用地址
security:
  - bearerAuth: []
tags:
  - name: 显式上下文缓存
    description: 创建、查询、延长、删除 Gemini 显式缓存
paths:
  /v1beta/cachedContents:
    post:
      tags:
        - 显式上下文缓存
      summary: 创建缓存
      description: >-
        把 `contents`、`systemInstruction`、`tools`（至少一项，可另带
        `toolConfig`）创建为一份缓存，返回缓存名 `name`。


        - **模型**：`model` 写 `models/gemini-3.8-flash` 或 `gemini-3.8-flash` 都可以。支持
        `gemini-3.8-flash`、`gemini-3.7-flash`、`gemini-3.6-flash`、`gemini-3.5-flash`、`gemini-3.5-flash-lite`、`gemini-3-flash-preview`、`gemini-3.1-flash-lite-preview`、`gemini-3.1-pro-preview`、`gemini-3.1-pro-preview-customtools`、`gemini-3-pro-preview`；Gemini
        4 系列不支持显式缓存。

        - **有效期**：`ttl` 形如 `"3600s"`，或 `expireTime`（RFC 3339 时间），两者只能给一个；都不填默认 1
        小时。最短 60 秒，最长 168 小时（`604800s`），到期自动删除。

        - **大小**：请求体不超过 10 MB；缓存内容需达到模型要求的最小 token 数（如 `gemini-3.8-flash` 为
        4,096 token），不足返回 400。

        - **字段**：只接受本接口列出的字段，传入其它字段返回 400。

        - **tools**：只接受
        `googleSearch`、`codeExecution`、`functionDeclarations`，其它工具返回 400。

        - **返回的 `name`**：形如 `cachedContents/<id>`，`<id>` 就是本次请求的请求
        ID。在控制台「日志」页按这个 id 搜索，就能看到创建缓存的扣费记录。

        - **计费**：创建时收取「缓存写入费」（单价与输入相同），并按有效期一次收取「缓存存储费」（每百万 token
        每小时）；引用缓存时，命中部分按缓存命中单价计费，缓存中声明了 `googleSearch`
        时每次搜索另计。缩短、删除、到期都不退存储费；延长按新增时长补收。各模型单价见
        [价格页](https://evolink.ai/pricing)。


        认证使用 `Authorization: Bearer`，也接受 `x-goog-api-key` 请求头。
      operationId: geminiCreateCachedContent
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateCachedContentRequest'
            examples:
              long_document:
                summary: 缓存一份长文档 + 系统指令，有效期 1 小时
                value:
                  model: models/gemini-3.8-flash
                  displayName: product-manual-v3
                  systemInstruction:
                    parts:
                      - text: 你是产品手册助手，只依据给定的手册内容回答，手册里没有的信息回答“手册未提及”。
                  contents:
                    - role: user
                      parts:
                        - text: （这里放产品手册全文。缓存内容需不少于 4,096 token。）
                  ttl: 3600s
              with_tools:
                summary: 缓存系统指令 + 函数定义，用绝对到期时间
                value:
                  model: gemini-3.8-flash
                  displayName: support-agent-tools
                  systemInstruction:
                    parts:
                      - text: （这里放很长的客服规范，需不少于 4,096 token。）
                  contents:
                    - role: user
                      parts:
                        - text: （历史工单样例……）
                  tools:
                    - functionDeclarations:
                        - name: lookup_order
                          description: 按订单号查询订单状态
                          parameters:
                            type: object
                            properties:
                              order_id:
                                type: string
                            required:
                              - order_id
                  expireTime: '2026-11-03T06:00:00Z'
      responses:
        '200':
          description: 缓存已创建。`usageMetadata.totalTokenCount` 是缓存的 token 数，写入费与存储费都按它计算
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CachedContent'
              example:
                name: cachedContents/20261103012026348092000s1oTuB96
                model: models/gemini-3.8-flash
                displayName: product-manual-v3
                createTime: '2026-11-03T01:20:27.311Z'
                updateTime: '2026-11-03T01:20:27.311Z'
                expireTime: '2026-11-03T02:20:26.902Z'
                usageMetadata:
                  totalTokenCount: 7525
        '400':
          description: 参数错误；模型不支持显式缓存；当前用户组暂未开放；缓存内容不足最小 token 数
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 400
                  message: ttl must not exceed 604800s (168h)
                  status: INVALID_ARGUMENT
                  details:
                    - '@type': type.googleapis.com/google.rpc.ErrorInfo
                      reason: INVALID_ARGUMENT
                      domain: evolink.ai
        '401':
          description: API Key 无效或缺失
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 401
                  message: Invalid API key
                  status: UNAUTHENTICATED
        '402':
          description: 余额不足以支付缓存写入费和存储费
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 402
                  message: insufficient quota for cache storage prepayment
                  status: RESOURCE_EXHAUSTED
                  details:
                    - '@type': type.googleapis.com/google.rpc.ErrorInfo
                      reason: INSUFFICIENT_QUOTA
                      domain: evolink.ai
        '403':
          description: Key 无权使用该模型、来源 IP 不在 Key 的白名单内，或 Key 所在的用户组已不可用
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 403
                  message: This key is not allowed to use model gemini-3.8-flash
                  status: PERMISSION_DENIED
        '404':
          description: 显式缓存功能未开放
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 404
                  message: explicit context caching is not enabled
                  status: NOT_FOUND
                  details:
                    - '@type': type.googleapis.com/google.rpc.ErrorInfo
                      reason: EXPLICIT_CACHE_DISABLED
                      domain: evolink.ai
        '413':
          description: 请求体超过 10 MB
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 413
                  message: >-
                    cache content exceeds 10485760 bytes; reference large files
                    with fileData.fileUri instead
                  status: INVALID_ARGUMENT
                  details:
                    - '@type': type.googleapis.com/google.rpc.ErrorInfo
                      reason: CACHE_CONTENT_TOO_LARGE
                      domain: evolink.ai
        '429':
          description: 触发频率限制
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 429
                  message: Rate limit exceeded
                  status: RESOURCE_EXHAUSTED
        '502':
          description: 服务暂时不可用，本次不扣费，请稍后重试
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 502
                  message: >-
                    the request could not be completed due to a service
                    authorization problem; please retry later or contact support
                  status: INTERNAL
                  details:
                    - '@type': type.googleapis.com/google.rpc.ErrorInfo
                      reason: UPSTREAM_ERROR
                      domain: evolink.ai
        '503':
          description: 服务暂时不可用，请稍后重试
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  code: 503
                  message: explicit context caching is temporarily unavailable
                  status: UNAVAILABLE
                  details:
                    - '@type': type.googleapis.com/google.rpc.ErrorInfo
                      reason: INTERNAL
                      domain: evolink.ai
components:
  schemas:
    CreateCachedContentRequest:
      type: object
      required:
        - model
      properties:
        model:
          type: string
          description: >-
            模型，`models/gemini-3.8-flash` 或 `gemini-3.8-flash` 两种写法均可。支持
            `gemini-3.8-flash`、`gemini-3.7-flash`、`gemini-3.6-flash`、`gemini-3.5-flash`、`gemini-3.5-flash-lite`、`gemini-3-flash-preview`、`gemini-3.1-flash-lite-preview`、`gemini-3.1-pro-preview`、`gemini-3.1-pro-preview-customtools`、`gemini-3-pro-preview`
          example: models/gemini-3.8-flash
        contents:
          type: array
          description: >-
            要缓存的对话内容，必须是数组。引用缓存时这些内容会作为对话前缀。`contents`、`systemInstruction`、`tools`
            至少提供一项
          items:
            $ref: '#/components/schemas/Content'
        systemInstruction:
          $ref: '#/components/schemas/Content'
          description: 系统指令。写进缓存后，引用缓存的生成请求里不能再带 systemInstruction
        tools:
          type: array
          description: 工具声明。写进缓存后，引用缓存的生成请求里不能再带 tools
          items:
            $ref: '#/components/schemas/Tool'
        toolConfig:
          type: object
          description: 工具调用配置（如 functionCallingConfig）。写进缓存后，引用缓存的生成请求里不能再带 toolConfig
        ttl:
          type: string
          description: >-
            有效期，如 `"3600s"`。最短 `60s`，最长 `604800s`（168 小时）。与 expireTime
            二选一，同时传入返回 400；都不填默认 `3600s`
          example: 3600s
        expireTime:
          type: string
          format: date-time
          description: 绝对到期时间（RFC 3339，UTC），与 ttl 二选一，同时传入返回 400
          example: '2026-11-03T06:00:00Z'
        displayName:
          type: string
          maxLength: 255
          description: 给自己看的名字，最长 255 个字符，不影响计费
          example: product-manual-v3
    CachedContent:
      type: object
      properties:
        name:
          type: string
          description: >-
            缓存名，形如 `cachedContents/<id>`。生成请求的 `cachedContent` 字段填它；`<id>`
            同时是创建请求的请求号
          example: cachedContents/20261103012026348092000s1oTuB96
        model:
          type: string
          description: 缓存绑定的模型，引用时生成请求的模型必须与之一致
          example: models/gemini-3.8-flash
        displayName:
          type: string
          description: 创建时给的名字，没给则不返回
        createTime:
          type: string
          format: date-time
          description: 创建时间（UTC）
        updateTime:
          type: string
          format: date-time
          description: 最近一次更新时间（UTC）
        expireTime:
          type: string
          format: date-time
          description: 到期时间（UTC），到期后自动删除
        usageMetadata:
          type: object
          properties:
            totalTokenCount:
              type: integer
              description: 缓存的 token 总数，缓存写入费与存储费按它计算
              example: 7525
    ErrorResponse:
      type: object
      description: >-
        Gemini 原生错误格式。`error.details[0].reason` 为原因码：`INVALID_ARGUMENT`
        参数错误；`EXPLICIT_CACHE_UNSUPPORTED`
        模型不支持显式缓存；`NO_AVAILABLE_CHANNEL`、`MODEL_PRICE_ERROR`
        当前用户组暂未开放；`CACHE_EXPIRED` 缓存已到期或剩余有效期过短；`CACHE_MODEL_MISMATCH`
        模型与缓存不一致；`INVALID_CACHED_CONTENT` `cachedContent`
        格式不正确；`INSUFFICIENT_QUOTA` 余额不足；`CACHE_NOT_FOUND`
        缓存不存在、已过期、已删除或不属于当前账号；`EXPLICIT_CACHE_DISABLED`
        功能暂未开放；`CACHE_CONTENT_TOO_LARGE` 请求体超过 10 MB；`UPSTREAM_ERROR` 请求未被接受，原因见
        `message`；`CACHE_CHANNEL_UNAVAILABLE`、`INTERNAL` 暂时不可用，请稍后重试。
      properties:
        error:
          type: object
          properties:
            code:
              type: integer
              description: HTTP 状态码
            message:
              type: string
            status:
              type: string
              description: 状态枚举，如 INVALID_ARGUMENT / NOT_FOUND / UNAVAILABLE
            details:
              type: array
              items:
                type: object
                properties:
                  '@type':
                    type: string
                    example: type.googleapis.com/google.rpc.ErrorInfo
                  reason:
                    type: string
                    example: CACHE_NOT_FOUND
                  domain:
                    type: string
                    example: evolink.ai
    Content:
      type: object
      required:
        - parts
      properties:
        role:
          type: string
          enum:
            - user
            - model
          description: 角色；系统指令不需要填
        parts:
          type: array
          items:
            $ref: '#/components/schemas/Part'
    Tool:
      type: object
      description: 工具声明。只接受下面三种，其它工具会被拒绝
      properties:
        googleSearch:
          type: object
          description: 联网搜索，填 `{}`
        codeExecution:
          type: object
          description: 代码执行，填 `{}`
        functionDeclarations:
          type: array
          description: 函数调用声明（OpenAPI 子集的参数结构）
          items:
            type: object
            properties:
              name:
                type: string
              description:
                type: string
              parameters:
                type: object
    Part:
      type: object
      description: 内容片段：文本、内联数据（base64）或文件引用，三选一
      properties:
        text:
          type: string
          description: 文本
        inlineData:
          type: object
          description: 内联二进制数据（图片 / 音频 / PDF 等）
          properties:
            mimeType:
              type: string
              example: application/pdf
            data:
              type: string
              description: base64 编码的数据
        fileData:
          type: object
          description: 文件引用
          properties:
            mimeType:
              type: string
            fileUri:
              type: string
              description: 公网可访问的 URL
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        ##所有接口均需要使用 Bearer Token 进行认证##


        **获取 API Key：**


        访问 [API Key 管理页面](https://evolink.ai/dashboard/keys) 获取您的 API Key


        **使用时在请求头中添加：**

        ```

        Authorization: Bearer YOUR_API_KEY

        ```


        也接受 Gemini 原生写法：请求头 `x-goog-api-key: YOUR_API_KEY`，或 URL 参数
        `?key=YOUR_API_KEY`。

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.