diff --git a/.gitignore b/.gitignore index b593b06..9331cec 100644 --- a/.gitignore +++ b/.gitignore @@ -293,7 +293,7 @@ docker/supabase/volumes/db/data/ infra/docker/volumes/db/data/ # OpenCode local config -.opencode/ +# .opencode/ is now tracked - see .opencode/.gitignore for exclusions # Local git worktrees .worktrees/ diff --git a/.opencode/skills/ag-ui/SKILL.md b/.opencode/skills/ag-ui/SKILL.md new file mode 100644 index 0000000..fe08786 --- /dev/null +++ b/.opencode/skills/ag-ui/SKILL.md @@ -0,0 +1,111 @@ +--- +name: ag-ui +description: AG-UI protocol for agent-user interaction. Use when implementing agent chat, streaming events, tool calls, state synchronization, SSE, multimodal messages, MCP/A2A integration, or any AG-UI protocol development. +--- + +# AG-UI Skills + +AG-UI 协议开发权威指南。**必须使用**场景:构建 agentic 应用、实现 agent 与用户交互、处理流式事件、工具调用生命周期、状态同步、多模态消息、MCP/A2A 集成。提供完整模块索引与源文件行号映射。 + +## 何时使用 + +**必须使用**的场景: +- 实现 Agent 与前端的流式交互 +- 处理 Agent 生命周期事件(RunStarted/Finished、StepStarted/Finished) +- 实现工具调用(ToolCall 事件流) +- Agent 状态管理与前端同步 +- 集成 MCP/A2A 协议的 agent 应用 +- 实现人机协作(Interrupts、Approval 流程) +- 处理多模态消息(文本、图片、音频、视频) + +**查询模式**: +- "如何实现 agent 流式响应" +- "tool call 事件流程" +- "agent state delta 同步" +- "human-in-the-loop interrupt" +- "AG-UI 与 MCP 集成" + +## 模块索引 + +按功能模块查看源文件对应章节: + +| 模块 | 作用 | 源文件行号 | +|------|------|------------| +| [protocol](modules/protocol.md) | 协议概述,与 MCP、A2A 关系 | 1-33 | +| [agents](modules/agents.md) | Agent 概念、架构、类型、实现 | 35-451 | +| [architecture](modules/architecture.md) | 核心架构、设计原则、运行机制 | 453-679 | +| [events](modules/events.md) | 所有事件类型详解 | 680-1475 | +| [generative-ui](modules/generative-ui.md) | 生成式 UI 规范(A2UI/MCP-UI) | 1476-1496 | +| [messages](modules/messages.md) | 消息结构、类型、同步机制 | 1498-1952 | +| [middleware](modules/middleware.md) | 中间件:转换、过滤、增强事件流 | 1954-2158 | +| [reasoning](modules/reasoning.md) | LLM 推理支持,加密推理内容 | 2160-2638 | +| [serialization](modules/serialization.md) | 事件流序列化、压缩、分支 | 2640-2827 | +| [state](modules/state.md) | Agent 与前端状态同步 | 2829-3080 | +| [tools](modules/tools.md) | 工具定义、调用生命周期 | 3082-3441 | +| [drafts](modules/drafts.md) | 提案功能:Generative UI, Interrupts, Meta Events, Multimodal | 3492-4846 | +| [contributing](modules/contributing.md) | 贡献指南、路线图、更新日志 | 3443-3485 | +| [overview](modules/overview.md) | **AG-UI 协议总体介绍** | 4894-5261 | + +## 源文件 + +- `llms-full.txt` - AG-UI 协议完整文档(唯一信源,10632 行) +- `scripts/` - 可执行示例代码(见下方"示例脚本") + +## 示例脚本 + +`scripts/` 目录包含可直接运行的 TypeScript 示例: + +| 示例 | 用途 | 参考文档 | +|------|------|---------| +| [minimal_agent.ts](scripts/minimal_agent.ts) | 最小 Agent 实现 | [agents](modules/agents.md) 行 132-197 | +| [tool_call_example.ts](scripts/tool_call_example.ts) | 工具调用流程 | [events](modules/events.md) 行 938-1066 | +| [state_sync_example.ts](scripts/state_sync_example.ts) | Snapshot-Delta 状态同步 | [events](modules/events.md) 行 1067-1155 | + +**运行示例**: +```bash +# 安装依赖 +npm install @ag-ui/client rxjs + +# 运行 +npx ts-node scripts/minimal_agent.ts +``` + +详见 [scripts/README.md](scripts/README.md) + +## 常见事件速查 + +| 场景 | 关键事件 | 详见 | +|------|---------|------| +| 流式响应 | TextMessageStart → Content → End | [events](modules/events.md) 行 835-937 | +| 工具调用 | ToolCallStart → Args → End → Result | [events](modules/events.md) 行 938-1066 | +| 状态同步 | StateSnapshot, StateDelta | [events](modules/events.md) 行 1067-1155 | +| 生命周期 | RunStarted/Finished, StepStarted/Finished | [events](modules/events.md) 行 715-754 | +| 人机中断 | RunFinished(interrupt) | [drafts](modules/drafts.md) 行 3897-3920 | + +## 快速路径 + +**新手入门**: +1. [overview](modules/overview.md) - **理解 AG-UI 协议全貌与定位** +2. [protocol](modules/protocol.md) - AG-UI 在 AI 协议栈的位置(与 MCP/A2A 关系) +3. [architecture](modules/architecture.md) - 核心概念与设计原则 +4. [agents](modules/agents.md) - Agent 基础实现 +5. 运行 [minimal_agent.ts](scripts/minimal_agent.ts) 体验基础事件流 + +**实现功能**: +- 流式响应 → [events](modules/events.md) (TextMessage 事件) + [minimal_agent.ts](scripts/minimal_agent.ts) +- 工具调用 → [tools](modules/tools.md) + [events](modules/events.md) (ToolCall 事件) + [tool_call_example.ts](scripts/tool_call_example.ts) +- 状态同步 → [state](modules/state.md) + [events](modules/events.md) (StateDelta) + [state_sync_example.ts](scripts/state_sync_example.ts) +- 中间件 → [middleware](modules/middleware.md) + +**高级特性**: +- 人机协作 → [drafts](modules/drafts.md) (Interrupts) +- 多模态 → [drafts](modules/drafts.md) (Multimodal Messages) +- 生成式 UI → [generative-ui](modules/generative-ui.md) + [drafts](modules/drafts.md) (Generative UI) +- 推理加密 → [reasoning](modules/reasoning.md) + +## 建议使用方式 + +1. 先阅读 [architecture](modules/architecture.md) 了解核心概念 +2. 根据需要查看具体模块 +3. 事件类型参考 [events](modules/events.md) +4. 实现细节参考对应功能模块 diff --git a/docs/knowledges/ag-ui-llms-full.txt b/.opencode/skills/ag-ui/llms-full.txt similarity index 100% rename from docs/knowledges/ag-ui-llms-full.txt rename to .opencode/skills/ag-ui/llms-full.txt diff --git a/.opencode/skills/ag-ui/modules/agents.md b/.opencode/skills/ag-ui/modules/agents.md new file mode 100644 index 0000000..5f4c5cd --- /dev/null +++ b/.opencode/skills/ag-ui/modules/agents.md @@ -0,0 +1,16 @@ +# Agents + +**作用**: 介绍 AG-UI 中 Agent 的概念、架构、类型和实现方式。 + +**源文件**: `llms-full.txt` +**行号范围**: 35-451 + +**内容索引**: +- 什么是 Agent (行 47-62) +- Agent Architecture - AbstractAgent, 核心组件 (行 63-91) +- Agent Types - HttpAgent, Custom Agents (行 93-130) +- Implementing Agents - 基本实现示例 (行 132-197) +- Agent Capabilities - 交互通信、工具使用、状态管理、多 Agent 协作、人机协作、对话记忆 (行 199-358) +- 使用 Agent (行 360-399) +- Agent Configuration (行 401-424) +- Agent State Management (行 426-439) diff --git a/.opencode/skills/ag-ui/modules/architecture.md b/.opencode/skills/ag-ui/modules/architecture.md new file mode 100644 index 0000000..2a70cb9 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/architecture.md @@ -0,0 +1,17 @@ +# Core Architecture + +**作用**: 介绍 AG-UI 的核心架构、设计原则和运行机制。 + +**源文件**: `llms-full.txt` +**行号范围**: 453-679 + +**内容索引**: +- Design Principles - 事件驱动、双向交互、灵活中间件 (行 463-489) +- Architectural Overview - 客户端-服务器架构 (行 491-534) +- Protocol layer - run(input) -> Observable (行 537-567) +- Standard HTTP client - HttpAgent, SSE/HTTP binary (行 569-585) +- Message types - Lifecycle, Text, Tool, State, Special 事件 (行 587-609) +- Running Agents (行 611-640) +- State Management - STATE_SNAPSHOT, STATE_DELTA (行 642-652) +- Tools and Handoff (行 653-662) +- Base Event 属性 (行 664-677) diff --git a/.opencode/skills/ag-ui/modules/contributing.md b/.opencode/skills/ag-ui/modules/contributing.md new file mode 100644 index 0000000..829bbdb --- /dev/null +++ b/.opencode/skills/ag-ui/modules/contributing.md @@ -0,0 +1,15 @@ +# Contributing & Roadmap + +**作用**: 贡献指南、路线图和更新日志。 + +**源文件**: `llms-full.txt` +**行号范围**: 3443-3485 + +**内容索引**: +- Contributing (行 3443-3460): + - Naming conventions - integrations/, wip-, community- 前缀 (行 3448-3459) +- Roadmap (行 3462-3481): + - 公开路线图链接 (行 3467-3468) + - Get Involved - 贡献方式 (行 3470-3474) +- What's New (行 3477-3485): + - 2025-04-09: AG-UI 仓库公开发布 (行 3482-3484) diff --git a/.opencode/skills/ag-ui/modules/drafts.md b/.opencode/skills/ag-ui/modules/drafts.md new file mode 100644 index 0000000..315a5e4 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/drafts.md @@ -0,0 +1,53 @@ +# Drafts + +**作用**: 介绍 AG-UI 协议中正在考虑或开发中的提案功能。 + +**源文件**: `llms-full.txt` +**行号范围**: 3492-3854 (Generative UI), 3860-4105 (Interrupts), 4111-4349 (Meta Events), 4355-4846 (Multimodal) + +**Drafts 概述** (行 4847-4887): +- Drafts 状态定义 - Draft/Under Review/Accepted/Implemented/Withdrawn (行 4880-4886) + +**Generative User Interfaces** (行 3492-3854): + - Summary - 问题陈述与动机 (行 3494-3508) + - Challenges and Limitations - 工具描述长度、JSON Schema 约束 (行 3515-3531) + - Detailed Specification: + - Two-Step Generation Process - 两步生成流程图 (行 3535-3543) + - Step 1: What to Generate? - generateUserInterface 工具 (行 3545-3596) + - Step 2: How to Generate? - 次级 LLM 生成实际 UI (行 3598-3612) + - Implementation Examples: + - UISchemaGenerator - JSON Schema 输出 (行 3615-3673) + - ReactFormHookGenerator - React Hook Form 代码生成 (行 3675-3795) + - Implementation Considerations - SDK 变更 (行 3797-3819) + - Use Cases - 动态表单、数据可视化、交互式工作流 (行 3821-3838) + +**Interrupt-Aware Run Lifecycle** (行 3860-4105): + - Summary - 人机协作暂停机制 (行 3862-3875) + - Updates to RUN_FINISHED Event - outcome, interrupt 字段 (行 3897-3920) + - Updates to RunAgentInput - resume 字段 (行 3922-3937) + - Contract Rules (行 3939-3945) + - Implementation Examples (行 3947-4026) + - Use Cases - 人类批准、信息收集、策略强制 (行 4028-4051) + - Implementation Considerations (行 4052-4091) + +**Meta Events** (行 4111-4349): + - Summary - 独立于 Agent 运行的事件注解 (行 4115-4127) + - MetaEvent Type - metaType, payload (行 4145-4170) + - Implementation Examples: + - User Feedback - thumbs_up, thumbs_down (行 4174-4206) + - Annotations - note, tag (行 4208-4239) + - External System Events - analytics, moderation (行 4241-4276) + - Common Meta Event Types 表 (行 4278-4292) + - Use Cases (行 4294-4318) + +**Multimodal Messages** (行 4355-4846): + - Summary - 支持多模态输入消息 (行 4357-4371) + - Status: Implemented (行 4373-4376) + - Detailed Specification: + - Modality Types 表 - text, image, audio, video, document (行 4473-4483) + - Source Types - InputContentDataSource, InputContentUrlSource (行 4485-4509) + - Content Part Types - TextInputPart, ImageInputPart, AudioInputPart, VideoInputPart, DocumentInputPart (行 4511-4561) + - Provider Metadata (行 4562-4571) + - Implementation Examples (行 4573-4764) + - Implementation Considerations (行 4766-4798) + - Use Cases (行 4800-4827) diff --git a/.opencode/skills/ag-ui/modules/events.md b/.opencode/skills/ag-ui/modules/events.md new file mode 100644 index 0000000..cf6c928 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/events.md @@ -0,0 +1,20 @@ +# Events + +**作用**: 详细介绍 AG-UI 协议中的所有事件类型,包括生命周期、文本、工具调用、状态管理、推理等事件。 + +**源文件**: `llms-full.txt` +**行号范围**: 680-1475 + +**内容索引**: +- Event Types Overview - 事件分类表 (行 692-703) +- Base Event Properties (行 705-713) +- Lifecycle Events - RunStarted, RunFinished, RunError, StepStarted, StepFinished (行 715-754) +- Text Message Events - TextMessageStart, TextMessageContent, TextMessageEnd, TextMessageChunk (行 835-937) +- Tool Call Events - ToolCallStart, ToolCallArgs, ToolCallEnd, ToolCallResult, ToolCallChunk (行 938-1066) +- State Management Events - StateSnapshot, StateDelta, MessagesSnapshot (行 1067-1155) +- Activity Events - ActivitySnapshot, ActivityDelta (行 1156-1189) +- Special Events - Raw, Custom (行 1191-1233) +- Reasoning Events - ReasoningStart, ReasoningMessageStart/Content/End/Chunk, ReasoningEnd, ReasoningEncryptedValue (行 1234-1368) +- Deprecated Events - THINKING_* 事件迁移 (行 1369-1389) +- Draft Events - Meta Events, Modified Lifecycle Events (行 1391-1446) +- Event Flow Patterns - Start-Content-End, Snapshot-Delta, Lifecycle (行 1447-1474) diff --git a/.opencode/skills/ag-ui/modules/generative-ui.md b/.opencode/skills/ag-ui/modules/generative-ui.md new file mode 100644 index 0000000..aee800d --- /dev/null +++ b/.opencode/skills/ag-ui/modules/generative-ui.md @@ -0,0 +1,11 @@ +# Generative UI Specs + +**作用**: 介绍 AG-UI 与生成式 UI 规范的关系(A2UI、MCP-UI、Open-JSON-UI)。 + +**源文件**: `llms-full.txt` +**行号范围**: 1476-1496 + +**内容索引**: +- AG-UI and Generative UI Specs - AG-UI 不是生成式 UI 规范,而是用户交互协议 (行 1476-1496) +- AG-UI 与 A2UI、MCP-UI、Open-JSON-UI 的关系说明 +- Generative UI 实现详情见 [drafts](drafts.md) 的 Generative User Interfaces 章节 (行 3492-3854) diff --git a/.opencode/skills/ag-ui/modules/messages.md b/.opencode/skills/ag-ui/modules/messages.md new file mode 100644 index 0000000..3d85435 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/messages.md @@ -0,0 +1,21 @@ +# Messages + +**作用**: 介绍 AG-UI 中消息的结构、类型和同步机制。 + +**源文件**: `llms-full.txt` +**行号范围**: 1498-1952 + +**内容索引**: +- Message Structure - BaseMessage 接口, role, encryptedContent (行 1510-1537) +- Message Types: + - UserMessage - 用户消息, 支持多模态 InputContent (行 1543-1576) + - AssistantMessage - 助手消息, 含 toolCalls (行 1578-1591) + - SystemMessage - 系统消息 (行 1593-1604) + - ToolMessage - 工具结果消息 (行 1606-1627) + - ActivityMessage - 前端专用活动消息 (行 1628-1653) + - DeveloperMessage - 开发/调试消息 (行 1654-1665) + - ReasoningMessage - 推理消息 (行 1667-1704) +- Vendor Neutrality - 供应商中立性, 格式转换示例 (行 1705-1735) +- Message Synchronization - MESSAGES_SNAPSHOT, 流式消息 (行 1736-1794) +- Tool Integration - ToolCall, ToolResult 结构 (行 1795-1889) +- Practical Example - 完整对话示例 (行 1891-1939) diff --git a/.opencode/skills/ag-ui/modules/middleware.md b/.opencode/skills/ag-ui/modules/middleware.md new file mode 100644 index 0000000..36b1297 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/middleware.md @@ -0,0 +1,18 @@ +# Middleware + +**作用**: 介绍 AG-UI 中间件,用于转换、过滤和增强事件流。 + +**源文件**: `llms-full.txt` +**行号范围**: 1954-2158 + +**内容索引**: +- What is Middleware? - 中间件的作用 (行 1965-1973) +- How Middleware Works - 中间件链式调用 (行 1975-1991) +- Function-Based Middleware - 函数式中间件示例 (行 1993-2019) +- Class-Based Middleware - 类中间件示例 (行 2021-2055) +- Built-in Middleware - FilterToolCallsMiddleware (行 2062-2086) +- Middleware Patterns - 日志、认证、限流 (行 2088-2090) +- Combining Middleware (行 2092-2103) +- Execution Order - 中间件执行顺序 (行 2104-2124) +- Best Practices (行 2126-2134) +- Conditional Middleware (行 2136-2153) diff --git a/.opencode/skills/ag-ui/modules/overview.md b/.opencode/skills/ag-ui/modules/overview.md new file mode 100644 index 0000000..51f9f3b --- /dev/null +++ b/.opencode/skills/ag-ui/modules/overview.md @@ -0,0 +1,28 @@ +# AG-UI Overview + +**作用**: AG-UI 协议总体介绍,包括协议定位、核心特性、与其他协议的关系、以及构建块概览。 + +**源文件**: `llms-full.txt` +**行号范围**: 4894-5261 + +**内容索引**: +- 协议定义 - 开放、轻量、事件驱动的 Agent-User 交互协议 (行 4894-4901) +- Agentic Protocols - MCP/A2A/AG-UI 三层协议栈 (行 4910-4923) +- Building Blocks (行 4926-5088): + - Streaming chat - 流式对话 (行 4930-4941) + - Tool calling - 工具调用 (行 4943-4953) + - Structured state - 结构化状态 (行 4955-4965) + - Generative UI - 生成式 UI (行 4967-4977) + - Contextual context - 上下文管理 (行 4979-4989) + - Client-side tools - 客户端工具 (行 4991-5001) + - Auth & multi-tenancy - 认证与多租户 (行 5003-5013) + - Debugging & evals - 调试与评估 (行 5015-5025) + - Upcoming: Reasoning continuity - 推理连续性 (行 5027-5037) + - Upcoming: Multi-modal - 多模态 (行 5039-5049) + - Upcoming: Generative UI - 生成式 UI (行 5051-5061) + - Upcoming: Interrupts & approval flows - 中断与审批流程 (行 5063-5073) + - Upcoming: Meta events - 元事件 (行 5075-5085) +- Protocol Basics (行 5090-5261): + - Agent Definition - Agent 定义 (行 5095-5109) + - Event Stream - 事件流 (行 5111-5129) + - Common Patterns - 常见模式 (行 5131-5151) diff --git a/.opencode/skills/ag-ui/modules/protocol.md b/.opencode/skills/ag-ui/modules/protocol.md new file mode 100644 index 0000000..cbf3a3b --- /dev/null +++ b/.opencode/skills/ag-ui/modules/protocol.md @@ -0,0 +1,11 @@ +# Protocol + +**作用**: 介绍 AG-UI 与 MCP、A2A 协议的关系,以及 AG-UI 作为连接 Agent 与用户应用的协议定位。 + +**源文件**: `llms-full.txt` +**行号范围**: 1-33 + +**内容索引**: +- Agentic Protocols 概述 (MCP, A2A, AG-UI) +- AG-UI 与 MCP、A2A 的握手 +- Generative UI Specs 介绍 diff --git a/.opencode/skills/ag-ui/modules/reasoning.md b/.opencode/skills/ag-ui/modules/reasoning.md new file mode 100644 index 0000000..fa513a2 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/reasoning.md @@ -0,0 +1,26 @@ +# Reasoning + +**作用**: 介绍 AG-UI 对 LLM 推理的支持,包括链式思维可视化和加密推理内容。 + +**源文件**: `llms-full.txt` +**行号范围**: 2160-2638 + +**内容索引**: +- Overview - 推理可见性、状态连续性、隐私合规 (行 2171-2188) +- ReasoningMessage - 推理消息结构 (行 2190-2217) +- Reasoning Events: + - Event Flow - 推理事件流程图 (行 2223-2246) + - Event Types 表 (行 2248-2258) +- Privacy and Compliance: + - Zero Data Retention (ZDR) - 零数据保留 (行 2264-2273) + - Visibility Control - 可见性控制 (行 2274-2284) + - Compliance Considerations 表 - GDPR, SOC 2, HIPAA (行 2285-2293) +- Example Implementations: + - Basic Reasoning Flow (行 2296-2348) + - Encrypted Content for State Continuity (行 2350-2396) + - Attaching Encrypted Reasoning to Tool Calls (行 2398-2430) + - ZDR-Compliant Implementation (行 2432-2475) + - Using Convenience Chunk Event (行 2477-2503) +- Client Integration - 处理推理事件, 传递加密推理 (行 2505-2563) +- Migration from Thinking Events - THINKING_* 迁移到 REASONING_* (行 2565-2617) +- Best Practices (行 2619-2632) diff --git a/.opencode/skills/ag-ui/modules/serialization.md b/.opencode/skills/ag-ui/modules/serialization.md new file mode 100644 index 0000000..28d16a0 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/serialization.md @@ -0,0 +1,21 @@ +# Serialization + +**作用**: 介绍 AG-UI 事件流的序列化,用于历史恢复、分支和时间旅行。 + +**源文件**: `llms-full.txt` +**行号范围**: 2640-2827 + +**内容索引**: +- Core Concepts: + - Stream serialization - 事件流转为 JSON (行 2660-2662) + - Event compaction - 压缩事件流 (行 2662-2663) + - Run lineage - parentRunId 实现 git 类日志 (行 2664-2665) +- Updated Event Fields - RunStarted 新增 parentRunId, input (行 2667-2685) +- Event Compaction - compactEvents 函数, 压缩规则 (行 2686-2704) +- Branching and Time Travel - parentRunId 创建分支, git 类日志 (行 2705-2729) +- Examples: + - Basic Serialization (行 2732-2744) + - Event Compaction - 压缩前后示例 (行 2746-2774) + - Branching With parentRunId (行 2776-2795) + - Normalized Input (行 2797-2814) +- Implementation Notes (行 2816-2822) diff --git a/.opencode/skills/ag-ui/modules/state.md b/.opencode/skills/ag-ui/modules/state.md new file mode 100644 index 0000000..e7e4b9f --- /dev/null +++ b/.opencode/skills/ag-ui/modules/state.md @@ -0,0 +1,18 @@ +# State Management + +**作用**: 介绍 AG-UI 中 Agent 与前端之间的状态同步机制。 + +**源文件**: `llms-full.txt` +**行号范围**: 2829-3080 + +**内容索引**: +- Shared State Architecture - 共享状态架构, 双向通信 (行 2842-2857) +- State Synchronization Methods: + - State Snapshots - STATE_SNAPSHOT 事件 (行 2862-2882) + - State Deltas - STATE_DELTA 事件, JSON Patch (行 2884-2902) +- JSON Patch Format: + - RFC 6902 操作: add, replace, remove, move, copy, test (行 2903-2944) +- State Processing in AG-ui - fast-json-patch 使用示例 (行 2946-2977) +- Human-in-the-Loop Collaboration - 人机协作示例 (行 2978-3005) +- CopilotKit Implementation - useCoAgent, copilotkit_emit_state (行 3007-3050) +- Best Practices (行 3052-3068) diff --git a/.opencode/skills/ag-ui/modules/tools.md b/.opencode/skills/ag-ui/modules/tools.md new file mode 100644 index 0000000..3b8f7d9 --- /dev/null +++ b/.opencode/skills/ag-ui/modules/tools.md @@ -0,0 +1,24 @@ +# Tools + +**作用**: 介绍 AG-UI 中工具的定义、使用和人在环工作流。 + +**源文件**: `llms-full.txt` +**行号范围**: 3082-3441 + +**内容索引**: +- What Are Tools? - 工具的作用 (行 3095-3105) +- Tool Structure - Tool 接口定义 (行 3107-3130) +- Frontend-Defined Tools - 工具由前端定义并传递给 Agent (行 3132-3175) +- Tool Call Lifecycle: + - ToolCallStart (行 3179-3191) + - ToolCallArgs - 流式参数 (行 3193-3217) + - ToolCallEnd (行 3219-3229) +- Tool Results - ToolMessage 结构 (行 3231-3246) +- Human-in-the-Loop Workflows - 人机协作工作流 (行 3248-3270) +- CopilotKit Integration - useCopilotAction hook (行 3272-3304) +- Tool Examples: + - User Confirmation (行 3310-3332) + - Data Retrieval (行 3334-3358) + - User Interface Control (行 3360-3381) + - Content Generation (行 3383-3412) +- Best Practices (行 3414-3428) diff --git a/.opencode/skills/ag-ui/scripts/README.md b/.opencode/skills/ag-ui/scripts/README.md new file mode 100644 index 0000000..4557c29 --- /dev/null +++ b/.opencode/skills/ag-ui/scripts/README.md @@ -0,0 +1,163 @@ +# AG-UI 示例脚本 + +本目录包含 AG-UI 协议的实现示例,帮助开发者快速上手。 + +## 前置要求 + +```bash +# 安装依赖 +npm install @ag-ui/client rxjs + +# 或 +pnpm add @ag-ui/client rxjs +``` + +## 示例列表 + +### 1. minimal_agent.ts - 最小 Agent 实现 + +展示如何创建一个最基本的 AG-UI Agent,实现事件流。 + +**核心概念**: +- 继承 `AbstractAgent` 类 +- 实现 `run()` 方法返回 Observable 事件流 +- 发送生命周期事件 (RUN_STARTED/RUN_FINISHED) +- 发送文本消息事件 (TEXT_MESSAGE_START/CONTENT/END) + +**运行**: +```bash +# 使用 ts-node +npx ts-node scripts/minimal_agent.ts + +# 或编译后运行 +npx tsc scripts/minimal_agent.ts --esModuleInterop +node scripts/minimal_agent.js +``` + +**参考文档**: [modules/agents.md](../modules/agents.md) 行 132-197 + +--- + +### 2. tool_call_example.ts - 工具调用流程 + +展示 Agent 如何调用工具并流式传输参数和结果。 + +**核心概念**: +- 定义工具 (Tool) +- 工具调用事件流: ToolCallStart → ToolCallArgs → ToolCallEnd → ToolCallResult +- 流式传输工具参数(分块发送) +- 基于工具结果生成响应 + +**事件流**: +``` +ToolCallStart (工具名称) + ↓ +ToolCallArgs (参数片段 1) +ToolCallArgs (参数片段 2) +ToolCallArgs (参数片段 3) + ↓ +ToolCallEnd (参数传输完成) + ↓ +ToolCallResult (工具执行结果) +``` + +**运行**: +```bash +npx ts-node scripts/tool_call_example.ts +``` + +**参考文档**: [modules/events.md](../modules/events.md) 行 938-1066 + +--- + +### 3. state_sync_example.ts - 状态同步 + +展示 Agent 与前端的 Snapshot-Delta 状态同步模式。 + +**核心概念**: +- StateSnapshot - 完整状态快照 +- StateDelta - 增量更新 (JSON Patch RFC 6902) +- MessagesSnapshot - 消息历史快照 +- 前端状态管理器实现 + +**状态同步模式**: +``` +初始同步: + StateSnapshot (完整状态) + MessagesSnapshot (消息历史) + ↓ +增量更新: + StateDelta (JSON Patch 操作) + StateDelta (另一个更新) + ↓ +周期性刷新: + StateSnapshot (确保一致性) +``` + +**JSON Patch 操作类型**: +- `replace` - 替换值 +- `add` - 添加字段 +- `remove` - 删除字段 + +**运行**: +```bash +npx ts-node scripts/state_sync_example.ts +``` + +**参考文档**: [modules/events.md](../modules/events.md) 行 1067-1155 + +--- + +## 常见问题 + +### Q: 这些示例可以直接用于生产环境吗? + +A: 这些示例仅用于教学目的。生产环境应考虑: +- 错误处理和重试机制 +- 认证和授权 +- 日志和监控 +- 性能优化(如事件节流) + +### Q: 如何处理工具调用的并发? + +A: 每个工具调用有唯一的 `toolCallId`,可以并发执行多个工具: +```typescript +// 工具调用 1 +ToolCallStart(toolCallId: "tool_1") +ToolCallArgs(toolCallId: "tool_1", delta: "...") +ToolCallEnd(toolCallId: "tool_1") + +// 工具调用 2(并发) +ToolCallStart(toolCallId: "tool_2") +ToolCallArgs(toolCallId: "tool_2", delta: "...") +ToolCallEnd(toolCallId: "tool_2") +``` + +### Q: StateDelta 的 JSON Patch 格式如何工作? + +A: JSON Patch (RFC 6902) 是标准的增量更新格式: +```json +[ + { "op": "replace", "path": "/session/currentPage", "value": 2 }, + { "op": "add", "path": "/formData", "value": {...} }, + { "op": "remove", "path": "/tempField" } +] +``` + +推荐使用 [fast-json-patch](https://github.com/Starcounter-Jack/Fast-JSON-Patch) 库处理。 + +--- + +## 进阶示例 + +需要更复杂的示例?查看官方仓库: +- [AG-UI GitHub](https://github.com/ag-ui/ag-ui) +- [CopilotKit Examples](https://github.com/CopilotKit/CopilotKit/tree/main/examples) + +--- + +## 相关资源 + +- [AG-UI 协议文档](../llms-full.txt) - 完整协议规范 +- [模块索引](../SKILL.md#模块索引) - 按功能查找文档 +- [常见事件速查](../SKILL.md#常见事件速查) - 高频事件流程 diff --git a/.opencode/skills/ag-ui/scripts/minimal_agent.ts b/.opencode/skills/ag-ui/scripts/minimal_agent.ts new file mode 100644 index 0000000..ff2f29d --- /dev/null +++ b/.opencode/skills/ag-ui/scripts/minimal_agent.ts @@ -0,0 +1,99 @@ +/** + * 最小 AG-UI Agent 实现示例 + * + * 展示如何创建一个自定义 Agent,实现基本的事件流 + * + * 参考文档: modules/agents.md (行 132-197) + */ + +import { + AbstractAgent, + RunAgent, + RunAgentInput, + EventType, + BaseEvent, +} from "@ag-ui/client" +import { Observable } from "rxjs" + +class MinimalAgent extends AbstractAgent { + /** + * 实现 run 方法,返回事件流 + */ + run(input: RunAgentInput): RunAgent { + const { threadId, runId } = input + + return () => + new Observable((observer) => { + // 1. 发送 RUN_STARTED 事件 + observer.next({ + type: EventType.RUN_STARTED, + threadId, + runId, + }) + + // 2. 发送文本消息 + const messageId = Date.now().toString() + + // 消息开始 + observer.next({ + type: EventType.TEXT_MESSAGE_START, + messageId, + role: "assistant", + }) + + // 消息内容(流式) + observer.next({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId, + delta: "Hello! ", + }) + + observer.next({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId, + delta: "I'm a minimal AG-UI agent.", + }) + + // 消息结束 + observer.next({ + type: EventType.TEXT_MESSAGE_END, + messageId, + }) + + // 3. 发送 RUN_FINISHED 事件 + observer.next({ + type: EventType.RUN_FINISHED, + threadId, + runId, + }) + + // 完成流 + observer.complete() + }) + } +} + +// 使用示例 +const agent = new MinimalAgent({ + agentId: "minimal-agent", + description: "A minimal AG-UI agent example", +}) + +// 运行 Agent 并订阅事件流 +agent + .runAgent({ + runId: "run_123", + threadId: "thread_456", + messages: [], + tools: [], + context: [], + }) + .subscribe({ + next: (event) => { + console.log(`[${event.type}]`, event) + }, + error: (error) => console.error("Error:", error), + complete: () => console.log("Agent run completed"), + }) + +export { MinimalAgent } diff --git a/.opencode/skills/ag-ui/scripts/state_sync_example.ts b/.opencode/skills/ag-ui/scripts/state_sync_example.ts new file mode 100644 index 0000000..a377fc6 --- /dev/null +++ b/.opencode/skills/ag-ui/scripts/state_sync_example.ts @@ -0,0 +1,255 @@ +/** + * AG-UI 状态同步示例 + * + * 展示 Agent 与前端的 Snapshot-Delta 状态同步模式 + * + * 参考文档: modules/events.md (行 1067-1155) + * + * 状态管理模式: + * 1. StateSnapshot - 完整状态快照(初始同步/周期性刷新) + * 2. StateDelta - 增量更新(JSON Patch RFC 6902) + * 3. MessagesSnapshot - 消息历史快照 + */ + +import { + AbstractAgent, + RunAgent, + RunAgentInput, + EventType, + BaseEvent, +} from "@ag-ui/client" +import { Observable } from "rxjs" + +/** + * Agent 状态定义示例 + */ +interface AgentState { + user: { + name: string + preferences: { + theme: "light" | "dark" + language: string + } + } + session: { + currentPage: number + itemsPerPage: number + totalItems: number + } + formData?: { + [key: string]: any + } +} + +class StateSyncAgent extends AbstractAgent { + private state: AgentState = { + user: { + name: "Alice", + preferences: { + theme: "light", + language: "en", + }, + }, + session: { + currentPage: 1, + itemsPerPage: 10, + totalItems: 100, + }, + } + + run(input: RunAgentInput): RunAgent { + const { threadId, runId } = input + + return () => + new Observable((observer) => { + observer.next({ + type: EventType.RUN_STARTED, + threadId, + runId, + }) + + // 1. 发送初始状态快照 + observer.next({ + type: EventType.STATE_SNAPSHOT, + snapshot: this.state, + }) + + // 2. 发送消息历史快照 + observer.next({ + type: EventType.MESSAGES_SNAPSHOT, + messages: [ + { + id: "msg_1", + role: "user", + content: "Show me page 2", + }, + { + id: "msg_2", + role: "assistant", + content: "Loading page 2...", + }, + ], + }) + + // 3. 模拟状态变化 - 分页更新 + setTimeout(() => { + // 发送 Delta 更新(JSON Patch 格式) + observer.next({ + type: EventType.STATE_DELTA, + delta: [ + { op: "replace", path: "/session/currentPage", value: 2 }, + ], + }) + }, 500) + + // 4. 模拟用户偏好更新 + setTimeout(() => { + observer.next({ + type: EventType.STATE_DELTA, + delta: [ + { op: "replace", path: "/user/preferences/theme", value: "dark" }, + ], + }) + }, 1000) + + // 5. 添加新字段(表单数据) + setTimeout(() => { + observer.next({ + type: EventType.STATE_DELTA, + delta: [ + { + op: "add", + path: "/formData", + value: { + searchQuery: "AG-UI tutorial", + filters: ["beginner", "typescript"], + }, + }, + ], + }) + }, 1500) + + // 6. 周期性完整快照(确保状态一致性) + setTimeout(() => { + const updatedState: AgentState = { + ...this.state, + session: { + ...this.state.session, + currentPage: 2, + }, + user: { + ...this.state.user, + preferences: { + ...this.state.user.preferences, + theme: "dark", + }, + }, + formData: { + searchQuery: "AG-UI tutorial", + filters: ["beginner", "typescript"], + }, + } + + observer.next({ + type: EventType.STATE_SNAPSHOT, + snapshot: updatedState, + }) + + observer.next({ + type: EventType.RUN_FINISHED, + threadId, + runId, + }) + + observer.complete() + }, 2000) + }) + } +} + +/** + * 前端状态管理示例(接收端) + */ +class StateManager { + private state: AgentState | null = null + + handleEvent(event: BaseEvent) { + switch (event.type) { + case EventType.STATE_SNAPSHOT: + // 完整替换状态 + this.state = (event as any).snapshot as AgentState + console.log("[State] Snapshot received:", this.state) + break + + case EventType.STATE_DELTA: + // 应用 JSON Patch 增量更新 + if (this.state) { + const patches = (event as any).delta + this.state = this.applyPatches(this.state, patches) + console.log("[State] Delta applied:", patches) + console.log("[State] Current state:", this.state) + } + break + + case EventType.MESSAGES_SNAPSHOT: + console.log("[Messages] Snapshot:", (event as any).messages) + break + } + } + + /** + * 应用 JSON Patch 操作(简化实现) + * 生产环境应使用 json-patch 库 + */ + private applyPatches(state: AgentState, patches: any[]): AgentState { + const newState = JSON.parse(JSON.stringify(state)) + + for (const patch of patches) { + const { op, path, value } = patch + const pathParts = path.split("/").filter(Boolean) + let target: any = newState + + // 导航到目标对象的父级 + for (let i = 0; i < pathParts.length - 1; i++) { + target = target[pathParts[i]] + } + + const lastKey = pathParts[pathParts.length - 1] + + switch (op) { + case "replace": + target[lastKey] = value + break + case "add": + target[lastKey] = value + break + case "remove": + delete target[lastKey] + break + } + } + + return newState + } +} + +// 使用示例 +const agent = new StateSyncAgent() +const stateManager = new StateManager() + +agent + .runAgent({ + runId: "run_state_sync", + threadId: "thread_123", + messages: [], + tools: [], + context: [], + }) + .subscribe({ + next: (event) => { + stateManager.handleEvent(event) + }, + complete: () => console.log("\n[Complete] State sync demo finished"), + }) + +export { StateSyncAgent, StateManager, AgentState } diff --git a/.opencode/skills/ag-ui/scripts/tool_call_example.ts b/.opencode/skills/ag-ui/scripts/tool_call_example.ts new file mode 100644 index 0000000..8194200 --- /dev/null +++ b/.opencode/skills/ag-ui/scripts/tool_call_example.ts @@ -0,0 +1,201 @@ +/** + * AG-UI 工具调用示例 + * + * 展示 Agent 如何调用工具并流式传输参数和结果 + * + * 参考文档: modules/events.md (行 938-1066) + * + * 事件流: + * 1. ToolCallStart - 工具调用开始 + * 2. ToolCallArgs (多次) - 流式传输参数 + * 3. ToolCallEnd - 参数传输完成 + * 4. ToolCallResult - 工具执行结果 + */ + +import { + AbstractAgent, + RunAgent, + RunAgentInput, + EventType, + BaseEvent, +} from "@ag-ui/client" +import { Observable } from "rxjs" + +/** + * 工具定义示例 + */ +interface Tool { + name: string + description: string + parameters: Record +} + +const weatherTool: Tool = { + name: "get_weather", + description: "Get current weather for a location", + parameters: { + type: "object", + properties: { + location: { + type: "string", + description: "City name", + }, + unit: { + type: "string", + enum: ["celsius", "fahrenheit"], + }, + }, + required: ["location"], + }, +} + +class ToolCallingAgent extends AbstractAgent { + run(input: RunAgentInput): RunAgent { + const { threadId, runId } = input + + return () => + new Observable((observer) => { + observer.next({ + type: EventType.RUN_STARTED, + threadId, + runId, + }) + + // 模拟 Agent 分析用户请求后决定调用工具 + const toolCallId = `tool_${Date.now()}` + const messageId = `msg_${Date.now()}` + + // 1. 发送文本消息说明 + observer.next({ + type: EventType.TEXT_MESSAGE_START, + messageId, + role: "assistant", + }) + + observer.next({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId, + delta: "Let me check the weather for you.", + }) + + observer.next({ + type: EventType.TEXT_MESSAGE_END, + messageId, + }) + + // 2. 开始工具调用 + observer.next({ + type: EventType.TOOL_CALL_START, + toolCallId, + toolCallName: "get_weather", + parentMessageId: messageId, + }) + + // 3. 流式传输参数(分块发送) + observer.next({ + type: EventType.TOOL_CALL_ARGS, + toolCallId, + delta: '{"loc', // 参数片段 1 + }) + + observer.next({ + type: EventType.TOOL_CALL_ARGS, + toolCallId, + delta: 'ation":', // 参数片段 2 + }) + + observer.next({ + type: EventType.TOOL_CALL_ARGS, + toolCallId, + delta: ' "San Francisco"}', // 参数片段 3 + }) + + // 4. 参数传输完成 + observer.next({ + type: EventType.TOOL_CALL_END, + toolCallId, + }) + + // 5. 工具执行结果(模拟) + setTimeout(() => { + observer.next({ + type: EventType.TOOL_CALL_RESULT, + toolCallId, + content: JSON.stringify({ + location: "San Francisco", + temperature: "18°C", + condition: "Partly cloudy", + }), + }) + + // 6. 基于工具结果的响应 + const responseMsgId = `msg_${Date.now()}_response` + observer.next({ + type: EventType.TEXT_MESSAGE_START, + messageId: responseMsgId, + role: "assistant", + }) + + observer.next({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId: responseMsgId, + delta: "The current weather in San Francisco is 18°C and partly cloudy.", + }) + + observer.next({ + type: EventType.TEXT_MESSAGE_END, + messageId: responseMsgId, + }) + + observer.next({ + type: EventType.RUN_FINISHED, + threadId, + runId, + }) + + observer.complete() + }, 1000) + }) + } +} + +// 使用示例 +const agent = new ToolCallingAgent() + +agent + .runAgent({ + runId: "run_tool_example", + threadId: "thread_123", + messages: [ + { + id: "user_1", + role: "user", + content: "What's the weather in San Francisco?", + }, + ], + tools: [weatherTool as any], + context: [], + }) + .subscribe({ + next: (event) => { + switch (event.type) { + case EventType.TOOL_CALL_START: + console.log(`[Tool Call] Starting: ${(event as any).toolCallName}`) + break + case EventType.TOOL_CALL_ARGS: + process.stdout.write((event as any).delta) + break + case EventType.TOOL_CALL_END: + console.log("\n[Tool Call] Arguments complete") + break + case EventType.TOOL_CALL_RESULT: + console.log("[Tool Result]", (event as any).content) + break + default: + console.log(`[${event.type}]`) + } + }, + complete: () => console.log("Tool call flow completed"), + }) + +export { ToolCallingAgent, weatherTool } diff --git a/.opencode/skills/crewai/SKILL.md b/.opencode/skills/crewai/SKILL.md new file mode 100644 index 0000000..ee0be19 --- /dev/null +++ b/.opencode/skills/crewai/SKILL.md @@ -0,0 +1,93 @@ +--- +name: crewai +description: CrewAI framework for multi-agent orchestration. Use when building multi-agent systems, agent collaboration, task automation, crew orchestration, agent teams, delegation, or any CrewAI-related development. +--- + +# CrewAI Skills + +CrewAI 框架开发权威指南。**必须使用**场景:构建多 Agent 协作系统、编排 Agent 团队、任务自动化、工具集成、知识管理、LLM 应用开发。提供完整模块索引与源文件行号映射。 + +## 何时使用 + +**必须使用**的场景: +- 创建和管理 AI Agent 团队 +- 实现 Agent 间的协作和任务委托 +- 编排多步骤工作流和任务流程 +- 集成 RAG、向量存储和知识管理 +- 配置和管理 LLM 提供商 +- 构建自动化任务和工具 +- 实现 Agent 记忆和推理能力 +- 训练和微调 Agent 性能 + +**查询模式**: +- "如何创建 crewai agent" +- "agent collaboration 委托任务" +- "crew kickoff 执行流程" +- "crewai tools 集成" +- "knowledge RAG 配置" +- "llm 多模型切换" + +## 模块索引 + +按功能模块查看源文件对应章节: + +| 模块 | 作用 | 源文件行号 | +|------|------|------------| +| [agents](modules/agents.md) | Agent 概念、属性、创建、高级特性 | 1-1276 | +| [collaboration](modules/collaboration.md) | Agent 协作、委托、层级管理 | 1277-1655 | +| [crews](modules/crews.md) | Crew 概念、创建、执行流程 | 1656-2658 | +| [flows](modules/flows.md) | Flow 流程控制、状态管理 | 2659-3712 | +| [knowledge](modules/knowledge.md) | 知识管理、向量存储、RAG | 3713-4838 | +| [llms](modules/llms.md) | LLM 配置、多模型支持 | 4839-6469 | +| [memory](modules/memory.md) | Memory 记忆系统 | 6470-7341 | +| [planning](modules/planning.md) | Planning 任务规划 | 7342-7729 | +| [reasoning](modules/reasoning.md) | Reasoning 推理和反思 | 7730-7877 | +| [tasks](modules/tasks.md) | Task 概念、属性、执行流程 | 7878-9005 | +| [tools](modules/tools.md) | Tool 概念、创建、内置工具 | 9006-9292 | +| [training](modules/training.md) | Training 训练和微调 | 9293-12843 | +| [installation](modules/installation.md) | 安装、配置、项目创建 | 12844-14875 | +| [quickstart-tools](modules/quickstart-tools.md) | **快速开始 + 50+ 工具参考** | 14876-53221 | + +## 源文件 + +- `llms-full.md` - CrewAI 完整文档(唯一信源,53221 行) + +## 核心概念速查 + +| 概念 | 说明 | 详见 | +|------|------|------| +| **Agent** | 自主单元,执行任务、使用工具、协作 | [agents](modules/agents.md) | +| **Task** | Agent 完成的具体任务 | [tasks](modules/tasks.md) | +| **Crew** | Agent 团队,协作完成任务 | [crews](modules/crews.md) | +| **Tool** | Agent 可用的能力或功能 | [tools](modules/tools.md) | +| **Flow** | 工作流编排和状态管理 | [flows](modules/flows.md) | +| **Knowledge** | 知识存储和 RAG 检索 | [knowledge](modules/knowledge.md) | + +## 快速路径 + +**新手入门**: +1. [installation](modules/installation.md) - 安装和项目创建 +2. [agents](modules/agents.md) - 理解 Agent 核心概念 +3. [tasks](modules/tasks.md) - 创建第一个 Task +4. [crews](modules/crews.md) - 组建 Crew 并执行 +5. [quickstart-tools](modules/quickstart-tools.md) - 完整快速开始示例 + +**实现功能**: +- Agent 协作 → [collaboration](modules/collaboration.md) (委托、层级) +- 任务编排 → [crews](modules/crews.md) + [flows](modules/flows.md) +- 知识管理 → [knowledge](modules/knowledge.md) (RAG、向量存储) +- 工具集成 → [tools](modules/tools.md) + [quickstart-tools](modules/quickstart-tools.md) +- LLM 配置 → [llms](modules/llms.md) + +**高级特性**: +- Agent 记忆 → [memory](modules/memory.md) +- 任务规划 → [planning](modules/planning.md) +- 推理能力 → [reasoning](modules/reasoning.md) +- 性能优化 → [training](modules/training.md) + +## 建议使用方式 + +1. 先阅读 [installation](modules/installation.md) 了解安装和项目结构 +2. 根据需求查看核心概念模块(agents/tasks/crews/tools) +3. 高级功能参考对应模块(collaboration/knowledge/flows) +4. 工具集成参考 [quickstart-tools](modules/quickstart-tools.md) diff --git a/.opencode/skills/crewai/llms-full.md b/.opencode/skills/crewai/llms-full.md new file mode 100644 index 0000000..8b44a33 --- /dev/null +++ b/.opencode/skills/crewai/llms-full.md @@ -0,0 +1,53221 @@ +# Agents +Source: https://docs.crewai.com/en/concepts/agents + +Detailed guide on creating and managing agents within the CrewAI framework. + +## Overview of an Agent + +In the CrewAI framework, an `Agent` is an autonomous unit that can: + +* Perform specific tasks +* Make decisions based on its role and goal +* Use tools to accomplish objectives +* Communicate and collaborate with other agents +* Maintain memory of interactions +* Delegate tasks when allowed + + + Think of an agent as a specialized team member with specific skills, + expertise, and responsibilities. For example, a `Researcher` agent might excel + at gathering and analyzing information, while a `Writer` agent might be better + at creating content. + + + + CrewAI AMP includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time. + + Visual Agent Builder Screenshot + + The Visual Agent Builder enables: + + * Intuitive agent configuration with form-based interfaces + * Real-time testing and validation + * Template library with pre-configured agent types + * Easy customization of agent attributes and behaviors + + +## Agent Attributes + +| Attribute | Parameter | Type | Description | +| :-------------------------------------- | :----------------------- | :------------------------------------ | :------------------------------------------------------------------------------------------------------- | +| **Role** | `role` | `str` | Defines the agent's function and expertise within the crew. | +| **Goal** | `goal` | `str` | The individual objective that guides the agent's decision-making. | +| **Backstory** | `backstory` | `str` | Provides context and personality to the agent, enriching interactions. | +| **LLM** *(optional)* | `llm` | `Union[str, LLM, Any]` | Language model that powers the agent. Defaults to the model specified in `OPENAI_MODEL_NAME` or "gpt-4". | +| **Tools** *(optional)* | `tools` | `List[BaseTool]` | Capabilities or functions available to the agent. Defaults to an empty list. | +| **Function Calling LLM** *(optional)* | `function_calling_llm` | `Optional[Any]` | Language model for tool calling, overrides crew's LLM if specified. | +| **Max Iterations** *(optional)* | `max_iter` | `int` | Maximum iterations before the agent must provide its best answer. Default is 20. | +| **Max RPM** *(optional)* | `max_rpm` | `Optional[int]` | Maximum requests per minute to avoid rate limits. | +| **Max Execution Time** *(optional)* | `max_execution_time` | `Optional[int]` | Maximum time (in seconds) for task execution. | +| **Verbose** *(optional)* | `verbose` | `bool` | Enable detailed execution logs for debugging. Default is False. | +| **Allow Delegation** *(optional)* | `allow_delegation` | `bool` | Allow the agent to delegate tasks to other agents. Default is False. | +| **Step Callback** *(optional)* | `step_callback` | `Optional[Any]` | Function called after each agent step, overrides crew callback. | +| **Cache** *(optional)* | `cache` | `bool` | Enable caching for tool usage. Default is True. | +| **System Template** *(optional)* | `system_template` | `Optional[str]` | Custom system prompt template for the agent. | +| **Prompt Template** *(optional)* | `prompt_template` | `Optional[str]` | Custom prompt template for the agent. | +| **Response Template** *(optional)* | `response_template` | `Optional[str]` | Custom response template for the agent. | +| **Allow Code Execution** *(optional)* | `allow_code_execution` | `Optional[bool]` | Enable code execution for the agent. Default is False. | +| **Max Retry Limit** *(optional)* | `max_retry_limit` | `int` | Maximum number of retries when an error occurs. Default is 2. | +| **Respect Context Window** *(optional)* | `respect_context_window` | `bool` | Keep messages under context window size by summarizing. Default is True. | +| **Code Execution Mode** *(optional)* | `code_execution_mode` | `Literal["safe", "unsafe"]` | Mode for code execution: 'safe' (using Docker) or 'unsafe' (direct). Default is 'safe'. | +| **Multimodal** *(optional)* | `multimodal` | `bool` | Whether the agent supports multimodal capabilities. Default is False. | +| **Inject Date** *(optional)* | `inject_date` | `bool` | Whether to automatically inject the current date into tasks. Default is False. | +| **Date Format** *(optional)* | `date_format` | `str` | Format string for date when inject\_date is enabled. Default is "%Y-%m-%d" (ISO format). | +| **Reasoning** *(optional)* | `reasoning` | `bool` | Whether the agent should reflect and create a plan before executing a task. Default is False. | +| **Max Reasoning Attempts** *(optional)* | `max_reasoning_attempts` | `Optional[int]` | Maximum number of reasoning attempts before executing the task. If None, will try until ready. | +| **Embedder** *(optional)* | `embedder` | `Optional[Dict[str, Any]]` | Configuration for the embedder used by the agent. | +| **Knowledge Sources** *(optional)* | `knowledge_sources` | `Optional[List[BaseKnowledgeSource]]` | Knowledge sources available to the agent. | +| **Use System Prompt** *(optional)* | `use_system_prompt` | `Optional[bool]` | Whether to use system prompt (for o1 model support). Default is True. | + +## Creating Agents + +There are two ways to create agents in CrewAI: using **YAML configuration (recommended)** or defining them **directly in code**. + +### YAML Configuration (Recommended) + +Using YAML configuration provides a cleaner, more maintainable way to define agents. We strongly recommend using this approach in your CrewAI projects. + +After creating your CrewAI project as outlined in the [Installation](/en/installation) section, navigate to the `src/latest_ai_development/config/agents.yaml` file and modify the template to match your requirements. + + + Variables in your YAML files (like `{topic}`) will be replaced with values from your inputs when running the crew: + + ```python Code theme={null} + crew.kickoff(inputs={'topic': 'AI Agents'}) + ``` + + +Here's an example of how to configure agents using YAML: + +```yaml agents.yaml theme={null} +# src/latest_ai_development/config/agents.yaml +researcher: + role: > + {topic} Senior Data Researcher + goal: > + Uncover cutting-edge developments in {topic} + backstory: > + You're a seasoned researcher with a knack for uncovering the latest + developments in {topic}. Known for your ability to find the most relevant + information and present it in a clear and concise manner. + +reporting_analyst: + role: > + {topic} Reporting Analyst + goal: > + Create detailed reports based on {topic} data analysis and research findings + backstory: > + You're a meticulous analyst with a keen eye for detail. You're known for + your ability to turn complex data into clear and concise reports, making + it easy for others to understand and act on the information you provide. +``` + +To use this YAML configuration in your code, create a crew class that inherits from `CrewBase`: + +```python Code theme={null} +# src/latest_ai_development/crew.py +from crewai import Agent, Crew, Process +from crewai.project import CrewBase, agent, crew +from crewai_tools import SerperDevTool + +@CrewBase +class LatestAiDevelopmentCrew(): + """LatestAiDevelopment crew""" + + agents_config = "config/agents.yaml" + + @agent + def researcher(self) -> Agent: + return Agent( + config=self.agents_config['researcher'], # type: ignore[index] + verbose=True, + tools=[SerperDevTool()] + ) + + @agent + def reporting_analyst(self) -> Agent: + return Agent( + config=self.agents_config['reporting_analyst'], # type: ignore[index] + verbose=True + ) +``` + + + The names you use in your YAML files (`agents.yaml`) should match the method + names in your Python code. + + +### Direct Code Definition + +You can create agents directly in code by instantiating the `Agent` class. Here's a comprehensive example showing all available parameters: + +```python Code theme={null} +from crewai import Agent +from crewai_tools import SerperDevTool + +# Create an agent with all available parameters +agent = Agent( + role="Senior Data Scientist", + goal="Analyze and interpret complex datasets to provide actionable insights", + backstory="With over 10 years of experience in data science and machine learning, " + "you excel at finding patterns in complex datasets.", + llm="gpt-4", # Default: OPENAI_MODEL_NAME or "gpt-4" + function_calling_llm=None, # Optional: Separate LLM for tool calling + verbose=False, # Default: False + allow_delegation=False, # Default: False + max_iter=20, # Default: 20 iterations + max_rpm=None, # Optional: Rate limit for API calls + max_execution_time=None, # Optional: Maximum execution time in seconds + max_retry_limit=2, # Default: 2 retries on error + allow_code_execution=False, # Default: False + code_execution_mode="safe", # Default: "safe" (options: "safe", "unsafe") + respect_context_window=True, # Default: True + use_system_prompt=True, # Default: True + multimodal=False, # Default: False + inject_date=False, # Default: False + date_format="%Y-%m-%d", # Default: ISO format + reasoning=False, # Default: False + max_reasoning_attempts=None, # Default: None + tools=[SerperDevTool()], # Optional: List of tools + knowledge_sources=None, # Optional: List of knowledge sources + embedder=None, # Optional: Custom embedder configuration + system_template=None, # Optional: Custom system prompt template + prompt_template=None, # Optional: Custom prompt template + response_template=None, # Optional: Custom response template + step_callback=None, # Optional: Callback function for monitoring +) +``` + +Let's break down some key parameter combinations for common use cases: + +#### Basic Research Agent + +```python Code theme={null} +research_agent = Agent( + role="Research Analyst", + goal="Find and summarize information about specific topics", + backstory="You are an experienced researcher with attention to detail", + tools=[SerperDevTool()], + verbose=True # Enable logging for debugging +) +``` + +#### Code Development Agent + +```python Code theme={null} +dev_agent = Agent( + role="Senior Python Developer", + goal="Write and debug Python code", + backstory="Expert Python developer with 10 years of experience", + allow_code_execution=True, + code_execution_mode="safe", # Uses Docker for safety + max_execution_time=300, # 5-minute timeout + max_retry_limit=3 # More retries for complex code tasks +) +``` + +#### Long-Running Analysis Agent + +```python Code theme={null} +analysis_agent = Agent( + role="Data Analyst", + goal="Perform deep analysis of large datasets", + backstory="Specialized in big data analysis and pattern recognition", + memory=True, + respect_context_window=True, + max_rpm=10, # Limit API calls + function_calling_llm="gpt-4o-mini" # Cheaper model for tool calls +) +``` + +#### Custom Template Agent + +```python Code theme={null} +custom_agent = Agent( + role="Customer Service Representative", + goal="Assist customers with their inquiries", + backstory="Experienced in customer support with a focus on satisfaction", + system_template="""<|start_header_id|>system<|end_header_id|> + {{ .System }}<|eot_id|>""", + prompt_template="""<|start_header_id|>user<|end_header_id|> + {{ .Prompt }}<|eot_id|>""", + response_template="""<|start_header_id|>assistant<|end_header_id|> + {{ .Response }}<|eot_id|>""", +) +``` + +#### Date-Aware Agent with Reasoning + +```python Code theme={null} +strategic_agent = Agent( + role="Market Analyst", + goal="Track market movements with precise date references and strategic planning", + backstory="Expert in time-sensitive financial analysis and strategic reporting", + inject_date=True, # Automatically inject current date into tasks + date_format="%B %d, %Y", # Format as "May 21, 2025" + reasoning=True, # Enable strategic planning + max_reasoning_attempts=2, # Limit planning iterations + verbose=True +) +``` + +#### Reasoning Agent + +```python Code theme={null} +reasoning_agent = Agent( + role="Strategic Planner", + goal="Analyze complex problems and create detailed execution plans", + backstory="Expert strategic planner who methodically breaks down complex challenges", + reasoning=True, # Enable reasoning and planning + max_reasoning_attempts=3, # Limit reasoning attempts + max_iter=30, # Allow more iterations for complex planning + verbose=True +) +``` + +#### Multimodal Agent + +```python Code theme={null} +multimodal_agent = Agent( + role="Visual Content Analyst", + goal="Analyze and process both text and visual content", + backstory="Specialized in multimodal analysis combining text and image understanding", + multimodal=True, # Enable multimodal capabilities + verbose=True +) +``` + +### Parameter Details + +#### Critical Parameters + +* `role`, `goal`, and `backstory` are required and shape the agent's behavior +* `llm` determines the language model used (default: OpenAI's GPT-4) + +#### Memory and Context + +* `memory`: Enable to maintain conversation history +* `respect_context_window`: Prevents token limit issues +* `knowledge_sources`: Add domain-specific knowledge bases + +#### Execution Control + +* `max_iter`: Maximum attempts before giving best answer +* `max_execution_time`: Timeout in seconds +* `max_rpm`: Rate limiting for API calls +* `max_retry_limit`: Retries on error + +#### Code Execution + +* `allow_code_execution`: Must be True to run code +* `code_execution_mode`: + * `"safe"`: Uses Docker (recommended for production) + * `"unsafe"`: Direct execution (use only in trusted environments) + + + This runs a default Docker image. If you want to configure the docker image, + the checkout the Code Interpreter Tool in the tools section. Add the code + interpreter tool as a tool in the agent as a tool parameter. + + +#### Advanced Features + +* `multimodal`: Enable multimodal capabilities for processing text and visual content +* `reasoning`: Enable agent to reflect and create plans before executing tasks +* `inject_date`: Automatically inject current date into task descriptions + +#### Templates + +* `system_template`: Defines agent's core behavior +* `prompt_template`: Structures input format +* `response_template`: Formats agent responses + + + When using custom templates, ensure that both `system_template` and + `prompt_template` are defined. The `response_template` is optional but + recommended for consistent output formatting. + + + + When using custom templates, you can use variables like `{role}`, `{goal}`, + and `{backstory}` in your templates. These will be automatically populated + during execution. + + +## Agent Tools + +Agents can be equipped with various tools to enhance their capabilities. CrewAI supports tools from: + +* [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) +* [LangChain Tools](https://python.langchain.com/docs/integrations/tools) + +Here's how to add tools to an agent: + +```python Code theme={null} +from crewai import Agent +from crewai_tools import SerperDevTool, WikipediaTools + +# Create tools +search_tool = SerperDevTool() +wiki_tool = WikipediaTools() + +# Add tools to agent +researcher = Agent( + role="AI Technology Researcher", + goal="Research the latest AI developments", + tools=[search_tool, wiki_tool], + verbose=True +) +``` + +## Agent Memory and Context + +Agents can maintain memory of their interactions and use context from previous tasks. This is particularly useful for complex workflows where information needs to be retained across multiple tasks. + +```python Code theme={null} +from crewai import Agent + +analyst = Agent( + role="Data Analyst", + goal="Analyze and remember complex data patterns", + memory=True, # Enable memory + verbose=True +) +``` + + + When `memory` is enabled, the agent will maintain context across multiple + interactions, improving its ability to handle complex, multi-step tasks. + + +## Context Window Management + +CrewAI includes sophisticated automatic context window management to handle situations where conversations exceed the language model's token limits. This powerful feature is controlled by the `respect_context_window` parameter. + +### How Context Window Management Works + +When an agent's conversation history grows too large for the LLM's context window, CrewAI automatically detects this situation and can either: + +1. **Automatically summarize content** (when `respect_context_window=True`) +2. **Stop execution with an error** (when `respect_context_window=False`) + +### Automatic Context Handling (`respect_context_window=True`) + +This is the **default and recommended setting** for most use cases. When enabled, CrewAI will: + +```python Code theme={null} +# Agent with automatic context management (default) +smart_agent = Agent( + role="Research Analyst", + goal="Analyze large documents and datasets", + backstory="Expert at processing extensive information", + respect_context_window=True, # 🔑 Default: auto-handle context limits + verbose=True +) +``` + +**What happens when context limits are exceeded:** + +* ⚠️ **Warning message**: `"Context length exceeded. Summarizing content to fit the model context window."` +* 🔄 **Automatic summarization**: CrewAI intelligently summarizes the conversation history +* ✅ **Continued execution**: Task execution continues seamlessly with the summarized context +* 📝 **Preserved information**: Key information is retained while reducing token count + +### Strict Context Limits (`respect_context_window=False`) + +When you need precise control and prefer execution to stop rather than lose any information: + +```python Code theme={null} +# Agent with strict context limits +strict_agent = Agent( + role="Legal Document Reviewer", + goal="Provide precise legal analysis without information loss", + backstory="Legal expert requiring complete context for accurate analysis", + respect_context_window=False, # ❌ Stop execution on context limit + verbose=True +) +``` + +**What happens when context limits are exceeded:** + +* ❌ **Error message**: `"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."` +* 🛑 **Execution stops**: Task execution halts immediately +* 🔧 **Manual intervention required**: You need to modify your approach + +### Choosing the Right Setting + +#### Use `respect_context_window=True` (Default) when: + +* **Processing large documents** that might exceed context limits +* **Long-running conversations** where some summarization is acceptable +* **Research tasks** where general context is more important than exact details +* **Prototyping and development** where you want robust execution + +```python Code theme={null} +# Perfect for document processing +document_processor = Agent( + role="Document Analyst", + goal="Extract insights from large research papers", + backstory="Expert at analyzing extensive documentation", + respect_context_window=True, # Handle large documents gracefully + max_iter=50, # Allow more iterations for complex analysis + verbose=True +) +``` + +#### Use `respect_context_window=False` when: + +* **Precision is critical** and information loss is unacceptable +* **Legal or medical tasks** requiring complete context +* **Code review** where missing details could introduce bugs +* **Financial analysis** where accuracy is paramount + +```python Code theme={null} +# Perfect for precision tasks +precision_agent = Agent( + role="Code Security Auditor", + goal="Identify security vulnerabilities in code", + backstory="Security expert requiring complete code context", + respect_context_window=False, # Prefer failure over incomplete analysis + max_retry_limit=1, # Fail fast on context issues + verbose=True +) +``` + +### Alternative Approaches for Large Data + +When dealing with very large datasets, consider these strategies: + +#### 1. Use RAG Tools + +```python Code theme={null} +from crewai_tools import RagTool + +# Create RAG tool for large document processing +rag_tool = RagTool() + +rag_agent = Agent( + role="Research Assistant", + goal="Query large knowledge bases efficiently", + backstory="Expert at using RAG tools for information retrieval", + tools=[rag_tool], # Use RAG instead of large context windows + respect_context_window=True, + verbose=True +) +``` + +#### 2. Use Knowledge Sources + +```python Code theme={null} +# Use knowledge sources instead of large prompts +knowledge_agent = Agent( + role="Knowledge Expert", + goal="Answer questions using curated knowledge", + backstory="Expert at leveraging structured knowledge sources", + knowledge_sources=[your_knowledge_sources], # Pre-processed knowledge + respect_context_window=True, + verbose=True +) +``` + +### Context Window Best Practices + +1. **Monitor Context Usage**: Enable `verbose=True` to see context management in action +2. **Design for Efficiency**: Structure tasks to minimize context accumulation +3. **Use Appropriate Models**: Choose LLMs with context windows suitable for your tasks +4. **Test Both Settings**: Try both `True` and `False` to see which works better for your use case +5. **Combine with RAG**: Use RAG tools for very large datasets instead of relying solely on context windows + +### Troubleshooting Context Issues + +**If you're getting context limit errors:** + +```python Code theme={null} +# Quick fix: Enable automatic handling +agent.respect_context_window = True + +# Better solution: Use RAG tools for large data +from crewai_tools import RagTool +agent.tools = [RagTool()] + +# Alternative: Break tasks into smaller pieces +# Or use knowledge sources instead of large prompts +``` + +**If automatic summarization loses important information:** + +```python Code theme={null} +# Disable auto-summarization and use RAG instead +agent = Agent( + role="Detailed Analyst", + goal="Maintain complete information accuracy", + backstory="Expert requiring full context", + respect_context_window=False, # No summarization + tools=[RagTool()], # Use RAG for large data + verbose=True +) +``` + + + The context window management feature works automatically in the background. + You don't need to call any special functions - just set + `respect_context_window` to your preferred behavior and CrewAI handles the + rest! + + +## Direct Agent Interaction with `kickoff()` + +Agents can be used directly without going through a task or crew workflow using the `kickoff()` method. This provides a simpler way to interact with an agent when you don't need the full crew orchestration capabilities. + +### How `kickoff()` Works + +The `kickoff()` method allows you to send messages directly to an agent and get a response, similar to how you would interact with an LLM but with all the agent's capabilities (tools, reasoning, etc.). + +```python Code theme={null} +from crewai import Agent +from crewai_tools import SerperDevTool + +# Create an agent +researcher = Agent( + role="AI Technology Researcher", + goal="Research the latest AI developments", + tools=[SerperDevTool()], + verbose=True +) + +# Use kickoff() to interact directly with the agent +result = researcher.kickoff("What are the latest developments in language models?") + +# Access the raw response +print(result.raw) +``` + +### Parameters and Return Values + +| Parameter | Type | Description | +| :---------------- | :--------------------------------- | :------------------------------------------------------------------------ | +| `messages` | `Union[str, List[Dict[str, str]]]` | Either a string query or a list of message dictionaries with role/content | +| `response_format` | `Optional[Type[Any]]` | Optional Pydantic model for structured output | + +The method returns a `LiteAgentOutput` object with the following properties: + +* `raw`: String containing the raw output text +* `pydantic`: Parsed Pydantic model (if a `response_format` was provided) +* `agent_role`: Role of the agent that produced the output +* `usage_metrics`: Token usage metrics for the execution + +### Structured Output + +You can get structured output by providing a Pydantic model as the `response_format`: + +```python Code theme={null} +from pydantic import BaseModel +from typing import List + +class ResearchFindings(BaseModel): + main_points: List[str] + key_technologies: List[str] + future_predictions: str + +# Get structured output +result = researcher.kickoff( + "Summarize the latest developments in AI for 2025", + response_format=ResearchFindings +) + +# Access structured data +print(result.pydantic.main_points) +print(result.pydantic.future_predictions) +``` + +### Multiple Messages + +You can also provide a conversation history as a list of message dictionaries: + +```python Code theme={null} +messages = [ + {"role": "user", "content": "I need information about large language models"}, + {"role": "assistant", "content": "I'd be happy to help with that! What specifically would you like to know?"}, + {"role": "user", "content": "What are the latest developments in 2025?"} +] + +result = researcher.kickoff(messages) +``` + +### Async Support + +An asynchronous version is available via `kickoff_async()` with the same parameters: + +```python Code theme={null} +import asyncio + +async def main(): + result = await researcher.kickoff_async("What are the latest developments in AI?") + print(result.raw) + +asyncio.run(main()) +``` + + + The `kickoff()` method uses a `LiteAgent` internally, which provides a simpler + execution flow while preserving all of the agent's configuration (role, goal, + backstory, tools, etc.). + + +## Important Considerations and Best Practices + +### Security and Code Execution + +* When using `allow_code_execution`, be cautious with user input and always validate it +* Use `code_execution_mode: "safe"` (Docker) in production environments +* Consider setting appropriate `max_execution_time` limits to prevent infinite loops + +### Performance Optimization + +* Use `respect_context_window: true` to prevent token limit issues +* Set appropriate `max_rpm` to avoid rate limiting +* Enable `cache: true` to improve performance for repetitive tasks +* Adjust `max_iter` and `max_retry_limit` based on task complexity + +### Memory and Context Management + +* Leverage `knowledge_sources` for domain-specific information +* Configure `embedder` when using custom embedding models +* Use custom templates (`system_template`, `prompt_template`, `response_template`) for fine-grained control over agent behavior + +### Advanced Features + +* Enable `reasoning: true` for agents that need to plan and reflect before executing complex tasks +* Set appropriate `max_reasoning_attempts` to control planning iterations (None for unlimited attempts) +* Use `inject_date: true` to provide agents with current date awareness for time-sensitive tasks +* Customize the date format with `date_format` using standard Python datetime format codes +* Enable `multimodal: true` for agents that need to process both text and visual content + +### Agent Collaboration + +* Enable `allow_delegation: true` when agents need to work together +* Use `step_callback` to monitor and log agent interactions +* Consider using different LLMs for different purposes: + * Main `llm` for complex reasoning + * `function_calling_llm` for efficient tool usage + +### Date Awareness and Reasoning + +* Use `inject_date: true` to provide agents with current date awareness for time-sensitive tasks +* Customize the date format with `date_format` using standard Python datetime format codes +* Valid format codes include: %Y (year), %m (month), %d (day), %B (full month name), etc. +* Invalid date formats will be logged as warnings and will not modify the task description +* Enable `reasoning: true` for complex tasks that benefit from upfront planning and reflection + +### Model Compatibility + +* Set `use_system_prompt: false` for older models that don't support system messages +* Ensure your chosen `llm` supports the features you need (like function calling) + +## Troubleshooting Common Issues + +1. **Rate Limiting**: If you're hitting API rate limits: + + * Implement appropriate `max_rpm` + * Use caching for repetitive operations + * Consider batching requests + +2. **Context Window Errors**: If you're exceeding context limits: + + * Enable `respect_context_window` + * Use more efficient prompts + * Clear agent memory periodically + +3. **Code Execution Issues**: If code execution fails: + + * Verify Docker is installed for safe mode + * Check execution permissions + * Review code sandbox settings + +4. **Memory Issues**: If agent responses seem inconsistent: + * Check knowledge source configuration + * Review conversation history management + +Remember that agents are most effective when configured according to their specific use case. Take time to understand your requirements and adjust these parameters accordingly. + + +# CLI +Source: https://docs.crewai.com/en/concepts/cli + +Learn how to use the CrewAI CLI to interact with CrewAI. + + + Since release 0.140.0, CrewAI AMP started a process of migrating their login + provider. As such, the authentication flow via CLI was updated. Users that use + Google to login, or that created their account after July 3rd, 2025 will be + unable to log in with older versions of the `crewai` library. + + +## Overview + +The CrewAI CLI provides a set of commands to interact with CrewAI, allowing you to create, train, run, and manage crews & flows. + +## Installation + +To use the CrewAI CLI, make sure you have CrewAI installed: + +```shell Terminal theme={null} +pip install crewai +``` + +## Basic Usage + +The basic structure of a CrewAI CLI command is: + +```shell Terminal theme={null} +crewai [COMMAND] [OPTIONS] [ARGUMENTS] +``` + +## Available Commands + +### 1. Create + +Create a new crew or flow. + +```shell Terminal theme={null} +crewai create [OPTIONS] TYPE NAME +``` + +* `TYPE`: Choose between "crew" or "flow" +* `NAME`: Name of the crew or flow + +Example: + +```shell Terminal theme={null} +crewai create crew my_new_crew +crewai create flow my_new_flow +``` + +### 2. Version + +Show the installed version of CrewAI. + +```shell Terminal theme={null} +crewai version [OPTIONS] +``` + +* `--tools`: (Optional) Show the installed version of CrewAI tools + +Example: + +```shell Terminal theme={null} +crewai version +crewai version --tools +``` + +### 3. Train + +Train the crew for a specified number of iterations. + +```shell Terminal theme={null} +crewai train [OPTIONS] +``` + +* `-n, --n_iterations INTEGER`: Number of iterations to train the crew (default: 5) +* `-f, --filename TEXT`: Path to a custom file for training (default: "trained\_agents\_data.pkl") + +Example: + +```shell Terminal theme={null} +crewai train -n 10 -f my_training_data.pkl +``` + +### 4. Replay + +Replay the crew execution from a specific task. + +```shell Terminal theme={null} +crewai replay [OPTIONS] +``` + +* `-t, --task_id TEXT`: Replay the crew from this task ID, including all subsequent tasks + +Example: + +```shell Terminal theme={null} +crewai replay -t task_123456 +``` + +### 5. Log-tasks-outputs + +Retrieve your latest crew\.kickoff() task outputs. + +```shell Terminal theme={null} +crewai log-tasks-outputs +``` + +### 6. Reset-memories + +Reset the crew memories (long, short, entity, latest\_crew\_kickoff\_outputs). + +```shell Terminal theme={null} +crewai reset-memories [OPTIONS] +``` + +* `-l, --long`: Reset LONG TERM memory +* `-s, --short`: Reset SHORT TERM memory +* `-e, --entities`: Reset ENTITIES memory +* `-k, --kickoff-outputs`: Reset LATEST KICKOFF TASK OUTPUTS +* `-kn, --knowledge`: Reset KNOWLEDGE storage +* `-akn, --agent-knowledge`: Reset AGENT KNOWLEDGE storage +* `-a, --all`: Reset ALL memories + +Example: + +```shell Terminal theme={null} +crewai reset-memories --long --short +crewai reset-memories --all +``` + +### 7. Test + +Test the crew and evaluate the results. + +```shell Terminal theme={null} +crewai test [OPTIONS] +``` + +* `-n, --n_iterations INTEGER`: Number of iterations to test the crew (default: 3) +* `-m, --model TEXT`: LLM Model to run the tests on the Crew (default: "gpt-4o-mini") + +Example: + +```shell Terminal theme={null} +crewai test -n 5 -m gpt-3.5-turbo +``` + +### 8. Run + +Run the crew or flow. + +```shell Terminal theme={null} +crewai run +``` + + + Starting from version 0.103.0, the `crewai run` command can be used to run + both standard crews and flows. For flows, it automatically detects the type + from pyproject.toml and runs the appropriate command. This is now the + recommended way to run both crews and flows. + + + + Make sure to run these commands from the directory where your CrewAI project + is set up. Some commands may require additional configuration or setup within + your project structure. + + +### 9. Chat + +Starting in version `0.98.0`, when you run the `crewai chat` command, you start an interactive session with your crew. The AI assistant will guide you by asking for necessary inputs to execute the crew. Once all inputs are provided, the crew will execute its tasks. + +After receiving the results, you can continue interacting with the assistant for further instructions or questions. + +```shell Terminal theme={null} +crewai chat +``` + + + Ensure you execute these commands from your CrewAI project's root directory. + + + + IMPORTANT: Set the `chat_llm` property in your `crew.py` file to enable this command. + + ```python theme={null} + @crew + def crew(self) -> Crew: + return Crew( + agents=self.agents, + tasks=self.tasks, + process=Process.sequential, + verbose=True, + chat_llm="gpt-4o", # LLM for chat orchestration + ) + ``` + + +### 10. Deploy + +Deploy the crew or flow to [CrewAI AMP](https://app.crewai.com). + +* **Authentication**: You need to be authenticated to deploy to CrewAI AMP. + You can login or create an account with: + + ```shell Terminal theme={null} + crewai login + ``` + +* **Create a deployment**: Once you are authenticated, you can create a deployment for your crew or flow from the root of your localproject. + ```shell Terminal theme={null} + crewai deploy create + ``` + * Reads your local project configuration. + * Prompts you to confirm the environment variables (like `OPENAI_API_KEY`, `SERPER_API_KEY`) found locally. These will be securely stored with the deployment on the Enterprise platform. Ensure your sensitive keys are correctly configured locally (e.g., in a `.env` file) before running this. + +### 11. Organization Management + +Manage your CrewAI AMP organizations. + +```shell Terminal theme={null} +crewai org [COMMAND] [OPTIONS] +``` + +#### Commands: + +* `list`: List all organizations you belong to + +```shell Terminal theme={null} +crewai org list +``` + +* `current`: Display your currently active organization + +```shell Terminal theme={null} +crewai org current +``` + +* `switch`: Switch to a specific organization + +```shell Terminal theme={null} +crewai org switch +``` + + + You must be authenticated to CrewAI AMP to use these organization management + commands. + + +* **Create a deployment** (continued): + + * Links the deployment to the corresponding remote GitHub repository (it usually detects this automatically). + +* **Deploy the Crew**: Once you are authenticated, you can deploy your crew or flow to CrewAI AMP. + + ```shell Terminal theme={null} + crewai deploy push + ``` + + * Initiates the deployment process on the CrewAI AMP platform. + * Upon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID). + +* **Deployment Status**: You can check the status of your deployment with: + + ```shell Terminal theme={null} + crewai deploy status + ``` + + This fetches the latest deployment status of your most recent deployment attempt (e.g., `Building Images for Crew`, `Deploy Enqueued`, `Online`). + +* **Deployment Logs**: You can check the logs of your deployment with: + + ```shell Terminal theme={null} + crewai deploy logs + ``` + + This streams the deployment logs to your terminal. + +* **List deployments**: You can list all your deployments with: + + ```shell Terminal theme={null} + crewai deploy list + ``` + + This lists all your deployments. + +* **Delete a deployment**: You can delete a deployment with: + + ```shell Terminal theme={null} + crewai deploy remove + ``` + + This deletes the deployment from the CrewAI AMP platform. + +* **Help Command**: You can get help with the CLI with: + ```shell Terminal theme={null} + crewai deploy --help + ``` + This shows the help message for the CrewAI Deploy CLI. + +Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI AMP](http://app.crewai.com) using the CLI. + +