Skip to content

mytk2012/python_agent

Repository files navigation

AI Agent Framework (Python Version)

基于 Python 的 AI 智能体框架,支持多种开发模式和高并发架构。


目录


特性

核心功能

  • 双开发模式支持

    • AgentScope SDK 模式:基于阿里开源 AgentScope 的多智能体框架集成
      • 支持多种 LLM 提供商(DashScope/Qwen, OpenAI, Anthropic, Ollama, Gemini)
      • 支持 ReActAgent 智能体模式
      • 支持流式输出和工具调用
      • 支持 MCP (Model Context Protocol)
    • 自有 Agent 模式:基于本框架的自有编排逻辑
      • 三种 Loop 架构可选(Ralph/ReAct/Plan-Execute)
      • 智能路由(TaskRouter、ToolSelector)
  • 多种 Loop 架构

    • Ralph Loop:强制循环与自动化反馈范式
      • Stop Hook:拦截过早退出,强制继续迭代
      • 外部记忆:文件系统作为客观记忆
      • 验证标准:预设客观验证(如测试通过)
      • 无人值守自修正迭代
    • ReAct Loop:文本解析的推理-行动-观察模式(显式推理过程)
    • Plan-and-Execute Loop:三阶段规划-执行-综合架构(复杂任务)
  • 统一工具管理

    • 内置工具(静态注册):
      • 文件工具:读取、写入、追加、列表、存在检查、删除、创建目录、信息获取
      • Bash 工具:命令执行
      • HTTP 工具:GET、POST、PUT、DELETE 请求
      • 编辑工具:字符串替换、行插入、行删除、追加行
      • 搜索工具:glob 文件匹配、grep 内容搜索
      • 联网工具:Tavily 搜索、URL 内容提取
      • 文档工具:PDF、DOCX 加载(DocumentParserRegistry)
    • Skills 工具:动态加载
    • MCP 工具:Model Context Protocol 标准化接入
      • 支持传输协议:stdio、sse、websocket
      • 支持工具注册方式:装饰器注册、YAML 配置、API 注册
    • A2A 协议:Agent-to-Agent 协议支持跨智能体通信
  • Skills 系统

    • 基于 SKILL.md 文件的模块化能力扩展
    • 支持动态加载和热更新
    • 渐进式指令披露
  • 智能路由系统

    • TaskRouter:根据用户输入自动选择 LoopType
    • ToolSelector:根据用户输入智能选择相关工具
    • 支持任务复杂度评估和工具类别匹配
  • 智能体集成层

    • AgentIntegration:整合所有模块的完整执行流程
    • 自动任务路由和工具选择
    • 权限控制、Hooks、评测集成
    • 速率限制和并发控制
    • 统一的执行追踪和统计

模型服务

  • LLM 服务

    • 多 Provider 支持(OpenAI、Anthropic、LangChain)
    • LiteLLM Proxy 集成(统一监控、限流、成本追踪)
    • 流式响应支持
  • Embedding 服务

    • 支持多种 Embedding 模型
    • Xinference/vLLM 本地部署兼容
  • Reranker 服务

    • 本地 CrossEncoder Reranker
    • OpenAI 兼容 Rerank API

高并发与可扩展

  • 高并发架构

    • 内存队列和 Redis 队列双模式支持
    • 连接池管理
    • 令牌桶限流
    • 并发执行器(支持优先级、超时、重试)
  • WebSocket 实时通信

    • 流式响应支持
    • 实时状态推送
    • 连接认证机制
  • 多智能体协作

    • 主从模式(Master-Slave)
    • 对等模式(Peer-to-Peer)
    • 层次模式(Hierarchical)
    • 群体模式(Swarm)
    • 消息总线(MessageBus)支持异步消息传递
    • 协作策略:TaskResult, TaskStatus, AgentRole, CollaborationStrategy

可观测性

  • 日志系统

    • 基于 Loguru 的结构化日志
    • 支持日志级别配置
    • 审计日志服务
  • 分布式追踪

    • OpenTelemetry 集成
    • 支持 OTLP 导出
    • 请求链路追踪

安全特性

  • API Key 认证
  • 请求限流
  • 审计日志
  • 权限控制系统
    • 多级权限模式(PermissionMode)
    • 路径规则(PathRule)
    • 命令过滤

钩子系统

  • 生命周期钩子
    • SESSION_START:会话开始
    • SESSION_END:会话结束
    • PRE_TOOL_USE:工具执行前
    • POST_TOOL_USE:工具执行后
  • 钩子类型
    • CommandHook:执行 shell 命令
    • HttpHook:发送 HTTP 请求
    • PromptHook:使用 LLM 验证条件
    • AgentHook:使用 Agent 进行深度验证

分屏后端系统(Swarm)

  • 多智能体终端分屏可视化
    • SubprocessBackend:子进程后端(无分屏)
    • TmuxBackend:tmux 终端分屏
    • InProcessBackend:进程内后端
    • 支持后端自动检测和切换

记忆与上下文

  • 分层记忆架构

    • 工作记忆(短期):InMemoryWorkingMemory、RedisWorkingMemory
    • 长期记忆:AgentControlledMemory、VectorLongTermMemory
    • 记忆压缩:MemoryCompressor(支持摘要压缩)
    • 统一服务:UnifiedMemoryService
  • 上下文服务

    • 对话历史管理
    • 自动上下文压缩
    • 最大历史长度控制
    • 最大上下文窗口控制
    • ContextStats 统计信息

RAG 能力

RAG 模块是一个支持多知识库动态管理的检索增强生成系统。

  • 多知识库管理

    • 单例管理器 + 多实例设计,支持同时管理多个独立的知识库
    • 动态注册/删除:运行时动态创建、更新、删除知识库
    • 知识库配置持久化(JSON 格式)
  • 向量存储

    • Weaviate 向量数据库集成(主要)
    • Milvus 可选支持
    • Elasticsearch 全文搜索
    • Redis 辅助存储
  • 文档处理

    • PDF 文档解析
    • Word 文档处理
    • 自定义文档分割器(可注册扩展)
    • 自定义文档加载器(可注册扩展)
  • 检索增强

    • 纯向量检索
    • 纯关键词检索(Elasticsearch)
    • 混合检索(向量 + 全文)
    • Reranker 重排序(CrossEncoder / Cohere / OpenAI 兼容)
  • LLM 上下文构建

    • 内置上下文模板
    • 可注册自定义上下文构建器
    • 支持 RAG Pipeline 流式调用
  • RAG Pipeline

    • run_rag_pipeline: 完整 RAG 流程(检索 + 生成)
    • retrieve_only: 仅检索不生成

评估系统

框架提供完整的智能体能力评估系统:

  • 评估框架核心

    • EvalTask:评估任务定义(输入、预期输出、里程碑)
    • SolutionOutput:解决方案输出格式
    • TrajectoryStep:执行轨迹步骤记录
    • EvaluationResult:评估结果结构
  • 评估器

    • GeneralEvaluator:通用评估器
    • ParallelEvaluator:并行评估器(支持并发执行)
  • 评估指标

    • 准确性指标:ExactMatchMetric, ContainsMetric, AccuracyMetric
    • 效率指标:TokenEfficiencyMetric, TimeEfficiencyMetric
    • 轨迹指标:ProcessAccuracyMetric, ToolUseMetric
    • 正确性指标:ResultCorrectnessMetric, ProcessCorrectnessMetric, ToolSelectionMetric, ToolExecutionMetric, ConversationQualityMetric
  • 基准测试

    • BenchmarkBase:基准测试基类
    • JSONLBenchmark:JSONL 格式数据集加载
    • DatasetManager:数据集管理器
    • 内置数据集:工具使用、推理、多步骤任务、对话
  • 存储与报告

    • FileEvaluatorStorage:文件存储后端
    • ReportGenerator:Markdown 报告生成

