mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-09-12 22:29:41 +00:00
Compare commits
1 Commits
iris/fix-g
...
cursor/fix
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa4587cbb0 |
@@ -156,7 +156,8 @@
|
||||
"icon": "gear",
|
||||
"pages": [
|
||||
"edge/en/guides/advanced/customizing-prompts",
|
||||
"edge/en/guides/advanced/fingerprinting"
|
||||
"edge/en/guides/advanced/fingerprinting",
|
||||
"edge/en/guides/advanced/security-best-practices"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -13400,7 +13401,8 @@
|
||||
"icon": "gear",
|
||||
"pages": [
|
||||
"edge/pt-BR/guides/advanced/customizing-prompts",
|
||||
"edge/pt-BR/guides/advanced/fingerprinting"
|
||||
"edge/pt-BR/guides/advanced/fingerprinting",
|
||||
"edge/pt-BR/guides/advanced/security-best-practices"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -25750,7 +25752,8 @@
|
||||
"icon": "gear",
|
||||
"pages": [
|
||||
"edge/ko/guides/advanced/customizing-prompts",
|
||||
"edge/ko/guides/advanced/fingerprinting"
|
||||
"edge/ko/guides/advanced/fingerprinting",
|
||||
"edge/ko/guides/advanced/security-best-practices"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -38520,7 +38523,8 @@
|
||||
"icon": "gear",
|
||||
"pages": [
|
||||
"edge/ar/guides/advanced/customizing-prompts",
|
||||
"edge/ar/guides/advanced/fingerprinting"
|
||||
"edge/ar/guides/advanced/fingerprinting",
|
||||
"edge/ar/guides/advanced/security-best-practices"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
181
docs/edge/ar/guides/advanced/security-best-practices.mdx
Normal file
181
docs/edge/ar/guides/advanced/security-best-practices.mdx
Normal file
@@ -0,0 +1,181 @@
|
||||
---
|
||||
title: أفضل ممارسات الأمان لـ Agents في CrewAI
|
||||
description: إرشادات عملية لتكوين Agents وCrews في CrewAI بأمان في بيئات الإنتاج.
|
||||
icon: shield
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يركز هذا الدليل على **ضوابط CrewAI الأصلية** التي يمكنك استخدامها لتقليل مخاطر الأمان في أنظمة الإنتاج.
|
||||
|
||||
الهدف بسيط: إبقاء سلوك الـ Agent محدودًا، بأقل امتياز، وقابلًا للمراجعة.
|
||||
|
||||
## 1) تحديد التنفيذ لمنع السلوك الجامح
|
||||
|
||||
استخدم حدود التنفيذ على Agents وCrews حتى تتدهور الأعطال بشكل متوقع بدلًا من التصاعد.
|
||||
|
||||
### الضوابط الموصى بها
|
||||
|
||||
- `max_rpm`: تحديد معدل الطلبات إلى المزودين
|
||||
- `max_iter`: تحديد دورات التفكير/الأدوات التكرارية
|
||||
- `max_execution_time`: مهلة صارمة للعمل الطويل
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
analyst = Agent(
|
||||
role="Security Analyst",
|
||||
goal="Investigate and summarize incidents",
|
||||
backstory="Careful and methodical",
|
||||
max_rpm=30,
|
||||
max_iter=12,
|
||||
max_execution_time=180,
|
||||
)
|
||||
```
|
||||
|
||||
## 2) تطبيق أقل امتياز على الأدوات
|
||||
|
||||
تجنب منح كل أداة لكل Agent. امنح كل Agent فقط الأدوات المطلوبة لمهمته.
|
||||
|
||||
### لماذا يهم ذلك
|
||||
|
||||
- يقلل نطاق تأثير prompt injection أو أخطاء المنطق
|
||||
- يمنع الوصول العرضي إلى أنظمة غير ذات صلة
|
||||
- يحسّن إمكانية تتبع من يمكنه فعل ماذا
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai.tools import FileReadTool, SerperDevTool
|
||||
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Collect external facts",
|
||||
backstory="Finds reliable sources",
|
||||
tools=[SerperDevTool()],
|
||||
)
|
||||
|
||||
auditor = Agent(
|
||||
role="Document Auditor",
|
||||
goal="Review internal policy documents",
|
||||
backstory="Checks compliance language",
|
||||
tools=[FileReadTool()],
|
||||
)
|
||||
```
|
||||
|
||||
## 3) التعامل مع التفويض كحدود ثقة
|
||||
|
||||
عندما يكون `allow_delegation=True`، يمكن للـ Agent توجيه العمل إلى Agents أخرى. قد يكون ذلك مفيدًا، لكنه أيضًا حد أمني.
|
||||
|
||||
### أنماط تفويض آمنة
|
||||
|
||||
- اجعل التفويض معطّلًا افتراضيًا
|
||||
- فعّله فقط للأدوار التي تحتاج فعلًا إلى orchestration
|
||||
- ادمجه مع قيود Task واضحة وتنفيذ محدود
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
coordinator = Agent(
|
||||
role="Coordinator",
|
||||
goal="Route specialized tasks",
|
||||
backstory="Delegates carefully",
|
||||
allow_delegation=True,
|
||||
max_iter=8,
|
||||
)
|
||||
```
|
||||
|
||||
## 4) تقييد المخرجات بالمخططات والتوقعات
|
||||
|
||||
استخدم مخرجات منظمة whenever possible لتقليل الاستجابات الغامضة أو غير الآمنة.
|
||||
|
||||
### الضوابط الموصى بها
|
||||
|
||||
- `output_pydantic` لمخرجات Task validated بالمخطط
|
||||
- `expected_output` لوصف معايير قبول صارمة
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from crewai import Task
|
||||
|
||||
class RiskSummary(BaseModel):
|
||||
severity: str
|
||||
findings: list[str]
|
||||
recommendation: str
|
||||
|
||||
security_task = Task(
|
||||
description="Review tool configuration for least privilege",
|
||||
expected_output="A structured risk summary with severity, findings, and recommendation.",
|
||||
output_pydantic=RiskSummary,
|
||||
)
|
||||
```
|
||||
|
||||
## 5) إضافة إشراف بشري للإجراءات عالية المخاطر
|
||||
|
||||
للعمليات الحساسة (مثل الإجراءات المالية، تغييرات الإنتاج، أو التغييرات المؤثرة على العملاء)، أضف مراجعة بشرية في النقطة الصحيحة من مسار التنفيذ.
|
||||
|
||||
### ماذا يفعل `human_input=True`
|
||||
|
||||
`human_input=True` على Task يوقف التنفيذ **بعد** أن يشغّل الـ Agent أدواته وينتج نتيجة. يطلب ملاحظات بشرية على الإجابة النهائية **قبل قبول هذه المخرجات واعتمادها**. **لا** يمنع تنفيذ الأدوات — يمكن للـ Agent في Task مع `human_input=True` أن يستدعي أدوات مدمرة أو ذات آثار جانبية قبل أن يرى أي إنسان التشغيل.
|
||||
|
||||
استخدم `human_input=True` عندما تريد أن يراجع إنسان مخرجات Task أو يعدّلها أو يوافق عليها قبل أن تصبح النتيجة الرسمية (مثل سير عمل التدريب أو مراجعة الجودة).
|
||||
|
||||
```python
|
||||
from crewai import Task
|
||||
|
||||
review_task = Task(
|
||||
description="Draft the incident summary from collected logs",
|
||||
expected_output="A concise incident summary",
|
||||
human_input=True,
|
||||
)
|
||||
```
|
||||
|
||||
### عندما تحتاج موافقة قبل تشغيل الأدوات
|
||||
|
||||
لنقاط مثل:
|
||||
|
||||
- قبل تشغيل أدوات لا رجعة فيها
|
||||
- قبل الآثار الجانبية الخارجية (بريد، تذاكر، كتابة)
|
||||
- قبل استثناءات السياسة/الأمان
|
||||
|
||||
استخدم بوابات ما قبل التنفيذ:
|
||||
|
||||
- **[Tool hooks](/ar/learn/tool-hooks)** مع `@on(InterceptionPoint.PRE_TOOL_CALL)` و`request_human_input()` — يمنع استدعاء الأداة حتى الموافقة
|
||||
- **[Execution hooks](/ar/learn/execution-hooks)** في تشغيل Crew وFlow
|
||||
- **[@human_feedback](/ar/learn/human-feedback-in-flows)** على خطوات Flow للموافقة على مستوى سير العمل
|
||||
|
||||
```python
|
||||
from crewai.hooks import HookAborted, InterceptionPoint, on
|
||||
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email", "delete_file"])
|
||||
def require_approval(ctx):
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Approve {ctx.tool_name}?",
|
||||
default_message=f"Args: {ctx.tool_input}\nType 'yes' to approve:",
|
||||
)
|
||||
if response.strip().lower() != "yes":
|
||||
raise HookAborted(reason="denied by operator", source="approval-gate")
|
||||
```
|
||||
|
||||
للمراجعة لاحقًا، فكّر في تفعيل `verbose=True` على Agents في تدفقات حساسة لتسهيل الفحص أثناء التصحيح ومراجعة الحوادث.
|
||||
|
||||
## قائمة تحقق تشغيلية
|
||||
|
||||
استخدم هذه القائمة السريعة قبل النشر في الإنتاج:
|
||||
|
||||
- [ ] كل Agent له تنفيذ محدود (`max_rpm`، `max_iter`، `max_execution_time`)
|
||||
- [ ] الوصول إلى الأدوات محدود حسب الدور (بدون قائمة أدوات مشتركة واسعة)
|
||||
- [ ] التفويض معطّل ما لم يكن مطلوبًا صراحة
|
||||
- [ ] Tasks عالية التأثير تستخدم `output_pydantic` و`expected_output` دقيق
|
||||
- [ ] بوابات موافقة ما قبل التنفيذ موجودة للأدوات غير القابلة للتراجع أو ذات الآثار الجانبية (tool hooks أو Flow hooks أو `@human_feedback`)
|
||||
- [ ] `human_input=True` يُستخدم فقط حيث تكفي مراجعة المخرجات بعد التشغيل
|
||||
- [ ] تشغيلات Agent مسجّلة أو متتبعة للمراجعة بعد الحادث
|
||||
|
||||
## موارد ذات صلة
|
||||
|
||||
- [Agents](/ar/concepts/agents)
|
||||
- [Tasks](/ar/concepts/tasks)
|
||||
- [Flows](/ar/concepts/flows)
|
||||
- [Human input on execution](/ar/learn/human-input-on-execution)
|
||||
- [Human-in-the-loop](/ar/learn/human-in-the-loop)
|
||||
- [Tool Hooks](/ar/learn/tool-hooks)
|
||||
- [Tracing and observability](/ar/observability/overview)
|
||||
181
docs/edge/en/guides/advanced/security-best-practices.mdx
Normal file
181
docs/edge/en/guides/advanced/security-best-practices.mdx
Normal file
@@ -0,0 +1,181 @@
|
||||
---
|
||||
title: Security Best Practices for CrewAI Agents
|
||||
description: Practical guidance for configuring CrewAI agents and crews safely in production.
|
||||
icon: shield
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
This guide focuses on **CrewAI-native controls** you can use to reduce security risk in production systems.
|
||||
|
||||
The goal is simple: keep agent behavior bounded, least-privileged, and reviewable.
|
||||
|
||||
## 1) Bound execution to prevent runaway behavior
|
||||
|
||||
Use execution limits on agents and crews so failures degrade predictably instead of spiraling.
|
||||
|
||||
### Recommended controls
|
||||
|
||||
- `max_rpm`: cap request rate to providers
|
||||
- `max_iter`: cap iterative reasoning/tool cycles
|
||||
- `max_execution_time`: hard timeout for long-running work
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
analyst = Agent(
|
||||
role="Security Analyst",
|
||||
goal="Investigate and summarize incidents",
|
||||
backstory="Careful and methodical",
|
||||
max_rpm=30,
|
||||
max_iter=12,
|
||||
max_execution_time=180,
|
||||
)
|
||||
```
|
||||
|
||||
## 2) Apply least privilege to tools
|
||||
|
||||
Avoid giving every tool to every agent. Give each agent only the tools required for its task.
|
||||
|
||||
### Why this matters
|
||||
|
||||
- Reduces blast radius for prompt injection or logic errors
|
||||
- Prevents accidental access to unrelated systems
|
||||
- Improves traceability of who can do what
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai.tools import FileReadTool, SerperDevTool
|
||||
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Collect external facts",
|
||||
backstory="Finds reliable sources",
|
||||
tools=[SerperDevTool()],
|
||||
)
|
||||
|
||||
auditor = Agent(
|
||||
role="Document Auditor",
|
||||
goal="Review internal policy documents",
|
||||
backstory="Checks compliance language",
|
||||
tools=[FileReadTool()],
|
||||
)
|
||||
```
|
||||
|
||||
## 3) Treat delegation as a trust boundary
|
||||
|
||||
When `allow_delegation=True`, an agent can route work to other agents. That can be useful, but it is also a security boundary.
|
||||
|
||||
### Safe delegation patterns
|
||||
|
||||
- Keep delegation disabled by default
|
||||
- Enable it only for roles that truly need orchestration
|
||||
- Pair delegation with clear task constraints and bounded execution
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
coordinator = Agent(
|
||||
role="Coordinator",
|
||||
goal="Route specialized tasks",
|
||||
backstory="Delegates carefully",
|
||||
allow_delegation=True,
|
||||
max_iter=8,
|
||||
)
|
||||
```
|
||||
|
||||
## 4) Constrain outputs with schemas and expectations
|
||||
|
||||
Use structured outputs whenever possible to reduce ambiguous or unsafe free-form responses.
|
||||
|
||||
### Recommended controls
|
||||
|
||||
- `output_pydantic` for schema-validated task output
|
||||
- `expected_output` to describe strict acceptance criteria
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from crewai import Task
|
||||
|
||||
class RiskSummary(BaseModel):
|
||||
severity: str
|
||||
findings: list[str]
|
||||
recommendation: str
|
||||
|
||||
security_task = Task(
|
||||
description="Review tool configuration for least privilege",
|
||||
expected_output="A structured risk summary with severity, findings, and recommendation.",
|
||||
output_pydantic=RiskSummary,
|
||||
)
|
||||
```
|
||||
|
||||
## 5) Add human oversight for high-stakes actions
|
||||
|
||||
For sensitive operations (for example financial actions, production mutations, or customer-impacting changes), add human review at the right point in the execution path.
|
||||
|
||||
### What `human_input=True` does
|
||||
|
||||
Task `human_input=True` pauses **after** the agent has run its tools and produced a result. It prompts for human feedback on the final answer **before that output is accepted and finalized**. It does **not** gate tool execution — an agent on a task with `human_input=True` can still call destructive or side-effect tools before any human sees the run.
|
||||
|
||||
Use `human_input=True` when you want a human to review, refine, or approve the task output before it becomes the official result (for example training workflows or quality review).
|
||||
|
||||
```python
|
||||
from crewai import Task
|
||||
|
||||
review_task = Task(
|
||||
description="Draft the incident summary from collected logs",
|
||||
expected_output="A concise incident summary",
|
||||
human_input=True,
|
||||
)
|
||||
```
|
||||
|
||||
### When you need approval before tools run
|
||||
|
||||
For checkpoints such as:
|
||||
|
||||
- Before running irreversible tools
|
||||
- Before external side effects (emails, tickets, writes)
|
||||
- Before policy or security exceptions
|
||||
|
||||
Use pre-execution gates instead:
|
||||
|
||||
- **[Tool hooks](/en/learn/tool-hooks)** with `@on(InterceptionPoint.PRE_TOOL_CALL)` and `request_human_input()` — blocks the tool call until approved
|
||||
- **[Execution hooks](/en/learn/execution-hooks)** on Crew and Flow runs
|
||||
- **[@human_feedback](/en/learn/human-feedback-in-flows)** on Flow steps for workflow-level approval
|
||||
|
||||
```python
|
||||
from crewai.hooks import HookAborted, InterceptionPoint, on
|
||||
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email", "delete_file"])
|
||||
def require_approval(ctx):
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Approve {ctx.tool_name}?",
|
||||
default_message=f"Args: {ctx.tool_input}\nType 'yes' to approve:",
|
||||
)
|
||||
if response.strip().lower() != "yes":
|
||||
raise HookAborted(reason="denied by operator", source="approval-gate")
|
||||
```
|
||||
|
||||
For reviewability after the fact, consider enabling `verbose=True` on agents involved in sensitive flows so execution details are easier to inspect during debugging and incident review.
|
||||
|
||||
## Operational checklist
|
||||
|
||||
Use this quick checklist before production rollout:
|
||||
|
||||
- [ ] Every agent has bounded execution (`max_rpm`, `max_iter`, `max_execution_time`)
|
||||
- [ ] Tool access is scoped per role (no broad shared tool list)
|
||||
- [ ] Delegation is disabled unless explicitly required
|
||||
- [ ] High-impact tasks use `output_pydantic` and precise `expected_output`
|
||||
- [ ] Pre-execution approval gates exist for irreversible or side-effect tools (tool hooks, Flow hooks, or `@human_feedback`)
|
||||
- [ ] `human_input=True` is used only where post-run output review is sufficient
|
||||
- [ ] Agent runs are logged or traced for post-incident review
|
||||
|
||||
## Related resources
|
||||
|
||||
- [Agents](/en/concepts/agents)
|
||||
- [Tasks](/en/concepts/tasks)
|
||||
- [Flows](/en/concepts/flows)
|
||||
- [Human input on execution](/en/learn/human-input-on-execution)
|
||||
- [Human-in-the-loop](/en/learn/human-in-the-loop)
|
||||
- [Tool Hooks](/en/learn/tool-hooks)
|
||||
- [Tracing and observability](/en/observability/overview)
|
||||
181
docs/edge/ko/guides/advanced/security-best-practices.mdx
Normal file
181
docs/edge/ko/guides/advanced/security-best-practices.mdx
Normal file
@@ -0,0 +1,181 @@
|
||||
---
|
||||
title: CrewAI Agent 보안 모범 사례
|
||||
description: 프로덕션에서 CrewAI Agent와 Crew를 안전하게 구성하기 위한 실용 가이드.
|
||||
icon: shield
|
||||
---
|
||||
|
||||
## 개요
|
||||
|
||||
이 가이드는 프로덕션 시스템에서 보안 위험을 줄이기 위해 사용할 수 있는 **CrewAI 기본 제어**에 초점을 맞춥니다.
|
||||
|
||||
목표는 간단합니다. Agent 동작을 제한하고, 최소 권한을 적용하며, 검토 가능하게 유지하는 것입니다.
|
||||
|
||||
## 1) 실행 범위를 제한해 폭주 동작 방지
|
||||
|
||||
Agent와 Crew에 실행 제한을 설정하면 실패가 확산되기보다 예측 가능하게 처리됩니다.
|
||||
|
||||
### 권장 제어
|
||||
|
||||
- `max_rpm`: 프로바이더 요청 속도 상한
|
||||
- `max_iter`: 반복 추론/도구 호출 사이클 상한
|
||||
- `max_execution_time`: 장시간 작업에 대한 하드 타임아웃
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
analyst = Agent(
|
||||
role="Security Analyst",
|
||||
goal="Investigate and summarize incidents",
|
||||
backstory="Careful and methodical",
|
||||
max_rpm=30,
|
||||
max_iter=12,
|
||||
max_execution_time=180,
|
||||
)
|
||||
```
|
||||
|
||||
## 2) 도구에 최소 권한 적용
|
||||
|
||||
모든 Agent에게 모든 도구를 주지 마세요. 각 Agent에는 해당 Task에 필요한 도구만 제공하세요.
|
||||
|
||||
### 중요한 이유
|
||||
|
||||
- 프롬프트 인젝션이나 로직 오류의 영향 범위 축소
|
||||
- 관련 없는 시스템에 대한 우발적 접근 방지
|
||||
- 누가 무엇을 할 수 있는지 추적성 향상
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai.tools import FileReadTool, SerperDevTool
|
||||
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Collect external facts",
|
||||
backstory="Finds reliable sources",
|
||||
tools=[SerperDevTool()],
|
||||
)
|
||||
|
||||
auditor = Agent(
|
||||
role="Document Auditor",
|
||||
goal="Review internal policy documents",
|
||||
backstory="Checks compliance language",
|
||||
tools=[FileReadTool()],
|
||||
)
|
||||
```
|
||||
|
||||
## 3) 위임을 신뢰 경계로 취급
|
||||
|
||||
`allow_delegation=True`이면 Agent가 다른 Agent에게 작업을 라우팅할 수 있습니다. 유용할 수 있지만 보안 경계이기도 합니다.
|
||||
|
||||
### 안전한 위임 패턴
|
||||
|
||||
- 기본값으로 위임 비활성화
|
||||
- 실제로 오케스트레이션이 필요한 역할에만 활성화
|
||||
- 명확한 Task 제약과 제한된 실행과 함께 사용
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
coordinator = Agent(
|
||||
role="Coordinator",
|
||||
goal="Route specialized tasks",
|
||||
backstory="Delegates carefully",
|
||||
allow_delegation=True,
|
||||
max_iter=8,
|
||||
)
|
||||
```
|
||||
|
||||
## 4) 스키마와 기대 출력으로 출력 제한
|
||||
|
||||
가능한 한 구조화된 출력을 사용해 모호하거나 위험한 자유 형식 응답을 줄이세요.
|
||||
|
||||
### 권장 제어
|
||||
|
||||
- `output_pydantic`: 스키마로 검증되는 Task 출력
|
||||
- `expected_output`: 엄격한 수용 기준 설명
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from crewai import Task
|
||||
|
||||
class RiskSummary(BaseModel):
|
||||
severity: str
|
||||
findings: list[str]
|
||||
recommendation: str
|
||||
|
||||
security_task = Task(
|
||||
description="Review tool configuration for least privilege",
|
||||
expected_output="A structured risk summary with severity, findings, and recommendation.",
|
||||
output_pydantic=RiskSummary,
|
||||
)
|
||||
```
|
||||
|
||||
## 5) 고위험 작업에 대한 인간 감독 추가
|
||||
|
||||
민감한 작업(예: 금융 작업, 프로덕션 변경, 고객 영향 변경)에는 실행 경로의 올바른 지점에서 인간 검토를 추가하세요.
|
||||
|
||||
### `human_input=True`가 하는 일
|
||||
|
||||
Task의 `human_input=True`는 Agent가 도구를 실행하고 결과를 생성한 **후**에 일시 중지합니다. 최종 답변에 대한 인간 피드백을 요청하여 **해당 출력이 수락·확정되기 전**에 검토할 수 있게 합니다. 도구 실행을 차단하지 **않습니다** — `human_input=True`인 Task의 Agent도 사람이 실행을 보기 전에 파괴적이거나 부수 효과가 있는 도구를 호출할 수 있습니다.
|
||||
|
||||
공식 결과가 되기 전에 Task 출력을 검토·수정·승인하려는 경우(예: 트레이닝 워크플로, 품질 검토)에 `human_input=True`를 사용하세요.
|
||||
|
||||
```python
|
||||
from crewai import Task
|
||||
|
||||
review_task = Task(
|
||||
description="Draft the incident summary from collected logs",
|
||||
expected_output="A concise incident summary",
|
||||
human_input=True,
|
||||
)
|
||||
```
|
||||
|
||||
### 도구 실행 전 승인이 필요한 경우
|
||||
|
||||
다음과 같은 체크포인트에는 사전 실행 게이트를 사용하세요.
|
||||
|
||||
- 되돌릴 수 없는 도구 실행 전
|
||||
- 외부 부수 효과(이메일, 티켓, 쓰기) 전
|
||||
- 정책/보안 예외 전
|
||||
|
||||
사전 실행 게이트 예:
|
||||
|
||||
- **`@on(InterceptionPoint.PRE_TOOL_CALL)`** 및 `request_human_input()`이 있는 **[Tool hooks](/ko/learn/tool-hooks)** — 승인 전까지 도구 호출 차단
|
||||
- Crew 및 Flow 실행의 **[Execution hooks](/ko/learn/execution-hooks)**
|
||||
- 워크플로 수준 승인을 위한 Flow 단계의 **[@human_feedback](/ko/learn/human-feedback-in-flows)**
|
||||
|
||||
```python
|
||||
from crewai.hooks import HookAborted, InterceptionPoint, on
|
||||
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email", "delete_file"])
|
||||
def require_approval(ctx):
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Approve {ctx.tool_name}?",
|
||||
default_message=f"Args: {ctx.tool_input}\nType 'yes' to approve:",
|
||||
)
|
||||
if response.strip().lower() != "yes":
|
||||
raise HookAborted(reason="denied by operator", source="approval-gate")
|
||||
```
|
||||
|
||||
사후 검토를 위해 민감한 Flow에 관여하는 Agent에 `verbose=True`를 설정하면 디버깅 및 사후 분석 시 실행 세부 정보를 더 쉽게 확인할 수 있습니다.
|
||||
|
||||
## 운영 체크리스트
|
||||
|
||||
프로덕션 배포 전 빠른 체크리스트:
|
||||
|
||||
- [ ] 모든 Agent에 실행 제한(`max_rpm`, `max_iter`, `max_execution_time`) 적용
|
||||
- [ ] 역할별로 도구 접근 범위 제한(광범위한 공유 도구 목록 없음)
|
||||
- [ ] 명시적으로 필요한 경우가 아니면 위임 비활성화
|
||||
- [ ] 고영향 Task에 `output_pydantic`과 정확한 `expected_output` 사용
|
||||
- [ ] 되돌릴 수 없거나 부수 효과가 있는 도구에 사전 실행 승인 게이트 존재(tool hooks, Flow hooks, `@human_feedback`)
|
||||
- [ ] `human_input=True`는 실행 후 출력 검토로 충분한 경우에만 사용
|
||||
- [ ] Agent 실행이 사후 검토를 위해 로깅 또는 추적됨
|
||||
|
||||
## 관련 리소스
|
||||
|
||||
- [Agents](/ko/concepts/agents)
|
||||
- [Tasks](/ko/concepts/tasks)
|
||||
- [Flows](/ko/concepts/flows)
|
||||
- [Human input on execution](/ko/learn/human-input-on-execution)
|
||||
- [Human-in-the-loop](/ko/learn/human-in-the-loop)
|
||||
- [Tool Hooks](/ko/learn/tool-hooks)
|
||||
- [Tracing and observability](/ko/observability/overview)
|
||||
181
docs/edge/pt-BR/guides/advanced/security-best-practices.mdx
Normal file
181
docs/edge/pt-BR/guides/advanced/security-best-practices.mdx
Normal file
@@ -0,0 +1,181 @@
|
||||
---
|
||||
title: Melhores Práticas de Segurança para Agentes CrewAI
|
||||
description: Orientação prática para configurar agentes e crews CrewAI com segurança em produção.
|
||||
icon: shield
|
||||
---
|
||||
|
||||
## Visão geral
|
||||
|
||||
Este guia foca em **controles nativos do CrewAI** que você pode usar para reduzir riscos de segurança em sistemas de produção.
|
||||
|
||||
O objetivo é simples: manter o comportamento do agente limitado, com privilégio mínimo e auditável.
|
||||
|
||||
## 1) Limitar a execução para evitar comportamento descontrolado
|
||||
|
||||
Use limites de execução em agentes e crews para que falhas degradem de forma previsível em vez de escalar.
|
||||
|
||||
### Controles recomendados
|
||||
|
||||
- `max_rpm`: limitar taxa de requisições aos provedores
|
||||
- `max_iter`: limitar ciclos iterativos de raciocínio/ferramentas
|
||||
- `max_execution_time`: timeout rígido para trabalhos longos
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
analyst = Agent(
|
||||
role="Security Analyst",
|
||||
goal="Investigate and summarize incidents",
|
||||
backstory="Careful and methodical",
|
||||
max_rpm=30,
|
||||
max_iter=12,
|
||||
max_execution_time=180,
|
||||
)
|
||||
```
|
||||
|
||||
## 2) Aplicar privilégio mínimo às ferramentas
|
||||
|
||||
Evite dar todas as ferramentas a todos os agentes. Dê a cada agente apenas as ferramentas necessárias para sua tarefa.
|
||||
|
||||
### Por que isso importa
|
||||
|
||||
- Reduz o raio de impacto de prompt injection ou erros de lógica
|
||||
- Evita acesso acidental a sistemas não relacionados
|
||||
- Melhora a rastreabilidade de quem pode fazer o quê
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai.tools import FileReadTool, SerperDevTool
|
||||
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Collect external facts",
|
||||
backstory="Finds reliable sources",
|
||||
tools=[SerperDevTool()],
|
||||
)
|
||||
|
||||
auditor = Agent(
|
||||
role="Document Auditor",
|
||||
goal="Review internal policy documents",
|
||||
backstory="Checks compliance language",
|
||||
tools=[FileReadTool()],
|
||||
)
|
||||
```
|
||||
|
||||
## 3) Tratar delegação como um limite de confiança
|
||||
|
||||
Quando `allow_delegation=True`, um agente pode encaminhar trabalho a outros agentes. Isso pode ser útil, mas também é um limite de segurança.
|
||||
|
||||
### Padrões seguros de delegação
|
||||
|
||||
- Mantenha a delegação desativada por padrão
|
||||
- Ative apenas para papéis que realmente precisam de orquestração
|
||||
- Combine delegação com restrições claras de tarefa e execução limitada
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
coordinator = Agent(
|
||||
role="Coordinator",
|
||||
goal="Route specialized tasks",
|
||||
backstory="Delegates carefully",
|
||||
allow_delegation=True,
|
||||
max_iter=8,
|
||||
)
|
||||
```
|
||||
|
||||
## 4) Restringir saídas com schemas e expectativas
|
||||
|
||||
Use saídas estruturadas sempre que possível para reduzir respostas ambíguas ou inseguras em texto livre.
|
||||
|
||||
### Controles recomendados
|
||||
|
||||
- `output_pydantic` para saída de Task validada por schema
|
||||
- `expected_output` para descrever critérios rígidos de aceitação
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from crewai import Task
|
||||
|
||||
class RiskSummary(BaseModel):
|
||||
severity: str
|
||||
findings: list[str]
|
||||
recommendation: str
|
||||
|
||||
security_task = Task(
|
||||
description="Review tool configuration for least privilege",
|
||||
expected_output="A structured risk summary with severity, findings, and recommendation.",
|
||||
output_pydantic=RiskSummary,
|
||||
)
|
||||
```
|
||||
|
||||
## 5) Adicionar supervisão humana para ações de alto impacto
|
||||
|
||||
Para operações sensíveis (por exemplo ações financeiras, mutações em produção ou mudanças que afetam clientes), adicione revisão humana no ponto certo do caminho de execução.
|
||||
|
||||
### O que `human_input=True` faz
|
||||
|
||||
`human_input=True` em uma Task pausa **depois** que o agente executou suas ferramentas e produziu um resultado. Ele solicita feedback humano sobre a resposta final **antes que essa saída seja aceita e finalizada**. **Não** bloqueia a execução de ferramentas — um agente em uma Task com `human_input=True` ainda pode chamar ferramentas destrutivas ou com efeitos colaterais antes que qualquer humano veja a execução.
|
||||
|
||||
Use `human_input=True` quando quiser que um humano revise, refine ou aprove a saída da Task antes que ela se torne o resultado oficial (por exemplo fluxos de treinamento ou revisão de qualidade).
|
||||
|
||||
```python
|
||||
from crewai import Task
|
||||
|
||||
review_task = Task(
|
||||
description="Draft the incident summary from collected logs",
|
||||
expected_output="A concise incident summary",
|
||||
human_input=True,
|
||||
)
|
||||
```
|
||||
|
||||
### Quando você precisa de aprovação antes das ferramentas executarem
|
||||
|
||||
Para checkpoints como:
|
||||
|
||||
- Antes de executar ferramentas irreversíveis
|
||||
- Antes de efeitos colaterais externos (e-mails, tickets, gravações)
|
||||
- Antes de exceções de política ou segurança
|
||||
|
||||
Use gates de pré-execução:
|
||||
|
||||
- **[Tool hooks](/pt-BR/learn/tool-hooks)** com `@on(InterceptionPoint.PRE_TOOL_CALL)` e `request_human_input()` — bloqueia a chamada da ferramenta até aprovação
|
||||
- **[Execution hooks](/pt-BR/learn/execution-hooks)** em execuções de Crew e Flow
|
||||
- **[@human_feedback](/pt-BR/learn/human-feedback-in-flows)** em passos de Flow para aprovação no nível do workflow
|
||||
|
||||
```python
|
||||
from crewai.hooks import HookAborted, InterceptionPoint, on
|
||||
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email", "delete_file"])
|
||||
def require_approval(ctx):
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Approve {ctx.tool_name}?",
|
||||
default_message=f"Args: {ctx.tool_input}\nType 'yes' to approve:",
|
||||
)
|
||||
if response.strip().lower() != "yes":
|
||||
raise HookAborted(reason="denied by operator", source="approval-gate")
|
||||
```
|
||||
|
||||
Para auditabilidade posterior, considere habilitar `verbose=True` em agentes envolvidos em fluxos sensíveis para facilitar a inspeção durante depuração e revisão de incidentes.
|
||||
|
||||
## Checklist operacional
|
||||
|
||||
Use este checklist rápido antes do rollout em produção:
|
||||
|
||||
- [ ] Cada agente tem execução limitada (`max_rpm`, `max_iter`, `max_execution_time`)
|
||||
- [ ] O acesso a ferramentas é escopado por papel (sem lista ampla compartilhada)
|
||||
- [ ] A delegação está desativada, salvo quando explicitamente necessária
|
||||
- [ ] Tasks de alto impacto usam `output_pydantic` e `expected_output` preciso
|
||||
- [ ] Gates de aprovação pré-execução existem para ferramentas irreversíveis ou com efeito colateral (tool hooks, Flow hooks ou `@human_feedback`)
|
||||
- [ ] `human_input=True` é usado apenas onde revisão pós-execução da saída é suficiente
|
||||
- [ ] Execuções de agentes são registradas ou rastreadas para revisão pós-incidente
|
||||
|
||||
## Recursos relacionados
|
||||
|
||||
- [Agents](/pt-BR/concepts/agents)
|
||||
- [Tasks](/pt-BR/concepts/tasks)
|
||||
- [Flows](/pt-BR/concepts/flows)
|
||||
- [Human input on execution](/pt-BR/learn/human-input-on-execution)
|
||||
- [Human-in-the-loop](/pt-BR/learn/human-in-the-loop)
|
||||
- [Tool Hooks](/pt-BR/learn/tool-hooks)
|
||||
- [Tracing and observability](/pt-BR/observability/overview)
|
||||
Reference in New Issue
Block a user