返回 MCP 目录
public公开dns本地运行

praisonai

PraisonAI是一个生产就绪的多AI智能体框架,具有自反思功能,旨在创建AI智能体来自动化解决从简单任务到复杂挑战的各种问题。它通过将PraisonAI智能体、AG2和CrewAI集成到一个低代码解决方案中,简化了多智能体LLM系统的构建和管理,强调简单性、定制化和有效的人机协作。

article

README

🚀 Praison AI

Praison AI 是一个可用于生产环境的多 AI 智能体框架,具备自我反思能力。它旨在创建 AI 智能体,以自动化方式解决从简单任务到复杂挑战的各类问题。通过将 PraisonAI 智能体、AG2(前身为 AutoGen)和 CrewAI 集成到低代码解决方案中,它简化了多智能体大语言模型系统的构建和管理,强调简单性、可定制性以及有效的人机协作。

🚀 快速开始

在不到 1 分钟的时间内开始使用 PraisonAI:

# 安装
pip install praisonaiagents

# 设置 API 密钥
export OPENAI_API_KEY=your_key_here

# 创建一个简单的智能体
python -c "from praisonaiagents import Agent; Agent(instructions='You are a helpful AI assistant').start('Write a haiku about AI')"

✨ 主要特性

🤖 核心智能体

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 单智能体 | 示例 | 📖 | | 多智能体 | 示例 | 📖 | | 自动智能体 | 示例 | 📖 | | 自我反思 AI 智能体 | 示例 | 📖 | | 推理 AI 智能体 | 示例 | 📖 | | 多模态 AI 智能体 | 示例 | 📖 |

🔄 工作流

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 简单工作流 | 示例 | 📖 | | 带智能体的工作流 | 示例 | 📖 | | 智能体路由 (route()) | 示例 | 📖 | | 并行执行 (parallel()) | 示例 | 📖 | | 列表/CSV 循环 (loop()) | 示例 | 📖 | | 评估器 - 优化器 (repeat()) | 示例 | 📖 | | 条件步骤 | 示例 | 📖 | | 工作流分支 | 示例 | 📖 | | 工作流提前停止 | 示例 | 📖 | | 工作流检查点 | 示例 | 📖 |

💻 代码与开发

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 代码解释器智能体 | 示例 | 📖 | | AI 代码编辑工具 | 示例 | 📖 | | 外部智能体 (全部) | 示例 | 📖 | | Claude 代码 CLI | 示例 | 📖 | | Gemini CLI | 示例 | 📖 | | Codex CLI | 示例 | 📖 | | Cursor CLI | 示例 | 📖 |

🧠 记忆与知识

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 记忆(短期和长期) | 示例 | 📖 | | 基于文件的记忆 | 示例 | 📖 | | Claude 记忆工具 | 示例 | 📖 | | 添加自定义知识 | 示例 | 📖 | | RAG 智能体 | 示例 | 📖 | | 与 PDF 聊天智能体 | 示例 | 📖 | | 数据读取器(PDF、DOCX 等) | CLI | 📖 | | 向量存储选择 | CLI | 📖 | | 检索策略 | CLI | 📖 | | 重排器 | CLI | 📖 | | 索引类型(向量/关键字/混合) | CLI | 📖 | | 查询引擎(子问题等) | CLI | 📖 |

🔬 研究与情报

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 深度研究智能体 | 示例 | 📖 | | 查询重写智能体 | 示例 | 📖 | | 原生网络搜索 | 示例 | 📖 | | 内置搜索工具 | 示例 | 📖 | | 统一网络搜索 | 示例 | 📖 | | 网络抓取(Anthropic) | 示例 | 📖 |

📋 规划与执行

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 规划模式 | 示例 | 📖 | | 规划工具 | 示例 | 📖 | | 规划推理 | 示例 | 📖 | | 提示链 | 示例 | 📖 | | 评估器优化器 | 示例 | 📖 | | 编排器工作者 | 示例 | 📖 |

👥 专业智能体

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 数据分析智能体 | 示例 | 📖 | | 金融智能体 | 示例 | 📖 | | 购物智能体 | 示例 | 📖 | | 推荐智能体 | 示例 | 📖 | | 维基百科智能体 | 示例 | 📖 | | 编程智能体 | 示例 | 📖 | | 数学智能体 | 示例 | 📖 | | Markdown 智能体 | 示例 | 📖 | | 提示扩展智能体 | 示例 | 📖 |

🎨 媒体与多模态

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 图像生成智能体 | 示例 | 📖 | | 图像转文本智能体 | 示例 | 📖 | | 视频智能体 | 示例 | 📖 | | 相机集成 | 示例 | 📖 |

🔌 协议与集成

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | MCP 传输 | 示例 | 📖 | | WebSocket MCP | 示例 | 📖 | | MCP 安全 | 示例 | 📖 | | MCP 可恢复性 | 示例 | 📖 | | MCP 配置管理 | 示例 | 📖 | | LangChain 集成智能体 | 示例 | 📖 |

🛡️ 安全与控制

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 护栏 | 示例 | 📖 | | 人工批准 | 示例 | 📖 | | 规则与指令 | 示例 | 📖 |

⚙️ 高级特性

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 异步与并行处理 | 示例 | 📖 | | 并行化 | 示例 | 📖 | | 重复智能体 | 示例 | 📖 | | 智能体交接 | 示例 | 📖 | | 有状态智能体 | 示例 | 📖 | | 自主工作流 | 示例 | 📖 | | 结构化输出智能体 | 示例 | 📖 | | 模型路由器 | 示例 | 📖 | | 提示缓存 | 示例 | 📖 | | 快速上下文 | 示例 | 📖 |