接口与工具

  • REST API:完整的 FastAPI Web API
  • WebSocket API:实时通信接口
  • CLI 工具:命令行交互界面
  • TUI 界面:基于 Textual 的终端用户界面
  • Audit 日志:审计日志服务

快速开始

安装依赖

推荐使用 uv 进行依赖管理:

# 安装 uv(如果尚未安装)
curl -LsSf https://astral.sh/uv/install.sh | sh

# 同步核心依赖(创建虚拟环境并安装所有依赖)
uv sync

# 安装开发依赖
uv sync --extra dev

# 安装可选功能
uv sync --extra tui             # Terminal UI (Textual-based TUI)
uv sync --extra reranker        # 本地 CrossEncoder Reranker
uv sync --extra cohere-rerank   # Cohere Reranker API
uv sync --extra milvus          # Milvus 向量数据库
uv sync --extra doc-extended    # 扩展文档处理 (pdfplumber, xlsx 等)
uv sync --extra skills          # Skills 相关依赖 (网页爬取等)

# 安装所有可选功能
uv sync --extra all

或者使用 pip:

pip install -e .

配置环境变量

# 仓库已包含 .env 文件,可直接修改配置
# 编辑 .env 文件,配置你的 API 密钥

使用 Application Factory (推荐)

Application Factory 提供统一的入口,支持多种运行模式。配置会自动从 .env 文件加载:

import asyncio
from products import Application, AppMode

async def main():
    # 创建应用(库模式)- 配置自动从 .env 加载
    app = Application.from_config(mode=AppMode.LIBRARY)

    await app.initialize()

    # 聊天
    result = await app.chat("你好,请介绍一下自己")
    print(result['response'])

    await app.stop()

asyncio.run(main())

你也可以覆盖特定配置:

# 覆盖 .env 中的配置
app = Application.from_config(
    mode=AppMode.LIBRARY,
    llm_model="gpt-4o-mini",  # 覆盖 LLM_MODEL
    app_name="my-assistant",   # 覆盖 APP_NAME
)

命令行启动服务

# CLI 交互模式
uv run python -m products --chat

# Terminal UI 模式 (Textual-based TUI)
uv run python -m products --tui

# REST API 服务
uv run python -m products --serve

# WebSocket 服务
uv run python -m products --websocket

# 同时启动 Web + WebSocket
uv run python -m products --both

# 库模式(无服务器,用于嵌入)
uv run python -m products --library

# 查看帮助
uv run python -m products --help

# 查看版本
uv run python -m products --version

架构设计

十一层架构

┌─────────────────────────────────────────────────────────────┐
│              第0层:产品层 (Products)                        │
│  Application | CLI | Web | WebSocket | Library              │
│  统一应用入口、命令行启动、服务启动、库模式                    │
├─────────────────────────────────────────────────────────────┤
│              第一层:接口层 (Interface)                      │
│  Web (FastAPI) | WebSocket | CLI | CLI-TUI | Audit          │
│  对外服务接口、实时通信、命令行工具、TUI界面、审计日志         │
├─────────────────────────────────────────────────────────────┤
│              第二层:编排层 (Orchestration)                   │
│  Agent | Loops | Multi-Agent | Router                       │
│  智能体编排、循环控制、多智能体协调、智能路由                  │
├─────────────────────────────────────────────────────────────┤
│              第三层:SDK适配层 (Agent SDK)                    │
│  AgentScope Adapter | Base Adapter                           │
│  外部 Agent SDK 集成(AgentScope 等)                        │
├─────────────────────────────────────────────────────────────┤
│              第四层:智能体集成层 (Integrate)                 │
│  AgentIntegration | TaskRouter | ToolSelector               │
│  整合所有模块、完整执行流程、权限控制、Hooks、评测            │
├─────────────────────────────────────────────────────────────┤
│              第五层:能力层 (Capabilities)                    │
│  Skills系统 | 工具注册中心 | 内置工具 | MCP | A2A             │
│  模块化能力、工具管理、协议对接                               │
├─────────────────────────────────────────────────────────────┤
│              第六层:模型服务层 (Model Services)              │
│  LLM服务 | Embedding服务 | Reranker服务                       │
│  大模型调用、向量嵌入、重排序                                 │
├─────────────────────────────────────────────────────────────┤
│              第七层:状态管理层 (State Management)            │
│  Context服务 | Memory服务 (分层记忆)                          │
│  上下文管理、记忆存储                                         │
├─────────────────────────────────────────────────────────────┤
│              第八层:RAG模块 (RAG)                            │
│  检索 | 向量存储 | 文档处理 | 知识库管理                       │
│  检索增强生成、知识库                                         │
├─────────────────────────────────────────────────────────────┤
│              第九层:评估层 (Evaluation)                      │
│  评估器 | 指标系统 | 基准测试 | 数据集 | 报告生成              │
│  智能体能力评估、性能测试                                     │
├─────────────────────────────────────────────────────────────┤
│              第十层:基础层 (Foundation)                      │
│  配置管理 | 日志监控 | 队列 | 连接池 | 限流 | 追踪 | 错误处理  │
│  钩子系统 | 权限控制 | 分屏后端                                │
│  配置、监控、并发控制、生命周期管理                            │
└─────────────────────────────────────────────────────────────┘

层次说明

层次 目录 职责
Products products/ 统一应用入口(Application、CLI、Web、WebSocket、Library)
Interface interface/ 对外暴露接口(Web、WebSocket、CLI、CLI-TUI、Audit)
Orchestration orchestration/ Agent 核心逻辑和编排、智能路由
Agent SDK agent_sdk/ 外部 SDK 集成适配层(AgentScope 等)
Integrate integrate/ 智能体集成层,整合所有模块的完整执行流程
Capabilities capabilities/ 功能扩展(工具、技能、MCP、A2A)
Model Services model_services/ 外部模型服务集成
State Management state_management/ 内部状态管理(分层记忆)
RAG rag/ 检索增强生成模块
Evaluation evaluation/ 智能体能力评估框架
Foundation foundation/ 通用基础设施(配置、日志、钩子、权限、分屏后端)

Loop 架构详解

框架提供三种不同的 Agent 执行循环模式,通过 loop_type 参数选择:

RalphLoop(默认)

基于强制循环与自动化反馈的 AI 代理运行范式,核心特点:

核心概念

  • 强制循环:通过外部控制机制构建闭环,防止 AI 过早退出
  • Stop Hook:拦截 AI 的过早退出(如"任务完成"声明),强制继续迭代
  • 外部记忆:将文件系统和执行结果作为客观的"外部记忆"
  • 验证标准:预设客观验证标准(如测试通过),直到通过才完成

工作原理

用户输入 → LLM调用 → 检查StopHook → 执行工具 → 验证命令 → 未通过则继续迭代
                    ↓
            触发时强制继续

特点

  • 无人值守自修正迭代
  • 防止 AI 过早声称"完成"
  • 客观验证替代主观判断
  • 适合自动化任务执行

使用场景:代码修复、自动化任务、需要客观验证的场景

from integrate.agent import Agent, AgentConfig, LoopType
from orchestration.loops import RalphLoopConfig, StopHook, StopHookType, VerificationCommand, ExternalMemory

