diff --git a/docs/docs.json b/docs/docs.json index b902e0b41..37e060961 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -370,7 +370,8 @@ "pages": [ "en/enterprise/features/traces", "en/enterprise/features/webhook-streaming", - "en/enterprise/features/hallucination-guardrail" + "en/enterprise/features/hallucination-guardrail", + "en/enterprise/features/flow-hitl-management" ] }, { @@ -823,7 +824,8 @@ "pages": [ "pt-BR/enterprise/features/traces", "pt-BR/enterprise/features/webhook-streaming", - "pt-BR/enterprise/features/hallucination-guardrail" + "pt-BR/enterprise/features/hallucination-guardrail", + "pt-BR/enterprise/features/flow-hitl-management" ] }, { @@ -1287,7 +1289,8 @@ "pages": [ "ko/enterprise/features/traces", "ko/enterprise/features/webhook-streaming", - "ko/enterprise/features/hallucination-guardrail" + "ko/enterprise/features/hallucination-guardrail", + "ko/enterprise/features/flow-hitl-management" ] }, { diff --git a/docs/en/enterprise/features/flow-hitl-management.mdx b/docs/en/enterprise/features/flow-hitl-management.mdx new file mode 100644 index 000000000..c0b1fa957 --- /dev/null +++ b/docs/en/enterprise/features/flow-hitl-management.mdx @@ -0,0 +1,563 @@ +--- +title: "Flow HITL Management" +description: "Enterprise-grade human review for Flows with email-first notifications, routing rules, and auto-response capabilities" +icon: "users-gear" +mode: "wide" +--- + + +Flow HITL Management features require the `@human_feedback` decorator, available in **CrewAI version 1.8.0 or higher**. These features apply specifically to **Flows**, not Crews. + + +CrewAI Enterprise provides a comprehensive Human-in-the-Loop (HITL) management system for Flows that transforms AI workflows into collaborative human-AI processes. The platform uses an **email-first architecture** that enables anyone with an email address to respond to review requests—no platform account required. + +## Overview + + + + Responders can reply directly to notification emails to provide feedback + + + Route requests to specific emails based on method patterns or flow state + + + Configure automatic fallback responses when no human replies in time + + + +### Key Benefits + +- **Simple mental model**: Email addresses are universal; no need to manage platform users or roles +- **External responders**: Anyone with an email can respond, even non-platform users +- **Dynamic assignment**: Pull assignee email directly from flow state (e.g., `sales_rep_email`) +- **Reduced configuration**: Fewer settings to configure, faster time to value +- **Email as primary channel**: Most users prefer responding via email over logging into a dashboard + +## Setting Up Human Review Points in Flows + +Configure human review checkpoints within your Flows using the `@human_feedback` decorator. When execution reaches a review point, the system pauses, notifies the assignee via email, and waits for a response. + +```python +from crewai.flow.flow import Flow, start, listen +from crewai.flow.human_feedback import human_feedback, HumanFeedbackResult + +class ContentApprovalFlow(Flow): + @start() + def generate_content(self): + # AI generates content + return "Generated marketing copy for Q1 campaign..." + + @listen(generate_content) + @human_feedback( + message="Please review this content for brand compliance:", + emit=["approved", "rejected", "needs_revision"], + ) + def review_content(self, content): + return content + + @listen("approved") + def publish_content(self, result: HumanFeedbackResult): + print(f"Publishing approved content. Reviewer notes: {result.feedback}") + + @listen("rejected") + def archive_content(self, result: HumanFeedbackResult): + print(f"Content rejected. Reason: {result.feedback}") + + @listen("needs_revision") + def revise_content(self, result: HumanFeedbackResult): + print(f"Revision requested: {result.feedback}") +``` + +For complete implementation details, see the [Human Feedback in Flows](/en/learn/human-feedback-in-flows) guide. + +### Decorator Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `str` | The message displayed to the human reviewer | +| `emit` | `list[str]` | Valid response options (displayed as buttons in UI) | + +## Platform Configuration + +Access HITL configuration from: **Deployment → Settings → Human in the Loop Configuration** + + + HITL Configuration Settings + + +### Email Notifications + +Toggle to enable or disable email notifications for HITL requests. + +| Setting | Default | Description | +|---------|---------|-------------| +| Email Notifications | Enabled | Send emails when feedback is requested | + + +When disabled, responders must use the dashboard UI or you must configure webhooks for custom notification systems. + + +### SLA Target + +Set a target response time for tracking and metrics purposes. + +| Setting | Description | +|---------|-------------| +| SLA Target (minutes) | Target response time. Used for dashboard metrics and SLA tracking | + +Leave empty to disable SLA tracking. + +## Email Notifications & Responses + +The HITL system uses an email-first architecture where responders can reply directly to notification emails. + +### How Email Responses Work + + + + When a HITL request is created, an email is sent to the assigned responder with the review content and context. + + + The email includes a special reply-to address with a signed token for authentication. + + + The responder simply replies to the email with their feedback—no login required. + + + The platform receives the reply, verifies the signed token, and matches the sender email. + + + The feedback is recorded and the flow continues with the human's input. + + + +### Response Format + +Responders can reply with: + +- **Emit option**: If the reply matches an `emit` option (e.g., "approved"), it's used directly +- **Free-form text**: Any text response is passed to the flow as feedback +- **Plain text**: The first line of the reply body is used as feedback + +### Confirmation Emails + +After processing a reply, the responder receives a confirmation email indicating whether the feedback was successfully submitted or if an error occurred. + +### Email Token Security + +- Tokens are cryptographically signed for security +- Tokens expire after 7 days +- Sender email must match the token's authorized email +- Confirmation/error emails are sent after processing + +## Routing Rules + +Route HITL requests to specific email addresses based on method patterns. + + + HITL Routing Rules Configuration + + +### Rule Structure + +```json +{ + "name": "Approvals to Finance", + "match": { + "method_name": "approve_*" + }, + "assign_to_email": "finance@company.com", + "assign_from_input": "manager_email" +} +``` + +### Matching Patterns + +| Pattern | Description | Example Match | +|---------|-------------|---------------| +| `approve_*` | Wildcard (any chars) | `approve_payment`, `approve_vendor` | +| `review_?` | Single char | `review_a`, `review_1` | +| `validate_payment` | Exact match | `validate_payment` only | + +### Assignment Priority + +1. **Dynamic assignment** (`assign_from_input`): If configured, pulls email from flow state +2. **Static email** (`assign_to_email`): Falls back to configured email +3. **Deployment creator**: If no rule matches, the deployment creator's email is used + +### Dynamic Assignment Example + +If your flow state contains `{"sales_rep_email": "alice@company.com"}`, configure: + +```json +{ + "name": "Route to Sales Rep", + "match": { + "method_name": "review_*" + }, + "assign_from_input": "sales_rep_email" +} +``` + +The request will be assigned to `alice@company.com` automatically. + + +**Use Case**: Pull the assignee from your CRM, database, or previous flow step to dynamically route reviews to the right person. + + +## Auto-Response + +Automatically respond to HITL requests if no human responds within a timeout. This ensures flows don't hang indefinitely. + +### Configuration + +| Setting | Description | +|---------|-------------| +| Enabled | Toggle to enable auto-response | +| Timeout (minutes) | Time to wait before auto-responding | +| Default Outcome | The response value (must match an `emit` option) | + + + HITL Auto-Response Configuration + + +### Use Cases + +- **SLA compliance**: Ensure flows don't hang indefinitely +- **Default approval**: Auto-approve low-risk requests after timeout +- **Graceful degradation**: Continue with a safe default when reviewers are unavailable + + +Use auto-response carefully. Only enable it for non-critical reviews where a default response is acceptable. + + +## Review Process + +### Dashboard Interface + +The HITL review interface provides a clean, focused experience for reviewers: + +- **Markdown Rendering**: Rich formatting for review content with syntax highlighting +- **Context Panel**: View flow state, execution history, and related information +- **Feedback Input**: Provide detailed feedback and comments with your decision +- **Quick Actions**: One-click emit option buttons with optional comments + + + HITL Pending Requests List + + +### Response Methods + +Reviewers can respond via three channels: + +| Method | Description | +|--------|-------------| +| **Email Reply** | Reply directly to the notification email | +| **Dashboard** | Use the Enterprise dashboard UI | +| **API/Webhook** | Programmatic response via API | + +### History & Audit Trail + +Every HITL interaction is tracked with a complete timeline: + +- Decision history (approve/reject/revise) +- Reviewer identity and timestamp +- Feedback and comments provided +- Response method (email/dashboard/API) +- Response time metrics + +## Analytics & Monitoring + +Track HITL performance with comprehensive analytics. + +### Performance Dashboard + + + HITL Metrics Dashboard + + + + + Monitor average and median response times by reviewer or flow. + + + Analyze review volume patterns to optimize team capacity. + + + View approval/rejection rates across different review types. + + + Track percentage of reviews completed within SLA targets. + + + +### Audit & Compliance + +Enterprise-ready audit capabilities for regulatory requirements: + +- Complete decision history with timestamps +- Reviewer identity verification +- Immutable audit logs +- Export capabilities for compliance reporting + +## Common Use Cases + + + + **Use Case**: Internal security questionnaire automation with human validation + + - AI generates responses to security questionnaires + - Security team reviews and validates accuracy via email + - Approved responses are compiled into final submission + - Full audit trail for compliance + + + + **Use Case**: Marketing content requiring legal/brand review + + - AI generates marketing copy or social media content + - Route to brand team email for voice/tone review + - Automatic publishing upon approval + + + + **Use Case**: Expense reports, contract terms, budget allocations + + - AI pre-processes and categorizes financial requests + - Route based on amount thresholds using dynamic assignment + - Maintain complete audit trail for financial compliance + + + + **Use Case**: Route reviews to account owners from your CRM + + - Flow fetches account owner email from CRM + - Store email in flow state (e.g., `account_owner_email`) + - Use `assign_from_input` to route to the right person automatically + + + + **Use Case**: AI output validation before customer delivery + + - AI generates customer-facing content or responses + - QA team reviews via email notification + - Feedback loops improve AI performance over time + + + +## Webhooks API + +When your Flows pause for human feedback, you can configure webhooks to send request data to your own application. This enables: + +- Building custom approval UIs +- Integrating with internal tools (Jira, ServiceNow, custom dashboards) +- Routing approvals to third-party systems +- Mobile app notifications +- Automated decision systems + + + HITL Webhook Configuration + + +### Configuring Webhooks + + + + Go to your **Deployment** → **Settings** → **Human in the Loop** + + + Click to expand the **Webhooks** configuration + + + Enter your webhook URL (must be HTTPS in production) + + + Click **Save Configuration** to activate + + + +You can configure multiple webhooks. Each active webhook receives all HITL events. + +### Webhook Events + +Your endpoint will receive HTTP POST requests for these events: + +| Event Type | When Triggered | +|------------|----------------| +| `new_request` | A flow pauses and requests human feedback | + +### Webhook Payload + +All webhooks receive a JSON payload with this structure: + +```json +{ + "event": "new_request", + "request": { + "id": "550e8400-e29b-41d4-a716-446655440000", + "flow_id": "flow_abc123", + "method_name": "review_article", + "message": "Please review this article for publication.", + "emit_options": ["approved", "rejected", "request_changes"], + "state": { + "article_id": 12345, + "author": "john@example.com", + "category": "technology" + }, + "metadata": {}, + "created_at": "2026-01-14T12:00:00Z" + }, + "deployment": { + "id": 456, + "name": "Content Review Flow", + "organization_id": 789 + }, + "callback_url": "https://api.crewai.com/...", + "assigned_to_email": "reviewer@company.com" +} +``` + +### Responding to Requests + +To submit feedback, **POST to the `callback_url`** included in the webhook payload. + +```http +POST {callback_url} +Content-Type: application/json + +{ + "feedback": "Approved. Great article!", + "source": "my_custom_app" +} +``` + +### Security + + +All webhook requests are cryptographically signed using HMAC-SHA256 to ensure authenticity and prevent tampering. + + +#### Webhook Security + +- **HMAC-SHA256 signatures**: Every webhook includes a cryptographic signature +- **Per-webhook secrets**: Each webhook has its own unique signing secret +- **Encrypted at rest**: Signing secrets are encrypted in our database +- **Timestamp verification**: Prevents replay attacks + +#### Signature Headers + +Each webhook request includes these headers: + +| Header | Description | +|--------|-------------| +| `X-Signature` | HMAC-SHA256 signature: `sha256=` | +| `X-Timestamp` | Unix timestamp when the request was signed | + +#### Verification + +Verify by computing: + +```python +import hmac +import hashlib + +expected = hmac.new( + signing_secret.encode(), + f"{timestamp}.{payload}".encode(), + hashlib.sha256 +).hexdigest() + +if hmac.compare_digest(expected, signature): + # Valid signature +``` + +### Error Handling + +Your webhook endpoint should return a 2xx status code to acknowledge receipt: + +| Your Response | Our Behavior | +|---------------|--------------| +| 2xx | Webhook delivered successfully | +| 4xx/5xx | Logged as failed, no retry | +| Timeout (30s) | Logged as failed, no retry | + +## Security & RBAC + +### Dashboard Access + +HITL access is controlled at the deployment level: + +| Permission | Capability | +|------------|------------| +| `manage_human_feedback` | Configure HITL settings, view all requests | +| `respond_to_human_feedback` | Respond to requests, view assigned requests | + +### Email Response Authorization + +For email replies: +1. The reply-to token encodes the authorized email +2. Sender email must match the token's email +3. Token must not be expired (7-day default) +4. Request must still be pending + +### Audit Trail + +All HITL actions are logged: +- Request creation +- Assignment changes +- Response submission (with source: dashboard/email/API) +- Flow resume status + +## Troubleshooting + +### Emails Not Sending + +1. Check "Email Notifications" is enabled in configuration +2. Verify routing rules match the method name +3. Verify assignee email is valid +4. Check deployment creator fallback if no routing rules match + +### Email Replies Not Processing + +1. Check token hasn't expired (7-day default) +2. Verify sender email matches assigned email +3. Ensure request is still pending (not already responded) + +### Flow Not Resuming + +1. Check request status in dashboard +2. Verify callback URL is accessible +3. Ensure deployment is still running + +## Best Practices + + +**Start Simple**: Begin with email notifications to deployment creator, then add routing rules as your workflows mature. + + +1. **Use Dynamic Assignment**: Pull assignee emails from your flow state for flexible routing. + +2. **Configure Auto-Response**: Set up a fallback for non-critical reviews to prevent flows from hanging. + +3. **Monitor Response Times**: Use analytics to identify bottlenecks and optimize your review process. + +4. **Keep Review Messages Clear**: Write clear, actionable messages in the `@human_feedback` decorator. + +5. **Test Email Flow**: Send test requests to verify email delivery before going to production. + +## Related Resources + + + + Implementation guide for the `@human_feedback` decorator + + + Step-by-step guide for setting up HITL workflows + + + Configure role-based access control for your organization + + + Set up real-time event notifications + + diff --git a/docs/en/enterprise/guides/human-in-the-loop.mdx b/docs/en/enterprise/guides/human-in-the-loop.mdx index 73ef82a16..7824555bc 100644 --- a/docs/en/enterprise/guides/human-in-the-loop.mdx +++ b/docs/en/enterprise/guides/human-in-the-loop.mdx @@ -5,9 +5,54 @@ icon: "user-check" mode: "wide" --- -Human-In-The-Loop (HITL) is a powerful approach that combines artificial intelligence with human expertise to enhance decision-making and improve task outcomes. This guide shows you how to implement HITL within CrewAI. +Human-In-The-Loop (HITL) is a powerful approach that combines artificial intelligence with human expertise to enhance decision-making and improve task outcomes. This guide shows you how to implement HITL within CrewAI Enterprise. -## Setting Up HITL Workflows +## HITL Approaches in CrewAI + +CrewAI offers two approaches for implementing human-in-the-loop workflows: + +| Approach | Best For | Version | +|----------|----------|---------| +| **Flow-based** (`@human_feedback` decorator) | Production with Enterprise UI, email-first workflows, full platform features | **1.8.0+** | +| **Webhook-based** | Custom integrations, external systems (Slack, Teams, etc.), legacy setups | All versions | + +## Flow-Based HITL with Enterprise Platform + + +The `@human_feedback` decorator requires **CrewAI version 1.8.0 or higher**. + + +When using the `@human_feedback` decorator in your Flows, CrewAI Enterprise provides an **email-first HITL system** that enables anyone with an email address to respond to review requests: + + + + Responders receive email notifications and can reply directly—no login required. + + + Review and respond to HITL requests in the Enterprise dashboard when preferred. + + + Route requests to specific emails based on method patterns or pull from flow state. + + + Configure automatic fallback responses when no human replies within the timeout. + + + +### Key Benefits + +- **External responders**: Anyone with an email can respond, even non-platform users +- **Dynamic assignment**: Pull assignee email from flow state (e.g., `account_owner_email`) +- **Simple configuration**: Email-based routing is easier to set up than user/role management +- **Deployment creator fallback**: If no routing rule matches, the deployment creator is notified + + +For implementation details on the `@human_feedback` decorator, see the [Human Feedback in Flows](/en/learn/human-feedback-in-flows) guide. + + +## Setting Up Webhook-Based HITL Workflows + +For custom integrations with external systems like Slack, Microsoft Teams, or your own applications, you can use the webhook-based approach: @@ -99,3 +144,14 @@ HITL workflows are particularly valuable for: - Sensitive or high-stakes operations - Creative tasks requiring human judgment - Compliance and regulatory reviews + +## Learn More + + + + Explore the full Enterprise Flow HITL platform capabilities including email notifications, routing rules, auto-response, and analytics. + + + Implementation guide for the `@human_feedback` decorator in your Flows. + + diff --git a/docs/en/learn/human-in-the-loop.mdx b/docs/en/learn/human-in-the-loop.mdx index 02e327045..c9e8ba57d 100644 --- a/docs/en/learn/human-in-the-loop.mdx +++ b/docs/en/learn/human-in-the-loop.mdx @@ -151,3 +151,9 @@ HITL workflows are particularly valuable for: - Sensitive or high-stakes operations - Creative tasks requiring human judgment - Compliance and regulatory reviews + +## Enterprise Features + + + CrewAI Enterprise provides a comprehensive HITL management system for Flows with in-platform review, responder assignment, permissions, escalation policies, SLA management, dynamic routing, and full analytics. [Learn more →](/en/enterprise/features/flow-hitl-management) + diff --git a/docs/images/enterprise/hitl-list-pending-feedbacks.png b/docs/images/enterprise/hitl-list-pending-feedbacks.png new file mode 100644 index 000000000..223bcafd1 Binary files /dev/null and b/docs/images/enterprise/hitl-list-pending-feedbacks.png differ diff --git a/docs/images/enterprise/hitl-metrics.png b/docs/images/enterprise/hitl-metrics.png new file mode 100644 index 000000000..92e8a9102 Binary files /dev/null and b/docs/images/enterprise/hitl-metrics.png differ diff --git a/docs/images/enterprise/hitl-settings-auto-respond.png b/docs/images/enterprise/hitl-settings-auto-respond.png new file mode 100644 index 000000000..a2ebf667e Binary files /dev/null and b/docs/images/enterprise/hitl-settings-auto-respond.png differ diff --git a/docs/images/enterprise/hitl-settings-overview.png b/docs/images/enterprise/hitl-settings-overview.png new file mode 100644 index 000000000..ba4aaf8cd Binary files /dev/null and b/docs/images/enterprise/hitl-settings-overview.png differ diff --git a/docs/images/enterprise/hitl-settings-routing-rules.png b/docs/images/enterprise/hitl-settings-routing-rules.png new file mode 100644 index 000000000..652d85608 Binary files /dev/null and b/docs/images/enterprise/hitl-settings-routing-rules.png differ diff --git a/docs/images/enterprise/hitl-settings-webhook.png b/docs/images/enterprise/hitl-settings-webhook.png new file mode 100644 index 000000000..97c3c9d60 Binary files /dev/null and b/docs/images/enterprise/hitl-settings-webhook.png differ diff --git a/docs/ko/enterprise/features/flow-hitl-management.mdx b/docs/ko/enterprise/features/flow-hitl-management.mdx new file mode 100644 index 000000000..a760a4c44 --- /dev/null +++ b/docs/ko/enterprise/features/flow-hitl-management.mdx @@ -0,0 +1,563 @@ +--- +title: "Flow HITL 관리" +description: "이메일 우선 알림, 라우팅 규칙 및 자동 응답 기능을 갖춘 Flow용 엔터프라이즈급 인간 검토" +icon: "users-gear" +mode: "wide" +--- + + +Flow HITL 관리 기능은 `@human_feedback` 데코레이터가 필요하며, **CrewAI 버전 1.8.0 이상**에서 사용할 수 있습니다. 이 기능은 Crew가 아닌 **Flow**에만 적용됩니다. + + +CrewAI Enterprise는 AI 워크플로우를 협업적인 인간-AI 프로세스로 전환하는 Flow용 포괄적인 Human-in-the-Loop(HITL) 관리 시스템을 제공합니다. 플랫폼은 **이메일 우선 아키텍처**를 사용하여 이메일 주소가 있는 누구나 플랫폼 계정 없이도 검토 요청에 응답할 수 있습니다. + +## 개요 + + + + 응답자가 알림 이메일에 직접 회신하여 피드백 제공 가능 + + + 메서드 패턴 또는 Flow 상태에 따라 특정 이메일로 요청 라우팅 + + + 시간 내에 인간이 응답하지 않을 경우 자동 대체 응답 구성 + + + +### 주요 이점 + +- **간단한 멘탈 모델**: 이메일 주소는 보편적이며 플랫폼 사용자나 역할을 관리할 필요 없음 +- **외부 응답자**: 플랫폼 사용자가 아니어도 이메일이 있는 누구나 응답 가능 +- **동적 할당**: Flow 상태에서 직접 담당자 이메일 가져오기 (예: `sales_rep_email`) +- **간소화된 구성**: 설정할 항목이 적어 더 빠르게 가치 실현 +- **이메일이 주요 채널**: 대부분의 사용자는 대시보드 로그인보다 이메일로 응답하는 것을 선호 + +## Flow에서 인간 검토 포인트 설정 + +`@human_feedback` 데코레이터를 사용하여 Flow 내에 인간 검토 체크포인트를 구성합니다. 실행이 검토 포인트에 도달하면 시스템이 일시 중지되고, 담당자에게 이메일로 알리며, 응답을 기다립니다. + +```python +from crewai.flow.flow import Flow, start, listen +from crewai.flow.human_feedback import human_feedback, HumanFeedbackResult + +class ContentApprovalFlow(Flow): + @start() + def generate_content(self): + # AI가 콘텐츠 생성 + return "Q1 캠페인용 마케팅 카피 생성..." + + @listen(generate_content) + @human_feedback( + message="브랜드 준수를 위해 이 콘텐츠를 검토해 주세요:", + emit=["approved", "rejected", "needs_revision"], + ) + def review_content(self, content): + return content + + @listen("approved") + def publish_content(self, result: HumanFeedbackResult): + print(f"승인된 콘텐츠 게시 중. 검토자 노트: {result.feedback}") + + @listen("rejected") + def archive_content(self, result: HumanFeedbackResult): + print(f"콘텐츠 거부됨. 사유: {result.feedback}") + + @listen("needs_revision") + def revise_content(self, result: HumanFeedbackResult): + print(f"수정 요청: {result.feedback}") +``` + +완전한 구현 세부 사항은 [Flow에서 인간 피드백](/ko/learn/human-feedback-in-flows) 가이드를 참조하세요. + +### 데코레이터 파라미터 + +| 파라미터 | 유형 | 설명 | +|---------|------|------| +| `message` | `str` | 인간 검토자에게 표시되는 메시지 | +| `emit` | `list[str]` | 유효한 응답 옵션 (UI에서 버튼으로 표시) | + +## 플랫폼 구성 + +HITL 구성에 접근: **배포** → **설정** → **Human in the Loop 구성** + + + HITL 구성 설정 + + +### 이메일 알림 + +HITL 요청에 대한 이메일 알림을 활성화하거나 비활성화하는 토글입니다. + +| 설정 | 기본값 | 설명 | +|-----|-------|------| +| 이메일 알림 | 활성화됨 | 피드백 요청 시 이메일 전송 | + + +비활성화되면 응답자는 대시보드 UI를 사용하거나 커스텀 알림 시스템을 위해 webhook을 구성해야 합니다. + + +### SLA 목표 + +추적 및 메트릭 목적으로 목표 응답 시간을 설정합니다. + +| 설정 | 설명 | +|-----|------| +| SLA 목표 (분) | 목표 응답 시간. 대시보드 메트릭 및 SLA 추적에 사용 | + +SLA 추적을 비활성화하려면 비워 두세요. + +## 이메일 알림 및 응답 + +HITL 시스템은 응답자가 알림 이메일에 직접 회신할 수 있는 이메일 우선 아키텍처를 사용합니다. + +### 이메일 응답 작동 방식 + + + + HITL 요청이 생성되면 검토 콘텐츠와 컨텍스트가 포함된 이메일이 할당된 응답자에게 전송됩니다. + + + 이메일에는 인증을 위한 서명된 토큰이 포함된 특별한 reply-to 주소가 있습니다. + + + 응답자는 이메일에 피드백으로 회신하면 됩니다—로그인 필요 없음. + + + 플랫폼이 회신을 받고, 서명된 토큰을 확인하고, 발신자 이메일을 매칭합니다. + + + 피드백이 기록되고 인간의 입력으로 Flow가 계속됩니다. + + + +### 응답 형식 + +응답자는 다음과 같이 회신할 수 있습니다: + +- **Emit 옵션**: 회신이 `emit` 옵션과 일치하면 (예: "approved") 직접 사용됨 +- **자유 형식 텍스트**: 모든 텍스트 응답이 피드백으로 Flow에 전달됨 +- **일반 텍스트**: 회신 본문의 첫 번째 줄이 피드백으로 사용됨 + +### 확인 이메일 + +회신을 처리한 후 응답자는 피드백이 성공적으로 제출되었는지 또는 오류가 발생했는지 나타내는 확인 이메일을 받습니다. + +### 이메일 토큰 보안 + +- 토큰은 보안을 위해 암호화 서명됨 +- 토큰은 7일 후 만료됨 +- 발신자 이메일은 토큰의 인증된 이메일과 일치해야 함 +- 처리 후 확인/오류 이메일 전송됨 + +## 라우팅 규칙 + +메서드 패턴에 따라 HITL 요청을 특정 이메일 주소로 라우팅합니다. + + + HITL 라우팅 규칙 구성 + + +### 규칙 구조 + +```json +{ + "name": "재무팀으로 승인", + "match": { + "method_name": "approve_*" + }, + "assign_to_email": "finance@company.com", + "assign_from_input": "manager_email" +} +``` + +### 매칭 패턴 + +| 패턴 | 설명 | 매칭 예시 | +|-----|------|----------| +| `approve_*` | 와일드카드 (모든 문자) | `approve_payment`, `approve_vendor` | +| `review_?` | 단일 문자 | `review_a`, `review_1` | +| `validate_payment` | 정확히 일치 | `validate_payment`만 | + +### 할당 우선순위 + +1. **동적 할당** (`assign_from_input`): 구성된 경우 Flow 상태에서 이메일 가져옴 +2. **정적 이메일** (`assign_to_email`): 구성된 이메일로 대체 +3. **배포 생성자**: 규칙이 일치하지 않으면 배포 생성자의 이메일이 사용됨 + +### 동적 할당 예제 + +Flow 상태에 `{"sales_rep_email": "alice@company.com"}`이 포함된 경우: + +```json +{ + "name": "영업 담당자에게 라우팅", + "match": { + "method_name": "review_*" + }, + "assign_from_input": "sales_rep_email" +} +``` + +요청이 자동으로 `alice@company.com`에 할당됩니다. + + +**사용 사례**: CRM, 데이터베이스 또는 이전 Flow 단계에서 담당자를 가져와 적합한 사람에게 검토를 동적으로 라우팅하세요. + + +## 자동 응답 + +시간 내에 인간이 응답하지 않으면 HITL 요청에 자동으로 응답합니다. 이를 통해 Flow가 무한정 중단되지 않도록 합니다. + +### 구성 + +| 설정 | 설명 | +|-----|------| +| 활성화됨 | 자동 응답 활성화 토글 | +| 타임아웃 (분) | 자동 응답 전 대기 시간 | +| 기본 결과 | 응답 값 (`emit` 옵션과 일치해야 함) | + + + HITL 자동 응답 구성 + + +### 사용 사례 + +- **SLA 준수**: Flow가 무한정 중단되지 않도록 보장 +- **기본 승인**: 타임아웃 후 저위험 요청 자동 승인 +- **우아한 저하**: 검토자가 없을 때 안전한 기본값으로 계속 + + +자동 응답을 신중하게 사용하세요. 기본 응답이 허용되는 중요하지 않은 검토에만 활성화하세요. + + +## 검토 프로세스 + +### 대시보드 인터페이스 + +HITL 검토 인터페이스는 검토자에게 깔끔하고 집중된 경험을 제공합니다: + +- **마크다운 렌더링**: 구문 강조가 포함된 풍부한 형식의 검토 콘텐츠 +- **컨텍스트 패널**: Flow 상태, 실행 기록 및 관련 정보 보기 +- **피드백 입력**: 결정과 함께 상세한 피드백 및 코멘트 제공 +- **빠른 작업**: 선택적 코멘트가 있는 원클릭 emit 옵션 버튼 + + + HITL 대기 중인 요청 목록 + + +### 응답 방법 + +검토자는 세 가지 채널을 통해 응답할 수 있습니다: + +| 방법 | 설명 | +|-----|------| +| **이메일 회신** | 알림 이메일에 직접 회신 | +| **대시보드** | Enterprise 대시보드 UI 사용 | +| **API/Webhook** | API를 통한 프로그래밍 방식 응답 | + +### 기록 및 감사 추적 + +모든 HITL 상호작용은 완전한 타임라인으로 추적됩니다: + +- 결정 기록 (승인/거부/수정) +- 검토자 신원 및 타임스탬프 +- 제공된 피드백 및 코멘트 +- 응답 방법 (이메일/대시보드/API) +- 응답 시간 메트릭 + +## 분석 및 모니터링 + +포괄적인 분석으로 HITL 성능을 추적합니다. + +### 성능 대시보드 + + + HITL 메트릭 대시보드 + + + + + 검토자 또는 Flow별 평균 및 중앙값 응답 시간 모니터링. + + + 팀 용량 최적화를 위한 검토 볼륨 패턴 분석. + + + 다양한 검토 유형에 대한 승인/거부 비율 보기. + + + SLA 목표 내에 완료된 검토 비율 추적. + + + +### 감사 및 규정 준수 + +규제 요구 사항을 위한 엔터프라이즈급 감사 기능: + +- 타임스탬프가 있는 완전한 결정 기록 +- 검토자 신원 확인 +- 불변 감사 로그 +- 규정 준수 보고를 위한 내보내기 기능 + +## 일반적인 사용 사례 + + + + **사용 사례**: 인간 검증이 포함된 내부 보안 설문지 자동화 + + - AI가 보안 설문지에 대한 응답 생성 + - 보안팀이 이메일로 정확성 검토 및 검증 + - 승인된 응답이 최종 제출물로 편집 + - 규정 준수를 위한 완전한 감사 추적 + + + + **사용 사례**: 법무/브랜드 검토가 필요한 마케팅 콘텐츠 + + - AI가 마케팅 카피 또는 소셜 미디어 콘텐츠 생성 + - 브랜드팀 이메일로 목소리/톤 검토를 위해 라우팅 + - 승인 시 자동 게시 + + + + **사용 사례**: 경비 보고서, 계약 조건, 예산 배분 + + - AI가 재무 요청을 사전 처리하고 분류 + - 동적 할당을 사용하여 금액 임계값에 따라 라우팅 + - 재무 규정 준수를 위한 완전한 감사 추적 유지 + + + + **사용 사례**: CRM에서 계정 담당자에게 검토 라우팅 + + - Flow가 CRM에서 계정 담당자 이메일 가져옴 + - 이메일을 Flow 상태에 저장 (예: `account_owner_email`) + - `assign_from_input`을 사용하여 적합한 사람에게 자동 라우팅 + + + + **사용 사례**: 고객 전달 전 AI 출력 검증 + + - AI가 고객 대면 콘텐츠 또는 응답 생성 + - QA팀이 이메일 알림을 통해 검토 + - 피드백 루프가 시간이 지남에 따라 AI 성능 개선 + + + +## Webhook API + +Flow가 인간 피드백을 위해 일시 중지되면, 요청 데이터를 자체 애플리케이션으로 보내도록 webhook을 구성할 수 있습니다. 이를 통해 다음이 가능합니다: + +- 커스텀 승인 UI 구축 +- 내부 도구와 통합 (Jira, ServiceNow, 커스텀 대시보드) +- 타사 시스템으로 승인 라우팅 +- 모바일 앱 알림 +- 자동화된 결정 시스템 + + + HITL Webhook 구성 + + +### Webhook 구성 + + + + **배포** → **설정** → **Human in the Loop**으로 이동 + + + **Webhooks** 구성을 클릭하여 확장 + + + webhook URL 입력 (프로덕션에서는 HTTPS 필수) + + + **구성 저장**을 클릭하여 활성화 + + + +여러 webhook을 구성할 수 있습니다. 각 활성 webhook은 모든 HITL 이벤트를 수신합니다. + +### Webhook 이벤트 + +엔드포인트는 다음 이벤트에 대해 HTTP POST 요청을 수신합니다: + +| 이벤트 유형 | 트리거 시점 | +|------------|------------| +| `new_request` | Flow가 일시 중지되고 인간 피드백을 요청할 때 | + +### Webhook 페이로드 + +모든 webhook은 다음 구조의 JSON 페이로드를 수신합니다: + +```json +{ + "event": "new_request", + "request": { + "id": "550e8400-e29b-41d4-a716-446655440000", + "flow_id": "flow_abc123", + "method_name": "review_article", + "message": "이 기사의 게시를 검토해 주세요.", + "emit_options": ["approved", "rejected", "request_changes"], + "state": { + "article_id": 12345, + "author": "john@example.com", + "category": "technology" + }, + "metadata": {}, + "created_at": "2026-01-14T12:00:00Z" + }, + "deployment": { + "id": 456, + "name": "Content Review Flow", + "organization_id": 789 + }, + "callback_url": "https://api.crewai.com/...", + "assigned_to_email": "reviewer@company.com" +} +``` + +### 요청에 응답하기 + +피드백을 제출하려면 webhook 페이로드에 포함된 **`callback_url`로 POST**합니다. + +```http +POST {callback_url} +Content-Type: application/json + +{ + "feedback": "승인됨. 훌륭한 기사입니다!", + "source": "my_custom_app" +} +``` + +### 보안 + + +모든 webhook 요청은 HMAC-SHA256을 사용하여 암호화 서명되어 진위성을 보장하고 변조를 방지합니다. + + +#### Webhook 보안 + +- **HMAC-SHA256 서명**: 모든 webhook에 암호화 서명이 포함됨 +- **Webhook별 시크릿**: 각 webhook은 고유한 서명 시크릿을 가짐 +- **저장 시 암호화**: 서명 시크릿은 데이터베이스에서 암호화됨 +- **타임스탬프 검증**: 리플레이 공격 방지 + +#### 서명 헤더 + +각 webhook 요청에는 다음 헤더가 포함됩니다: + +| 헤더 | 설명 | +|------|------| +| `X-Signature` | HMAC-SHA256 서명: `sha256=` | +| `X-Timestamp` | 요청이 서명된 Unix 타임스탬프 | + +#### 검증 + +다음과 같이 계산하여 검증합니다: + +```python +import hmac +import hashlib + +expected = hmac.new( + signing_secret.encode(), + f"{timestamp}.{payload}".encode(), + hashlib.sha256 +).hexdigest() + +if hmac.compare_digest(expected, signature): + # 유효한 서명 +``` + +### 오류 처리 + +webhook 엔드포인트는 수신 확인을 위해 2xx 상태 코드를 반환해야 합니다: + +| 응답 | 동작 | +|------|------| +| 2xx | Webhook 성공적으로 전달됨 | +| 4xx/5xx | 실패로 기록됨, 재시도 없음 | +| 타임아웃 (30초) | 실패로 기록됨, 재시도 없음 | + +## 보안 및 RBAC + +### 대시보드 접근 + +HITL 접근은 배포 수준에서 제어됩니다: + +| 권한 | 기능 | +|-----|------| +| `manage_human_feedback` | HITL 설정 구성, 모든 요청 보기 | +| `respond_to_human_feedback` | 요청에 응답, 할당된 요청 보기 | + +### 이메일 응답 인증 + +이메일 회신의 경우: +1. reply-to 토큰이 인증된 이메일을 인코딩 +2. 발신자 이메일이 토큰의 이메일과 일치해야 함 +3. 토큰이 만료되지 않아야 함 (기본 7일) +4. 요청이 여전히 대기 중이어야 함 + +### 감사 추적 + +모든 HITL 작업이 기록됩니다: +- 요청 생성 +- 할당 변경 +- 응답 제출 (소스: 대시보드/이메일/API) +- Flow 재개 상태 + +## 문제 해결 + +### 이메일이 전송되지 않음 + +1. 구성에서 "이메일 알림"이 활성화되어 있는지 확인 +2. 라우팅 규칙이 메서드 이름과 일치하는지 확인 +3. 담당자 이메일이 유효한지 확인 +4. 라우팅 규칙이 일치하지 않는 경우 배포 생성자 대체 확인 + +### 이메일 회신이 처리되지 않음 + +1. 토큰이 만료되지 않았는지 확인 (기본 7일) +2. 발신자 이메일이 할당된 이메일과 일치하는지 확인 +3. 요청이 여전히 대기 중인지 확인 (아직 응답되지 않음) + +### Flow가 재개되지 않음 + +1. 대시보드에서 요청 상태 확인 +2. 콜백 URL에 접근 가능한지 확인 +3. 배포가 여전히 실행 중인지 확인 + +## 모범 사례 + + +**간단하게 시작**: 배포 생성자에게 이메일 알림으로 시작한 다음, 워크플로우가 성숙해지면 라우팅 규칙을 추가하세요. + + +1. **동적 할당 사용**: 유연한 라우팅을 위해 Flow 상태에서 담당자 이메일을 가져오세요. + +2. **자동 응답 구성**: 중요하지 않은 검토에 대해 Flow가 중단되지 않도록 대체를 설정하세요. + +3. **응답 시간 모니터링**: 분석을 사용하여 병목 현상을 식별하고 검토 프로세스를 최적화하세요. + +4. **검토 메시지를 명확하게 유지**: `@human_feedback` 데코레이터에 명확하고 실행 가능한 메시지를 작성하세요. + +5. **이메일 흐름 테스트**: 프로덕션에 가기 전에 테스트 요청을 보내 이메일 전달을 확인하세요. + +## 관련 리소스 + + + + `@human_feedback` 데코레이터 구현 가이드 + + + HITL 워크플로우 설정을 위한 단계별 가이드 + + + 조직을 위한 역할 기반 접근 제어 구성 + + + 실시간 이벤트 알림 설정 + + diff --git a/docs/ko/enterprise/guides/human-in-the-loop.mdx b/docs/ko/enterprise/guides/human-in-the-loop.mdx index 36556332d..924fddc6c 100644 --- a/docs/ko/enterprise/guides/human-in-the-loop.mdx +++ b/docs/ko/enterprise/guides/human-in-the-loop.mdx @@ -5,9 +5,54 @@ icon: "user-check" mode: "wide" --- -인간-중심(Human-In-The-Loop, HITL)은 인공지능과 인간 전문 지식을 결합하여 의사결정을 강화하고 작업 결과를 향상시키는 강력한 접근 방식입니다. 이 가이드는 CrewAI 내에서 HITL을 구현하는 방법을 보여줍니다. +인간-중심(Human-In-The-Loop, HITL)은 인공지능과 인간 전문 지식을 결합하여 의사결정을 강화하고 작업 결과를 향상시키는 강력한 접근 방식입니다. 이 가이드는 CrewAI Enterprise 내에서 HITL을 구현하는 방법을 보여줍니다. -## HITL 워크플로 설정 +## CrewAI의 HITL 접근 방식 + +CrewAI는 human-in-the-loop 워크플로우를 구현하기 위한 두 가지 접근 방식을 제공합니다: + +| 접근 방식 | 적합한 용도 | 버전 | +|----------|----------|---------| +| **Flow 기반** (`@human_feedback` 데코레이터) | Enterprise UI를 사용한 프로덕션, 이메일 우선 워크플로우, 전체 플랫폼 기능 | **1.8.0+** | +| **Webhook 기반** | 커스텀 통합, 외부 시스템 (Slack, Teams 등), 레거시 설정 | 모든 버전 | + +## Enterprise 플랫폼과 Flow 기반 HITL + + +`@human_feedback` 데코레이터는 **CrewAI 버전 1.8.0 이상**이 필요합니다. + + +Flow에서 `@human_feedback` 데코레이터를 사용하면, CrewAI Enterprise는 이메일 주소가 있는 누구나 검토 요청에 응답할 수 있는 **이메일 우선 HITL 시스템**을 제공합니다: + + + + 응답자가 이메일 알림을 받고 직접 회신할 수 있습니다—로그인이 필요 없습니다. + + + 원할 때 Enterprise 대시보드에서 HITL 요청을 검토하고 응답하세요. + + + 메서드 패턴에 따라 특정 이메일로 요청을 라우팅하거나 Flow 상태에서 가져오세요. + + + 타임아웃 내에 인간이 응답하지 않을 경우 자동 대체 응답을 구성하세요. + + + +### 주요 이점 + +- **외부 응답자**: 플랫폼 사용자가 아니어도 이메일이 있는 누구나 응답 가능 +- **동적 할당**: Flow 상태에서 담당자 이메일 가져오기 (예: `account_owner_email`) +- **간단한 구성**: 이메일 기반 라우팅은 사용자/역할 관리보다 설정이 쉬움 +- **배포 생성자 대체**: 라우팅 규칙이 일치하지 않으면 배포 생성자에게 알림 + + +`@human_feedback` 데코레이터의 구현 세부 사항은 [Flow에서 인간 피드백](/ko/learn/human-feedback-in-flows) 가이드를 참조하세요. + + +## Webhook 기반 HITL 워크플로 설정 + +Slack, Microsoft Teams 또는 자체 애플리케이션과 같은 외부 시스템과의 커스텀 통합을 위해 webhook 기반 접근 방식을 사용할 수 있습니다: @@ -99,3 +144,14 @@ HITL 워크플로우는 특히 다음과 같은 경우에 유용합니다: - 민감하거나 위험도가 높은 작업 - 인간의 판단이 필요한 창의적 작업 - 준수 및 규제 검토 + +## 자세히 알아보기 + + + + 이메일 알림, 라우팅 규칙, 자동 응답 및 분석을 포함한 전체 Enterprise Flow HITL 플랫폼 기능을 살펴보세요. + + + Flow에서 `@human_feedback` 데코레이터 구현 가이드. + + diff --git a/docs/ko/learn/human-in-the-loop.mdx b/docs/ko/learn/human-in-the-loop.mdx index 9ccdcb231..fe9c1d145 100644 --- a/docs/ko/learn/human-in-the-loop.mdx +++ b/docs/ko/learn/human-in-the-loop.mdx @@ -112,3 +112,9 @@ HITL 워크플로우는 다음과 같은 경우에 특히 유용합니다: - 민감하거나 고위험 작업 - 인간의 판단이 필요한 창의적 과제 - 컴플라이언스 및 규제 검토 + +## Enterprise 기능 + + + CrewAI Enterprise는 플랫폼 내 검토, 응답자 할당, 권한, 에스컬레이션 정책, SLA 관리, 동적 라우팅 및 전체 분석을 갖춘 Flow용 포괄적인 HITL 관리 시스템을 제공합니다. [자세히 알아보기 →](/ko/enterprise/features/flow-hitl-management) + diff --git a/docs/pt-BR/enterprise/features/flow-hitl-management.mdx b/docs/pt-BR/enterprise/features/flow-hitl-management.mdx new file mode 100644 index 000000000..1a6651203 --- /dev/null +++ b/docs/pt-BR/enterprise/features/flow-hitl-management.mdx @@ -0,0 +1,563 @@ +--- +title: "Gerenciamento HITL para Flows" +description: "Revisão humana de nível empresarial para Flows com notificações por email, regras de roteamento e capacidades de resposta automática" +icon: "users-gear" +mode: "wide" +--- + + +Os recursos de gerenciamento HITL para Flows requerem o decorador `@human_feedback`, disponível no **CrewAI versão 1.8.0 ou superior**. Estes recursos aplicam-se especificamente a **Flows**, não a Crews. + + +O CrewAI Enterprise oferece um sistema abrangente de gerenciamento Human-in-the-Loop (HITL) para Flows que transforma fluxos de trabalho de IA em processos colaborativos humano-IA. A plataforma usa uma **arquitetura email-first** que permite que qualquer pessoa com um endereço de email responda a solicitações de revisão—sem necessidade de conta na plataforma. + +## Visão Geral + + + + Respondentes podem responder diretamente aos emails de notificação para fornecer feedback + + + Direcione solicitações para emails específicos com base em padrões de método ou estado do flow + + + Configure respostas automáticas de fallback quando nenhum humano responder a tempo + + + +### Principais Benefícios + +- **Modelo mental simples**: Endereços de email são universais; não é necessário gerenciar usuários ou funções da plataforma +- **Respondentes externos**: Qualquer pessoa com email pode responder, mesmo não sendo usuário da plataforma +- **Atribuição dinâmica**: Obtenha o email do responsável diretamente do estado do flow (ex: `sales_rep_email`) +- **Configuração reduzida**: Menos configurações para definir, tempo mais rápido para gerar valor +- **Email como canal principal**: A maioria dos usuários prefere responder via email do que fazer login em um dashboard + +## Configurando Pontos de Revisão Humana em Flows + +Configure checkpoints de revisão humana em seus Flows usando o decorador `@human_feedback`. Quando a execução atinge um ponto de revisão, o sistema pausa, notifica o responsável via email e aguarda uma resposta. + +```python +from crewai.flow.flow import Flow, start, listen +from crewai.flow.human_feedback import human_feedback, HumanFeedbackResult + +class ContentApprovalFlow(Flow): + @start() + def generate_content(self): + # IA gera conteúdo + return "Texto de marketing gerado para campanha Q1..." + + @listen(generate_content) + @human_feedback( + message="Por favor, revise este conteúdo para conformidade com a marca:", + emit=["approved", "rejected", "needs_revision"], + ) + def review_content(self, content): + return content + + @listen("approved") + def publish_content(self, result: HumanFeedbackResult): + print(f"Publicando conteúdo aprovado. Notas do revisor: {result.feedback}") + + @listen("rejected") + def archive_content(self, result: HumanFeedbackResult): + print(f"Conteúdo rejeitado. Motivo: {result.feedback}") + + @listen("needs_revision") + def revise_content(self, result: HumanFeedbackResult): + print(f"Revisão solicitada: {result.feedback}") +``` + +Para detalhes completos de implementação, consulte o guia [Feedback Humano em Flows](/pt-BR/learn/human-feedback-in-flows). + +### Parâmetros do Decorador + +| Parâmetro | Tipo | Descrição | +|-----------|------|-----------| +| `message` | `str` | A mensagem exibida para o revisor humano | +| `emit` | `list[str]` | Opções de resposta válidas (exibidas como botões na UI) | + +## Configuração da Plataforma + +Acesse a configuração HITL em: **Deployment** → **Settings** → **Human in the Loop Configuration** + + + Configurações HITL + + +### Notificações por Email + +Toggle para ativar ou desativar notificações por email para solicitações HITL. + +| Configuração | Padrão | Descrição | +|--------------|--------|-----------| +| Notificações por Email | Ativado | Enviar emails quando feedback for solicitado | + + +Quando desativado, os respondentes devem usar a UI do dashboard ou você deve configurar webhooks para sistemas de notificação personalizados. + + +### Meta de SLA + +Defina um tempo de resposta alvo para fins de rastreamento e métricas. + +| Configuração | Descrição | +|--------------|-----------| +| Meta de SLA (minutos) | Tempo de resposta alvo. Usado para métricas do dashboard e rastreamento de SLA | + +Deixe vazio para desativar o rastreamento de SLA. + +## Notificações e Respostas por Email + +O sistema HITL usa uma arquitetura email-first onde os respondentes podem responder diretamente aos emails de notificação. + +### Como Funcionam as Respostas por Email + + + + Quando uma solicitação HITL é criada, um email é enviado ao respondente atribuído com o conteúdo e contexto da revisão. + + + O email inclui um endereço reply-to especial com um token assinado para autenticação. + + + O respondente simplesmente responde ao email com seu feedback—nenhum login necessário. + + + A plataforma recebe a resposta, verifica o token assinado e corresponde o email do remetente. + + + O feedback é registrado e o flow continua com a entrada humana. + + + +### Formato de Resposta + +Respondentes podem responder com: + +- **Opção emit**: Se a resposta corresponder a uma opção `emit` (ex: "approved"), ela é usada diretamente +- **Texto livre**: Qualquer resposta de texto é passada para o flow como feedback +- **Texto simples**: A primeira linha do corpo da resposta é usada como feedback + +### Emails de Confirmação + +Após processar uma resposta, o respondente recebe um email de confirmação indicando se o feedback foi enviado com sucesso ou se ocorreu um erro. + +### Segurança do Token de Email + +- Tokens são assinados criptograficamente para segurança +- Tokens expiram após 7 dias +- Email do remetente deve corresponder ao email autorizado do token +- Emails de confirmação/erro são enviados após o processamento + +## Regras de Roteamento + +Direcione solicitações HITL para endereços de email específicos com base em padrões de método. + + + Configuração de Regras de Roteamento HITL + + +### Estrutura da Regra + +```json +{ + "name": "Aprovações para Financeiro", + "match": { + "method_name": "approve_*" + }, + "assign_to_email": "financeiro@empresa.com", + "assign_from_input": "manager_email" +} +``` + +### Padrões de Correspondência + +| Padrão | Descrição | Exemplo de Correspondência | +|--------|-----------|---------------------------| +| `approve_*` | Wildcard (qualquer caractere) | `approve_payment`, `approve_vendor` | +| `review_?` | Caractere único | `review_a`, `review_1` | +| `validate_payment` | Correspondência exata | apenas `validate_payment` | + +### Prioridade de Atribuição + +1. **Atribuição dinâmica** (`assign_from_input`): Se configurado, obtém email do estado do flow +2. **Email estático** (`assign_to_email`): Fallback para email configurado +3. **Criador do deployment**: Se nenhuma regra corresponder, o email do criador do deployment é usado + +### Exemplo de Atribuição Dinâmica + +Se seu estado do flow contém `{"sales_rep_email": "alice@empresa.com"}`, configure: + +```json +{ + "name": "Direcionar para Representante de Vendas", + "match": { + "method_name": "review_*" + }, + "assign_from_input": "sales_rep_email" +} +``` + +A solicitação será atribuída automaticamente para `alice@empresa.com`. + + +**Caso de Uso**: Obtenha o responsável do seu CRM, banco de dados ou etapa anterior do flow para direcionar revisões dinamicamente para a pessoa certa. + + +## Resposta Automática + +Responda automaticamente a solicitações HITL se nenhum humano responder dentro do timeout. Isso garante que os flows não fiquem travados indefinidamente. + +### Configuração + +| Configuração | Descrição | +|--------------|-----------| +| Ativado | Toggle para ativar resposta automática | +| Timeout (minutos) | Tempo de espera antes de responder automaticamente | +| Resultado Padrão | O valor da resposta (deve corresponder a uma opção `emit`) | + + + Configuração de Resposta Automática HITL + + +### Casos de Uso + +- **Conformidade com SLA**: Garante que flows não fiquem travados indefinidamente +- **Aprovação padrão**: Aprove automaticamente solicitações de baixo risco após timeout +- **Degradação graciosa**: Continue com um padrão seguro quando revisores não estiverem disponíveis + + +Use resposta automática com cuidado. Ative apenas para revisões não críticas onde uma resposta padrão é aceitável. + + +## Processo de Revisão + +### Interface do Dashboard + +A interface de revisão HITL oferece uma experiência limpa e focada para revisores: + +- **Renderização Markdown**: Formatação rica para conteúdo de revisão com destaque de sintaxe +- **Painel de Contexto**: Visualize estado do flow, histórico de execução e informações relacionadas +- **Entrada de Feedback**: Forneça feedback detalhado e comentários com sua decisão +- **Ações Rápidas**: Botões de opção emit com um clique com comentários opcionais + + + Lista de Solicitações HITL Pendentes + + +### Métodos de Resposta + +Revisores podem responder por três canais: + +| Método | Descrição | +|--------|-----------| +| **Resposta por Email** | Responda diretamente ao email de notificação | +| **Dashboard** | Use a UI do dashboard Enterprise | +| **API/Webhook** | Resposta programática via API | + +### Histórico e Trilha de Auditoria + +Toda interação HITL é rastreada com uma linha do tempo completa: + +- Histórico de decisões (aprovar/rejeitar/revisar) +- Identidade do revisor e timestamp +- Feedback e comentários fornecidos +- Método de resposta (email/dashboard/API) +- Métricas de tempo de resposta + +## Análise e Monitoramento + +Acompanhe o desempenho HITL com análises abrangentes. + +### Dashboard de Desempenho + + + Dashboard de Métricas HITL + + + + + Monitore tempos de resposta médios e medianos por revisor ou flow. + + + Analise padrões de volume de revisão para otimizar capacidade da equipe. + + + Visualize taxas de aprovação/rejeição em diferentes tipos de revisão. + + + Acompanhe a porcentagem de revisões concluídas dentro das metas de SLA. + + + +### Auditoria e Conformidade + +Capacidades de auditoria prontas para empresas para requisitos regulatórios: + +- Histórico completo de decisões com timestamps +- Verificação de identidade do revisor +- Logs de auditoria imutáveis +- Capacidades de exportação para relatórios de conformidade + +## Casos de Uso Comuns + + + + **Caso de Uso**: Automação de questionários de segurança internos com validação humana + + - IA gera respostas para questionários de segurança + - Equipe de segurança revisa e valida precisão via email + - Respostas aprovadas são compiladas na submissão final + - Trilha de auditoria completa para conformidade + + + + **Caso de Uso**: Conteúdo de marketing que requer revisão legal/marca + + - IA gera texto de marketing ou conteúdo de mídia social + - Roteie para email da equipe de marca para revisão de voz/tom + - Publicação automática após aprovação + + + + **Caso de Uso**: Relatórios de despesas, termos de contrato, alocações de orçamento + + - IA pré-processa e categoriza solicitações financeiras + - Roteie com base em limites de valor usando atribuição dinâmica + - Mantenha trilha de auditoria completa para conformidade financeira + + + + **Caso de Uso**: Direcione revisões para proprietários de conta do seu CRM + + - Flow obtém email do proprietário da conta do CRM + - Armazene email no estado do flow (ex: `account_owner_email`) + - Use `assign_from_input` para direcionar automaticamente para a pessoa certa + + + + **Caso de Uso**: Validação de saída de IA antes da entrega ao cliente + + - IA gera conteúdo ou respostas voltadas ao cliente + - Equipe de QA revisa via notificação por email + - Loops de feedback melhoram desempenho da IA ao longo do tempo + + + +## API de Webhooks + +Quando seus Flows pausam para feedback humano, você pode configurar webhooks para enviar dados da solicitação para sua própria aplicação. Isso permite: + +- Construir UIs de aprovação personalizadas +- Integrar com ferramentas internas (Jira, ServiceNow, dashboards personalizados) +- Rotear aprovações para sistemas de terceiros +- Notificações em apps mobile +- Sistemas de decisão automatizados + + + Configuração de Webhook HITL + + +### Configurando Webhooks + + + + Vá para **Deployment** → **Settings** → **Human in the Loop** + + + Clique para expandir a configuração de **Webhooks** + + + Digite sua URL de webhook (deve ser HTTPS em produção) + + + Clique em **Salvar Configuração** para ativar + + + +Você pode configurar múltiplos webhooks. Cada webhook ativo recebe todos os eventos HITL. + +### Eventos de Webhook + +Seu endpoint receberá requisições HTTP POST para estes eventos: + +| Tipo de Evento | Quando é Disparado | +|----------------|-------------------| +| `new_request` | Um flow pausa e solicita feedback humano | + +### Payload do Webhook + +Todos os webhooks recebem um payload JSON com esta estrutura: + +```json +{ + "event": "new_request", + "request": { + "id": "550e8400-e29b-41d4-a716-446655440000", + "flow_id": "flow_abc123", + "method_name": "review_article", + "message": "Por favor, revise este artigo para publicação.", + "emit_options": ["approved", "rejected", "request_changes"], + "state": { + "article_id": 12345, + "author": "john@example.com", + "category": "technology" + }, + "metadata": {}, + "created_at": "2026-01-14T12:00:00Z" + }, + "deployment": { + "id": 456, + "name": "Content Review Flow", + "organization_id": 789 + }, + "callback_url": "https://api.crewai.com/...", + "assigned_to_email": "reviewer@company.com" +} +``` + +### Respondendo a Solicitações + +Para enviar feedback, **faça POST para a `callback_url`** incluída no payload do webhook. + +```http +POST {callback_url} +Content-Type: application/json + +{ + "feedback": "Aprovado. Ótimo artigo!", + "source": "my_custom_app" +} +``` + +### Segurança + + +Todas as requisições de webhook são assinadas criptograficamente usando HMAC-SHA256 para garantir autenticidade e prevenir adulteração. + + +#### Segurança do Webhook + +- **Assinaturas HMAC-SHA256**: Todo webhook inclui uma assinatura criptográfica +- **Secrets por webhook**: Cada webhook tem seu próprio secret de assinatura único +- **Criptografado em repouso**: Os secrets de assinatura são criptografados no nosso banco de dados +- **Verificação de timestamp**: Previne ataques de replay + +#### Headers de Assinatura + +Cada requisição de webhook inclui estes headers: + +| Header | Descrição | +|--------|-----------| +| `X-Signature` | Assinatura HMAC-SHA256: `sha256=` | +| `X-Timestamp` | Timestamp Unix de quando a requisição foi assinada | + +#### Verificação + +Verifique computando: + +```python +import hmac +import hashlib + +expected = hmac.new( + signing_secret.encode(), + f"{timestamp}.{payload}".encode(), + hashlib.sha256 +).hexdigest() + +if hmac.compare_digest(expected, signature): + # Assinatura válida +``` + +### Tratamento de Erros + +Seu endpoint de webhook deve retornar um código de status 2xx para confirmar o recebimento: + +| Sua Resposta | Nosso Comportamento | +|--------------|---------------------| +| 2xx | Webhook entregue com sucesso | +| 4xx/5xx | Registrado como falha, sem retry | +| Timeout (30s) | Registrado como falha, sem retry | + +## Segurança e RBAC + +### Acesso ao Dashboard + +O acesso HITL é controlado no nível do deployment: + +| Permissão | Capacidade | +|-----------|------------| +| `manage_human_feedback` | Configurar settings HITL, ver todas as solicitações | +| `respond_to_human_feedback` | Responder a solicitações, ver solicitações atribuídas | + +### Autorização de Resposta por Email + +Para respostas por email: +1. O token reply-to codifica o email autorizado +2. Email do remetente deve corresponder ao email do token +3. Token não deve estar expirado (padrão 7 dias) +4. Solicitação ainda deve estar pendente + +### Trilha de Auditoria + +Todas as ações HITL são registradas: +- Criação de solicitação +- Mudanças de atribuição +- Submissão de resposta (com fonte: dashboard/email/API) +- Status de retomada do flow + +## Solução de Problemas + +### Emails Não Enviando + +1. Verifique se "Notificações por Email" está ativado na configuração +2. Verifique se as regras de roteamento correspondem ao nome do método +3. Verifique se o email do responsável é válido +4. Verifique o fallback do criador do deployment se nenhuma regra de roteamento corresponder + +### Respostas de Email Não Processando + +1. Verifique se o token não expirou (padrão 7 dias) +2. Verifique se o email do remetente corresponde ao email atribuído +3. Garanta que a solicitação ainda está pendente (não respondida ainda) + +### Flow Não Retomando + +1. Verifique o status da solicitação no dashboard +2. Verifique se a URL de callback está acessível +3. Garanta que o deployment ainda está rodando + +## Melhores Práticas + + +**Comece Simples**: Comece com notificações por email para o criador do deployment, depois adicione regras de roteamento conforme seus fluxos de trabalho amadurecem. + + +1. **Use Atribuição Dinâmica**: Obtenha emails de responsáveis do seu estado do flow para roteamento flexível. + +2. **Configure Resposta Automática**: Defina um fallback para revisões não críticas para evitar que flows fiquem travados. + +3. **Monitore Tempos de Resposta**: Use análises para identificar gargalos e otimizar seu processo de revisão. + +4. **Mantenha Mensagens de Revisão Claras**: Escreva mensagens claras e acionáveis no decorador `@human_feedback`. + +5. **Teste o Fluxo de Email**: Envie solicitações de teste para verificar a entrega de email antes de ir para produção. + +## Recursos Relacionados + + + + Guia de implementação para o decorador `@human_feedback` + + + Guia passo a passo para configurar workflows HITL + + + Configure controle de acesso baseado em função para sua organização + + + Configure notificações de eventos em tempo real + + diff --git a/docs/pt-BR/enterprise/guides/human-in-the-loop.mdx b/docs/pt-BR/enterprise/guides/human-in-the-loop.mdx index 298290aef..7d853d1e4 100644 --- a/docs/pt-BR/enterprise/guides/human-in-the-loop.mdx +++ b/docs/pt-BR/enterprise/guides/human-in-the-loop.mdx @@ -5,9 +5,54 @@ icon: "user-check" mode: "wide" --- -Human-In-The-Loop (HITL) é uma abordagem poderosa que combina inteligência artificial com expertise humana para aprimorar a tomada de decisão e melhorar os resultados das tarefas. Este guia mostra como implementar HITL dentro do CrewAI. +Human-In-The-Loop (HITL) é uma abordagem poderosa que combina inteligência artificial com expertise humana para aprimorar a tomada de decisão e melhorar os resultados das tarefas. Este guia mostra como implementar HITL dentro do CrewAI Enterprise. -## Configurando Workflows HITL +## Abordagens HITL no CrewAI + +CrewAI oferece duas abordagens para implementar workflows human-in-the-loop: + +| Abordagem | Melhor Para | Versão | +|----------|----------|---------| +| **Baseada em Flow** (decorador `@human_feedback`) | Produção com UI Enterprise, workflows email-first, recursos completos da plataforma | **1.8.0+** | +| **Baseada em Webhook** | Integrações customizadas, sistemas externos (Slack, Teams, etc.), configurações legadas | Todas as versões | + +## HITL Baseado em Flow com Plataforma Enterprise + + +O decorador `@human_feedback` requer **CrewAI versão 1.8.0 ou superior**. + + +Ao usar o decorador `@human_feedback` em seus Flows, o CrewAI Enterprise oferece um **sistema HITL email-first** que permite que qualquer pessoa com um endereço de email responda a solicitações de revisão: + + + + Respondentes recebem notificações por email e podem responder diretamente—nenhum login necessário. + + + Revise e responda a solicitações HITL no dashboard Enterprise quando preferir. + + + Direcione solicitações para emails específicos com base em padrões de método ou obtenha do estado do flow. + + + Configure respostas automáticas de fallback quando nenhum humano responder dentro do timeout. + + + +### Principais Benefícios + +- **Respondentes externos**: Qualquer pessoa com email pode responder, mesmo não sendo usuário da plataforma +- **Atribuição dinâmica**: Obtenha o email do responsável do estado do flow (ex: `account_owner_email`) +- **Configuração simples**: Roteamento baseado em email é mais fácil de configurar do que gerenciamento de usuários/funções +- **Fallback do criador do deployment**: Se nenhuma regra de roteamento corresponder, o criador do deployment é notificado + + +Para detalhes de implementação do decorador `@human_feedback`, consulte o guia [Feedback Humano em Flows](/pt-BR/learn/human-feedback-in-flows). + + +## Configurando Workflows HITL Baseados em Webhook + +Para integrações customizadas com sistemas externos como Slack, Microsoft Teams ou suas próprias aplicações, você pode usar a abordagem baseada em webhook: @@ -99,3 +144,14 @@ Workflows HITL são particularmente valiosos para: - Operações sensíveis ou de alto risco - Tarefas criativas que exigem julgamento humano - Revisões de conformidade e regulatórias + +## Saiba Mais + + + + Explore os recursos completos da plataforma HITL para Flows, incluindo notificações por email, regras de roteamento, resposta automática e análises. + + + Guia de implementação para o decorador `@human_feedback` em seus Flows. + + diff --git a/docs/pt-BR/learn/human-in-the-loop.mdx b/docs/pt-BR/learn/human-in-the-loop.mdx index 07528027c..d56fa1167 100644 --- a/docs/pt-BR/learn/human-in-the-loop.mdx +++ b/docs/pt-BR/learn/human-in-the-loop.mdx @@ -112,3 +112,9 @@ Workflows HITL são particularmente valiosos para: - Operações sensíveis ou de alto risco - Tarefas criativas que requerem julgamento humano - Revisões de conformidade e regulamentação + +## Recursos Enterprise + + + O CrewAI Enterprise oferece um sistema abrangente de gerenciamento HITL para Flows com revisão na plataforma, atribuição de respondentes, permissões, políticas de escalação, gerenciamento de SLA, roteamento dinâmico e análises completas. [Saiba mais →](/pt-BR/enterprise/features/flow-hitl-management) +