🛠️ 工具与配置

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 100+ 自定义工具 | 示例 | 📖 | | YAML 配置 | 示例 | 📖 | | 100+ 大语言模型支持 | 示例 | 📖 | | 回调智能体 | 示例 | 📖 | | 钩子 | 示例 | 📖 | | 中间件系统 | 示例 | 📖 | | 可配置模型 | 示例 | 📖 | | 速率限制器 | 示例 | 📖 | | 注入工具状态 | 示例 | 📖 | | 影子 Git 检查点 | 示例 | 📖 | | 后台任务 | 示例 | 📖 | | 策略引擎 | 示例 | 📖 | | 思考预算 | 示例 | 📖 | | 输出样式 | 示例 | 📖 | | 上下文压缩 | 示例 | 📖 |

📊 监控与管理

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 会话管理 | 示例 | 📖 | | 自动保存会话 | 示例 | 📖 | | 上下文中的历史记录 | 示例 | 📖 | | 遥测 | 示例 | 📖 | | 项目文档 (.praison/docs/) | 示例 | 📖 | | AI 提交消息 | 示例 | 📖 | | 提示中的 @提及 | 示例 | 📖 |

🖥️ CLI 特性

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 斜杠命令 | 示例 | 📖 | | 自主模式 | 示例 | 📖 | | 成本跟踪 | 示例 | 📖 | | 存储库映射 | 示例 | 📖 | | 交互式 TUI | 示例 | 📖 | | Git 集成 | 示例 | 📖 | | 沙盒执行 | 示例 | 📖 | | CLI 比较 | 示例 | 📖 | | 配置文件/基准测试 | 示例 | 📖 | | 自动模式 | 示例 | 📖 | | 初始化 | 示例 | 📖 | | 文件输入 | 示例 | 📖 | | 最终智能体 | 示例 | 📖 | | 最大令牌数 | 示例 | 📖 |

🧪 评估

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 准确性评估 | 示例 | 📖 | | 性能评估 | 示例 | 📖 | | 可靠性评估 | 示例 | 📖 | | 标准评估 | 示例 | 📖 |

🎯 智能体技能

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 技能管理 | 示例 | 📖 | | 自定义技能 | 示例 | 📖 |

⏰ 24/7 调度

| 特性 | 代码示例 | 文档 | |---------|:----:|:----:| | 智能体调度器 | 示例 | 📖 |

📦 安装指南

Python SDK

用于编码的轻量级包:

pip install praisonaiagents

如需支持 CLI 的完整框架:

pip install praisonai

JavaScript SDK

npm install praisonai

环境变量

| 变量 | 是否必需 | 描述 | |----------|----------|-------------| | OPENAI_API_KEY | 是* | OpenAI API 密钥 | | ANTHROPIC_API_KEY | 否 | Anthropic Claude API 密钥 | | GOOGLE_API_KEY | 否 | Google Gemini API 密钥 | | GROQ_API_KEY | 否 | Groq API 密钥 | | OPENAI_BASE_URL | 否 | 自定义 API 端点(用于 Ollama、Groq 等) |

*至少需要一个大语言模型提供商的 API 密钥。

# 设置 API 密钥
export OPENAI_API_KEY=your_key_here

# 对于 Ollama(本地模型)
export OPENAI_BASE_URL=http://localhost:11434/v1

# 对于 Groq
export OPENAI_API_KEY=your_groq_key
export OPENAI_BASE_URL=https://api.groq.com/openai/v1

💻 使用示例

Python 代码示例

基础用法

# 单智能体
from praisonaiagents import Agent
agent = Agent(instructions="Your are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")

# 多智能体
from praisonaiagents import Agent, PraisonAIAgents

research_agent = Agent(instructions="Research about AI")
summarise_agent = Agent(instructions="Summarise research agent's findings")
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()

高级用法

# 带规划模式的智能体
from praisonaiagents import Agent

def search_web(query: str) -> str:
    return f"Search results for: {query}"

agent = Agent(
    name="AI Assistant",
    instructions="Research and write about topics",
    planning=True,              # 启用规划模式
    planning_tools=[search_web], # 规划研究的工具
    planning_reasoning=True      # 思维链推理
)

result = agent.start("Research AI trends in 2025 and write a summary")

# 深度研究智能体
from praisonaiagents import DeepResearchAgent

# OpenAI 深度研究
agent = DeepResearchAgent(
    model="o4-mini-deep-research",  # 或 "o3-deep-research"
    verbose=True
)

result = agent.research("What are the latest AI trends in 2025?")
print(result.report)
print(f"Citations: {len(result.citations)}")

# Gemini 深度研究
from praisonaiagents import DeepResearchAgent

agent = DeepResearchAgent(
    model="deep-research-pro",  # 自动检测为 Gemini
    verbose=True
)

result = agent.research("Research quantum computing advances")
print(result.report)

# 查询重写智能体
from praisonaiagents import QueryRewriterAgent, RewriteStrategy

agent = QueryRewriterAgent(model="gpt-4o-mini")

# 基础 - 扩展缩写,添加上下文
result = agent.rewrite("AI trends")
print(result.primary_query)  # "What are the current trends in Artificial Intelligence?"

# HyDE - 生成假设文档进行语义匹配
result = agent.rewrite("What is quantum computing?", strategy=RewriteStrategy.HYDE)

# 回溯 - 生成更广泛的上下文问题
result = agent.rewrite("GPT-4 vs Claude 3?", strategy=RewriteStrategy.STEP_BACK)

