Skip to content

15.2 Skills 上下文管理

上下文管理概述

上下文管理是 Skills 能夠理解專案、程式碼和使用者需求的關鍵機制。本節將深入探討 Skills 如何收集、儲存、檢索和利用上下文資訊。

上下文类型

1. 项目上下文

1.1 项目结构

项目结构上下文

包含信息

  • 目錄層次結構
  • 檔案組織方式
  • 模組劃分
  • 資源位置

收集方式

  • 掃描檔案系統
  • 解析目錄結構
  • 識別關鍵目錄
  • 構建結構樹
python
### 示例

    bash


    ├── src/
    │   ├── main.py
    │   ├── utils/
    │   │   ├── helpers.py
    │   │   └── validators.py
    │   └── api/
    │       ├── routes.py
    │       └── models.py
    ├── tests/
    │   ├── test_main.py
    │   └── test_utils.py
    ├── docs/
    │   └── api.md
    ├── config/
    │   ├── settings.py
    │   └── logging.yaml
    ├── requirements.txt
    ├── setup.py
    └── README.md
    ~~~#### 1.2 技术栈

    ## 技术栈上下文
    ### 包含信息
    - 编程语言
    - 框架和库
    - 构建工具
    - 测试框架
    - 部署平台
    ### 收集方式
    - 解析依赖文件
    - 检测配置文件
    - 分析导入语句
    - 识别工具链
    ### 示例
    ~~~`yaml
    `yaml

    technology_stack:
    language: Python
    version: "3.9"
    frameworks:
     - Flask 2.3.0
     - SQLAlchemy 2.0.0
    libraries:
     - requests 2.28.0
     - numpy 1.24.0
    build_tools:
     - setuptools
     - wheel
    test_frameworks:
     - pytest 7.3.0
     - pytest-cov
    deployment:
     - Docker
     - Kubernetes

    #### 1.3 配置信息

    ## 配置上下文
    ### 包含信息
    - 应用配置
    - 环境变量
    - 构建配置
    - 部署配置
    ### 收集方式
    - 读取配置文件
    - 解析环境变量
    - 分析设置文件
    - 检测 CI/CD 配置
    ### 示例
    ~~~`python
    `python

    # config/settings.py
    class Config:
    DEBUG = False
    TESTING = False
    DATABASE_URI = os.getenv('DATABASE_URI')
    SECRET_KEY = os.getenv('SECRET_KEY')
    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')

    class DevelopmentConfig(Config):
    DEBUG = True

    class ProductionConfig(Config):
    DEBUG = False

    ### 2. 代码上下文

    #### 2.1 代码结构

    ## 代码结构上下文
    ### 包含信息
    - 模块组织
    - 类层次结构
    - 函数定义
    - 变量作用域
    ### 收集方式
    - 解析源代码
    - 构建抽象语法树(AST
    - 分析符号表
    - 追踪依赖关系
    ### 示例

    ```

    src/
    ├── main.py
    │   ├── class Application
    │   │   ├── method __init__
    │   │   ├── method run
    │   │   └── method shutdown
    │   └── function main
    ├── utils/
    │   ├── helpers.py
    │   │   ├── function format_date
    │   │   └── function validate_email
    │   └── validators.py
    │       └── class Validator
    │           ├── method validate
    │           └── method sanitize

```python

    ```> > ~~~

    #### 2.2 程式碼依賴

    ## 程式碼依賴上下文

    ### 包含資訊


    - 匯入關係
    - 函式呼叫
    - 類繼承
    - 模組引用

    ### 收集方式


    - 分析 import 語句
    - 追蹤函式呼叫
    - 解析類定義
    - 構建依賴圖

    ### 示例

    ~~~`python
    `python

    # 依賴圖

    main.py
    ├─> utils/helpers.py
    │   ├─> datetime (標準庫)
    │   └─> utils/validators.py
    │       └─> re (標準庫)
    ├─> api/routes.py
    │   ├─> flask (外部庫)
    │   └─> api/models.py
    └─> config/settings.py
    └─> os (標準庫)

    ```> >

    ~~~
    #### 2.3 代码模式

    ## 代码模式上下文
    ### 包含信息
    - 设计模式
    - 编码风格
    - 命名约定
    - 代码规范
    ### 收集方式
    - 模式识别算法
    - 风格分析
    - 命名分析
    - 规则检查
    ### 示例
    ~~~`yaml
    `yaml

    code_patterns:
    design_patterns:
     - singleton: Application
     - factory: create_validator
     - strategy: validate_input

    coding_style:
    naming_convention: snake_case
    max_line_length: 88
    docstring_style: Google

    conventions:
     - use_type_hints: true
     - include_docstrings: true
     - follow_pep8: true

    ```> > ~~~

    ### 3. 使用者上下文

    #### 3.1 使用者偏好

    ## 使用者偏好上下文

    ### 包含資訊


    - 編碼風格偏好
    - 工具使用偏好
    - 輸出格式偏好
    - 互動方式偏好

    ### 收集方式


    - 讀取使用者配置
    - 分析歷史操作
    - 收集使用者反饋
    - 學習使用模式

    ### 示例

    ~~~`yaml
    `yaml

    user_preferences:
    coding_style:
    language: Python
    style_guide: PEP8
    formatter: black
    linter: pylint

    output_preferences:
    format: markdown
    verbosity: normal
    include_code_blocks: true

    interaction_preferences:
    auto_confirm: false
    show_progress: true
    color_output: true

    ```> >

    ~~~
    #### 3.2 历史记录

    ## 历史记录上下文
    ### 包含信息
    - 执行过的命令
    - 使用过的 Skills
    - 修改过的文件
    - 生成的内容
    ### 收集方式
    - 记录操作日志
    - 追踪文件变更
    - 统计使用频率
    - 分析操作模式
    ### 示例
    ~~~`json
    `json

    {
    "history": [
    {
    "timestamp": "2024-01-15T10:30:00Z",
    "command": "claude --skill code-review --file src/main.py",
    "skill": "code-review",
    "files": ["src/main.py"],
    "result": "success"
    },
    {
    "timestamp": "2024-01-15T10:35:00Z",
    "command": "claude --skill generate-tests --file src/utils.py",
    "skill": "generate-tests",
    "files": ["src/utils.py", "tests/test_utils.py"],
    "result": "success"
    }
    ]
    }

    ```#### 3.3 學習進度

    ~~~
    markdown

    ## 學習進度上下文

    ### 包含資訊


    - 掌握的 Skills
    - 常用的功能
    - 遇到的問題
    - 改進建議

    ### 收集方式


    - 跟蹤使用情況
    - 分析錯誤模式
    - 收集反饋
    - 評估熟練度

    ### 示例

    learning_progress:
    mastered_skills:

     - code-review: 85%
     - generate-tests: 70%
     - refactor: 60%

    frequently_used:

     - code-review: 45
     - generate-tests: 30
     - format-code: 25

    common_issues:

     - type: parameter_validation

    frequency: 10
    suggestion: "使用 --help 檢視引數說明"

    improvement_suggestions:

     - "嘗試使用更多高階功能"
     - "學習自定義 Skill 開發"

    `> >

    ~~~

    ### 4. 会话上下文

    #### 4.1 对话历史

    ~~~
    markdown

    ## 对话历史上下文

    ### 包含信息


    - 用户请求
    - 系统响应
    - 执行的操作
    - 中间结果

    ### 收集方式


    - 记录对话
    - 追踪操作
    - 保存结果
    - 维护状态

    ### 示例

    {
    "conversation": [
    {
    "role": "user",
    "message": "帮我审查 src/main.py 的代码质量",
    "timestamp": "2024-01-15T10:30:00Z"
    },
    {
    "role": "assistant",
    "message": "正在执行代码审查...",
    "action": "execute_skill",
    "skill": "code-review",
    "timestamp": "2024-01-15T10:30:01Z"
    },
    {
    "role": "assistant",
    "message": "审查完成!发现 5 个问题。",
    "result": {...},
    "timestamp": "2024-01-15T10:30:15Z"
    }
    ]
    }

    `> >

    #### 4.2 執行狀態

    ~~~markdown
    markdown

    ## 執行狀態上下文

    ### 包含資訊


    - 當前任務
    - 執行進度
    - 中間結果
    - 錯誤資訊

    ### 收集方式


    - 跟蹤執行
    - 記錄進度
    - 儲存狀態
    - 捕獲錯誤

    ### 示例

    ~~~yaml

    ```yaml

    execution_state:
      current_task:
        skill: code-review
        step: 3/5
        status: in_progress

      progress:
        completed_steps:
          - analyze_structure
          - check_security
        current_step: evaluate_quality
        remaining_steps:
          - generate_report
          - save_results

      intermediate_results:
        issues_found: 3
        security_issues: 1
        quality_score: 75

      errors: []

    #### 4.3 资源状态

    ```markdown

    ## 資源狀態上下文

    ### 包含資訊

    > - 開啟的檔案
    > - 使用的工具
    > - 佔用的資源
    > - 網路連線

    ### 收集方式

    > - 監控資源
    > - 追蹤連線
    > - 統計使用
    > - 檢測洩漏

    ### 示例

    ~~~yaml

    ```yaml

    resource_state:
      open_files:
        - src/main.py
        - src/utils.py
        - tests/test_main.py

      active_tools:
        - read_file
        - search_codebase
        - run_command

      resource_usage:
        memory: "256MB"
        cpu: "15%"
        disk_io: "10MB/s"

      network_connections:
        - type: mcp
          server: github
          status: connected

    ## 上下文收集

    ### 收集策略

    #### 1. 按需收集

    ## 按需收集策略
    ### 原则
    - 只收集需要的上下文
    - 避免不必要的开销
    - 动态调整收集范围
    ### 实现方式
    - 分析 Skill 需求
    - 识别必需的上下文
    - 延迟加载非关键上下文
    - 按需扩展收集范围
    ### 示例
    ~~~`python
    `python

    def collect_context(skill_name, parameters):
     # 分析 Skill 需求
    requirements = analyze_skill_requirements(skill_name)

     # 收集必需的上下文
    context = {}
    for req in requirements.required:
    context[req] = collect_required_context(req)

     # 延迟加载可选上下文
    for req in requirements.optional:
    if should_collect(req, parameters):
    context[req] = collect_optional_context(req)

    return context

    ```> >

    ~~~

    #### 2. 增量收集

    ## 增量收集策略

    ### 原則


    - 基於已有上下文
    - 只收集變更部分
    - 減少重複工作

    ### 實現方式


    - 維護上下文快照
    - 檢測變更
    - 只更新變更部分
    - 複用未變更部分

    ### 示例

    ~~~`python
    `python

    def incremental_collect(previous_context, changes):
    new_context = previous_context.copy()

    for change in changes:
    if change.type == "file_modified":

     # 只更新變更的檔案

    new_context["code"][change.file] = analyze_file(change.file)
    elif change.type == "file_added":

     # 新增新檔案

    new_context["code"][change.file] = analyze_file(change.file)
    elif change.type == "file_deleted":

     # 刪除檔案

    del new_context["code"][change.file]

    return new_context

    ```> > ~~~

    #### 3. 并行收集

    ## 并行收集策略
    ### 原则
    - 同时收集多个上下文
    - 提高收集效率
    - 合理分配资源
    ### 实现方式
    - 识别独立任务
    - 并行执行
    - 合并结果
    - 处理依赖关系
    ### 示例
    ~~~`python
    `python

    async def parallel_collect(context_types):
    tasks = []

     # 创建并行任务
    for ctx_type in context_types:
    if is_independent(ctx_type):
    task = asyncio.create_task(collect_context(ctx_type))
    tasks.append(task)

     # 等待所有任务完成
    results = await asyncio.gather(*tasks)

     # 合并结果
    context = merge_results(results)
    return context

    ```> >

    ~~~

    ### 收集最佳化

    #### 1. 快取機制

    ## 快取機制

    ### 快取策略


    - 記憶體快取(快速訪問)
    - 磁碟快取(持久化)
    - 分散式快取(多節點)

    ### 快取鍵


    - 上下文型別
    - 檔案路徑
    - 時間戳
    - 版本號

    ### 快取失效


    - 檔案變更
    - 配置更新
    - 時間過期
    - 手動清除

    ### 示例

    ~~~`python
    `python

    class ContextCache:
    def __init__(self):
    self.memory_cache = {}
    self.disk_cache = DiskCache()

    def get(self, key):

     # 先查記憶體快取

    if key in self.memory_cache:
    return self.memory_cache[key]

     # 再查磁碟快取

    value = self.disk_cache.get(key)
    if value:
    self.memory_cache[key] = value
    return value

    return None

    def set(self, key, value, ttl=3600):

     # 設定記憶體快取

    self.memory_cache[key] = value

     # 設定磁碟快取

    self.disk_cache.set(key, value, ttl)

    ```> > ~~~

    #### 2. 智能过滤

    ## 智能过滤
    ### 过滤策略
    - 相关性分析
    - 重要性评分
    - 优先级排序
    - 数量限制
    ### 过滤维度
    - 文件类型
    - 代码复杂度
    - 修改频率
    - 使用频率
    ### 示例
    ~~~`python
    `python

    def filter_context(context, requirements):
    filtered = {}

     # 按相关性过滤
    for item in context.items():
    relevance = calculate_relevance(item, requirements)
    if relevance > threshold:
    filtered[item.key] = item.value

     # 按重要性排序
    sorted_items = sort_by_importance(filtered)

     # 限制数量
    limited = limit_items(sorted_items, max_items)

    return limited

    ```> >

    ~~~

    #### 3. 壓縮技術

    ## 壓縮技術

    ### 壓縮策略


    - 摘要壓縮
    - 去重壓縮
    - 結構壓縮
    - 演算法壓縮

    ### 壓縮方法


    - 提取關鍵資訊
    - 移除冗餘資料
    - 簡化結構
    - 使用壓縮演算法

    ### 示例

    ~~~`python
    `python

    def compress_context(context):
    compressed = {}

    for key, value in context.items():

     # 摘要壓縮

    if is_large(value):
    compressed[key] = summarize(value)

     # 去重壓縮

    elif has_duplicates(value):
    compressed[key] = deduplicate(value)

     # 結構壓縮

    else:
    compressed[key] = simplify_structure(value)

    return compressed

    ```## 上下文存储

    ### 存储结构

    #### 1. 层次结构

    ~~~
    markdown

    ## 层次存储结构

    ### 存储层次

    ### 存储策略
    - 热数据存内存
    - 温数据存磁盘
    - 冷数据存远程

    ### 示例
    Context Storage
    ├── Memory Layer
    │   ├── Current Session
    │   ├── Active Skills
    │   └── Frequently Used
    ├── Disk Layer
    │   ├── Project Context
    │   ├── User Preferences
    │   └── Historical Data
    └── Remote Layer
    │   ├── Backup Data
    │   ├── Shared Context
    │   └── Archive Data

    `````> >

    ~~~

    #### 2. 索引结构

    ~~~markdown
    markdown

    ## 索引结构

    ### 索引类型


    - 文件索引
    - 符号索引
    - 依赖索引
    - 时间索引

    ### 索引优化


    - B+ 树索引
    - 哈希索引
    - 全文索引
    - 倒排索引

    ### 示例

    class ContextIndex:
    def __init__(self):
    self.file_index = BPlusTree()
    self.symbol_index = HashIndex()
    self.dependency_index = GraphIndex()
    self.time_index = TimeSeriesIndex()

    def add(self, context_item):

     # 添加到多个索引

    self.file_index.add(context_item.path, context_item)
    self.symbol_index.add(context_item.symbols, context_item)
    self.dependency_index.add(context_item.dependencies, context_item)
    self.time_index.add(context_item.timestamp, context_item)

    def query(self, query):

     # 组合查询

    results = []
    if query.path:
    results.extend(self.file_index.query(query.path))
    if query.symbols:
    results.extend(self.symbol_index.query(query.symbols))
    return deduplicate(results)

    ~~~

    #### 2. 版本控制

    ~~~markdown
    markdown

    ## 版本控制

    ### 版本策略


    - 时间戳版本
    - 增量版本
    - 标签版本
    - 分支版本

    ### 版本操作


    - 创建版本
    - 切换版本
    - 比较版本
    - 合并版本

    ### 示例

    class ContextVersionManager:
    def __init__(self):
    self.versions = {}
    self.current_version = None

    def create_version(self, label=None):
    version = {
    "id": generate_id(),
    "timestamp": datetime.now(),
    "label": label,
    "context": copy.deepcopy(self.current_context)
    }
    self.versions[version["id"]] = version
    self.current_version = version["id"]
    return version["id"]

    def switch_version(self, version_id):
    if version_id in self.versions:
    self.current_version = version_id
    self.current_context = copy.deepcopy(self.versions[version_id]["context"])
    return True
    return False

    ~~~

    #### 2. 模糊检索

    ~~~markdown
    markdown

    ## 模糊检索

    ### 检索方式


    - 模糊匹配
    - 相似度检索
    - 语义检索
    - 关联检索

    ### 示例

    def fuzzy_retrieve(context, query):
    results = []

    for item in context.items():

     # 计算相似度

    similarity = calculate_similarity(item, query)
    if similarity > threshold:
    results.append((item, similarity))

     # 按相似度排序

    results.sort(key=lambda x: x[1], reverse=True)

    return [item for item, _ in results]

    #### 3. 组合检索

    ~~~
    markdown

    ## 组合检索

    ### 检索方式


    - 多条件组合
    - 逻辑运算
    - 权重组合
    - 分级检索

    ### 示例

    ~~~python

    ## 預計算

    ### 預計算內容

    > - 統計資訊
    > - 關聯關係
    > - 索引資料
    > - 聚合結果

    ### 預計算時機

    > - 上下文更新時
    > - 定期批處理
    > - 按需觸發

    ### 示例

    ~~~python

    ```python

    def precompute_context(context):
        # 计算统计信息
        stats = calculate_statistics(context)
        context.statistics = stats

        # 计算关联关系
        relations = calculate_relations(context)
        context.relations = relations

        # 构建索引
        index = build_index(context)
        context.index = index

    ```> >

    #### 2. 查詢最佳化

    ~~~`markdown
    `markdown

    ## 查詢最佳化

    ### 最佳化策略

    > - 查詢重寫
    > - 執行計劃最佳化
    > - 索引選擇
    > - 結果快取

    ### 示例

    ~~~python

    ```python

    def optimize_query(query, context):
        # 查询重写
        optimized = rewrite_query(query)

        # 选择最佳索引
        best_index = select_best_index(optimized, context.indexes)

        # 生成执行计划
        plan = generate_execution_plan(optimized, best_index)

        return plan


    ## 總結

    Skills 的上下文管理是一個複雜而精密的系統,涉及多種上下文型別、收集策略、儲存機制和檢索方法。有效的上下文管理能夠:

    1. **提高準確性**:提供更準確的上下文資訊
    2. **提升效能**:最佳化上下文收集和檢索效率
    3. **增強體驗**:提供更流暢的使用者體驗
    4. **支援擴充套件**:為功能擴充套件提供基礎

    在下一節中,我們將探討 Skills 與主代理的互動機制,瞭解 Skills 如何與主代理協同工作。

    ~~~

基于 MIT 许可发布 | 永久导航