# 配置 Ralph Loop
config = AgentConfig(
    name="assistant",
    loop_type=LoopType.RALPH,
)

# 可选:自定义 Ralph Loop 配置
ralph_config = RalphLoopConfig(
    max_iterations=10,
    stop_hooks=[
        StopHook(hook_type=StopHookType.EARLY_EXIT, enabled=True),
        StopHook(hook_type=StopHookType.EMPTY_RESPONSE, enabled=True),
    ],
    verification_commands=[
        VerificationCommand(command="pytest tests/", description="运行测试"),
    ],
    external_memory=ExternalMemory(memory_dir="./agent_memory", feedback_files=["./error.log"]),
)

agent = Agent(config)

ReActLoop

基于 ReAct 论文实现的文本解析循环,通过解析 Thought/Action/Observation 格式进行推理。

工作原理

用户输入 → LLM调用(无tools) → 解析Thought/Action → 执行工具 → 生成Observation → 循环

特点

  • 显式的推理过程,可解释性强
  • 不依赖 LLM 的 tool_calls 能力
  • 适合需要展示思考过程的场景

提示词格式

Thought: [思考内容]
Action: [工具名称]
Action Input: [工具参数]

# 或最终答案
Thought: [最终推理]
Answer: [最终答案]

使用场景:需要显式推理过程、调试、教育演示

agent = Agent(AgentConfig(
    name="reasoning-agent",
    loop_type=LoopType.REACT,
))

PlanAndExecuteLoop

三阶段规划执行架构,先制定计划再逐步执行。

工作原理

阶段1: 规划 → 生成步骤列表
阶段2: 执行 → 依次执行每个步骤(可动态重规划)
阶段3: 综合 → 汇总结果生成最终答案

特点

  • 结构化的任务分解
  • 支持动态重规划
  • 适合复杂多步骤任务

使用场景:复杂任务分解、项目管理、研究分析

agent = Agent(AgentConfig(
    name="planning-agent",
    loop_type=LoopType.PLAN_AND_EXECUTE,
))

Loop 类型对比

特性 RalphLoop ReActLoop PlanAndExecuteLoop
LLM调用方式 tool_calls 纯文本 混合
推理可见性 隐式 显式 显式+结构化
适合LLM类型 现代LLM 所有LLM 现代LLM
任务复杂度 简单到中等 简单到中等 复杂多步骤
可解释性 一般 最高
Stop Hook ✅ 支持 ❌ 不支持 ❌ 不支持
外部记忆 ✅ 支持 ❌ 不支持 ❌ 不支持
验证标准 ✅ 支持 ❌ 不支持 ❌ 不支持
无人值守自修正 ✅ 支持 ❌ 不支持 ✅ 部分

使用示例

Application Factory 模式(推荐)

from products import Application, AppMode, create_app

# 方式 1: 库模式(嵌入到其他应用)- 配置从 .env 加载
app = create_app(mode=AppMode.LIBRARY)
await app.initialize()
result = await app.chat("你好")

# 方式 2: CLI 模式
app = create_app(mode=AppMode.CLI)
await app.start()

# 方式 3: Web Server 模式
app = create_app(mode=AppMode.WEB_SERVER)
await app.start()

# 方式 4: WebSocket 模式
app = create_app(mode=AppMode.WEBSOCKET)
await app.start()

# 方式 5: Web + WebSocket 同时运行
app = create_app(mode=AppMode.BOTH)
await app.start()

# 方式 6: 异步上下文管理器
async with create_app(mode=AppMode.LIBRARY) as app:
    result = await app.chat("Hello")

原始 Agent API

from products import Agent, AgentConfig

# AgentConfig 会自动从 .env 加载默认值
config = AgentConfig(
    name="my-assistant",
    # 以下参数可选,不提供则从 .env 加载
    # llm_provider="openai",
    # llm_model="gpt-4o-mini",
    # api_key="sk-...",
)

agent = Agent(config)
await agent.initialize()

result = await agent.chat("你好,请介绍一下自己")
print(result['response'])

Agent SDK 适配器模式

框架支持使用 AgentScope SDK 作为底层 Agent 实现,提供更丰富的多智能体能力。

启用 AgentScope SDK

在创建 Application 时设置 use_agentscope_sdk=True

from products import Application, AppMode

# 方式 1: 使用 AgentScope SDK(推荐)
app = Application.from_config(
    mode=AppMode.LIBRARY,
    use_agentscope_sdk=True,           # 启用 AgentScope SDK
    agentscope_provider="openai",       # LLM 提供商
)

await app.initialize()
result = await app.chat("你好")
print(result['response'])

支持的 LLM 提供商

AgentScope SDK 支持以下 LLM 提供商:

Provider 说明 环境变量
openai OpenAI GPT 系列 OPENAI_API_KEY
dashscope 阿里云通义千问 DASHSCOPE_API_KEY
anthropic Anthropic Claude ANTHROPIC_API_KEY
ollama 本地 Ollama 模型 无需 API Key
gemini Google Gemini GOOGLE_API_KEY

使用模型预设配置

from products import create_agent, AgentSDK, SDKAdapterConfig, get_model_preset

# 使用预设配置(快速开始)
preset = get_model_preset("qwen-max")  # 或 "gpt-4o", "claude-3-sonnet" 等
config = SDKAdapterConfig(
    name="assistant",
    system_prompt="你是一个智能助手。",
    extra=preset,
)

agent = create_agent(sdk=AgentSDK.AGENT_SCOPE, config=config)
await agent.initialize()
result = await agent.run("你好")

自定义配置

from products import create_agent, AgentSDK, SDKAdapterConfig

config = SDKAdapterConfig(
    name="my-agent",
    model="gpt-4o",
    api_key="sk-...",
    api_url="https://api.openai.com/v1",  # 可选
    system_prompt="你是一个专业的 AI 助手。",
    extra={
        "provider": "openai",
        "stream": True,
    },
)

agent = create_agent(sdk=AgentSDK.AGENT_SCOPE, config=config)
await agent.initialize()
result = await agent.run("你好")

智能路由使用

from products import TaskRouter, ToolSelector

# 任务路由:自动选择 LoopType
router = TaskRouter()
result = router.route("请帮我分析这段代码的bug")
print(result.loop_type)  # 自动选择合适的 Loop

# 工具选择:智能匹配相关工具
selector = ToolSelector()
result = selector.select_tools("读取 config.yaml 文件")
print(result.tools)  # 返回匹配的工具列表

钩子系统使用

from products import HookRegistry, HookEvent, CommandHookDefinition

registry = HookRegistry()

# 注册工具执行前的钩子
registry.register(
    HookEvent.PRE_TOOL_USE,
    CommandHookDefinition(
        type="command",
        command="echo 'Tool about to execute: $ARGUMENTS'",
        block_on_failure=True,
    )
)

权限控制使用

from products import PermissionChecker, PermissionMode, PathRule, PermissionSettings

checker = PermissionChecker(
    mode=PermissionMode.INTERACTIVE,  # 交互模式
    settings=PermissionSettings(
        allow_read=[PathRule(path="/home/user", recursive=True)],
        allow_write=[PathRule(path="/home/user/projects", recursive=True)],
    )
)

# 检查权限
decision = checker.check_read("/home/user/data/file.txt")
print(decision)  # PermissionDecision.ALLOW / DENY / ASK

分屏后端使用

from products import detect_backend, TmuxBackend, TeammateSpawnConfig

# 自动检测可用后端
backend = detect_backend()

# 或指定后端
backend = TmuxBackend()