# 子查询 - 分解复杂问题
result = agent.rewrite("RAG setup and best embedding models?", strategy=RewriteStrategy.SUB_QUERIES)

# 上下文 - 使用聊天历史解决引用问题
result = agent.rewrite("What about cost?", chat_history=[...])

# 智能体记忆(零依赖)
from praisonaiagents import Agent
from praisonaiagents.memory import FileMemory

# 启用记忆
agent = Agent(
    name="Personal Assistant",
    instructions="You are a helpful assistant that remembers user preferences.",
    memory=True,  # 启用基于文件的记忆(无需额外依赖!)
    user_id="user123"  # 按用户隔离记忆
)

# 记忆会自动注入对话中
result = agent.start("My name is John and I prefer Python")
# 智能体将在未来的对话中记住这一点

# 自动生成记忆
from praisonaiagents.memory import FileMemory, AutoMemory

memory = FileMemory(user_id="user123")
auto = AutoMemory(memory, enabled=True)

# 自动从对话中提取和存储记忆
memories = auto.process_interaction(
    "My name is John and I prefer Python for backend work"
)
# 提取:name="John", preference="Python for backend"

# 智能体工作流
from praisonaiagents import Agent, Workflow

# 创建智能体
researcher = Agent(
    name="Researcher",
    role="Research Analyst",
    goal="Research topics thoroughly",
    instructions="Provide concise, factual information."
)

writer = Agent(
    name="Writer",
    role="Content Writer", 
    goal="Write engaging content",
    instructions="Write clear, engaging content based on research."
)

# 创建工作流
workflow = Workflow(steps=[researcher, writer])

# 运行工作流 - 智能体按顺序处理
result = workflow.start("What are the benefits of AI agents?")
print(result["output"])

# 工作流模式(路由、并行、循环、重复)
from praisonaiagents import Agent, Workflow
from praisonaiagents.workflows import route, parallel, loop, repeat

# 1. 路由 - 分类器智能体将任务路由到专业智能体
classifier = Agent(name="Classifier", instructions="Respond with 'technical' or 'creative'")
tech_agent = Agent(name="TechExpert", role="Technical Expert")
creative_agent = Agent(name="Creative", role="Creative Writer")

workflow = Workflow(steps=[
    classifier,
    route({
        "technical": [tech_agent],
        "creative": [creative_agent]
    })
])

# 2. 并行 - 多个智能体并发工作
market_agent = Agent(name="Market", role="Market Researcher")
competitor_agent = Agent(name="Competitor", role="Competitor Analyst")
aggregator = Agent(name="Aggregator", role="Synthesizer")

workflow = Workflow(steps=[
    parallel([market_agent, competitor_agent]),
    aggregator
])

# 3. 循环 - 智能体处理每个项目
processor = Agent(name="Processor", role="Item Processor")
summarizer = Agent(name="Summarizer", role="Summarizer")

workflow = Workflow(
    steps=[loop(processor, over="items"), summarizer],
    variables={"items": ["AI", "ML", "NLP"]}
)

# 4. 重复 - 评估器 - 优化器模式
generator = Agent(name="Generator", role="Content Generator")
evaluator = Agent(name="Evaluator", instructions="Say 'APPROVED' if good")

workflow = Workflow(steps=[
    generator,
    repeat(evaluator, until=lambda ctx: "approved" in ctx.previous_result.lower(), max_iterations=3)
])

# 5. 回调
workflow = Workflow(
    steps=[researcher, writer],
    on_step_complete=lambda name, r: print(f"✅ {name} done")
)

# 6. 带规划和推理
workflow = Workflow(
    steps=[researcher, writer],
    planning=True,
    reasoning=True
)

# 7. 异步执行
import asyncio
result = asyncio.run(workflow.astart("input"))

# 8. 状态跟踪
workflow.status  # "not_started" | "running" | "completed"
workflow.step_statuses  # {"step1": "completed", "step2": "skipped"}

# YAML 工作流模板
from praisonaiagents.workflows import YAMLWorkflowParser, WorkflowManager

# 选项 1:解析 YAML 字符串
parser = YAMLWorkflowParser()
workflow = parser.parse_string(yaml_content)
result = workflow.start("Research AI trends")

# 选项 2:使用 WorkflowManager 从文件加载
manager = WorkflowManager()
workflow = manager.load_yaml("research_workflow.yaml")
result = workflow.start("Research AI trends")

# 选项 3:直接执行 YAML
result = manager.execute_yaml(
    "research_workflow.yaml",
    input_data="Research AI trends",
    variables={"topic": "Machine Learning"}
)

# 钩子
from praisonaiagents.hooks import (
    HookRegistry, HookRunner, HookEvent, HookResult,
    BeforeToolInput
)

# 创建钩子注册表
registry = HookRegistry()

# 记录所有工具调用
@registry.on(HookEvent.BEFORE_TOOL)
def log_tools(event_data: BeforeToolInput) -> HookResult:
    print(f"Tool: {event_data.tool_name}")
    return HookResult.allow()

# 阻止危险操作
@registry.on(HookEvent.BEFORE_TOOL)
def security_check(event_data: BeforeToolInput) -> HookResult:
    if "delete" in event_data.tool_name.lower():
        return HookResult.deny("Delete operations blocked")
    return HookResult.allow()

# 执行钩子
runner = HookRunner(registry)

# 影子 Git 检查点
from praisonaiagents.checkpoints import CheckpointService

service = CheckpointService(workspace_dir="./my_project")
await service.initialize()

# 保存更改前的检查点
result = await service.save("Before refactoring")

