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

# 清理旧工具结果

> 用占位文本替换消息历史中的旧工具结果，减少后续请求的输入 token 数；需要时可按记录编号回查原文。

工具调用产生的搜索结果、日志和代码输出会保存在对话历史中，并随后续请求重复发送。如果不清理，这些旧结果会持续增加请求的输入 token 数，占用上下文窗口。对于内容较长、后续不再需要完整原文的旧结果，可以在客户端将请求中的这些内容替换为占位文本，只保留近期工具结果的原文。

本文通过 Python 示例实现这一流程：完整结果先保存到本地 JSONL 文件，再清理并更新模型当前使用的 `messages`。占位文本记录归档文件路径和记录编号，便于业务系统回查。

| 对象 | 保存的内容 | 用途 |
| - | - | - |
| 消息历史 `messages` | 最近结果的原文，以及旧结果的占位文本 | 清理后用于后续请求 |
| 本地 JSONL 归档 | 完整工具结果、`tool_call_id` 和 `record_id` | 持久化保存并支持回查 |
| 占位文本 | 归档文件路径和 `record_id` | 指明完整结果的保存位置 |

## 实现工具结果清理函数

清理策略由两个 token 阈值控制：

| 参数 | 含义 |
| - | - |
| `protect_recent_tokens` | 保护窗口：从最新一条工具结果开始累计 token 数，窗口内的结果保留原文 |
| `min_clearable_tokens` | 触发阈值：窗口外的旧结果累计超过该值才执行清理，否则消息历史保持不变 |

保护窗口从最新一条工具结果开始，由近及远累计 token 数，直到累计值达到窗口大小；计入的结果都保留原文，包括使累计值达到窗口大小的那一条。因此，无论窗口设多小，最新的工具结果都保留原文。

例如，历史中有四条工具结果，从最新一条开始累计的 token 数依次为 10000、35000、43000 和 71000，保护窗口为 `40000`：累计到 43000 时达到窗口大小，前三条保留原文；最旧的一条在窗口外，旧结果共 28000 token（71000-43000），超过触发阈值 `20000`，替换为占位文本。

以下代码以单进程、单对话场景演示归档和清理流程。实际应用应为每个对话使用独立归档；历史较多时，可以改用数据库保存完整结果。

运行前请在环境变量 `MOONSHOT_API_KEY` 中配置 API Key：

```python expandable theme={null}
from collections import Counter
from copy import deepcopy
import json
import os
from pathlib import Path
from typing import Any
import uuid
from openai import OpenAI

Message = dict[str, Any]
MODEL = "kimi-k3.1-pro"
BASE_URL = "https://api.moonshot.cn/v1"


# 请求函数
def complete(messages: list[Message], **parameters: Any) -> dict[str, Any]:
    client = OpenAI(
        api_key=os.environ["MOONSHOT_API_KEY"],
        base_url=BASE_URL,
    )
    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        max_tokens=8192,
        **parameters,
    )
    return response.model_dump()


# 读取归档，并按 tool_call_id 建立索引
def read_archive(archive_path: Path) -> dict[str, dict[str, Any]]:
    records: dict[str, dict[str, Any]] = {}
    if not archive_path.exists():
        return records
    with archive_path.open("r", encoding="utf-8") as stream:
        for line in stream:
            if not line.strip():
                continue
            record: dict[str, Any] = json.loads(line)
            tool_call_id: str = record["tool_call_id"]
            if tool_call_id in records:
                raise ValueError(f"Duplicate tool_call_id in archive: {tool_call_id}")
            records[tool_call_id] = record
    return records


# 每收到一条工具结果就调用一次；重复归档同一结果不会重复写入
def archive_tool_result(message: Message, archive_path: Path) -> str:
    if message.get("role") != "tool" or not isinstance(message.get("tool_call_id"), str):
        raise ValueError("Expected a tool message with a tool_call_id")
    tool_call_id: str = message["tool_call_id"]
    existing: dict[str, Any] | None = read_archive(archive_path).get(tool_call_id)
    if existing is not None:
        if existing.get("content") != message.get("content"):
            raise ValueError(f"Tool_call_id already archived with different content: {tool_call_id}")
        return existing["record_id"]

    record: dict[str, Any] = {
        "record_id": uuid.uuid4().hex,
        "tool_call_id": tool_call_id,
        "content": deepcopy(message.get("content")),
    }
    serialized: str = json.dumps(record, ensure_ascii=False)
    with archive_path.open("a", encoding="utf-8") as stream:
        stream.write(serialized + "\n")
    return record["record_id"]


# 不删除消息，只检查工具调用与结果的配对
def validate_tool_pairs(messages: list[Message]) -> None:
    call_ids: list[Any] = [
        call.get("id")
        for message in messages
        if message.get("role") == "assistant"
        for call in (message.get("tool_calls") or [])
    ]
    result_ids: list[Any] = [
        message.get("tool_call_id")
        for message in messages
        if message.get("role") == "tool"
    ]
    identifiers: list[Any] = [*call_ids, *result_ids]
    if any(not isinstance(identifier, str) or not identifier for identifier in identifiers):
        raise ValueError("Tool calls and results must have non-empty string IDs")
    if len(call_ids) != len(set(call_ids)) or Counter(call_ids) != Counter(result_ids):
        raise ValueError("Every tool call must have exactly one matching tool result")


# 约 2 个字符折合 1 token
def estimate_tokens(text: str) -> int:
    return len(text) // 2


# 清理主函数：保护窗口内的近期结果保留原文，旧结果替换为占位文本
def clear_old_tool_results(
    messages: list[Message],
    archive_path: Path,
    protect_recent_tokens: int = 40000,
    min_clearable_tokens: int = 20000,
) -> list[Message]:
    if type(protect_recent_tokens) is not int or protect_recent_tokens < 0:
        raise ValueError("protect_recent_tokens must be a non-negative integer")
    if type(min_clearable_tokens) is not int or min_clearable_tokens < 0:
        raise ValueError("min_clearable_tokens must be a non-negative integer")
    cleaned_messages: list[Message] = deepcopy(messages)
    validate_tool_pairs(cleaned_messages)
    tool_indexes: list[int] = [
        index
        for index, message in enumerate(cleaned_messages)
        if message.get("role") == "tool"
    ]

    # 从最新一条开始，由近及远累计，落入保护窗口的结果保留原文
    protected_tokens: int = 0
    protected_count: int = 0
    for index in reversed(tool_indexes):
        protected_tokens += estimate_tokens(
            cleaned_messages[index].get("content") or ""
        )
        protected_count += 1
        if protected_tokens >= protect_recent_tokens:
            break
    older_indexes: list[int] = tool_indexes[: len(tool_indexes) - protected_count]
    if not older_indexes:
        return cleaned_messages

    # 旧结果累计未超过触发阈值时，保持消息历史不变
    clearable_tokens: int = sum(
        estimate_tokens(cleaned_messages[index].get("content") or "")
        for index in older_indexes
    )
    if clearable_tokens < min_clearable_tokens:
        return cleaned_messages

    records: dict[str, dict[str, Any]] = read_archive(archive_path)
    replacements: dict[int, str] = {}
    for index in older_indexes:
        message: Message = cleaned_messages[index]
        record: dict[str, Any] | None = records.get(message["tool_call_id"])
        if record is None:
            raise ValueError("Archive every complete tool result before cleaning its content")
        placeholder: str = (
            f"较早的工具结果已清理。完整结果见 {archive_path}，"
            f"记录编号：{record['record_id']}。"
        )
        if message.get("content") == record.get("content"):
            replacements[index] = placeholder
        elif message.get("content") != placeholder:
            raise ValueError("Archive every complete tool result before cleaning its content")
    for index, placeholder in replacements.items():
        cleaned_messages[index]["content"] = placeholder
    return cleaned_messages
```

