Skip to main content

Structured LLM task runner with schema validation, confidence scoring, and subagent orchestration

Project description

Cognitive Modules

CI PyPI version Python 3.9+ License: MIT

可验证的结构化 AI 任务规范

Cognitive Modules 是一种 AI 任务定义规范,专为需要强约束、可验证、可审计的生成任务设计。

特性

  • 强类型契约 - JSON Schema 双向验证输入输出
  • 可解释输出 - 强制输出 confidence + rationale
  • 子代理编排 - @call:module 支持模块间调用
  • 参数传递 - $ARGUMENTS 运行时替换
  • 多 LLM 支持 - OpenAI / Anthropic / MiniMax / Ollama
  • 公共注册表 - cog install registry:module-name

安装

# 基础安装
pip install cognitive-modules

# 带 LLM 支持
pip install cognitive-modules[openai]      # OpenAI
pip install cognitive-modules[anthropic]   # Claude
pip install cognitive-modules[all]         # 全部

快速开始

# 配置 LLM
export LLM_PROVIDER=openai
export OPENAI_API_KEY=sk-xxx

# 或使用 MiniMax
export LLM_PROVIDER=minimax
export MINIMAX_API_KEY=sk-xxx

# 运行代码审查
cog run code-reviewer --args "def login(u,p): return db.query(f'SELECT * FROM users WHERE name={u}')" --pretty

# 运行任务排序
cog run task-prioritizer --args "修复bug(紧急), 写文档, 优化性能" --pretty

# 运行 API 设计
cog run api-designer --args "用户系统 CRUD API" --pretty

与 Skills 对比

Skills Cognitive Modules
定位 轻量指令扩展 可验证的结构化任务
输入校验 ✅ JSON Schema
输出校验 ✅ JSON Schema
置信度 ✅ 必须 0-1
推理过程 ✅ 必须 rationale
参数传递 ✅ $ARGUMENTS ✅ $ARGUMENTS
子代理 ✅ context: fork ✅ @call + context
验证工具 ✅ cog validate
注册表 ✅ cog install

CLI 命令

# 模块管理
cog list                    # 列出已安装模块
cog info <module>           # 查看模块详情
cog validate <module>       # 验证模块结构

# 运行模块
cog run <module> input.json -o output.json --pretty
cog run <module> --args "需求描述" --pretty
cog run <module> --args "需求" --subagent  # 启用子代理

# 创建模块
cog init <name> -d "描述"

# 安装/卸载
cog install github:user/repo/path
cog install registry:module-name
cog uninstall <module>

# 注册表
cog registry                # 查看公共模块
cog search <query>          # 搜索模块

# 环境检查
cog doctor

内置模块

模块 功能 示例
code-reviewer 代码审查 cog run code-reviewer --args "你的代码"
code-simplifier 代码简化 cog run code-simplifier --args "复杂代码"
task-prioritizer 任务优先级排序 cog run task-prioritizer --args "任务1,任务2"
api-designer REST API 设计 cog run api-designer --args "订单系统"
ui-spec-generator UI 规范生成 cog run ui-spec-generator --args "电商首页"
product-analyzer 产品分析(子代理示例) cog run product-analyzer --args "健康产品" -s

模块格式

新格式(推荐)

my-module/
├── MODULE.md       # 元数据 + 指令
├── schema.json     # 输入输出 Schema
└── examples/
    ├── input.json
    └── output.json

MODULE.md

---
name: my-module
version: 1.0.0
responsibility: 一句话描述

excludes:
  - 不做的事情

constraints:
  no_network: true
  no_inventing_data: true
  require_confidence: true
  require_rationale: true

context: fork  # 可选:隔离执行
---

# 指令

根据用户需求 $ARGUMENTS 执行任务。

可以调用其他模块:
@call:other-module($ARGUMENTS)

在 AI 工具中使用

Cursor / Codex CLI

在项目根目录创建 AGENTS.md

## 代码审查

当需要审查代码时:
1. 读取 `~/.cognitive/modules/code-reviewer/MODULE.md`
2. 按 schema.json 格式输出
3. 包含 issues、summary、rationale、confidence

直接对话

读取 ~/.cognitive/modules/code-reviewer/MODULE.md,
审查这段代码:def login(u,p): ...

配置 LLM

# OpenAI
export LLM_PROVIDER=openai
export OPENAI_API_KEY=sk-xxx

# Anthropic Claude
export LLM_PROVIDER=anthropic
export ANTHROPIC_API_KEY=sk-ant-xxx

# MiniMax
export LLM_PROVIDER=minimax
export MINIMAX_API_KEY=sk-xxx

# Ollama(本地)
export LLM_PROVIDER=ollama

# 检查配置
cog doctor

创建新模块(完整流程)

code-simplifier 为例:

Step 1: 创建目录结构