# 进行更改...

# 需要时恢复
await service.restore(result.checkpoint.id)

# 查看差异
diff = await service.diff()

# 后台任务
import asyncio
from praisonaiagents.background import BackgroundRunner, BackgroundConfig

async def main():
    config = BackgroundConfig(max_concurrent_tasks=3)
    runner = BackgroundRunner(config=config)
    
    async def my_task(name: str) -> str:
        await asyncio.sleep(2)
        return f"Task {name} completed"
    
    task = await runner.submit(my_task, args=("example",), name="my_task")
    await task.wait(timeout=10.0)
    print(task.result)

asyncio.run(main())

# 策略引擎
from praisonaiagents.policy import (
    PolicyEngine, Policy, PolicyRule, PolicyAction
)

engine = PolicyEngine()

policy = Policy(
    name="no_delete",
    rules=[
        PolicyRule(
            action=PolicyAction.DENY,
            resource="tool:delete_*",
            reason="Delete operations blocked"
        )
    ]
)
engine.add_policy(policy)

result = engine.check("tool:delete_file", {})
print(f"Allowed: {result.allowed}")

# 思考预算
from praisonaiagents.thinking import ThinkingBudget, ThinkingTracker

# 使用预定义级别
budget = ThinkingBudget.high()  # 16,000 个令牌

# 跟踪使用情况
tracker = ThinkingTracker()
session = tracker.start_session(budget_tokens=16000)
tracker.end_session(session, tokens_used=12000)

summary = tracker.get_summary()
print(f"Utilization: {summary['average_utilization']:.1%}")

# 输出样式
from praisonaiagents.output import OutputStyle, OutputFormatter

# 使用预设样式
style = OutputStyle.concise()
formatter = OutputFormatter(style)

# 格式化输出
text = "# Hello\n\nThis is **bold** text."
plain = formatter.format(text)
print(plain)

# 上下文压缩
from praisonaiagents.compaction import (
    ContextCompactor, CompactionStrategy
)

compactor = ContextCompactor(
    max_tokens=4000,
    strategy=CompactionStrategy.SLIDING,
    preserve_recent=3
)

messages = [...]  # 你的对话历史
compacted, result = compactor.compact(messages)

print(f"Compression: {result.compression_ratio:.1%}")

# 字段名称参考(A-I-G-S)
PraisonAI 同时接受旧的(agents.yaml)和新的(workflow.yaml)字段名称。对于新项目,建议使用**规范名称**:

| 规范名称(推荐) | 别名(也可用) | 用途 |
|-------------------------|-------------------|---------|
| `agents` | `roles` | 定义智能体角色 |
| `instructions` | `backstory` | 智能体行为/角色 |
| `action` | `description` | 步骤的操作 |
| `steps` | `tasks`(嵌套) | 定义工作项 |
| `name` | `topic` | 工作流标识符 |

# A-I-G-S 助记符 - 易于记忆:
- **A**gents - 谁来完成工作
- **I**nstructions - 他们的行为方式
- **G**oal - 他们要实现的目标
- **S**teps - 他们要做的事情

# 快速参考 - 规范格式
name: My Workflow              # 工作流名称(不是 'topic')
agents:                        # 定义智能体(不是 'roles')
  my_agent:
    role: Job Title            # 智能体的角色
    goal: What to achieve      # 智能体的目标
    instructions: How to act   # 智能体的行为(不是 'backstory')
    
steps:                         # 定义步骤(不是 'tasks')
  - agent: my_agent
    action: What to do         # 步骤操作(不是 'description')

# 注意:解析器同时接受旧名称和新名称。运行 `praisonai workflow validate <file.yaml>` 以查看规范名称的建议。

# 扩展 agents.yaml 与工作流模式
# 特性对等:现在 `agents.yaml` 和 `workflow.yaml` 支持相同的特性:
# - 所有工作流模式(路由、并行、循环、重复)
# - 所有智能体字段(function_calling_llm、max_rpm、max_execution_time、reflect_llm、模板)
# - 所有步骤字段(expected_output、context、output_json、create_directory、回调)
# - 框架支持(praisonai、crewai、autogen)
# - 流程类型(顺序、层次结构、工作流)

# 你可以通过设置 `process: workflow` 直接在 agents.yaml 中使用高级工作流模式:

# agents.yaml 与工作流模式
framework: praisonai
process: workflow  # 启用工作流模式
topic: "Research AI trends"

workflow:
  planning: true
  reasoning: true
  verbose: true

variables:
  topic: AI trends

agents:  # 规范:使用 'agents' 而不是 'roles'
  classifier:
    role: Request Classifier
    instructions: "Classify requests into categories"  # 规范:使用 'instructions' 而不是 'backstory'
    goal: Classify requests
    
  researcher:
    role: Research Analyst
    instructions: "Expert researcher"  # 规范:使用 'instructions' 而不是 'backstory'
    goal: Research topics
    tools:
      - tavily_search

steps:
  # 顺序步骤
  - agent: classifier
    action: "Classify: {{topic}}"
    
  # 路由模式 - 基于决策的分支
  - name: routing
    route:
      technical: [tech_expert]
      default: [researcher]
      
  # 并行模式 - 并发执行
  - name: parallel_research
    parallel:
      - agent: researcher
        action: "Research market trends"
      - agent: researcher
        action: "Research competitors"
        
  # 循环模式 - 遍历项目
  - agent: researcher
    action: "Analyze {{item}}"
    loop:
      over: topics
      
  # 重复模式 - 评估器 - 优化器
  - agent: aggregator
    action: "Synthesize findings"
    repeat:
      until: "comprehensive"
      max_iterations: 3