代码中各组成部分的作用如下：

| 组成部分 | 代码标识 | 作用 |
| - | - | - |
| 清理主函数 | `clear_old_tool_results()` | 返回清理后的消息列表，并识别已有占位文本；未超过触发阈值时不做修改 |
| 估算函数 | `estimate_tokens()` | 估算文本的 token 数 |
| 归档函数 | `archive_tool_result()` | 将一条完整工具结果保存到 JSONL |
| 配对检查函数 | `validate_tool_pairs()` | 确保每个工具调用都有且只有一个对应结果 |

## 调用清理函数更新消息历史

本示例用 `messages` 保存模型当前使用的消息历史，用 `new_tool_messages` 保存本轮新得到的工具结果。

首次接入尚未归档的历史时，先逐条归档 `messages` 中已有的工具结果；如果加载的是此前已经清理并归档过的历史，则跳过这一步。对于仍保留原文的待清理结果，函数会核对归档记录及内容，检查失败时会报错并停止清理。

每个对话使用独立的归档文件：

```python theme={null}
archive_path = Path(f"tool-results/{conversation_id}.jsonl")
archive_path.parent.mkdir(parents=True, exist_ok=True)

for message in messages:
    if message.get("role") == "tool":
        archive_tool_result(message, archive_path)
```

之后每轮收齐工具结果，先将它们追加到 `messages` 并归档，再清理旧结果并更新 `messages`。发送请求时沿用应用原有的 `tools`：

```python theme={null}
for tool_message in new_tool_messages:
    messages.append(tool_message)
    archive_tool_result(tool_message, archive_path)

# 清理后直接更新消息历史
messages = clear_old_tool_results(
    messages,
    archive_path,
    protect_recent_tokens=40000,  # 演示值
    min_clearable_tokens=20000,  # 演示值
)
response: dict[str, Any] = complete(messages, tools=tools)
assistant: Message = response["choices"][0]["message"]

messages.append(assistant)
print(assistant.get("content"))
```

如果批量归档中途失败，重试前应按 `tool_call_id` 跳过已经追加到 `messages` 的结果，避免重复追加消息。

本示例设置保护窗口 `protect_recent_tokens` 为 `40000` token，触发阈值 `min_clearable_tokens` 为 `20000` token。可以按任务需要调整这两个值，例如将 `min_clearable_tokens` 设为 `0` 时，每轮都会清理窗口外的旧结果。

## 选择保护窗口和触发阈值

后续仍需使用较早结果时，应调大保护窗口；不再依赖这些结果时可以调小。建议根据实际任务比较回答质量和 `usage.prompt_tokens`。

首次将旧结果替换为占位文本时，被替换消息及其后续内容会发生变化，可能影响 [上下文缓存](https://platform.kimi.com/docs/guide/context-caching.md) 命中。评估清理效果时，应同时检查缓存命中情况。

如果某些工具结果包含后续仍需遵循的指令（如技能说明），可以按工具名豁免这类结果，不参与清理。
