context-engineering-diagnostic-optimizer

Diagnose and optimize context-window usage efficiency for AI Agent/LLM applications. Automatically detect issues such as context bloat, redundant retrievals, ineffective tool calls, and overly long prompts, and produce actionable optimization plans covering five strategies: context isolation, trimming, compressed summarization, dynamic tool loading, and external unloading. Applicable to mainstream agent frameworks such as Claude Code, LangChain, LangGraph, Dify, and AgentScope.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "context-engineering-diagnostic-optimizer" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-f89106a20e4ea1cd5398f4384308ffaabae446ec4788c5c94063af10d3c6ffde. Verify the upstream source and version against https://skillhub.cn/skills/user_27d87c91/context-engineering-diagnostic-optimizer before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Diagnose and optimize context-window usage efficiency for AI Agent/LLM applications. Automatically detect issues such as context bloat, redundant retrievals, ineffective tool calls, and overly long prompts, and produce actionable optimization plans covering five strategies: context isolation, trimming, compressed summarization, dynamic tool loading, and external unloading. Applicable to mainstream agent frameworks such as Claude Code, LangChain, LangGraph, Dify, and AgentScope.

0 Downloads

Introduction source: third_party · user_27d87c91 · 1.0.0 Reference

SkillPi interpretation

Audience
Translation pending; see source documentation.
Inputs and outputs
Translation pending; see source documentation.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: context-engineering-diagnostic-optimizer
description: >-
  诊断并优化你的 AI Agent / LLM 应用的上下文窗口使用效率。
  自动检测上下文膨胀、冗余检索、无效工具调用、提示词过长等问题,
  输出可执行的优化方案——涵盖上下文隔离、修剪、压缩总结、
  动态工具装载与外部卸载五大策略。
  适用于 Claude Code、LangChain、LangGraph、Dify、AgentScope 等主流 Agent 框架。
tags:
  - context-engineering
  - agent-optimization
  - token-efficiency
  - llm-debugging
  - rag
author: aigeek_laogao
version: 1.0.0

上下文工程诊断优化器

一句话说清

你的 Agent 是不是越聊越笨、越跑越慢、越用越贵? 本技能用 5 分钟诊断你的上下文使用情况,告诉你哪里浪费了 token、哪里可以优化,并给出可直接落地的修改方案。


适用场景

  • Agent 运行几轮后回答质量明显下降
  • 上下文窗口频繁溢出,不得不截断历史
  • API 费用居高不下,但不知道哪里能省
  • 工具调用越来越多,Agent 却越来越慢
  • 多轮对话中 Agent "遗忘"了早期重要信息
  • RAG 检索返回了大量文档,但答案反而变差

诊断流程

第一步:上下文结构扫描

请提供以下任一信息,我来做结构分析:

  • Claude Code / ChatGPT 场景:粘贴你的系统提示词 + 最近 3-5 轮对话
  • LangChain / LangGraph 场景:粘贴你的 prompt_template + chat_history 结构
  • Dify 场景:导出你的应用配置或粘贴提示词编排截图描述
  • 通用场景:描述你的 Agent 架构(角色、工具数量、典型对话轮次)

我会输出一份 上下文结构诊断报告,包含:

📊 上下文结构诊断报告
├── 总 token 估算
├── 各部分占比
│   ├── 系统提示词 (X%)
│   ├── 工具定义 (X%)
│   ├── 对话历史 (X%)
│   └── 检索上下文 (X%)
├── 冗余检测
│   ├── 重复信息 (X tokens)
│   ├── 无效轮次 (X tokens)
│   └── 低价值内容 (X tokens)
└── 风险预警
    ├── 上下文溢出风险: 高/中/低
    └── 信息遗忘风险: 高/中/低

第二步:问题识别

根据扫描结果,对照以下 6 种常见上下文病灶 进行匹配:

病灶 症状 根因
🔴 提示词肥胖症 系统提示词超过 2000 token,Agent 仍然"不听话" 提示词包含太多一次性示例、重复约束、未使用的角色设定
🔴 历史堆积症 保留全部对话历史,越聊越慢 未区分短期记忆/长期记忆,无差别全量保留
🔴 工具爆炸症 定义了大量工具但大部分从未被调用 工具未按需装载,一次性全量注入上下文
🟡 检索过载症 RAG 召回 20+ 个文档块,答案却不如只用 3 个准确 缺少 Reranking、未做上下文压缩
🟡 上下文污染症 Agent 被历史中某次错误输出带偏 缺少上下文隔离机制,错误信息持久驻留
🟢 输出冗余症 Agent 输出大段 Markdown/代码,下一轮又全量回传 未对长输出做摘要或外部存储

第三步:生成优化方案

针对识别出的病灶,从 五大策略工具箱 中匹配具体方案。


五大策略工具箱

策略一:上下文修剪(Context Pruning)

适用病灶:提示词肥胖症、历史堆积症

具体手段:

修剪对象             │  方法                          │  节省量
─────────────────────┼────────────────────────────────┼──────────
系统提示词中的示例    │ 保留 1 个最具代表性的,其余删除  │ 30-50%
对话历史早期轮次      │ 保留最近 N 轮 + 首轮任务描述     │ 40-60%
未使用的工具定义      │ 从系统提示中移除,改为按需装载    │ 20-40%
重复的安全/格式约束    │ 合并同类项,只说一次             │ 10-20%

操作模板(LangChain 示例):

# 修剪前:全量历史
messages = system_prompt + chat_history + user_query

# 修剪后:保留关键信息
def prune_history(messages, max_turns=10, keep_first=True):
    if len(messages) <= max_turns * 2:
        return messages  # Human + AI 各算一轮

    # 始终保留首轮(含任务定义)
    first_turn = messages[:2] if keep_first else []
    # 保留最近 N 轮
    recent = messages[-(max_turns * 2):]
    # 中间轮次做摘要
    middle_summary = summarize_middle(messages[2:-(max_turns * 2)])

    return first_turn + [middle_summary] + recent

策略二:上下文隔离(Context Isolation)

适用病灶:上下文污染症

核心思想:不同任务/话题使用独立的上下文空间,避免相互污染。

具体手段:

  1. 会话级隔离:每个独立任务新建对话,不共享历史
  2. 工具级隔离:工具调用结果与对话历史分池管理
  3. 错误隔离:将 Agent 的错误输出标记后移出主上下文,仅保留"已纠正"的摘要

操作模板(LangGraph 示例):

from langgraph.graph import StateGraph
from langgraph.checkpoint import MemorySaver

# 为不同子任务创建独立上下文
def route_by_topic(state):
    topic = classify_topic(state["messages"][-1])
    if topic == "code_review":
        return "code_context"  # 代码审查专用上下文
    elif topic == "documentation":
        return "doc_context"   # 文档编写专用上下文
    else:
        return "general_context"

# 每种上下文维护独立的历史
graph = StateGraph(AgentState)
graph.add_node("code_context", code_agent, context_window=8000)
graph.add_node("doc_context", doc_agent, context_window=8000)

策略三:压缩总结(Compression & Summarization)

适用病灶:检索过载症、历史堆积症

具体手段:

  1. 检索上下文压缩:对 RAG 召回的文档块做 LLM 摘要后再注入上下文
  2. 对话摘要压缩:每 N 轮自动生成对话摘要,替换原始历史
  3. 分层压缩:工具输出 → 关键字段提取 → 仅保留决策相关信息

操作模板:

# RAG 上下文压缩:20 个文档块 → 压缩为结构化摘要
def compress_retrieved_docs(docs, max_tokens=1500):
    # 第一步:Reranking,取 Top-5
    top_docs = rerank(docs, top_k=5)

    # 第二步:LLM 压缩每个文档为 1-2 句要点
    compressed = []
    for doc in top_docs:
        summary = llm.invoke(
            f"用一句话概括以下内容的关键信息,只保留与用户问题相关的部分:\n{doc.page_content}"
        )
        compressed.append(summary)

    # 第三步:结构化拼接
    return "\n---\n".join(compressed)


# 对话历史压缩
def compress_conversation(messages, trigger_tokens=4000):
    current_tokens = count_tokens(messages)
    if current_tokens < trigger_tokens:
        return messages

    # 对中间轮次做摘要
    summary = llm.invoke(
        "将以下对话历史压缩为结构化摘要,保留:1)用户偏好 2)已做决策 3)待完成事项\n"
        f"{format_messages(messages[2:-6])}"
    )
    return [messages[0], messages[1], 
            HumanMessage(content=f"[历史摘要]{summary}"),
            *messages[-6:]]

策略四:工具自适应装载(Adaptive Tool Loading)

适用病灶:工具爆炸症

核心思想:不在系统提示词中一次性列出所有工具,而是根据当前任务按需装载。

具体手段:

  1. 工具分层:核心工具(始终加载)+ 扩展工具(按需加载)
  2. 工具描述压缩:仅保留工具名 + 一句话描述,被调用时再展开完整参数
  3. 工具检索:用语义搜索匹配当前任务相关的工具

操作模板:

# 工具按需装载
class AdaptiveToolLoader:
    def __init__(self):
        self.tool_index = build_tool_index(all_tools)  # 向量索引
        self.core_tools = [search, memory, calculator]  # 始终加载

    def load_tools(self, user_query):
        # 语义匹配 Top-3 相关工具
        relevant = search_tools(user_query, self.tool_index, top_k=3)
        # 合并核心工具 + 匹配工具
        return self.core_tools + relevant

# 对比:
# ❌ 8 个工具全量注入 → ~2000 tokens 工具定义
# ✅ 3 核心 + 3 按需 → ~800 tokens,节省 60%

策略五:上下文外部卸载(Context External Offloading)

适用病灶:输出冗余症、检索过载症

核心思想:将大块内容(代码、长文档、表格)移到上下文外存储,上下文内仅保留引用指针 + 关键摘要。