# 使用相同的简单命令运行
praisonai agents.yaml

# MCP(模型上下文协议)
# MCP 客户端(使用 MCP 服务器)
from praisonaiagents import Agent, MCP

# stdio - 本地 NPX/Python 服务器
agent = Agent(tools=MCP("npx @modelcontextprotocol/server-memory"))

# 可流式传输的 HTTP - 生产服务器
agent = Agent(tools=MCP("https://api.example.com/mcp"))

# WebSocket - 实时双向
agent = Agent(tools=MCP("wss://api.example.com/mcp", auth_token="token"))

# SSE(旧版) - 向后兼容
agent = Agent(tools=MCP("http://localhost:8080/sse"))

# 使用环境变量
agent = Agent(
    tools=MCP(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-brave-search"],
        env={"BRAVE_API_KEY": "your-key"}
    )
)

# 多个 MCP 服务器 + 常规函数
def my_custom_tool(query: str) -> str:
    """自定义工具函数。"""
    return f"Result: {query}"

agent = Agent(
    name="MultiToolAgent",
    instructions="Agent with multiple MCP servers",
    tools=[
        MCP("uvx mcp-server-time"),                    # 时间工具
        MCP("npx @modelcontextprotocol/server-memory"), # 内存工具
        my_custom_tool                                  # 常规函数
    ]
)

# MCP 服务器(将工具暴露为 MCP 服务器)
from praisonaiagents.mcp import ToolsMCPServer

def search_web(query: str, max_results: int = 5) -> dict:
    """在网络上搜索信息。"""
    return {"results": [f"Result for {query}"]}

def calculate(expression: str) -> dict:
    """计算数学表达式。"""
    return {"result": eval(expression)}

# 创建并运行 MCP 服务器
server = ToolsMCPServer(name="my-tools")
server.register_tools([search_web, calculate])
server.run()  # stdio 用于 Claude Desktop
# server.run_sse(host="0.0.0.0", port=8080)  # SSE 用于 Web 客户端

# MCP 特性
| 特性 | 描述 |
|---------|-------------|
| 会话管理 | 自动处理 Mcp-Session-Id |
| 协议版本控制 | Mcp-Protocol-Version 标头 |
| 可恢复性 | 通过 Last-Event-ID 恢复 SSE 流 |
| 安全性 | 源验证,防止 DNS 重绑定 |
| WebSocket | 具有指数退避的自动重新连接 |

# A2A(智能体到智能体协议)
# PraisonAI 支持 [A2A 协议](https://a2a-protocol.org) 进行智能体间通信,使你的智能体能够被发现并与其他 AI 智能体协作。

# A2A 服务器(将智能体暴露为 A2A 服务器)
from praisonaiagents import Agent, A2A
from fastapi import FastAPI

# 创建带工具的智能体
def search_web(query: str) -> str:
    """在网络上搜索信息。"""
    return f"Results for: {query}"

agent = Agent(
    name="Research Assistant",
    role="Research Analyst",
    goal="Help users research topics",
    tools=[search_web]
)

# 暴露为 A2A 服务器
a2a = A2A(agent=agent, url="http://localhost:8000/a2a")

app = FastAPI()
app.include_router(a2a.get_router())

# 运行:uvicorn app:app --reload
# 智能体卡片:GET /.well-known/agent.json
# 状态:GET /status

# A2A 特性
| 特性 | 描述 |
|---------|-------------|
| 智能体卡片 | 用于智能体发现的 JSON 元数据 |
| 技能提取 | 从工具自动生成技能 |
| 任务管理 | 有状态的任务生命周期 |
| 流式传输 | SSE 流式传输以实现实时更新 |

# 文档:[docs.praison.ai/a2a](https://docs.praison.ai/a2a) | 示例:[examples/python/a2a](https://github.com/MervinPraison/PraisonAI/tree/main/examples/python/a2a)

JavaScript 代码示例

const { Agent } = require('praisonai');
const agent = new Agent({ instructions: 'You are a helpful AI assistant' });
agent.start('Write a movie script about a robot in Mars');

📚 详细文档

🌐 支持的提供商

PraisonAI 通过无缝集成支持 100 多个大语言模型提供商:

| 提供商 | 示例 | |----------|:-------:| | OpenAI | 示例 | | Anthropic | 示例 | | Google Gemini | 示例 | | Ollama | 示例 | | Groq | 示例 | | DeepSeek | 示例 | | xAI Grok | 示例 | | Mistral | 示例 | | Cohere | 示例 | | Perplexity | 示例 | | Fireworks | 示例 | | Together AI | 示例 | | OpenRouter | 示例 | | HuggingFace | 示例 | | Azure OpenAI | 示例 | | AWS Bedrock | 示例 | | Google Vertex | 示例 | | Databricks | 示例 | | Cloudflare | 示例 | | AI21 | 示例 | | Replicate | 示例 | | SageMaker | 示例 | | Moonshot | 示例 | | vLLM | 示例 |

🎯 CLI / 无代码界面

PraisonAI 提供强大的 CLI 用于无代码自动化和快速原型开发。

CLI 快速参考

| 类别 | 命令 | |----------|----------| | 执行 | praisonai, --auto, --interactive, --chat | | 研究 | research, --query-rewrite, --deep-research | | 规划 | --planning, --planning-tools, --planning-reasoning | | 工作流 | workflow run, workflow list, workflow auto | | 记忆 | memory show, memory add, memory search, memory clear | | 知识 | knowledge add, knowledge query, knowledge list | | 会话 | session list, session resume, session delete | | 工具 | tools list, tools info, tools search | | MCP | mcp list, mcp create, mcp enable | | 开发 | commit, docs, checkpoint, hooks | | 调度 | schedule start, schedule list, schedule stop |