# 创建分屏
config = TeammateSpawnConfig(
    name="agent-1",
    command="python -m products --chat",
)
result = await backend.create_pane(config)

智能体集成使用

Integrate 模块提供完整的智能体执行流程整合:

from products import Agent, AgentConfig
from integrate import AgentIntegrationTemplate, IntegrationConfig

# 创建 Agent
agent = Agent(AgentConfig(name="smart-agent"))
await agent.initialize()

# 创建集成配置
config = IntegrationConfig()
config.auto_route = True           # 自动任务路由
config.auto_select_tools = True    # 自动工具选择
config.tracing_enabled = True      # 启用追踪
config.permission_mode = "default" # 权限模式
config.hooks_enabled = True        # 启用 Hooks
config.rate_limit_enabled = True   # 启用速率限制
config.evaluation_enabled = False  # 禁用评测

# 创建集成模板(组装功能)
integration = AgentIntegrationTemplate(
    agent=agent,
    config=config,
)
await integration.initialize()

# 执行完整流程
result = await integration.execute("帮我制定一个计划来读取文件")

# 查看路由决策
print(result.get("_integration", {}).get("loop_type"))
print(result.get("_integration", {}).get("selected_tools"))

# 获取统计信息
stats = integration.get_stats()
print(f"Plan模式次数: {stats.get('plan_mode_count', 0)}")
print(f"正常模式次数: {stats.get('normal_mode_count', 0)}")

流式执行

async for event in app.stream_execute("请分析这段代码"):
    if event["type"] == "token":
        print(event["content"], end="")
    elif event["type"] == "tool_call":
        print(f"\n调用工具: {event['tool_name']}")
    elif event["type"] == "complete":
        print(f"\n完成: {event['content']}")

评估系统使用

from products import (
    GeneralEvaluator,
    FileEvaluatorStorage,
    JSONLBenchmark,
    DatasetManager,
    EvalTask,
    SolutionOutput,
)

# 方式1: 使用数据集管理器
manager = DatasetManager()
benchmark = manager.get_dataset("tool_use")

# 方式2: 直接加载JSONL文件
benchmark = JSONLBenchmark("./evaluation/datasets/tool_use")

# 定义解决方案函数
async def my_solution(task: EvalTask) -> SolutionOutput:
    result = await agent.execute(task.input)
    return SolutionOutput.from_agent_result(result)

# 创建评估器
evaluator = GeneralEvaluator(
    name="My Evaluation",
    benchmark=benchmark,
    storage=FileEvaluatorStorage("./evaluation/results"),
)

# 运行评估
await evaluator.run(my_solution)

启动服务

# REST API 服务
uv run python -m products --serve

# WebSocket 服务
uv run python -m products --websocket

# CLI 交互模式
uv run python -m products --chat

# Terminal UI 模式
uv run python -m products --tui

# 同时启动 Web + WebSocket
uv run python -m products --both

服务将在 http://localhost:8000 启动(WebSocket 在 8001)。


应用模式说明

Application Factory 支持 5 种运行模式:

模式 说明 使用场景
LIBRARY 库模式(无服务器) 嵌入到其他应用程序
CLI 命令行交互模式 本地开发调试、快速测试
WEB_SERVER REST API 服务器 提供 HTTP API 服务
WEBSOCKET WebSocket 服务器 实时通信、流式响应
BOTH Web + WebSocket 同时运行 完整的生产环境部署

项目结构

