SuperClaude框架打造多模式Claude工作流,提升AI开发效率

60 阅读12分钟开源

框架概述

SuperClaude 是一个基于 Claude(Anthropic 提供的 LLM)构建的开源工作流框架。它通过 Markdown 编写的 commandsagentsmodes 三类资产,将行为指令、角色设定和响应风格以系统提示的形式注入模型,实现高度可组合、可复用的 AI 辅助开发流程。框架核心提供了动态加载、会话记忆、历史保存与恢复等能力,适用于从需求脑暴到代码实现、从安全审计到业务策划的全链路任务。

环境准备

import subprocess, sys, os, json, textwrap, time
from pathlib import Path

def _pip(pkg):
    subprocess.run([sys.executable, "-m", "pip", "install", "-q", pkg], check=True)

for mod, pkg in [("anthropic", "anthropic>=0.40.0"), ("rich", "rich")]:
    try:
        __import__(mod)
    except ImportError:
        _pip(pkg)
  1. 克隆仓库git clone --depth 1 https://github.com/SuperClaude-Org/SuperClaude_Framework.git
  2. 配置 API Key:从环境变量 ANTHROPIC_API_KEY 读取,若缺失将在 Colab/本地交互式输入。
  3. 初始化客户端client = Anthropic(),默认模型 claude-sonnet-4-5

资产发现与加载

def discover_assets(root: Path) -> dict:
    """遍历仓库,将 .md 文件按文件夹划分到 commands、agents、modes 三个桶中。"""
    buckets = {"commands": {}, "agents": {}, "modes": {}}
    for md in root.rglob("*.md"):
        rel = str(md.relative_to(root)).lower().replace("\\", "/")
        name = md.stem.lower()
        if "/commands/" in f"/{rel}":
            buckets["commands"].setdefault(name, md)
        elif "/agents/" in f"/{rel}":
            buckets["agents"].setdefault(name, md)
        elif "/modes/" in f"/{rel}" or "mode" in name:
            buckets["modes"].setdefault(name, md)
    return buckets

ASSETS = discover_assets(Path("/content/SuperClaude_Framework"))

运行后可通过 show_inventory() 查看每类资产的数量与名称,帮助快速定位所需指令。

核心类实现

class SuperClaude:
    """包装 Anthropic API,自动拼装系统提示并维护会话历史。"""
    BASE_SYSTEM = """You are operating inside the SuperClaude Framework …"""
    def __init__(self, model="claude-sonnet-4-5"):
        self.model, self.history = model, []
    def _load(self, kind, name):
        p = ASSETS[kind].get(name.lower())
        return p.read_text(encoding="utf-8") if p else f"# {kind}:{name} (not found)"
    def _system(self, command=None, agent=None, modes=None, extra=None):
        parts = [self.BASE_SYSTEM, ""]
        if command: parts += [f"## Command /sc:{command}", self._load("commands", command)]
        if agent:   parts += [f"## Agent {agent}", self._load("agents", agent)]
        for m in (modes or []):
            parts += [f"## Mode {m}", self._load("modes", m)]
        if extra: parts += ["## Extra directives", extra]
        parts.append("")
        return "

".join(parts)
    def run(self, prompt, *, command=None, agent=None, modes=None, extra=None, max_tokens=1800, stream=True, remember=True):
        sys_prompt = self._system(command, agent, modes, extra)
        msgs = self.history + [{"role": "user", "content": prompt}]
        # 省略流式实现细节,仅保留核心调用
        try:
            resp = client.messages.create(model=self.model, max_tokens=max_tokens, system=sys_prompt, messages=msgs)
            text = "".join(b.text for b in resp.content if b.type == "text")
        except Exception as e:
            text = f"API error: {e}"
        if remember:
            self.history += [{"role": "user", "content": prompt}, {"role": "assistant", "content": text}]
        return text
    def save(self, path="/content/sc_session.json", note=""):
        Path(path).write_text(json.dumps({"meta": {"note": note, "model": self.model}, "history": self.history}, indent=2))
    def load(self, path="/content/sc_session.json"):
        d = json.loads(Path(path).read_text())
        self.history = d["history"]

该类实现了 指令/代理/模式 的组合注入、会话记忆 自动累积以及 持久化save / load)功能,满足长期项目的迭代需求。

实战工作流示例

sc = SuperClaude()
# 1. 需求脑暴
sc.run(
    "为大学生设计一款个人理财 APP,给出目标用户、核心功能、差异化竞争点和 MVP 切分。",
    command="brainstorm",
    modes=["brainstorming"],
    max_tokens=1200,
    remember=False,
)
# 2. 前端实现
sc.run(
    "实现一个 React+TypeScript 组件 BudgetRing,渲染月度支出环形图,使用 Tailwind,无第三方图表库。",
    command="implement",
    agent="frontend-architect",
    max_tokens=2000,
    remember=False,
)
# 3. 安全审计
sc.run(
    "审查以下 Flask 登录代码的安全风险并给出修复建议。",
    command="analyze",
    agent="security-engineer",
    max_tokens=1500,
    remember=False,
)
# 4. 商业策划
sc.run(
    "为医疗合规 SaaS 项目制定定位、ICP、GTM、风险与里程碑。",
    command="business-panel",
    max_tokens=1800,
    remember=False,
)
# 5. 深度研究规划
sc.run(
    "主题:2026 年向量数据库现状。给出研究路线、关键来源、可信度阈值以及未解问题。",
    command="research",
    modes=["deep-research"],
    max_tokens=2000,
    remember=False,
)

每一步都通过不同的 commandagentmode 引导 Claude 产生专业化输出,展示了框架在 脑暴、实现、审计、策划、研究 等多场景的通用性。

多步骤会话与持久化

sc.run("项目:GitHub 仓库摘要 CLI 工具。先进行范围脑暴。", command="brainstorm", max_tokens=900)
sc.run("设计系统架构:模块划分、数据流、关键依赖。", command="design", max_tokens=1100)
sc.run("实现核心函数 summarize_repo(url) ,仅使用标准库。", command="implement", max_tokens=1500)
sc.run("为上述函数生成 pytest 测试,全部 mock 网络。", command="test", max_tokens=900)
sc.run("编写完整 README,包含安装、使用示例、限制。", command="document", max_tokens=900)
sc.save(note="repo-summarizer-cli 完整工作流")

通过 saveload,开发者可以在不同会话之间无缝切换,避免上下文丢失,极大提升了 长程协作 的可操作性。

小结与后续扩展

  • 指令化 Prompt:将业务逻辑抽象为 Markdown 文件,复用性强。
  • 角色感知:Agent 为 Claude 注入特定专业背景(前端、后端、安全等)。
  • 模式切换:Mode 控制输出风格,如「深度研究」或「令牌高效」模式。
  • 会话记忆:历史自动累积,支持跨步骤上下文。
  • 持久化save/load 让项目可长期追踪。

未来可进一步扩展:

  1. 自定义 CommandAgent 打包为 pip 包,供团队内部复用;
  2. 接入 多模型路由(Claude + Gemini),实现任务级别的模型选择;
  3. 引入 向量检索(RAG)模块,为长文档提供上下文增强。

关键要点:SuperClaude 将结构化 Prompt 与 LLM 能力深度结合,提供了“一键式”从概念到代码的完整 AI 开发流水线,是面向企业与个人开发者的实用工具。

本文是对第三方新闻源的主观解读。消息可能出现过时、不准确、歧义或错误的地方,仅供参考使用。点击此处查看消息源。