自动模式

pip install praisonai
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
praisonai --auto create a movie script about Robots in Mars

交互式模式 CLI

# 启动交互式终端模式(受 Gemini CLI、Codex CLI、Claude Code 启发)
praisonai --interactive
praisonai -i

# 特性:
# - 流式响应(无框)
# - 内置工具:read_file、write_file、list_files、execute_command、internet_search
# - 斜杠命令:/help、/exit、/tools、/clear

# 聊天模式 - 具有交互式风格的单提示(用于测试/脚本编写)
# 使用 --chat(或 --chat-mode 以实现向后兼容)
praisonai "list files in current folder" --chat
praisonai "search the web for AI news" --chat
praisonai "read README.md" --chat

聊天 UI(Web 界面)

# 启动基于 Web 的 Chainlit 聊天界面(需要 praisonai[chat])
pip install "praisonai[chat]"
praisonai chat
# 在浏览器中打开 http://localhost:8084

查询重写(适用于任何命令)

# 重写查询以获得更好的结果(使用 QueryRewriterAgent)
praisonai "AI trends" --query-rewrite

# 使用搜索工具进行重写(智能体决定何时搜索)
praisonai "latest developments" --query-rewrite --rewrite-tools "internet_search"

# 适用于任何提示
praisonai "explain quantum computing" --query-rewrite -v

深度研究 CLI

# 默认:OpenAI (o4-mini-deep-research)
praisonai research "What are the latest AI trends in 2025?"

# 使用 Gemini
praisonai research --model deep-research-pro "Your research query"

# 在研究前重写查询
praisonai research --query-rewrite "AI trends"

# 使用搜索工具进行重写
praisonai research --query-rewrite --rewrite-tools "internet_search" "AI trends"

# 使用文件中的自定义工具(在深度研究前收集上下文)
praisonai research --tools tools.py "Your research query"
praisonai research -t my_tools.py "Your research query"

# 使用内置工具名称(逗号分隔)
praisonai research --tools "internet_search,wiki_search" "Your query"
praisonai research -t "yfinance,calculator_tools" "Stock analysis query"

# 将输出保存到文件(output/research/{query}.md)
praisonai research --save "Your research query"
praisonai research -s "Your research query"

# 组合选项
praisonai research --query-rewrite --tools tools.py --save "Your research query"

# 详细模式(显示调试日志)
praisonai research -v "Your research query"

规划模式 CLI

# 启用规划模式 - 智能体在执行前创建计划
praisonai "Research AI trends and write a summary" --planning

# 规划时使用工具进行研究
praisonai "Analyze market trends" --planning --planning-tools tools.py

# 规划时使用思维链推理
praisonai "Complex analysis task" --planning --planning-reasoning

# 自动批准计划而无需确认
praisonai "Task" --planning --auto-approve-plan

工具批准 CLI

# 自动批准所有工具执行(谨慎使用!)
praisonai "run ls command" --trust

# 自动批准风险级别以下的工具(对更高风险的工具进行提示)
# 级别:low, medium, high, critical
praisonai "write to file" --approve-level high  # 仅对关键工具进行提示
praisonai "task" --approve-level medium         # 对高风险和关键工具进行提示

# 默认行为(无标志):对所有危险工具进行提示
praisonai "run shell command"  # 将提示批准

记忆 CLI

# 为智能体启用记忆(跨会话持久化)
praisonai "My name is John" --memory

# 按用户隔离记忆
praisonai "Remember my preferences" --memory --user-id user123

# 记忆管理命令
praisonai memory show                      # 显示记忆统计信息
praisonai memory add "User prefers Python" # 添加到长期记忆
praisonai memory search "Python"           # 搜索记忆
praisonai memory clear                     # 清除短期记忆
praisonai memory clear all                 # 清除所有记忆
praisonai memory save my_session           # 保存会话
praisonai memory resume my_session         # 恢复会话
praisonai memory sessions                  # 列出保存的会话
praisonai memory checkpoint                # 创建检查点
praisonai memory restore <checkpoint_id>   # 恢复检查点
praisonai memory checkpoints               # 列出检查点
praisonai memory help                      # 显示所有命令

规则 CLI

# 列出所有加载的规则(来自 PRAISON.md、CLAUDE.md 等)
praisonai rules list

# 显示特定规则的详细信息
praisonai rules show <rule_name>

# 创建新规则
praisonai rules create my_rule "Always use type hints"

# 删除规则
praisonai rules delete my_rule

# 显示规则统计信息
praisonai rules stats

# 在提示中包含手动规则
praisonai "Task" --include-rules security,testing

工作流 CLI

# 列出可用的工作流
praisonai workflow list

# 执行带有工具的工作流并保存输出
praisonai workflow run "Research Blog" --tools tavily --save

# 使用变量执行
praisonai workflow run deploy --workflow-var environment=staging --workflow-var branch=main

# 使用规划模式执行(AI 为每个工作流步骤创建子步骤)
praisonai workflow run "Research Blog" --planning --verbose

# 使用推理模式执行(思维链)
praisonai workflow run "Analysis" --reasoning --verbose

# 启用记忆执行
praisonai workflow run "Research" --memory

# 显示工作流详细信息
praisonai workflow show deploy

# 创建新的工作流模板
praisonai workflow create my_workflow