python_agent/
├── products/                 # 产品层(统一应用入口)
│   ├── __init__.py           # 模块导出(Application, AppMode, create_app)
│   ├── __main__.py           # 命令行入口(--chat, --serve, --websocket, --library)
│   └── application.py        # Application 类(应用工厂、配置加载、Agent 管理)
├── agent_sdk/                # SDK适配层
│   ├── base.py               # 基础适配器抽象(BaseAgentAdapter, SDKAdapterConfig, AgentResult)
│   ├── __init__.py           # 模块导出和 create_agent 工厂函数
│   ├── examples.py           # 使用示例
│   └── agent_scope/          # AgentScope SDK 适配
│       ├── __init__.py       # 模块导出
│       ├── adapter.py        # AgentScopeAdapter 适配器实现
│       ├── wrapper.py        # AgentScopeWrapper(用于产品形态集成)
│       └── types.py          # 类型定义(ModelProvider, AgentType, 模型预设)
├── integrate/                # 智能体集成层
│   ├── __init__.py           # 模块导出
│   ├── agent.py              # Agent 类(整合 agent.py + template.py)
│   └── core/                 # 核心组件
│       ├── __init__.py       # 模块导出
│       ├── config.py         # IntegrationConfig, RoutingConfig, ToolSelectionConfig
│       ├── template.py       # AgentIntegrationTemplate(六阶段执行流程)
│       ├── types.py          # AgentExecutionContext, AgentExecution
│       └── multi_agent_executor.py  # 多智能体执行器
├── capabilities/             # 能力层
│   ├── __init__.py           # 模块导出
│   ├── tool_registry/        # 工具注册中心
│   │   ├── __init__.py       # 模块导出
│   │   └── tool_registry.py  # ToolRegistry, Tool, ToolResult, ToolSource
│   ├── skills/               # Skills 系统
│   │   ├── __init__.py       # 模块导出
│   │   ├── skill_loader.py   # SkillLoader, SkillInfo
│   │   └── skill_errors.py   # SkillError
│   ├── tools/                # 内置工具(静态注册)
│   │   ├── __init__.py       # 模块导出
│   │   ├── file_tools.py     # 文件工具(读、写、追加、列表等)
│   │   ├── bash_tools.py     # Bash 命令执行工具
│   │   ├── http_tools.py     # HTTP 请求工具(GET/POST/PUT/DELETE)
│   │   ├── edit_tools.py     # 文件编辑工具(替换、插入、删除行)
│   │   ├── search_tools.py   # 搜索工具(glob、grep)
│   │   ├── web_search_tools.py  # 联网搜索工具(Tavily)
│   │   └── document_tools.py # 文档加载工具(PDF、DOCX等)
│   ├── mcp/                  # MCP (Model Context Protocol)
│   │   ├── __init__.py       # 模块导出
│   │   ├── mcp_client.py     # MCP 客户端
│   │   ├── mcp_client_manager.py  # MCP 客户端管理器
│   │   ├── mcp_tool_registry.py   # MCP 工具注册表
│   │   └── mcp_types.py      # MCP 类型定义
│   └── a2a/                  # A2A (Agent-to-Agent Protocol)
│       ├── __init__.py       # 模块导出
│       ├── a2a_client.py     # A2A 客户端、A2ARemoteAgent
│       ├── a2a_client_manager.py  # A2A 客户端管理器
│       ├── a2a_formatter.py  # A2A 格式化器
│       └── a2a_types.py      # A2A 类型定义
├── config/                   # 配置目录
│   ├── application.yaml      # 应用配置
│   ├── a2a.yaml              # A2A 协议配置
│   ├── litellm.yaml          # LiteLLM Proxy 配置
│   ├── mcp.yaml              # MCP 服务器配置
│   ├── mcp_tools.yaml        # MCP 工具配置
│   ├── model.yaml            # 模型服务配置
│   ├── observability.yaml    # 可观测性配置
│   ├── rag.yaml              # RAG 配置
│   └── skills.yaml           # Skills 配置
├── evaluation/               # 评估层
│   ├── __init__.py           # 模块导出
│   ├── cli.py                # 评估 CLI
│   ├── core/                 # 评估核心
│   │   ├── __init__.py       # 模块导出
│   │   ├── base.py           # EvalTask, SolutionOutput, BenchmarkBase, EvaluationResult
│   │   ├── evaluator.py      # EvaluatorBase
│   │   ├── metric.py         # MetricBase, MetricResult, MetricType
│   │   └── storage.py        # EvaluatorStorageBase
│   ├── evaluators/           # 评估器
│   │   ├── __init__.py       # 模块导出
│   │   ├── general.py        # GeneralEvaluator
│   │   └── parallel.py       # ParallelEvaluator
│   ├── metrics/              # 评估指标
│   │   ├── __init__.py       # 模块导出
│   │   ├── accuracy.py       # ExactMatchMetric, ContainsMetric, AccuracyMetric
│   │   ├── efficiency.py     # TokenEfficiencyMetric, TimeEfficiencyMetric
│   │   ├── trajectory.py     # ProcessAccuracyMetric, ToolUseMetric
│   │   └ correctness.py    # ResultCorrectnessMetric, ProcessCorrectnessMetric 等
│   ├── benchmarks/           # 基准测试
│   │   ├── __init__.py       # 模块导出
│   │   ├── base.py           # BenchmarkBase
│   │   └ builtin/          # 内置基准测试
│   │       ├── __init__.py   # 模块导出
│   │       └ tool_use.py   # ToolUseBenchmark
│   ├── datasets/             # 数据集
│   │   ├── __init__.py       # 模块导出
│   │   ├── loader.py         # DatasetManager, JSONLBenchmark
│   │   ├── tool_use/         # 工具使用数据集
│   │   ├── reasoning/        # 推理数据集
│   │   ├── multi_step/       # 多步骤任务数据集
│   │   └ conversation/     # 对话数据集
│   ├── report/               # 报告生成
│   │   ├── __init__.py       # 模块导出
│   │   └ generator.py      # ReportGenerator
│   ├── results/              # 结果存储
│   └ storage/              # 存储后端
│       ├── __init__.py       # 模块导出
│       └ file_storage.py   # FileEvaluatorStorage
├── foundation/               # 基础层
│   ├── __init__.py           # 模块导出
│   ├── config/               # 配置管理
│   │   ├── __init__.py       # 模块导出
│   │   ├── config.py         # Config, AppConfig, ConfigMixin
│   │   └ yaml_loader.py    # YAMLConfigLoader (MCP, Skills)
│   ├── observability/        # 日志和监控
│   │   ├── __init__.py       # 模块导出
│   │   ├── logger.py         # Logger, get_logger, configure_logging
│   │   └ tracing.py        # OpenTelemetry 追踪
│   ├── queue/                # 队列(内存/Redis)
│   │   ├── __init__.py       # 模块导出
│   │   ├── i_queue.py        # IQueue 接口
│   │   ├── memory_queue.py   # MemoryQueue
│   │   └ redis_queue.py    # RedisQueue
│   ├── pool/                 # 连接池
│   │   ├── __init__.py       # 模块导出
│   │   └ connection_pool.py
│   ├── rate_limit/           # 限流器
│   │   ├── __init__.py       # 模块导出
│   │   └ rate_limiter.py   # RateLimiter (令牌桶)
│   ├── concurrency/          # 并发执行器
│   │   ├── __init__.py       # 模块导出
│   │   └ executor.py         # Executor (优先级、超时、重试)
│   ├── errors/               # 错误处理
│   │   ├── __init__.py       # 模块导出
│   │   └ agent_errors.py   # AgentError, ValidationError, ToolError 等
│   ├── middleware/           # 中间件
│   │   ├── __init__.py       # 模块导出
│   │   └ middleware.py     # Middleware, LoggingMiddleware, MetricsMiddleware
│   ├── hooks/                # 钩子系统
│   │   ├── __init__.py       # 模块导出
│   │   ├── events.py         # HookEvent
│   │   ├── types.py          # HookResult, AggregatedHookResult
│   │   ├── schemas.py        # HookDefinition (Command, Http, Prompt, Agent)
│   │   ├── registry.py       # HookRegistry
│   │   └ executor.py       # HookExecutor, HookExecutionContext
│   ├── permissions/          # 权限控制
│   │   ├── __init__.py       # 模块导出
│   │   ├── modes.py          # PermissionMode
│   │   ├── types.py          # PermissionDecision, PathRule
│   │   └ checker.py        # PermissionChecker, PermissionSettings
│   └── swarm/                # 分屏后端系统
│       ├── __init__.py       # 模块导出
│       ├── types.py          # BackendType, PaneId, TeammateSpawnConfig 等
│       └ backends.py       # BaseBackend, SubprocessBackend, TmuxBackend, InProcessBackend
├── interface/                # 接口层
│   ├── __init__.py           # 模块导出
│   ├── web/                  # Web API (FastAPI)
│   │   ├── __init__.py       # 模块导出
│   │   └ web_server.py     # WebServer
│   ├── websocket/            # WebSocket
│   │   ├── __init__.py       # 模块导出
│   │   └ ws_server.py      # WSServer
│   ├── cli/                  # CLI 工具
│   │   ├── __init__.py       # 模块导出
│   │   └ cli.py            # CLI
│   ├── cli_tui/              # CLI TUI (Textual-based)
│   │   ├── __init__.py       # 模块导出
│   │   ├── app.py            # AgentTUIApp, TUIConfig
│   │   └ protocol.py      # FrontendRequest, BackendEvent, TranscriptItem
│   └ audit/                # 审计日志
│       ├── __init__.py       # 模块导出
│       └ audit_log_service.py  # AuditLogService, AuditLogEntry
├── model_services/           # 模型服务层
│   ├── __init__.py           # 模块导出
│   ├── model_service.py      # 统一模型服务入口
│   ├── llm/                  # LLM 服务
│   │   ├── __init__.py       # 模块导出
│   │   ├── llm_service.py    # LLM 服务主类
│   │   ├── llm_types.py      # LLM 类型定义
│   │   ├── llm_errors.py     # LLM 错误类
│   │   └ providers/        # LLM Provider
│   │       ├── __init__.py   # 模块导出
│   │       ├── base_llm_provider.py  # BaseLLMProvider
│   │       └ langchain_provider.py # LangChain Provider
│   ├── embedding/            # Embedding 服务
│   │   ├── __init__.py       # 模块导出
│   │   ├── embedding_service.py
│   │   └ embedding_types.py
│   └ reranker/             # Reranker 服务
│       ├── __init__.py       # 模块导出
│       ├── reranker_service.py
│       ├── reranker_types.py
│       └ langchain_rerank.py  # LangChain Reranker 实现
├── orchestration/            # 编排层
│   ├── __init__.py           # 模块导出
│   ├── agent.py              # Agent 主类(Agent, AgentConfig, LoopType)
│   ├── loops/                # Loop 实现
│   │   ├── __init__.py       # 模块导出
│   │   ├── base_loop.py      # BaseLoop 基类
│   │   ├── ralph_loop.py     # RalphLoop (强制循环, StopHook, 外部记忆, 验证标准)
│   │   ├── react_loop.py     # ReActLoop (文本解析)
│   │   └ plan_and_execute_loop.py  # PlanAndExecuteLoop
│   ├── multi_agent/          # 多智能体协作
│   │   ├── __init__.py       # 模块导出
│   │   ├── message_bus.py    # MessageBus, AgentMessage, MessageType
│   │   └ multi_agent_coordinator.py  # MultiAgentCoordinator, Task, AgentRole
│   └── router/               # 智能路由
│       ├── __init__.py       # 模块导出
│       ├── types.py          # ToolCategory, RoutingRule, RoutingResult
│       ├── task_router.py    # TaskRouter
│       └ tool_selector.py  # ToolSelector
├── rag/                      # RAG 模块
│   ├── __init__.py           # 模块导出
│   ├── config/               # 知识库配置(KnowledgeBaseConfig, kb_registry)
│   ├── embedding/            # 向量嵌入与知识库管理
│   │   ├── __init__.py       # 模块导出
│   │   ├── core/             # 核心功能(Weaviate, ES, Redis)
│   │   └ adapters/         # 向量存储适配器
│   ├── extensions/           # 扩展功能示例
│   ├── llm/                  # RAG LLM(上下文构建器)
│   │   ├── __init__.py       # 模块导出
│   │   ├── llm.py            # RAG LLM 服务
│   │   └ context/          # 上下文模板与构建器
│   ├── retrieval/            # 检索模块(MixedRetriever, VectorRetriever)
│   ├── splitment/            # 文档分割(BaseSplitter, DocumentLoader)
│   ├── rag/                  # RAG Pipeline
│   └ utils/                # 工具函数
├── state_management/         # 状态管理层
│   ├── __init__.py           # 模块导出
│   ├── context/              # 上下文服务
│   │   ├── __init__.py       # 模块导出
│   │   ├── context_service.py  # ContextService, ContextStats
│   │    context_errors.py   # ContextError
│   └ memory/               # 分层记忆服务
│       ├── __init__.py       # 模块导出
│       ├── types.py          # MemoryMark, MemoryType, MemoryMessage
│       ├── memory_service.py # MemoryService(兼容旧接口)
│       ├── unified_service.py # UnifiedMemoryService(统一接口)
│       ├── working_memory/   # 工作记忆(短期)
│       │   ├── __init__.py   # 模块导出
│       │   ├── base.py       # WorkingMemoryBase
│       │   ├── in_memory.py  # InMemoryWorkingMemory
│       │    redis_memory.py # RedisWorkingMemory
│       ├── long_term_memory/ # 长期记忆
│       │   ├── __init__.py   # 模块导出
│       │   ├── base.py       # LongTermMemoryBase
│       │    vector_memory.py # VectorLongTermMemory
│       └ compression/      # 记忆压缩
│           ├── __init__.py   # 模块导出
│            compressor.py # MemoryCompressor
├── skills/                   # Skills 目录
│   ├── pdf/                  # PDF 处理 Skill
│   └ rag/                  # RAG Skill
├── tests/                    # 测试目录
│   ├── test_a2a.py           # A2A 协议测试
│   ├── test_agent_full_integration.py  # Agent 全集成测试
│   ├── test_concurrency.py             # 并发测试
│   ├── test_context_full.py            # 上下文服务测试
│   ├── test_evaluation.py              # 评估测试
│   ├── test_knowledge_base_complete.py # 知识库完整测试
│   ├── test_layered_memory.py          # 分层记忆测试
│   ├── test_memory_with_agents.py      # 记忆与Agent集成测试
│   ├── test_model_services.py          # 模型服务测试
│   ├── test_multi_agent.py             # 多智能体测试
│   ├── test_security.py                # 安全测试
│   ├── test_skills_with_agents.py      # Skills与Agent集成测试
│   ├── test_tool_management.py         # 工具管理测试
│   ├── test_tracing.py                 # 追踪测试
│   ├── test_websocket.py               # WebSocket 测试
│   └ test_tools.py                   # 工具测试
├── scripts/                  # 脚本目录
│   └ install.sh             # 安装脚本
├── docs/                     # 文档目录
│   ├── ARCHITECTURE_ISSUES.md # 架构问题文档
│   └ DEPLOYMENT.md          # 部署文档
├── application.py            # Application Factory
├── __init__.py               # 包入口
├── __main__.py               # CLI 入口
├── pyproject.toml            # 项目配置
├── uv.lock                   # uv 依赖锁定文件
├── .venv/                    # uv 虚拟环境
└── .env                      # 环境配置