mkdir -p cognitive/modules/code-simplifier

Step 2: 编写 MODULE.md

cat > cognitive/modules/code-simplifier/MODULE.md << 'EOF'
---
name: code-simplifier
version: 1.0.0
responsibility: Simplify complex code while preserving functionality

excludes:
  - Changing the code's behavior
  - Adding new features
  - Removing functionality

constraints:
  no_network: true
  no_side_effects: true
  require_confidence: true
  require_rationale: true
---

# Code Simplifier Module

You are an expert at refactoring and simplifying code.

## Input

Code to simplify: $ARGUMENTS

## Simplification Strategies

1. **Remove redundancy** - Eliminate duplicate code
2. **Improve naming** - Use clear, descriptive names
3. **Reduce nesting** - Flatten deep conditionals
4. **Simplify logic** - Use built-in functions

## Output Requirements

Return JSON containing:
- `simplified_code`: The simplified version
- `changes`: List of changes made
- `summary`: Brief description
- `rationale`: Explanation of decisions
- `confidence`: Confidence score [0-1]
EOF

Step 3: 编写 schema.json

cat > cognitive/modules/code-simplifier/schema.json << 'EOF'
{
  "$schema": "https://ziel-io.github.io/cognitive-modules/schema/v1.json",
  "input": {
    "type": "object",
    "properties": {
      "code": { "type": "string" },
      "language": { "type": "string" },
      "$ARGUMENTS": { "type": "string" }
    }
  },
  "output": {
    "type": "object",
    "required": ["simplified_code", "changes", "summary", "rationale", "confidence"],
    "properties": {
      "simplified_code": { "type": "string" },
      "changes": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "type": { "type": "string" },
            "description": { "type": "string" }
          }
        }
      },
      "summary": { "type": "string" },
      "rationale": { "type": "string" },
      "confidence": { "type": "number", "minimum": 0, "maximum": 1 }
    }
  }
}
EOF

Step 4: 验证模块

cog validate code-simplifier
cog list  # 确认模块出现在列表中

Step 5: 测试运行

cog run code-simplifier --args "def calc(x): if x > 0: if x < 10: return x * 2 else: return x else: return 0" --pretty

Step 6: 添加示例(可选)

mkdir -p cognitive/modules/code-simplifier/examples
# 添加 input.json 和 output.json 作为测试用例

模块设计要点

要素 必须 说明
name 唯一标识符,kebab-case
version 语义化版本
responsibility 一句话描述职责
excludes 明确列出不做的事
$ARGUMENTS 支持命令行参数
confidence 输出必须包含 0-1 置信度
rationale 输出必须包含推理过程
schema.json 定义输入输出契约

开发

# 克隆
git clone https://github.com/ziel-io/cognitive-modules.git
cd cognitive-modules

# 安装开发依赖
pip install -e ".[dev]"

# 运行测试
pytest tests/ -v

# 创建新模块(使用模板)
cog init my-module -d "模块描述"
cog validate my-module

项目结构

cognitive-modules/
├── src/cognitive/          # CLI 源码
│   ├── cli.py              # 命令入口
│   ├── loader.py           # 模块加载
│   ├── runner.py           # 模块执行
│   ├── subagent.py         # 子代理编排
│   ├── validator.py        # 模块验证
│   ├── registry.py         # 模块安装
│   ├── templates.py        # 模块模板
│   └── providers/          # LLM 后端
├── cognitive/modules/      # 内置模块
├── tests/                  # 单元测试
├── SPEC.md                 # 规范文档
├── INTEGRATION.md          # 集成指南
└── cognitive-registry.json # 公共注册表

文档

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cognitive_modules-0.3.0.tar.gz (32.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cognitive_modules-0.3.0-py3-none-any.whl (27.9 kB view details)

Uploaded Python 3

File details

Details for the file cognitive_modules-0.3.0.tar.gz.

File metadata

  • Download URL: cognitive_modules-0.3.0.tar.gz
  • Upload date:
  • Size: 32.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for cognitive_modules-0.3.0.tar.gz
Algorithm Hash digest
SHA256 bd436b8eabe0cb73e0df9d30c7b764c64c2ffe1a3d38be253f9d9a17ba2e304d
MD5 ccac359a5ba6fa75a7b1ac5e12e20425
BLAKE2b-256 3c008c2082093c1c6fdc63bf16a6d65d3b6e1c49f21b553183d5b78ba3939bcb

See more details on using hashes here.

File details

Details for the file cognitive_modules-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for cognitive_modules-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 61424303204799f2155c538c549d2c5b3920efee2f1b7c591c27ef3e6ef79e49
MD5 77a5ea0db2cd54c7ca00c3969cc6e688
BLAKE2b-256 6f101620434b3895d3af0078c8f8529d3b97cf2eb24e096e572c64a873e0229c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page