具体手段:

  1. 长输出卸载:Agent 生成的长代码/报告 → 写入文件,上下文内只保留前 3 行 + 文件路径
  2. 检索结果卸载:RAG 召回的文档全文 → 存为临时引用,上下文内只保留摘要
  3. 文件系统作为外部记忆:用文件系统替代上下文窗口存储中间结果

操作模板:

# 长代码输出卸载
def offload_long_output(content, context_budget=500):
    if count_tokens(content) <= context_budget:
        return content  # 够短,直接保留

    import hashlib, os
    file_id = hashlib.md5(content.encode()).hexdigest()[:8]
    filepath = f"/tmp/ctx_offload/{file_id}.md"

    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    with open(filepath, "w") as f:
        f.write(content)

    # 上下文内只保留摘要 + 引用
    preview = content[:200] + "..."
    return (
        f"[内容已卸载至 {filepath}]\n"
        f"摘要:{summarize(content)}\n"
        f"预览:{preview}\n"
        f"需要完整内容时,读取 {filepath}"
    )

快速诊断问卷(30 秒自测)

在让我做详细诊断之前,你可以先回答这 5 个问题,判断是否需要优化:

# 问题 是(+1 分) 否(0 分)
1 你的系统提示词超过 1500 token 吗? ⚠️ ✅
2 你的 Agent 定义的工具超过 5 个吗? ⚠️ ✅
3 你的对话超过 10 轮后 Agent 明显变笨吗? ⚠️ ✅
4 你的 RAG 每次都召回 10+ 个文档块吗? ⚠️ ✅
5 你的单次 API 调用平均超过 8000 token 吗? ⚠️ ✅

得分解读:

  • 0-1 分 🟢 你的上下文管理整体健康,可以关注细节优化
  • 2-3 分 🟡 存在明显优化空间,预计可节省 30-50% token
  • 4-5 分 🔴 上下文亟需治理,预计可节省 50-80% token

输出格式

诊断完成后,我始终以以下格式输出结果:

📊 上下文健康度评分:XX/100

🔴 高优先级问题(立即修复):
  1. [问题名称] — 预计节省 X tokens — [修复方案]
  2. ...

🟡 中优先级优化(本周修复):
  1. [问题名称] — 预计节省 X tokens — [优化方案]
  2. ...

🟢 锦上添花(有余力再做):
  1. [建议]
  2. ...

💰 预估总节省:X tokens/次调用 → X 元/月(按当前费率)

📝 实施优先级排序(ROI 从高到低):
  1. [改动最小、效果最大的方案]
  2. ...

常见问题速查

Q: 所有 Agent 都需要上下文优化吗?

不是。 如果你的 Agent 只做简单的单轮问答、对话不超过 5 轮、工具不超过 3 个,当前上下文完全够用。当你的 Agent 出现"越聊越笨""费用暴涨""响应变慢"时,才需要优化。

Q: 优化后会不会丢失重要信息?

不会——如果做对了。 核心原则是:区分"永久需要的信息"和"仅在当前步骤需要的信息"。前者压缩保留,后者用完即弃。本技能的所有策略都遵循这一原则。

Q: 我应该先做哪个策略?

ROI 排序:修剪 > 压缩 > 隔离 > 动态装载 > 外部卸载。 修剪是最快见效的(改几行代码),外部卸载是最彻底的(但需要架构改动)。

Q: 支持哪些框架?

通用方法论适用于所有框架。代码模板目前覆盖:Claude Code / LangChain / LangGraph / Dify / AgentScope。其他框架可以给出等效方案。


技能作者

  • 作者:aigeek_laogao(10年+ AI/架构经验,专注大模型应用落地、Agent智能体、上下文工程)
  • 实战项目:各业务场景Agent、DeepSeek/千问本地化部署、GraphRAG法律法规匹配系统
  • 联系方式:53248550@qq.com

版本记录

版本 日期 变更
1.0.0 2026-06-26 初始发布,包含五大策略完整工具箱、诊断流程、快速问卷

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value95/100

Highlights

  • 直接解决Agent上下文膨胀、token浪费、性能下降等核心痛点
  • 提供可落地的五大优化策略,适用于主流框架
  • 具有广泛实用价值,适用于Claude Code、LangChain、LangGraph、Dify、AgentScope等
Trigger Precision90/100

Highlights

  • 触发词精准完整,覆盖多种变体,边界清晰
  • description明确描述功能场景,适用框架列举清晰
Structure and Standards95/100

Highlights

  • Phase/步骤清晰,有出口条件,含端到端示例
  • frontmatter完整,单文件≤500行
  • 结构完整,包含诊断流程、五大策略工具箱、快速问卷、输出格式等
Execution Reliability90/100

Highlights

  • 工具来源明确,参数正确,覆盖主要异常
  • 不可逆操作有确认机制
  • 提供具体代码模板和操作步骤,可靠性高
Evidence Verifiability (mean of the first four)93/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.