# 内联工作流(无需模板文件)
praisonai "What is AI?" --workflow "Research,Summarize" --save

# 带有步骤操作的内联工作流
praisonai "GPT-5" --workflow "Research:Search for info,Write:Write blog" --tools tavily

# 工作流 CLI 帮助
praisonai workflow help
YAML 工作流文件
# 运行 YAML 工作流文件
praisonai workflow run research.yaml

# 使用变量运行
praisonai workflow run research.yaml --var topic="AI trends"

# 验证 YAML 工作流
praisonai workflow validate research.yaml

# 从模板创建(简单、路由、并行、循环、评估器 - 优化器)
praisonai workflow template routing --output my_workflow.yaml
自动生成工作流
# 从主题自动生成顺序工作流
praisonai workflow auto "Research AI trends"

# 生成并行工作流(多个智能体并发工作)
praisonai workflow auto "Research AI trends" --pattern parallel

# 生成路由工作流(分类器将任务路由到专家)
praisonai workflow auto "Build a chatbot" --pattern routing

# 生成编排器 - 工作者工作流(中央编排器委派任务)
praisonai workflow auto "Comprehensive market analysis" --pattern orchestrator-workers

# 生成评估器 - 优化器工作流(迭代改进)
praisonai workflow auto "Write and refine article" --pattern evaluator-optimizer

# 指定输出文件
praisonai workflow auto "Build a chatbot" --pattern routing

# 指定输出文件
praisonai workflow auto "Research AI" --pattern sequential --output my_workflow.yaml

工作流 CLI 选项 | 标志 | 描述 | |------|-------------| | --workflow-var key=value | 设置工作流变量(可重复) | | --var key=value | 为 YAML 工作流设置变量 | | --pattern <pattern> | 自动生成的模式(顺序、并行、路由、循环、编排器 - 工作者、评估器 - 优化器) | | --output <file> | 自动生成的输出文件 | | --llm <model> | 大语言模型(例如,openai/gpt-4o-mini) | | --tools <tools> | 工具(逗号分隔,例如,tavily) | | --planning | 启用规划模式 | | --reasoning | 启用推理模式 | | --memory | 启用记忆 | | --verbose | 启用详细输出 | | --save | 将输出保存到文件 |

钩子 CLI

# 列出已配置的钩子
praisonai hooks list

# 显示钩子统计信息
praisonai hooks stats

# 创建 hooks.json 模板
praisonai hooks init

Claude 记忆工具 CLI

# 启用 Claude 记忆工具(仅适用于 Anthropic 模型)
praisonai "Research and remember findings" --claude-memory --llm anthropic/claude-sonnet-4-20250514

护栏 CLI

# 使用大语言模型护栏验证输出
praisonai "Write code" --guardrail "Ensure code is secure and follows best practices"

# 与其他标志组合使用
praisonai "Generate SQL query" --guardrail "No DROP or DELETE statements" --save

指标 CLI

# 显示令牌使用情况和成本指标
praisonai "Analyze this data" --metrics

# 与其他功能组合使用
praisonai "Complex task" --metrics --planning

调度器 CLI

praisonai schedule start <name> "task" --interval hourly
praisonai schedule list
praisonai schedule logs <name> [--follow]
praisonai schedule stop <name>
praisonai schedule restart <name>
praisonai schedule delete <name>
praisonai schedule describe <name>
praisonai schedule save <name> [file.yaml]
praisonai schedule "task" --interval hourly  # 前台模式
praisonai schedule agents.yaml  # 前台模式

图像处理 CLI

# 使用基于视觉的任务处理图像
praisonai "Describe this image" --image path/to/image.png

# 分析图像内容
praisonai "What objects are in this photo?" --image photo.jpg --llm openai/gpt-4o

遥测 CLI

# 启用使用情况监控和分析
praisonai "Task" --telemetry

# 与指标结合以实现全面可观察性
praisonai "Complex analysis" --telemetry --metrics

MCP(模型上下文协议)CLI

# 使用 MCP 服务器工具
praisonai "Search files" --mcp "npx -y @modelcontextprotocol/server-filesystem ."

# 带有环境变量的 MCP
praisonai "Search web" --mcp "npx -y @modelcontextprotocol/server-brave-search" --mcp-env "BRAVE_API_KEY=your_key"

# 多个 MCP 选项
praisonai "Task" --mcp "npx server" --mcp-env "KEY1=value1,KEY2=value2"

快速上下文 CLI

# 在代码库中搜索相关上下文
praisonai "Find authentication code" --fast-context ./src

# 为任何任务添加代码上下文
praisonai "Explain this function" --fast-context /path/to/project

知识 CLI

# 向知识库添加文档
praisonai knowledge add document.pdf
praisonai knowledge add ./docs/

# 搜索知识库
praisonai knowledge search "API authentication"

# 列出索引文档
praisonai knowledge list

# 清除知识库
praisonai knowledge clear

# 显示知识库信息
praisonai knowledge info

# 显示所有命令
praisonai knowledge help

会话 CLI

# 列出所有保存的会话
praisonai session list

# 显示会话详细信息
praisonai session show my-project

# 恢复会话(加载到内存中)
praisonai session resume my-project

# 删除会话
praisonai session delete my-project

# 每次运行后自动保存会话
praisonai "Analyze this code" --auto-save my-project

# 从最后 N 个会话加载历史记录到上下文中
praisonai "Continue our discussion" --history 5

会话管理(Python)

from praisonaiagents import Agent

# 每次运行后自动保存会话
agent = Agent(
    name="Assistant",
    memory=True,
    auto_save="my-project"
)

# 从最后 5 个会话加载历史记录
agent = Agent(
    name="Assistant",
    memory=True,
    history_in_context=5
)

工作流检查点

from praisonaiagents.memory.workflows import WorkflowManager

manager = WorkflowManager()

# 每个步骤后保存检查点
result = manager.execute("deploy", checkpoint="deploy-v1")

# 从检查点恢复
result = manager.execute("deploy", resume="deploy-v1")

# 列出/删除检查点
manager.list_checkpoints()
manager.delete_checkpoint("deploy-v1")

工具 CLI

praisonai tools list
praisonai tools info internet_search
praisonai tools search "web"
praisonai tools doctor
praisonai tools resolve shell_tool
praisonai tools discover
praisonai tools show-sources
praisonai tools show-sources --template ai-video-editor

| 命令 | 示例 | 文档 | |---------|---------|------| | tools list | 示例 | 文档 | | tools resolve | 示例 | 文档 | | tools discover | 示例 | 文档 | | tools show-sources | 示例 | 文档 |

交接 CLI

# 启用智能体间任务委派
praisonai "Research and write article" --handoff "researcher,writer,editor"

# 复杂的多智能体工作流
praisonai "Analyze data and create report" --handoff "analyst,visualizer,writer"

自动记忆 CLI

# 启用自动记忆提取
praisonai "Learn about user preferences" --auto-memory

# 与用户隔离结合使用
praisonai "Remember my settings" --auto-memory --user-id user123

待办事项 CLI

# 从任务生成待办事项列表
praisonai "Plan the project" --todo

# 添加待办事项
praisonai todo add "Implement feature X"

# 列出所有待办事项
praisonai todo list

# 完成待办事项
praisonai todo complete 1

# 删除待办事项
praisonai todo delete 1

# 清除所有待办事项
praisonai todo clear

# 显示所有命令
praisonai todo help

路由器 CLI

# 根据任务复杂性自动选择最佳模型
praisonai "Simple question" --router

# 指定首选提供商
praisonai "Complex analysis" --router --router-provider anthropic

# 路由器自动选择:
# - 简单任务 → gpt-4o-mini, claude-3-haiku
# - 复杂任务 → gpt-4-turbo, claude-3-opus

# 使用模型路由模板创建工作流
praisonai workflow create --template model-routing --output my_workflow.yaml

自定义模型可以在 agents.yaml 中配置。有关详细信息,请参阅 模型路由器文档

流程显示 CLI

# 启用可视化工作流跟踪
praisonai agents.yaml --flow-display

# 与其他功能结合使用
praisonai "Multi-step task" --planning --flow-display

文档 CLI

# 列出所有项目文档
praisonai docs list

# 创建新文档
praisonai docs create project-overview "This project is a Python web app..."

# 显示特定文档
praisonai docs show project-overview

# 删除文档
praisonai docs delete old-doc

# 显示所有命令
praisonai docs help

MCP 配置 CLI

# 列出所有 MCP 配置
praisonai mcp list

# 创建新的 MCP 配置
praisonai mcp create filesystem npx -y @modelcontextprotocol/server-filesystem .

# 显示特定配置
praisonai mcp show filesystem

# 启用/禁用配置
praisonai mcp enable filesystem
praisonai mcp disable filesystem

# 删除配置
praisonai mcp delete filesystem

# 显示所有命令
praisonai mcp help

AI 提交 CLI

# 全自动模式:暂存所有更改、进行安全检查、提交并推送
praisonai commit -a

# 交互式模式(需要先执行 git add)
praisonai commit

# 交互式模式并自动推送
praisonai commit --push

# 跳过安全检查(不推荐)
praisonai commit -a --no-verify

特性

  • 🤖 AI 生成的常规提交消息
  • 🔒 内置安全扫描(API 密钥、密码、机密、敏感文件)
  • 📦 使用 -a 标志自动暂存
  • 🚀 全自动模式下自动推送
  • ✏️ 交互式模式下在提交前编辑消息

安全检测

  • API 密钥、机密、令牌(AWS、GitHub、GitLab、Slack)
  • 密码和私钥
  • 敏感文件(.env, id_rsa, .pem, .key 等)

服务 CLI(API 服务器)

# 为 YAML 中定义的智能体启动 API 服务器
praisonai serve agents.yaml

# 使用自定义端口和主机
praisonai serve agents.yaml --port 8005 --host 0.0.0.0

# 替代标志样式
praisonai agents.yaml --serve

# 服务器提供:
# POST /agents          - 按顺序运行所有智能体
# POST /agents/{name}   - 运行特定智能体(例如,/agents/researcher)
# GET  /agents/list     - 列出可用智能体

n8n 集成 CLI

# 将工作流导出到 n8n 并在浏览器中打开
praisonai agents.yaml --n8n

# 使用自定义 n8n URL
praisonai agents.yaml --n8n --n8n-url http://localhost:5678

# 设置 N8N_API_KEY 以实现自动导入
help

运行方式说明

cloud

托管运行

托管运行通常表示这个 MCP Server 由服务方环境承载,用户一般按页面提供的连接方式或授权流程接入,不需要在本地长期启动一个 MCP 进程

  1. 打开服务方连接页
  2. 完成授权或复制端点
  3. 在 MCP 客户端中连接
terminal

本地运行 / 其它方式

本地运行通常需要用户在自己的电脑或服务器上安装依赖,把 server_config 复制到 MCP 客户端,并按 env_schema 补齐环境变量、密钥或其它配置

  1. 复制 server_config
  2. 安装所需依赖
  3. 补齐环境变量后重启客户端