环境配置

框架采用双层配置架构:

├── .env                    # 敏感信息(不进入版本控制)
│   └── API Keys, 密码, 模型URL
│
└── config/                 # 非敏感配置(进入版本控制)
    ├── model.yaml          # 模型层配置(llm, embedding, reranker 参数)
    ├── application.yaml    # 应用层配置(app, memory, context, queue...)
    ├── observability.yaml  # 可观测性配置(日志、追踪)
    ├── rag.yaml            # RAG 配置
    ├── skills.yaml         # Skills 配置
    ├── mcp.yaml            # MCP 配置
    ├── a2a.yaml            # A2A 配置
    └── litellm.yaml        # LiteLLM Proxy 配置

配置优先级:环境变量 > .env > YAML 文件 > 默认值

快速配置

仓库已包含 .env 文件,直接修改敏感信息即可。

非敏感配置可直接修改 config/*.yaml 文件。

主要环境变量

应用配置

变量 说明 默认值
APP_NAME 应用名称 agent-framework
APP_ENV 运行环境 development
APP_HOST 服务绑定地址 0.0.0.0
APP_PORT HTTP 服务端口 8000
WS_PORT WebSocket 端口 8001

LLM 配置

变量 说明 默认值
LLM_PROVIDER LLM 提供商 openai
LLM_MODEL LLM 模型 gpt-4o-mini
LLM_API_KEY LLM API 密钥 -
LLM_API_URL API 地址(兼容 OpenAI) -
LLM_TEMPERATURE 温度参数 0.7
LLM_MAX_TOKENS 最大 Token 数 2048
LLM_TIMEOUT 请求超时(秒) 60
LLM_MAX_RETRIES 最大重试次数 3
LITELLM_PROXY_URL LiteLLM Proxy 地址 -
LITELLM_PROXY_ENABLED 启用 LiteLLM Proxy false

Embedding 配置

变量 说明 默认值
EMBEDDING_MODEL Embedding 模型 -
EMBEDDING_API_URL Embedding API 地址 -
EMBEDDING_API_KEY Embedding API 密钥 -
EMBEDDING_BATCH_SIZE 批处理大小 32

Reranker 配置

变量 说明 默认值
RERANKER_ENABLED 启用 Reranker false
RERANKER_TYPE Reranker 类型 openai_compat
RERANKER_MODEL Reranker 模型 -
RERANKER_API_URL Reranker API 地址 -

Memory 配置

变量 说明 默认值
MEMORY_TYPE 记忆类型 ephemeral
MEMORY_TTL 记忆有效期(秒) 3600
MEMORY_REDIS_URL Redis 连接 URL -

Context 配置

变量 说明 默认值
MAX_HISTORY_LENGTH 最大历史长度 50
MAX_CONTEXT_WINDOW 最大上下文窗口 8000
ENABLE_CONTEXT_COMPRESSION 启用上下文压缩 true

Queue 配置

变量 说明 默认值
QUEUE_TYPE 队列类型 memory
REDIS_URL Redis 连接 URL redis://localhost:6379/0

Skills 配置

变量 说明 默认值
SKILLS_DIR Skills 目录 ./skills
ENABLE_SKILLS 启用 Skills true

MCP 配置

变量 说明 默认值
MCP_ENABLED 启用 MCP false
MCP_CONFIG_PATH MCP 配置路径 ./config/mcp.yaml
MCP_TIMEOUT MCP 超时时间 30000

A2A 配置

变量 说明 默认值
A2A_ENABLED 启用 A2A false
A2A_CONFIG_PATH A2A 配置路径 ./config/a2a.yaml

可观测性配置

变量 说明 默认值
LOG_LEVEL 日志级别 info
LOG_PRETTY 美化日志输出 true
OTEL_ENABLED 启用 OpenTelemetry false
OTEL_EXPORTER_OTLP_ENDPOINT OTLP 导出端点 -

安全配置

变量 说明 默认值
API_KEY API 密钥 -
ENABLE_AUTH 启用认证 false

审计日志配置

变量 说明 默认值
AUDIT_LOG_ENABLED 启用审计日志 true
AUDIT_LOG_REQUEST_BODY 记录请求体 false

WebSocket 配置

变量 说明 默认值
WS_MAX_CONNECTIONS 最大连接数 1000
WS_MAX_MESSAGE_SIZE 最大消息大小 1048576

AgentScope SDK 配置

AgentScope SDK 通过 Application 配置启用,无需额外环境变量:

# 在代码中配置
app = Application.from_config(
    mode=AppMode.LIBRARY,
    use_agentscope_sdk=True,           # 启用 AgentScope SDK
    agentscope_provider="openai",       # LLM 提供商
    agentscope_stream=True,             # 流式输出
)

支持的 LLM 提供商及所需环境变量:

Provider 环境变量 说明
openai OPENAI_API_KEY OpenAI GPT 系列
dashscope DASHSCOPE_API_KEY 阿里云通义千问
anthropic ANTHROPIC_API_KEY Anthropic Claude
ollama 本地 Ollama(默认 http://localhost:11434)
gemini GOOGLE_API_KEY Google Gemini

LLM Provider 配置

框架采用 LangChain ChatOpenAI + LiteLLM Proxy 架构:

┌─────────────────────────────────────┐
│    应用层 (Agent / Tools / Loop)     │
└─────────────────┬───────────────────┘
                  ↓
┌─────────────────────────────────────┐
│      LangChain ChatOpenAI           │
│   (统一接口,工具调用,流式响应)      │
└─────────────────┬───────────────────┘
                  ↓ base_url = LiteLLM Proxy
┌─────────────────────────────────────┐
│         LiteLLM Proxy               │
│  • 监控统计 (Token/成本/延迟)        │
│  • 速率限制 / 负载均衡               │
│  • 模型路由 / 降级策略               │
└─────────────────┬───────────────────┘
                  ↓
┌─────────────────────────────────────┐
│     各模型 API                       │
│  OpenAI / Anthropic / Qwen / ...    │
└─────────────────────────────────────┘

配置方式

方式一:LiteLLM Proxy 模式(推荐)

应用层只需配置 Proxy 地址和模型名称,所有模型配置在 LiteLLM 中管理:

# .env 配置 - LiteLLM Proxy 模式
LITELLM_PROXY_ENABLED=true
LITELLM_PROXY_URL=http://localhost:4000  # LiteLLM Proxy 地址
LLM_MODEL=gpt-4o                          # LiteLLM 中配置的 model_name
LLM_API_KEY=your-litellm-master-key      # LiteLLM Proxy 密钥
# 不需要 LLM_PROVIDER 和 LLM_API_URL

方式二:直连模式

直接连接各模型 API,不经过 LiteLLM:

# .env 配置 - 直连模式
LLM_PROVIDER=openai                       # 模型提供商
LLM_MODEL=gpt-4o                          # 模型名称
LLM_API_KEY=your-api-key                  # API 密钥
LLM_API_URL=                              # 可选,Qwen 需设置 DashScope 地址

LiteLLM Proxy 配置示例

LiteLLM 的 config.yaml 定义模型映射:

model_list:
  # 应用层使用 gpt-4o,实际调用 OpenAI
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY

  # 应用层使用 claude-3,实际调用 Anthropic
  - model_name: claude-3
    litellm_params:
      model: anthropic/claude-3-opus-20240229
      api_key: os.environ/ANTHROPIC_API_KEY

  # 应用层使用 qwen-max,实际调用 DashScope
  - model_name: qwen-max
    litellm_params:
      model: openai/qwen-max
      api_key: os.environ/QWEN_API_KEY
      api_base: https://dashscope.aliyuncs.com/compatible-mode/v1

general_settings:
  master_key: your-master-key

LiteLLM Proxy 优势

  • 统一监控:所有模型调用的 Token、成本、延迟一目了然
  • 灵活路由:配置模型降级、负载均衡策略
  • 速率限制:统一管理 API 调用频率
  • 透明代理:应用层无需修改,只需配置 base_url

LiteLLM Proxy 部署

# 使用 Docker 部署
docker run -d \
  --name litellm-proxy \
  -p 4000:4000 \
  -v ./litellm_config.yaml:/app/config.yaml \
  ghcr.io/berriai/litellm:main-latest \
  --config /app/config.yaml --detailed_debug

开发

# 安装开发依赖
uv sync --extra dev

# 运行测试
uv run pytest

# 代码检查
uv run ruff check .
uv run black .
uv run mypy .

# 运行特定测试
uv run pytest tests/test_agent_full_integration.py
uv run pytest tests/test_knowledge_base_complete.py
uv run pytest tests/test_layered_memory.py
uv run pytest tests/test_a2a.py
uv run pytest tests/test_evaluation.py

Skills 系统

框架采用 Skills-based 开发模式,每个 Skill 是一个包含 SKILL.md 文件的目录,提供特定领域的能力。

Skills 目录

Skills 默认存放在 ./skills 目录(可通过 SKILLS_DIR 配置)。如果目录不存在,框架会跳过 Skills 加载。

内置 Skills

当前项目包含以下 Skills:

Skill 用途 目录
pdf PDF 文档处理和分析 skills/pdf/
rag 检索增强生成 skills/rag/

创建自定义 Skill

# 1. 创建 Skill 目录
mkdir -p skills/my-skill

# 2. 创建 SKILL.md 文件
cat > skills/my-skill/SKILL.md << 'EOF'
---
name: my-skill
description: "我的自定义 Skill"
category: Custom
---
# My Skill

这里是 Skill 的详细指令...
EOF

SKILL.md 格式

---
name: skill-name
description: "Skill 的简要描述"
license: MIT
category: Skill 类别
allowed-tools:
  - bash
  - file-read
---

# Skill 详细指令

- 功能说明
- 使用方法
- 示例代码
- 最佳实践

核心 API

主包 products 导出以下核心 API:

Application Factory(统一入口)

from products import Application, ApplicationConfig, AppMode, create_app

Agent(自有编排)

from products import Agent, AgentConfig, LoopType, AgentExecutionContext

Loops(循环架构)

from products import (
    BaseLoop,            # Loop 基类
    RalphLoop,           # Ralph Loop(强制循环)
    ReActLoop,           # ReAct Loop(文本解析)
    PlanAndExecuteLoop,  # Plan-Execute Loop(规划执行)
)

Ralph Loop 配置

from orchestration.loops import (
    RalphLoopConfig,     # Ralph Loop 配置类
    StopHook,            # Stop Hook 配置
    StopHookType,        # Stop Hook 类型枚举
    VerificationCommand, # 验证命令配置
    ExternalMemory,      # 外部记忆配置
)

Multi-Agent(多智能体协作)

from products import (
    MultiAgentCoordinator,
    AgentRegistration,
    Task,
    TaskResult,
    TaskStatus,
    AgentRole,
    CollaborationStrategy,
    MessageBus,
    AgentMessage,
    MessageType,
)

Router(智能路由)

from products import (
    TaskRouter,           # 任务路由器
    ToolSelector,         # 工具选择器
    RoutingRule,          # 路由规则
    RoutingResult,        # 路由结果
    ToolSelectionResult,  # 工具选择结果
    ToolCategory,         # 工具类别
)

Agent SDK 适配器

from products import (
    BaseAgentAdapter,
    SDKAdapterConfig,
    AgentResult,
    AgentSDK,
    AgentStatus,
    AgentScopeAdapter,
    create_agent,
    # AgentScope 特定类型
    ModelProvider,
    AgentType,
    create_model_config,
    get_model_preset,
    MODEL_PRESETS,
)

Model Services(模型服务)

from products import (
    # 统一入口
    ModelService,
    get_model_service,
    reset_model_service,
    # LLM 服务
    LLMService,
    LLMProvider,
    Message,
    ToolCall,
    ChatResponse,
    # Embedding 服务
    EmbeddingService,
    EmbeddingConfig,
    EmbeddingProvider,
    EmbeddingResult,
    # Reranker 服务
    RerankerService,
    RerankerConfig,
    RerankerType,
    RerankResult,
)

State Management(状态管理)

# Context 服务
from products import (
    ContextService,
    ContextStats,
    Message,
    ContextError,
)

# 分层记忆架构
from products import (
    # 核心类型
    MemoryMark,
    MemoryType,
    MemoryMessage,
    CompressionConfig,
    CompressionSummary,
    LongTermMemoryConfig,
    MemoryQueryResult,
    RetrievedMemory,
    # 工作记忆(短期)
    WorkingMemoryBase,
    InMemoryWorkingMemory,
    RedisWorkingMemory,
    # 长期记忆
    LongTermMemoryBase,
    AgentControlledMemory,
    VectorLongTermMemory,
    # 记忆压缩
    MemoryCompressor,
    # 统一服务
    UnifiedMemoryConfig,
    UnifiedMemoryService,
    # 兼容旧接口
    MemoryService,
    MemoryBackend,
    EphemeralMemoryBackend,
    RedisMemoryBackend,
    MemoryError,
)

Capabilities(能力层)

# 工具注册中心
from products import (
    ToolRegistry,
    Tool,
    ToolResult,
    ToolSource,
)

# Skills 系统
from products import SkillLoader, SkillInfo

# MCP 协议
from products import MCPClient, MCPClientManager

# A2A 协议
from products import (
    A2AClient,
    A2AClientManager,
    A2ARemoteAgent,
    AgentCard,
    A2AConfig,
    TaskState,
    A2AFormatter,
)

Interface(接口层)

from products import (
    WebServer,        # REST API 服务器
    WSServer,         # WebSocket 服务器
    CLI,              # 命令行界面
    AuditLogService,  # 审计日志服务
    AuditLogEntry,    # 审计日志条目
)

Evaluation(评估系统)

from products import (
    # Core - 数据结构
    EvalTask,
    SolutionOutput,
    BenchmarkBase,
    EvaluationResult,
    TrajectoryStep,
    SolutionStats,
    ToolDefinition,
    Milestone,
    DataLoader,
    RemoteBenchmark,
    # Core - Metric
    MetricBase,
    MetricResult,
    MetricType,
    EvaluatorBase,
    EvaluatorStorageBase,
    # Metrics
    ExactMatchMetric,
    ContainsMetric,
    AccuracyMetric,
    TokenEfficiencyMetric,
    TimeEfficiencyMetric,
    ProcessAccuracyMetric,
    ToolUseMetric,
    ResultCorrectnessMetric,
    ProcessCorrectnessMetric,
    ToolSelectionMetric,
    ToolExecutionMetric,
    ConversationQualityMetric,
    # Evaluators
    GeneralEvaluator,
    ParallelEvaluator,
    # Storage
    FileEvaluatorStorage,
    # Benchmarks
    JSONBenchmark,
    ToolUseBenchmark,
    JSONLBenchmark,
    DatasetManager,
    # Report
    ReportGenerator,
)

Integrate(智能体集成)

from products import (
    ExecutionPhase,        # 执行阶段枚举
    IntegrationConfig,     # 集成配置
    AgentIntegration,      # 智能体集成实现
)

RAG(检索增强生成)

from products import (
    # 配置
    KnowledgeBaseConfig,
    KnowledgeBaseRegistry,
    kb_registry,
    register_knowledge_base,
    get_knowledge_base,
    list_knowledge_bases,
    # 知识库管理
    KnowledgeBaseManager,
    kb_manager,
    ElasticSearchManagement,
    RedisManagement,
    WeaviateManagement,
    # 文档处理
    BaseSplitter,
    DocumentLoader,
    register_splitter,
    get_splitter,
    register_loader,
    get_loader,
    # 检索
    MixedRetriever,
    ElasticRetriever,
    VectorRetriever,
    # LLM
    LLM,
    call_rag_llm,
    call_rag_llm_with_retrieval,
    # 上下文构建
    BaseContextBuilder,
    ContextBuilderRegistry,
    register_context_builder,
    create_context_builder,
    # RAG 流水线
    RAGPipeline,
    run_rag_pipeline,
    retrieve_only,
)

Foundation - Config(配置管理)

from products import (
    Config,
    get_config,
    ConfigMixin,
    YAMLConfigLoader,
    get_yaml_loader,
)

Foundation - Observability(可观测性)

# 日志
from products import (
    FoundationLogger,
    foundation_get_logger,
    configure_logging,
    get_log_config,
)

# 追踪
from products import (
    init_tracing,
    init_tracing_from_config,
    shutdown_tracing,
    get_tracer,
    is_tracing_enabled,
    get_current_span,
    get_trace_id,
    get_span_id,
    set_attribute,
    set_attributes,
    add_event,
    record_exception,
    traced,
    traced_llm,
    traced_tool,
    traced_rag,
    span_context,
    inject_trace_context,
    extract_trace_context,
    set_session_id,
    set_conversation_id,
    set_user_id,
    set_agent_context,
)

Foundation - Queue(队列)

from products import IQueue, MemoryQueue, RedisQueue

Foundation - Pool & Rate Limit(连接池与限流)

from products import ConnectionPool, RateLimiter

Foundation - Concurrency(并发执行)

from products import Executor

Foundation - Errors(错误处理)

from products import (
    AgentError,
    ValidationError,
    ExecutionError,
    NetworkError,
    TimeoutError,
    RateLimitError,
    ToolError,
)

Foundation - Middleware(中间件)

from products import (
    Middleware,
    LoggingMiddleware,
    MetricsMiddleware,
    ErrorHandlerMiddleware,
    TracingMiddleware,
    MiddlewareChain,
)

Foundation - Permissions(权限控制)

from products import (
    PermissionMode,
    PermissionDecision,
    PathRule,
    PermissionChecker,
    PermissionSettings,
)

Foundation - Hooks(钩子系统)

from products import (
    HookEvent,
    HookResult,
    AggregatedHookResult,
    HookDefinition,
    CommandHookDefinition,
    HttpHookDefinition,
    PromptHookDefinition,
    AgentHookDefinition,
    HookRegistry,
    HookExecutor,
    HookExecutionContext,
)

Foundation - Swarm(分屏后端)

from products import (
    BackendType,
    PaneId,
    CreatePaneResult,
    BackendDetectionResult,
    TeammateSpawnConfig,
    SpawnResult,
    BaseBackend,
    SubprocessBackend,
    TmuxBackend,
    InProcessBackend,
    detect_backend,
    get_backend,
)

许可证

MIT

About

fully completed agents with harness by haipeng

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors