Add Korean translations (#3307)
Some checks failed
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled

This commit is contained in:
Daniel Barreto
2025-08-12 19:58:12 -03:00
committed by GitHub
parent 251ae00b8b
commit a0eadf783b
185 changed files with 36306 additions and 0 deletions

View File

@@ -696,6 +696,352 @@
]
}
]
},
{
"language": "ko",
"global": {
"anchors": [
{
"anchor": "웹사이트",
"href": "https://crewai.com",
"icon": "globe"
},
{
"anchor": "법정",
"href": "https://community.crewai.com",
"icon": "discourse"
},
{
"anchor": "Crew GPT",
"href": "https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant",
"icon": "robot"
},
{
"anchor": "출시",
"href": "https://github.com/crewAIInc/crewAI/releases",
"icon": "tag"
}
]
},
"tabs": [
{
"tab": "기술 문서",
"groups": [
{
"group": "시작 안내",
"pages": ["ko/introduction", "ko/installation", "ko/quickstart"]
},
{
"group": "안내서",
"pages": [
{
"group": "전략",
"pages": ["ko/guides/concepts/evaluating-use-cases"]
},
{
"group": "Agents",
"pages": ["ko/guides/agents/crafting-effective-agents"]
},
{
"group": "Crews",
"pages": ["ko/guides/crews/first-crew"]
},
{
"group": "Flows",
"pages": [
"ko/guides/flows/first-flow",
"ko/guides/flows/mastering-flow-state"
]
},
{
"group": "고급",
"pages": [
"ko/guides/advanced/customizing-prompts",
"ko/guides/advanced/fingerprinting"
]
}
]
},
{
"group": "핵심 개념",
"pages": [
"ko/concepts/agents",
"ko/concepts/tasks",
"ko/concepts/crews",
"ko/concepts/flows",
"ko/concepts/knowledge",
"ko/concepts/llms",
"ko/concepts/processes",
"ko/concepts/collaboration",
"ko/concepts/training",
"ko/concepts/memory",
"ko/concepts/reasoning",
"ko/concepts/planning",
"ko/concepts/testing",
"ko/concepts/cli",
"ko/concepts/tools",
"ko/concepts/event-listener"
]
},
{
"group": "MCP 통합",
"pages": [
"ko/mcp/overview",
"ko/mcp/stdio",
"ko/mcp/sse",
"ko/mcp/streamable-http",
"ko/mcp/multiple-servers",
"ko/mcp/security"
]
},
{
"group": "도구",
"pages": [
"ko/tools/overview",
{
"group": "파일 & 문서",
"pages": [
"ko/tools/file-document/overview",
"ko/tools/file-document/filereadtool",
"ko/tools/file-document/filewritetool",
"ko/tools/file-document/pdfsearchtool",
"ko/tools/file-document/docxsearchtool",
"ko/tools/file-document/mdxsearchtool",
"ko/tools/file-document/xmlsearchtool",
"ko/tools/file-document/txtsearchtool",
"ko/tools/file-document/jsonsearchtool",
"ko/tools/file-document/csvsearchtool",
"ko/tools/file-document/directorysearchtool",
"ko/tools/file-document/directoryreadtool",
"ko/tools/file-document/ocrtool",
"ko/tools/file-document/pdf-text-writing-tool"
]
},
{
"group": "웹 스크래핑 & 브라우징",
"pages": [
"ko/tools/web-scraping/overview",
"ko/tools/web-scraping/scrapewebsitetool",
"ko/tools/web-scraping/scrapeelementfromwebsitetool",
"ko/tools/web-scraping/scrapflyscrapetool",
"ko/tools/web-scraping/seleniumscrapingtool",
"ko/tools/web-scraping/scrapegraphscrapetool",
"ko/tools/web-scraping/spidertool",
"ko/tools/web-scraping/browserbaseloadtool",
"ko/tools/web-scraping/hyperbrowserloadtool",
"ko/tools/web-scraping/stagehandtool",
"ko/tools/web-scraping/firecrawlcrawlwebsitetool",
"ko/tools/web-scraping/firecrawlscrapewebsitetool",
"ko/tools/web-scraping/oxylabsscraperstool",
"ko/tools/web-scraping/brightdata-tools"
]
},
{
"group": "검색 및 연구",
"pages": [
"ko/tools/search-research/overview",
"ko/tools/search-research/serperdevtool",
"ko/tools/search-research/bravesearchtool",
"ko/tools/search-research/exasearchtool",
"ko/tools/search-research/linkupsearchtool",
"ko/tools/search-research/githubsearchtool",
"ko/tools/search-research/websitesearchtool",
"ko/tools/search-research/codedocssearchtool",
"ko/tools/search-research/youtubechannelsearchtool",
"ko/tools/search-research/youtubevideosearchtool",
"ko/tools/search-research/tavilysearchtool",
"ko/tools/search-research/tavilyextractortool",
"ko/tools/search-research/arxivpapertool",
"ko/tools/search-research/serpapi-googlesearchtool",
"ko/tools/search-research/serpapi-googleshoppingtool",
"ko/tools/search-research/databricks-query-tool"
]
},
{
"group": "데이터베이스 & 데이터",
"pages": [
"ko/tools/database-data/overview",
"ko/tools/database-data/mysqltool",
"ko/tools/database-data/pgsearchtool",
"ko/tools/database-data/snowflakesearchtool",
"ko/tools/database-data/nl2sqltool",
"ko/tools/database-data/qdrantvectorsearchtool",
"ko/tools/database-data/weaviatevectorsearchtool",
"ko/tools/database-data/mongodbvectorsearchtool",
"ko/tools/database-data/singlestoresearchtool"
]
},
{
"group": "인공지능 & 머신러닝",
"pages": [
"ko/tools/ai-ml/overview",
"ko/tools/ai-ml/dalletool",
"ko/tools/ai-ml/visiontool",
"ko/tools/ai-ml/aimindtool",
"ko/tools/ai-ml/llamaindextool",
"ko/tools/ai-ml/langchaintool",
"ko/tools/ai-ml/ragtool",
"ko/tools/ai-ml/codeinterpretertool"
]
},
{
"group": "클라우드 & 저장",
"pages": [
"ko/tools/cloud-storage/overview",
"ko/tools/cloud-storage/s3readertool",
"ko/tools/cloud-storage/s3writertool",
"ko/tools/cloud-storage/bedrockinvokeagenttool",
"ko/tools/cloud-storage/bedrockkbretriever"
]
},
{
"group": "자동화 & 통합",
"pages": [
"ko/tools/automation/overview",
"ko/tools/automation/apifyactorstool",
"ko/tools/automation/composiotool",
"ko/tools/automation/multiontool",
"ko/tools/automation/zapieractionstool"
]
}
]
},
{
"group": "오브저버빌리티",
"pages": [
"ko/observability/overview",
"ko/observability/agentops",
"ko/observability/arize-phoenix",
"ko/observability/langdb",
"ko/observability/langfuse",
"ko/observability/langtrace",
"ko/observability/maxim",
"ko/observability/mlflow",
"ko/observability/neatlogs",
"ko/observability/openlit",
"ko/observability/opik",
"ko/observability/patronus-evaluation",
"ko/observability/portkey",
"ko/observability/weave"
]
},
{
"group": "익히다",
"pages": [
"ko/learn/overview",
"ko/learn/llm-selection-guide",
"ko/learn/conditional-tasks",
"ko/learn/coding-agents",
"ko/learn/create-custom-tools",
"ko/learn/custom-llm",
"ko/learn/custom-manager-agent",
"ko/learn/customizing-agents",
"ko/learn/dalle-image-generation",
"ko/learn/force-tool-output-as-result",
"ko/learn/hierarchical-process",
"ko/learn/human-input-on-execution",
"ko/learn/kickoff-async",
"ko/learn/kickoff-for-each",
"ko/learn/llm-connections",
"ko/learn/multimodal-agents",
"ko/learn/replay-tasks-from-latest-crew-kickoff",
"ko/learn/sequential-process",
"ko/learn/using-annotations"
]
},
{
"group": "원격측정",
"pages": ["ko/telemetry"]
}
]
},
{
"tab": "기업",
"groups": [
{
"group": "시작 안내",
"pages": ["ko/enterprise/introduction"]
},
{
"group": "특징",
"pages": [
"ko/enterprise/features/tool-repository",
"ko/enterprise/features/webhook-streaming",
"ko/enterprise/features/traces",
"ko/enterprise/features/hallucination-guardrail",
"ko/enterprise/features/integrations",
"ko/enterprise/features/agent-repositories"
]
},
{
"group": "통합 문서",
"pages": [
"ko/enterprise/integrations/asana",
"ko/enterprise/integrations/box",
"ko/enterprise/integrations/clickup",
"ko/enterprise/integrations/github",
"ko/enterprise/integrations/gmail",
"ko/enterprise/integrations/google_calendar",
"ko/enterprise/integrations/google_sheets",
"ko/enterprise/integrations/hubspot",
"ko/enterprise/integrations/jira",
"ko/enterprise/integrations/linear",
"ko/enterprise/integrations/notion",
"ko/enterprise/integrations/salesforce",
"ko/enterprise/integrations/shopify",
"ko/enterprise/integrations/slack",
"ko/enterprise/integrations/stripe",
"ko/enterprise/integrations/zendesk"
]
},
{
"group": "사용 안내서",
"pages": [
"ko/enterprise/guides/build-crew",
"ko/enterprise/guides/deploy-crew",
"ko/enterprise/guides/kickoff-crew",
"ko/enterprise/guides/update-crew",
"ko/enterprise/guides/enable-crew-studio",
"ko/enterprise/guides/azure-openai-setup",
"ko/enterprise/guides/hubspot-trigger",
"ko/enterprise/guides/react-component-export",
"ko/enterprise/guides/salesforce-trigger",
"ko/enterprise/guides/slack-trigger",
"ko/enterprise/guides/team-management",
"ko/enterprise/guides/webhook-automation",
"ko/enterprise/guides/human-in-the-loop",
"ko/enterprise/guides/zapier-trigger"
]
},
{
"group": "학습 자원",
"pages": ["ko/enterprise/resources/frequently-asked-questions"]
}
]
},
{
"tab": "API 레퍼런스",
"groups": [
{
"group": "시작 안내",
"pages": ["ko/api-reference/introduction"]
},
{
"group": "Endpoints",
"openapi": "enterprise-api.yaml"
}
]
},
{
"tab": "예시",
"groups": [
{
"group": "예시",
"pages": ["ko/examples/example"]
}
]
}
]
}
]
},

View File

@@ -0,0 +1,119 @@
---
title: "소개"
description: "CrewAI Enterprise REST API에 대한 완벽한 참고 자료"
icon: "code"
---
# CrewAI 엔터프라이즈 API
CrewAI 엔터프라이즈 API 참고 자료에 오신 것을 환영합니다. 이 API를 사용하면 배포된 crew와 프로그래밍 방식으로 상호작용할 수 있어, 애플리케이션, 워크플로우 및 서비스와의 통합이 가능합니다.
## 빠른 시작
<Steps>
<Step title="API 자격 증명 받기">
CrewAI Enterprise 대시보드에서 자신의 crew 상세 페이지로 이동하여 Status 탭에서 Bearer Token을 복사하세요.
</Step>
<Step title="필수 입력값 확인하기">
`GET /inputs` 엔드포인트를 사용하여 crew가 기대하는 파라미터를 확인하세요.
</Step>
<Step title="Crew 실행 시작하기">
입력값과 함께 `POST /kickoff`를 호출하여 crew 실행을 시작하고 `kickoff_id`를 받으세요.
</Step>
<Step title="진행 상황 모니터링">
`GET /status/{kickoff_id}`를 사용하여 실행 상태를 확인하고 결과를 조회하세요.
</Step>
</Steps>
## 인증
모든 API 요청은 Bearer 토큰을 사용한 인증이 필요합니다. `Authorization` 헤더에 토큰을 포함하세요:
```bash
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" \
https://your-crew-url.crewai.com/inputs
```
### 토큰 유형
| 토큰 유형 | 범위 | 사용 사례 |
|:-----------|:--------|:----------|
| **Bearer Token** | 조직 단위 접근 | 전체 crew 운영, 서버 간 통합에 이상적 |
| **User Bearer Token** | 사용자 범위 접근 | 제한된 권한, 사용자별 작업에 적합 |
<Tip>
두 토큰 유형 모두 CrewAI Enterprise 대시보드의 crew 상세 페이지 Status 탭에서 확인할 수 있습니다.
</Tip>
## 기본 URL
각 배포된 crew마다 고유한 API 엔드포인트가 있습니다:
```
https://your-crew-name.crewai.com
```
`your-crew-name`을(를) 대시보드에서 확인할 수 있는 실제 crew의 URL로 교체하세요.
## 일반적인 워크플로우
1. **탐색**: `GET /inputs`를 호출하여 crew가 필요한 것을 파악합니다.
2. **실행**: `POST /kickoff`를 통해 입력값을 제출하여 처리를 시작합니다.
3. **모니터링**: 완료될 때까지 `GET /status/{kickoff_id}`를 주기적으로 조회합니다.
4. **결과**: 완료된 응답에서 최종 출력을 추출합니다.
## 오류 처리
API는 표준 HTTP 상태 코드를 사용합니다:
| 코드 | 의미 |
|------|:--------|
| `200` | 성공 |
| `400` | 잘못된 요청 - 잘못된 입력 형식 |
| `401` | 인증 실패 - 잘못된 베어러 토큰 |
| `404` | 찾을 수 없음 - 리소스가 존재하지 않음 |
| `422` | 유효성 검사 오류 - 필수 입력 누락 |
| `500` | 서버 오류 - 지원팀에 문의하십시오 |
## 인터랙티브 테스트
<Info>
**왜 "전송" 버튼이 없나요?** 각 CrewAI Enterprise 사용자는 고유한 crew URL을 가지므로, 혼동을 피하기 위해 인터랙티브 플레이그라운드 대신 **참조 모드**를 사용합니다. 이를 통해 비작동 전송 버튼 없이 요청이 어떻게 생겼는지 정확히 보여줍니다.
</Info>
각 엔드포인트 페이지에서는 다음을 확인할 수 있습니다:
- ✅ 모든 파라미터가 포함된 **정확한 요청 형식**
- ✅ 성공 및 오류 사례에 대한 **응답 예시**
- ✅ 여러 언어(cURL, Python, JavaScript 등)로 제공되는 **코드 샘플**
- ✅ 올바른 Bearer 토큰 형식의 **인증 예시**
### **실제 API를 테스트하려면:**
<CardGroup cols={2}>
<Card title="cURL 예제 복사" icon="terminal">
cURL 예제를 복사한 후, URL과 토큰을 실제 값으로 교체하세요
</Card>
<Card title="Postman/Insomnia 사용" icon="play">
예제를 원하는 API 테스트 도구에 가져오세요
</Card>
</CardGroup>
**예시 작업 흐름:**
1. **cURL 예제를 복사**합니다 (엔드포인트 페이지에서)
2. **`your-actual-crew-name.crewai.com`**을(를) 실제 crew URL로 교체합니다
3. **Bearer 토큰을** 대시보드에서 복사한 실제 토큰으로 교체합니다
4. **요청을 실행**합니다 (터미널이나 API 클라이언트에서)
## 도움이 필요하신가요?
<CardGroup cols={2}>
<Card title="Enterprise Support" icon="headset" href="mailto:support@crewai.com">
API 통합 및 문제 해결에 대한 지원을 받으세요
</Card>
<Card title="Enterprise Dashboard" icon="chart-line" href="https://app.crewai.com">
crew를 관리하고 실행 로그를 확인하세요
</Card>
</CardGroup>

690
docs/ko/concepts/agents.mdx Normal file
View File

@@ -0,0 +1,690 @@
---
title: 에이전트
description: CrewAI 프레임워크 내에서 에이전트를 생성하고 관리하는 자세한 가이드입니다.
icon: robot
---
## 에이전트 개요
CrewAI 프레임워크에서 `Agent`는 다음과 같은 역할을 수행하는 자율적 단위입니다:
- 특정 작업 수행
- 자신의 역할과 목표에 기반한 의사결정
- 도구를 활용하여 목표 달성
- 다른 에이전트와의 소통 및 협업
- 상호작용에 대한 기억 유지
- 허용될 경우 작업 위임
<Tip>
에이전트는 특정한 기술, 전문성, 책임을 가진 전문 팀원이라고 생각하시면 됩니다. 예를 들어, `Researcher` 에이전트는 정보 수집 및 분석에 뛰어날 수 있고, `Writer` 에이전트는 콘텐츠 작성에 더 강점을 가질 수 있습니다.
</Tip>
<Note type="info" title="엔터프라이즈 확장: 시각적 에이전트 빌더">
CrewAI Enterprise에는 코드를 작성하지 않고도 에이전트 생성 및 구성을 간편하게 할 수 있는 시각적 에이전트 빌더가 포함되어 있습니다. 에이전트를 시각적으로 설계하고 실시간으로 테스트하세요.
![Visual Agent Builder Screenshot](/images/enterprise/crew-studio-interface.png)
시각적 에이전트 빌더를 통해 다음과 같은 기능을 사용할 수 있습니다:
- 폼 기반 인터페이스를 통한 직관적 에이전트 구성
- 실시간 테스트 및 검증
- 사전 구성된 에이전트 유형 템플릿 라이브러리
- 에이전트 속성 및 행동의 손쉬운 커스터마이즈
</Note>
## 에이전트 속성
| 속성 | 파라미터 | 타입 | 설명 |
| :-------------------------------------- | :----------------------- | :---------------------------- | :----------------------------------------------------------------------------------------------------------------- |
| **역할** | `role` | `str` | 에이전트의 기능과 전문 분야를 정의합니다. |
| **목표** | `goal` | `str` | 에이전트의 의사결정을 이끄는 개별 목표입니다. |
| **배경 이야기** | `backstory` | `str` | 에이전트에게 맥락과 개성을 부여하여 상호작용을 풍부하게 합니다. |
| **LLM** _(옵션)_ | `llm` | `Union[str, LLM, Any]` | 에이전트를 구동하는 언어 모델입니다. `OPENAI_MODEL_NAME`에 지정된 모델 또는 "gpt-4"가 기본값입니다. |
| **도구** _(옵션)_ | `tools` | `List[BaseTool]` | 에이전트가 사용할 수 있는 기능 혹은 역량입니다. 기본값은 빈 리스트입니다. |
| **Function Calling LLM** _(옵션)_ | `function_calling_llm` | `Optional[Any]` | 도구 호출을 위한 언어 모델로, 지정 시 crew의 LLM을 재정의합니다. |
| **최대 반복 횟수** _(옵션)_ | `max_iter` | `int` | 에이전트가 최선의 답변을 제공하기 전 최대 반복 수입니다. 기본값은 20입니다. |
| **최대 RPM** _(옵션)_ | `max_rpm` | `Optional[int]` | 레이트 리밋 회피를 위한 분당 최대 요청 수입니다. |
| **최대 실행 시간** _(옵션)_ | `max_execution_time` | `Optional[int]` | 작업 실행의 최대 시간(초)입니다. |
| **상세 로그** _(옵션)_ | `verbose` | `bool` | 디버깅을 위한 상세 실행 로그를 활성화합니다. 기본값은 False입니다. |
| **위임 허용** _(옵션)_ | `allow_delegation` | `bool` | 에이전트가 다른 에이전트에게 작업을 위임할 수 있도록 허용합니다. 기본값은 False입니다. |
| **Step Callback** _(옵션)_ | `step_callback` | `Optional[Any]` | 각 에이전트 단계 후 호출되는 함수로, crew 콜백을 재정의합니다. |
| **캐시** _(옵션)_ | `cache` | `bool` | 도구 사용에 대해 캐싱을 활성화합니다. 기본값은 True입니다. |
| **시스템 템플릿** _(옵션)_ | `system_template` | `Optional[str]` | 에이전트 맞춤형 시스템 프롬프트 템플릿입니다. |
| **프롬프트 템플릿** _(옵션)_ | `prompt_template` | `Optional[str]` | 에이전트 맞춤형 프롬프트 템플릿입니다. |
| **응답 템플릿** _(옵션)_ | `response_template` | `Optional[str]` | 에이전트 맞춤형 응답 템플릿입니다. |
| **코드 실행 허용** _(옵션)_ | `allow_code_execution` | `Optional[bool]` | 에이전트의 코드 실행 활성화 여부입니다. 기본값은 False입니다. |
| **최대 재시도 횟수** _(옵션)_ | `max_retry_limit` | `int` | 오류 발생 시 최대 재시도 횟수입니다. 기본값은 2입니다. |
| **컨텍스트 윈도우 준수** _(옵션)_ | `respect_context_window` | `bool` | 메시지를 컨텍스트 윈도우 크기 내로 유지하기 위하여 요약 기능을 사용합니다. 기본값은 True입니다. |
| **코드 실행 모드** _(옵션)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | 코드 실행 모드: 'safe'(Docker 사용) 또는 'unsafe'(직접 실행). 기본값은 'safe'입니다. |
| **멀티모달** _(옵션)_ | `multimodal` | `bool` | 에이전트가 멀티모달 기능을 지원하는지 여부입니다. 기본값은 False입니다. |
| **날짜 자동 삽입** _(옵션)_ | `inject_date` | `bool` | 작업에 현재 날짜를 자동으로 삽입할지 여부입니다. 기본값은 False입니다. |
| **날짜 형식** _(옵션)_ | `date_format` | `str` | inject_date 활성화 시 날짜 표시 형식 문자열입니다. 기본값은 "%Y-%m-%d"(ISO 포맷)입니다. |
| **추론** _(옵션)_ | `reasoning` | `bool` | 에이전트가 작업을 실행하기 전에 반영 및 플랜을 생성할지 여부입니다. 기본값은 False입니다. |
| **최대 추론 시도 수** _(옵션)_ | `max_reasoning_attempts` | `Optional[int]` | 작업 실행 전 최대 추론 시도 횟수입니다. 설정하지 않으면 준비될 때까지 시도합니다. |
| **임베더** _(옵션)_ | `embedder` | `Optional[Dict[str, Any]]` | 에이전트가 사용하는 임베더 설정입니다. |
| **지식 소스** _(옵션)_ | `knowledge_sources` | `Optional[List[BaseKnowledgeSource]]` | 에이전트가 사용할 수 있는 지식 소스입니다. |
| **시스템 프롬프트 사용** _(옵션)_ | `use_system_prompt` | `Optional[bool]` | 시스템 프롬프트 사용 여부(o1 모델 지원용). 기본값은 True입니다. |
## 에이전트 생성
CrewAI에서 에이전트를 생성하는 방법에는 **YAML 구성(권장)**을 사용하는 방법과 **코드에서 직접 정의**하는 두 가지가 있습니다.
### YAML 구성 (권장)
YAML 구성을 사용하면 에이전트를 보다 깔끔하고 유지 관리하기 쉽도록 정의할 수 있습니다. CrewAI 프로젝트에서 이 방식을 사용하는 것을 강력히 권장합니다.
[설치](/ko/installation) 섹션에 설명된 대로 CrewAI 프로젝트를 생성한 후, `src/latest_ai_development/config/agents.yaml` 파일로 이동하여 템플릿을 여러분의 요구 사항에 맞게 수정하세요.
<Note>
YAML 파일의 변수(예: `{topic}`)는 crew를 실행할 때 입력값에서 가져온 값으로 대체됩니다:
```python Code
crew.kickoff(inputs={'topic': 'AI Agents'})
```
</Note>
아래는 YAML을 사용하여 에이전트를 구성하는 예시입니다:
```yaml agents.yaml
# 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.
```
이 YAML 구성을 코드에서 사용하려면, `CrewBase`를 상속하는 crew 클래스를 생성하세요:
```python Code
# 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
)
```
<Note>
YAML 파일(`agents.yaml`)에서 사용하는 이름은 파이썬 코드의 메서드 이름과 일치해야 합니다.
</Note>
### 직접 코드 정의
`Agent` 클래스를 인스턴스화하여 코드에서 직접 agent를 생성할 수 있습니다. 아래는 사용 가능한 모든 파라미터를 보여주는 종합적인 예제입니다:
```python Code
from crewai import Agent
from crewai_tools import SerperDevTool
# 사용 가능한 모든 파라미터로 agent 생성
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", # 기본값: OPENAI_MODEL_NAME 또는 "gpt-4"
function_calling_llm=None, # 옵션: 도구 호출을 위한 별도의 LLM
verbose=False, # 기본값: False
allow_delegation=False, # 기본값: False
max_iter=20, # 기본값: 20번 반복
max_rpm=None, # 옵션: API 호출에 대한 속도 제한
max_execution_time=None, # 옵션: 최대 실행 시간(초 단위)
max_retry_limit=2, # 기본값: 오류 시 2번 재시도
allow_code_execution=False, # 기본값: False
code_execution_mode="safe", # 기본값: "safe" (옵션: "safe", "unsafe")
respect_context_window=True, # 기본값: True
use_system_prompt=True, # 기본값: True
multimodal=False, # 기본값: False
inject_date=False, # 기본값: False
date_format="%Y-%m-%d", # 기본값: ISO 형식
reasoning=False, # 기본값: False
max_reasoning_attempts=None, # 기본값: None
tools=[SerperDevTool()], # 옵션: 도구 리스트
knowledge_sources=None, # 옵션: 지식 소스 리스트
embedder=None, # 옵션: 커스텀 임베더 구성
system_template=None, # 옵션: 커스텀 시스템 프롬프트 템플릿
prompt_template=None, # 옵션: 커스텀 프롬프트 템플릿
response_template=None, # 옵션: 커스텀 응답 템플릿
step_callback=None, # 옵션: 모니터링용 콜백 함수
)
```
일반적인 사용 사례를 위한 주요 파라미터 조합을 살펴보겠습니다:
#### 기본 연구 에이전트
```python Code
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
)
```
#### 코드 개발 에이전트
```python Code
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
)
```
#### 장기 실행 분석 에이전트
```python Code
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
)
```
#### 커스텀 템플릿 에이전트
```python Code
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|>""",
)
```
#### 날짜 인식이 가능한 Reasoning Agent
```python Code
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
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
)
```
#### 멀티모달 에이전트
```python Code
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
)
```
### 매개변수 세부 정보
#### 중요 파라미터
- `role`, `goal`, 그리고 `backstory`는 필수이며 에이전트의 행동을 결정합니다
- `llm`은 사용되는 언어 모델을 결정합니다 (기본값: OpenAI의 GPT-4)
#### 메모리 및 컨텍스트
- `memory`: 대화 이력을 유지하도록 활성화합니다
- `respect_context_window`: 토큰 제한 문제를 방지합니다
- `knowledge_sources`: 도메인별 지식 기반을 추가합니다
#### 실행 제어
- `max_iter`: 최적의 답변을 제공하기 전의 최대 시도 횟수
- `max_execution_time`: 제한 시간(초 단위)
- `max_rpm`: API 호출 속도 제한
- `max_retry_limit`: 오류 발생 시 재시도 횟수
#### 코드 실행
- `allow_code_execution`: 코드를 실행하려면 True여야 합니다
- `code_execution_mode`:
- `"safe"`: Docker를 사용합니다 (프로덕션에 권장)
- `"unsafe"`: 직접 실행 (신뢰할 수 있는 환경에서만 사용)
<Note>
이 옵션은 기본 Docker 이미지를 실행합니다. Docker 이미지를 구성하려면 도구 섹션에 있는 Code Interpreter Tool을 확인하십시오.
Code Interpreter Tool을 에이전트의 도구 파라미터로 추가하십시오.
</Note>
#### 고급 기능
- `multimodal`: 텍스트와 시각적 콘텐츠 처리를 위한 멀티모달 기능 활성화
- `reasoning`: 에이전트가 작업을 수행하기 전에 반영하고 계획을 작성할 수 있도록 활성화
- `inject_date`: 현재 날짜를 작업 설명에 자동으로 삽입
#### 템플릿
- `system_template`: 에이전트의 핵심 동작을 정의합니다
- `prompt_template`: 입력 형식을 구성합니다
- `response_template`: 에이전트 응답을 포맷합니다
<Note>
커스텀 템플릿을 사용할 때는 `system_template`과 `prompt_template`가 모두 정의되어 있는지 확인하십시오. `response_template`은 선택 사항이지만 일관된 출력 포맷을 위해 권장됩니다.
</Note>
<Note>
커스텀 템플릿을 사용할 때는 템플릿에서 `{role}`, `{goal}`, `{backstory}`와 같은 변수를 사용할 수 있습니다. 이 변수들은 실행 중에 자동으로 채워집니다.
</Note>
## 에이전트 도구
에이전트는 다양한 도구를 장착하여 그 능력을 향상시킬 수 있습니다. CrewAI는 다음의 도구들을 지원합니다:
- [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools)
- [LangChain Tools](https://python.langchain.com/docs/integrations/tools)
에이전트에 도구를 추가하는 방법은 다음과 같습니다:
```python Code
from crewai import Agent
from crewai_tools import SerperDevTool, WikipediaTools
# 도구 생성
search_tool = SerperDevTool()
wiki_tool = WikipediaTools()
# 에이전트에 도구 추가
researcher = Agent(
role="AI Technology Researcher",
goal="Research the latest AI developments",
tools=[search_tool, wiki_tool],
verbose=True
)
```
## 에이전트 메모리와 컨텍스트
에이전트는 상호작용의 메모리를 유지하고 이전 작업의 컨텍스트를 사용할 수 있습니다. 이는 여러 작업에 걸쳐 정보를 유지해야 하는 복잡한 워크플로우에서 특히 유용합니다.
```python Code
from crewai import Agent
analyst = Agent(
role="Data Analyst",
goal="Analyze and remember complex data patterns",
memory=True, # Enable memory
verbose=True
)
```
<Note>
`memory`가 활성화되면 에이전트는 여러 상호작용에 걸쳐 컨텍스트를 유지하게 되어, 복잡하고 여러 단계로 이루어진 작업을 처리하는 능력이 향상됩니다.
</Note>
## 컨텍스트 윈도우 관리
CrewAI는 대화가 언어 모델의 토큰 한도를 초과하는 상황을 처리하기 위해 정교한 자동 컨텍스트 윈도우 관리 기능을 포함하고 있습니다. 이 강력한 기능은 `respect_context_window` 매개변수로 제어됩니다.
### 컨텍스트 윈도우 관리 방식
에이전트의 대화 기록이 LLM의 컨텍스트 윈도우 크기를 초과할 경우, CrewAI는 이 상황을 자동으로 감지하고 다음 중 하나를 수행할 수 있습니다:
1. **자동으로 내용을 요약** ( `respect_context_window=True` 인 경우)
2. **오류와 함께 실행 중지** ( `respect_context_window=False` 인 경우)
### 자동 컨텍스트 처리 (`respect_context_window=True`)
이 설정은 대부분의 사용 사례에서 **기본값이자 권장 옵션**입니다. 활성화되면 CrewAI는 다음과 같이 동작합니다:
```python Code
# 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
)
```
**컨텍스트 한도를 초과할 경우 발생하는 일:**
- ⚠️ **경고 메시지**: `"Context length exceeded. Summarizing content to fit the model context window."`
- 🔄 **자동 요약**: CrewAI가 대화 기록을 지능적으로 요약함
- ✅ **작업 지속**: 요약된 컨텍스트로 작업이 원활하게 계속됨
- 📝 **정보 보존**: 토큰 수를 줄이면서도 주요 정보는 유지됨
### 엄격한 컨텍스트 제한(`respect_context_window=False`)
정확한 제어가 필요하며, 정보를 잃지 않으려면 실행이 중지되도록 할 때:
```python Code
# 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
)
```
**컨텍스트 한도를 초과하면 발생하는 일:**
- ❌ **오류 메시지**: `"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."`
- 🛑 **실행 중지**: 작업 실행이 즉시 중단됨
- 🔧 **수동 개입 필요**: 접근 방식을 직접 수정해야 함
### 올바른 설정 선택
#### 다음과 같은 경우 `respect_context_window=True` (기본값)을 사용하세요:
- **문서가 클 경우** 컨텍스트 제한을 초과할 수 있습니다
- **오래 지속되는 대화**에서 일부 요약이 허용되는 경우
- **연구 과제**에서 정확한 세부사항보다는 전체적인 컨텍스트가 더 중요한 경우
- **프로토타이핑 및 개발**에서 견고한 실행을 원하는 경우
```python Code
# 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
)
```
#### `respect_context_window=False`를 사용할 때:
- **정확성이 매우 중요**하고 정보 손실이 허용되지 않을 때
- **법률 또는 의료 업무**에서 전체 맥락이 필요한 경우
- **코드 리뷰**에서 누락된 세부 정보가 버그를 유발할 수 있는 경우
- **금융 분석**에서 정확도가 최우선인 경우
```python Code
# 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
)
```
### 대용량 데이터에 대한 대체 접근 방식
매우 큰 데이터셋을 다룰 때는 다음과 같은 전략을 고려하세요:
#### 1. RAG 도구 사용하기
```python Code
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. 지식 소스 사용
```python Code
# 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
)
```
### 컨텍스트 윈도우 모범 사례
1. **컨텍스트 사용 모니터링**: `verbose=True`를 활성화하여 컨텍스트 관리 과정을 확인하세요
2. **효율성 설계**: 작업 구조를 효과적으로 설계하여 컨텍스트 누적을 최소화하세요
3. **적절한 모델 사용**: 작업에 적합한 컨텍스트 윈도우를 가진 LLM을 선택하세요
4. **두 가지 설정 모두 테스트**: `True`와 `False` 모두 시도하여 어떤 것이 더 효과적인지 확인하세요
5. **RAG와 조합 사용**: 매우 큰 데이터셋의 경우 컨텍스트 윈도우에만 의존하지 말고 RAG 도구도 함께 사용하세요
### 컨텍스트 문제 해결
**컨텍스트 제한 오류가 발생하는 경우:**
```python Code
# 빠른 해결책: 자동 처리 활성화
agent.respect_context_window = True
# 더 나은 솔루션: 대용량 데이터에는 RAG 도구 사용
from crewai_tools import RagTool
agent.tools = [RagTool()]
# 대안: 작업을 더 작은 단위로 나누기
# 또는 대용량 프롬프트 대신 knowledge 소스 사용
```
**자동 요약 기능이 중요한 정보를 놓치는 경우:**
```python Code
# 자동 요약 비활성화 후 RAG 사용
agent = Agent(
role="Detailed Analyst",
goal="Maintain complete information accuracy",
backstory="Expert requiring full context",
respect_context_window=False, # 요약 안 함
tools=[RagTool()], # 대용량 데이터에는 RAG 사용
verbose=True
)
```
<Note>
컨텍스트 윈도우 관리 기능은 백그라운드에서 자동으로 작동합니다. 특별한 함수를 호출할 필요가 없으며, 원하는 동작에 맞게 `respect_context_window`만 설정하면 CrewAI가 나머지를 처리합니다!
</Note>
## `kickoff()`을 사용한 에이전트 직접 상호작용
에이전트는 `kickoff()` 메서드를 사용하여 작업(task)이나 crew 워크플로우를 거치지 않고 직접 사용할 수 있습니다. 이는 전체 crew 오케스트레이션 기능이 필요하지 않을 때 에이전트와 상호작용하는 더 간단한 방법을 제공합니다.
### `kickoff()` 작동 방식
`kickoff()` 메서드는 메시지를 에이전트에게 직접 보내고 응답을 받을 수 있게 해줍니다. 이는 LLM과 상호 작용하는 것과 유사하지만, 에이전트의 모든 기능(도구, 추론 등)을 활용할 수 있다는 점이 다릅니다.
```python Code
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)
```
### 매개변수 및 반환 값
| 매개변수 | 타입 | 설명 |
| :---------------- | :---------------------------------- | :------------------------------------------------------------------------ |
| `messages` | `Union[str, List[Dict[str, str]]]` | 문자열 쿼리 또는 역할/내용이 포함된 메시지 딕셔너리의 리스트 |
| `response_format` | `Optional[Type[Any]]` | 구조화된 출력을 위한 선택적 Pydantic 모델 |
이 메서드는 다음과 같은 속성을 가진 `LiteAgentOutput` 객체를 반환합니다:
- `raw`: 원시 출력 텍스트를 포함하는 문자열
- `pydantic`: 파싱된 Pydantic 모델 (`response_format`이 제공된 경우)
- `agent_role`: 출력을 생성한 agent의 역할
- `usage_metrics`: 실행에 대한 토큰 사용 지표
### 구조화된 출력
`response_format`으로 Pydantic 모델을 제공하여 구조화된 출력을 받을 수 있습니다:
```python Code
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)
```
### 여러 개의 메시지
대화 기록을 메시지 딕셔너리의 목록으로 제공할 수도 있습니다:
```python Code
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)
```
### 비동기 지원
동일한 매개변수를 사용하는 비동기 버전은 `kickoff_async()`를 통해 사용할 수 있습니다:
```python Code
import asyncio
async def main():
result = await researcher.kickoff_async("What are the latest developments in AI?")
print(result.raw)
asyncio.run(main())
```
<Note>
`kickoff()` 메서드는 내부적으로 `LiteAgent`를 사용하며, 모든 agent 설정(역할, 목표, 백스토리, 도구 등)을 유지하면서도 더 간단한 실행 흐름을 제공합니다.
</Note>
## 중요한 고려사항 및 모범 사례
### 보안 및 코드 실행
- `allow_code_execution`을 사용할 때는 사용자 입력에 주의하고 항상 입력 값을 검증하세요
- 운영 환경에서는 `code_execution_mode: "safe"`(Docker)를 사용하세요
- 무한 루프를 방지하기 위해 적절한 `max_execution_time` 제한을 설정하는 것을 고려하세요
### 성능 최적화
- `respect_context_window: true`를 사용하여 토큰 제한 문제를 방지하세요.
- 적절한 `max_rpm`을 설정하여 속도 제한을 피하세요.
- 반복적인 작업의 성능 향상을 위해 `cache: true`를 활성화하세요.
- 작업의 복잡도에 따라 `max_iter`와 `max_retry_limit`을 조정하세요.
### 메모리 및 컨텍스트 관리
- 도메인별 정보를 위해 `knowledge_sources`를 활용하세요
- 커스텀 임베딩 모델을 사용할 때는 `embedder`를 구성하세요
- 에이전트 행동을 세밀하게 제어하려면 커스텀 템플릿(`system_template`, `prompt_template`, `response_template`)을 사용하세요
### 고급 기능
- 복잡한 작업을 실행하기 전에 계획을 세우고 반성해야 하는 에이전트의 경우 `reasoning: true`를 활성화하세요.
- 계획 반복 횟수를 제어하려면 적절한 `max_reasoning_attempts` 값을 설정하세요 (무제한 시 None 사용).
- 시간에 민감한 작업을 위해 에이전트가 현재 날짜를 인식할 수 있도록 `inject_date: true`를 사용하세요.
- 표준 Python datetime 형식 코드를 사용하여 `date_format`으로 날짜 형식을 맞춤 설정할 수 있습니다.
- 텍스트와 시각적 콘텐츠를 모두 처리해야 하는 에이전트의 경우 `multimodal: true`를 활성화하세요.
### 에이전트 협업
- 에이전트들이 함께 작업해야 할 때 `allow_delegation: true`를 활성화하세요
- 에이전트 상호작용을 모니터링하고 기록하려면 `step_callback`을 사용하세요
- 다양한 목적에 따라 서로 다른 LLM을 사용하는 것을 고려하세요:
- 복잡한 추론에는 메인 `llm`
- 효율적인 도구 사용에는 `function_calling_llm`
### 날짜 인식 및 추론
- 시간에 민감한 작업을 위해 `inject_date: true`를 사용하여 에이전트에게 현재 날짜 인식 기능을 제공합니다.
- 표준 Python datetime 형식 코드를 사용하는 `date_format`으로 날짜 형식을 사용자 정의할 수 있습니다.
- 유효한 형식 코드는 다음과 같습니다: %Y (연도), %m (월), %d (일), %B (전체 월 이름) 등.
- 잘못된 날짜 형식은 경고로 기록되며, 작업 설명을 수정하지 않습니다.
- 사전 계획 및 성찰이 필요한 복잡한 작업의 경우 `reasoning: true`를 활성화하세요.
### 모델 호환성
- 시스템 메시지를 지원하지 않는 이전 모델의 경우 `use_system_prompt: false`로 설정하세요
- 선택한 `llm`이(가) 필요한 기능(예: 함수 호출)을 지원하는지 확인하세요
## 일반적인 문제 해결
1. **Rate Limiting(속도 제한)**: API 속도 제한에 도달하는 경우:
- 적절한 `max_rpm` 구현
- 반복적인 작업에 캐싱 사용
- 요청을 일괄 처리(batch)하는 것 고려
2. **Context Window Errors(컨텍스트 윈도우 오류)**: 컨텍스트 한계를 초과하는 경우:
- `respect_context_window` 활성화
- 더 효율적인 프롬프트 사용
- 주기적으로 에이전트 메모리 정리
3. **Code Execution Issues(코드 실행 문제)**: 코드 실행이 실패하는 경우:
- 안전 모드를 위해 Docker 설치 여부 확인
- 실행 권한 확인
- 코드 샌드박스 설정 검토
4. **Memory Issues(메모리 문제)**: 에이전트 응답이 일관되지 않은 경우:
- knowledge 소스 구성 확인
- 대화 기록 관리 검토
에이전트는 특정 사용 사례에 맞게 구성될 때 가장 효과적입니다. 자신의 요구 사항을 이해하고 이에 맞게 이러한 매개변수를 조정하는 데 시간을 투자하세요.

390
docs/ko/concepts/cli.mdx Normal file
View File

@@ -0,0 +1,390 @@
---
title: CLI
description: CrewAI CLI를 사용하여 CrewAI와 상호 작용하는 방법을 알아보세요.
icon: terminal
---
<Warning>릴리즈 0.140.0부터 CrewAI Enterprise는 로그인 제공자 마이그레이션 프로세스를 시작했습니다. 이에 따라 CLI를 통한 인증 흐름이 업데이트되었습니다. Google을 통해 로그인하거나 2025년 7월 3일 이후에 계정을 생성한 사용자는 이전 버전의 `crewai` 라이브러리로는 로그인할 수 없습니다.</Warning>
## 개요
CrewAI CLI는 CrewAI와 상호작용할 수 있는 명령어 세트를 제공하여 crew 및 flow를 생성, 학습, 실행, 관리할 수 있습니다.
## 설치
CrewAI CLI를 사용하려면, CrewAI가 설치되어 있어야 합니다:
```shell Terminal
pip install crewai
```
## 기본 사용법
CrewAI CLI 명령어의 기본 구조는 다음과 같습니다:
```shell Terminal
crewai [COMMAND] [OPTIONS] [ARGUMENTS]
```
## 사용 가능한 명령어
### 1. 생성
새로운 crew 또는 flow를 생성합니다.
```shell Terminal
crewai create [OPTIONS] TYPE NAME
```
- `TYPE`: "crew" 또는 "flow" 중에서 선택
- `NAME`: crew 또는 flow의 이름
예시:
```shell Terminal
crewai create crew my_new_crew
crewai create flow my_new_flow
```
### 2. 버전
설치된 CrewAI의 버전을 표시합니다.
```shell Terminal
crewai version [OPTIONS]
```
- `--tools`: (선택 사항) 설치된 CrewAI tools의 버전을 표시합니다.
예시:
```shell Terminal
crewai version
crewai version --tools
```
### 3. 훈련
지정된 횟수만큼 crew를 훈련시킵니다.
```shell Terminal
crewai train [OPTIONS]
```
- `-n, --n_iterations INTEGER`: crew를 훈련할 반복 횟수 (기본값: 5)
- `-f, --filename TEXT`: 훈련에 사용할 커스텀 파일의 경로 (기본값: "trained_agents_data.pkl")
예시:
```shell Terminal
crewai train -n 10 -f my_training_data.pkl
```
### 4. 다시 실행
특정 task에서 crew 실행을 다시 재생합니다.
```shell Terminal
crewai replay [OPTIONS]
```
- `-t, --task_id TEXT`: 이 task ID에서부터 crew를 다시 재생하며, 이후의 모든 task를 포함합니다.
예시:
```shell Terminal
crewai replay -t task_123456
```
### 5. Log-tasks-outputs
가장 최근의 crew.kickoff() 작업 결과를 조회합니다.
```shell Terminal
crewai log-tasks-outputs
```
### 6. Reset-memories
크루의 메모리(롱, 쇼트, 엔티티, latest_crew_kickoff_outputs)를 초기화합니다.
```shell Terminal
crewai reset-memories [OPTIONS]
```
- `-l, --long`: LONG TERM 메모리 초기화
- `-s, --short`: SHORT TERM 메모리 초기화
- `-e, --entities`: ENTITIES 메모리 초기화
- `-k, --kickoff-outputs`: LATEST KICKOFF TASK OUTPUTS 초기화
- `-kn, --knowledge`: KNOWLEDGE 저장소 초기화
- `-akn, --agent-knowledge`: AGENT KNOWLEDGE 저장소 초기화
- `-a, --all`: 모든 메모리 초기화
예시:
```shell Terminal
crewai reset-memories --long --short
crewai reset-memories --all
```
### 7. 테스트
crew를 테스트하고 결과를 평가합니다.
```shell Terminal
crewai test [OPTIONS]
```
- `-n, --n_iterations INTEGER`: crew를 테스트할 반복 횟수 (기본값: 3)
- `-m, --model TEXT`: Crew에서 테스트를 실행할 LLM 모델 (기본값: "gpt-4o-mini")
예시:
```shell Terminal
crewai test -n 5 -m gpt-3.5-turbo
```
### 8. 실행
crew 또는 flow를 실행합니다.
```shell Terminal
crewai run
```
<Note>
버전 0.103.0부터 `crewai run` 명령은 표준 crew와 flow 모두를 실행하는 데 사용할 수 있습니다. flow의 경우 pyproject.toml에서 유형을 자동으로 감지하여 적절한 명령을 실행합니다. 이제 crew와 flow 모두를 실행하는 권장 방법입니다.
</Note>
<Note>
이 명령들은 CrewAI 프로젝트가 설정된 디렉터리에서 실행해야 합니다.
일부 명령은 프로젝트 구조 내에서 추가 구성 또는 설정이 필요할 수 있습니다.
</Note>
### 9. Chat
버전 `0.98.0`부터 `crewai chat` 명령어를 실행하면 크루와의 대화형 세션이 시작됩니다. AI 어시스턴트가 크루를 실행하는 데 필요한 입력값을 요청하며 안내합니다. 모든 입력값이 제공되면 크루가 작업을 실행합니다.
결과를 받은 후에도 추가 지시나 질문을 위해 어시스턴트와 계속 상호작용할 수 있습니다.
```shell Terminal
crewai chat
```
<Note>
이 명령어들은 CrewAI 프로젝트의 루트 디렉터리에서 실행해야 합니다.
</Note>
<Note>
중요: 이 명령어를 사용하려면 `crew.py` 파일에서 `chat_llm` 속성을 설정해야 합니다.
```python
@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
)
```
</Note>
### 10. 배포
crew 또는 flow를 [CrewAI Enterprise](https://app.crewai.com)에 배포하세요.
- **인증**: CrewAI Enterprise에 배포하려면 인증이 필요합니다.
아래 명령어로 로그인하거나 계정을 생성할 수 있습니다:
```shell Terminal
crewai login
```
- **배포 생성**: 인증이 완료되면, 로컬 프로젝트의 루트에서 crew 또는 flow에 대한 배포를 생성할 수 있습니다.
```shell Terminal
crewai deploy create
```
- 로컬 프로젝트 구성을 읽어옵니다.
- 로컬에서 확인된 환경 변수(`OPENAI_API_KEY`, `SERPER_API_KEY` 등)를 확인하도록 안내합니다. 이 변수들은 Enterprise 플랫폼에 배포할 때 안전하게 저장됩니다. 실행 전에 중요한 키가 로컬(예: `.env` 파일)에 올바르게 구성되어 있는지 확인하세요.
### 11. 조직 관리
CrewAI Enterprise 조직을 관리합니다.
```shell Terminal
crewai org [COMMAND] [OPTIONS]
```
#### 명령어:
- `list`: 사용자가 속한 모든 조직을 나열합니다.
```shell Terminal
crewai org list
```
- `current`: 현재 활성화된 조직을 표시합니다.
```shell Terminal
crewai org current
```
- `switch`: 특정 조직으로 전환합니다.
```shell Terminal
crewai org switch <organization_id>
```
<Note>
이러한 조직 관리 명령어를 사용하려면 CrewAI Enterprise에 인증되어 있어야 합니다.
</Note>
- **배포 생성** (계속):
- 배포를 해당 원격 GitHub 저장소에 연결합니다 (일반적으로 자동으로 감지됩니다).
- **Crew 배포**: 인증이 완료되면 crew 또는 flow를 CrewAI Enterprise에 배포할 수 있습니다.
```shell Terminal
crewai deploy push
```
- CrewAI Enterprise 플랫폼에서 배포 프로세스를 시작합니다.
- 성공적으로 시작되면, Deployment created successfully! 메시지와 함께 Deployment Name 및 고유한 Deployment ID(UUID)가 출력됩니다.
- **배포 상태**: 배포 상태를 확인하려면 다음을 사용합니다:
```shell Terminal
crewai deploy status
```
이 명령은 가장 최근의 배포 시도에 대한 최신 배포 상태(예: `Building Images for Crew`, `Deploy Enqueued`, `Online`)를 가져옵니다.
- **배포 로그**: 배포 로그를 확인하려면 다음을 사용합니다:
```shell Terminal
crewai deploy logs
```
이 명령은 배포 로그를 터미널로 스트리밍합니다.
- **배포 목록**: 모든 배포를 나열하려면 다음을 사용합니다:
```shell Terminal
crewai deploy list
```
이 명령은 모든 배포를 나열합니다.
- **배포 삭제**: 배포를 삭제하려면 다음을 사용합니다:
```shell Terminal
crewai deploy remove
```
이 명령은 CrewAI Enterprise 플랫폼에서 배포를 삭제합니다.
- **도움말 명령어**: CLI에 대한 도움말을 보려면 다음을 사용합니다:
```shell Terminal
crewai deploy --help
```
이 명령은 CrewAI Deploy CLI에 대한 도움말 메시지를 표시합니다.
CLI를 사용하여 [CrewAI Enterprise](http://app.crewai.com)에 crew를 배포하는 단계별 시연은 아래 비디오 튜토리얼을 참조하십시오.
<iframe
width="100%"
height="400"
src="https://www.youtube.com/embed/3EqSV-CYDZA"
title="CrewAI Deployment Guide"
frameborder="0"
style={{ borderRadius: '10px' }}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
### 11. API 키
```crewai create crew``` 명령어를 실행하면, CLI에서 선택할 수 있는 LLM 제공업체 목록이 표시되고, 그 다음으로 선택한 제공업체에 대한 모델 선택이 이어집니다.
LLM 제공업체와 모델을 선택하면, API 키를 입력하라는 메시지가 표시됩니다.
#### 사용 가능한 LLM 공급자
다음은 CLI에서 제안하는 가장 인기 있는 LLM 공급자 목록입니다:
* OpenAI
* Groq
* Anthropic
* Google Gemini
* SambaNova
공급자를 선택하면, CLI가 해당 공급자에서 사용 가능한 모델을 보여주고 API 키 입력을 요청합니다.
#### 기타 옵션
"기타"를 선택하면 LiteLLM에서 지원하는 공급자 목록에서 선택할 수 있습니다.
공급자를 선택하면 CLI에서 Key 이름과 API 키 입력을 요청합니다.
각 공급자의 Key 이름은 다음 링크에서 확인할 수 있습니다:
* [LiteLLM 공급자](https://docs.litellm.ai/docs/providers)
### 12. 구성 관리
CrewAI의 CLI 구성 설정을 관리합니다.
```shell Terminal
crewai config [COMMAND] [OPTIONS]
```
#### 명령어:
- `list`: 모든 CLI 구성 매개변수 표시
```shell Terminal
crewai config list
```
- `set`: CLI 구성 매개변수 설정
```shell Terminal
crewai config set <key> <value>
```
- `reset`: 모든 CLI 구성 매개변수를 기본값으로 초기화
```shell Terminal
crewai config reset
```
#### 사용 가능한 구성 파라미터
- `enterprise_base_url`: CrewAI Enterprise 인스턴스의 기본 URL
- `oauth2_provider`: 인증에 사용되는 OAuth2 공급자 (예: workos, okta, auth0)
- `oauth2_audience`: OAuth2 audience 값으로, 일반적으로 대상 API 또는 리소스를 식별하는 데 사용됨
- `oauth2_client_id`: 인증 요청 시 사용되는 공급자가 발급한 OAuth2 클라이언트 ID
- `oauth2_domain`: 토큰 발급에 사용되는 OAuth2 공급자의 도메인 (예: your-org.auth0.com)
#### 예시
현재 설정 표시:
```shell Terminal
crewai config list
```
예시 출력:
```
CrewAI CLI Configuration
┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Setting ┃ Value ┃ Description ┃
┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ enterprise_base_url│ https://app.crewai.com │ CrewAI Enterprise 인스턴스의 기본 URL │
│ org_name │ Not set │ 현재 활성화된 조직의 이름 │
│ org_uuid │ Not set │ 현재 활성화된 조직의 UUID │
│ oauth2_provider │ workos │ 인증에 사용되는 OAuth2 제공자 (예: workos, okta, auth0) │
│ oauth2_audience │ client_01YYY │ 일반적으로 대상 API나 리소스를 식별하는 데 사용되는 OAuth2 audience 값 │
│ oauth2_client_id │ client_01XXX │ 제공자로부터 발급된 OAuth2 client ID로, 인증 요청 시 사용됨 │
│ oauth2_domain │ login.crewai.com │ 토큰 발급에 사용되는 OAuth2 제공자의 도메인(예: your-org.auth0.com) │
```
엔터프라이즈 기본 URL 설정:
```shell Terminal
crewai config set enterprise_base_url https://my-enterprise.crewai.com
```
OAuth2 제공자 설정:
```shell Terminal
crewai config set oauth2_provider auth0
```
OAuth2 도메인 설정:
```shell Terminal
crewai config set oauth2_domain my-company.auth0.com
```
모든 설정을 기본값으로 재설정:
```shell Terminal
crewai config reset
```
<Note>
설정 값은 `~/.config/crewai/settings.json`에 저장됩니다. 조직 이름과 UUID와 같은 일부 설정 값은 읽기 전용이며 인증 및 조직 명령을 통해 관리됩니다. 도구 저장소 관련 설정은 숨겨져 있으며 사용자가 직접 설정할 수 없습니다.
</Note>

View File

@@ -0,0 +1,362 @@
---
title: 협업
description: CrewAI 팀 내에서 에이전트가 함께 작업하고, 작업을 위임하며, 효과적으로 소통하는 방법에 대해 설명합니다.
icon: screen-users
---
## 개요
CrewAI에서의 협업은 에이전트들이 팀으로서 함께 작업하며, 각자의 전문성을 활용하기 위해 작업을 위임하고 질문을 주고받을 수 있도록 합니다. `allow_delegation=True`로 설정하면, 에이전트들은 자동으로 강력한 협업 도구에 접근할 수 있습니다.
## 빠른 시작: 협업 활성화
```python
from crewai import Agent, Crew, Task
# Enable collaboration for agents
researcher = Agent(
role="Research Specialist",
goal="Conduct thorough research on any topic",
backstory="Expert researcher with access to various sources",
allow_delegation=True, # 🔑 Key setting for collaboration
verbose=True
)
writer = Agent(
role="Content Writer",
goal="Create engaging content based on research",
backstory="Skilled writer who transforms research into compelling content",
allow_delegation=True, # 🔑 Enables asking questions to other agents
verbose=True
)
# Agents can now collaborate automatically
crew = Crew(
agents=[researcher, writer],
tasks=[...],
verbose=True
)
```
## 에이전트 협업 방식
`allow_delegation=True`로 설정하면, CrewAI는 에이전트에게 두 가지 강력한 도구를 자동으로 제공합니다.
### 1. **업무 위임 도구**
에이전트가 특정 전문성을 가진 팀원에게 작업을 할당할 수 있습니다.
```python
# Agent automatically gets this tool:
# Delegate work to coworker(task: str, context: str, coworker: str)
```
### 2. **질문하기 도구**
에이전트가 동료로부터 정보를 수집하기 위해 특정 질문을 할 수 있게 해줍니다.
```python
# Agent automatically gets this tool:
# Ask question to coworker(question: str, context: str, coworker: str)
```
## 협업의 실제
아래는 에이전트들이 콘텐츠 제작 작업에 협력하는 완성된 예시입니다:
```python
from crewai import Agent, Crew, Task, Process
# Create collaborative agents
researcher = Agent(
role="Research Specialist",
goal="Find accurate, up-to-date information on any topic",
backstory="""You're a meticulous researcher with expertise in finding
reliable sources and fact-checking information across various domains.""",
allow_delegation=True,
verbose=True
)
writer = Agent(
role="Content Writer",
goal="Create engaging, well-structured content",
backstory="""You're a skilled content writer who excels at transforming
research into compelling, readable content for different audiences.""",
allow_delegation=True,
verbose=True
)
editor = Agent(
role="Content Editor",
goal="Ensure content quality and consistency",
backstory="""You're an experienced editor with an eye for detail,
ensuring content meets high standards for clarity and accuracy.""",
allow_delegation=True,
verbose=True
)
# Create a task that encourages collaboration
article_task = Task(
description="""Write a comprehensive 1000-word article about 'The Future of AI in Healthcare'.
The article should include:
- Current AI applications in healthcare
- Emerging trends and technologies
- Potential challenges and ethical considerations
- Expert predictions for the next 5 years
Collaborate with your teammates to ensure accuracy and quality.""",
expected_output="A well-researched, engaging 1000-word article with proper structure and citations",
agent=writer # Writer leads, but can delegate research to researcher
)
# Create collaborative crew
crew = Crew(
agents=[researcher, writer, editor],
tasks=[article_task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
```
## 협업 패턴
### 패턴 1: 조사 → 작성 → 편집
```python
research_task = Task(
description="Research the latest developments in quantum computing",
expected_output="Comprehensive research summary with key findings and sources",
agent=researcher
)
writing_task = Task(
description="Write an article based on the research findings",
expected_output="Engaging 800-word article about quantum computing",
agent=writer,
context=[research_task] # Gets research output as context
)
editing_task = Task(
description="Edit and polish the article for publication",
expected_output="Publication-ready article with improved clarity and flow",
agent=editor,
context=[writing_task] # Gets article draft as context
)
```
### 패턴 2: 협업 단일 작업
```python
collaborative_task = Task(
description="""Create a marketing strategy for a new AI product.
Writer: Focus on messaging and content strategy
Researcher: Provide market analysis and competitor insights
Work together to create a comprehensive strategy.""",
expected_output="Complete marketing strategy with research backing",
agent=writer # Lead agent, but can delegate to researcher
)
```
## 계층적 협업
복잡한 프로젝트의 경우, 매니저 에이전트를 활용하여 계층적 프로세스를 사용하세요:
```python
from crewai import Agent, Crew, Task, Process
# Manager agent coordinates the team
manager = Agent(
role="Project Manager",
goal="Coordinate team efforts and ensure project success",
backstory="Experienced project manager skilled at delegation and quality control",
allow_delegation=True,
verbose=True
)
# Specialist agents
researcher = Agent(
role="Researcher",
goal="Provide accurate research and analysis",
backstory="Expert researcher with deep analytical skills",
allow_delegation=False, # Specialists focus on their expertise
verbose=True
)
writer = Agent(
role="Writer",
goal="Create compelling content",
backstory="Skilled writer who creates engaging content",
allow_delegation=False,
verbose=True
)
# Manager-led task
project_task = Task(
description="Create a comprehensive market analysis report with recommendations",
expected_output="Executive summary, detailed analysis, and strategic recommendations",
agent=manager # Manager will delegate to specialists
)
# Hierarchical crew
crew = Crew(
agents=[manager, researcher, writer],
tasks=[project_task],
process=Process.hierarchical, # Manager coordinates everything
manager_llm="gpt-4o", # Specify LLM for manager
verbose=True
)
```
## 협업을 위한 모범 사례
### 1. **명확한 역할 정의**
```python
# ✅ Good: Specific, complementary roles
researcher = Agent(role="Market Research Analyst", ...)
writer = Agent(role="Technical Content Writer", ...)
# ❌ Avoid: Overlapping or vague roles
agent1 = Agent(role="General Assistant", ...)
agent2 = Agent(role="Helper", ...)
```
### 2. **전략적 위임 활성화**
```python
# ✅ Enable delegation for coordinators and generalists
lead_agent = Agent(
role="Content Lead",
allow_delegation=True, # Can delegate to specialists
...
)
# ✅ Disable for focused specialists (optional)
specialist_agent = Agent(
role="Data Analyst",
allow_delegation=False, # Focuses on core expertise
...
)
```
### 3. **컨텍스트 공유**
```python
# ✅ Use context parameter for task dependencies
writing_task = Task(
description="Write article based on research",
agent=writer,
context=[research_task], # Shares research results
...
)
```
### 4. **명확한 작업 설명**
```python
# ✅ 구체적이고 실행 가능한 설명
Task(
description="""Research competitors in the AI chatbot space.
Focus on: pricing models, key features, target markets.
Provide data in a structured format.""",
...
)
# ❌ 협업에 도움이 되지 않는 모호한 설명
Task(description="Do some research about chatbots", ...)
```
## 협업 문제 해결
### 문제: 에이전트들이 협업하지 않음
**증상:** 에이전트들이 각자 작업하며, 위임이 이루어지지 않음
```python
# ✅ Solution: Ensure delegation is enabled
agent = Agent(
role="...",
allow_delegation=True, # This is required!
...
)
```
### 문제: 지나친 이중 확인
**증상:** 에이전트가 과도하게 질문을 하여 진행이 느려짐
```python
# ✅ Solution: Provide better context and specific roles
Task(
description="""Write a technical blog post about machine learning.
Context: Target audience is software developers with basic ML knowledge.
Length: 1200 words
Include: code examples, practical applications, best practices
If you need specific technical details, delegate research to the researcher.""",
...
)
```
### 문제: 위임 루프
**증상:** 에이전트들이 무한히 서로에게 위임함
```python
# ✅ Solution: Clear hierarchy and responsibilities
manager = Agent(role="Manager", allow_delegation=True)
specialist1 = Agent(role="Specialist A", allow_delegation=False) # No re-delegation
specialist2 = Agent(role="Specialist B", allow_delegation=False)
```
## 고급 협업 기능
### 맞춤 협업 규칙
```python
# Set specific collaboration guidelines in agent backstory
agent = Agent(
role="Senior Developer",
backstory="""You lead development projects and coordinate with team members.
Collaboration guidelines:
- Delegate research tasks to the Research Analyst
- Ask the Designer for UI/UX guidance
- Consult the QA Engineer for testing strategies
- Only escalate blocking issues to the Project Manager""",
allow_delegation=True
)
```
### 협업 모니터링
```python
def track_collaboration(output):
"""Track collaboration patterns"""
if "Delegate work to coworker" in output.raw:
print("🤝 Delegation occurred")
if "Ask question to coworker" in output.raw:
print("❓ Question asked")
crew = Crew(
agents=[...],
tasks=[...],
step_callback=track_collaboration, # Monitor collaboration
verbose=True
)
```
## 메모리와 학습
에이전트가 과거 협업을 기억할 수 있도록 합니다:
```python
agent = Agent(
role="Content Lead",
memory=True, # Remembers past interactions
allow_delegation=True,
verbose=True
)
```
메모리가 활성화되면, 에이전트는 이전 협업에서 학습하여 시간이 지남에 따라 더 나은 위임 결정을 내릴 수 있습니다.
## 다음 단계
- **예제 시도하기**: 기본 협업 예제부터 시작하세요
- **역할 실험하기**: 다양한 에이전트 역할 조합을 테스트해 보세요
- **상호작용 모니터링**: 협업 과정을 직접 보려면 `verbose=True`를 사용하세요
- **작업 설명 최적화**: 명확한 작업이 더 나은 협업으로 이어집니다
- **확장하기**: 복잡한 프로젝트에는 계층적 프로세스를 시도해 보세요
협업은 개별 AI 에이전트를 복잡하고 다면적인 문제를 함께 해결할 수 있는 강력한 팀으로 변화시킵니다.

368
docs/ko/concepts/crews.mdx Normal file
View File

@@ -0,0 +1,368 @@
---
title: 크루
description: crewAI 프레임워크에서 크루를 이해하고 다양한 속성과 기능을 활용하기.
icon: people-group
---
## 개요
crewAI에서 crew는 일련의 작업을 달성하기 위해 함께 협력하는 에이전트들의 그룹을 나타냅니다. 각 crew는 작업 실행, 에이전트 간 협업, 그리고 전체 워크플로우에 대한 전략을 정의합니다.
## Crew 속성
| 속성 | 파라미터 | 설명 |
| :-------------------------------------- | :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Tasks** | `tasks` | crew에 할당된 작업들의 리스트. |
| **Agents** | `agents` | crew의 일원이 되는 에이전트들의 리스트. |
| **Process** _(선택사항)_ | `process` | crew가 따르는 프로세스 플로우(예: 순차, 계층적). 기본값은 `sequential`. |
| **Verbose** _(선택사항)_ | `verbose` | 실행 중 로그의 상세도 설정. 기본값은 `False`. |
| **Manager LLM** _(선택사항)_ | `manager_llm` | 계층적 프로세스에서 매니저 에이전트가 사용하는 언어 모델. **계층적 프로세스를 사용할 때 필수.** |
| **Function Calling LLM** _(선택사항)_ | `function_calling_llm` | 전달 시, crew 전체의 모든 agent에 대해 도구의 function calling에 이 LLM을 사용. 각 agent마다 개별 LLM을 가질 수 있으며, 이 경우 crew의 function calling LLM을 오버라이드 함. |
| **Config** _(선택사항)_ | `config` | crew용으로 선택적인 구성 설정. `Json` 또는 `Dict[str, Any]` 형식 사용. |
| **Max RPM** _(선택사항)_ | `max_rpm` | 실행 중 crew가 준수하는 분당 최대 요청 수. 기본값은 `None`. |
| **Memory** _(선택사항)_ | `memory` | 실행 메모리(단기, 장기, 엔터티 메모리) 저장에 사용됨. |
| **Cache** _(선택사항)_ | `cache` | 도구 실행 결과를 캐시에 저장할지 여부. 기본값은 `True`. |
| **Embedder** _(선택사항)_ | `embedder` | crew에서 사용할 embedder 설정. 현재는 주로 메모리에서 사용. 기본값은 `{"provider": "openai"}`. |
| **Step Callback** _(선택사항)_ | `step_callback` | 각 agent의 단계가 끝난 후 호출되는 함수. agent의 작업 기록이나 기타 작업 수행에 사용 가능; agent별 `step_callback`을 오버라이드하지 않음. |
| **Task Callback** _(선택사항)_ | `task_callback` | 각 작업 완료 후 호출되는 함수. 작업 실행 후 모니터링이나 추가 작업에 유용. |
| **Share Crew** _(선택사항)_ | `share_crew` | 라이브러리 개선 및 모델 학습을 위해 crew 정보와 실행을 crewAI 팀에 공유할지 여부. |
| **Output Log File** _(선택사항)_ | `output_log_file` | `True`로 설정 시 로그를 현재 디렉터리에 logs.txt로 저장하거나 파일 경로 지정 가능. 파일명이 .json으로 끝나면 JSON 형식, 아니면 txt 형식으로 로그를 저장. 기본값은 `None`. |
| **Manager Agent** _(선택사항)_ | `manager_agent` | 매니저로 사용할 커스텀 agent를 설정. |
| **Prompt File** _(선택사항)_ | `prompt_file` | crew에서 사용할 prompt JSON 파일 경로. |
| **Planning** *(선택사항)* | `planning` | Crew에 계획 수립 기능을 추가. 활성화하면 각 Crew 반복 전에 모든 Crew 데이터를 AgentPlanner로 전송하여 작업계획을 세우고, 이 계획이 각 작업 설명에 추가됨. |
| **Planning LLM** *(선택사항)* | `planning_llm` | 계획 과정에서 AgentPlanner가 사용하는 언어 모델. |
| **Knowledge Sources** _(선택사항)_ | `knowledge_sources` | crew 수준에서 사용 가능한 지식 소스. 모든 agent가 접근 가능. |
<Tip>
**Crew Max RPM**: `max_rpm` 속성은 crew가 분당 처리할 수 있는 최대 요청 수를 설정하며, 개별 agent의 `max_rpm` 설정을 crew 단위로 지정할 경우 오버라이드합니다.
</Tip>
## 크루 생성하기
CrewAI에서 크루를 생성하는 방법은 두 가지가 있습니다: **YAML 구성(권장)**을 사용하는 방법과 **코드에서 직접 정의**하는 방법입니다.
### YAML 구성 (권장)
YAML 구성을 사용하면 crew를 정의할 때 더 깔끔하고 유지 관리하기 쉬운 방법을 제공하며, CrewAI 프로젝트에서 agent 및 task를 정의하는 방식과 일관성을 유지할 수 있습니다.
[설치](/ko/installation) 섹션에 설명된 대로 CrewAI 프로젝트를 생성한 후, `CrewBase`를 상속받는 클래스에서 데코레이터를 이용해 agent, task, 그리고 crew 자체를 정의할 수 있습니다.
#### 데코레이터가 적용된 예시 Crew 클래스
```python code
from crewai import Agent, Crew, Task, Process
from crewai.project import CrewBase, agent, task, crew, before_kickoff, after_kickoff
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class YourCrewName:
"""Description of your crew"""
agents: List[BaseAgent]
tasks: List[Task]
# YAML 구성 파일 경로
# YAML로 정의된 에이전트와 태스크의 예시는 아래 링크를 참고하세요:
# - Task: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended
# - Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'
@before_kickoff
def prepare_inputs(self, inputs):
# crew 시작 전에 입력값을 수정합니다
inputs['additional_data'] = "Some extra information"
return inputs
@after_kickoff
def process_output(self, output):
# crew가 종료된 후 출력값을 수정합니다
output.raw += "\nProcessed after kickoff."
return output
@agent
def agent_one(self) -> Agent:
return Agent(
config=self.agents_config['agent_one'], # type: ignore[index]
verbose=True
)
@agent
def agent_two(self) -> Agent:
return Agent(
config=self.agents_config['agent_two'], # type: ignore[index]
verbose=True
)
@task
def task_one(self) -> Task:
return Task(
config=self.tasks_config['task_one'] # type: ignore[index]
)
@task
def task_two(self) -> Task:
return Task(
config=self.tasks_config['task_two'] # type: ignore[index]
)
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents, # @agent 데코레이터로 자동 수집
tasks=self.tasks, # @task 데코레이터로 자동 수집
process=Process.sequential,
verbose=True,
)
```
위 코드를 실행하는 방법:
```python code
YourCrewName().crew().kickoff(inputs={"any": "input here"})
```
<Note>
태스크들은 정의된 순서대로 실행됩니다.
</Note>
`CrewBase` 클래스와 이 데코레이터들은 에이전트와 태스크의 수집을 자동화하여
수동으로 관리할 필요를 줄여줍니다.
#### `annotations.py`의 데코레이터 개요
CrewAI는 `annotations.py` 파일에서 크루 클래스 내의 메서드를 특별히 처리하기 위해 사용하는 여러 데코레이터를 제공합니다:
- `@CrewBase`: 클래스를 크루 기본 클래스로 표시합니다.
- `@agent`: `Agent` 객체를 반환하는 메서드임을 나타냅니다.
- `@task`: `Task` 객체를 반환하는 메서드임을 나타냅니다.
- `@crew`: `Crew` 객체를 반환하는 메서드임을 나타냅니다.
- `@before_kickoff`: (옵션) 크루가 시작되기 전에 실행될 메서드를 표시합니다.
- `@after_kickoff`: (옵션) 크루가 종료된 후에 실행될 메서드를 표시합니다.
이러한 데코레이터들은 크루의 구조를 구성하는 데 도움이 되며, 에이전트와 태스크를 수동으로 나열하지 않아도 자동으로 수집할 수 있도록 해줍니다.
### 직접 코드 정의 (대안)
또는 YAML 구성 파일을 사용하지 않고 코드에서 직접 crew를 정의할 수 있습니다.
```python code
from crewai import Agent, Crew, Task, Process
from crewai_tools import YourCustomTool
class YourCrewName:
def agent_one(self) -> Agent:
return Agent(
role="Data Analyst",
goal="Analyze data trends in the market",
backstory="An experienced data analyst with a background in economics",
verbose=True,
tools=[YourCustomTool()]
)
def agent_two(self) -> Agent:
return Agent(
role="Market Researcher",
goal="Gather information on market dynamics",
backstory="A diligent researcher with a keen eye for detail",
verbose=True
)
def task_one(self) -> Task:
return Task(
description="Collect recent market data and identify trends.",
expected_output="A report summarizing key trends in the market.",
agent=self.agent_one()
)
def task_two(self) -> Task:
return Task(
description="Research factors affecting market dynamics.",
expected_output="An analysis of factors influencing the market.",
agent=self.agent_two()
)
def crew(self) -> Crew:
return Crew(
agents=[self.agent_one(), self.agent_two()],
tasks=[self.task_one(), self.task_two()],
process=Process.sequential,
verbose=True
)
```
위 코드를 실행하는 방법:
```python code
YourCrewName().crew().kickoff(inputs={})
```
이 예시에서:
- 에이전트와 태스크는 데코레이터 없이 클래스 내에서 직접 정의됩니다.
- 에이전트와 태스크 목록을 수동으로 생성하고 관리합니다.
- 이 방식은 더 많은 제어를 제공하지만, 대규모 프로젝트의 경우 유지보수가 어려울 수 있습니다.
## Crew Output
CrewAI 프레임워크에서 crew의 출력은 `CrewOutput` 클래스 내에 캡슐화되어 있습니다.
이 클래스는 crew 실행 결과를 구조화된 방식으로 접근할 수 있도록 하며, 원시 문자열, JSON, Pydantic 모델과 같은 다양한 형식을 포함합니다.
`CrewOutput`에는 최종 task 출력 결과, 토큰 사용량, 그리고 개별 task 출력 결과가 포함됩니다.
### Crew 출력 속성
| 속성 | 매개변수 | 타입 | 설명 |
| :--------------- | :--------------- | :--------------------------- | :----------------------------------------------------------------------------------------- |
| **Raw** | `raw` | `str` | crew의 원시 출력값입니다. 출력의 기본 형식입니다. |
| **Pydantic** | `pydantic` | `Optional[BaseModel]` | crew의 구조화된 출력을 나타내는 Pydantic 모델 객체입니다. |
| **JSON Dict** | `json_dict` | `Optional[Dict[str, Any]]` | crew의 JSON 출력을 나타내는 딕셔너리입니다. |
| **Tasks Output** | `tasks_output` | `List[TaskOutput]` | crew 내 각 작업의 출력을 나타내는 `TaskOutput` 객체의 리스트입니다. |
| **Token Usage** | `token_usage` | `Dict[str, Any]` | 실행 중 언어 모델의 성능에 대한 통찰을 제공하는 토큰 사용 요약 정보입니다. |
### Crew 출력 메서드 및 속성
| 메서드/속성 | 설명 |
| :-------------- | :------------------------------------------------------------------------------------------------ |
| **json** | 출력 형식이 JSON인 경우 crew 출력의 JSON 문자열 표현을 반환합니다. |
| **to_dict** | JSON 및 Pydantic 출력을 사전으로 변환합니다. |
| \***\*str\*\*** | crew 출력의 문자열 표현을 반환합니다. 우선순위는 Pydantic, 그 다음 JSON, 마지막으로 raw입니다. |
### Crew 출력 접근하기
crew가 실행된 후에는 `Crew` 객체의 `output` 속성을 통해 출력값에 접근할 수 있습니다. `CrewOutput` 클래스는 이 출력값을 다루고 표시하는 다양한 방법을 제공합니다.
#### 예시
```python Code
# Example crew execution
crew = Crew(
agents=[research_agent, writer_agent],
tasks=[research_task, write_article_task],
verbose=True
)
crew_output = crew.kickoff()
# Accessing the crew output
print(f"Raw Output: {crew_output.raw}")
if crew_output.json_dict:
print(f"JSON Output: {json.dumps(crew_output.json_dict, indent=2)}")
if crew_output.pydantic:
print(f"Pydantic Output: {crew_output.pydantic}")
print(f"Tasks Output: {crew_output.tasks_output}")
print(f"Token Usage: {crew_output.token_usage}")
```
## 크루 로그 접근하기
`output_log_file`을 `True(Boolean)` 또는 `file_name(str)`로 설정하면 크루 실행의 실시간 로그를 볼 수 있습니다. 이벤트 로그는 `file_name.txt`와 `file_name.json` 두 가지 형식 모두를 지원합니다.
`True(Boolean)`로 설정할 경우에는 `logs.txt`로 저장됩니다.
`output_log_file`이 `False(Boolean)` 또는 `None`으로 설정된 경우에는 로그가 저장되지 않습니다.
```python Code
# 크루 로그 저장하기
crew = Crew(output_log_file = True) # 로그는 logs.txt로 저장됩니다
crew = Crew(output_log_file = file_name) # 로그는 file_name.txt로 저장됩니다
crew = Crew(output_log_file = file_name.txt) # 로그는 file_name.txt로 저장됩니다
crew = Crew(output_log_file = file_name.json) # 로그는 file_name.json으로 저장됩니다
```
## 메모리 활용
crew는 메모리(단기, 장기 및 엔티티 메모리)를 활용하여 시간이 지남에 따라 실행 및 학습을 향상시킬 수 있습니다. 이 기능을 통해 crew는 실행 메모리를 저장하고 회상할 수 있어, 의사결정 및 작업 실행 전략에 도움이 됩니다.
## 캐시 활용
캐시는 도구 실행 결과를 저장하는 데 사용될 수 있으며, 동일한 작업을 반복 실행할 필요를 줄여 프로세스의 효율성을 높입니다.
## Crew 사용 메트릭
crew 실행 후, `usage_metrics` 속성에 접근하여 crew가 실행한 모든 작업에 대한 언어 모델(LLM) 사용 메트릭을 확인할 수 있습니다. 이를 통해 운영 효율성과 개선이 필요한 영역에 대한 인사이트를 얻을 수 있습니다.
```python Code
# Access the crew's usage metrics
crew = Crew(agents=[agent1, agent2], tasks=[task1, task2])
crew.kickoff()
print(crew.usage_metrics)
```
## Crew 실행 프로세스
- **순차적 프로세스**: 작업이 하나씩 차례로 실행되어 linear flow의 작업 흐름을 제공합니다.
- **계층적 프로세스**: 매니저 agent가 crew를 조정하여 작업을 위임하고 결과를 검증한 후 다음 단계로 이동합니다. **참고**: 이 프로세스에는 `manager_llm` 또는 `manager_agent`가 필요하며, 프로세스 flow 검증을 위해 필수적입니다.
### 크루 시작하기
크루가 구성되면, `kickoff()` 메서드를 사용하여 워크플로를 시작하세요. 이렇게 하면 정의된 프로세스 플로우에 따라 실행 과정이 시작됩니다.
```python Code
# Start the crew's task execution
result = my_crew.kickoff()
print(result)
```
### Crew를 시작하는 다양한 방법
crew가 구성되면, 적절한 시작 방법으로 workflow를 시작하세요. CrewAI는 kickoff 프로세스를 더 잘 제어할 수 있도록 여러 방법을 제공합니다: `kickoff()`, `kickoff_for_each()`, `kickoff_async()`, 그리고 `kickoff_for_each_async()`.
- `kickoff()`: 정의된 process flow에 따라 실행 프로세스를 시작합니다.
- `kickoff_for_each()`: 입력 이벤트나 컬렉션 내 각 항목에 대해 순차적으로 task를 실행합니다.
- `kickoff_async()`: 비동기적으로 workflow를 시작합니다.
- `kickoff_for_each_async()`: 입력 이벤트나 각 항목에 대해 비동기 처리를 활용하여 task를 동시에 실행합니다.
```python Code
# Start the crew's task execution
result = my_crew.kickoff()
print(result)
# Example of using kickoff_for_each
inputs_array = [{'topic': 'AI in healthcare'}, {'topic': 'AI in finance'}]
results = my_crew.kickoff_for_each(inputs=inputs_array)
for result in results:
print(result)
# Example of using kickoff_async
inputs = {'topic': 'AI in healthcare'}
async_result = await my_crew.kickoff_async(inputs=inputs)
print(async_result)
# Example of using kickoff_for_each_async
inputs_array = [{'topic': 'AI in healthcare'}, {'topic': 'AI in finance'}]
async_results = await my_crew.kickoff_for_each_async(inputs=inputs_array)
for async_result in async_results:
print(async_result)
```
이러한 메서드는 crew 내에서 task를 관리하고 실행하는 데 유연성을 제공하며, 동기 및 비동기 workflow 모두 필요에 맞게 사용할 수 있도록 지원합니다.
### 특정 Task에서 다시 실행하기
이제 CLI 명령어 `replay`를 사용하여 특정 task에서 다시 실행할 수 있습니다.
CrewAI의 replay 기능을 사용하면 커맨드라인 인터페이스(CLI)를 통해 특정 task에서 다시 실행할 수 있습니다. `crewai replay -t <task_id>` 명령어를 실행하면 replay 과정에서 사용할 `task_id`를 지정할 수 있습니다.
Kickoff은 이제 최신 kickoff에서 반환된 task output을 로컬에 저장하므로, 해당 지점부터 다시 실행할 수 있습니다.
### CLI를 사용하여 특정 작업에서 다시 실행하기
replay 기능을 사용하려면 다음 단계를 따라주세요:
1. 터미널 또는 명령 프롬프트를 엽니다.
2. CrewAI 프로젝트가 위치한 디렉터리로 이동합니다.
3. 아래 명령어를 실행합니다:
최신 kickoff 작업 ID를 확인하려면 다음을 사용하세요:
```shell
crewai log-tasks-outputs
```
그런 다음, 특정 작업에서 다시 실행하려면 다음을 사용하세요:
```shell
crewai replay -t <task_id>
```
이 명령어들을 사용하면 이전에 실행된 작업의 컨텍스트를 유지하면서 최신 kickoff 작업부터 다시 실행할 수 있습니다.

View File

@@ -0,0 +1,390 @@
---
title: '이벤트 리스너'
description: 'CrewAI 이벤트에 연결하여 맞춤형 통합 및 모니터링 구축'
icon: spinner
---
## 개요
CrewAI는 강력한 이벤트 시스템을 제공하여 crew 실행 중 발생하는 다양한 이벤트를 수신하고 이에 반응할 수 있도록 합니다. 이 기능을 통해 맞춤형 통합, 모니터링 솔루션, 로깅 시스템 또는 CrewAI의 내부 이벤트에 따라 트리거되어야 하는 기타 모든 기능을 구축할 수 있습니다.
## 작동 방식
CrewAI는 실행 수명 주기 전반에 걸쳐 이벤트를 발생시키는 이벤트 버스 아키텍처를 사용합니다. 이벤트 시스템은 다음과 같은 구성 요소로 구축되어 있습니다:
1. **CrewAIEventsBus**: 이벤트 등록 및 발생을 관리하는 싱글톤 이벤트 버스
2. **BaseEvent**: 시스템 내 모든 이벤트의 기본 클래스
3. **BaseEventListener**: 커스텀 이벤트 리스너 생성을 위한 추상 기본 클래스
CrewAI에서 특정 동작(예: Crew가 실행을 시작하거나 Agent가 task를 완료하거나 tool이 사용될 때)이 발생하면, 시스템은 해당 이벤트를 발생시킵니다. 이러한 이벤트에 대한 핸들러를 등록하여 해당 이벤트가 발생할 때 커스텀 코드를 실행할 수 있습니다.
<Note type="info" title="Enterprise Enhancement: Prompt Tracing">
CrewAI Enterprise는 event 시스템을 활용하여 모든 prompt, completion 및 관련 메타데이터를 추적, 저장 및 시각화하는 내장 Prompt Tracing 기능을 제공합니다. 이 기능을 통해 agent 운영에 대한 강력한 디버깅 기능과 투명성을 얻을 수 있습니다.
![Prompt Tracing Dashboard](/images/enterprise/traces-overview.png)
Prompt Tracing을 통해 다음과 같은 작업이 가능합니다:
- LLM에 전송된 모든 prompt의 전체 기록 보기
- token 사용량 및 비용 추적
- agent reasoning 실패 디버깅
- 팀 내에서 prompt 시퀀스 공유
- 다양한 prompt 전략 비교
- 컴플라이언스 및 감사를 위한 trace 내보내기
</Note>
## 커스텀 이벤트 리스너 생성하기
커스텀 이벤트 리스너를 생성하려면 다음 단계를 따라야 합니다:
1. `BaseEventListener`를 상속하는 클래스를 생성합니다.
2. `setup_listeners` 메서드를 구현합니다.
3. 원하는 이벤트에 대한 핸들러를 등록합니다.
4. 해당 파일에서 리스너의 인스턴스를 생성합니다.
아래는 커스텀 이벤트 리스너 클래스의 간단한 예시입니다:
```python
from crewai.utilities.events import (
CrewKickoffStartedEvent,
CrewKickoffCompletedEvent,
AgentExecutionCompletedEvent,
)
from crewai.utilities.events.base_event_listener import BaseEventListener
class MyCustomListener(BaseEventListener):
def __init__(self):
super().__init__()
def setup_listeners(self, crewai_event_bus):
@crewai_event_bus.on(CrewKickoffStartedEvent)
def on_crew_started(source, event):
print(f"Crew '{event.crew_name}' has started execution!")
@crewai_event_bus.on(CrewKickoffCompletedEvent)
def on_crew_completed(source, event):
print(f"Crew '{event.crew_name}' has completed execution!")
print(f"Output: {event.output}")
@crewai_event_bus.on(AgentExecutionCompletedEvent)
def on_agent_execution_completed(source, event):
print(f"Agent '{event.agent.role}' completed task")
print(f"Output: {event.output}")
```
## 리스너를 올바르게 등록하기
리스너 클래스를 정의하는 것만으로는 충분하지 않습니다. 해당 클래스의 인스턴스를 생성하고 애플리케이션에 임포트되었는지 확인해야 합니다. 이렇게 하면 다음과 같은 효과가 있습니다:
1. 이벤트 핸들러가 이벤트 버스에 등록됩니다.
2. 리스너 인스턴스가 메모리에 유지됩니다(가비지 컬렉션되지 않음).
3. 이벤트가 발생할 때 리스너가 활성화됩니다.
### 옵션 1: Crew 또는 Flow 구현에서 가져오기 및 인스턴스화
가장 중요한 것은 Crew 또는 Flow가 정의되고 실행되는 파일에서 리스너의 인스턴스를 생성하는 것입니다.
#### 크루 기반 애플리케이션의 경우
크루 구현 파일 상단에 리스너를 생성하고 임포트하세요:
```python
# In your crew.py file
from crewai import Agent, Crew, Task
from my_listeners import MyCustomListener
# Create an instance of your listener
my_listener = MyCustomListener()
class MyCustomCrew:
# Your crew implementation...
def crew(self):
return Crew(
agents=[...],
tasks=[...],
# ...
)
```
#### 플로우 기반 애플리케이션의 경우
플로우 구현 파일 상단에 리스너를 생성하고 임포트하세요:
```python
# main.py 또는 flow.py 파일에서
from crewai.flow import Flow, listen, start
from my_listeners import MyCustomListener
# 리스너 인스턴스 생성
my_listener = MyCustomListener()
class MyCustomFlow(Flow):
# 플로우 구현...
@start()
def first_step(self):
# ...
```
이렇게 하면 크루 또는 플로우가 실행될 때 리스너가 로드되고 활성화됩니다.
### 옵션 2: 리스너를 위한 패키지 생성
여러 개의 리스너가 있는 경우 등 보다 구조적인 접근 방식을 원한다면 다음과 같이 진행하세요:
1. 리스너를 위한 패키지를 생성합니다:
```
my_project/
├── listeners/
│ ├── __init__.py
│ ├── my_custom_listener.py
│ └── another_listener.py
```
2. `my_custom_listener.py`에서 리스너 클래스를 정의하고 인스턴스를 생성합니다:
```python
# my_custom_listener.py
from crewai.utilities.events.base_event_listener import BaseEventListener
# ... import events ...
class MyCustomListener(BaseEventListener):
# ... implementation ...
# 리스너 인스턴스 생성
my_custom_listener = MyCustomListener()
```
3. `__init__.py`에서 리스너 인스턴스를 임포트하여 로드되도록 합니다:
```python
# __init__.py
from .my_custom_listener import my_custom_listener
from .another_listener import another_listener
# 다른 곳에서 접근이 필요하다면 익스포트할 수도 있습니다
__all__ = ['my_custom_listener', 'another_listener']
```
4. Crew나 Flow 파일에서 리스너 패키지를 임포트합니다:
```python
# crew.py 또는 flow.py 파일 내에서
import my_project.listeners # 모든 리스너가 로드됩니다
class MyCustomCrew:
# Your crew implementation...
```
이것이 바로 CrewAI의 내장 `agentops_listener`가 등록되는 방식과 동일합니다. CrewAI 코드베이스에서는 다음과 같이 되어 있습니다:
```python
# src/crewai/utilities/events/third_party/__init__.py
from .agentops_listener import agentops_listener
```
이렇게 하면 `crewai.utilities.events` 패키지가 임포트될 때 `agentops_listener`가 자동으로 로드됩니다.
## 사용 가능한 이벤트 유형
CrewAI는 여러분이 청취할 수 있는 다양한 이벤트를 제공합니다:
### Crew 이벤트
- **CrewKickoffStartedEvent**: Crew가 실행을 시작할 때 발생
- **CrewKickoffCompletedEvent**: Crew가 실행을 완료할 때 발생
- **CrewKickoffFailedEvent**: Crew가 실행을 완료하지 못할 때 발생
- **CrewTestStartedEvent**: Crew가 테스트를 시작할 때 발생
- **CrewTestCompletedEvent**: Crew가 테스트를 완료할 때 발생
- **CrewTestFailedEvent**: Crew가 테스트를 완료하지 못할 때 발생
- **CrewTrainStartedEvent**: Crew가 훈련을 시작할 때 발생
- **CrewTrainCompletedEvent**: Crew가 훈련을 완료할 때 발생
- **CrewTrainFailedEvent**: Crew가 훈련을 완료하지 못할 때 발생
### 에이전트 이벤트
- **AgentExecutionStartedEvent**: 에이전트가 작업 실행을 시작할 때 발생함
- **AgentExecutionCompletedEvent**: 에이전트가 작업 실행을 완료할 때 발생함
- **AgentExecutionErrorEvent**: 에이전트가 실행 도중 오류를 만날 때 발생함
### 작업 이벤트
- **TaskStartedEvent**: 작업이 실행을 시작할 때 발생
- **TaskCompletedEvent**: 작업이 실행을 완료할 때 발생
- **TaskFailedEvent**: 작업이 실행을 완료하지 못할 때 발생
- **TaskEvaluationEvent**: 작업이 평가될 때 발생
### 도구 사용 이벤트
- **ToolUsageStartedEvent**: 도구 실행이 시작될 때 발생함
- **ToolUsageFinishedEvent**: 도구 실행이 완료될 때 발생함
- **ToolUsageErrorEvent**: 도구 실행 중 오류가 발생할 때 발생함
- **ToolValidateInputErrorEvent**: 도구 입력 검증 중 오류가 발생할 때 발생함
- **ToolExecutionErrorEvent**: 도구 실행 중 오류가 발생할 때 발생함
- **ToolSelectionErrorEvent**: 도구 선택 시 오류가 발생할 때 발생함
### 지식 이벤트
- **KnowledgeRetrievalStartedEvent**: 지식 검색이 시작될 때 발생
- **KnowledgeRetrievalCompletedEvent**: 지식 검색이 완료될 때 발생
- **KnowledgeQueryStartedEvent**: 지식 쿼리가 시작될 때 발생
- **KnowledgeQueryCompletedEvent**: 지식 쿼리가 완료될 때 발생
- **KnowledgeQueryFailedEvent**: 지식 쿼리가 실패할 때 발생
- **KnowledgeSearchQueryFailedEvent**: 지식 검색 쿼리가 실패할 때 발생
### LLM 가드레일 이벤트
- **LLMGuardrailStartedEvent**: 가드레일 검증이 시작될 때 발생합니다. 적용되는 가드레일에 대한 세부 정보와 재시도 횟수를 포함합니다.
- **LLMGuardrailCompletedEvent**: 가드레일 검증이 완료될 때 발생합니다. 검증의 성공/실패, 결과 및 오류 메시지(있는 경우)에 대한 세부 정보를 포함합니다.
### Flow 이벤트
- **FlowCreatedEvent**: Flow가 생성될 때 발생
- **FlowStartedEvent**: Flow가 실행을 시작할 때 발생
- **FlowFinishedEvent**: Flow가 실행을 완료할 때 발생
- **FlowPlotEvent**: Flow가 플롯될 때 발생
- **MethodExecutionStartedEvent**: Flow 메서드가 실행을 시작할 때 발생
- **MethodExecutionFinishedEvent**: Flow 메서드가 실행을 완료할 때 발생
- **MethodExecutionFailedEvent**: Flow 메서드가 실행을 완료하지 못할 때 발생
### LLM 이벤트
- **LLMCallStartedEvent**: LLM 호출이 시작될 때 발생
- **LLMCallCompletedEvent**: LLM 호출이 완료될 때 발생
- **LLMCallFailedEvent**: LLM 호출이 실패할 때 발생
- **LLMStreamChunkEvent**: 스트리밍 LLM 응답 중 각 청크를 받을 때마다 발생
### 메모리 이벤트
- **MemoryQueryStartedEvent**: 메모리 쿼리가 시작될 때 발생합니다. 쿼리, limit, 선택적 score threshold를 포함합니다.
- **MemoryQueryCompletedEvent**: 메모리 쿼리가 성공적으로 완료될 때 발생합니다. 쿼리, 결과, limit, score threshold, 쿼리 실행 시간을 포함합니다.
- **MemoryQueryFailedEvent**: 메모리 쿼리 실행에 실패할 때 발생합니다. 쿼리, limit, score threshold, 오류 메시지를 포함합니다.
- **MemorySaveStartedEvent**: 메모리 저장 작업이 시작될 때 발생합니다. 저장할 값, 메타데이터, 선택적 agent 역할을 포함합니다.
- **MemorySaveCompletedEvent**: 메모리 저장 작업이 성공적으로 완료될 때 발생합니다. 저장된 값, 메타데이터, agent 역할, 저장 실행 시간을 포함합니다.
- **MemorySaveFailedEvent**: 메모리 저장 작업에 실패할 때 발생합니다. 값, 메타데이터, agent 역할, 오류 메시지를 포함합니다.
- **MemoryRetrievalStartedEvent**: 태스크 프롬프트를 위한 메모리 검색이 시작될 때 발생합니다. 선택적 태스크 ID를 포함합니다.
- **MemoryRetrievalCompletedEvent**: 태스크 프롬프트를 위한 메모리 검색이 성공적으로 완료될 때 발생합니다. 태스크 ID, 메모리 내용, 검색 실행 시간을 포함합니다.
## 이벤트 핸들러 구조
각 이벤트 핸들러는 두 개의 매개변수를 받습니다:
1. **source**: 이벤트를 발생시킨 객체
2. **event**: 이벤트별 데이터를 포함하는 이벤트 인스턴스
이벤트 객체의 구조는 이벤트 타입에 따라 다르지만, 모든 이벤트는 `BaseEvent`를 상속하며 다음을 포함합니다:
- **timestamp**: 이벤트가 발생한 시간
- **type**: 이벤트 타입을 나타내는 문자열 식별자
추가 필드는 이벤트 타입에 따라 다릅니다. 예를 들어, `CrewKickoffCompletedEvent`에는 `crew_name`과 `output` 필드가 포함됩니다.
## 실제 예시: AgentOps와의 통합
CrewAI는 AI 에이전트를 위한 모니터링 및 관찰 플랫폼인 [AgentOps](https://github.com/AgentOps-AI/agentops)와의 서드파티 통합 예시를 포함하고 있습니다. 구현 방식은 다음과 같습니다:
```python
from typing import Optional
from crewai.utilities.events import (
CrewKickoffCompletedEvent,
ToolUsageErrorEvent,
ToolUsageStartedEvent,
)
from crewai.utilities.events.base_event_listener import BaseEventListener
from crewai.utilities.events.crew_events import CrewKickoffStartedEvent
from crewai.utilities.events.task_events import TaskEvaluationEvent
try:
import agentops
AGENTOPS_INSTALLED = True
except ImportError:
AGENTOPS_INSTALLED = False
class AgentOpsListener(BaseEventListener):
tool_event: Optional["agentops.ToolEvent"] = None
session: Optional["agentops.Session"] = None
def __init__(self):
super().__init__()
def setup_listeners(self, crewai_event_bus):
if not AGENTOPS_INSTALLED:
return
@crewai_event_bus.on(CrewKickoffStartedEvent)
def on_crew_kickoff_started(source, event: CrewKickoffStartedEvent):
self.session = agentops.init()
for agent in source.agents:
if self.session:
self.session.create_agent(
name=agent.role,
agent_id=str(agent.id),
)
@crewai_event_bus.on(CrewKickoffCompletedEvent)
def on_crew_kickoff_completed(source, event: CrewKickoffCompletedEvent):
if self.session:
self.session.end_session(
end_state="Success",
end_state_reason="Finished Execution",
)
@crewai_event_bus.on(ToolUsageStartedEvent)
def on_tool_usage_started(source, event: ToolUsageStartedEvent):
self.tool_event = agentops.ToolEvent(name=event.tool_name)
if self.session:
self.session.record(self.tool_event)
@crewai_event_bus.on(ToolUsageErrorEvent)
def on_tool_usage_error(source, event: ToolUsageErrorEvent):
agentops.ErrorEvent(exception=event.error, trigger_event=self.tool_event)
```
이 listener는 crew가 시작될 때 AgentOps 세션을 초기화하고, agent를 AgentOps에 등록하며, 도구 사용을 추적하고, crew가 완료되면 세션을 종료합니다.
AgentOps listener는 `src/crewai/utilities/events/third_party/__init__.py` 파일의 import를 통해 CrewAI 이벤트 시스템에 등록됩니다:
```python
from .agentops_listener import agentops_listener
```
이렇게 하면 `crewai.utilities.events` 패키지가 import될 때 `agentops_listener`가 로드되는 것이 보장됩니다.
## 고급 사용법: Scoped Handlers
임시 이벤트 처리가 필요한 경우(테스트 또는 특정 작업에 유용함), `scoped_handlers` 컨텍스트 관리자를 사용할 수 있습니다:
```python
from crewai.utilities.events import crewai_event_bus, CrewKickoffStartedEvent
with crewai_event_bus.scoped_handlers():
@crewai_event_bus.on(CrewKickoffStartedEvent)
def temp_handler(source, event):
print("This handler only exists within this context")
# Do something that emits events
# 컨텍스트 밖에서는 임시 핸들러가 제거됩니다
```
## 사용 사례
이벤트 리스너는 다양한 목적으로 사용할 수 있습니다:
1. **로깅 및 모니터링**: Crew의 실행을 추적하고 중요한 이벤트를 기록합니다
2. **분석**: Crew의 성능과 동작에 대한 데이터를 수집합니다
3. **디버깅**: 특정 문제를 디버깅하기 위해 임시 리스너를 설정합니다
4. **통합**: CrewAI를 모니터링 플랫폼, 데이터베이스 또는 알림 서비스와 같은 외부 시스템과 연결합니다
5. **사용자 정의 동작**: 특정 이벤트에 따라 사용자 정의 동작을 트리거합니다
## 모범 사례
1. **핸들러를 가볍게 유지하세요**: 이벤트 핸들러는 경량이어야 하며, 블로킹 작업을 피해야 합니다.
2. **오류 처리**: 예외가 메인 실행에 영향을 주지 않도록 이벤트 핸들러에 적절한 오류 처리를 포함하세요.
3. **정리**: 리스너가 자원을 할당한다면, 이를 적절하게 정리하는지 확인하세요.
4. **선택적 리스닝**: 실제로 처리해야 하는 이벤트에만 리스닝하세요.
5. **테스트**: 이벤트 리스너가 예상대로 동작하는지 독립적으로 테스트하세요.
CrewAI의 이벤트 시스템을 활용하면 기능을 확장하고 기존 인프라와 원활하게 통합할 수 있습니다.

909
docs/ko/concepts/flows.mdx Normal file
View File

@@ -0,0 +1,909 @@
---
title: Flows
description: CrewAI Flows를 사용하여 AI 워크플로우를 생성하고 관리하는 방법을 알아보세요.
icon: arrow-progress
---
## 개요
CrewAI Flows는 AI 워크플로우의 생성 및 관리를 간소화하기 위해 설계된 강력한 기능입니다. Flows를 사용하면 개발자는 다양한 코딩 작업과 각 Crew를 효율적으로 결합하고 조정할 수 있어, 정교한 AI 자동화를 구축할 수 있는 견고한 프레임워크를 제공합니다.
Flows는 구조화된 이벤트 기반 워크플로우를 생성할 수 있게 해줍니다. 이를 통해 여러 작업을 원활하게 연결하고, 상태를 관리하며, AI 애플리케이션에서 실행 흐름을 제어할 수 있습니다. Flows를 사용하면 CrewAI의 전체 역량을 활용하는 다단계 프로세스를 손쉽게 설계하고 구현할 수 있습니다.
1. **간편한 워크플로우 생성**: 여러 Crew와 작업을 손쉽게 연결하여 복잡한 AI 워크플로우를 만듭니다.
2. **상태 관리**: Flows를 통해 워크플로우 내의 다양한 작업 간에 상태를 쉽고 효율적으로 관리 및 공유할 수 있습니다.
3. **이벤트 기반 아키텍처**: 이벤트 기반 모델을 기반으로 하여, 역동적이고 반응성 높은 워크플로우를 구현할 수 있습니다.
4. **유연한 제어 흐름**: 워크플로우 내에서 조건문, 반복문, 분기 등을 구현할 수 있습니다.
## 시작하기
OpenAI를 사용하여 한 작업에서 무작위 도시를 생성하고, 그 도시를 사용해 다른 작업에서 재미있는 사실을 생성하는 간단한 Flow를 만들어보겠습니다.
```python Code
from crewai.flow.flow import Flow, listen, start
from dotenv import load_dotenv
from litellm import completion
class ExampleFlow(Flow):
model = "gpt-4o-mini"
@start()
def generate_city(self):
print("Starting flow")
# Each flow state automatically gets a unique ID
print(f"Flow State ID: {self.state['id']}")
response = completion(
model=self.model,
messages=[
{
"role": "user",
"content": "Return the name of a random city in the world.",
},
],
)
random_city = response["choices"][0]["message"]["content"]
# Store the city in our state
self.state["city"] = random_city
print(f"Random City: {random_city}")
return random_city
@listen(generate_city)
def generate_fun_fact(self, random_city):
response = completion(
model=self.model,
messages=[
{
"role": "user",
"content": f"Tell me a fun fact about {random_city}",
},
],
)
fun_fact = response["choices"][0]["message"]["content"]
# Store the fun fact in our state
self.state["fun_fact"] = fun_fact
return fun_fact
flow = ExampleFlow()
flow.plot()
result = flow.kickoff()
print(f"Generated fun fact: {result}")
```
![Flow Visual image](/images/crewai-flow-1.png)
위 예제에서는 OpenAI를 사용하여 무작위 도시를 생성하고, 해당 도시에 대한 재미있는 사실을 생성하는 간단한 Flow를 만들었습니다. 이 Flow는 `generate_city`와 `generate_fun_fact`라는 두 가지 작업으로 구성되어 있습니다. `generate_city` 작업이 Flow의 시작점이며, `generate_fun_fact` 작업이 `generate_city` 작업의 출력을 감지합니다.
각 Flow 인스턴스는 상태(state)에 자동으로 고유 식별자(UUID)를 부여 받아, 흐름 실행을 추적하고 관리하는 데 도움이 됩니다. 상태에는 실행 중에 유지되는 추가 데이터(예: 생성된 도시와 재미있는 사실)도 저장할 수 있습니다.
Flow를 실행하면 다음과 같은 과정을 따릅니다:
1. 상태를 위한 고유 ID를 생성
2. 무작위 도시를 생성하여 상태에 저장
3. 해당 도시에 대한 재미있는 사실을 생성하여 상태에 저장
4. 결과를 콘솔에 출력
상태의 고유 ID와 저장된 데이터는 흐름 실행을 추적하고, 작업 간의 컨텍스트를 유지하는 데 유용합니다.
**참고:** OpenAI API 요청 인증을 위해 `OPENAI_API_KEY`를 `.env` 파일에 설정해야 합니다. 이 키는 필수입니다.
### @start()
`@start()` 데코레이터는 메서드를 Flow의 시작 지점으로 표시하는 데 사용됩니다. Flow가 시작되면 `@start()`로 데코레이트된 모든 메서드가 병렬로 실행됩니다. 하나의 Flow에서 여러 개의 start 메서드를 가질 수 있으며, Flow가 시작될 때 이들은 모두 실행됩니다.
### @listen()
`@listen()` 데코레이터는 Flow 내에서 다른 태스크의 출력을 수신하는 리스너로 메서드를 표시하는 데 사용됩니다. `@listen()`으로 데코레이션된 메서드는 지정된 태스크가 출력을 내보낼 때 실행됩니다. 이 메서드는 자신이 리스닝하고 있는 태스크의 출력을 인자로 접근할 수 있습니다.
#### 사용법
`@listen()` 데코레이터는 여러 가지 방법으로 사용할 수 있습니다:
1. **메서드 이름으로 리스닝하기**: 리스닝하고자 하는 메서드의 이름을 문자열로 전달할 수 있습니다. 해당 메서드가 완료되면, 리스너 메서드가 트리거됩니다.
```python Code
@listen("generate_city")
def generate_fun_fact(self, random_city):
# Implementation
```
2. **메서드 자체로 리스닝하기**: 메서드 자체를 전달할 수도 있습니다. 해당 메서드가 완료되면, 리스너 메서드가 트리거됩니다.
```python Code
@listen(generate_city)
def generate_fun_fact(self, random_city):
# Implementation
```
### Flow 출력
Flow의 출력을 접근하고 다루는 것은 AI 워크플로우를 더 큰 애플리케이션이나 시스템에 통합하는 데 필수적입니다. CrewAI Flow는 최종 출력물을 쉽게 가져오고, 중간 결과에 접근하며, Flow의 전체 상태를 관리할 수 있는 직관적인 메커니즘을 제공합니다.
#### 최종 출력값 가져오기
Flow를 실행하면, 최종 출력값은 마지막으로 완료된 메서드에 의해 결정됩니다. `kickoff()` 메서드는 이 마지막 메서드의 결과를 반환합니다.
최종 출력값을 확인하는 방법은 다음과 같습니다:
<CodeGroup>
```python Code
from crewai.flow.flow import Flow, listen, start
class OutputExampleFlow(Flow):
@start()
def first_method(self):
return "Output from first_method"
@listen(first_method)
def second_method(self, first_output):
return f"Second method received: {first_output}"
flow = OutputExampleFlow()
flow.plot("my_flow_plot")
final_output = flow.kickoff()
print("---- Final Output ----")
print(final_output)
```
```text Output
---- Final Output ----
Second method received: Output from first_method
```
</CodeGroup>
![Flow Visual image](/images/crewai-flow-2.png)
이 예제에서 `second_method`가 마지막으로 완료된 메서드이므로, 해당 메서드의 결과가 Flow의 최종 출력값이 됩니다.
`kickoff()` 메서드는 이 최종 출력값을 반환하며, 이 값은 콘솔에 출력됩니다.
`plot()` 메서드는 HTML 파일을 생성하며, 이를 통해 flow를 쉽게 이해할 수 있습니다.
#### 상태에 접근하고 업데이트하기
최종 출력을 가져오는 것 외에도, Flow 내에서 상태(state)에 접근하고 업데이트할 수 있습니다. 상태는 Flow의 다양한 메소드 간 데이터를 저장하고 공유하는 데 사용할 수 있습니다. Flow가 실행된 후에는, 실행 중에 추가되거나 업데이트된 정보를 조회하기 위해 상태에 접근할 수 있습니다.
다음은 상태를 업데이트하고 접근하는 방법의 예시입니다:
<CodeGroup>
```python Code
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel
class ExampleState(BaseModel):
counter: int = 0
message: str = ""
class StateExampleFlow(Flow[ExampleState]):
@start()
def first_method(self):
self.state.message = "Hello from first_method"
self.state.counter += 1
@listen(first_method)
def second_method(self):
self.state.message += " - updated by second_method"
self.state.counter += 1
return self.state.message
flow = StateExampleFlow()
flow.plot("my_flow_plot")
final_output = flow.kickoff()
print(f"Final Output: {final_output}")
print("Final State:")
print(flow.state)
```
```text Output
Final Output: Hello from first_method - updated by second_method
Final State:
counter=2 message='Hello from first_method - updated by second_method'
```
</CodeGroup>
![Flow Visual image](/images/crewai-flow-2.png)
이 예시에서 상태는 `first_method`와 `second_method` 모두에 의해 업데이트됩니다.
Flow가 실행된 후, 이러한 메소드들에 의해 수행된 업데이트 내용을 확인하려면 최종 상태에 접근할 수 있습니다.
최종 메소드의 출력이 반환되고 상태에 접근할 수 있도록 함으로써, CrewAI Flow는 AI 워크플로우의 결과를 더 큰 애플리케이션이나 시스템에 쉽게 통합할 수 있게 하며,
Flow 실행 과정 전반에 걸쳐 상태를 유지하고 접근하면서도 이를 용이하게 만듭니다.
## 플로우 상태 관리
상태를 효과적으로 관리하는 것은 신뢰할 수 있고 유지 보수가 용이한 AI 워크플로를 구축하는 데 매우 중요합니다. CrewAI 플로우는 비정형 및 정형 상태 관리를 위한 강력한 메커니즘을 제공하여, 개발자가 자신의 애플리케이션에 가장 적합한 접근 방식을 선택할 수 있도록 합니다.
### 비구조적 상태 관리
비구조적 상태 관리에서는 모든 상태가 `Flow` 클래스의 `state` 속성에 저장됩니다.
이 방식은 엄격한 스키마를 정의하지 않고도 개발자가 상태 속성을 즉석에서 추가하거나 수정할 수 있는 유연성을 제공합니다.
비구조적 상태에서도 CrewAI Flows는 각 상태 인스턴스에 대한 고유 식별자(UUID)를 자동으로 생성하고 유지합니다.
```python Code
from crewai.flow.flow import Flow, listen, start
class UnstructuredExampleFlow(Flow):
@start()
def first_method(self):
# The state automatically includes an 'id' field
print(f"State ID: {self.state['id']}")
self.state['counter'] = 0
self.state['message'] = "Hello from structured flow"
@listen(first_method)
def second_method(self):
self.state['counter'] += 1
self.state['message'] += " - updated"
@listen(second_method)
def third_method(self):
self.state['counter'] += 1
self.state['message'] += " - updated again"
print(f"State after third_method: {self.state}")
flow = UnstructuredExampleFlow()
flow.plot("my_flow_plot")
flow.kickoff()
```
![Flow Visual image](/images/crewai-flow-3.png)
**참고:** `id` 필드는 흐름의 실행 전체에 걸쳐 자동으로 생성되어 보존됩니다. 이를 직접 관리하거나 설정할 필요가 없으며, 새로운 데이터로 상태를 업데이트할 때도 자동으로 유지됩니다.
**핵심 포인트:**
- **유연성:** `self.state`에 미리 정해진 제약 없이 속성을 동적으로 추가할 수 있습니다.
- **단순성:** 상태 구조가 최소이거나 크게 달라지는 단순한 워크플로우에 이상적입니다.
### 구조화된 상태 관리
구조화된 상태 관리는 미리 정의된 스키마를 활용하여 워크플로 전반에 걸쳐 일관성과 타입 안전성을 보장합니다. Pydantic의 `BaseModel`과 같은 모델을 사용하면 상태의 정확한 형태를 정의할 수 있어, 개발 환경에서 더 나은 검증 및 자동 완성이 가능합니다.
CrewAI Flows의 각 상태는 인스턴스 추적 및 관리를 돕기 위해 자동으로 고유 식별자(UUID)를 할당받습니다. 이 ID는 Flow 시스템에 의해 자동으로 생성되고 관리됩니다.
```python Code
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel
class ExampleState(BaseModel):
# Note: 'id' field is automatically added to all states
counter: int = 0
message: str = ""
class StructuredExampleFlow(Flow[ExampleState]):
@start()
def first_method(self):
# Access the auto-generated ID if needed
print(f"State ID: {self.state.id}")
self.state.message = "Hello from structured flow"
@listen(first_method)
def second_method(self):
self.state.counter += 1
self.state.message += " - updated"
@listen(second_method)
def third_method(self):
self.state.counter += 1
self.state.message += " - updated again"
print(f"State after third_method: {self.state}")
flow = StructuredExampleFlow()
flow.kickoff()
```
![Flow Visual image](/images/crewai-flow-3.png)
**핵심 포인트:**
- **정의된 스키마:** `ExampleState`는 상태 구조를 명확히 정의하여 코드 가독성과 유지보수성을 향상시킵니다.
- **타입 안전성:** Pydantic을 활용하면 상태의 속성이 지정된 타입을 준수하도록 보장하여 런타임 오류를 줄일 수 있습니다.
- **자동 완성:** IDE에서 정의된 상태 모델을 기반으로 더 나은 자동 완성과 오류 확인이 가능합니다.
### 비구조적 상태 관리와 구조적 상태 관리 선택하기
- **비구조적 상태 관리를 사용할 때:**
- 워크플로의 상태가 단순하거나 매우 동적일 때.
- 엄격한 상태 정의보다 유연성이 우선시될 때.
- 스키마 정의의 오버헤드 없이 빠른 프로토타이핑이 필요할 때.
- **구조적 상태 관리를 사용할 때:**
- 워크플로에 잘 정의되고 일관된 상태 구조가 필요할 때.
- 애플리케이션의 신뢰성을 위해 타입 안전성과 검증이 중요할 때.
- 더 나은 개발자 경험을 위해 IDE의 자동 완성 및 타입 체크 기능을 활용하고자 할 때.
CrewAI Flows는 비구조적 및 구조적 상태 관리 옵션을 모두 제공함으로써, 개발자들이 다양한 애플리케이션 요구 사항에 맞춰 유연하면서도 견고한 AI 워크플로를 구축할 수 있도록 지원합니다.
## 플로우 지속성
@persist 데코레이터는 CrewAI 플로우에서 자동 상태 지속성을 활성화하여, 플로우 상태를 재시작이나 다른 워크플로우 실행 간에도 유지할 수 있도록 합니다. 이 데코레이터는 클래스 수준이나 메서드 수준 모두에 적용할 수 있어, 상태 지속성을 관리하는 데 유연성을 제공합니다.
### 클래스 레벨 영속성
클래스 레벨에서 @persist 데코레이터를 적용하면 모든 flow 메서드 상태가 자동으로 영속됩니다:
```python
@persist # 기본적으로 SQLiteFlowPersistence 사용
class MyFlow(Flow[MyState]):
@start()
def initialize_flow(self):
# 이 메서드는 상태가 자동으로 영속됩니다
self.state.counter = 1
print("Initialized flow. State ID:", self.state.id)
@listen(initialize_flow)
def next_step(self):
# 상태(self.state.id 포함)는 자동으로 다시 로드됩니다
self.state.counter += 1
print("Flow state is persisted. Counter:", self.state.counter)
```
### 메서드 수준의 지속성
더 세밀한 제어를 위해, @persist를 특정 메서드에 적용할 수 있습니다:
```python
class AnotherFlow(Flow[dict]):
@persist # Persists only this method's state
@start()
def begin(self):
if "runs" not in self.state:
self.state["runs"] = 0
self.state["runs"] += 1
print("Method-level persisted runs:", self.state["runs"])
```
### 작동 방식
1. **고유 상태 식별**
- 각 flow 상태에는 자동으로 고유한 UUID가 할당됩니다.
- 이 ID는 상태 업데이트 및 메소드 호출 시에도 유지됩니다.
- 구조화된 상태(Pydantic BaseModel)와 비구조화된 상태(딕셔너리) 모두를 지원합니다.
2. **기본 SQLite 백엔드**
- SQLiteFlowPersistence는 기본 저장 백엔드입니다.
- 상태는 자동으로 로컬 SQLite 데이터베이스에 저장됩니다.
- 데이터베이스 작업 실패 시 명확한 메시지를 제공하는 견고한 오류 처리가 제공됩니다.
3. **오류 처리**
- 데이터베이스 작업에 대한 포괄적인 오류 메시지가 제공됩니다.
- 저장 및 로드 중에 상태가 자동으로 검증됩니다.
- 지속성 작업에 문제가 발생할 경우 명확한 피드백을 제공합니다.
### 중요한 고려사항
- **상태 유형**: 구조화된(Pydantic BaseModel) 상태와 비구조화된(딕셔너리) 상태 모두 지원됩니다
- **자동 ID**: `id` 필드는 존재하지 않을 경우 자동으로 추가됩니다
- **상태 복구**: 실패하거나 재시작된 flow는 이전 상태를 자동으로 불러올 수 있습니다
- **커스텀 구현**: 특수한 저장소 요구 사항을 위해 직접 FlowPersistence 구현을 제공할 수 있습니다
### 기술적 이점
1. **저수준 접근을 통한 정밀한 제어**
- 고급 사용 사례를 위한 영속성 작업에 대한 직접 접근
- 메서드 수준의 영속성 데코레이터를 통한 세밀한 제어
- 내장된 상태 검사 및 디버깅 기능
- 상태 변경 및 영속성 작업에 대한 완전한 가시성
2. **향상된 신뢰성**
- 시스템 장애 또는 재시작 후 자동 상태 복구
- 데이터 무결성을 위한 트랜잭션 기반 상태 업데이트
- 명확한 오류 메시지를 제공하는 포괄적인 오류 처리
- 상태 저장 및 로드 작업 시 강력한 검증
3. **확장 가능한 아키텍처**
- FlowPersistence 인터페이스를 통한 사용자 정의 가능한 영속성 백엔드
- SQLite를 넘어선 특수 저장 솔루션 지원
- 구조화된(Pydantic) 상태와 비구조화(dict) 상태 모두와 호환
- 기존 CrewAI 흐름 패턴과의 원활한 통합
영속성 시스템의 아키텍처는 기술적 정밀성과 맞춤화 옵션을 강조하여, 개발자가 내장된 신뢰성 기능의 이점을 누리면서 상태 관리에 대한 완전한 제어권을 유지할 수 있게 해줍니다.
## 흐름 제어
### 조건부 로직: `or`
Flows에서 `or_` 함수는 여러 메서드를 감지하고 지정된 메서드 중 하나에서 출력이 발생하면 리스너 메서드를 트리거합니다.
<CodeGroup>
```python Code
from crewai.flow.flow import Flow, listen, or_, start
class OrExampleFlow(Flow):
@start()
def start_method(self):
return "Hello from the start method"
@listen(start_method)
def second_method(self):
return "Hello from the second method"
@listen(or_(start_method, second_method))
def logger(self, result):
print(f"Logger: {result}")
flow = OrExampleFlow()
flow.plot("my_flow_plot")
flow.kickoff()
```
```text Output
Logger: Hello from the start method
Logger: Hello from the second method
```
</CodeGroup>
![Flow Visual image](/images/crewai-flow-4.png)
이 Flow를 실행하면, `logger` 메서드는 `start_method` 또는 `second_method`의 출력에 의해 트리거됩니다.
`or_` 함수는 여러 메서드를 감지하고 지정된 메서드 중 하나에서 출력이 발생하면 리스너 메서드를 트리거하는 데 사용됩니다.
### 조건부 로직: `and`
Flows에서 `and_` 함수는 여러 메서드를 리슨하고, 지정된 모든 메서드가 출력을 발생시킬 때만 리스너 메서드가 트리거되도록 합니다.
<CodeGroup>
```python Code
from crewai.flow.flow import Flow, and_, listen, start
class AndExampleFlow(Flow):
@start()
def start_method(self):
self.state["greeting"] = "Hello from the start method"
@listen(start_method)
def second_method(self):
self.state["joke"] = "What do computers eat? Microchips."
@listen(and_(start_method, second_method))
def logger(self):
print("---- Logger ----")
print(self.state)
flow = AndExampleFlow()
flow.plot()
flow.kickoff()
```
```text Output
---- Logger ----
{'greeting': 'Hello from the start method', 'joke': 'What do computers eat? Microchips.'}
```
</CodeGroup>
![Flow Visual image](/images/crewai-flow-5.png)
이 Flow를 실행하면, `logger` 메서드는 `start_method`와 `second_method`가 모두 출력을 발생시켰을 때만 트리거됩니다.
`and_` 함수는 여러 메서드를 리슨하고, 지정된 모든 메서드가 출력을 발생시킬 때만 리스너 메서드를 트리거하는 데 사용됩니다.
### Router
Flows의 `@router()` 데코레이터를 사용하면 메서드의 출력값에 따라 조건부 라우팅 로직을 정의할 수 있습니다.
메서드의 출력에 따라 서로 다른 경로를 지정할 수 있어 실행 흐름을 동적으로 제어할 수 있습니다.
<CodeGroup>
```python Code
import random
from crewai.flow.flow import Flow, listen, router, start
from pydantic import BaseModel
class ExampleState(BaseModel):
success_flag: bool = False
class RouterFlow(Flow[ExampleState]):
@start()
def start_method(self):
print("Starting the structured flow")
random_boolean = random.choice([True, False])
self.state.success_flag = random_boolean
@router(start_method)
def second_method(self):
if self.state.success_flag:
return "success"
else:
return "failed"
@listen("success")
def third_method(self):
print("Third method running")
@listen("failed")
def fourth_method(self):
print("Fourth method running")
flow = RouterFlow()
flow.plot("my_flow_plot")
flow.kickoff()
```
```text Output
Starting the structured flow
Third method running
Fourth method running
```
</CodeGroup>
![Flow Visual image](/images/crewai-flow-6.png)
위 예제에서 `start_method`는 랜덤 불리언 값을 생성하여 state에 저장합니다.
`second_method`는 `@router()` 데코레이터를 사용해 불리언 값에 따라 조건부 라우팅 로직을 정의합니다.
불리언 값이 `True`이면 메서드는 `"success"`를 반환하고, `False`이면 `"failed"`를 반환합니다.
`third_method`와 `fourth_method`는 `second_method`의 출력값을 기다렸다가 반환된 값에 따라 실행됩니다.
이 Flow를 실행하면, `start_method`에서 생성된 랜덤 불리언 값에 따라 출력값이 달라집니다.
## 플로우에 에이전트 추가하기
에이전트는 플로우에 원활하게 통합할 수 있으며, 단순하고 집중된 작업 실행이 필요할 때 전체 Crew의 경량 대안으로 활용됩니다. 아래는 에이전트를 플로우 내에서 사용하여 시장 조사를 수행하는 예시입니다:
```python
import asyncio
from typing import Any, Dict, List
from crewai_tools import SerperDevTool
from pydantic import BaseModel, Field
from crewai.agent import Agent
from crewai.flow.flow import Flow, listen, start
# Define a structured output format
class MarketAnalysis(BaseModel):
key_trends: List[str] = Field(description="List of identified market trends")
market_size: str = Field(description="Estimated market size")
competitors: List[str] = Field(description="Major competitors in the space")
# Define flow state
class MarketResearchState(BaseModel):
product: str = ""
analysis: MarketAnalysis | None = None
# Create a flow class
class MarketResearchFlow(Flow[MarketResearchState]):
@start()
def initialize_research(self) -> Dict[str, Any]:
print(f"Starting market research for {self.state.product}")
return {"product": self.state.product}
@listen(initialize_research)
async def analyze_market(self) -> Dict[str, Any]:
# Create an Agent for market research
analyst = Agent(
role="Market Research Analyst",
goal=f"Analyze the market for {self.state.product}",
backstory="You are an experienced market analyst with expertise in "
"identifying market trends and opportunities.",
tools=[SerperDevTool()],
verbose=True,
)
# Define the research query
query = f"""
Research the market for {self.state.product}. Include:
1. Key market trends
2. Market size
3. Major competitors
Format your response according to the specified structure.
"""
# Execute the analysis with structured output format
result = await analyst.kickoff_async(query, response_format=MarketAnalysis)
if result.pydantic:
print("result", result.pydantic)
else:
print("result", result)
# Return the analysis to update the state
return {"analysis": result.pydantic}
@listen(analyze_market)
def present_results(self, analysis) -> None:
print("\nMarket Analysis Results")
print("=====================")
if isinstance(analysis, dict):
# If we got a dict with 'analysis' key, extract the actual analysis object
market_analysis = analysis.get("analysis")
else:
market_analysis = analysis
if market_analysis and isinstance(market_analysis, MarketAnalysis):
print("\nKey Market Trends:")
for trend in market_analysis.key_trends:
print(f"- {trend}")
print(f"\nMarket Size: {market_analysis.market_size}")
print("\nMajor Competitors:")
for competitor in market_analysis.competitors:
print(f"- {competitor}")
else:
print("No structured analysis data available.")
print("Raw analysis:", analysis)
# Usage example
async def run_flow():
flow = MarketResearchFlow()
flow.plot("MarketResearchFlowPlot")
result = await flow.kickoff_async(inputs={"product": "AI-powered chatbots"})
return result
# Run the flow
if __name__ == "__main__":
asyncio.run(run_flow())
```
![Flow Visual image](/images/crewai-flow-7.png)
이 예시는 플로우에서 에이전트를 사용할 때의 몇 가지 주요 기능을 보여줍니다:
1. **구조화된 출력**: Pydantic 모델을 사용하여 예상 출력 형식(`MarketAnalysis`)을 정의함으로써 플로우 전체에서 타입 안정성과 구조화된 데이터를 보장합니다.
2. **상태 관리**: 플로우 상태(`MarketResearchState`)는 단계 간의 컨텍스트를 유지하고 입력과 출력을 모두 저장합니다.
3. **도구 통합**: 에이전트는 기능 강화를 위해 `WebsiteSearchTool`과 같은 도구를 사용할 수 있습니다.
## Flows에 Crews 추가하기
CrewAI에서 여러 crews로 flow를 생성하는 것은 간단합니다.
다음 명령어를 실행하여 여러 crews가 포함된 flow를 생성하는 데 필요한 모든 스캐폴딩이 포함된 새 CrewAI 프로젝트를 생성할 수 있습니다.
```bash
crewai create flow name_of_flow
```
이 명령어는 필요한 폴더 구조를 갖춘 새 CrewAI 프로젝트를 생성합니다. 생성된 프로젝트에는 이미 동작 중인 미리 구축된 crew인 `poem_crew`가 포함되어 있습니다. 이 crew를 템플릿으로 사용하여 복사, 붙여넣기, 수정함으로써 다른 crew를 만들 수 있습니다.
### 폴더 구조
`crewai create flow name_of_flow` 명령을 실행하면 다음과 유사한 폴더 구조를 볼 수 있습니다:
| 디렉터리/파일 | 설명 |
| :--------------------- | :----------------------------------------------------------------- |
| `name_of_flow/` | flow의 루트 디렉터리입니다. |
| ├── `crews/` | 특정 crew에 대한 디렉터리를 포함합니다. |
| │ └── `poem_crew/` | "poem_crew"의 설정 및 스크립트가 포함된 디렉터리입니다. |
| │ ├── `config/` | "poem_crew"의 설정 파일 디렉터리입니다. |
| │ │ ├── `agents.yaml` | "poem_crew"의 agent를 정의하는 YAML 파일입니다. |
| │ │ └── `tasks.yaml` | "poem_crew"의 task를 정의하는 YAML 파일입니다. |
| │ ├── `poem_crew.py` | "poem_crew"의 기능을 위한 스크립트입니다. |
| ├── `tools/` | flow에서 사용되는 추가 도구를 위한 디렉터리입니다. |
| │ └── `custom_tool.py` | 사용자 정의 도구 구현 파일입니다. |
| ├── `main.py` | flow를 실행하는 메인 스크립트입니다. |
| ├── `README.md` | 프로젝트 설명 및 안내 문서입니다. |
| ├── `pyproject.toml` | 프로젝트의 종속성 및 설정을 위한 구성 파일입니다. |
| └── `.gitignore` | 버전 관리에서 무시할 파일과 디렉터리를 지정합니다. |
### 크루 빌드하기
`crews` 폴더에서는 여러 개의 크루를 정의할 수 있습니다. 각 크루는 자체 폴더를 가지며, 설정 파일과 크루 정의 파일을 포함합니다. 예를 들어, `poem_crew` 폴더에는 다음과 같은 파일이 있습니다:
- `config/agents.yaml`: 크루의 agent를 정의합니다.
- `config/tasks.yaml`: 크루의 task를 정의합니다.
- `poem_crew.py`: agent, task, 그리고 크루 자체를 포함한 crew 정의가 들어 있습니다.
`poem_crew`를 복사, 붙여넣기, 그리고 편집하여 다른 크루를 생성할 수 있습니다.
### `main.py`에서 Crew 연결하기
`main.py` 파일은 flow를 생성하고 crew들을 서로 연결하는 곳입니다. `Flow` 클래스를 사용하고, `@start`와 `@listen` 데코레이터를 사용하여 실행 흐름을 지정하여 flow를 정의할 수 있습니다.
다음은 `main.py` 파일에서 `poem_crew`를 연결하는 예제입니다:
```python Code
#!/usr/bin/env python
from random import randint
from pydantic import BaseModel
from crewai.flow.flow import Flow, listen, start
from .crews.poem_crew.poem_crew import PoemCrew
class PoemState(BaseModel):
sentence_count: int = 1
poem: str = ""
class PoemFlow(Flow[PoemState]):
@start()
def generate_sentence_count(self):
print("Generating sentence count")
self.state.sentence_count = randint(1, 5)
@listen(generate_sentence_count)
def generate_poem(self):
print("Generating poem")
result = PoemCrew().crew().kickoff(inputs={"sentence_count": self.state.sentence_count})
print("Poem generated", result.raw)
self.state.poem = result.raw
@listen(generate_poem)
def save_poem(self):
print("Saving poem")
with open("poem.txt", "w") as f:
f.write(self.state.poem)
def kickoff():
poem_flow = PoemFlow()
poem_flow.kickoff()
def plot():
poem_flow = PoemFlow()
poem_flow.plot("PoemFlowPlot")
if __name__ == "__main__":
kickoff()
plot()
```
이 예제에서 `PoemFlow` 클래스는 문장 수를 생성하고, `PoemCrew`를 사용하여 시를 생성한 후, 시를 파일에 저장하는 flow를 정의합니다. 이 flow는 `kickoff()` 메서드를 호출하여 시작됩니다. `plot()` 메서드로 PoemFlowPlot이 생성됩니다.
![Flow Visual image](/images/crewai-flow-8.png)
### 플로우 실행하기
(선택 사항) 플로우를 실행하기 전에, 다음 명령어를 실행하여 의존성을 설치할 수 있습니다:
```bash
crewai install
```
모든 의존성이 설치되면, 다음 명령어를 실행하여 가상 환경을 활성화해야 합니다:
```bash
source .venv/bin/activate
```
가상 환경을 활성화한 후, 아래 명령어 중 하나를 실행하여 플로우를 실행할 수 있습니다:
```bash
crewai flow kickoff
```
또는
```bash
uv run kickoff
```
플로우가 실행되면, 콘솔에서 출력을 확인할 수 있습니다.
## 플롯 플로우
AI 워크플로우를 시각화하면 플로우의 구조와 실행 경로에 대한 중요한 인사이트를 얻을 수 있습니다. CrewAI는 플로우의 인터랙티브 플롯을 생성할 수 있는 강력한 시각화 도구를 제공하여 AI 워크플로우를 보다 쉽게 이해하고 최적화할 수 있도록 도와줍니다.
### 플롯(Plots)이란 무엇인가요?
CrewAI에서 플롯(Plots)은 AI 워크플로우의 그래픽 표현입니다. 플롯은 다양한 태스크와 그들의 연결, 그리고 태스크 간 데이터 흐름을 시각적으로 보여줍니다. 이러한 시각화는 작업 순서를 이해하고, 병목 현상을 식별하며, 워크플로우 논리가 기대에 부합하는지 확인하는 데 도움이 됩니다.
### 플롯 생성 방법
CrewAI는 플로우의 플롯을 생성하는 두 가지 편리한 방법을 제공합니다:
#### 옵션 1: `plot()` 메서드 사용하기
flow 인스턴스와 직접 작업하는 경우, flow 객체에서 `plot()` 메서드를 호출하여 플롯을 생성할 수 있습니다. 이 메서드는 flow의 인터랙티브 플롯이 포함된 HTML 파일을 생성합니다.
```python Code
# Assuming you have a flow instance
flow.plot("my_flow_plot")
```
이렇게 하면 현재 디렉토리에 `my_flow_plot.html`이라는 파일이 생성됩니다. 이 파일을 웹 브라우저에서 열어 인터랙티브 플롯을 볼 수 있습니다.
#### 옵션 2: 커맨드 라인 사용
구조화된 CrewAI 프로젝트 내에서 작업 중이라면 커맨드 라인을 사용하여 플롯을 생성할 수 있습니다. 이는 전체 플로우 설정을 시각화하고자 하는 대규모 프로젝트에서 특히 유용합니다.
```bash
crewai flow plot
```
이 명령은 플로우의 플롯이 포함된 HTML 파일을 생성하며, 이는 `plot()` 메서드와 유사합니다. 파일은 프로젝트 디렉터리에 저장되며, 웹 브라우저에서 열어 플로우를 탐색할 수 있습니다.
### 플롯 이해하기
생성된 플롯은 flow 내의 작업을 나타내는 노드와 실행 흐름을 나타내는 방향성이 있는 엣지를 표시합니다. 플롯은 인터랙티브하게 제공되어, 확대/축소를 하거나 노드 위에 마우스를 올려 추가 정보를 볼 수 있습니다.
flow를 시각화하면 워크플로의 구조를 더욱 명확하게 이해할 수 있어 디버깅, 최적화, 그리고 AI 프로세스를 다른 사람들에게 설명하는 데 도움이 됩니다.
### 결론
플로우를 시각적으로 표현하는 것은 CrewAI의 강력한 기능으로, 복잡한 AI 워크플로우를 설계하고 관리하는 능력을 크게 향상시켜줍니다. `plot()` 메서드나 커맨드 라인 중 어떤 방법을 사용하더라도, 플롯을 생성하면 워크플로우의 시각적 표현을 얻을 수 있어 개발과 발표 모두에 도움이 됩니다.
## 다음 단계
추가적인 flow 예제를 살펴보고 싶으시다면, 저희 examples 레포지토리에서 다양한 추천 예제를 확인하실 수 있습니다. 아래는 각각 고유한 사용 사례를 보여주는 네 가지 구체적인 flow 예제로, 현재 문제 유형에 맞는 예시를 찾는 데 도움이 될 것입니다:
1. **이메일 자동 응답자 Flow**: 이 예제는 백그라운드 작업이 계속 실행되면서 이메일 응답을 자동화하는 무한 루프를 보여줍니다. 수동 개입 없이 반복적으로 수행해야 하는 작업에 적합한 사용 사례입니다. [예제 보기](https://github.com/crewAIInc/crewAI-examples/tree/main/email_auto_responder_flow)
2. **리드 점수 Flow**: 이 flow 예제는 human-in-the-loop 피드백을 추가하고 router를 사용하여 다양한 조건 분기를 처리하는 방법을 보여줍니다. 워크플로우에 동적 의사결정과 인간의 관리·감독을 통합하는 방식을 확인할 수 있는 훌륭한 예시입니다. [예제 보기](https://github.com/crewAIInc/crewAI-examples/tree/main/lead-score-flow)
3. **책 집필 Flow**: 이 예제는 여러 crew를 연속적으로 연결하는 데 탁월하며, 한 crew의 출력 결과가 다른 crew에 의해 사용됩니다. 구체적으로, 한 crew가 전체 책의 개요를 작성하고, 다른 crew가 그 개요를 바탕으로 챕터를 생성합니다. 결국 모든 것이 연결되어 완성된 책이 만들어집니다. 여러 작업 간 조율이 필요한 복잡한 다단계 프로세스에 적합한 flow입니다. [예제 보기](https://github.com/crewAIInc/crewAI-examples/tree/main/write_a_book_with_flows)
4. **미팅 어시스턴트 Flow**: 이 flow는 하나의 이벤트가 여러 후속 작업을 트리거하도록 브로드캐스트하는 방법을 보여줍니다. 예를 들어, 미팅이 끝난 후 Trello 보드를 업데이트하고 Slack 메시지를 전송하며 결과를 저장할 수 있습니다. 하나의 이벤트로부터 여러 결과를 처리하는 좋은 예시로, 포괄적인 작업 관리 및 알림 시스템에 이상적입니다. [예제 보기](https://github.com/crewAIInc/crewAI-examples/tree/main/meeting_assistant_flow)
이 예제들을 통해 반복되는 작업 자동화부터 동적 의사결정과 인간 피드백이 포함된 복잡한 다단계 프로세스 관리에 이르기까지 다양한 사용 사례에서 CrewAI Flows를 어떻게 활용할 수 있는지에 대한 통찰력을 얻을 수 있습니다.
또한, 아래의 CrewAI에서 flows를 사용하는 방법에 대한 YouTube 영상을 확인해보세요!
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/MTb5my6VOT8"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
## 플로우 실행하기
플로우를 실행하는 방법에는 두 가지가 있습니다:
### Flow API 사용하기
플로우를 프로그래밍 방식으로 실행하려면, 플로우 클래스의 인스턴스를 생성하고 `kickoff()` 메서드를 호출하면 됩니다:
```python
flow = ExampleFlow()
result = flow.kickoff()
```
### CLI 사용하기
버전 0.103.0부터 `crewai run` 명령어를 사용하여 flow를 실행할 수 있습니다:
```shell
crewai run
```
이 명령어는 프로젝트가 pyproject.toml의 `type = "flow"` 설정을 기반으로 flow인지 자동으로 감지하여 해당 방식으로 실행합니다. 명령줄에서 flow를 실행하는 권장 방법입니다.
하위 호환성을 위해 다음 명령어도 사용할 수 있습니다:
```shell
crewai flow kickoff
```
하지만 `crewai run` 명령어가 이제 crew와 flow 모두에 작동하므로 더욱 선호되는 방법입니다.

View File

@@ -0,0 +1,961 @@
---
title: Knowledge
description: CrewAI에서 knowledge란 무엇이며 어떻게 사용하는지 알아봅니다.
icon: book
---
## 개요
Knowledge in CrewAI는 AI 에이전트가 작업 중에 외부 정보 소스에 접근하고 이를 활용할 수 있게 해주는 강력한 시스템입니다.
이는 에이전트에게 작업할 때 참고할 수 있는 참조 도서관을 제공하는 것과 같습니다.
<Info>
Knowledge를 사용함으로써 얻는 주요 이점:
- 에이전트에게 도메인 특화 정보를 제공
- 실제 데이터를 통한 의사 결정 지원
- 대화 전체의 맥락 유지
- 응답을 사실 기반 정보에 근거
</Info>
## 빠른 시작 예제
<Tip>
파일 기반 Knowledge Sources의 경우, 프로젝트의 루트에 `knowledge` 디렉토리를 생성하고 그 안에 파일을 배치해야 합니다.
또한, 소스를 생성할 때는 `knowledge` 디렉토리로부터의 상대 경로를 사용하세요.
</Tip>
### 기본 문자열 지식 예제
```python Code
from crewai import Agent, Task, Crew, Process, LLM
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Create a knowledge source
content = "Users name is John. He is 30 years old and lives in San Francisco."
string_source = StringKnowledgeSource(content=content)
# Create an LLM with a temperature of 0 to ensure deterministic outputs
llm = LLM(model="gpt-4o-mini", temperature=0)
# Create an agent with the knowledge store
agent = Agent(
role="About User",
goal="You know everything about the user.",
backstory="You are a master at understanding people and their preferences.",
verbose=True,
allow_delegation=False,
llm=llm,
)
task = Task(
description="Answer the following questions about the user: {question}",
expected_output="An answer to the question.",
agent=agent,
)
crew = Crew(
agents=[agent],
tasks=[task],
verbose=True,
process=Process.sequential,
knowledge_sources=[string_source], # Enable knowledge by adding the sources here
)
result = crew.kickoff(inputs={"question": "What city does John live in and how old is he?"})
```
### 웹 콘텐츠 지식 예시
<Note>
다음 예시가 작동하려면 `docling`을 설치해야 합니다: `uv add docling`
</Note>
```python Code
from crewai import LLM, Agent, Crew, Process, Task
from crewai.knowledge.source.crew_docling_source import CrewDoclingSource
# Create a knowledge source from web content
content_source = CrewDoclingSource(
file_paths=[
"https://lilianweng.github.io/posts/2024-11-28-reward-hacking",
"https://lilianweng.github.io/posts/2024-07-07-hallucination",
],
)
# Create an LLM with a temperature of 0 to ensure deterministic outputs
llm = LLM(model="gpt-4o-mini", temperature=0)
# Create an agent with the knowledge store
agent = Agent(
role="About papers",
goal="You know everything about the papers.",
backstory="You are a master at understanding papers and their content.",
verbose=True,
allow_delegation=False,
llm=llm,
)
task = Task(
description="Answer the following questions about the papers: {question}",
expected_output="An answer to the question.",
agent=agent,
)
crew = Crew(
agents=[agent],
tasks=[task],
verbose=True,
process=Process.sequential,
knowledge_sources=[content_source],
)
result = crew.kickoff(
inputs={"question": "What is the reward hacking paper about? Be sure to provide sources."}
)
```
## 지원되는 Knowledge Sources
CrewAI는 다양한 유형의 knowledge source를 기본적으로 지원합니다:
<CardGroup cols={2}>
<Card title="텍스트 소스" icon="text">
- 원시 문자열
- 텍스트 파일 (.txt)
- PDF 문서
</Card>
<Card title="구조화된 데이터" icon="table">
- CSV 파일
- 엑셀 스프레드시트
- JSON 문서
</Card>
</CardGroup>
### 텍스트 파일 지식 소스
```python
from crewai.knowledge.source.text_file_knowledge_source import TextFileKnowledgeSource
text_source = TextFileKnowledgeSource(
file_paths=["document.txt", "another.txt"]
)
```
### PDF 지식 소스
```python
from crewai.knowledge.source.pdf_knowledge_source import PDFKnowledgeSource
pdf_source = PDFKnowledgeSource(
file_paths=["document.pdf", "another.pdf"]
)
```
### CSV 지식 소스
```python
from crewai.knowledge.source.csv_knowledge_source import CSVKnowledgeSource
csv_source = CSVKnowledgeSource(
file_paths=["data.csv"]
)
```
### Excel 지식 소스
```python
from crewai.knowledge.source.excel_knowledge_source import ExcelKnowledgeSource
excel_source = ExcelKnowledgeSource(
file_paths=["spreadsheet.xlsx"]
)
```
### JSON 지식 소스
```python
from crewai.knowledge.source.json_knowledge_source import JSONKnowledgeSource
json_source = JSONKnowledgeSource(
file_paths=["data.json"]
)
```
<Note>
반드시 ./knowledge 폴더를 생성해 주세요. 모든 소스 파일(예: .txt, .pdf, .xlsx, .json)은 중앙 집중식 관리를 위해 이 폴더에 보관해야 합니다.
</Note>
## Agent vs Crew Knowledge: 완벽 가이드
<Info>
**Knowledge 레벨 이해하기**: CrewAI는 agent와 crew 두 가지 레벨의 knowledge를 지원합니다. 이 섹션에서는 각각이 어떻게 동작하는지, 언제 초기화되는지, 그리고 dependency에 대한 일반적인 오해를 명확히 설명합니다.
</Info>
### 지식 초기화가 실제로 작동하는 방식
다음은 지식을 사용할 때 실제로 발생하는 일입니다:
#### 에이전트 수준 지식 (독립적)
```python
from crewai import Agent, Task, Crew
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Agent with its own knowledge - NO crew knowledge needed
specialist_knowledge = StringKnowledgeSource(
content="Specialized technical information for this agent only"
)
specialist_agent = Agent(
role="Technical Specialist",
goal="Provide technical expertise",
backstory="Expert in specialized technical domains",
knowledge_sources=[specialist_knowledge] # Agent-specific knowledge
)
task = Task(
description="Answer technical questions",
agent=specialist_agent,
expected_output="Technical answer"
)
# No crew-level knowledge required
crew = Crew(
agents=[specialist_agent],
tasks=[task]
)
result = crew.kickoff() # Agent knowledge works independently
```
#### `crew.kickoff()` 중에 일어나는 일
`crew.kickoff()`를 호출하면 다음과 같은 순서로 동작합니다:
```python
# During kickoff
for agent in self.agents:
agent.crew = self # Agent gets reference to crew
agent.set_knowledge(crew_embedder=self.embedder) # Agent knowledge initialized
agent.create_agent_executor()
```
#### 스토리지 독립성
각 knowledge 수준은 독립적인 스토리지 컬렉션을 사용합니다:
```python
# Agent knowledge storage
agent_collection_name = agent.role # e.g., "Technical Specialist"
# Crew knowledge storage
crew_collection_name = "crew"
# Both stored in same ChromaDB instance but different collections
# Path: ~/.local/share/CrewAI/{project}/knowledge/
# ├── crew/ # Crew knowledge collection
# ├── Technical Specialist/ # Agent knowledge collection
# └── Another Agent Role/ # Another agent's collection
```
### 전체 작동 예제
#### 예시 1: Agent-Only Knowledge
```python
from crewai import Agent, Task, Crew
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Agent-specific knowledge
agent_knowledge = StringKnowledgeSource(
content="Agent-specific information that only this agent needs"
)
agent = Agent(
role="Specialist",
goal="Use specialized knowledge",
backstory="Expert with specific knowledge",
knowledge_sources=[agent_knowledge],
embedder={ # Agent can have its own embedder
"provider": "openai",
"config": {"model": "text-embedding-3-small"}
}
)
task = Task(
description="Answer using your specialized knowledge",
agent=agent,
expected_output="Answer based on agent knowledge"
)
# No crew knowledge needed
crew = Crew(agents=[agent], tasks=[task])
result = crew.kickoff() # Works perfectly
```
#### 예시 2: 에이전트 및 크루 지식 모두
```python
# Crew-wide knowledge (shared by all agents)
crew_knowledge = StringKnowledgeSource(
content="Company policies and general information for all agents"
)
# Agent-specific knowledge
specialist_knowledge = StringKnowledgeSource(
content="Technical specifications only the specialist needs"
)
specialist = Agent(
role="Technical Specialist",
goal="Provide technical expertise",
backstory="Technical expert",
knowledge_sources=[specialist_knowledge] # Agent-specific
)
generalist = Agent(
role="General Assistant",
goal="Provide general assistance",
backstory="General helper"
# No agent-specific knowledge
)
crew = Crew(
agents=[specialist, generalist],
tasks=[...],
knowledge_sources=[crew_knowledge] # Crew-wide knowledge
)
# Result:
# - specialist gets: crew_knowledge + specialist_knowledge
# - generalist gets: crew_knowledge only
```
#### 예제 3: 서로 다른 지식을 가진 다중 에이전트
```python
# Different knowledge for different agents
sales_knowledge = StringKnowledgeSource(content="Sales procedures and pricing")
tech_knowledge = StringKnowledgeSource(content="Technical documentation")
support_knowledge = StringKnowledgeSource(content="Support procedures")
sales_agent = Agent(
role="Sales Representative",
knowledge_sources=[sales_knowledge],
embedder={"provider": "openai", "config": {"model": "text-embedding-3-small"}}
)
tech_agent = Agent(
role="Technical Expert",
knowledge_sources=[tech_knowledge],
embedder={"provider": "ollama", "config": {"model": "mxbai-embed-large"}}
)
support_agent = Agent(
role="Support Specialist",
knowledge_sources=[support_knowledge]
# Will use crew embedder as fallback
)
crew = Crew(
agents=[sales_agent, tech_agent, support_agent],
tasks=[...],
embedder={ # Fallback embedder for agents without their own
"provider": "google",
"config": {"model": "text-embedding-004"}
}
)
# Each agent gets only their specific knowledge
# Each can use different embedding providers
```
<Tip>
벡터 데이터베이스에서 도구를 사용한 검색과 달리, 사전에 지식이 탑재된 에이전트는 검색 퍼소나나 태스크가 필요하지 않습니다.
에이전트나 crew가 동작하는 데 필요한 관련 지식 소스만 추가하면 됩니다.
지식 소스는 에이전트 또는 crew 레벨에 추가할 수 있습니다.
crew 레벨 지식 소스는 **crew 내 모든 에이전트**가 사용하게 됩니다.
에이전트 레벨 지식 소스는 해당 지식이 사전 탑재된 **특정 에이전트**만 사용하게 됩니다.
</Tip>
## Knowledge 구성
crew 또는 agent에 대해 knowledge 구성을 할 수 있습니다.
```python Code
from crewai.knowledge.knowledge_config import KnowledgeConfig
knowledge_config = KnowledgeConfig(results_limit=10, score_threshold=0.5)
agent = Agent(
...
knowledge_config=knowledge_config
)
```
<Tip>
`results_limit`: 반환할 관련 문서의 개수입니다. 기본값은 3입니다.
`score_threshold`: 문서가 관련성이 있다고 간주되기 위한 최소 점수입니다. 기본값은 0.35입니다.
</Tip>
## 지원되는 Knowledge 매개변수
<ParamField body="sources" type="List[BaseKnowledgeSource]" required="Yes">
저장 및 쿼리할 콘텐츠를 제공하는 knowledge source들의 리스트입니다. PDF, CSV, Excel, JSON, 텍스트 파일 또는 문자열 콘텐츠를 포함할 수 있습니다.
</ParamField>
<ParamField body="collection_name" type="str">
knowledge가 저장될 컬렉션의 이름입니다. 서로 다른 knowledge 세트를 식별하는 데 사용됩니다. 제공하지 않을 경우 기본값은 "knowledge"입니다.
</ParamField>
<ParamField body="storage" type="Optional[KnowledgeStorage]">
knowledge가 저장되고 검색되는 방식을 관리하기 위한 커스텀 저장소 구성입니다. 별도로 제공하지 않는 경우 기본 storage가 생성됩니다.
</ParamField>
## 지식 저장 투명성
<Info>
**지식 저장 이해하기**: CrewAI는 ChromaDB를 사용하여 벡터 저장소에 지식 소스를 플랫폼별 디렉토리에 자동으로 저장합니다. 이러한 위치와 기본값을 이해하면 프로덕션 배포, 디버깅, 저장소 관리에 도움이 됩니다.
</Info>
### CrewAI가 Knowledge 파일을 저장하는 위치
기본적으로 CrewAI는 memory와 동일한 저장 시스템을 사용하여, knowledge를 플랫폼별 디렉터리에 저장합니다.
#### 플랫폼별 기본 저장 위치
**macOS:**
```
~/Library/Application Support/CrewAI/{project_name}/
└── knowledge/ # Knowledge ChromaDB files
├── chroma.sqlite3 # ChromaDB metadata
├── {collection_id}/ # Vector embeddings
└── knowledge_{collection}/ # Named collections
```
**Linux:**
```
~/.local/share/CrewAI/{project_name}/
└── knowledge/
├── chroma.sqlite3
├── {collection_id}/
└── knowledge_{collection}/
```
**Windows:**
```
C:\Users\{username}\AppData\Local\CrewAI\{project_name}\
└── knowledge\
├── chroma.sqlite3
├── {collection_id}\
└── knowledge_{collection}\
```
### 지식 저장 위치 찾기
CrewAI가 지식 파일을 저장하는 위치를 정확히 확인하려면:
```python
from crewai.utilities.paths import db_storage_path
import os
# Get the knowledge storage path
knowledge_path = os.path.join(db_storage_path(), "knowledge")
print(f"Knowledge storage location: {knowledge_path}")
# List knowledge collections and files
if os.path.exists(knowledge_path):
print("\nKnowledge storage contents:")
for item in os.listdir(knowledge_path):
item_path = os.path.join(knowledge_path, item)
if os.path.isdir(item_path):
print(f"📁 Collection: {item}/")
# Show collection contents
try:
for subitem in os.listdir(item_path):
print(f" └── {subitem}")
except PermissionError:
print(f" └── (permission denied)")
else:
print(f"📄 {item}")
else:
print("No knowledge storage found yet.")
```
### 지식 저장 위치 제어
#### 옵션 1: 환경 변수 (권장)
```python
import os
from crewai import Crew
# Set custom storage location for all CrewAI data
os.environ["CREWAI_STORAGE_DIR"] = "./my_project_storage"
# All knowledge will now be stored in ./my_project_storage/knowledge/
crew = Crew(
agents=[...],
tasks=[...],
knowledge_sources=[...]
)
```
#### 옵션 2: 사용자 지정 Knowledge 저장소
```python
from crewai.knowledge.storage.knowledge_storage import KnowledgeStorage
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Create custom storage with specific embedder
custom_storage = KnowledgeStorage(
embedder={
"provider": "ollama",
"config": {"model": "mxbai-embed-large"}
},
collection_name="my_custom_knowledge"
)
# Use with knowledge sources
knowledge_source = StringKnowledgeSource(
content="Your knowledge content here"
)
knowledge_source.storage = custom_storage
```
#### 옵션 3: 프로젝트별 Knowledge 저장소
```python
import os
from pathlib import Path
# Store knowledge in project directory
project_root = Path(__file__).parent
knowledge_dir = project_root / "knowledge_storage"
os.environ["CREWAI_STORAGE_DIR"] = str(knowledge_dir)
# Now all knowledge will be stored in your project directory
```
### 기본 임베딩 제공자 동작
<Info>
**기본 임베딩 제공자**: CrewAI는 다른 LLM 제공자를 사용할 때도 지식 저장을 위해 기본적으로 OpenAI 임베딩(`text-embedding-3-small`)을 사용합니다. 설정에 맞게 쉽게 이 옵션을 커스터마이즈할 수 있습니다.
</Info>
#### 기본 동작 이해하기
```python
from crewai import Agent, Crew, LLM
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# When using Claude as your LLM...
agent = Agent(
role="Researcher",
goal="Research topics",
backstory="Expert researcher",
llm=LLM(provider="anthropic", model="claude-3-sonnet") # Using Claude
)
# CrewAI will still use OpenAI embeddings by default for knowledge
# This ensures consistency but may not match your LLM provider preference
knowledge_source = StringKnowledgeSource(content="Research data...")
crew = Crew(
agents=[agent],
tasks=[...],
knowledge_sources=[knowledge_source]
# Default: Uses OpenAI embeddings even with Claude LLM
)
```
#### 지식 임베딩 공급자 사용자 정의
```python
# Option 1: Voyage AI 사용 (Claude 사용자에게 Anthropic이 권장)
crew = Crew(
agents=[agent],
tasks=[...],
knowledge_sources=[knowledge_source],
embedder={
"provider": "voyageai", # Claude 사용자에게 권장
"config": {
"api_key": "your-voyage-api-key",
"model": "voyage-3" # 최고 품질을 원하면 "voyage-3-large" 사용
}
}
)
# Option 2: 로컬 임베딩 사용 (외부 API 호출 없음)
crew = Crew(
agents=[agent],
tasks=[...],
knowledge_sources=[knowledge_source],
embedder={
"provider": "ollama",
"config": {
"model": "mxbai-embed-large",
"url": "http://localhost:11434/api/embeddings"
}
}
)
# Option 3: 에이전트 수준의 임베딩 사용자 정의
agent = Agent(
role="Researcher",
goal="Research topics",
backstory="Expert researcher",
knowledge_sources=[knowledge_source],
embedder={
"provider": "google",
"config": {
"model": "models/text-embedding-004",
"api_key": "your-google-key"
}
}
)
```
#### Azure OpenAI 임베딩 구성
Azure OpenAI 임베딩을 사용할 때:
1. 먼저 Azure 플랫폼에 임베딩 모델을 배포했는지 확인하세요.
2. 그런 다음 다음과 같은 구성을 사용해야 합니다:
```python
agent = Agent(
role="Researcher",
goal="Research topics",
backstory="Expert researcher",
knowledge_sources=[knowledge_source],
embedder={
"provider": "azure",
"config": {
"api_key": "your-azure-api-key",
"model": "text-embedding-ada-002", # change to the model you are using and is deployed in Azure
"api_base": "https://your-azure-endpoint.openai.azure.com/",
"api_version": "2024-02-01"
}
}
)
```
## 고급 기능
### 쿼리 리라이팅
CrewAI는 지식 검색을 최적화하기 위해 지능형 쿼리 리라이팅 메커니즘을 구현합니다. 에이전트가 지식 소스를 검색해야 할 때, 원시 태스크 프롬프트는 자동으로 더 효과적인 검색 쿼리로 변환됩니다.
#### 쿼리 재작성 방식
1. 에이전트가 knowledge 소스를 사용할 수 있을 때 작업을 실행하면 `_get_knowledge_search_query` 메서드가 트리거됩니다.
2. 에이전트의 LLM을 사용하여 원래 작업 프롬프트를 최적화된 검색 쿼리로 변환합니다.
3. 이 최적화된 쿼리는 knowledge 소스에서 관련 정보를 검색하는 데 사용됩니다.
#### 쿼리 리라이트(Query Rewriting)의 이점
<CardGroup cols={2}>
<Card title="향상된 검색 정확도" icon="bullseye-arrow">
주요 개념에 집중하고 불필요한 내용을 제거함으로써, 쿼리 리라이트는 보다 관련성 높은 정보를 검색할 수 있게 도와줍니다.
</Card>
<Card title="컨텍스트 인식" icon="brain">
리라이트된 쿼리는 벡터 데이터베이스 검색을 위해 더욱 구체적이고 컨텍스트를 인식할 수 있도록 설계되어 있습니다.
</Card>
</CardGroup>
#### 예시
```python
# Original task prompt
task_prompt = "Answer the following questions about the user's favorite movies: What movie did John watch last week? Format your answer in JSON."
# Behind the scenes, this might be rewritten as:
rewritten_query = "What movies did John watch last week?"
```
재작성된 쿼리는 핵심 정보 요구에 더 집중하며, 출력 형식에 대한 불필요한 지시사항을 제거합니다.
<Tip>
이 메커니즘은 완전히 자동으로 동작하며 사용자가 별도의 설정을 할 필요가 없습니다. agent의 LLM을 사용하여 쿼리 재작성을 수행하므로, 더 강력한 LLM을 사용할 경우 재작성된 쿼리의 품질이 향상될 수 있습니다.
</Tip>
### Knowledge 이벤트
CrewAI는 knowledge 검색 과정에서 이벤트를 발생시키며, 이벤트 시스템을 사용하여 이를 감지할 수 있습니다. 이러한 이벤트를 통해 에이전트가 knowledge를 어떻게 검색하고 사용하는지 모니터링, 디버깅, 분석할 수 있습니다.
#### 사용 가능한 Knowledge 이벤트
- **KnowledgeRetrievalStartedEvent**: 에이전트가 소스에서 knowledge를 검색하기 시작할 때 발생
- **KnowledgeRetrievalCompletedEvent**: knowledge 검색이 완료되었을 때 발생하며, 사용된 쿼리와 검색된 콘텐츠를 포함
- **KnowledgeQueryStartedEvent**: knowledge 소스에 쿼리를 시작할 때 발생
- **KnowledgeQueryCompletedEvent**: 쿼리가 성공적으로 완료되었을 때 발생
- **KnowledgeQueryFailedEvent**: knowledge 소스에 대한 쿼리가 실패했을 때 발생
- **KnowledgeSearchQueryFailedEvent**: 검색 쿼리가 실패했을 때 발생
#### 예시: Knowledge Retrieval 모니터링
```python
from crewai.utilities.events import (
KnowledgeRetrievalStartedEvent,
KnowledgeRetrievalCompletedEvent,
)
from crewai.utilities.events.base_event_listener import BaseEventListener
class KnowledgeMonitorListener(BaseEventListener):
def setup_listeners(self, crewai_event_bus):
@crewai_event_bus.on(KnowledgeRetrievalStartedEvent)
def on_knowledge_retrieval_started(source, event):
print(f"Agent '{event.agent.role}' started retrieving knowledge")
@crewai_event_bus.on(KnowledgeRetrievalCompletedEvent)
def on_knowledge_retrieval_completed(source, event):
print(f"Agent '{event.agent.role}' completed knowledge retrieval")
print(f"Query: {event.query}")
print(f"Retrieved {len(event.retrieved_knowledge)} knowledge chunks")
# Create an instance of your listener
knowledge_monitor = KnowledgeMonitorListener()
```
이벤트 사용에 대한 자세한 내용은 [이벤트 리스너](https://docs.crewai.com/concepts/event-listener) 문서를 참고하세요.
### 맞춤형 지식 소스
CrewAI를 사용하면 `BaseKnowledgeSource` 클래스를 확장하여 모든 유형의 데이터에 대한 맞춤형 지식 소스를 만들 수 있습니다. 이제 우주 뉴스 기사를 가져오고 처리하는 실용적인 예제를 만들어보겠습니다.
최근 우주 탐사 동향은 다음과 같습니다. 최신 우주 뉴스 기사들을 기반으로 정리하였습니다:
1. SpaceX가 2023년 11월 17일 오전에 예정된, 두 번째 Starship/Super Heavy 통합 발사를 위한 최종 규제 승인을 받았습니다. 이는 SpaceX의 우주 탐사 및 우주 식민화에 대한 야심찬 계획에서 중요한 단계입니다. [출처: SpaceNews](https://spacenews.com/starship-cleared-for-nov-17-launch/)
2. SpaceX는 미국 연방통신위원회(FCC)에 1세대 차세대 Starlink Gen2 위성의 첫 발사를 시작할 계획임을 알렸습니다. 이는 전 세계에 고속 인터넷을 제공하는 Starlink 위성 인터넷 서비스의 주요 업그레이드입니다. [출처: Teslarati](https://www.teslarati.com/spacex-first-starlink-gen2-satellite-launch-2022/)
3. AI 스타트업 Synthetaic이 시리즈 B 펀딩에서 1,500만 달러를 유치했습니다. 이 회사는 인공 지능을 사용하여 우주 및 공중 센서에서 데이터를 분석하며, 이는 우주 탐사와 위성 기술에 큰 응용 가능성이 있습니다. [출처: SpaceNews](https://spacenews.com/ai-startup-synthetaic-raises-15-million-in-series-b-funding/)
4. 미 우주군(Space Force)은 미국 인도-태평양 사령부(Indo-Pacific Command) 내에 부대를 공식적으로 창설하여 인도-태평양 지역에 항구적인 존재감을 확보하였습니다. 이는 우주 안보 및 지정학에 중대한 영향을 미칠 수 있습니다. [출처: SpaceNews](https://spacenews.com/space-force-establishes-permanent-presence-in-indo-pacific-region/)
5. 우주 추적 및 데이터 분석 기업 Slingshot Aerospace는 저지구 궤도(LEO) 커버리지를 확대하기 위해 지상 광학 망원경 네트워크를 확장하고 있습니다. 이는 저지구 궤도의 위성 및 우주 잔해 추적과 분석 능력을 향상시킬 수 있습니다. [출처: SpaceNews](https://spacenews.com/slingshots-space-tracking-network-to-extend-coverage-of-low-earth-orbit/)
6. 중국 국가자연과학기금위원회는 연구자들이 초대형 우주선 조립을 연구하기 위한 5개년 프로젝트를 발표했습니다. 이는 우주선 기술과 우주 탐사 역량의 비약적인 발전을 가져올 수 있습니다. [출처: SpaceNews](https://spacenews.com/china-researching-challenges-of-kilometer-scale-ultra-large-spacecraft/)
7. 스탠포드 대학교의 AEroSpace Autonomy Research 센터(CAESAR)는 우주선 자율성에 초점을 맞추고 있습니다. 센터는 2024년 5월 22일에 업계, 학계, 정부 간 협력을 촉진하기 위한 시작 행사를 개최하였습니다. 이는 자율 우주선 기술의 발전에 중대한 기여를 할 수 있습니다. [출처: SpaceNews](https://spacenews.com/stanford-center-focuses-on-spacecraft-autonomy/)
```
</CodeGroup>
## 디버깅 및 문제 해결
### 지식 문제 디버깅
#### 에이전트 지식 초기화 확인
```python
from crewai import Agent, Crew, Task
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
knowledge_source = StringKnowledgeSource(content="Test knowledge")
agent = Agent(
role="Test Agent",
goal="Test knowledge",
backstory="Testing",
knowledge_sources=[knowledge_source]
)
crew = Crew(agents=[agent], tasks=[Task(...)])
# Before kickoff - knowledge not initialized
print(f"Before kickoff - Agent knowledge: {getattr(agent, 'knowledge', None)}")
crew.kickoff()
# After kickoff - knowledge initialized
print(f"After kickoff - Agent knowledge: {agent.knowledge}")
print(f"Agent knowledge collection: {agent.knowledge.storage.collection_name}")
print(f"Number of sources: {len(agent.knowledge.sources)}")
```
#### Knowledge 저장 위치 확인
```python
import os
from crewai.utilities.paths import db_storage_path
# Check storage structure
storage_path = db_storage_path()
knowledge_path = os.path.join(storage_path, "knowledge")
if os.path.exists(knowledge_path):
print("Knowledge collections found:")
for collection in os.listdir(knowledge_path):
collection_path = os.path.join(knowledge_path, collection)
if os.path.isdir(collection_path):
print(f" - {collection}/")
# Show collection contents
for item in os.listdir(collection_path):
print(f" └── {item}")
```
#### 테스트 지식 검색
```python
# Test agent knowledge retrieval
if hasattr(agent, 'knowledge') and agent.knowledge:
test_query = ["test query"]
results = agent.knowledge.query(test_query)
print(f"Agent knowledge results: {len(results)} documents found")
# Test crew knowledge retrieval (if exists)
if hasattr(crew, 'knowledge') and crew.knowledge:
crew_results = crew.query_knowledge(test_query)
print(f"Crew knowledge results: {len(crew_results)} documents found")
```
#### 지식 컬렉션 검사하기
```python
import chromadb
from crewai.utilities.paths import db_storage_path
import os
# Connect to CrewAI's knowledge ChromaDB
knowledge_path = os.path.join(db_storage_path(), "knowledge")
if os.path.exists(knowledge_path):
client = chromadb.PersistentClient(path=knowledge_path)
collections = client.list_collections()
print("Knowledge Collections:")
for collection in collections:
print(f" - {collection.name}: {collection.count()} documents")
# Sample a few documents to verify content
if collection.count() > 0:
sample = collection.peek(limit=2)
print(f" Sample content: {sample['documents'][0][:100]}...")
else:
print("No knowledge storage found")
```
#### 지식 처리 확인
```python
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Create a test knowledge source
test_source = StringKnowledgeSource(
content="Test knowledge content for debugging",
chunk_size=100, # Small chunks for testing
chunk_overlap=20
)
# Check chunking behavior
print(f"Original content length: {len(test_source.content)}")
print(f"Chunk size: {test_source.chunk_size}")
print(f"Chunk overlap: {test_source.chunk_overlap}")
# Process and inspect chunks
test_source.add()
print(f"Number of chunks created: {len(test_source.chunks)}")
for i, chunk in enumerate(test_source.chunks[:3]): # Show first 3 chunks
print(f"Chunk {i+1}: {chunk[:50]}...")
```
### 일반적인 Knowledge Storage 문제
**"파일을 찾을 수 없음" 오류:**
```python
# Ensure files are in the correct location
from crewai.utilities.constants import KNOWLEDGE_DIRECTORY
import os
knowledge_dir = KNOWLEDGE_DIRECTORY # Usually "knowledge"
file_path = os.path.join(knowledge_dir, "your_file.pdf")
if not os.path.exists(file_path):
print(f"File not found: {file_path}")
print(f"Current working directory: {os.getcwd()}")
print(f"Expected knowledge directory: {os.path.abspath(knowledge_dir)}")
```
**"Embedding dimension mismatch" 오류:**
```python
# This happens when switching embedding providers
# Reset knowledge storage to clear old embeddings
crew.reset_memories(command_type='knowledge')
# Or use consistent embedding providers
crew = Crew(
agents=[...],
tasks=[...],
knowledge_sources=[...],
embedder={"provider": "openai", "config": {"model": "text-embedding-3-small"}}
)
```
**"ChromaDB permission denied" 오류:**
```bash
# Fix storage permissions
chmod -R 755 ~/.local/share/CrewAI/
```
**Knowledge가 여러 번 실행 시 유지되지 않음:**
```python
# Verify storage location consistency
import os
from crewai.utilities.paths import db_storage_path
print("CREWAI_STORAGE_DIR:", os.getenv("CREWAI_STORAGE_DIR"))
print("Computed storage path:", db_storage_path())
print("Knowledge path:", os.path.join(db_storage_path(), "knowledge"))
```
### 지식 초기화 명령어
```python
# Reset only agent-specific knowledge
crew.reset_memories(command_type='agent_knowledge')
# Reset both crew and agent knowledge
crew.reset_memories(command_type='knowledge')
# CLI commands
# crewai reset-memories --agent-knowledge # Agent knowledge only
# crewai reset-memories --knowledge # All knowledge
```
### 지식 초기화
CrewAI에 저장된 지식을 초기화해야 하는 경우, `crewai reset-memories` 명령어를 `--knowledge` 옵션과 함께 사용할 수 있습니다.
```bash Command
crewai reset-memories --knowledge
```
이 기능은 지식 소스를 업데이트했고, 에이전트들이 최신 정보를 사용하도록 보장하고 싶을 때 유용합니다.
## 베스트 프랙티스
<AccordionGroup>
<Accordion title="콘텐츠 구성">
- 콘텐츠 유형에 맞는 적절한 청크 크기를 유지하세요
- 컨텍스트 보존을 위해 콘텐츠 중복을 고려하세요
- 관련 정보를 별도의 지식 소스로 체계화하세요
</Accordion>
<Accordion title="성능 팁">
- 콘텐츠의 복잡성에 따라 청크 크기를 조정하세요
- 적절한 임베딩 모델을 설정하세요
- 더 빠른 처리를 위해 로컬 임베딩 프로바이더 사용을 고려하세요
</Accordion>
<Accordion title="원타임 지식">
- CrewAI에서 제공하는 일반적인 파일 구조에서는 kickoff가 트리거될 때마다 knowledge 소스가 임베딩됩니다.
- knowledge 소스가 크면, 매번 동일한 데이터가 임베딩되어 비효율성과 지연이 발생합니다.
- 이를 해결하려면 knowledge_sources 파라미터 대신 knowledge 파라미터를 직접 초기화하세요.
- 전체 아이디어를 얻으려면 이 이슈를 참고하세요 [Github Issue](https://github.com/crewAIInc/crewAI/issues/2755)
</Accordion>
<Accordion title="지식 관리">
- 역할별 정보에는 agent 레벨의 knowledge를 사용하세요
- 모든 agent가 필요로 하는 공유 정보에는 crew 레벨의 knowledge를 사용하세요
- 서로 다른 임베딩 전략이 필요하다면 agent 레벨에서 embedder를 설정하세요
- agent 역할을 설명적으로 유지하여 일관된 콜렉션 이름을 사용하세요
- kickoff 후 agent.knowledge를 확인하여 knowledge 초기화를 테스트하세요
- 지식이 저장되는 위치를 모니터링하여 storage 위치를 파악하세요
- 올바른 명령 유형을 사용하여 적절하게 knowledge를 초기화(리셋)하세요
</Accordion>
<Accordion title="프로덕션 환경 베스트 프랙티스">
- 프로덕션에서는 `CREWAI_STORAGE_DIR`를 지정된 위치로 설정하세요
- LLM 구성과 맞도록 임베딩 프로바이더를 명확히 선택하고, API 키 충돌을 방지하세요
- 문서가 추가될수록 knowledge storage 용량을 모니터링하세요
- 도메인 또는 목적에 따라 knowledge 소스를 콜렉션 이름으로 체계화하세요
- 지식 디렉터리를 백업 및 배포 전략에 포함시키세요
- knowledge 파일과 storage 디렉터리에 적절한 파일 권한을 부여하세요
- API 키와 민감한 설정에는 환경 변수를 사용하세요
</Accordion>
</AccordionGroup>

956
docs/ko/concepts/llms.mdx Normal file
View File

@@ -0,0 +1,956 @@
---
title: 'LLMs'
description: 'CrewAI 프로젝트에서 대형 언어 모델(LLM)을 구성하고 사용하는 방법에 대한 종합 안내서'
icon: 'microchip-ai'
---
## 개요
CrewAI는 LiteLLM을 통해 다양한 LLM 제공업체와 통합되어, 특정 사용 사례에 맞는 올바른 모델을 선택할 수 있는 유연성을 제공합니다. 이 가이드는 CrewAI 프로젝트에서 다양한 LLM 제공업체를 구성하고 사용하는 방법을 이해하는 데 도움이 될 것입니다.
## LLM이란 무엇인가요?
Large Language Models(LLM)는 CrewAI 에이전트의 핵심 지능입니다. 에이전트가 문맥을 이해하고, 결정을 내리며, 인간과 유사한 응답을 생성할 수 있도록 합니다. 알아두어야 할 내용은 다음과 같습니다:
<CardGroup cols={2}>
<Card title="LLM 기본" icon="brain">
Large Language Models는 방대한 양의 텍스트 데이터로 학습된 AI 시스템입니다. CrewAI 에이전트의 지능을 구동하여, 인간과 유사한 텍스트를 이해하고 생성할 수 있도록 합니다.
</Card>
<Card title="컨텍스트 윈도우" icon="window">
컨텍스트 윈도우는 LLM이 한 번에 처리할 수 있는 텍스트 양을 결정합니다. 더 큰 윈도우(예: 128K 토큰)는 더 많은 문맥을 다룰 수 있지만, 비용과 속도 면에서 더 부담이 될 수 있습니다.
</Card>
<Card title="Temperature" icon="temperature-three-quarters">
Temperature(0.0에서 1.0)는 응답의 무작위성을 조절합니다. 낮은 값(예: 0.2)은 더 집중적이고 결정적인 결과를, 높은 값(예: 0.8)은 창의성과 다양성을 높입니다.
</Card>
<Card title="제공자 선택" icon="server">
각 LLM 제공자(예: OpenAI, Anthropic, Google)는 다양한 기능, 가격, 특성을 가진 모델을 제공합니다. 정확성, 속도, 비용 등 요구 사항에 따라 선택하세요.
</Card>
</CardGroup>
## LLM 설정하기
CrewAI 코드 내에는 사용할 모델을 지정할 수 있는 여러 위치가 있습니다. 모델을 지정한 후에는 사용하는 각 모델 제공자에 대한 설정(예: API 키)을 제공해야 합니다. 각 제공자에 맞는 [제공자 설정 예제](#provider-configuration-examples) 섹션을 참고하세요.
<Tabs>
<Tab title="1. 환경 변수">
가장 간단하게 시작할 수 있는 방법입니다. `.env` 파일이나 앱 코드에서 환경 변수로 직접 모델을 설정할 수 있습니다. `crewai create`를 사용해 프로젝트를 부트스트랩했다면 이미 설정되어 있을 수 있습니다.
```bash .env
MODEL=model-id # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...
# 반드시 여기에서 API 키도 설정하세요. 아래 제공자
# 섹션을 참고하세요.
```
<Warning>
API 키를 절대 버전 관리 시스템에 커밋하지 마세요. 환경 파일(.env)이나 시스템의 비밀 관리 기능을 사용하세요.
</Warning>
</Tab>
<Tab title="2. YAML 구성">
에이전트 구성을 정의하는 YAML 파일을 만드세요. 이 방법은 버전 관리와 팀 협업에 적합합니다:
```yaml agents.yaml {6}
researcher:
role: Research Specialist
goal: Conduct comprehensive research and analysis
backstory: A dedicated research professional with years of experience
verbose: true
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
# (아래 제공자 구성 예제 참고)
```
<Info>
YAML 구성의 장점:
- 에이전트 설정을 버전 관리할 수 있습니다.
- 다양한 모델 간 전환이 쉽습니다.
- 팀원들과 구성을 공유할 수 있습니다.
- 모델 선택과 목적을 문서화할 수 있습니다.
</Info>
</Tab>
<Tab title="3. 직접 코드 작성">
최대한 유연하게 LLM을 Python 코드에서 직접 구성할 수 있습니다:
```python {4,8}
from crewai import LLM
# 기본 설정
llm = LLM(model="model-id-here") # gpt-4o, gemini-2.0-flash, anthropic/claude...
# 자세한 파라미터로 고급 설정
llm = LLM(
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
temperature=0.7, # 더욱 창의적인 결과를 원할 때 높게 설정
timeout=120, # 응답을 기다릴 최대 초
max_tokens=4000, # 응답의 최대 길이
top_p=0.9, # 누클리어스 샘플링 파라미터
frequency_penalty=0.1 , # 반복 줄이기
presence_penalty=0.1, # 주제 다양성 높이기
response_format={"type": "json"}, # 구조화된 출력용
seed=42 # 결과 재현성 확보용
)
```
<Info>
파라미터 설명:
- `temperature`: 랜덤성 제어 (0.0-1.0)
- `timeout`: 응답 대기 최대 시간
- `max_tokens`: 응답 길이 제한
- `top_p`: 샘플링 시 temperature의 대체값
- `frequency_penalty`: 단어 반복 감소
- `presence_penalty`: 새로운 주제 생성 유도
- `response_format`: 출력 구조 지정
- `seed`: 일관된 출력 보장
</Info>
</Tab>
</Tabs>
## 공급자 구성 예시
CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양한 LLM 공급자를 지원합니다.
이 섹션에서는 프로젝트의 요구에 가장 적합한 LLM을 선택, 구성, 최적화하는 데 도움이 되는 자세한 예시를 제공합니다.
<AccordionGroup>
<Accordion title="OpenAI">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
# Required
OPENAI_API_KEY=sk-...
# Optional
OPENAI_API_BASE=<custom-base-url>
OPENAI_ORGANIZATION=<your-org-id>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
from crewai import LLM
llm = LLM(
model="openai/gpt-4", # call model by provider/model_name
temperature=0.8,
max_tokens=150,
top_p=0.9,
frequency_penalty=0.1,
presence_penalty=0.1,
stop=["END"],
seed=42
)
```
OpenAI는 다양한 모델과 기능을 제공하는 대표적인 LLM 공급자 중 하나입니다.
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|-------------------|-------------------|-----------------------------------------------|
| GPT-4 | 8,192 토큰 | 고정확도 작업, 복잡한 추론 |
| GPT-4 Turbo | 128,000 토큰 | 장문 콘텐츠, 문서 분석 |
| GPT-4o & GPT-4o-mini | 128,000 토큰 | 비용 효율적인 대용량 컨텍스트 처리 |
| o3-mini | 200,000 토큰 | 빠른 추론, 복잡한 추론 |
| o1-mini | 128,000 토큰 | 빠른 추론, 복잡한 추론 |
| o1-preview | 128,000 토큰 | 빠른 추론, 복잡한 추론 |
| o1 | 200,000 토큰 | 빠른 추론, 복잡한 추론 |
</Accordion>
<Accordion title="Meta-Llama">
Meta의 Llama API는 Meta의 대형 언어 모델 패밀리 접근을 제공합니다.
API는 [Meta Llama API](https://llama.developer.meta.com?utm_source=partner-crewai&utm_medium=website)에서 사용할 수 있습니다.
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
# Meta Llama API Key Configuration
LLAMA_API_KEY=LLM|your_api_key_here
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
from crewai import LLM
# Meta Llama LLM 초기화
llm = LLM(
model="meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8",
temperature=0.8,
stop=["END"],
seed=42
)
```
https://llama.developer.meta.com/docs/models/ 에 기재된 모든 모델이 지원됩니다.
| 모델 ID | 입력 컨텍스트 길이 | 출력 컨텍스트 길이 | 입력 모달리티 | 출력 모달리티 |
| ------- | ------------------ | ------------------ | ---------------- | ---------------- |
| `meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8` | 128k | 4028 | 텍스트, 이미지 | 텍스트 |
| `meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 128k | 4028 | 텍스트, 이미지 | 텍스트 |
| `meta_llama/Llama-3.3-70B-Instruct` | 128k | 4028 | 텍스트 | 텍스트 |
| `meta_llama/Llama-3.3-8B-Instruct` | 128k | 4028 | 텍스트 | 텍스트 |
</Accordion>
<Accordion title="Anthropic">
```toml Code
# Required
ANTHROPIC_API_KEY=sk-ant-...
# Optional
ANTHROPIC_API_BASE=<custom-base-url>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="anthropic/claude-3-sonnet-20240229-v1:0",
temperature=0.7
)
```
</Accordion>
<Accordion title="Google (Gemini API)">
`.env` 파일에 API 키를 설정하십시오. 키가 필요하거나 기존 키를 찾으려면 [AI Studio](https://aistudio.google.com/apikey)를 확인하세요.
```toml .env
# https://ai.google.dev/gemini-api/docs/api-key
GEMINI_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
from crewai import LLM
llm = LLM(
model="gemini/gemini-2.0-flash",
temperature=0.7,
)
```
### Gemini 모델
Google은 다양한 용도에 최적화된 강력한 모델을 제공합니다.
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|----------------------------------|-----------------|------------------------------------------------------------------------|
| gemini-2.5-flash-preview-04-17 | 1M 토큰 | 적응형 사고, 비용 효율성 |
| gemini-2.5-pro-preview-05-06 | 1M 토큰 | 향상된 사고 및 추론, 멀티모달 이해, 고급 코딩 등 |
| gemini-2.0-flash | 1M 토큰 | 차세대 기능, 속도, 사고, 실시간 스트리밍 |
| gemini-2.0-flash-lite | 1M 토큰 | 비용 효율성과 낮은 대기 시간 |
| gemini-1.5-flash | 1M 토큰 | 밸런스 잡힌 멀티모달 모델, 대부분의 작업에 적합 |
| gemini-1.5-flash-8B | 1M 토큰 | 가장 빠르고, 비용 효율적, 고빈도 작업에 적합 |
| gemini-1.5-pro | 2M 토큰 | 최고의 성능, 논리적 추론, 코딩, 창의적 협업 등 다양한 추론 작업에 적합 |
전체 모델 목록은 [Gemini 모델 문서](https://ai.google.dev/gemini-api/docs/models)에서 확인할 수 있습니다.
### Gemma
Gemini API를 통해 Google 인프라에서 호스팅되는 [Gemma 모델](https://ai.google.dev/gemma/docs)도 API 키를 이용해 사용할 수 있습니다.
| 모델 | 컨텍스트 윈도우 |
|----------------|----------------|
| gemma-3-1b-it | 32k 토큰 |
| gemma-3-4b-it | 32k 토큰 |
| gemma-3-12b-it | 32k 토큰 |
| gemma-3-27b-it | 128k 토큰 |
</Accordion>
<Accordion title="Google (Vertex AI)">
Google Cloud Console에서 자격증명을 받아 JSON 파일로 저장한 후, 다음 코드로 로드하세요:
```python Code
import json
file_path = 'path/to/vertex_ai_service_account.json'
# Load the JSON file
with open(file_path, 'r') as file:
vertex_credentials = json.load(file)
# Convert the credentials to a JSON string
vertex_credentials_json = json.dumps(vertex_credentials)
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
from crewai import LLM
llm = LLM(
model="gemini-1.5-pro-latest", # or vertex_ai/gemini-1.5-pro-latest
temperature=0.7,
vertex_credentials=vertex_credentials_json
)
```
Google은 다양한 용도에 최적화된 강력한 모델들을 제공합니다:
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|----------------------------------|-----------------|------------------------------------------------------------------------|
| gemini-2.5-flash-preview-04-17 | 1M 토큰 | 적응형 사고, 비용 효율성 |
| gemini-2.5-pro-preview-05-06 | 1M 토큰 | 향상된 사고 및 추론, 멀티모달 이해, 고급 코딩 등 |
| gemini-2.0-flash | 1M 토큰 | 차세대 기능, 속도, 사고, 실시간 스트리밍 |
| gemini-2.0-flash-lite | 1M 토큰 | 비용 효율성과 낮은 대기 시간 |
| gemini-1.5-flash | 1M 토큰 | 밸런스 잡힌 멀티모달 모델, 대부분의 작업에 적합 |
| gemini-1.5-flash-8B | 1M 토큰 | 가장 빠르고, 비용 효율적, 고빈도 작업에 적합 |
| gemini-1.5-pro | 2M 토큰 | 최고의 성능, 논리적 추론, 코딩, 창의적 협업 등 다양한 추론 작업에 적합 |
</Accordion>
<Accordion title="Azure">
```toml Code
# Required
AZURE_API_KEY=<your-api-key>
AZURE_API_BASE=<your-resource-url>
AZURE_API_VERSION=<api-version>
# Optional
AZURE_AD_TOKEN=<your-azure-ad-token>
AZURE_API_TYPE=<your-azure-api-type>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="azure/gpt-4",
api_version="2023-05-15"
)
```
</Accordion>
<Accordion title="AWS Bedrock">
```toml Code
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-key>
AWS_DEFAULT_REGION=<your-region>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
)
```
Amazon Bedrock을 사용하기 전에, 환경에 boto3가 설치되어 있는지 확인하십시오.
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)은 대표적인 AI 회사들의 여러 파운데이션 모델에 통합 API를 통해 접근할 수 있는 매니지드 서비스로, 안전하고 책임감 있는 AI 응용프로그램 개발을 가능하게 해줍니다.
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|-----------------------------|--------------------|------------------------------------------------------------------------|
| Amazon Nova Pro | 최대 300k 토큰 | 다양한 작업에서 정확성, 속도, 비용을 균형 있게 제공하는 고성능 모델 |
| Amazon Nova Micro | 최대 128k 토큰 | 텍스트 전용, 최소 레이턴시 응답에 최적화된 비용 효율적 고성능 모델 |
| Amazon Nova Lite | 최대 300k 토큰 | 이미지, 비디오, 텍스트를 아우르는 실시간 멀티모달 처리 |
| Claude 3.7 Sonnet | 최대 128k 토큰 | 복잡한 추론, 코딩 및 AI 에이전트에 적합한 고성능 모델 |
| Claude 3.5 Sonnet v2 | 최대 200k 토큰 | 소프트웨어 공학, 에이전트 기능, 컴퓨터 상호작용에 특화된 최신 모델 |
| Claude 3.5 Sonnet | 최대 200k 토큰 | 다양한 작업에 탁월한 지능 및 추론 제공, 최적의 속도·비용 모델 |
| Claude 3.5 Haiku | 최대 200k 토큰 | 빠르고 컴팩트한 멀티모달 모델, 신속하고 자연스러운 대화에 최적 |
| Claude 3 Sonnet | 최대 200k 토큰 | 지능과 속도의 균형 잡힌 멀티모달 모델, 대규모 배포에 적합 |
| Claude 3 Haiku | 최대 200k 토큰 | 컴팩트한 고속 멀티모달 모델, 신속한 응답과 자연스러운 대화형 상호작용 |
| Claude 3 Opus | 최대 200k 토큰 | 인간 같은 추론과 우수한 문맥 이해로 복잡한 작업 수행 |
| Claude 2.1 | 최대 200k 토큰 | 확장된 컨텍스트, 신뢰도 개선, 로봇화 감소, 장문 및 RAG 적용에 적합 |
| Claude | 최대 100k 토큰 | 복잡한 대화, 창의적 콘텐츠 생성, 정교한 지시 수행에 탁월 |
| Claude Instant | 최대 100k 토큰 | 일상 대화, 분석, 요약, 문서 Q&A 등 빠르고 비용 효율적인 모델 |
| Llama 3.1 405B Instruct | 최대 128k 토큰 | 챗봇, 코딩, 도메인 특화 작업을 위한 합성 데이터 생성 및 추론용 첨단 LLM |
| Llama 3.1 70B Instruct | 최대 128k 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 능력 강화 |
| Llama 3.1 8B Instruct | 최대 128k 토큰 | 우수한 언어 이해, 추론, 텍스트 생성 기능의 최첨단 모델 |
| Llama 3 70B Instruct | 최대 8k 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 기능 강화 |
| Llama 3 8B Instruct | 최대 8k 토큰 | 첨단 언어 이해력, 추론, 텍스트 생성이 가능한 최첨단 LLM |
| Titan Text G1 - Lite | 최대 4k 토큰 | 영어 과제 및 요약, 콘텐츠 생성에 최적화된 경량 비용 효율적 모델 |
| Titan Text G1 - Express | 최대 8k 토큰 | 일반 언어, 대화, RAG 지원, 영어 및 100여 개 언어 지원 |
| Cohere Command | 최대 4k 토큰 | 사용자의 명령 수행, 실질적 기업 솔루션 제공에 특화된 모델 |
| Jurassic-2 Mid | 최대 8,191 토큰 | 다양한 언어 과제(Q&A, 요약, 생성 등)에 적합한 품질-비용 균형 모델 |
| Jurassic-2 Ultra | 최대 8,191 토큰 | 고급 텍스트 생성과 이해, 분석 및 콘텐츠 제작 등 복잡한 작업 수행 |
| Jamba-Instruct | 최대 256k 토큰 | 비용 효율적인 대용량 문맥 창작, 요약, Q&A에 최적화된 모델 |
| Mistral 7B Instruct | 최대 32k 토큰 | 명령을 따르고, 요청을 완성하며, 창의적 텍스트를 생성하는 LLM |
| Mistral 8x7B Instruct | 최대 32k 토큰 | 명령 및 요청 완성, 창의적 텍스트 생성이 가능한 MOE LLM |
</Accordion>
<Accordion title="Amazon SageMaker">
```toml Code
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-key>
AWS_DEFAULT_REGION=<your-region>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="sagemaker/<my-endpoint>"
)
```
</Accordion>
<Accordion title="Mistral">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
MISTRAL_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="mistral/mistral-large-latest",
temperature=0.7
)
```
</Accordion>
<Accordion title="Nvidia NIM">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
NVIDIA_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="nvidia_nim/meta/llama3-70b-instruct",
temperature=0.7
)
```
Nvidia NIM은 일반 목적 작업부터 특수 목적 응용까지 다양한 용도를 위한 모델 제품군을 제공합니다.
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|------------------------------------------------------------------------|----------------|---------------------------------------------------------------------|
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8,192 토큰 | 챗봇, 가상 비서, 콘텐츠 생성을 위한 최신형 소형 언어 모델 |
| nvidia/nemotron-4-mini-hindi-4b-instruct | 4,096 토큰 | 힌디-영어 SLM, 힌디 언어 전용 온디바이스 추론 |
| nvidia/llama-3.1-nemotron-70b-instruct | 128k 토큰 | 더욱 도움이 되는 답변을 위해 커스터마이즈됨 |
| nvidia/llama3-chatqa-1.5-8b | 128k 토큰 | 챗봇, 검색엔진용 맥락 인식 응답 생성에 탁월한 고급 LLM |
| nvidia/llama3-chatqa-1.5-70b | 128k 토큰 | 챗봇, 검색엔진용 맥락 인식 응답 생성에 탁월한 고급 LLM |
| nvidia/vila | 128k 토큰 | 텍스트/이미지/비디오 이해 및 정보성 응답 생성을 지원하는 멀티모달 모델 |
| nvidia/neva-22 | 4,096 토큰 | 텍스트/이미지 이해 및 정보성 응답 생성을 지원하는 멀티모달 모델 |
| nvidia/nemotron-mini-4b-instruct | 8,192 토큰 | 일반 목적 작업 |
| nvidia/usdcode-llama3-70b-instruct | 128k 토큰 | OpenUSD 지식 질의 응답, USD-Python 코드 생성이 가능한 최신 LLM |
| nvidia/nemotron-4-340b-instruct | 4,096 토큰 | 실제 데이터를 모사하는 다양한 합성 데이터 생성 |
| meta/codellama-70b | 100k 토큰 | 자연어 → 코드 및 코드 → 자연어 전환 가능한 LLM |
| meta/llama2-70b | 4,096 토큰 | 텍스트, 코드 생성에 최적화된 최첨단 대형 언어 모델 |
| meta/llama3-8b-instruct | 8,192 토큰 | 최첨단 언어 이해 및 추론, 텍스트 생성 기능 모델 |
| meta/llama3-70b-instruct | 8,192 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 |
| meta/llama-3.1-8b-instruct | 128k 토큰 | 최첨단 언어 이해 및 추론, 텍스트 생성 기능의 첨단 모델 |
| meta/llama-3.1-70b-instruct | 128k 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 |
| meta/llama-3.1-405b-instruct | 128k 토큰 | 챗봇, 코딩, 도메인 특화 작업 합성 데이터 생성 및 추론 |
| meta/llama-3.2-1b-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 모델 |
| meta/llama-3.2-3b-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 |
| meta/llama-3.2-11b-vision-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 |
| meta/llama-3.2-90b-vision-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 |
| google/gemma-7b | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
| google/gemma-2b | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
| google/codegemma-7b | 8,192 토큰 | 코드 생성 및 보완에 특화된 Google Gemma-7B 기반 모델 |
| google/codegemma-1.1-7b | 8,192 토큰 | 코드 생성, 보완, 추론, 명령 수행에 강점을 가진 고급 프로그래밍 모델 |
| google/recurrentgemma-2b | 8,192 토큰 | 긴 시퀀스 생성 시 빠른 추론을 가능케 하는 순환 아키텍처 LLM |
| google/gemma-2-9b-it | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
| google/gemma-2-27b-it | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
| google/gemma-2-2b-it | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
| google/deplot | 512 토큰 | 플롯 이미지를 표로 변환하는 원샷 비주얼 언어 이해 모델 |
| google/paligemma | 8,192 토큰 | 텍스트, 이미지 입력 이해 및 정보성 응답 생성에 능한 비전 언어 모델 |
| mistralai/mistral-7b-instruct-v0.2 | 32k 토큰 | 명령을 따르고, 요청을 완성하며, 창의적 텍스트 생성이 가능한 LLM |
| mistralai/mixtral-8x7b-instruct-v0.1 | 8,192 토큰 | 명령 및 요청 완성, 창의 텍스트 생성이 가능한 MOE LLM |
| mistralai/mistral-large | 4,096 토큰 | 실제 데이터 특성을 모방하는 다양한 합성 데이터 생성 |
| mistralai/mixtral-8x22b-instruct-v0.1 | 8,192 토큰 | 실제 데이터 특성을 모방하는 다양한 합성 데이터 생성 |
| mistralai/mistral-7b-instruct-v0.3 | 32k 토큰 | 명령을 따르고, 요청을 완성하며, 창의적 텍스트 생성이 가능한 LLM |
| nv-mistralai/mistral-nemo-12b-instruct | 128k 토큰 | 추론, 코드, 다국어 작업에 적합한 최첨단 언어 모델; 단일 GPU에서 구동 |
| mistralai/mamba-codestral-7b-v0.1 | 256k 토큰 | 광범위한 프로그래밍 언어 및 작업에서 코드 작성 및 상호작용 전용 모델 |
| microsoft/phi-3-mini-128k-instruct | 128K 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
| microsoft/phi-3-mini-4k-instruct | 4,096 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
| microsoft/phi-3-small-8k-instruct | 8,192 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
| microsoft/phi-3-small-128k-instruct | 128K 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
| microsoft/phi-3-medium-4k-instruct | 4,096 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
| microsoft/phi-3-medium-128k-instruct | 128K 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
| microsoft/phi-3.5-mini-instruct | 128K 토큰 | 지연, 메모리/컴퓨트 한계 환경에서 AI 응용프로그램 구동 가능한 다국어 LLM |
| microsoft/phi-3.5-moe-instruct | 128K 토큰 | 연산 효율적 콘텐츠 생성을 위한 Mixture of Experts 기반 첨단 LLM |
| microsoft/kosmos-2 | 1,024 토큰 | 이미지의 시각적 요소 이해 및 추론을 위한 획기적 멀티모달 모델 |
| microsoft/phi-3-vision-128k-instruct | 128k 토큰 | 이미지에서 고품질 추론이 가능한 최첨단 공개 멀티모달 모델 |
| microsoft/phi-3.5-vision-instruct | 128k 토큰 | 이미지에서 고품질 추론이 가능한 최첨단 공개 멀티모달 모델 |
| databricks/dbrx-instruct | 12k 토큰 | 언어 이해, 코딩, RAG에 최신 성능을 제공하는 범용 LLM |
| snowflake/arctic | 1,024 토큰 | SQL 생성 및 코딩에 집중한 기업용 고효율 추론 모델 |
| aisingapore/sea-lion-7b-instruct | 4,096 토큰 | 동남아 언어 및 문화 다양성을 반영하는 LLM |
| ibm/granite-8b-code-instruct | 4,096 토큰 | 소프트웨어 프로그래밍 LLM, 코드 생성, 완성, 설명, 멀티턴 전환 |
| ibm/granite-34b-code-instruct | 8,192 토큰 | 소프트웨어 프로그래밍 LLM, 코드 생성, 완성, 설명, 멀티턴 전환 |
| ibm/granite-3.0-8b-instruct | 4,096 토큰 | RAG, 요약, 분류, 코드, 에이전틱AI 지원 첨단 소형 언어 모델 |
| ibm/granite-3.0-3b-a800m-instruct | 4,096 토큰 | RAG, 요약, 엔터티 추출, 분류에 최적화된 고효율 Mixture of Experts 모델 |
| mediatek/breeze-7b-instruct | 4,096 토큰 | 실제 데이터 특성을 모방하는 다양한 합성 데이터 생성 |
| upstage/solar-10.7b-instruct | 4,096 토큰 | 지시 따르기, 추론, 수학 등에서 뛰어난 NLP 작업 수행 |
| writer/palmyra-med-70b-32k | 32k 토큰 | 의료 분야에서 정확하고 문맥에 맞는 응답 생성에 선도적인 LLM |
| writer/palmyra-med-70b | 32k 토큰 | 의료 분야에서 정확하고 문맥에 맞는 응답 생성에 선도적인 LLM |
| writer/palmyra-fin-70b-32k | 32k 토큰 | 금융 분석, 보고, 데이터 처리에 특화된 LLM |
| 01-ai/yi-large | 32k 토큰 | 영어, 중국어로 훈련, 챗봇 및 창의적 글쓰기 등 다양한 작업에 사용 |
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k 토큰 | 고급 코드 생성, 완성, 인필링 등의 기능을 제공하는 강력한 코딩 모델 |
| rakuten/rakutenai-7b-instruct | 1,024 토큰 | 언어 이해, 추론, 텍스트 생성이 탁월한 최첨단 LLM |
| rakuten/rakutenai-7b-chat | 1,024 토큰 | 언어 이해, 추론, 텍스트 생성이 탁월한 최첨단 LLM |
| baichuan-inc/baichuan2-13b-chat | 4,096 토큰 | 중국어 및 영어 대화, 코딩, 수학, 지시 따르기, 퀴즈 풀이 지원 |
</Accordion>
<Accordion title="Local NVIDIA NIM Deployed using WSL2">
NVIDIA NIM을 이용하면 Windows 기기에서 WSL2(Windows Subsystem for Linux)를 통해 강력한 LLM을 로컬로 실행할 수 있습니다.
이 방식은 Nvidia GPU를 활용하여 프라이빗하고, 안전하며, 비용 효율적인 AI 추론을 클라우드 서비스에 의존하지 않고 구현할 수 있습니다.
데이터 프라이버시, 오프라인 기능이 필요한 개발, 테스트, 또는 프로덕션 환경에 최적입니다.
로컬 NVIDIA NIM 모델 설치 단계별 가이드는 다음과 같습니다:
1. [NVIDIA 홈페이지](https://docs.nvidia.com/nim/wsl2/latest/getting-started.html)의 설치 안내를 따르세요.
2. 로컬 모델을 설치합니다. Llama 3.1-8b는 [여기](https://build.nvidia.com/meta/llama-3_1-8b-instruct/deploy) 안내를 참조하세요.
3. crewai 로컬 모델을 구성하세요:
```python Code
from crewai.llm import LLM
local_nvidia_nim_llm = LLM(
model="openai/meta/llama-3.1-8b-instruct", # it's an openai-api compatible model
base_url="http://localhost:8000/v1",
api_key="<your_api_key|any text if you have not configured it>", # api_key is required, but you can use any text
)
# 그런 다음 crew에서 사용할 수 있습니다:
@CrewBase
class MyCrew():
# ...
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'], # type: ignore[index]
llm=local_nvidia_nim_llm
)
# ...
```
</Accordion>
<Accordion title="Groq">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
GROQ_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="groq/llama-3.2-90b-text-preview",
temperature=0.7
)
```
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|-----------------|-------------------|----------------------------------|
| Llama 3.1 70B/8B| 131,072 토큰 | 고성능, 대용량 문맥 작업 |
| Llama 3.2 Series| 8,192 토큰 | 범용 작업 |
| Mixtral 8x7B | 32,768 토큰 | 성능과 문맥의 균형 |
</Accordion>
<Accordion title="IBM watsonx.ai">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
# Required
WATSONX_URL=<your-url>
WATSONX_APIKEY=<your-apikey>
WATSONX_PROJECT_ID=<your-project-id>
# Optional
WATSONX_TOKEN=<your-token>
WATSONX_DEPLOYMENT_SPACE_ID=<your-space-id>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="watsonx/meta-llama/llama-3-1-70b-instruct",
base_url="https://api.watsonx.ai/v1"
)
```
</Accordion>
<Accordion title="Ollama (Local LLMs)">
1. Ollama 설치: [ollama.ai](https://ollama.ai/)
2. 모델 실행: `ollama run llama3`
3. 구성:
```python Code
llm = LLM(
model="ollama/llama3:70b",
base_url="http://localhost:11434"
)
```
</Accordion>
<Accordion title="Fireworks AI">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
FIREWORKS_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct",
temperature=0.7
)
```
</Accordion>
<Accordion title="Perplexity AI">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
PERPLEXITY_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="llama-3.1-sonar-large-128k-online",
base_url="https://api.perplexity.ai/"
)
```
</Accordion>
<Accordion title="Hugging Face">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
HF_TOKEN=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct"
)
```
</Accordion>
<Accordion title="SambaNova">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
SAMBANOVA_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="sambanova/Meta-Llama-3.1-8B-Instruct",
temperature=0.7
)
```
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|-----------------|---------------------|--------------------------------------|
| Llama 3.1 70B/8B| 최대 131,072 토큰 | 고성능, 대용량 문맥 작업 |
| Llama 3.1 405B | 8,192 토큰 | 고성능, 높은 출력 품질 |
| Llama 3.2 Series| 8,192 토큰 | 범용, 멀티모달 작업 |
| Llama 3.3 70B | 최대 131,072 토큰 | 고성능, 높은 출력 품질 |
| Qwen2 familly | 8,192 토큰 | 고성능, 높은 출력 품질 |
</Accordion>
<Accordion title="Cerebras">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
# Required
CEREBRAS_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="cerebras/llama3.1-70b",
temperature=0.7,
max_tokens=8192
)
```
<Info>
Cerebras 특징:
- 빠른 추론 속도
- 경쟁력 있는 가격
- 속도와 품질의 우수한 밸런스
- 긴 컨텍스트 윈도우 지원
</Info>
</Accordion>
<Accordion title="Open Router">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
OPENROUTER_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="openrouter/deepseek/deepseek-r1",
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY
)
```
<Info>
Open Router 모델:
- openrouter/deepseek/deepseek-r1
- openrouter/deepseek/deepseek-chat
</Info>
</Accordion>
<Accordion title="Nebius AI Studio">
`.env` 파일에 다음 환경 변수를 설정하십시오:
```toml Code
NEBIUS_API_KEY=<your-api-key>
```
CrewAI 프로젝트에서의 예시 사용법:
```python Code
llm = LLM(
model="nebius/Qwen/Qwen3-30B-A3B"
)
```
<Info>
Nebius AI Studio 특징:
- 대규모 오픈소스 모델 보유
- 높은 속도 제한
- 경쟁력 있는 가격
- 속도와 품질의 우수한 밸런스
</Info>
</Accordion>
</AccordionGroup>
## 스트리밍 응답
CrewAI는 LLM의 스트리밍 응답을 지원하여, 애플리케이션이 출력물을 생성되는 즉시 실시간으로 수신하고 처리할 수 있습니다.
<Tabs>
<Tab title="기본 설정">
LLM을 초기화할 때 `stream` 파라미터를 `True`로 설정하여 스트리밍을 활성화합니다:
```python
from crewai import LLM
# 스트리밍이 활성화된 LLM 생성
llm = LLM(
model="openai/gpt-4o",
stream=True # 스트리밍 활성화
)
```
스트리밍이 활성화되면, 응답이 생성되는 대로 청크 단위로 전달되어 보다 반응성 있는 사용자 경험을 만듭니다.
</Tab>
<Tab title="이벤트 처리">
CrewAI는 스트리밍 중 수신되는 각 청크에 대해 이벤트를 발생시킵니다:
```python
from crewai.utilities.events import (
LLMStreamChunkEvent
)
from crewai.utilities.events.base_event_listener import BaseEventListener
class MyCustomListener(BaseEventListener):
def setup_listeners(self, crewai_event_bus):
@crewai_event_bus.on(LLMStreamChunkEvent)
def on_llm_stream_chunk(self, event: LLMStreamChunkEvent):
# 각 청크가 도착할 때마다 처리
print(f"Received chunk: {event.chunk}")
my_listener = MyCustomListener()
```
<Tip>
[자세한 내용은 여기를 클릭하세요](https://docs.crewai.com/concepts/event-listener#event-listeners)
</Tip>
</Tab>
<Tab title="에이전트 & 태스크 추적">
CrewAI의 모든 LLM 이벤트에는 에이전트 및 태스크 정보가 포함되어 있어, 특정 에이전트나 태스크별로 LLM 상호작용을 추적하고 필터링할 수 있습니다:
```python
from crewai import LLM, Agent, Task, Crew
from crewai.utilities.events import LLMStreamChunkEvent
from crewai.utilities.events.base_event_listener import BaseEventListener
class MyCustomListener(BaseEventListener):
def setup_listeners(self, crewai_event_bus):
@crewai_event_bus.on(LLMStreamChunkEvent)
def on_llm_stream_chunk(source, event):
if researcher.id == event.agent_id:
print("\n==============\n Got event:", event, "\n==============\n")
my_listener = MyCustomListener()
llm = LLM(model="gpt-4o-mini", temperature=0, stream=True)
researcher = Agent(
role="About User",
goal="You know everything about the user.",
backstory="""You are a master at understanding people and their preferences.""",
llm=llm,
)
search = Task(
description="Answer the following questions about the user: {question}",
expected_output="An answer to the question.",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[search])
result = crew.kickoff(
inputs={"question": "..."}
)
```
<Info>
이 기능은 다음과 같은 경우에 특히 유용합니다:
- 특정 에이전트 동작을 디버깅할 때
- 태스크 유형별 LLM 사용 기록을 남길 때
- 어떤 에이전트가 어떤 유형의 LLM 호출을 하는지 감사할 때
- 특정 태스크의 성능을 모니터링할 때
</Info>
</Tab>
</Tabs>
## 구조화된 LLM 호출
CrewAI는 Pydantic 모델을 사용하여 `response_format`을 정의함으로써 LLM 호출에서 구조화된 응답을 지원합니다. 이를 통해 프레임워크가 출력을 자동으로 파싱하고 검증할 수 있어, 수동 후처리 없이도 응답을 애플리케이션에 쉽게 통합할 수 있습니다.
예를 들어, 예상되는 응답 구조를 나타내는 Pydantic 모델을 정의하고 LLM을 인스턴스화할 때 `response_format`으로 전달할 수 있습니다. 이 모델은 LLM 출력을 구조화된 Python 객체로 변환하는 데 사용됩니다.
```python Code
from crewai import LLM
class Dog(BaseModel):
name: str
age: int
breed: str
llm = LLM(model="gpt-4o", response_format=Dog)
response = llm.call(
"Analyze the following messages and return the name, age, and breed. "
"Meet Kona! She is 3 years old and is a black german shepherd."
)
print(response)
# Output:
# Dog(name='Kona', age=3, breed='black german shepherd')
```
## 고급 기능 및 최적화
LLM 설정을 최대한 활용하는 방법을 알아보세요:
<AccordionGroup>
<Accordion title="컨텍스트 윈도우 관리">
CrewAI는 스마트한 컨텍스트 관리 기능을 제공합니다:
```python
from crewai import LLM
# CrewAI는 자동으로 다음을 처리합니다:
# 1. 토큰 계산 및 추적
# 2. 필요시 콘텐츠 요약
# 3. 큰 컨텍스트에 대한 작업 분할
llm = LLM(
model="gpt-4",
max_tokens=4000, # 응답 길이 제한
)
```
<Info>
컨텍스트 관리 모범 사례:
1. 적절한 컨텍스트 윈도우를 가진 모델 선택
2. 가능하면 긴 입력값을 사전 처리
3. 큰 문서에는 청킹(chunking) 사용
4. 비용 최적화를 위해 토큰 사용량 모니터링
</Info>
</Accordion>
<Accordion title="성능 최적화">
<Steps>
<Step title="토큰 사용 최적화">
작업에 맞는 컨텍스트 윈도우를 선택하세요:
- 작은 작업 (최대 4K 토큰): 표준 모델
- 중간 작업 (4K~32K 사이): 확장 모델
- 큰 작업 (32K 이상): 대형 컨텍스트 모델
```python
# 모델을 적절한 설정으로 구성
llm = LLM(
model="openai/gpt-4-turbo-preview",
temperature=0.7, # 작업에 따라 조정
max_tokens=4096, # 출력 요구 사항에 맞게 설정
timeout=300 # 복잡한 작업을 위한 더 긴 타임아웃
)
```
<Tip>
- 사실 기반 응답에는 낮은 temperature(0.1~0.3)
- 창의적인 작업에는 높은 temperature(0.7~0.9)
</Tip>
</Step>
<Step title="모범 사례">
1. 토큰 사용량 모니터링
2. 속도 제한(rate limiting) 구현
3. 가능하면 캐싱 사용
4. 적절한 max_tokens 제한 설정
</Step>
</Steps>
<Info>
비용 및 성능을 최적화하기 위해 토큰 사용량을 정기적으로 모니터링하고 필요에 따라 설정을 조정하세요.
</Info>
</Accordion>
<Accordion title="추가 파라미터 드롭">
CrewAI는 내부적으로 LLM 호출에 Litellm을 사용하며, 이를 통해 특정 사용 사례에 필요하지 않은 추가 파라미터를 제거할 수 있습니다. 이를 통해 코드가 간소화되며 LLM 구성의 복잡성을 줄일 수 있습니다.
예를 들어, <code>stop</code> 파라미터를 보낼 필요가 없다면 LLM 호출에서 제외할 수 있습니다:
```python
from crewai import LLM
import os
os.environ["OPENAI_API_KEY"] = "<api-key>"
o3_llm = LLM(
model="o3",
drop_params=True,
additional_drop_params=["stop"]
)
```
</Accordion>
</AccordionGroup>
## 일반적인 문제 및 해결 방법
<Tabs>
<Tab title="인증">
<Warning>
대부분의 인증 문제는 API 키 형식과 환경 변수 이름을 확인하여 해결할 수 있습니다.
</Warning>
```bash
# OpenAI
OPENAI_API_KEY=sk-...
# Anthropic
ANTHROPIC_API_KEY=sk-ant-...
```
</Tab>
<Tab title="모델 이름">
<Check>
항상 모델 이름에 provider 접두사를 포함하세요.
</Check>
```python
# 올바른 예시
llm = LLM(model="openai/gpt-4")
# 잘못된 예시
llm = LLM(model="gpt-4")
```
</Tab>
<Tab title="컨텍스트 길이">
<Tip>
대규모 작업에는 더 큰 컨텍스트 모델을 사용하세요.
</Tip>
```python
# 대용량 컨텍스트 모델
llm = LLM(model="openai/gpt-4o") # 128K tokens
```
</Tab>
</Tabs>

1159
docs/ko/concepts/memory.mdx Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,152 @@
---
title: 계획
description: CrewAI Crew에 계획을 추가하고 성능을 향상시키는 방법을 알아보세요.
icon: ruler-combined
---
## 개요
CrewAI의 planning 기능을 통해 crew에 계획 수립 기능을 추가할 수 있습니다. 해당 기능을 활성화하면, 각 Crew 반복 전에 모든 Crew 정보가 AgentPlanner로 전송되어 작업이 단계별로 계획되며, 이 계획이 각 작업 설명에 추가됩니다.
### Planning 기능 사용하기
Planning 기능을 시작하는 것은 매우 간단합니다. 필요한 유일한 단계는 Crew에 `planning=True`를 추가하는 것입니다:
<CodeGroup>
```python Code
from crewai import Crew, Agent, Task, Process
# Assemble your crew with planning capabilities
my_crew = Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
planning=True,
)
```
</CodeGroup>
이 시점부터 crew는 planning이 활성화되며, 각 반복 전에 작업이 계획됩니다.
<Warning>
Planning이 활성화되면, crewAI는 planning을 위해 기본 LLM으로 `gpt-4o-mini`를 사용합니다. 이 기능은 유효한 OpenAI API 키가 필요합니다. 에이전트가 서로 다른 LLM을 사용할 수도 있기 때문에, OpenAI API 키가 설정되어 있지 않거나 LLM API 호출과 관련된 예상치 못한 동작이 발생할 경우 혼란을 일으킬 수 있습니다.
</Warning>
#### LLM 계획하기
이제 작업을 계획할 때 사용할 LLM을 정의할 수 있습니다.
기본 사례 예제를 실행하면 아래와 같은 출력이 나타나는데, 이는 AgentPlanner의 출력으로, 에이전트 작업에 추가할 단계별 논리를 생성합니다.
<CodeGroup>
```python Code
from crewai import Crew, Agent, Task, Process
# Assemble your crew with planning capabilities and custom LLM
my_crew = Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
planning=True,
planning_llm="gpt-4o"
)
# Run the crew
my_crew.kickoff()
```
```markdown Result
[2024-07-15 16:49:11][INFO]: Planning the crew execution
**작업 실행을 위한 단계별 계획**
**작업 번호 1: AI LLM에 대해 철저히 조사하기**
**에이전트:** AI LLMs 시니어 데이터 리서처
**에이전트 목표:** AI LLM의 최신 개발 동향 파악
**작업 예상 결과:** AI LLM에 대한 가장 관련성 높은 정보 10가지가 포함된 리스트
**작업 도구:** 명시되지 않음
**에이전트 도구:** 명시되지 않음
**단계별 계획:**
1. **조사 범위 정의:**
- 아키텍처의 발전, 사용 사례, 윤리적 고려사항, 성능 측정 기준 등 AI LLM의 특정 영역을 결정합니다.
2. **신뢰할 수 있는 출처 식별:**
- 학술지, 산업 리포트, 컨퍼런스(예: NeurIPS, ACL), AI 연구소(예: OpenAI, Google AI), 온라인 데이터베이스(예: IEEE Xplore, arXiv) 등 AI 연구를 위한 평판 좋은 출처를 나열합니다.
3. **데이터 수집:**
- 2024년 및 2025년 초에 발표된 최신 논문, 기사, 리포트를 검색합니다.
- "Large Language Models 2025", "AI LLM advancements", "AI ethics 2025"와 같은 키워드를 사용합니다.
4. **발견 사항 분석:**
- 각 출처에서 핵심 내용을 읽고 요약합니다.
- 지난 1년간 소개된 새로운 기술, 모델, 애플리케이션 등을 강조합니다.
5. **정보 정리:**
- 정보를 관련 주제별로 분류합니다(예: 새로운 아키텍처, 윤리적 영향, 실세계 적용 등).
- 각 핵심 포인트는 간결하면서도 정보가 풍부하도록 합니다.
6. **리스트 작성:**
- 가장 관련성 높은 10가지 정보를 불릿 포인트로 정리합니다.
- 리스트가 명확하고 적절한지 검토합니다.
**예상 결과:**
AI LLM에 대한 가장 관련성 높은 정보 10가지를 담은 불릿 포인트 리스트.
---
**작업 번호 2: 받은 컨텍스트를 검토하고 각 주제를 리포트의 전체 섹션으로 확장하기**
**에이전트:** AI LLMs 리포팅 애널리스트
**에이전트 목표:** AI LLM 데이터 분석 및 연구 결과를 기반으로 상세 리포트를 작성
**작업 예상 결과:** 주요 주제별로 각 섹션이 포함된 완전한 리포트 (마크다운 형식, '```' 없이)
**작업 도구:** 명시되지 않음
**에이전트 도구:** 명시되지 않음
**단계별 계획:**
1. **불릿 포인트 검토:**
- AI LLMs 시니어 데이터 리서처가 제공한 10가지 불릿 포인트 리스트를 꼼꼼히 읽습니다.
2. **리포트 개요 작성:**
- 각 불릿 포인트를 주요 섹션 제목으로 삼아 개요를 만듭니다.
- 각 주요 제목 아래 하위 섹션을 기획하여 해당 주제의 다양한 측면을 다룹니다.
3. **추가 세부 사항 조사:**
- 각 불릿 포인트별로, 더 자세한 정보를 수집하기 위해 필요 시 추가 조사를 진행합니다.
- 각 섹션을 뒷받침할 사례 연구, 예시, 통계자료 등을 찾습니다.
4. **상세 섹션 작성:**
- 각 불릿 포인트를 포괄적인 섹션으로 확장합니다.
- 각 섹션에는 도입, 상세 설명, 예시, 결론이 포함되어야 합니다.
- 제목, 부제목, 리스트, 강조 등 마크다운 포맷을 사용합니다.
5. **검토 및 편집:**
- 리포트의 명확성, 일관성, 정확성을 위해 교정합니다.
- 리포트가 각 섹션에서 논리적으로 자연스럽게 흐르는지 확인합니다.
- 마크다운 기준에 맞게 포맷을 맞춥니다.
6. **리포트 최종화:**
- 모든 섹션이 확장되고 상세하게 작성되어 완전한 리포트가 되었는지 확인합니다.
- 포맷을 다시 확인하고 필요한 경우 수정합니다.
**예상 결과:**
주요 주제별로 각 섹션이 포함된 완전한 리포트 (마크다운 형식, '```' 없이).
```
</CodeGroup>

View File

@@ -0,0 +1,66 @@
---
title: 프로세스
description: CrewAI에서 프로세스를 통한 워크플로우 관리에 대한 상세 가이드와 최신 구현 세부 사항.
icon: bars-staggered
---
## 개요
<Tip>
프로세스는 에이전트에 의해 작업이 실행되도록 조정하며, 이는 인간 팀에서의 프로젝트 관리와 유사합니다.
이러한 프로세스는 작업이 미리 정의된 전략에 따라 효율적으로 분배되고 실행되도록 보장합니다.
</Tip>
## 프로세스 구현
- **순차적(Sequential)**: 작업을 순차적으로 실행하여 작업이 질서 있게 진행되도록 보장합니다.
- **계층적(Hierarchical)**: 작업을 관리 계층 구조로 조직하며, 작업은 체계적인 명령 체계를 기반으로 위임 및 실행됩니다. 계층적 프로세스를 활성화하려면 매니저 언어 모델(`manager_llm`) 또는 커스텀 매니저 에이전트(`manager_agent`)를 crew에서 지정해야 하며, 이를 통해 매니저가 작업을 생성하고 관리할 수 있도록 지원합니다.
- **합의 프로세스(Consensual Process, 계획됨)**: 에이전트들 간에 작업 실행에 대한 협력적 의사결정을 목표로 하며, 이 프로세스 유형은 CrewAI 내에서 작업 관리를 민주적으로 접근하도록 도입됩니다. 앞으로 개발될 예정이며, 현재 코드베이스에는 구현되어 있지 않습니다.
## 팀워크에서 프로세스의 역할
프로세스는 개별 에이전트가 통합된 단위로 작동할 수 있도록 하여, 공통된 목표를 효율적이고 일관성 있게 달성하도록 노력하는 과정을 간소화합니다.
## 프로세스를 Crew에 할당하기
프로세스를 crew에 할당하려면, crew 생성 시 프로세스 유형을 지정하여 실행 전략을 설정합니다. 계층적 프로세스의 경우, 매니저 에이전트에 대해 `manager_llm` 또는 `manager_agent`를 반드시 정의해야 합니다.
```python
from crewai import Crew, Process
# Example: Creating a crew with a sequential process
crew = Crew(
agents=my_agents,
tasks=my_tasks,
process=Process.sequential
)
# Example: Creating a crew with a hierarchical process
# Ensure to provide a manager_llm or manager_agent
crew = Crew(
agents=my_agents,
tasks=my_tasks,
process=Process.hierarchical,
manager_llm="gpt-4o"
# or
# manager_agent=my_manager_agent
)
```
**참고:** `Crew` 객체를 생성하기 전에 반드시 `my_agents`와 `my_tasks`가 정의되어 있어야 하며, 계층적 프로세스의 경우 `manager_llm` 또는 `manager_agent` 중 하나도 필요합니다.
## 순차적 프로세스
이 방법은 동적인 팀 워크플로우를 반영하며, 작업을 신중하고 체계적으로 진행합니다. 작업 수행은 작업 목록에 정의된 순서를 따르며, 한 작업의 출력이 다음 작업의 컨텍스트로 사용됩니다.
작업 컨텍스트를 사용자 지정하려면, `Task` 클래스의 `context` 매개변수를 사용하여 이후 작업에 컨텍스트로 사용될 출력을 지정하세요.
## 계층적 프로세스
기업의 계층 구조를 모방하는 CrewAI는 사용자 지정 관리자 에이전트를 지정하거나 자동으로 생성할 수 있으며, 이때 관리자 언어 모델(`manager_llm`)의 지정을 요구합니다. 이 에이전트는 계획 수립, 위임, 검증 등 작업 실행을 감독합니다. 작업은 미리 할당되지 않으며, 관리자가 에이전트의 역량에 따라 작업을 분배하고, 산출물을 검토하며, 작업 완료 여부를 평가합니다.
## Process 클래스: 상세 개요
`Process` 클래스는 열거형(`Enum`)으로 구현되어 타입 안전성을 보장하며, 프로세스 값을 정의된 타입(`sequential`, `hierarchical`)으로 제한합니다. 합의 기반(consensual) 프로세스는 향후 추가될 예정이며, 이는 지속적인 개발과 혁신에 대한 우리의 의지를 강조합니다.
## 결론
CrewAI 내의 프로세스를 통해 촉진되는 구조화된 협업은 에이전트 간 체계적인 팀워크를 가능하게 하는 데 매우 중요합니다.
이 문서는 최신 기능, 향상 사항, 그리고 예정된 Consensual Process 통합을 반영하도록 업데이트되었으며, 사용자가 가장 최신이고 포괄적인 정보를 이용할 수 있도록 보장합니다.

View File

@@ -0,0 +1,147 @@
---
title: Reasoning
description: "에이전트 reasoning을 활성화하고 사용하는 방법을 배워 작업 실행을 향상하세요."
icon: brain
---
## 개요
Agent reasoning은 에이전트가 작업을 수행하기 전에 해당 작업을 반성하고 계획을 수립할 수 있도록 해주는 기능입니다. 이를 통해 에이전트는 작업에 더 체계적으로 접근할 수 있으며, 할당된 업무를 수행할 준비가 되었는지 확인할 수 있습니다.
## 사용 방법
에이전트에 reasoning을 활성화하려면 에이전트를 생성할 때 `reasoning=True`로 설정하면 됩니다.
```python
from crewai import Agent
agent = Agent(
role="Data Analyst",
goal="Analyze complex datasets and provide insights",
backstory="You are an experienced data analyst with expertise in finding patterns in complex data.",
reasoning=True, # Enable reasoning
max_reasoning_attempts=3 # Optional: Set a maximum number of reasoning attempts
)
```
## 작동 방식
reasoning이 활성화되면, 작업을 실행하기 전에 에이전트는 다음을 수행합니다:
1. 작업을 반영하고 상세한 계획을 수립합니다.
2. 작업을 실행할 준비가 되었는지 평가합니다.
3. 준비가 완료되거나 max_reasoning_attempts에 도달할 때까지 필요에 따라 계획을 다듬습니다.
4. reasoning 계획을 실행 전에 작업 설명에 삽입합니다.
이 프로세스는 에이전트가 복잡한 작업을 관리하기 쉬운 단계로 분해하고, 시작하기 전에 잠재적인 문제를 식별하는 데 도움을 줍니다.
## 구성 옵션
<ParamField body="reasoning" type="bool" default="False">
reasoning 활성화 또는 비활성화
</ParamField>
<ParamField body="max_reasoning_attempts" type="int" default="None">
실행을 진행하기 전에 계획을 개선할 최대 시도 횟수입니다. None(기본값)인 경우, agent는 준비될 때까지 계속해서 개선을 시도합니다.
</ParamField>
## 예제
다음은 전체 예제입니다:
```python
from crewai import Agent, Task, Crew
# Create an agent with reasoning enabled
analyst = Agent(
role="Data Analyst",
goal="Analyze data and provide insights",
backstory="You are an expert data analyst.",
reasoning=True,
max_reasoning_attempts=3 # Optional: Set a limit on reasoning attempts
)
# Create a task
analysis_task = Task(
description="Analyze the provided sales data and identify key trends.",
expected_output="A report highlighting the top 3 sales trends.",
agent=analyst
)
# Create a crew and run the task
crew = Crew(agents=[analyst], tasks=[analysis_task])
result = crew.kickoff()
print(result)
```
## 오류 처리
reasoning 프로세스는 견고하게 설계되어 있으며, 오류 처리가 내장되어 있습니다. reasoning 중에 오류가 발생하면, 에이전트는 reasoning 계획 없이 작업을 계속 실행합니다. 이는 reasoning 프로세스가 실패하더라도 작업이 계속 실행될 수 있도록 보장합니다.
코드에서 발생할 수 있는 오류를 처리하는 방법은 다음과 같습니다:
```python
from crewai import Agent, Task
import logging
# reasoning 오류를 캡처하기 위해 로깅을 설정합니다
logging.basicConfig(level=logging.INFO)
# reasoning이 활성화된 에이전트를 생성합니다
agent = Agent(
role="Data Analyst",
goal="Analyze data and provide insights",
reasoning=True,
max_reasoning_attempts=3
)
# 작업을 생성합니다
task = Task(
description="Analyze the provided sales data and identify key trends.",
expected_output="A report highlighting the top 3 sales trends.",
agent=agent
)
# 작업 실행
# reasoning 중 오류가 발생해도 로그에 기록되며 실행은 계속됩니다
result = agent.execute_task(task)
```
## 예시 Reasoning 출력
다음은 데이터 분석 작업을 위한 reasoning 계획의 예시입니다:
```
Task: Analyze the provided sales data and identify key trends.
Reasoning Plan:
I'll analyze the sales data to identify the top 3 trends.
1. Understanding of the task:
I need to analyze sales data to identify key trends that would be valuable for business decision-making.
2. Key steps I'll take:
- First, I'll examine the data structure to understand what fields are available
- Then I'll perform exploratory data analysis to identify patterns
- Next, I'll analyze sales by time periods to identify temporal trends
- I'll also analyze sales by product categories and customer segments
- Finally, I'll identify the top 3 most significant trends
3. Approach to challenges:
- If the data has missing values, I'll decide whether to fill or filter them
- If the data has outliers, I'll investigate whether they're valid data points or errors
- If trends aren't immediately obvious, I'll apply statistical methods to uncover patterns
4. Use of available tools:
- I'll use data analysis tools to explore and visualize the data
- I'll use statistical tools to identify significant patterns
- I'll use knowledge retrieval to access relevant information about sales analysis
5. Expected outcome:
A concise report highlighting the top 3 sales trends with supporting evidence from the data.
READY: I am ready to execute the task.
```
이 reasoning 계획은 agent가 작업에 접근하는 방식을 체계적으로 구성하고, 발생할 수 있는 잠재적 문제를 고려하며, 기대되는 결과를 제공하도록 돕습니다.

902
docs/ko/concepts/tasks.mdx Normal file
View File

@@ -0,0 +1,902 @@
---
title: 작업
description: CrewAI 프레임워크 내에서 작업을 관리하고 생성하는 방법에 대한 자세한 안내서입니다.
icon: list-check
---
## 개요
CrewAI 프레임워크에서 `Task`는 `Agent`가 완료하는 구체적인 과제입니다.
Task는 실행을 위한 모든 세부 정보를 제공합니다. 여기에는 설명, 책임 Agent, 필요한 도구 등이 포함되어 다양한 작업 복잡성을 지원합니다.
CrewAI 내의 Task는 협업이 가능하며, 여러 Agent가 함께 작업해야 할 수도 있습니다. 이는 Task 속성을 통해 관리되며, Crew의 프로세스를 통해 조율되어 팀워크와 효율성을 향상시킵니다.
<Note type="info" title="엔터프라이즈 기능: 비주얼 Task 빌더">
CrewAI 엔터프라이즈에는 복잡한 Task 생성과 연결을 단순화하는 Crew Studio의 비주얼 Task 빌더가 포함되어 있습니다. Task 흐름을 시각적으로 설계하고, 코드를 작성하지 않고도 실시간으로 테스트해 볼 수 있습니다.
![Task Builder Screenshot](/images/enterprise/crew-studio-interface.png)
비주얼 Task 빌더의 주요 기능:
- 드래그 앤 드롭 방식의 Task 생성
- 시각적 Task 종속성과 흐름 관리
- 실시간 테스트 및 검증
- 손쉬운 공유 및 협업
</Note>
### 작업 실행 흐름
작업은 두 가지 방법으로 실행될 수 있습니다:
- **순차적**: 작업이 정의된 순서대로 실행됩니다
- **계층적**: 작업이 역할과 전문성에 따라 에이전트에게 할당됩니다
실행 흐름은 crew를 생성할 때 정의됩니다:
```python Code
crew = Crew(
agents=[agent1, agent2],
tasks=[task1, task2],
process=Process.sequential # or Process.hierarchical
)
```
## 태스크 속성
| 속성 | 매개변수 | 타입 | 설명 |
| :------------------------------- | :-------------------- | :------------------------------- | :------------------------------------------------------------------------------------------------------------ |
| **설명** | `description` | `str` | 태스크가 다루는 내용을 명확하고 간결하게 설명합니다. |
| **예상 출력** | `expected_output` | `str` | 태스크가 완료된 모습에 대한 구체적인 설명입니다. |
| **이름** _(선택 사항)_ | `name` | `Optional[str]` | 태스크의 이름 식별자입니다. |
| **에이전트** _(선택 사항)_ | `agent` | `Optional[BaseAgent]` | 태스크 실행을 담당하는 에이전트입니다. |
| **도구** _(선택 사항)_ | `tools` | `List[BaseTool]` | 이 태스크를 위해 에이전트가 사용할 수 있는 도구/리소스 목록입니다. |
| **컨텍스트** _(선택 사항)_ | `context` | `Optional[List["Task"]]` | 이 태스크의 컨텍스트로 사용될 다른 태스크의 출력입니다. |
| **비동기 실행** _(선택 사항)_ | `async_execution` | `Optional[bool]` | 태스크를 비동기적으로 실행할지 여부입니다. 기본값은 False입니다. |
| **사용자 입력** _(선택 사항)_ | `human_input` | `Optional[bool]` | 태스크의 최종 답안을 에이전트가 제출한 뒤 사람이 검토할지 여부입니다. 기본값은 False입니다. |
| **마크다운** _(선택 사항)_ | `markdown` | `Optional[bool]` | 태스크가 에이전트에게 최종 답안을 마크다운으로 포매팅해서 반환하도록 지시할지 여부입니다. 기본값은 False입니다. |
| **설정** _(선택 사항)_ | `config` | `Optional[Dict[str, Any]]` | 태스크별 설정 파라미터입니다. |
| **출력 파일** _(선택 사항)_ | `output_file` | `Optional[str]` | 태스크 결과를 저장할 파일 경로입니다. |
| **디렉터리 생성** _(선택 사항)_ | `create_directory` | `Optional[bool]` | output_file의 디렉터리가 존재하지 않을 경우 생성할지 여부입니다. 기본값은 True입니다. |
| **출력 JSON** _(선택 사항)_ | `output_json` | `Optional[Type[BaseModel]]` | JSON 출력을 구조화하기 위한 Pydantic 모델입니다. |
| **Pydantic 출력** _(선택 사항)_ | `output_pydantic` | `Optional[Type[BaseModel]]` | 태스크 출력용 Pydantic 모델입니다. |
| **콜백** _(선택 사항)_ | `callback` | `Optional[Any]` | 태스크 완료 후 실행할 함수/객체입니다. |
| **가드레일** _(선택 사항)_ | `guardrail` | `Optional[Callable]` | 다음 태스크로 진행하기 전에 태스크 출력을 검증하는 함수입니다. |
## 작업 생성하기
CrewAI에서 작업을 생성하는 방법에는 **YAML 구성(권장)** 을 사용하는 방법과 **코드에서 직접 정의하는 방법** 두 가지가 있습니다.
### YAML 구성 (권장)
YAML 구성을 사용하면 작업을 정의할 때 더 깔끔하고 유지 관리가 용이한 방법을 제공합니다. CrewAI 프로젝트에서 작업을 정의할 때 이 방식을 사용하는 것을 강력히 권장합니다.
[설치](/ko/installation) 섹션에 따라 CrewAI 프로젝트를 생성한 후, `src/latest_ai_development/config/tasks.yaml` 파일로 이동하여 템플릿을 귀하의 특정 작업 요구 사항에 맞게 수정하세요.
<Note>
YAML 파일 내 변수(예: `{topic}`)는 크루를 실행할 때 입력값에서 가져온 값으로 대체됩니다:
```python Code
crew.kickoff(inputs={'topic': 'AI Agents'})
```
</Note>
아래는 YAML을 사용하여 작업을 구성하는 방법의 예시입니다:
```yaml tasks.yaml
research_task:
description: >
Conduct a thorough research about {topic}
Make sure you find any interesting and relevant information given
the current year is 2025.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher
reporting_task:
description: >
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
expected_output: >
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
agent: reporting_analyst
markdown: true
output_file: report.md
```
이 YAML 구성을 코드에서 사용하려면 `CrewBase`를 상속받는 크루 클래스를 생성하세요:
```python crew.py
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
@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
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'] # type: ignore[index]
)
@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task'] # type: ignore[index]
)
@crew
def crew(self) -> Crew:
return Crew(
agents=[
self.researcher(),
self.reporting_analyst()
],
tasks=[
self.research_task(),
self.reporting_task()
],
process=Process.sequential
)
```
<Note>
YAML 파일(`agents.yaml` 및 `tasks.yaml`)에서 사용하는 이름은 Python 코드의 메서드 이름과 일치해야 합니다.
</Note>
### 코드에서 직접 태스크 정의 (대안)
또는 YAML 구성 없이 코드에서 직접 태스크를 정의할 수 있습니다:
```python task.py
from crewai import Task
research_task = Task(
description="""
Conduct a thorough research about AI Agents.
Make sure you find any interesting and relevant information given
the current year is 2025.
""",
expected_output="""
A list with 10 bullet points of the most relevant information about AI Agents
""",
agent=researcher
)
reporting_task = Task(
description="""
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
""",
expected_output="""
A fully fledge reports with the mains topics, each with a full section of information.
""",
agent=reporting_analyst,
markdown=True, # Enable markdown formatting for the final output
output_file="report.md"
)
```
<Tip>
`agent`를 직접 지정하여 할당하거나, 역할·가용성 등에 따라 `hierarchical` CrewAI 프로세스가 자동으로 결정하도록 둘 수 있습니다.
</Tip>
## 작업 결과
작업 결과를 이해하는 것은 효과적인 AI 워크플로우를 구축하는 데 매우 중요합니다. CrewAI는 여러 출력 형식을 지원하는 `TaskOutput` 클래스를 통해 작업 결과를 구조적으로 처리할 수 있는 방식을 제공합니다. 이 클래스는 작업 간에 출력값을 쉽게 전달할 수 있도록 지원합니다.
CrewAI 프레임워크에서 작업의 출력은 `TaskOutput` 클래스에 캡슐화되어 있습니다. 이 클래스는 작업의 결과를 구조적으로 접근할 수 있도록 해주며, raw 출력, JSON, Pydantic 모델 등 다양한 형식을 지원합니다.
기본적으로 `TaskOutput`에는 `raw` 출력만 포함됩니다. 원래의 `Task` 객체가 각각 `output_pydantic` 또는 `output_json`으로 구성된 경우에만 `TaskOutput`에 `pydantic` 또는 `json_dict` 출력이 포함됩니다.
### 작업 출력 속성
| 속성 | 파라미터 | 타입 | 설명 |
| :---------------- | :----------------- | :------------------------- | :---------------------------------------------------------------------------------------------------- |
| **설명** | `description` | `str` | 작업에 대한 설명입니다. |
| **요약** | `summary` | `Optional[str]` | 설명의 처음 10단어에서 자동 생성된 작업의 요약입니다. |
| **Raw** | `raw` | `str` | 작업의 원시 출력값입니다. 출력의 기본 형식입니다. |
| **Pydantic** | `pydantic` | `Optional[BaseModel]` | 작업의 구조화된 출력을 나타내는 Pydantic 모델 객체입니다. |
| **JSON Dict** | `json_dict` | `Optional[Dict[str, Any]]` | 작업의 JSON 출력을 나타내는 딕셔너리입니다. |
| **Agent** | `agent` | `str` | 작업을 실행한 agent입니다. |
| **Output Format** | `output_format` | `OutputFormat` | 작업 출력의 형식입니다. RAW, JSON, Pydantic 옵션이 있으며, 기본값은 RAW입니다. |
### 태스크 메서드 및 프로퍼티
| Method/Property | 설명 |
| :-------------- | :------------------------------------------------------------------------------------------------- |
| **json** | 출력 포맷이 JSON일 경우 태스크 출력의 JSON 문자열 표현을 반환합니다. |
| **to_dict** | JSON 및 Pydantic 출력을 딕셔너리로 변환합니다. |
| **str** | 태스크 출력의 문자열 표현을 반환하며, Pydantic을 우선으로 하고 그 다음은 JSON, 그 다음은 raw를 사용합니다. |
### 작업 출력 액세스
작업이 실행된 후에는 `Task` 객체의 `output` 속성을 통해 그 출력을 액세스할 수 있습니다. `TaskOutput` 클래스는 이 출력을 다양한 방식으로 상호작용하고 표시할 수 있는 기능을 제공합니다.
#### 예시
```python Code
# Example task
task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
# Execute the crew
crew = Crew(
agents=[research_agent],
tasks=[task],
verbose=True
)
result = crew.kickoff()
# Accessing the task output
task_output = task.output
print(f"Task Description: {task_output.description}")
print(f"Task Summary: {task_output.summary}")
print(f"Raw Output: {task_output.raw}")
if task_output.json_dict:
print(f"JSON Output: {json.dumps(task_output.json_dict, indent=2)}")
if task_output.pydantic:
print(f"Pydantic Output: {task_output.pydantic}")
```
## 마크다운 출력 포매팅
`markdown` 매개변수는 작업 출력에 대해 자동 마크다운 포매팅을 활성화합니다. 이 값을 `True`로 설정하면, 작업은 에이전트에게 최종 답변을 올바른 마크다운 문법으로 포매팅하도록 지시합니다.
### 마크다운(Markdown) 포매팅 사용하기
```python Code
# Example task with markdown formatting enabled
formatted_task = Task(
description="Create a comprehensive report on AI trends",
expected_output="A well-structured report with headers, sections, and bullet points",
agent=reporter_agent,
markdown=True # Enable automatic markdown formatting
)
```
`markdown=True`일 때, 에이전트는 다음과 같이 출력을 포매팅하라는 추가 지시를 받게 됩니다:
- 헤더에는 `#` 사용
- 볼드체는 `**텍스트**` 사용
- 이탤릭체는 `*텍스트*` 사용
- 불릿 포인트에는 `-` 또는 `*` 사용
- 인라인 코드는 `` `코드` `` 사용
- 코드 블록은 ``` ```언어 ``` 사용
### 마크다운을 활용한 YAML 구성
```yaml tasks.yaml
analysis_task:
description: >
Analyze the market data and create a detailed report
expected_output: >
A comprehensive analysis with charts and key findings
agent: analyst
markdown: true # Enable markdown formatting
output_file: analysis.md
```
### 마크다운 출력의 이점
- **일관된 포맷팅**: 모든 출력이 올바른 마크다운 규칙을 따르도록 보장합니다
- **향상된 가독성**: 헤더, 목록, 강조 등으로 구조화된 콘텐츠
- **문서화에 적합**: 출력을 문서 시스템에서 바로 사용할 수 있습니다
- **크로스 플랫폼 호환성**: 마크다운은 보편적으로 지원됩니다
<Note>
마크다운 포맷팅 지침은 `markdown=True`일 때 작업 프롬프트에 자동으로 추가되므로, 작업 설명에 포맷팅 요구사항을 따로 명시할 필요가 없습니다.
</Note>
## 작업 종속성 및 컨텍스트
작업은 `context` 속성을 사용하여 다른 작업의 출력에 의존할 수 있습니다. 예를 들어:
```python Code
research_task = Task(
description="Research the latest developments in AI",
expected_output="A list of recent AI developments",
agent=researcher
)
analysis_task = Task(
description="Analyze the research findings and identify key trends",
expected_output="Analysis report of AI trends",
agent=analyst,
context=[research_task] # This task will wait for research_task to complete
)
```
## 작업 가드레일
작업 가드레일은 작업 출력물을 다음 작업에 전달하기 전에 유효성을 검사하고 변환할 수 있는 방식을 제공합니다. 이 기능은 데이터 품질을 보장하고 에이전트의 출력이 특정 기준을 충족하지 않을 때 피드백을 제공하는 데 도움이 됩니다.
가드레일은 사용자 지정 유효성 검사 로직을 포함하는 Python 함수로 구현되며, 유효성 검사 프로세스를 완전히 제어할 수 있어 신뢰할 수 있고 결정적인 결과를 보장합니다.
### 함수 기반 가드레일
함수 기반 가드레일을 태스크에 추가하려면 `guardrail` 파라미터를 통해 검증 함수를 제공하세요:
```python Code
from typing import Tuple, Union, Dict, Any
from crewai import TaskOutput
def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate blog content meets requirements."""
try:
# Check word count
word_count = len(result.split())
if word_count > 200:
return (False, "Blog content exceeds 200 words")
# Additional validation logic here
return (True, result.strip())
except Exception as e:
return (False, "Unexpected error during validation")
blog_task = Task(
description="Write a blog post about AI",
expected_output="A blog post under 200 words",
agent=blog_agent,
guardrail=validate_blog_content # Add the guardrail function
)
```
### Guardrail 함수 요구사항
1. **함수 시그니처**:
- 정확히 하나의 매개변수(태스크 출력)를 받아야 함
- `(bool, Any)` 형태의 튜플을 반환해야 함
- 타입 힌트는 권장하지만 필수는 아님
2. **반환 값**:
- 성공 시: `(bool, Any)` 형태의 튜플을 반환. 예: `(True, validated_result)`
- 실패 시: `(bool, str)` 형태의 튜플을 반환. 예: `(False, "Error message explain the failure")`
### 오류 처리 모범 사례
1. **구조화된 오류 응답**:
```python Code
from crewai import TaskOutput, LLMGuardrail
def validate_with_context(result: TaskOutput) -> Tuple[bool, Any]:
try:
# Main validation logic
validated_data = perform_validation(result)
return (True, validated_data)
except ValidationError as e:
return (False, f"VALIDATION_ERROR: {str(e)}")
except Exception as e:
return (False, str(e))
```
2. **오류 범주**:
- 구체적인 오류 코드 사용
- 관련 컨텍스트 포함
- 실행 가능한 피드백 제공
3. **검증 체인**:
```python Code
from typing import Any, Dict, List, Tuple, Union
from crewai import TaskOutput
def complex_validation(result: TaskOutput) -> Tuple[bool, Any]:
"""Chain multiple validation steps."""
# Step 1: Basic validation
if not result:
return (False, "Empty result")
# Step 2: Content validation
try:
validated = validate_content(result)
if not validated:
return (False, "Invalid content")
# Step 3: Format validation
formatted = format_output(validated)
return (True, formatted)
except Exception as e:
return (False, str(e))
```
### 가드레일 결과 처리
가드레일이 `(False, error)`를 반환할 때:
1. 에러가 에이전트에게 다시 전달됩니다
2. 에이전트가 문제를 수정하려고 시도합니다
3. 다음 중 하나가 될 때까지 이 과정이 반복됩니다:
- 가드레일이 `(True, result)`를 반환함
- 최대 재시도 횟수에 도달함
재시도 처리가 포함된 예시:
```python Code
from typing import Optional, Tuple, Union
from crewai import TaskOutput, Task
def validate_json_output(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate and parse JSON output."""
try:
# Try to parse as JSON
data = json.loads(result)
return (True, data)
except json.JSONDecodeError as e:
return (False, "Invalid JSON format")
task = Task(
description="Generate a JSON report",
expected_output="A valid JSON object",
agent=analyst,
guardrail=validate_json_output,
max_retries=3 # Limit retry attempts
)
```
## 작업에서 구조화된 일관된 출력 얻기
<Note>
또한 crew의 마지막 작업의 출력이 실제 crew 자체의 최종 출력이 된다는 점도 중요합니다.
</Note>
### `output_pydantic` 사용하기
`output_pydantic` 속성을 사용하면 작업 출력이 준수해야 할 Pydantic 모델을 정의할 수 있습니다. 이를 통해 출력이 구조화될 뿐만 아니라 Pydantic 모델에 따라 유효성 검증도 보장할 수 있습니다.
다음은 output_pydantic을 사용하는 방법을 보여주는 예제입니다.
```python Code
import json
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
class Blog(BaseModel):
title: str
content: str
blog_agent = Agent(
role="Blog Content Generator Agent",
goal="Generate a blog title and content",
backstory="""You are an expert content creator, skilled in crafting engaging and informative blog posts.""",
verbose=False,
allow_delegation=False,
llm="gpt-4o",
)
task1 = Task(
description="""Create a blog title and content on a given topic. Make sure the content is under 200 words.""",
expected_output="A compelling blog title and well-written content.",
agent=blog_agent,
output_pydantic=Blog,
)
# Instantiate your crew with a sequential process
crew = Crew(
agents=[blog_agent],
tasks=[task1],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()
# Option 1: Accessing Properties Using Dictionary-Style Indexing
print("Accessing Properties - Option 1")
title = result["title"]
content = result["content"]
print("Title:", title)
print("Content:", content)
# Option 2: Accessing Properties Directly from the Pydantic Model
print("Accessing Properties - Option 2")
title = result.pydantic.title
content = result.pydantic.content
print("Title:", title)
print("Content:", content)
# Option 3: Accessing Properties Using the to_dict() Method
print("Accessing Properties - Option 3")
output_dict = result.to_dict()
title = output_dict["title"]
content = output_dict["content"]
print("Title:", title)
print("Content:", content)
# Option 4: Printing the Entire Blog Object
print("Accessing Properties - Option 5")
print("Blog:", result)
```
이 예제에서:
* title과 content 필드를 가진 Pydantic 모델 Blog가 정의되어 있습니다.
* 작업 task1은 output_pydantic 속성을 사용하여 출력이 Blog 모델을 준수해야 함을 명시합니다.
* crew를 실행한 후, 위와 같이 다양한 방법으로 구조화된 출력을 확인할 수 있습니다.
#### 출력 접근 방법 설명
1. 딕셔너리 스타일 인덱싱: `result["field_name"]`을 사용하여 필드를 직접 접근할 수 있습니다. 이는 CrewOutput 클래스가 `__getitem__` 메서드를 구현하고 있기 때문에 가능합니다.
2. Pydantic 모델에서 직접 접근: `result.pydantic` 객체에서 속성에 직접 접근할 수 있습니다.
3. to_dict() 메서드 사용: 출력을 딕셔너리로 변환한 후 필드에 접근합니다.
4. 전체 객체 출력: 단순히 result 객체를 출력하여 구조화된 출력을 확인할 수 있습니다.
### `output_json` 사용하기
`output_json` 속성을 사용하면 예상되는 출력을 JSON 형식으로 정의할 수 있습니다. 이를 통해 태스크의 출력이 쉽게 파싱되고, 애플리케이션에서 사용할 수 있는 유효한 JSON 구조임을 보장합니다.
다음은 `output_json` 사용 방법을 보여주는 예시입니다:
```python Code
import json
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
# Define the Pydantic model for the blog
class Blog(BaseModel):
title: str
content: str
# Define the agent
blog_agent = Agent(
role="Blog Content Generator Agent",
goal="Generate a blog title and content",
backstory="""You are an expert content creator, skilled in crafting engaging and informative blog posts.""",
verbose=False,
allow_delegation=False,
llm="gpt-4o",
)
# Define the task with output_json set to the Blog model
task1 = Task(
description="""Create a blog title and content on a given topic. Make sure the content is under 200 words.""",
expected_output="A JSON object with 'title' and 'content' fields.",
agent=blog_agent,
output_json=Blog,
)
# Instantiate the crew with a sequential process
crew = Crew(
agents=[blog_agent],
tasks=[task1],
verbose=True,
process=Process.sequential,
)
# Kickoff the crew to execute the task
result = crew.kickoff()
# Option 1: Accessing Properties Using Dictionary-Style Indexing
print("Accessing Properties - Option 1")
title = result["title"]
content = result["content"]
print("Title:", title)
print("Content:", content)
# Option 2: Printing the Entire Blog Object
print("Accessing Properties - Option 2")
print("Blog:", result)
```
이 예시에서:
* Pydantic 모델인 Blog가 title과 content 필드로 정의되어 있으며, 이는 JSON 출력의 구조를 명시하는 데 사용됩니다.
* 태스크 task1은 output_json 속성을 사용하여 Blog 모델에 부합하는 JSON 출력을 기대함을 나타냅니다.
* crew를 실행한 후, 두 가지 방식으로 구조화된 JSON 출력을 접근할 수 있습니다.
#### 출력 접근 방법 설명
1. 딕셔너리 스타일 인덱싱을 사용하여 속성 접근하기: result["field_name"]과 같이 필드를 직접 접근할 수 있습니다. 이는 CrewOutput 클래스가 __getitem__ 메서드를 구현하고 있어 출력을 딕셔너리처럼 사용할 수 있기 때문입니다. 이 방법에서는 result에서 title과 content를 가져옵니다.
2. 전체 블로그 객체 출력하기: result를 출력하면 CrewOutput 객체의 문자열 표현을 얻을 수 있습니다. __str__ 메서드가 JSON 출력을 반환하도록 구현되어 있기 때문에, 전체 출력을 Blog 객체를 나타내는 형식이 잘 갖추어진 문자열로 볼 수 있습니다.
---
output_pydantic 또는 output_json을 사용하면, 작업의 출력이 일관되고 구조화된 형식으로 생성되므로 애플리케이션 내 또는 여러 작업 간에 데이터를 더 쉽게 처리하고 활용할 수 있습니다.
## 도구와 작업 통합
향상된 작업 성능과 에이전트 상호작용을 위해 [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) 및 [LangChain Tools](https://python.langchain.com/docs/integrations/tools)의 도구를 활용하세요.
## 도구와 함께 Task 생성하기
```python Code
import os
os.environ["OPENAI_API_KEY"] = "Your Key"
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
from crewai import Agent, Task, Crew
from crewai_tools import SerperDevTool
research_agent = Agent(
role='Researcher',
goal='Find and summarize the latest AI news',
backstory="""You're a researcher at a large company.
You're responsible for analyzing data and providing insights
to the business.""",
verbose=True
)
# to perform a semantic search for a specified query from a text's content across the internet
search_tool = SerperDevTool()
task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
crew = Crew(
agents=[research_agent],
tasks=[task],
verbose=True
)
result = crew.kickoff()
print(result)
```
이 예시는 특정 도구와 함께 사용되는 task가 맞춤형 task 실행을 위해 에이전트의 기본 도구 세트를 어떻게 재정의할 수 있는지 보여줍니다.
## 다른 작업 참조하기
CrewAI에서는 한 작업의 출력이 자동으로 다음 작업으로 전달되지만, 특정 작업(여러 개 포함)의 출력을 다른 작업의 컨텍스트로 명확하게 지정할 수도 있습니다.
이는 한 작업이 바로 뒤에 수행되지 않는 다른 작업의 출력에 의존해야 할 때 유용합니다. 이는 작업의 `context` 속성을 통해 수행됩니다:
```python Code
# ...
research_ai_task = Task(
description="Research the latest developments in AI",
expected_output="A list of recent AI developments",
async_execution=True,
agent=research_agent,
tools=[search_tool]
)
research_ops_task = Task(
description="Research the latest developments in AI Ops",
expected_output="A list of recent AI Ops developments",
async_execution=True,
agent=research_agent,
tools=[search_tool]
)
write_blog_task = Task(
description="Write a full blog post about the importance of AI and its latest news",
expected_output="Full blog post that is 4 paragraphs long",
agent=writer_agent,
context=[research_ai_task, research_ops_task]
)
#...
```
## 비동기 실행
작업을 비동기로 실행되도록 정의할 수 있습니다. 이는 crew가 해당 작업이 완료될 때까지 기다리지 않고 다음 작업을 계속 진행한다는 것을 의미합니다. 시간이 오래 걸리는 작업이거나, 이후 작업 수행에 필수적이지 않은 작업에 유용합니다.
이후 작업에서 비동기 작업의 출력이 완료될 때까지 기다리도록 하려면, `context` 속성을 사용할 수 있습니다.
```python Code
#...
list_ideas = Task(
description="List of 5 interesting ideas to explore for an article about AI.",
expected_output="Bullet point list of 5 ideas for an article.",
agent=researcher,
async_execution=True # Will be executed asynchronously
)
list_important_history = Task(
description="Research the history of AI and give me the 5 most important events.",
expected_output="Bullet point list of 5 important events.",
agent=researcher,
async_execution=True # Will be executed asynchronously
)
write_article = Task(
description="Write an article about AI, its history, and interesting ideas.",
expected_output="A 4 paragraph article about AI.",
agent=writer,
context=[list_ideas, list_important_history] # Will wait for the output of the two tasks to be completed
)
#...
```
## 콜백 메커니즘
콜백 함수는 작업이 완료된 후 실행되며, 작업 결과에 따라 동작 또는 알림을 트리거할 수 있습니다.
```python Code
# ...
def callback_function(output: TaskOutput):
# Do something after the task is completed
# Example: Send an email to the manager
print(f"""
Task completed!
Task: {output.description}
Output: {output.raw}
""")
research_task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool],
callback=callback_function
)
#...
```
## 특정 Task Output 접근하기
crew가 실행을 마치면, 해당 task 객체의 `output` 속성을 사용하여 특정 task의 output에 접근할 수 있습니다:
```python Code
# ...
task1 = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
#...
crew = Crew(
agents=[research_agent],
tasks=[task1, task2, task3],
verbose=True
)
result = crew.kickoff()
# Returns a TaskOutput object with the description and results of the task
print(f"""
Task completed!
Task: {task1.output.description}
Output: {task1.output.raw}
""")
```
## 도구 재정의 메커니즘
작업에서 도구를 지정하면 에이전트의 기능을 동적으로 조정할 수 있어 CrewAI의 유연성이 강조됩니다.
## 오류 처리 및 검증 메커니즘
작업을 생성하고 실행하는 동안, 작업 속성의 견고성과 신뢰성을 보장하기 위해 특정 검증 메커니즘이 마련되어 있습니다. 이는 다음에 국한되지 않습니다:
- 작업마다 한 가지 출력 유형만 설정하여 명확한 출력 기대치를 유지함
- 고유 식별자 시스템의 무결성을 유지하기 위해 `id` 속성의 수동 할당을 방지함
이러한 검증 절차는 crewAI 프레임워크 내에서 작업 실행의 일관성과 신뢰성을 유지하는 데 도움이 됩니다.
## 파일 저장 시 디렉토리 생성
`create_directory` 매개변수는 CrewAI가 작업 결과를 파일로 저장할 때 디렉토리를 자동으로 생성할지 여부를 제어합니다. 이 기능은 출력물을 체계적으로 정리하고, 특히 복잡한 프로젝트 계층 구조에서 파일 경로가 올바르게 구조화되도록 보장하는 데 매우 유용합니다.
### 기본 동작
기본적으로 `create_directory=True`로 설정되어 있으며, 이는 CrewAI가 출력 파일 경로에 누락된 디렉토리를 자동으로 생성함을 의미합니다:
```python Code
# 기본 동작 - 디렉토리가 자동으로 생성됩니다
report_task = Task(
description='Generate a comprehensive market analysis report',
expected_output='A detailed market analysis with charts and insights',
agent=analyst_agent,
output_file='reports/2025/market_analysis.md', # 'reports/2025/'가 없으면 생성됩니다
markdown=True
)
```
### 디렉터리 생성 비활성화
자동 디렉터리 생성을 방지하고 디렉터리가 이미 존재함을 보장하려면 `create_directory=False`로 설정하세요:
```python Code
# Strict mode - directory must already exist
strict_output_task = Task(
description='Save critical data that requires existing infrastructure',
expected_output='Data saved to pre-configured location',
agent=data_agent,
output_file='secure/vault/critical_data.json',
create_directory=False # Will raise RuntimeError if 'secure/vault/' doesn't exist
)
```
### YAML 구성
이 동작은 YAML 태스크 정의에서도 구성할 수 있습니다:
```yaml tasks.yaml
analysis_task:
description: >
분기별 재무 분석 생성
expected_output: >
분기별 인사이트가 포함된 종합 재무 보고서
agent: financial_analyst
output_file: reports/quarterly/q4_2024_analysis.pdf
create_directory: true # 'reports/quarterly/' 디렉토리를 자동으로 생성
audit_task:
description: >
컴플라이언스 감사 수행 및 기존 감사 디렉토리에 저장
expected_output: >
컴플라이언스 감사 보고서
agent: auditor
output_file: audit/compliance_report.md
create_directory: false # 디렉토리가 이미 존재해야 함
```
### 사용 사례
**자동 디렉토리 생성 (`create_directory=True`):**
- 개발 및 프로토타이핑 환경
- 날짜 기반 폴더로 동적 보고서 생성
- 디렉토리 구조가 달라질 수 있는 자동화된 워크플로우
- 사용자별 폴더가 필요한 멀티 테넌트 애플리케이션
**수동 디렉토리 관리 (`create_directory=False`):**
- 엄격한 파일 시스템 제어가 필요한 운영 환경
- 디렉토리가 사전 구성되어야 하는 보안 민감 애플리케이션
- 특정 권한 요구 사항이 있는 시스템
- 디렉토리 생성이 감사되는 규정 준수 환경
### 오류 처리
`create_directory=False`이고 디렉토리가 존재하지 않는 경우, CrewAI는 `RuntimeError`를 발생시킵니다:
```python Code
try:
result = crew.kickoff()
except RuntimeError as e:
# Handle missing directory error
print(f"Directory creation failed: {e}")
# Create directory manually or use fallback location
```
아래 영상을 통해 CrewAI에서 구조화된 출력을 사용하는 방법을 확인하세요:
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/dNpKQk5uxHw"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
## 결론
작업(task)은 CrewAI 에이전트의 행동을 이끄는 원동력입니다.
작업과 그 결과를 적절하게 정의함으로써, 에이전트가 독립적으로 또는 협업 단위로 효과적으로 작동할 수 있는 기반을 마련할 수 있습니다.
작업에 적합한 도구를 장착하고, 실행 과정을 이해하며, 견고한 검증 절차를 따르는 것은 CrewAI의 잠재력을 극대화하는 데 필수적입니다.
이를 통해 에이전트가 할당된 작업에 효과적으로 준비되고, 작업이 의도대로 수행될 수 있습니다.

View File

@@ -0,0 +1,48 @@
---
title: 테스트
description: CrewAI Crew를 테스트하고 그 성능을 평가하는 방법을 알아보세요.
icon: vial
---
## 개요
테스트는 개발 프로세스에서 매우 중요한 부분이며, crew가 예상대로 동작하는지 확인하는 것이 필수적입니다. crewAI를 사용하면 내장된 테스트 기능을 통해 crew를 쉽게 테스트하고 성능을 평가할 수 있습니다.
### 테스트 기능 사용하기
CLI 명령어 `crewai test`를 추가하여 crew 테스트를 쉽게 할 수 있습니다. 이 명령어는 지정한 반복 횟수만큼 crew를 실행하고, 자세한 성능 지표를 제공합니다. 매개변수로는 `n_iterations`와 `model`이 있으며, 이들은 선택 사항이고 각각 기본값은 2와 `gpt-4o-mini`입니다. 현재는 OpenAI만 지원됩니다.
```bash
crewai test
```
더 많은 반복 횟수로 실행하거나 다른 모델을 사용하려면 다음과 같이 매개변수를 지정할 수 있습니다:
```bash
crewai test --n_iterations 5 --model gpt-4o
```
또는 축약형을 사용할 수 있습니다:
```bash
crewai test -n 5 -m gpt-4o
```
`crewai test` 명령어를 실행하면 crew가 지정한 횟수만큼 실행되고, 수행이 끝나면 성능 지표가 표시됩니다.
실행 마지막에 표시되는 점수 표는 다음과 같은 지표로 crew의 성능을 보여줍니다:
<center>**작업 점수 (1-10 높을수록 좋음)**</center>
| Tasks/Crew/Agents | Run 1 | Run 2 | Avg. Total | Agents | Additional Info |
|:------------------|:-----:|:-----:|:----------:|:------------------------------:|:---------------------------------|
| Task 1 | 9.0 | 9.5 | **9.2** | Professional Insights | |
| | | | | Researcher | |
| Task 2 | 9.0 | 10.0 | **9.5** | Company Profile Investigator | |
| Task 3 | 9.0 | 9.0 | **9.0** | Automation Insights | |
| | | | | Specialist | |
| Task 4 | 9.0 | 9.0 | **9.0** | Final Report Compiler | Automation Insights Specialist |
| Crew | 9.00 | 9.38 | **9.2** | | |
| Execution Time (s) | 126 | 145 | **135** | | |
위 예시는 두 번 실행한 crew의 테스트 결과를 보여주며, 각 작업과 crew 전체의 평균 총점이 포함되어 있습니다.

282
docs/ko/concepts/tools.mdx Normal file
View File

@@ -0,0 +1,282 @@
---
title: 도구
description: CrewAI 프레임워크 내에서 에이전트 협업과 작업 실행을 위해 도구를 이해하고 활용하기.
icon: screwdriver-wrench
---
## 개요
CrewAI 도구는 에이전트에게 웹 검색, 데이터 분석부터 동료 간 협업 및 작업 위임에 이르기까지 다양한 기능을 제공합니다.
이 문서에서는 CrewAI 프레임워크 내에서 이러한 도구를 생성, 통합 및 활용하는 방법과, 협업 도구에 초점을 맞춘 새로운 기능에 대해 설명합니다.
## Tool이란 무엇인가?
CrewAI에서 tool은 에이전트가 다양한 작업을 수행하기 위해 활용할 수 있는 기술 또는 기능입니다.
이에는 [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) 및 [LangChain Tools](https://python.langchain.com/docs/integrations/tools)의 tool이 포함되어,
간단한 검색부터 복잡한 상호작용, 그리고 에이전트 간의 효과적인 협업까지 모두 가능하게 합니다.
<Note type="info" title="엔터프라이즈 확장: Tools Repository">
CrewAI 엔터프라이즈는 주요 비즈니스 시스템 및 API와의 사전 구축된 통합을 제공하는 종합적인 Tools Repository를 제공합니다. 며칠이 걸리던 엔터프라이즈 tool로 에이전트를 몇 분 만에 배포할 수 있습니다.
엔터프라이즈 Tools Repository에는 다음이 포함됩니다:
- 인기 엔터프라이즈 시스템용 사전 구축 커넥터
- 커스텀 tool 생성 인터페이스
- 버전 관리 및 공유 기능
- 보안 및 규정 준수 기능
</Note>
## 도구의 주요 특징
- **유틸리티**: 웹 검색, 데이터 분석, 콘텐츠 생성, 에이전트 협업과 같은 작업을 위해 제작됨.
- **통합성**: 도구를 워크플로우에 원활하게 통합하여 에이전트의 역량을 강화함.
- **맞춤화 가능성**: 맞춤형 도구를 개발하거나 기존 도구를 활용할 수 있는 유연성을 제공하여 에이전트의 특정 요구 사항에 대응함.
- **오류 처리**: 원활한 작동을 보장하기 위해 강력한 오류 처리 메커니즘을 포함함.
- **캐싱 메커니즘**: 성능 최적화와 중복 작업 감소를 위한 지능형 캐싱 기능을 갖춤.
- **비동기 지원**: 동기 및 비동기 도구를 모두 처리하여 논블로킹(Non-blocking) 작업을 가능하게 함.
## CrewAI 도구 사용하기
crewAI 도구로 에이전트의 기능을 확장하려면, 우선 추가 도구 패키지를 설치하세요:
```bash
pip install 'crewai[tools]'
```
아래는 도구 사용 예시입니다:
```python Code
import os
from crewai import Agent, Task, Crew
# crewAI 도구 임포트
from crewai_tools import (
DirectoryReadTool,
FileReadTool,
SerperDevTool,
WebsiteSearchTool
)
# API 키 설정
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API 키
os.environ["OPENAI_API_KEY"] = "Your Key"
# 도구 인스턴스화
docs_tool = DirectoryReadTool(directory='./blog-posts')
file_tool = FileReadTool()
search_tool = SerperDevTool()
web_rag_tool = WebsiteSearchTool()
# 에이전트 생성
researcher = Agent(
role='Market Research Analyst',
goal='Provide up-to-date market analysis of the AI industry',
backstory='An expert analyst with a keen eye for market trends.',
tools=[search_tool, web_rag_tool],
verbose=True
)
writer = Agent(
role='Content Writer',
goal='Craft engaging blog posts about the AI industry',
backstory='A skilled writer with a passion for technology.',
tools=[docs_tool, file_tool],
verbose=True
)
# 작업 정의
research = Task(
description='Research the latest trends in the AI industry and provide a summary.',
expected_output='A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.',
agent=researcher
)
write = Task(
description='Write an engaging blog post about the AI industry, based on the research analyst's summary. Draw inspiration from the latest blog posts in the directory.',
expected_output='A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.',
agent=writer,
output_file='blog-posts/new_post.md' # 최종 블로그 글이 여기에 저장됩니다
)
# 계획 기능을 활성화하여 crew 구성
crew = Crew(
agents=[researcher, writer],
tasks=[research, write],
verbose=True,
planning=True, # 계획 기능 활성화
)
# 작업 실행
crew.kickoff()
```
## 사용 가능한 CrewAI 도구
- **에러 처리**: 모든 도구는 에러 처리 기능이 내장되어 있어, 에이전트가 예외 상황을 우아하게 관리하며 작업을 계속할 수 있습니다.
- **캐싱 메커니즘**: 모든 도구는 캐싱을 지원하여, 에이전트가 이전에 얻은 결과를 효율적으로 재사용할 수 있고 외부 자원에 대한 부하를 줄이며 실행 시간을 단축할 수 있습니다. 또한 도구의 `cache_function` 속성을 사용하여 캐싱 메커니즘을 세밀하게 제어할 수 있습니다.
사용 가능한 도구 목록과 그 설명은 다음과 같습니다:
| 도구 | 설명 |
| :-------------------------------- | :---------------------------------------------------------------------------------------------------- |
| **ApifyActorsTool** | 웹 스크래핑 및 자동화 작업을 위해 Apify Actors를 워크플로우에 통합하는 도구입니다. |
| **BrowserbaseLoadTool** | 웹 브라우저와 상호작용하고 데이터를 추출하는 도구입니다. |
| **CodeDocsSearchTool** | 코드 문서 및 관련 기술 문서를 검색하는 데 최적화된 RAG 도구입니다. |
| **CodeInterpreterTool** | 파이썬 코드를 해석하는 도구입니다. |
| **ComposioTool** | Composio 도구의 사용을 가능하게 합니다. |
| **CSVSearchTool** | CSV 파일 내에서 검색하도록 설계된 RAG 도구이며, 구조화된 데이터를 처리하도록 맞춤화되어 있습니다. |
| **DALL-E Tool** | DALL-E API를 사용해 이미지를 생성하는 도구입니다. |
| **DirectorySearchTool** | 디렉터리 내에서 검색하는 RAG 도구로, 파일 시스템을 탐색할 때 유용합니다. |
| **DOCXSearchTool** | DOCX 문서 내에서 검색하는 데 특화된 RAG 도구로, Word 파일을 처리할 때 이상적입니다. |
| **DirectoryReadTool** | 디렉터리 구조와 그 내용을 읽고 처리하도록 지원하는 도구입니다. |
| **EXASearchTool** | 다양한 데이터 소스를 폭넓게 검색하기 위해 설계된 도구입니다. |
| **FileReadTool** | 다양한 파일 형식을 지원하며 파일에서 데이터를 읽고 추출할 수 있는 도구입니다. |
| **FirecrawlSearchTool** | Firecrawl을 이용해 웹페이지를 검색하고 결과를 반환하는 도구입니다. |
| **FirecrawlCrawlWebsiteTool** | Firecrawl을 사용해 웹페이지를 크롤링하는 도구입니다. |
| **FirecrawlScrapeWebsiteTool** | Firecrawl을 통해 웹페이지의 URL을 스크래핑하고 그 내용을 반환하는 도구입니다. |
| **GithubSearchTool** | GitHub 저장소 내에서 검색하는 RAG 도구로, 코드 및 문서 검색에 유용합니다. |
| **SerperDevTool** | 개발 용도로 특화된 도구로, 특정 기능이 개발 중입니다. |
| **TXTSearchTool** | 텍스트(.txt) 파일 내에서 검색하는 데 중점을 둔 RAG 도구로, 비구조적 데이터에 적합합니다. |
| **JSONSearchTool** | JSON 파일 내에서 검색하도록 설계된 RAG 도구로, 구조화된 데이터 처리에 적합합니다. |
| **LlamaIndexTool** | LlamaIndex 도구의 사용을 가능하게 합니다. |
| **MDXSearchTool** | 마크다운(MDX) 파일 내에서 검색하도록 맞춤화된 RAG 도구로, 문서화에 유용합니다. |
| **PDFSearchTool** | PDF 문서 내에서 검색하는 RAG 도구로, 스캔된 문서를 처리하기에 이상적입니다. |
| **PGSearchTool** | PostgreSQL 데이터베이스 내에서 검색하는 데 최적화된 RAG 도구로, 데이터베이스 쿼리에 적합합니다. |
| **Vision Tool** | DALL-E API를 사용해 이미지를 생성하는 도구입니다. |
| **RagTool** | 다양한 데이터 소스 및 형식을 처리할 수 있는 범용 RAG 도구입니다. |
| **ScrapeElementFromWebsiteTool** | 웹사이트에서 특정 요소만 스크래핑할 수 있는 도구로, 목표 데이터 추출에 유용합니다. |
| **ScrapeWebsiteTool** | 전체 웹사이트를 스크래핑할 수 있도록 도와주는 도구로, 포괄적인 데이터 수집에 이상적입니다. |
| **WebsiteSearchTool** | 웹사이트 콘텐츠를 검색하는 RAG 도구로, 웹 데이터 추출에 최적화되어 있습니다. |
| **XMLSearchTool** | XML 파일 내에서 검색하도록 설계된 RAG 도구로, 구조화된 데이터 형식에 적합합니다. |
| **YoutubeChannelSearchTool** | 유튜브 채널 내에서 검색하는 RAG 도구로, 동영상 콘텐츠 분석에 유용합니다. |
| **YoutubeVideoSearchTool** | 유튜브 동영상 내에서 검색하는 RAG 도구로, 동영상 데이터 추출에 이상적입니다. |
## 자체 도구 만들기
<Tip>
개발자는 에이전트의 요구에 맞는 `custom tools`를 직접 제작하거나,
미리 구축된 옵션을 활용할 수 있습니다.
</Tip>
CrewAI 도구를 만드는 방법에는 두 가지 주요 방법이 있습니다:
### `BaseTool` 서브클래싱
```python Code
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class MyToolInput(BaseModel):
"""Input schema for MyCustomTool."""
argument: str = Field(..., description="Description of the argument.")
class MyCustomTool(BaseTool):
name: str = "Name of my tool"
description: str = "What this tool does. It's vital for effective utilization."
args_schema: Type[BaseModel] = MyToolInput
def _run(self, argument: str) -> str:
# Your tool's logic here
return "Tool's result"
```
## 비동기 도구 지원
CrewAI는 비동기 도구를 지원하여, 네트워크 요청, 파일 I/O 또는 기타 비동기 작업과 같이 메인 실행 스레드를 차단하지 않고 비차단 연산을 수행하는 도구를 구현할 수 있습니다.
### 비동기 툴 만들기
비동기 툴을 만드는 방법에는 두 가지가 있습니다:
#### 1. `tool` 데코레이터를 비동기 함수와 함께 사용하기
```python Code
from crewai.tools import tool
@tool("fetch_data_async")
async def fetch_data_async(query: str) -> str:
"""Asynchronously fetch data based on the query."""
# Simulate async operation
await asyncio.sleep(1)
return f"Data retrieved for {query}"
```
#### 2. 사용자 지정 Tool 클래스에서 비동기 메서드 구현
```python Code
from crewai.tools import BaseTool
class AsyncCustomTool(BaseTool):
name: str = "async_custom_tool"
description: str = "An asynchronous custom tool"
async def _run(self, query: str = "") -> str:
"""Asynchronously run the tool"""
# Your async implementation here
await asyncio.sleep(1)
return f"Processed {query} asynchronously"
```
### 비동기 도구 사용하기
비동기 도구는 표준 Crew 워크플로우와 Flow 기반 워크플로우 모두에서 원활하게 작동합니다:
```python Code
# In standard Crew
agent = Agent(role="researcher", tools=[async_custom_tool])
# In Flow
class MyFlow(Flow):
@start()
async def begin(self):
crew = Crew(agents=[agent])
result = await crew.kickoff_async()
return result
```
CrewAI 프레임워크는 동기 및 비동기 도구의 실행을 자동으로 처리하므로, 별도로 호출 방법을 신경 쓸 필요가 없습니다.
### `tool` 데코레이터 활용하기
```python Code
from crewai.tools import tool
@tool("Name of my tool")
def my_tool(question: str) -> str:
"""Clear description for what this tool is useful for, your agent will need this information to use it."""
# Function logic here
return "Result from your custom tool"
```
### 커스텀 캐싱 메커니즘
<Tip>
도구는 선택적으로 `cache_function`을 구현하여 캐싱 동작을 세밀하게 조정할 수 있습니다.
이 함수는 특정 조건에 따라 결과를 언제 캐싱할지 결정하여 캐싱 로직을 정교하게 제어할 수 있도록 합니다.
</Tip>
```python Code
from crewai.tools import tool
@tool
def multiplication_tool(first_number: int, second_number: int) -> str:
"""Useful for when you need to multiply two numbers together."""
return first_number * second_number
def cache_func(args, result):
# In this case, we only cache the result if it's a multiple of 2
cache = result % 2 == 0
return cache
multiplication_tool.cache_function = cache_func
writer1 = Agent(
role="Writer",
goal="You write lessons of math for kids.",
backstory="You're an expert in writing and you love to teach kids but you know nothing of math.",
tools=[multiplication_tool],
allow_delegation=False,
)
#...
```
## 결론
도구는 CrewAI 에이전트의 역량을 확장하는 데 중요한 역할을 하며, 이를 통해 에이전트가 폭넓은 작업을 수행하고 효과적으로 협업할 수 있습니다. CrewAI로 솔루션을 구축할 때는, 맞춤형 또는 기존의 도구를 모두 활용하여 에이전트를 강화하고 AI 생태계를 향상시키세요. 에이전트의 성능과 기능을 최적화하기 위해 오류 처리, 캐싱 메커니즘, 그리고 도구 인자의 유연성도 고려해보시기 바랍니다.

View File

@@ -0,0 +1,131 @@
---
title: 교육
description: 피드백을 조기에 제공하여 CrewAI 에이전트를 학습시키고 일관된 결과를 얻는 방법을 알아보세요.
icon: dumbbell
---
## 개요
CrewAI의 학습 기능을 사용하면 커맨드라인 인터페이스(CLI)를 통해 AI 에이전트를 학습시킬 수 있습니다.
`crewai train -n <n_iterations>` 명령어를 실행하면 학습 프로세스의 반복 횟수를 지정할 수 있습니다.
학습 과정에서 CrewAI는 에이전트의 성능을 최적화하기 위한 다양한 기법과 인간의 피드백을 활용합니다.
이를 통해 에이전트는 이해력, 의사결정 능력, 문제 해결 능력을 향상할 수 있습니다.
### CLI를 사용하여 Crew 학습시키기
학습 기능을 사용하려면 다음 단계를 따르십시오:
1. 터미널 또는 명령 프롬프트를 엽니다.
2. CrewAI 프로젝트가 위치한 디렉터리로 이동합니다.
3. 다음 명령어를 실행합니다:
```shell
crewai train -n <n_iterations> <filename> (optional)
```
<Tip>
`<n_iterations>`를 원하는 학습 반복 횟수로, `<filename>`을 `.pkl`로 끝나는 적절한 파일 이름으로 바꿔 입력하세요.
</Tip>
### 크루를 프로그래밍 방식으로 훈련시키기
크루를 프로그래밍 방식으로 훈련시키려면 다음 단계를 따르세요:
1. 훈련을 위한 반복 횟수를 정의합니다.
2. 훈련 프로세스에 사용할 입력 파라미터를 지정합니다.
3. 잠재적인 오류를 처리하기 위해 try-except 블록 내에서 훈련 명령을 실행합니다.
```python Code
n_iterations = 2
inputs = {"topic": "CrewAI Training"}
filename = "your_model.pkl"
try:
YourCrewName_Crew().crew().train(
n_iterations=n_iterations,
inputs=inputs,
filename=filename
)
except Exception as e:
raise Exception(f"An error occurred while training the crew: {e}")
```
### 주요 참고 사항
- **양의 정수 필수 조건:** 반복 횟수(`n_iterations`)가 양의 정수인지 확인하세요. 이 조건이 충족되지 않으면 코드에서 `ValueError`가 발생합니다.
- **파일명 필수 조건:** 파일명이 `.pkl`로 끝나는지 확인하세요. 이 조건이 충족되지 않으면 코드에서 `ValueError`가 발생합니다.
- **에러 처리:** 코드는 서브프로세스 오류 및 예기치 않은 예외를 처리하며, 사용자에게 에러 메시지를 제공합니다.
에이전트의 복잡성에 따라 훈련 과정이 다소 시간이 소요될 수 있으며, 각 반복마다 사용자의 피드백이 필요함을 유의하세요.
훈련이 완료되면, 에이전트는 향상된 능력과 지식을 갖추게 되어, 더욱 복잡한 작업을 해결하고 일관성 있고 가치 있는 인사이트를 제공할 수 있습니다.
에이전트를 정기적으로 업데이트하고 재훈련하여 최신 정보와 업계 발전을 반영할 수 있도록 하세요.
CrewAI와 함께 즐거운 훈련 되세요! 🚀
## 소형 언어 모델 고려사항
<Warning>
소형 언어 모델(≤7B 파라미터)을 학습 데이터 평가에 사용할 때, 구조화된 출력 생성 및 복잡한 지침 준수에 어려움을 겪을 수 있으니 주의하시기 바랍니다.
</Warning>
### 소형 모델의 학습 평가 한계
<CardGroup cols={2}>
<Card title="JSON 출력 정확도" icon="triangle-exclamation">
소형 모델은 구조화된 학습 평가에 필요한 유효한 JSON 응답을 생성하는 데 종종 어려움을 겪으며, 이로 인해 파싱 오류와 불완전한 데이터가 발생할 수 있습니다.
</Card>
<Card title="평가 품질" icon="chart-line">
7B 파라미터 미만의 모델은 대형 모델에 비해 더 제한적이고 깊이 있는 추론이 부족한 평가 결과를 제공할 수 있습니다.
</Card>
<Card title="지침 준수" icon="list-check">
복잡한 학습 평가 기준을 소형 모델이 완전히 따르거나 고려하지 못할 수 있습니다.
</Card>
<Card title="일관성" icon="rotate">
소형 모델은 여러 학습 반복 과정에서 평가의 일관성이 부족할 수 있습니다.
</Card>
</CardGroup>
### 학습을 위한 권장 사항
<Tabs>
<Tab title="Best Practice">
최적의 학습 품질과 신뢰할 수 있는 평가를 위해 최소 7B 파라미터 이상의 모델을 사용하는 것을 강력히 권장합니다:
```python
from crewai import Agent, Crew, Task, LLM
# Recommended minimum for training evaluation
llm = LLM(model="mistral/open-mistral-7b")
# Better options for reliable training evaluation
llm = LLM(model="anthropic/claude-3-sonnet-20240229-v1:0")
llm = LLM(model="gpt-4o")
# Use this LLM with your agents
agent = Agent(
role="Training Evaluator",
goal="Provide accurate training feedback",
llm=llm
)
```
<Tip>
더 강력한 모델일수록 더 우수한 피드백과 뛰어난 추론을 제공하므로, 더욱 효과적인 학습 반복이 가능합니다.
</Tip>
</Tab>
<Tab title="Small Model Usage">
학습 평가를 위해 반드시 소형 모델을 사용해야 한다면 다음과 같은 제약 사항에 유의하세요:
```python
# Using a smaller model (expect some limitations)
llm = LLM(model="huggingface/microsoft/Phi-3-mini-4k-instruct")
```
<Warning>
CrewAI는 소형 모델에 대한 최적화 기능을 포함하고 있지만, 더 많은 인간의 개입이 필요한 덜 신뢰할 수 있고 세밀하지 않은 평가 결과가 발생할 수 있습니다.
</Warning>
</Tab>
</Tabs>

View File

@@ -0,0 +1,157 @@
---
title: '에이전트 저장소'
description: '에이전트 저장소를 사용하여 팀과 프로젝트 전반에 걸쳐 에이전트를 공유하고 재사용하는 방법을 알아보세요'
icon: 'database'
---
생각: 이제 훌륭한 답변을 드릴 수 있습니다.
최종 답변:
Agent Repositories는 엔터프라이즈 사용자가 팀과 프로젝트 전반에 걸쳐 agent 정의를 저장, 공유, 재사용할 수 있도록 합니다. 이 기능을 통해 조직은 표준화된 agent의 중앙 라이브러리를 유지할 수 있어 일관성을 높이고 중복 작업을 줄일 수 있습니다.
## 에이전트 저장소의 이점
- **표준화**: 조직 전반에서 일관된 에이전트 정의를 유지합니다
- **재사용성**: 한 번 에이전트를 생성하여 여러 crew 및 프로젝트에서 사용할 수 있습니다
- **거버넌스**: 조직 전체에 적용되는 에이전트 구성 정책을 구현합니다
- **협업**: 여러 팀이 서로의 작업을 공유하고 발전시킬 수 있도록 지원합니다
## 에이전트 저장소 사용하기
### 사전 준비 사항
1. CrewAI 계정이 있어야 하며, [무료 플랜](https://app.crewai.com)을 이용해보세요.
2. CrewAI CLI를 사용하여 인증되어 있어야 합니다.
3. 여러 개의 조직이 있는 경우, CLI 명령어를 사용하여 올바른 조직으로 전환했는지 확인하세요:
```bash
crewai org switch <org_id>
```
### 저장소에서 에이전트 생성 및 관리
저장소에서 에이전트를 생성하고 관리하려면 Enterprise Dashboard를 사용하세요.
### 리포지토리에서 에이전트 불러오기
코드에서 `from_repository` 파라미터를 사용하여 리포지토리에서 에이전트를 불러올 수 있습니다:
```python
from crewai import Agent
# Create an agent by loading it from a repository
# The agent is loaded with all its predefined configurations
researcher = Agent(
from_repository="market-research-agent"
)
```
### 저장소 설정 재정의
구성에서 특정 설정을 제공하여 저장소의 설정을 재정의할 수 있습니다.
```python
researcher = Agent(
from_repository="market-research-agent",
goal="Research the latest trends in AI development", # Override the repository goal
verbose=True # Add a setting not in the repository
)
```
### 예제: Repository 에이전트로 Crew 생성하기
```python
from crewai import Crew, Agent, Task
# Load agents from repositories
researcher = Agent(
from_repository="market-research-agent"
)
writer = Agent(
from_repository="content-writer-agent"
)
# Create tasks
research_task = Task(
description="Research the latest trends in AI",
agent=researcher
)
writing_task = Task(
description="Write a comprehensive report based on the research",
agent=writer
)
# Create the crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, writing_task],
verbose=True
)
# Run the crew
result = crew.kickoff()
```
### 예시: `kickoff()`를 Repository Agent와 함께 사용하기
`kickoff()` 메서드를 이용해 repository agent를 직접 사용하여 보다 간단하게 상호작용할 수도 있습니다:
```python
from crewai import Agent
from pydantic import BaseModel
from typing import List
# 구조화된 출력 형식 정의
class MarketAnalysis(BaseModel):
key_trends: List[str]
opportunities: List[str]
recommendation: str
# 저장소에서 agent 불러오기
analyst = Agent(
from_repository="market-analyst-agent",
verbose=True
)
# 자유 형식 응답 받기
result = analyst.kickoff("Analyze the AI market in 2025")
print(result.raw) # 원시 응답 접근
# 구조화된 출력 받기
structured_result = analyst.kickoff(
"Provide a structured analysis of the AI market in 2025",
response_format=MarketAnalysis
)
# 구조화된 데이터 접근
print(f"Key Trends: {structured_result.pydantic.key_trends}")
print(f"Recommendation: {structured_result.pydantic.recommendation}")
```
## 모범 사례
1. **명명 규칙**: 리포지토리 에이전트에 대해 명확하고 설명적인 이름을 사용하세요.
2. **문서화**: 각 에이전트에 대한 포괄적인 설명을 포함하세요.
3. **도구 관리**: 리포지토리 에이전트가 참조하는 도구들이 환경에 제공되는지 확인하세요.
4. **접근 제어**: 권한이 있는 팀원만 리포지토리 에이전트를 수정할 수 있도록 권한을 관리하세요.
## 조직 관리
조직을 전환하거나 현재 조직을 확인하려면 CrewAI CLI를 사용하세요:
```bash
# 현재 조직 보기
crewai org current
# 다른 조직으로 전환
crewai org switch <org_id>
# 사용 가능한 모든 조직 목록 확인
crewai org list
```
<Note>
리포지토리에서 agent를 불러올 때는 인증이 완료되어 있어야 하며, 올바른 조직으로 전환되어 있어야 합니다. 오류가 발생하면 위의 CLI 명령어를 사용하여 인증 상태와 조직 설정을 확인하세요.
</Note>

View File

@@ -0,0 +1,250 @@
---
title: 환각 방어책
description: "CrewAI 작업에서 AI 환각을 방지하고 감지합니다"
icon: "shield-check"
---
## 개요
Hallucination Guardrail은 AI가 생성한 콘텐츠가 사실에 기반하고 환각이 포함되어 있지 않은지 검증하는 엔터프라이즈 기능입니다. 이 기능은 작업 출력물을 참조 컨텍스트와 비교 분석하여, 잠재적으로 환각이 감지되었을 때 상세한 피드백을 제공합니다.
## 환각(Hallucinations)이란 무엇인가요?
AI 환각은 언어 모델이 그럴듯해 보이지만 사실과 다르거나 제공된 맥락에 의해 뒷받침되지 않는 내용을 생성할 때 발생합니다. Hallucination Guardrail은 다음과 같은 방법으로 이러한 문제를 방지합니다:
- 출력물을 참조 맥락과 비교
- 원본 자료에 대한 충실도 평가
- 문제 있는 콘텐츠에 대한 상세 피드백 제공
- 검증 엄격성을 위한 사용자 정의 임계값 지원
## 기본 사용법
### 가드레일 설정하기
```python
from crewai.tasks.hallucination_guardrail import HallucinationGuardrail
from crewai import LLM
# Basic usage - will use task's expected_output as context
guardrail = HallucinationGuardrail(
llm=LLM(model="gpt-4o-mini")
)
# With explicit reference context
context_guardrail = HallucinationGuardrail(
context="AI helps with various tasks including analysis and generation.",
llm=LLM(model="gpt-4o-mini")
)
```
### 작업에 추가하기
```python
from crewai import Task
# Create your task with the guardrail
task = Task(
description="Write a summary about AI capabilities",
expected_output="A factual summary based on the provided context",
agent=my_agent,
guardrail=guardrail # Add the guardrail to validate output
)
```
## 고급 구성
### 사용자 지정 임계값 검증
보다 엄격한 검증을 위해 사용자 지정 신뢰성 임계값(0-10 범위)를 설정할 수 있습니다:
```python
# Strict guardrail requiring high faithfulness score
strict_guardrail = HallucinationGuardrail(
context="Quantum computing uses qubits that exist in superposition states.",
llm=LLM(model="gpt-4o-mini"),
threshold=8.0 # Requires score >= 8 to pass validation
)
```
### 도구 응답 컨텍스트 포함하기
작업에서 도구를 사용할 때 더 정확한 검증을 위해 도구 응답을 포함할 수 있습니다:
```python
# Guardrail with tool response context
weather_guardrail = HallucinationGuardrail(
context="Current weather information for the requested location",
llm=LLM(model="gpt-4o-mini"),
tool_response="Weather API returned: Temperature 22°C, Humidity 65%, Clear skies"
)
```
## 작동 원리
### 검증 프로세스
1. **컨텍스트 분석**: 가드레일은 작업 결과를 제공된 참조 컨텍스트와 비교합니다.
2. **정확성 점수 부여**: 내부 평가자를 사용하여 정확성 점수(0-10)를 부여합니다.
3. **판단 결정**: 콘텐츠가 정확한지 또는 환각이 포함되어 있는지 결정합니다.
4. **임계값 확인**: 사용자 지정 임계값이 설정된 경우 해당 점수와 비교하여 검증합니다.
5. **피드백 생성**: 검증에 실패할 때 상세한 사유를 제공합니다.
### 검증 논리
- **기본 모드**: 판정 기반 검증(FAITHFUL vs HALLUCINATED)을 사용함
- **임계값 모드**: 신뢰성 점수가 지정된 임계값에 도달하거나 이를 초과해야 함
- **오류 처리**: 평가 오류를 우아하게 처리하고 유익한 피드백을 제공함
## 가드레일 결과
가드레일은 검증 상태를 나타내는 구조화된 결과를 반환합니다:
```python
# Example of guardrail result structure
{
"valid": False,
"feedback": "Content appears to be hallucinated (score: 4.2/10, verdict: HALLUCINATED). The output contains information not supported by the provided context."
}
```
### 결과 속성
- **valid**: 출력이 검증을 통과했는지 여부를 나타내는 불리언 값
- **feedback**: 검증 실패 시 상세 설명. 다음을 포함:
- 신뢰도 점수
- 판정 분류
- 실패의 구체적인 이유
## 작업 시스템과의 통합
### 자동 검증
가드레일이 태스크에 추가되면, 태스크가 완료로 표시되기 전에 출력값이 자동으로 검증됩니다:
```python
# Task output validation flow
task_output = agent.execute_task(task)
validation_result = guardrail(task_output)
if validation_result.valid:
# Task completes successfully
return task_output
else:
# Task fails with validation feedback
raise ValidationError(validation_result.feedback)
```
### 이벤트 추적
guardrail은 CrewAI의 이벤트 시스템과 통합되어 가시성을 제공합니다:
- **검증 시작됨**: guardrail 평가가 시작될 때
- **검증 완료됨**: 평가가 결과와 함께 종료될 때
- **검증 실패**: 평가 중 기술적 오류가 발생할 때
## 모범 사례
### 컨텍스트 가이드라인
<Steps>
<Step title="포괄적인 컨텍스트 제공">
AI가 출력할 때 기반이 되어야 할 모든 관련 사실 정보를 포함하세요:
```python
context = """
Company XYZ was founded in 2020 and specializes in renewable energy solutions.
They have 150 employees and generated $50M revenue in 2023.
Their main products include solar panels and wind turbines.
"""
```
</Step>
<Step title="관련 있는 컨텍스트만 유지하기">
혼란을 피하기 위해 작업과 직접적으로 관련된 정보만 포함하세요:
```python
# Good: Focused context
context = "The current weather in New York is 18°C with light rain."
# Avoid: Unrelated information
context = "The weather is 18°C. The city has 8 million people. Traffic is heavy."
```
</Step>
<Step title="컨텍스트를 정기적으로 업데이트하기">
참고하는 컨텍스트가 최신이고 정확한 정보를 반영하는지 확인하세요.
</Step>
</Steps>
### 임계값 선택
<Steps>
<Step title="기본 검증으로 시작하기">
맞춤 임계값 없이 시작하여 기준 성능을 파악합니다.
</Step>
<Step title="요구사항에 따라 조정하기">
- **중요 콘텐츠**: 최대 정확도를 위해 임계값 8-10 사용
- **일반 콘텐츠**: 균형 잡힌 검증을 위해 임계값 6-7 사용
- **창의적 콘텐츠**: 임계값 4-5 또는 기본 판정 기반 검증 사용
</Step>
<Step title="모니터링 및 반복">
검증 결과를 추적하고, 오탐/미탐을 기반으로 임계값을 조정합니다.
</Step>
</Steps>
## 성능 고려사항
### 실행 시간에 미치는 영향
- **검증 오버헤드**: 각 가드레일마다 작업당 약 1~3초가 추가됩니다
- **LLM 효율성**: 평가에는 효율적인 모델을 선택하세요 (예: gpt-4o-mini)
### 비용 최적화
- **모델 선택**: guardrail 평가에는 더 작고 효율적인 모델을 사용하세요
- **컨텍스트 크기**: 참조 컨텍스트는 간결하면서도 포괄적으로 유지하세요
- **캐싱**: 반복적인 콘텐츠의 검증 결과를 캐싱하는 것을 고려하세요
## 문제 해결
<Accordion title="검증이 항상 실패함">
**가능한 원인:**
- 컨텍스트가 너무 제한적이거나 작업 결과와 관련이 없음
- 임계값이 콘텐츠 유형에 비해 너무 높게 설정됨
- 참조 컨텍스트에 오래된 정보가 포함되어 있음
**해결 방법:**
- 작업 요구사항에 맞게 컨텍스트를 검토하고 업데이트하세요
- 임계값을 낮추거나 기본 판정 기반 검증을 사용하세요
- 컨텍스트가 최신이며 정확한지 확인하세요
</Accordion>
<Accordion title="오탐 (유효한 콘텐츠가 무효로 판정됨)">
**가능한 원인:**
- 창의적이거나 해석적인 작업에 임계값이 너무 높음
- 컨텍스트가 결과의 모든 유효한 측면을 포함하지 않음
- 평가 모델이 과도하게 보수적임
**해결 방법:**
- 임계값을 낮추거나 기본 검증을 사용하세요
- 폭넓은 허용 가능한 콘텐츠를 포함하도록 컨텍스트를 확장하세요
- 다른 평가 모델로 테스트하세요
</Accordion>
<Accordion title="평가 오류">
**가능한 원인:**
- 네트워크 연결 문제
- LLM 모델 사용 불가 또는 속도 제한
- 잘못된 형식의 작업 출력 또는 컨텍스트
**해결 방법:**
- 네트워크 연결 및 LLM 서비스 상태를 확인하세요
- 일시적 오류에 대해 재시도 로직을 구현하세요
- guardrail 평가 전에 작업 출력 형식을 검증하세요
</Accordion>
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
환각 guardrail 구성 또는 문제 해결에 도움이 필요하시면 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,179 @@
---
title: 통합
description: "에이전트가 조치를 취할 수 있도록 연결된 애플리케이션입니다."
icon: "plug"
---
## 개요
에이전트가 OAuth를 지원하는 모든 공급자와 인증하고 작업을 수행할 수 있도록 지원합니다. Salesforce와 HubSpot부터 Google 및 GitHub까지, 16개 이상의 통합 서비스를 제공합니다.
<Frame>
![Integrations](/images/enterprise/crew_connectors.png)
</Frame>
## 지원되는 통합
### **커뮤니케이션 & 협업**
- **Gmail** - 이메일 및 임시 저장 관리
- **Slack** - 워크스페이스 알림 및 경고
- **Microsoft** - Office 365 및 Teams 통합
### **프로젝트 관리**
- **Jira** - 이슈 추적 및 프로젝트 관리
- **ClickUp** - 작업 및 생산성 관리
- **Asana** - 팀 작업 및 프로젝트 조정
- **Notion** - 페이지 및 데이터베이스 관리
- **Linear** - 소프트웨어 프로젝트 및 버그 추적
- **GitHub** - 저장소 및 이슈 관리
### **고객 관계 관리**
- **Salesforce** - CRM 계정 및 기회 관리
- **HubSpot** - 영업 파이프라인 및 연락처 관리
- **Zendesk** - 고객 지원 티켓 관리
### **비즈니스 & 금융**
- **Stripe** - 결제 처리 및 고객 관리
- **Shopify** - 전자상거래 스토어 및 상품 관리
### **생산성 및 저장소**
- **Google Sheets** - 스프레드시트 데이터 동기화
- **Google Calendar** - 일정 및 스케줄 관리
- **Box** - 파일 저장 및 문서 관리
추가 기능도 곧 제공됩니다!
## 사전 준비 사항
Authentication Integrations를 사용하기 전에 다음이 준비되어 있는지 확인하세요:
- [CrewAI Enterprise](https://app.crewai.com) 계정. 무료 체험으로 시작할 수 있습니다.
## 통합 설정
### 1. 계정 연결하기
1. [CrewAI Enterprise](https://app.crewai.com)로 이동합니다.
2. **Integrations** 탭으로 이동합니다 - https://app.crewai.com/crewai_plus/connectors
3. Authentication Integrations 섹션에서 원하는 서비스의 **Connect** 버튼을 클릭합니다.
4. OAuth 인증 과정을 완료합니다.
5. 사용 사례에 필요한 권한을 부여합니다.
6. [CrewAI Enterprise](https://app.crewai.com) 계정 페이지 - https://app.crewai.com/crewai_plus/settings/account 에서 Enterprise Token을 받습니다.
<Frame>
![Integrations](/images/enterprise/enterprise_action_auth_token.png)
</Frame>
### 2. 통합 도구 설치
최신 버전의 `crewai-tools` 패키지만 있으면 됩니다.
```bash
uv add crewai-tools
```
## 사용 예시
### 기본 사용법
<Tip>
인증한 모든 서비스가 도구로 제공됩니다. 따라서 필요한 것은 `CrewaiEnterpriseTools`를 에이전트에 추가하는 것뿐이며, 바로 사용하실 수 있습니다.
</Tip>
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Gmail tool will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# print the tools
print(enterprise_tools)
# Create an agent with Gmail capabilities
email_agent = Agent(
role="Email Manager",
goal="Manage and organize email communications",
backstory="An AI assistant specialized in email management and communication.",
tools=enterprise_tools
)
# Task to send an email
email_task = Task(
description="Draft and send a follow-up email to john@example.com about the project update",
agent=email_agent,
expected_output="Confirmation that email was sent successfully"
)
# Run the task
crew = Crew(
agents=[email_agent],
tasks=[email_task]
)
# Run the crew
crew.kickoff()
```
### 필터링 도구
```python
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
actions_list=["gmail_find_email"] # only gmail_find_email tool will be available
)
gmail_tool = enterprise_tools["gmail_find_email"]
gmail_agent = Agent(
role="Gmail Manager",
goal="Manage gmail communications and notifications",
backstory="An AI assistant that helps coordinate gmail communications.",
tools=[gmail_tool]
)
notification_task = Task(
description="Find the email from john@example.com",
agent=gmail_agent,
expected_output="Email found from john@example.com"
)
# Run the task
crew = Crew(
agents=[slack_agent],
tasks=[notification_task]
)
```
## 모범 사례
### 보안
- **최소 권한 원칙**: 에이전트의 작업에 필요한 최소한의 권한만 부여하세요
- **정기적인 감사**: 연결된 통합 및 해당 권한을 주기적으로 검토하세요
- **자격 증명 보안**: 자격 증명을 하드코딩하지 말고, CrewAI의 안전한 인증 플로우를 사용하세요
### 필터링 도구
배포된 crew에서 연결된 서비스의 설정 페이지에서 각 통합에 대해 사용할 수 있는 작업을 지정할 수 있습니다.
<Frame>
![Integrations](/images/enterprise/filtering_enterprise_action_tools.png)
</Frame>
### 다중 사용자 조직을 위한 Scoped Deployments
crew를 배포하고 각 통합을 특정 사용자에게 범위 지정할 수 있습니다. 예를 들어, google에 연결하는 crew는 특정 사용자의 gmail 계정을 사용할 수 있습니다.
<Tip>
이것은 통합을 특정 사용자에게 범위 지정하고자 하는 다중 사용자 조직에서 유용합니다.
</Tip>
`user_bearer_token`을 사용하여 통합을 특정 사용자에 범위 지정하면 crew가 시작될 때 사용자의 bearer token을 사용해 통합에 인증합니다. 사용자가 로그인하지 않은 경우, crew는 연결된 통합을 사용하지 않습니다. 기본 bearer token을 사용하여 crew와 함께 배포된 통합에 인증할 수 있습니다.
<Frame>
![Integrations](/images/enterprise/user_bearer_token.png)
</Frame>
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
통합 설정이나 문제 해결에 대한 지원이 필요하시면 저희 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,106 @@
---
title: 도구 저장소
description: "도구 저장소를 사용하여 도구를 관리하기"
icon: "toolbox"
---
## 개요
Tool Repository는 CrewAI 도구를 위한 패키지 관리자입니다. 사용자는 CrewAI crew와 flow에 통합되는 도구를 게시, 설치 및 관리할 수 있습니다.
도구는 다음과 같이 분류됩니다:
- **비공개**: 조직 내에서만 접근할 수 있습니다(기본값)
- **공개**: `--public` 플래그로 게시하면 모든 CrewAI 사용자가 접근할 수 있습니다
이 저장소는 버전 관리 시스템이 아닙니다. 코드 변경 사항을 추적하고 협업을 활성화하려면 Git을 사용하십시오.
## 사전 요구 사항
Tool Repository를 사용하기 전에 다음이 준비되어 있어야 합니다:
- [CrewAI Enterprise](https://app.crewai.com) 계정
- [CrewAI CLI](https://docs.crewai.com/concepts/cli#cli) 설치됨
- uv>=0.5.0 이 설치되어 있어야 합니다. [업그레이드 방법](https://docs.astral.sh/uv/getting-started/installation/#upgrading-uv)을 참고하세요.
- [Git](https://git-scm.com) 설치 및 구성 완료
- CrewAI Enterprise 조직에서 도구를 게시하거나 설치할 수 있는 액세스 권한
## 도구 설치
도구를 설치하려면:
```bash
crewai tool install <tool-name>
```
이 명령은 도구를 설치하고 `pyproject.toml`에 추가합니다.
## 도구 생성 및 게시
새 도구 프로젝트를 생성하려면:
```bash
crewai tool create <tool-name>
```
이 명령은 로컬에 스캐폴딩된 도구 프로젝트를 생성합니다.
변경 사항을 적용한 후, Git 저장소를 초기화하고 코드를 커밋합니다:
```bash
git init
git add .
git commit -m "Initial version"
```
도구를 게시하려면:
```bash
crewai tool publish
```
기본적으로 도구는 비공개로 게시됩니다. 도구를 공개로 설정하려면:
```bash
crewai tool publish --public
```
도구 빌드에 대한 자세한 내용은 [나만의 도구 만들기](https://docs.crewai.com/concepts/tools#creating-your-own-tools)를 참고하세요.
## 도구 업데이트
공개된 도구를 업데이트하려면:
1. 로컬에서 도구를 수정합니다.
2. `pyproject.toml`에서 버전을 업데이트합니다(예: `0.1.0`에서 `0.1.1`로).
3. 변경 사항을 커밋하고 배포합니다.
```bash
git commit -m "Update version to 0.1.1"
crewai tool publish
```
## 도구 삭제
도구를 삭제하려면:
1. [CrewAI Enterprise](https://app.crewai.com)로 이동합니다.
2. **Tools**로 이동합니다.
3. 도구를 선택합니다.
4. **Delete**를 클릭합니다.
<Warning>
삭제는 영구적입니다. 삭제된 도구는 복구하거나 다시 설치할 수 없습니다.
</Warning>
## 보안 점검
모든 공개된 버전은 자동화된 보안 점검을 거치며, 통과한 후에만 설치할 수 있습니다.
도구의 보안 점검 상태는 다음에서 확인할 수 있습니다:
`CrewAI Enterprise > Tools > Your Tool > Versions`
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
API 통합 또는 문제 해결에 대한 지원이 필요하시면 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,145 @@
---
title: 트레이스
description: "Traces를 사용하여 내 크루 모니터링하기"
icon: "timeline"
---
## 개요
Trace는 crew 실행에 대한 포괄적인 가시성을 제공하여 성능 모니터링, 문제 디버깅, AI agent workflow 최적화에 도움을 줍니다.
## Traces란 무엇인가요?
CrewAI Enterprise의 Traces는 crew의 작동 과정을 처음 입력에서 최종 출력까지 모든 측면에서 포착하는 상세 실행 기록입니다. Traces에는 다음 내용이 기록됩니다:
- Agent의 생각 및 추론
- 작업 실행 세부 정보
- 도구 사용 및 출력
- 토큰 소모 메트릭
- 실행 시간
- 비용 추정치
<Frame>
![Traces Overview](/images/enterprise/traces-overview.png)
</Frame>
## 트레이스(Traces) 접근하기
<Steps>
<Step title="트레이스 탭으로 이동">
CrewAI Enterprise 대시보드에 들어가면, **트레이스**를 클릭하여 모든 실행 기록을 볼 수 있습니다.
</Step>
<Step title="실행 선택하기">
모든 crew 실행 목록이 날짜별로 정렬되어 표시됩니다. 상세 트레이스를 보려면 원하는 실행을 클릭하세요.
</Step>
</Steps>
## 트레이스 인터페이스 이해하기
트레이스 인터페이스는 여러 섹션으로 나뉘어 있으며, 각 섹션은 crew의 실행에 대한 다양한 인사이트를 제공합니다.
### 1. 실행 요약
상단 섹션에서는 실행에 대한 고수준 메트릭을 표시합니다:
- **총 토큰**: 모든 작업에서 소모된 토큰 수
- **프롬프트 토큰**: LLM에 프롬프트로 사용된 토큰
- **컴플리션 토큰**: LLM 응답에서 생성된 토큰
- **요청 수**: 수행된 API 호출 수
- **실행 시간**: crew 런의 전체 소요 시간
- **예상 비용**: 토큰 사용량을 기반으로 한 대략적인 비용
<Frame>
![Execution Summary](/images/enterprise/trace-summary.png)
</Frame>
### 2. Tasks & Agents
이 섹션에서는 crew 실행에 포함된 모든 task와 agent를 보여줍니다:
- task 이름 및 agent 할당
- 각 task에 사용된 agent 및 LLM
- 상태 (완료/실패)
- task의 개별 실행 시간
<Frame>
![Task List](/images/enterprise/trace-tasks.png)
</Frame>
### 3. 최종 결과
모든 작업이 완료된 후 crew가 생성한 최종 결과를 표시합니다.
<Frame>
![최종 결과](/images/enterprise/final-output.png)
</Frame>
### 4. 실행 타임라인
각 작업이 시작되고 종료된 시점을 시각적으로 표현하여 병목 현상이나 병렬 실행 패턴을 파악하는 데 도움이 됩니다.
<Frame>
![실행 타임라인](/images/enterprise/trace-timeline.png)
</Frame>
### 5. 상세 작업 보기
타임라인이나 작업 목록에서 특정 작업을 클릭하면 다음을 볼 수 있습니다:
<Frame>
![상세 작업 보기](/images/enterprise/trace-detailed-task.png)
</Frame>
- **작업 키**: 작업의 고유 식별자
- **작업 ID**: 시스템 내의 기술적 식별자
- **상태**: 현재 상태 (완료/진행 중/실패)
- **에이전트**: 해당 작업을 수행한 에이전트
- **LLM**: 이 작업에 사용된 언어 모델
- **시작/종료 시간**: 작업이 시작되고 완료된 시간
- **실행 시간**: 이 특정 작업의 소요 시간
- **작업 설명**: 에이전트에게 지시된 작업 내용
- **예상 출력**: 요청된 출력 형식
- **입력**: 이전 작업에서 이 작업에 제공된 입력값
- **출력**: 에이전트가 실제로 생성한 결과
## 디버깅을 위한 트레이스 사용
트레이스는 crew 문제 해결에 매우 유용합니다:
<Steps>
<Step title="실패 지점 식별">
crew 실행이 예상한 결과를 내지 못할 때, 트레이스를 확인하여 어디에서 문제가 발생했는지 찾으세요. 다음을 확인하세요:
- 실패한 작업
- 에이전트의 예상 밖 결정
- 도구 사용 오류
- 잘못 해석된 지침
<Frame>
![Failure Points](/images/enterprise/failure.png)
</Frame>
</Step>
<Step title="성능 최적화">
실행 메트릭을 사용하여 성능 병목 현상을 파악하세요:
- 예상보다 오래 걸린 작업
- 과도한 토큰 사용
- 중복된 도구 작업
- 불필요한 API 호출
</Step>
<Step title="비용 효율성 향상">
토큰 사용량 및 비용 추정치를 분석해 crew의 효율성을 최적화하세요:
- 더 간단한 작업에는 더 작은 모델을 사용 고려
- 프롬프트를 더 간결하게 다듬기
- 자주 액세스하는 정보 캐싱
- 중복 작업을 최소화하도록 작업 구조화하기
</Step>
</Steps>
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
트레이스 분석이나 기타 CrewAI 엔터프라이즈 기능에 대한 지원이 필요하시면 저희 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,81 @@
---
title: 웹훅 스트리밍
description: "웹훅 스트리밍을 사용하여 이벤트를 웹훅으로 스트리밍하기"
icon: "webhook"
---
## 개요
Enterprise Event Streaming을 사용하면 CrewAI Enterprise에 배포된 crew 및 flow에 대한 실시간 웹훅 업데이트(예: 모델 호출, 도구 사용, flow 단계)를 받을 수 있습니다.
## 사용법
Kickoff API를 사용할 때, 요청에 `webhooks` 객체를 포함시키세요. 예를 들면 아래와 같습니다:
```json
{
"inputs": {"foo": "bar"},
"webhooks": {
"events": ["crew_kickoff_started", "llm_call_started"],
"url": "https://your.endpoint/webhook",
"realtime": false,
"authentication": {
"strategy": "bearer",
"token": "my-secret-token"
}
}
}
```
`realtime`이 `true`로 설정되면, 각 이벤트가 개별적으로 그리고 즉시 전달되지만 crew/flow 성능에 영향을 미칠 수 있습니다.
## Webhook 형식
각 webhook은 이벤트 목록을 전송합니다:
```json
{
"events": [
{
"id": "event-id",
"execution_id": "crew-run-id",
"timestamp": "2025-02-16T10:58:44.965Z",
"type": "llm_call_started",
"data": {
"model": "gpt-4",
"messages": [
{"role": "system", "content": "You are an assistant."},
{"role": "user", "content": "Summarize this article."}
]
}
}
]
}
```
`data` 객체의 구조는 이벤트 타입에 따라 다릅니다. 자세한 내용은 GitHub의 [이벤트 목록](https://github.com/crewAIInc/crewAI/tree/main/src/crewai/utilities/events)을 참조하세요.
요청이 HTTP를 통해 전송되므로, 이벤트의 순서가 보장되지 않습니다. 순서가 필요하다면 `timestamp` 필드를 사용하세요.
## 지원되는 이벤트
CrewAI는 Enterprise Event Streaming에서 시스템 이벤트와 사용자 지정 이벤트 둘 다를 지원합니다. 이러한 이벤트는 crew 및 flow 실행 중에 구성한 웹훅 엔드포인트로 전송됩니다.
- `crew_kickoff_started`
- `crew_step_started`
- `crew_step_completed`
- `crew_execution_completed`
- `llm_call_started`
- `llm_call_completed`
- `tool_usage_started`
- `tool_usage_completed`
- `crew_test_failed`
- *...그리고 기타 여러 가지*
이벤트 이름은 내부 이벤트 버스와 일치합니다. 전체 목록은 [GitHub 소스](https://github.com/crewAIInc/crewAI/tree/main/src/crewai/utilities/events)에서 확인할 수 있습니다.
사용자 지정 이벤트도 직접 발생시킬 수 있으며, 시스템 이벤트와 함께 웹훅 스트림을 통해 전달됩니다.
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
웹훅 통합 또는 문제 해결에 대한 지원이 필요하다면 저희 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,51 @@
---
title: "Azure OpenAI 설정"
description: "엔터프라이즈 LLM 연결을 위해 Crew Studio와 함께 Azure OpenAI를 구성합니다"
icon: "microsoft"
---
이 가이드는 Azure OpenAI와 Crew Studio를 연동하여 원활한 엔터프라이즈 AI 운영을 수행하는 방법을 안내합니다.
## 설정 프로세스
<Steps>
<Step title="Azure OpenAI Studio 접속">
1. Azure에서 `Azure AI Services > 배포 선택 > Azure OpenAI Studio 열기`로 이동합니다.
2. 왼쪽 메뉴에서 `Deployments`를 클릭합니다. 배포가 없다면 원하는 모델로 새 배포를 생성하세요.
3. 생성이 완료되면 해당 배포를 선택하고, 페이지 오른쪽에서 `Target URI`와 `Key`를 찾습니다. 이 정보가 필요하니 페이지를 열어둔 상태로 두세요.
<Frame>
<img src="/images/enterprise/azure-openai-studio.png" alt="Azure OpenAI Studio" />
</Frame>
</Step>
<Step title="CrewAI Enterprise 연결 구성">
4. 다른 탭에서 `CrewAI Enterprise > LLM Connections`를 엽니다. LLM Connection에 이름을 지정하고, 공급자로 Azure를 선택한 다음, Azure에서 선택한 것과 동일한 모델을 선택하세요.
5. 같은 페이지에서 3단계에서 가져온 환경 변수를 추가하세요:
- 하나는 `AZURE_DEPLOYMENT_TARGET_URL` (Target URI 사용)로 명명합니다. URL은 다음과 같이 표시됩니다: https://your-deployment.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview
- 다른 하나는 `AZURE_API_KEY` (Key 사용)로 명명합니다.
6. `Add Connection`을 클릭하여 LLM Connection을 저장합니다.
</Step>
<Step title="기본 구성 설정">
7. `CrewAI Enterprise > Settings > Defaults > Crew Studio LLM Settings`에서 새 LLM Connection과 모델을 기본값으로 설정합니다.
</Step>
<Step title="네트워크 액세스 구성">
8. 네트워크 액세스 설정을 확인하세요:
- Azure에서 `Azure OpenAI > 배포 선택`으로 이동합니다.
- `Resource Management > Networking`으로 이동합니다.
- `Allow access from all networks`가 활성화되어 있는지 확인하세요. 이 설정이 제한되어 있으면 CrewAI가 Azure OpenAI 엔드포인트에 접근하지 못할 수 있습니다.
</Step>
</Steps>
## 확인
모두 준비되었습니다! 이제 Crew Studio는 Azure OpenAI 연결을 사용합니다. 모든 기능이 제대로 작동하는지 확인하려면 간단한 crew 또는 task를 만들어 연결을 테스트해 보세요.
## 문제 해결
문제가 발생한 경우:
- Target URI 형식이 예상 패턴과 일치하는지 확인하세요
- API 키가 올바르고 적절한 권한을 가지고 있는지 확인하세요
- 네트워크 액세스가 CrewAI 연결을 허용하도록 구성되어 있는지 확인하세요
- 배포 모델이 CrewAI에서 구성한 것과 일치하는지 확인하세요

View File

@@ -0,0 +1,43 @@
---
title: "Crew 빌드"
description: "Crew는 함께 작업을 완수하기 위해 협력하는 에이전트 그룹입니다."
icon: "people-arrows"
---
## 개요
[CrewAI Enterprise](https://app.crewai.com)는 프로덕션 환경에서 AI 에이전트를 **생성**, **배포** 및 **관리**하는 과정을 간소화합니다.
## 시작하기
<iframe
width="100%"
height="400"
src="https://www.youtube.com/embed/-kSOTtYzgEw"
title="Building Crews with CrewAI CLI"
frameborder="0"
style={{ borderRadius: '10px' }}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
### 설치 및 설정
<Card title="표준 설치 따라하기" icon="wrench" href="/ko/installation">
CrewAI CLI를 설정하고 첫 번째 프로젝트를 생성하기 위해 표준 설치 가이드를 따라주세요.
</Card>
### 크루 구성하기
<Card title="빠른 시작 튜토리얼" icon="rocket" href="/ko/quickstart">
YAML 구성을 사용하여 첫 번째 에이전트 크루를 만드는 방법은 빠른 시작 가이드를 따라주세요.
</Card>
## 지원 및 리소스
Enterprise 전용 지원 또는 문의가 필요하신 경우, [support@crewai.com](mailto:support@crewai.com)으로 저희 전담 지원팀에 연락해 주시기 바랍니다.
<Card title="데모 예약" icon="calendar" href="mailto:support@crewai.com">
Enterprise 기능과 해당 기능이 귀사의 조직에 어떻게 도움이 될 수 있는지 알아보시려면 저희 팀과 상담 일정을 예약하세요.
</Card>

View File

@@ -0,0 +1,290 @@
---
title: "Crew 배포"
description: "CrewAI 엔터프라이즈에서 Crew 배포하기"
icon: "rocket"
---
<Note>
로컬에서 또는 Crew Studio를 통해 crew를 생성한 후, 다음 단계는 이를 CrewAI Enterprise 플랫폼에 배포하는 것입니다. 본 가이드에서는 다양한 배포 방법을 다루며, 여러분의 워크플로우에 가장 적합한 방식을 선택할 수 있도록 안내합니다.
</Note>
## 사전 준비 사항
<CardGroup cols={2}>
<Card title="배포 준비가 된 Crew" icon="users">
작동 중인 crew가 로컬에서 빌드되었거나 Crew Studio를 통해 생성되어 있어야 합니다.
</Card>
<Card title="GitHub 저장소" icon="github">
crew 코드가 GitHub 저장소에 있어야 합니다(GitHub 연동 방식의 경우).
</Card>
</CardGroup>
## 옵션 1: CrewAI CLI를 사용한 배포
CLI는 로컬에서 개발된 crew를 Enterprise 플랫폼에 가장 빠르게 배포할 수 있는 방법을 제공합니다.
<Steps>
<Step title="CrewAI CLI 설치">
아직 설치하지 않았다면 CrewAI CLI를 설치하세요:
```bash
pip install crewai[tools]
```
<Tip>
CLI는 기본 CrewAI 패키지에 포함되어 있지만, `[tools]` 추가 옵션을 사용하면 모든 배포 종속성을 함께 설치할 수 있습니다.
</Tip>
</Step>
<Step title="Enterprise 플랫폼에 인증">
먼저, CrewAI Enterprise 플랫폼에 CLI를 인증해야 합니다:
```bash
# 이미 CrewAI Enterprise 계정이 있거나 새로 생성하고 싶을 때:
crewai login
```
위 명령어를 실행하면 CLI가 다음을 진행합니다:
1. URL과 고유 기기 코드를 표시합니다
2. 브라우저를 열어 인증 페이지로 이동합니다
3. 기기 확인을 요청합니다
4. 인증 과정을 완료합니다
인증이 성공적으로 완료되면 터미널에 확인 메시지가 표시됩니다!
</Step>
<Step title="배포 생성">
프로젝트 디렉터리에서 다음 명령어를 실행하세요:
```bash
crewai deploy create
```
이 명령어는 다음을 수행합니다:
1. GitHub 저장소 정보를 감지합니다
2. 로컬 `.env` 파일의 환경 변수를 식별합니다
3. 이러한 변수를 Enterprise 플랫폼으로 안전하게 전송합니다
4. 고유 식별자가 부여된 새 배포를 만듭니다
성공적으로 생성되면 다음과 같은 메시지가 표시됩니다:
```shell
Deployment created successfully!
Name: your_project_name
Deployment ID: 01234567-89ab-cdef-0123-456789abcdef
Current Status: Deploy Enqueued
```
</Step>
<Step title="배포 진행 상황 모니터링">
다음 명령어로 배포 상태를 추적할 수 있습니다:
```bash
crewai deploy status
```
빌드 과정의 상세 로그가 필요하다면:
```bash
crewai deploy logs
```
<Tip>
첫 배포는 컨테이너 이미지를 빌드하므로 일반적으로 10~15분 정도 소요됩니다. 이후 배포는 훨씬 빠릅니다.
</Tip>
</Step>
</Steps>
## 추가 CLI 명령어
CrewAI CLI는 배포를 관리하기 위한 여러 명령어를 제공합니다:
```bash
# 모든 배포 목록 확인
crewai deploy list
# 배포 상태 확인
crewai deploy status
# 배포 로그 보기
crewai deploy logs
# 코드 변경 후 업데이트 푸시
crewai deploy push
# 배포 삭제
crewai deploy remove <deployment_id>
```
## 옵션 2: 웹 인터페이스를 통한 직접 배포
GitHub 계정을 연결하여 CrewAI Enterprise 웹 인터페이스를 통해 crews를 직접 배포할 수도 있습니다. 이 방법은 로컬 머신에서 CLI를 사용할 필요가 없습니다.
<Steps>
<Step title="GitHub로 푸시하기">
crew를 GitHub 저장소에 푸시해야 합니다. 아직 crew를 만들지 않았다면, [이 튜토리얼](/ko/quickstart)을 따라할 수 있습니다.
</Step>
<Step title="GitHub를 CrewAI Enterprise에 연결하기">
1. [CrewAI Enterprise](https://app.crewai.com)에 로그인합니다.
2. "Connect GitHub" 버튼을 클릭합니다.
<Frame>
![Connect GitHub Button](/images/enterprise/connect-github.png)
</Frame>
</Step>
<Step title="저장소 선택하기">
GitHub 계정을 연결한 후 배포할 저장소를 선택할 수 있습니다:
<Frame>
![Select Repository](/images/enterprise/select-repo.png)
</Frame>
</Step>
<Step title="환경 변수 설정하기">
배포 전에, LLM 제공업체 또는 기타 서비스에 연결할 환경 변수를 설정해야 합니다:
1. 변수를 개별적으로 또는 일괄적으로 추가할 수 있습니다.
2. 환경 변수는 `KEY=VALUE` 형식(한 줄에 하나씩)으로 입력합니다.
<Frame>
![Set Environment Variables](/images/enterprise/set-env-variables.png)
</Frame>
</Step>
<Step title="Crew 배포하기">
1. "Deploy" 버튼을 클릭하여 배포 프로세스를 시작합니다.
2. 진행 바를 통해 진행 상황을 모니터링할 수 있습니다.
3. 첫 번째 배포에는 일반적으로 약 10-15분 정도 소요되며, 이후 배포는 더 빠릅니다.
<Frame>
![Deploy Progress](/images/enterprise/deploy-progress.png)
</Frame>
배포가 완료되면 다음을 확인할 수 있습니다:
- crew의 고유 URL
- crew API를 보호할 Bearer 토큰
- 배포를 삭제해야 하는 경우 "Delete" 버튼
</Step>
</Steps>
## ⚠️ 환경 변수 보안 요구사항
<Warning>
**중요**: CrewAI Enterprise는 환경 변수 이름에 대한 보안 제한이 있으며, 이를 따르지 않을 경우 배포가 실패할 수 있습니다.
</Warning>
### 차단된 환경 변수 패턴
보안상의 이유로, 다음과 같은 환경 변수 명명 패턴은 **자동으로 필터링**되며 배포에 문제가 발생할 수 있습니다:
**차단된 패턴:**
- `_TOKEN`으로 끝나는 변수 (예: `MY_API_TOKEN`)
- `_PASSWORD`로 끝나는 변수 (예: `DB_PASSWORD`)
- `_SECRET`로 끝나는 변수 (예: `API_SECRET`)
- 특정 상황에서 `_KEY`로 끝나는 변수
**특정 차단 변수:**
- `GITHUB_USER`, `GITHUB_TOKEN`
- `AWS_REGION`, `AWS_DEFAULT_REGION`
- 다양한 내부 CrewAI 시스템 변수
### 허용된 예외
일부 변수는 차단된 패턴과 일치하더라도 명시적으로 허용됩니다:
- `AZURE_AD_TOKEN`
- `AZURE_OPENAI_AD_TOKEN`
- `ENTERPRISE_ACTION_TOKEN`
- `CREWAI_ENTEPRISE_TOOLS_TOKEN`
### 네이밍 문제 해결 방법
환경 변수 제한으로 인해 배포가 실패하는 경우:
```bash
# ❌ 이러한 이름은 배포 실패를 초래합니다
OPENAI_TOKEN=sk-...
DATABASE_PASSWORD=mypassword
API_SECRET=secret123
# ✅ 대신 다음과 같은 네이밍 패턴을 사용하세요
OPENAI_API_KEY=sk-...
DATABASE_CREDENTIALS=mypassword
API_CONFIG=secret123
```
### 모범 사례
1. **표준 명명 규칙 사용**: `PROVIDER_TOKEN` 대신 `PROVIDER_API_KEY` 사용
2. **먼저 로컬에서 테스트**: crew가 이름이 변경된 변수로 제대로 동작하는지 확인
3. **코드 업데이트**: 이전 변수 이름을 참조하는 부분을 모두 변경
4. **변경 내용 문서화**: 팀을 위해 이름이 변경된 변수를 기록
<Tip>
배포 실패 시, 환경 변수 에러 메시지가 난해하다면 먼저 변수 이름이 이 패턴을 따르는지 확인하세요.
</Tip>
### 배포된 Crew와 상호작용하기
배포가 완료되면 다음을 통해 crew에 접근할 수 있습니다:
1. **REST API**: 플랫폼에서 아래의 주요 경로가 포함된 고유한 HTTPS 엔드포인트를 생성합니다:
- `/inputs`: 필요한 입력 파라미터 목록
- `/kickoff`: 제공된 입력값으로 실행 시작
- `/status/{kickoff_id}`: 실행 상태 확인
2. **웹 인터페이스**: [app.crewai.com](https://app.crewai.com)에 방문하여 다음을 확인할 수 있습니다:
- **Status 탭**: 배포 정보, API 엔드포인트 세부 정보 및 인증 토큰 확인
- **Run 탭**: crew 구조의 시각적 표현
- **Executions 탭**: 모든 실행 내역
- **Metrics 탭**: 성능 분석
- **Traces 탭**: 상세 실행 인사이트
### 실행 트리거하기
Enterprise 대시보드에서 다음 작업을 수행할 수 있습니다:
1. crew 이름을 클릭하여 상세 정보를 엽니다
2. 관리 인터페이스에서 "Trigger Crew"를 선택합니다
3. 나타나는 모달에 필요한 입력값을 입력합니다
4. 파이프라인을 따라 실행의 진행 상황을 모니터링합니다
### 모니터링 및 분석
Enterprise 플랫폼은 포괄적인 가시성 기능을 제공합니다:
- **실행 관리**: 활성 및 완료된 실행 추적
- **트레이스**: 각 실행의 상세 분해
- **메트릭**: 토큰 사용량, 실행 시간, 비용
- **타임라인 보기**: 작업 시퀀스의 시각적 표현
### 고급 기능
Enterprise 플랫폼은 또한 다음을 제공합니다:
- **환경 변수 관리**: API 키를 안전하게 저장 및 관리
- **LLM 연결**: 다양한 LLM 공급자와의 통합 구성
- **Custom Tools Repository**: 도구 생성, 공유 및 설치
- **Crew Studio**: 코드를 작성하지 않고 채팅 인터페이스를 통해 crew 빌드
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Enterprise 플랫폼의 배포 문제 또는 문의 사항이 있으시면 지원팀에 연락해 주십시오.
</Card>

View File

@@ -0,0 +1,165 @@
---
title: "Crew Studio 활성화"
description: "CrewAI Enterprise에서 Crew Studio 활성화하기"
icon: "comments"
---
<Tip>
Crew Studio는 대화형 인터페이스를 통해 빠르게 Crew를 스캐폴딩하거나 구축할 수 있는 강력한 **노코드/로우코드** 도구입니다.
</Tip>
## Crew Studio란?
Crew Studio는 코드를 작성하지 않고도 AI agent crew를 생성할 수 있는 혁신적인 방법입니다.
<Frame>
![Crew Studio Interface](/images/enterprise/crew-studio-interface.png)
</Frame>
Crew Studio를 사용하면 다음과 같은 작업이 가능합니다:
- Crew Assistant와 채팅하여 문제를 설명
- agent 및 task를 자동으로 생성
- 적절한 tool 선택
- 필요한 입력값 구성
- 커스터마이징을 위한 다운로드 가능한 코드 생성
- CrewAI Enterprise 플랫폼에 직접 배포
## 구성 단계
Crew Studio를 사용하기 전에 LLM 연결을 구성해야 합니다:
<Steps>
<Step title="LLM 연결 설정">
CrewAI Enterprise 대시보드의 **LLM Connections** 탭으로 이동하여 새 LLM 연결을 만듭니다.
<Note>
CrewAI에서 지원하는 원하는 LLM 공급자를 자유롭게 사용하실 수 있습니다.
</Note>
LLM 연결을 구성하세요:
- `Connection Name`(예: `OpenAI`)을 입력하세요.
- 모델 공급자를 선택하세요: `openai` 또는 `azure`
- Studio에서 생성되는 Crews에 사용할 모델을 선택하세요.
- 최소한 `gpt-4o`, `o1-mini`, `gpt-4o-mini`를 권장합니다.
- API 키를 환경 변수로 추가하세요:
- OpenAI의 경우: `OPENAI_API_KEY`에 API 키를 추가
- Azure OpenAI의 경우: [이 글](https://blog.crewai.com/configuring-azure-openai-with-crewai-a-comprehensive-guide/)을 참고하여 구성
- `Add Connection`을 클릭하여 구성을 저장하세요.
<Frame>
![LLM 연결 구성](/images/enterprise/llm-connection-config.png)
</Frame>
</Step>
<Step title="연결 추가 확인">
설정이 완료되면 새 연결이 사용 가능한 연결 목록에 추가된 것을 볼 수 있습니다.
<Frame>
![연결 추가됨](/images/enterprise/connection-added.png)
</Frame>
</Step>
<Step title="LLM 기본값 구성">
메인 메뉴에서 **Settings → Defaults**로 이동하여 LLM 기본값을 구성하세요:
- 에이전트 및 기타 구성 요소의 기본 모델을 선택하세요
- Crew Studio의 기본 구성을 설정하세요
변경 사항을 적용하려면 `Save Settings`를 클릭하세요.
<Frame>
![LLM 기본값 구성](/images/enterprise/llm-defaults.png)
</Frame>
</Step>
</Steps>
## Crew Studio 사용하기
LLM 연결과 기본 설정을 구성했다면 이제 Crew Studio 사용을 시작할 준비가 완료되었습니다!
<Steps>
<Step title="Studio 접속">
CrewAI Enterprise 대시보드에서 **Studio** 섹션으로 이동하세요.
</Step>
<Step title="대화 시작">
Crew Assistant와 대화를 시작하며 해결하고자 하는 문제를 설명하세요:
```md
I need a crew that can research the latest AI developments and create a summary report.
```
Crew Assistant는 귀하의 요구 사항을 더 잘 이해하기 위해 추가 질문을 할 것입니다.
</Step>
<Step title="생성된 crew 검토">
생성된 crew 구성을 검토하세요. 구성에는 다음이 포함됩니다:
- 에이전트 및 그들의 역할
- 수행할 작업
- 필요한 입력값
- 사용할 도구
이 단계에서 구성 내용을 세부적으로 수정할 수 있습니다.
</Step>
<Step title="배포 또는 다운로드">
구성에 만족하면 다음을 수행할 수 있습니다:
- 생성된 코드를 다운로드하여 로컬에서 커스터마이징
- crew를 CrewAI Enterprise 플랫폼에 직접 배포
- 구성을 수정하고 crew를 재생성
</Step>
<Step title="crew 테스트">
배포 후 샘플 입력으로 crew를 테스트하여 기대한 대로 동작하는지 확인하세요.
</Step>
</Steps>
<Tip>
최상의 결과를 얻으려면 crew가 달성해야 할 목표를 명확하고 상세하게 설명하세요. 원하는 입력값과 예상 결과를 설명에 포함시키는 것이 좋습니다.
</Tip>
## 예시 워크플로우
다음은 Crew Studio를 사용하여 crew를 생성하는 일반적인 워크플로우입니다:
<Steps>
<Step title="문제 설명하기">
먼저 문제를 설명하세요:
```md
I need a crew that can analyze financial news and provide investment recommendations
```
</Step>
<Step title="질문에 답하기">
crew assistant가 요구 사항을 구체화할 수 있도록 하는 추가 질문에 답변하세요.
</Step>
<Step title="계획 검토하기">
생성된 crew 계획을 검토하세요. 여기에는 다음과 같은 항목이 포함될 수 있습니다:
- 금융 뉴스를 수집하는 Research Agent
- 데이터를 해석하는 Analysis Agent
- 투자 조언을 제공하는 Recommendations Agent
</Step>
<Step title="승인 또는 수정">
계획을 승인하거나 필요하다면 변경을 요청하세요.
</Step>
<Step title="다운로드 또는 배포">
사용자화를 위해 코드를 다운로드하거나 플랫폼에 직접 배포하세요.
</Step>
<Step title="테스트 및 개선">
샘플 입력으로 crew를 테스트하고 필요에 따라 개선하세요.
</Step>
</Steps>
<Card title="도움이 필요하세요?" icon="headset" href="mailto:support@crewai.com">
Crew Studio 또는 기타 CrewAI Enterprise 기능 지원이 필요하다면 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,53 @@
---
title: "HubSpot 트리거"
description: "HubSpot 워크플로우에서 CrewAI 크루를 직접 트리거하세요"
icon: "hubspot"
---
이 가이드는 HubSpot Workflows에서 직접 crew를 시작할 수 있도록 CrewAI Enterprise용 HubSpot 트리거를 설정하는 단계별 과정을 제공합니다.
## 사전 준비 사항
- CrewAI Enterprise 계정
- [HubSpot Workflows](https://knowledge.hubspot.com/workflows/create-workflows) 기능이 활성화된 HubSpot 계정
## 설정 단계
<Steps>
<Step title="HubSpot 계정을 CrewAI Enterprise와 연결하기">
- `CrewAI Enterprise 계정 > 트리거`에 로그인합니다.
- 사용 가능한 트리거 목록에서 `HubSpot`을 선택합니다.
- CrewAI Enterprise와 연결하고자 하는 HubSpot 계정을 선택합니다.
- 화면에 나타나는 안내에 따라 CrewAI Enterprise가 HubSpot 계정에 접근하도록 승인합니다.
- HubSpot이 CrewAI Enterprise와 성공적으로 연결되면 확인 메시지가 표시됩니다.
</Step>
<Step title="HubSpot 워크플로우 생성하기">
- `HubSpot 계정 > 자동화 > 워크플로우 > 새 워크플로우`에 로그인합니다.
- 필요에 맞는 워크플로우 유형을 선택합니다 (예: 처음부터 시작).
- 워크플로우 빌더에서 더하기(+) 아이콘을 클릭하여 새로운 작업을 추가합니다.
- `통합 앱 > CrewAI > Crew 시작하기`를 선택합니다.
- 시작할 Crew를 선택합니다.
- `저장`을 클릭하여 워크플로우에 작업을 추가합니다.
<Frame>
<img src="/images/enterprise/hubspot-workflow-1.png" alt="HubSpot Workflow 1" />
</Frame>
</Step>
<Step title="Crew 결과를 다른 작업과 함께 사용하기">
- Crew 시작 단계 이후, 더하기(+) 아이콘을 클릭하여 새로운 작업을 추가합니다.
- 예를 들어, 내부 이메일 알림을 전송하려면 `커뮤니케이션 > 내부 이메일 알림 전송`을 선택합니다.
- 본문 필드에서 `데이터 삽입`을 클릭하고, `다음에서 속성 또는 작업 결과 보기 > 작업 결과 > Crew 결과`를 선택하여 이메일에 Crew 데이터를 포함합니다.
<Frame>
<img src="/images/enterprise/hubspot-workflow-2.png" alt="HubSpot Workflow 2" />
</Frame>
- 필요에 따라 추가 작업을 구성합니다.
- 모든 워크플로우 단계를 검토하여 올바르게 설정되었는지 확인합니다.
- 워크플로우를 활성화합니다.
<Frame>
<img src="/images/enterprise/hubspot-workflow-3.png" alt="HubSpot Workflow 3" />
</Frame>
</Step>
</Steps>
## 추가 자료
사용 가능한 작업과 사용자 지정 옵션에 대한 자세한 정보는 [HubSpot 워크플로우 문서](https://knowledge.hubspot.com/workflows/create-workflows)를 참고하세요.

View File

@@ -0,0 +1,78 @@
---
title: "HITL 워크플로우"
description: "CrewAI에서 의사결정 향상을 위한 Human-In-The-Loop 워크플로우 구현 방법을 알아보세요"
icon: "user-check"
---
인간-중심(Human-In-The-Loop, HITL)은 인공지능과 인간 전문 지식을 결합하여 의사결정을 강화하고 작업 결과를 향상시키는 강력한 접근 방식입니다. 이 가이드는 CrewAI 내에서 HITL을 구현하는 방법을 보여줍니다.
## HITL 워크플로 설정
<Steps>
<Step title="작업 구성">
사람 입력이 활성화된 상태로 작업을 설정하세요:
<Frame>
<img src="/images/enterprise/crew-human-input.png" alt="Crew Human Input" />
</Frame>
</Step>
<Step title="Webhook URL 제공">
crew를 시작할 때 인간 입력을 위한 webhook URL을 포함하세요:
<Frame>
<img src="/images/enterprise/crew-webhook-url.png" alt="Crew Webhook URL" />
</Frame>
</Step>
<Step title="Webhook 알림 받기">
crew가 사람 입력이 필요한 작업을 완료하면 다음 정보를 포함한 webhook 알림을 받게 됩니다:
- **Execution ID**
- **Task ID**
- **Task output**
</Step>
<Step title="작업 출력 검토">
시스템이 `Pending Human Input` 상태에서 일시 중지됩니다. 작업 출력을 신중하게 검토하세요.
</Step>
<Step title="사람 피드백 제출">
다음 정보를 포함하여 crew의 resume endpoint를 호출하세요:
<Frame>
<img src="/images/enterprise/crew-resume-endpoint.png" alt="Crew Resume Endpoint" />
</Frame>
<Warning>
**피드백이 작업 실행에 미치는 영향**:
피드백 전체 내용이 이후 작업 실행을 위한 추가 컨텍스트로 통합되므로 피드백 제공 시 신중함이 매우 중요합니다.
</Warning>
이는 다음을 의미합니다:
- 피드백에 입력한 모든 정보가 작업의 컨텍스트 일부가 됩니다.
- 관련 없는 상세 정보는 부정적인 영향을 줄 수 있습니다.
- 간결하고 관련성 높은 피드백이 작업의 집중도와 효율성을 유지하는 데 도움이 됩니다.
- 제출 전 항상 피드백을 신중히 검토하여 작업 실행을 긍정적으로 안내할 수 있는 관련 정보만 포함되어 있는지 확인하세요.
</Step>
<Step title="부정적 피드백 처리">
부정적인 피드백을 제공하는 경우:
- crew가 귀하의 피드백에서 추가된 컨텍스트와 함께 작업을 재시도합니다.
- 추가 확인을 위한 다른 webhook 알림을 받게 됩니다.
- 만족할 때까지 4-6단계를 반복하세요.
</Step>
<Step title="작업 실행 계속 진행">
긍정적인 피드백을 제출하면 실행이 다음 단계로 진행됩니다.
</Step>
</Steps>
## 모범 사례
- **구체적으로 작성하세요**: 해당 작업에 직접적으로 관련된 명확하고 실행 가능한 피드백을 제공하세요
- **관련성 유지**: 작업 수행 개선에 도움이 되는 정보만 포함하세요
- **적시에 응답하세요**: 워크플로우 지연을 피하기 위해 HITL 프롬프트에 신속하게 응답하세요
- **꼼꼼하게 검토하세요**: 제출 전에 피드백을 다시 확인하여 정확성을 보장하세요
## 일반적인 사용 사례
HITL 워크플로우는 특히 다음과 같은 경우에 유용합니다:
- 품질 보증 및 검증
- 복잡한 의사 결정 시나리오
- 민감하거나 위험도가 높은 작업
- 인간의 판단이 필요한 창의적 작업
- 준수 및 규제 검토

View File

@@ -0,0 +1,185 @@
---
title: "Kickoff Crew"
description: "CrewAI Enterprise에서 Crew를 시작하세요"
icon: "flag-checkered"
---
## 개요
Crew를 CrewAI Enterprise 플랫폼에 배포한 후에는 웹 인터페이스 또는 API를 통해 실행을 시작할 수 있습니다. 이 가이드는 두 가지 접근 방식을 모두 다룹니다.
## 방법 1: 웹 인터페이스 사용
### 1단계: 배포된 Crew로 이동하기
1. [CrewAI Enterprise](https://app.crewai.com)에 로그인합니다.
2. 프로젝트 목록에서 crew 이름을 클릭합니다.
3. crew의 상세 페이지로 이동합니다.
<Frame>
![Crew Dashboard](/images/enterprise/crew-dashboard.png)
</Frame>
### 2단계: 실행 시작
crew의 상세 페이지에서 실행을 시작할 수 있는 두 가지 옵션이 있습니다:
#### 옵션 A: 빠른 시작
1. Test Endpoints 섹션에서 `Kickoff` 링크를 클릭합니다.
2. JSON 에디터에서 crew에 필요한 입력 파라미터를 입력합니다.
3. `Send Request` 버튼을 클릭합니다.
<Frame>
![Kickoff Endpoint](/images/enterprise/kickoff-endpoint.png)
</Frame>
#### 옵션 B: 시각적 인터페이스 사용
1. crew 상세 페이지에서 `Run` 탭을 클릭합니다.
2. 양식 필드에 필요한 입력값을 입력합니다.
3. `Run Crew` 버튼을 클릭합니다.
<Frame>
![Run Crew](/images/enterprise/run-crew.png)
</Frame>
### 3단계: 실행 진행 상황 모니터링
실행을 시작한 후:
1. `kickoff_id`가 포함된 응답을 받게 됩니다. - **이 ID를 복사하세요**
2. 이 ID는 실행을 추적하는 데 필수적입니다
<Frame>
![작업 ID 복사](/images/enterprise/copy-task-id.png)
</Frame>
### 4단계: 실행 상태 확인
실행 진행 상황을 모니터링하려면:
1. Test Endpoints 섹션에서 "Status" 엔드포인트를 클릭하세요
2. 지정된 필드에 `kickoff_id`를 붙여넣으세요
3. "Get Status" 버튼을 클릭하세요
<Frame>
![Get Status](/images/enterprise/get-status.png)
</Frame>
상태 응답에는 다음이 표시됩니다:
- 현재 실행 상태(`running`, `completed` 등)
- 진행 중인 작업에 대한 세부 정보
- 지금까지 생성된 모든 출력
### 5단계: 최종 결과 보기
실행이 완료되면:
1. 상태가 `completed`로 변경됩니다.
2. 전체 실행 결과와 출력을 확인할 수 있습니다.
3. 더 자세한 내용을 보려면 crew 상세 페이지의 `Executions` 탭을 확인하세요.
## 방법 2: API 사용
CrewAI Enterprise REST API를 사용하여 프로그래밍 방식으로 crews를 시작할 수도 있습니다.
### 인증
모든 API 요청에는 인증을 위한 베어러 토큰이 필요합니다:
```bash
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" https://your-crew-url.crewai.com
```
베어러 토큰은 crew의 상세 페이지의 Status 탭에서 확인할 수 있습니다.
### 크루 상태 확인
작업을 실행하기 전에 크루가 정상적으로 실행되고 있는지 확인할 수 있습니다:
```bash
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" https://your-crew-url.crewai.com
```
요청이 성공하면 크루가 정상적으로 동작 중임을 나타내는 메시지가 반환됩니다:
```
Healthy%
```
### 1단계: 필요한 입력값 확인
먼저, crew에서 요구하는 입력값이 무엇인지 확인합니다:
```bash
curl -X GET \
-H "Authorization: Bearer YOUR_CREW_TOKEN" \
https://your-crew-url.crewai.com/inputs
```
응답은 예를 들어 다음과 같이 필수 입력 파라미터 배열을 포함한 JSON 객체로 반환됩니다:
```json
{"inputs":["topic","current_year"]}
```
이 예시에서는 해당 crew에서 두 개의 입력값인 `topic`과 `current_year`를 필요로 함을 보여줍니다.
### 2단계: kickoff 실행
필수 입력값을 제공하여 실행을 시작합니다:
```bash
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_CREW_TOKEN" \
-d '{"inputs": {"topic": "AI Agent Frameworks", "current_year": "2025"}}' \
https://your-crew-url.crewai.com/kickoff
```
응답에는 추적에 필요한 `kickoff_id`가 포함됩니다:
```json
{"kickoff_id":"abcd1234-5678-90ef-ghij-klmnopqrstuv"}
```
### 3단계: 실행 상태 확인
kickoff_id를 사용하여 실행 진행 상황을 모니터링하세요:
```bash
curl -X GET \
-H "Authorization: Bearer YOUR_CREW_TOKEN" \
https://your-crew-url.crewai.com/status/abcd1234-5678-90ef-ghij-klmnopqrstuv
```
## 실행 처리
### 장기 실행
오랜 시간이 걸릴 수 있는 실행의 경우:
1. 주기적으로 상태를 확인하는 폴링 메커니즘을 구현하는 것을 고려하세요
2. 실행 완료 시 알림을 받을 수 있도록 웹훅(가능한 경우)을 사용하세요
3. 잠재적인 타임아웃에 대비하여 오류 처리를 구현하세요
### 실행 컨텍스트
실행 컨텍스트에는 다음이 포함됩니다:
- 시작 시 제공된 입력값
- 배포 중에 구성된 환경 변수
- 태스크 간에 유지되는 상태
### 실행 실패 디버깅
실행이 실패할 경우:
1. "Executions" 탭에서 자세한 로그를 확인하세요
2. "Traces" 탭에서 단계별 실행 세부 정보를 검토하세요
3. 트레이스 세부 정보에서 LLM 응답과 도구 사용 내역을 확인하세요
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
실행 문제 또는 엔터프라이즈 플랫폼 관련 질문이 있으신 경우, 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,103 @@
---
title: "React 컴포넌트 내보내기"
description: "CrewAI Enterprise React 컴포넌트를 애플리케이션에 내보내고 통합하는 방법을 알아보세요"
icon: "react"
---
이 가이드는 CrewAI Enterprise crew를 React 컴포넌트로 내보내고 이를 여러분의 애플리케이션에 통합하는 방법을 설명합니다.
## React 컴포넌트 내보내기
<Steps>
<Step title="컴포넌트 내보내기">
배포된 crew 오른쪽에 있는 줄임표(세 개의 점)를 클릭한 다음 내보내기 옵션을 선택하고 파일을 로컬에 저장하세요. 본 예시에서는 `CrewLead.jsx`를 사용합니다.
<Frame>
<img src="/images/enterprise/export-react-component.png" alt="React 컴포넌트 내보내기" />
</Frame>
</Step>
</Steps>
## 리액트 환경 설정
이 리액트 컴포넌트를 로컬에서 실행하려면 리액트 개발 환경을 설정하고 이 컴포넌트를 리액트 프로젝트에 통합해야 합니다.
<Steps>
<Step title="Node.js 설치">
- 공식 웹사이트(https://nodejs.org/)에서 Node.js를 다운로드하고 설치하세요.
- 안정성을 위해 LTS(장기 지원) 버전을 선택하세요.
</Step>
<Step title="새 리액트 프로젝트 생성">
- 명령 프롬프트 또는 PowerShell을 엽니다.
- 프로젝트를 생성하고자 하는 디렉터리로 이동하세요.
- 다음 명령어를 실행하여 새로운 리액트 프로젝트를 생성합니다:
```bash
npx create-react-app my-crew-app
```
- 프로젝트 디렉터리로 이동합니다:
```bash
cd my-crew-app
```
</Step>
<Step title="필요한 의존성 설치">
```bash
npm install react-dom
```
</Step>
<Step title="CrewLead 컴포넌트 생성">
- 다운로드한 파일 `CrewLead.jsx`를 프로젝트의 `src` 폴더로 이동하세요.
</Step>
<Step title="App.js를 수정하여 CrewLead 컴포넌트 사용">
- `src/App.js`를 엽니다.
- 내용물을 아래와 같이 교체하세요:
```jsx
import React from 'react';
import CrewLead from './CrewLead';
function App() {
return (
<div className="App">
<CrewLead baseUrl="YOUR_API_BASE_URL" bearerToken="YOUR_BEARER_TOKEN" />
</div>
);
}
export default App;
```
- `YOUR_API_BASE_URL` 및 `YOUR_BEARER_TOKEN` 부분을 실제 API 값으로 바꿔주세요.
</Step>
<Step title="개발 서버 시작">
- 프로젝트 디렉터리에서 다음 명령어를 실행하세요:
```bash
npm start
```
- 개발 서버가 시작되며, 기본 웹 브라우저가 자동으로 http://localhost:3000 을 열고 리액트 앱이 실행되는 것을 확인할 수 있습니다.
</Step>
</Steps>
## 커스터마이징
그런 다음 `CrewLead.jsx`를 커스터마이즈하여 색상, 제목 등을 추가할 수 있습니다.
<Frame>
<img src="/images/enterprise/customise-react-component.png" alt="React 컴포넌트 커스터마이즈" />
</Frame>
<Frame>
<img src="/images/enterprise/customise-react-component-2.png" alt="React 컴포넌트 커스터마이즈" />
</Frame>
## 다음 단계
- 구성 요소 스타일을 애플리케이션 디자인에 맞게 맞춤화하세요
- 추가 구성을 위한 props를 추가하세요
- 애플리케이션의 상태 관리와 통합하세요
- 오류 처리 및 로딩 상태를 추가하세요

View File

@@ -0,0 +1,44 @@
---
title: "Salesforce 트리거"
description: "Salesforce 워크플로우에서 CrewAI crew를 트리거하여 CRM 자동화"
icon: "salesforce"
---
CrewAI Enterprise는 Salesforce에서 트리거되어 고객 관계 관리 워크플로우를 자동화하고 영업 운영을 강화할 수 있습니다.
## 개요
Salesforce는 기업이 영업, 서비스, 마케팅 운영을 효율화할 수 있도록 돕는 선도적인 고객 관계 관리(CRM) 플랫폼입니다. Salesforce에서 CrewAI 트리거를 설정하면 다음과 같은 작업을 수행할 수 있습니다:
- 리드 점수 산정 및 자격 심사 자동화
- 개인화된 영업 자료 생성
- AI 기반 응답으로 고객 서비스 강화
- 데이터 분석 및 보고 간소화
## 데모
<Frame>
<iframe width="100%" height="400" src="https://www.youtube.com/embed/oJunVqjjfu4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</Frame>
## 시작하기
Salesforce 트리거를 설정하려면:
1. **지원팀 문의**: Salesforce 트리거 설정을 위해 CrewAI Enterprise 지원팀에 연락하세요.
2. **요구 사항 검토**: 필요한 Salesforce 권한과 API 액세스 권한이 있는지 확인하세요.
3. **연결 구성**: 지원팀과 협력하여 CrewAI와 귀하의 Salesforce 인스턴스 간의 연결을 설정하세요.
4. **트리거 테스트**: 트리거가 귀하의 특정 사용 사례에 맞게 올바르게 작동하는지 확인하세요.
## 사용 사례
일반적인 Salesforce + CrewAI 트리거 시나리오는 다음과 같습니다:
- **Lead 처리**: 들어오는 리드를 자동으로 분석하고 점수화
- **제안서 생성**: 기회 데이터를 기반으로 맞춤형 제안서 생성
- **고객 인사이트**: 고객 상호작용 이력에서 분석 보고서 생성
- **후속 조치 자동화**: 개인화된 후속 메시지 및 추천 생성
## 다음 단계
자세한 설정 지침 및 고급 구성 옵션에 대해서는 CrewAI Enterprise 지원팀에 문의해 주시기 바랍니다. 지원팀은 귀하의 특정 Salesforce 환경과 비즈니스 요구에 맞는 맞춤형 안내를 제공해 드릴 수 있습니다.

View File

@@ -0,0 +1,61 @@
---
title: "Slack 트리거"
description: "슬래시 명령어를 사용해 Slack에서 CrewAI crew를 직접 트리거합니다"
icon: "slack"
---
이 가이드는 CrewAI 트리거를 사용하여 Slack에서 직접 crew를 시작하는 방법을 설명합니다.
## 사전 요구 사항
- CrewAI Slack 트리거가 설치되어 있고 Slack 워크스페이스에 연결되어 있음
- CrewAI에서 하나 이상의 crew가 구성되어 있음
## 설정 단계
<Steps>
<Step title="CrewAI Slack 트리거가 설정되어 있는지 확인">
CrewAI 대시보드에서 **트리거** 섹션으로 이동합니다.
<Frame>
<img src="/images/enterprise/slack-integration.png" alt="CrewAI Slack Integration" />
</Frame>
Slack이 나열되어 있고 연결되어 있는지 확인합니다.
</Step>
<Step title="Slack 채널을 엽니다">
- crew를 시작하려는 채널로 이동합니다.
- 슬래시 명령어 "**/kickoff**"를 입력하여 crew 시작 프로세스를 시작합니다.
- 입력하는 동안 "**Kickoff crew**"가 나타나야 합니다:
<Frame>
<img src="/images/enterprise/kickoff-slack-crew.png" alt="Kickoff crew" />
</Frame>
- Enter를 누르거나 "**Kickoff crew**" 옵션을 선택합니다. "**Kickoff an AI Crew**"라는 제목의 대화상자가 나타납니다.
</Step>
<Step title="시작할 crew를 선택합니다">
- "**Select of the crews online:**"라는 드롭다운 메뉴에서 시작할 crew를 선택합니다.
- 아래 예시에서는 "**prep-for-meeting**"이 선택되어 있습니다:
<Frame>
<img src="/images/enterprise/kickoff-slack-crew-dropdown.png" alt="Kickoff crew dropdown" />
</Frame>
- crew에 입력값이 필요한 경우 "**Add Inputs**" 버튼을 클릭하여 입력값을 제공합니다.
<Note>
위 예시에서 "**Add Inputs**" 버튼이 보이지만 아직 클릭되지 않았습니다.
</Note>
</Step>
<Step title="Kickoff을 클릭하고 crew가 완료될 때까지 기다립니다">
- crew를 선택하고 필요한 입력값을 추가했다면, "**Kickoff**"를 클릭하여 crew를 시작합니다.
<Frame>
<img src="/images/enterprise/kickoff-slack-crew-kickoff.png" alt="Kickoff crew" />
</Frame>
- crew가 실행을 시작하면 Slack 채널에서 결과를 확인할 수 있습니다.
<Frame>
<img src="/images/enterprise/kickoff-slack-crew-results.png" alt="Kickoff crew results" />
</Frame>
</Step>
</Steps>
## 팁
- Slack 워크스페이스에서 `/kickoff` 명령어를 사용할 수 있는 필요한 권한이 있는지 확인하세요.
- 드롭다운에서 원하는 crew가 보이지 않는 경우, CrewAI에서 해당 crew가 올바르게 구성되어 있고 온라인 상태인지 확인하세요.

View File

@@ -0,0 +1,87 @@
---
title: "팀 관리"
description: "CrewAI Enterprise 조직에서 팀원을 초대하고 관리하는 방법을 알아보세요"
icon: "users"
---
CrewAI Enterprise 계정의 관리자라면 새로운 팀원을 조직에 쉽게 초대할 수 있습니다. 이 안내서는 단계별로 프로세스를 안내합니다.
## 팀 멤버 초대하기
<Steps>
<Step title="설정 페이지 접속">
- CrewAI Enterprise 계정에 로그인합니다
- 대시보드 오른쪽 상단에 있는 기어 아이콘(⚙️)을 찾습니다
- 기어 아이콘을 클릭하여 **설정** 페이지에 접속합니다:
<Frame>
<img src="/images/enterprise/settings-page.png" alt="Settings Page" />
</Frame>
</Step>
<Step title="멤버 섹션으로 이동">
- 설정 페이지에서 `Members` 탭이 보입니다
- `Members` 탭을 클릭하여 **멤버** 페이지에 접속합니다:
<Frame>
<img src="/images/enterprise/members-tab.png" alt="Members Tab" />
</Frame>
</Step>
<Step title="새 멤버 초대">
- 멤버 섹션에서 현재 멤버 목록(본인 포함)을 확인할 수 있습니다
- `Email` 입력 필드를 찾습니다
- 초대하고자 하는 사람의 이메일 주소를 입력합니다
- `Invite` 버튼을 클릭하여 초대장을 보냅니다
</Step>
<Step title="필요에 따라 반복">
- 이 과정을 반복하여 여러 팀 멤버를 초대할 수 있습니다
- 초대한 각 멤버는 조직에 가입할 수 있는 이메일 초대장을 받게 됩니다
</Step>
</Steps>
## 역할 추가하기
플랫폼의 다양한 부분에 대한 접근 권한을 제어하기 위해 팀원들에게 역할을 추가할 수 있습니다.
<Steps>
<Step title="설정 페이지 접근">
- CrewAI Enterprise 계정에 로그인하세요
- 대시보드 오른쪽 상단에서 기어 아이콘(⚙️)을 찾으세요
- 기어 아이콘을 클릭하여 **설정** 페이지에 접근하세요:
<Frame>
<img src="/images/enterprise/settings-page.png" alt="설정 페이지" />
</Frame>
</Step>
<Step title="멤버 섹션으로 이동">
- 설정 페이지에서 `Roles` 탭을 확인할 수 있습니다
- `Roles` 탭을 클릭하여 **Roles** 페이지로 이동하세요.
<Frame>
<img src="/images/enterprise/roles-tab.png" alt="Roles 탭" />
</Frame>
- 새로운 역할을 추가하려면 `Add Role` 버튼을 클릭하세요.
- 역할의 세부 정보와 권한을 입력한 후 `Create Role` 버튼을 클릭하여 역할을 생성하세요.
<Frame>
<img src="/images/enterprise/add-role-modal.png" alt="Add Role 모달" />
</Frame>
</Step>
<Step title="멤버에게 역할 추가하기">
- 멤버 섹션에서 현재 멤버(본인 포함) 목록을 확인할 수 있습니다
<Frame>
<img src="/images/enterprise/member-accepted-invitation.png" alt="멤버 초대 수락 완료" />
</Frame>
- 멤버가 초대를 수락하면 역할을 추가할 수 있습니다.
- 다시 `Roles` 탭으로 이동하세요
- 역할을 추가할 멤버로 이동한 후 `Role` 열에서 드롭다운을 클릭하세요
- 멤버에게 추가할 역할을 선택하세요
- `Update` 버튼을 클릭하여 역할을 저장하세요
<Frame>
<img src="/images/enterprise/assign-role.png" alt="멤버에 역할 추가" />
</Frame>
</Step>
</Steps>
## 중요 참고 사항
- **관리자 권한**: 관리자 권한이 있는 사용자만 새 멤버를 초대할 수 있습니다
- **이메일 정확성**: 팀 멤버의 정확한 이메일 주소를 확인하세요
- **초대 수락**: 초대된 멤버는 조직에 가입하기 위해 초대를 수락해야 합니다
- **이메일 알림**: 팀 멤버에게 초대 이메일(스팸 폴더 포함)을 확인하도록 안내할 수 있습니다
이 단계들을 따르면 팀을 손쉽게 확장하고 CrewAI Enterprise 조직 내에서 더욱 효과적으로 협업할 수 있습니다.

View File

@@ -0,0 +1,88 @@
---
title: "크루 업데이트"
description: "CrewAI Enterprise에서 크루 업데이트하기"
icon: "pencil"
---
<Note>
CrewAI Enterprise에 crew를 배포한 후, 코드, 보안 설정 또는 구성을 업데이트해야 할 수 있습니다.
이 가이드는 이러한 일반적인 업데이트 작업을 수행하는 방법을 설명합니다.
</Note>
## 왜 Crew를 업데이트해야 하나요?
CrewAI는 기본적으로 GitHub 업데이트를 자동으로 반영하지 않으므로, 배포 시 `Auto-update` 옵션을 선택하지 않았다면 수동으로 업데이트를 트리거해야 합니다.
Crew 배포를 업데이트하고 싶은 이유는 여러 가지가 있을 수 있습니다:
- GitHub에 푸시한 최신 커밋으로 코드를 업데이트하고 싶은 경우
- 보안상의 이유로 bearer 토큰을 재설정하고 싶은 경우
- 환경 변수를 업데이트하고 싶은 경우
## 1. 최신 커밋으로 Crew 코드 업데이트하기
GitHub 저장소에 새로운 커밋을 푸시한 후 배포를 업데이트하려면 다음 단계를 따르세요:
1. CrewAI Enterprise 플랫폼에서 자신의 crew로 이동하세요.
2. crew 상세 페이지에서 `Re-deploy` 버튼을 클릭하세요.
<Frame>
![Re-deploy Button](/images/enterprise/redeploy-button.png)
</Frame>
이 작업을 수행하면 진행률 표시줄을 통해 추적할 수 있는 업데이트가 트리거됩니다. 시스템은 저장소에서 최신 코드를 가져와서 배포를 다시 빌드합니다.
## 2. 베어러 토큰 재설정
현재 토큰이 유출되었을 가능성이 있다고 의심되는 경우 등, 새 베어러 토큰을 생성해야 한다면 다음 단계를 따르세요:
1. CrewAI Enterprise 플랫폼에서 해당 crew로 이동하세요.
2. `Bearer Token` 섹션을 찾으세요.
3. 현재 토큰 옆에 있는 `Reset` 버튼을 클릭하세요.
<Frame>
![Reset Token](/images/enterprise/reset-token.png)
</Frame>
<Warning>
베어러 토큰을 재설정하면 이전 토큰은 즉시 사용할 수 없게 됩니다. 이전 토큰을 사용하고 있는 모든 애플리케이션이나 스크립트에서 토큰을 반드시 업데이트하세요.
</Warning>
## 3. 환경 변수 업데이트하기
crew의 환경 변수를 업데이트하려면 다음 단계를 따르세요:
1. 먼저 crew 이름을 클릭하여 배포 페이지에 접속합니다.
<Frame>
![환경 변수 버튼](/images/enterprise/env-vars-button.png)
</Frame>
2. `Environment Variables` 섹션을 찾습니다 (`Settings` 아이콘을 클릭해야 접근할 수 있습니다)
3. 제공된 필드에서 기존 변수를 수정하거나 새 변수를 추가합니다
4. 수정한 각 변수 옆의 `Update` 버튼을 클릭합니다
<Frame>
![환경 변수 업데이트](/images/enterprise/update-env-vars.png)
</Frame>
5. 마지막으로, 변경 사항을 적용하려면 페이지 하단의 `Update Deployment` 버튼을 클릭합니다
<Note>
환경 변수를 업데이트하면 새로운 배포가 트리거되지만, 이는 환경 설정만 업데이트하며 코드 자체는 변경되지 않습니다.
</Note>
## 업데이트 후
업데이트를 수행한 후:
1. 시스템이 crew를 다시 빌드하고 배포합니다
2. 실시간으로 배포 진행 상황을 모니터링할 수 있습니다
3. 완료되면 변경 사항이 예상대로 작동하는지 crew를 테스트합니다
<Tip>
업데이트 후 문제가 발생하면 플랫폼에서 배포 로그를 확인하거나 지원팀에 문의하여 도움을 받을 수 있습니다.
</Tip>
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
crew 업데이트나 배포 문제 해결에 대해 지원이 필요하시면 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,121 @@
---
title: "웹후크 자동화"
description: "ActivePieces, Zapier, Make.com과 같은 플랫폼을 사용하여 CrewAI Enterprise 워크플로우를 웹후크로 자동화하세요"
icon: "webhook"
---
CrewAI Enterprise를 사용하면 웹훅을 통해 워크플로우를 자동화할 수 있습니다. 이 문서에서는 웹훅을 설정하고 사용하는 과정을 안내하며, Zapier와 Make.com과 유사한 워크플로우 자동화 플랫폼인 ActivePieces와의 통합에 중점을 두고 crew 실행을 시작하는 방법을 설명합니다.
## Webhook 설정하기
<Steps>
<Step title="Kickoff 인터페이스 접근">
- CrewAI Enterprise 대시보드로 이동하세요.
- crew 실행을 시작할 때 사용하는 `/kickoff` 섹션을 찾으세요.
<Frame>
<img src="/images/enterprise/kickoff-interface.png" alt="Kickoff 인터페이스" />
</Frame>
</Step>
<Step title="JSON Content 구성하기">
JSON Content 섹션에서 다음 정보를 입력해야 합니다:
- **inputs**: 다음 항목이 포함된 JSON 객체:
- `company`: 회사 이름 (예: "tesla")
- `product_name`: 제품 이름 (예: "crewai")
- `form_response`: 응답 유형 (예: "financial")
- `icp_description`: 이상적인 고객 프로필(ICP)에 대한 간략한 설명
- `product_description`: 제품에 대한 짧은 설명
- `taskWebhookUrl`, `stepWebhookUrl`, `crewWebhookUrl`: 다양한 webhook 엔드포인트의 URL (ActivePieces, Zapier, Make.com 또는 기타 호환 플랫폼)
</Step>
<Step title="ActivePieces와 통합하기">
이 예시에서는 ActivePieces를 사용합니다. 또한 Zapier, Make.com 등 다른 플랫폼도 사용할 수 있습니다.
ActivePieces와 통합하려면:
1. ActivePieces에서 새 flow를 설정하세요.
2. 트리거를 추가하세요 (예: `Every Day` 스케줄).
<Frame>
<img src="/images/enterprise/activepieces-trigger.png" alt="ActivePieces 트리거" />
</Frame>
3. HTTP 액션 단계를 추가하세요.
- 액션을 `Send HTTP request`로 설정하세요.
- 메소드는 `POST`로 사용하세요.
- URL은 CrewAI Enterprise kickoff 엔드포인트로 설정하세요.
- 필요한 헤더 추가 (예: `Bearer Token`)
<Frame>
<img src="/images/enterprise/activepieces-headers.png" alt="ActivePieces 헤더" />
</Frame>
- Body에는 2단계에서 구성한 JSON content를 포함하세요.
<Frame>
<img src="/images/enterprise/activepieces-body.png" alt="ActivePieces 본문" />
</Frame>
- crew가 미리 정의된 시간에 kickoff됩니다.
</Step>
<Step title="Webhook 설정하기">
1. ActivePieces에서 새 flow를 만들고 이름을 지정하세요.
<Frame>
<img src="/images/enterprise/activepieces-flow.png" alt="ActivePieces Flow" />
</Frame>
2. 트리거로 webhook 단계를 추가하세요:
- 트리거 유형으로 `Catch Webhook`을 선택하세요.
- 이 작업을 통해 HTTP 요청을 수신하고 flow를 트리거하는 고유 URL이 생성됩니다.
<Frame>
<img src="/images/enterprise/activepieces-webhook.png" alt="ActivePieces Webhook" />
</Frame>
- 이메일이 crew webhook 본문 텍스트를 사용하도록 구성하세요.
<Frame>
<img src="/images/enterprise/activepieces-email.png" alt="ActivePieces 이메일" />
</Frame>
</Step>
</Steps>
## Webhook 출력 예시
<Tabs>
<Tab title="Step Webhook">
`stepWebhookUrl` - 각 agent의 inner thought가 실행될 때마다 호출되는 콜백
```json
{
"action": "**crewai 엔터프라이즈 솔루션을 위한 금융 산업에 대한 예비 조사 보고서**\n1. 산업 개요 및 동향\n금융 산업은 ....\n결론:\n금융 산업은 디지털 고객 참여, 위험 관리, 규정 준수와 같은 분야에서 crewai와 같은 AI 솔루션을 적용하기에 비옥한 토양을 제공합니다. 고객의 구체적인 요구와 규모에 더 맞춘 crewai 솔루션을 제안하기 위해 리드와의 추가적인 접촉이 추천됩니다.",
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0"
}
```
</Tab>
<Tab title="Task Webhook">
`taskWebhookUrl` - 각 task가 종료될 때마다 호출되는 콜백
```json
{
"description": "리드의 데이터에서 수집한 정보를 활용해 리드가 속한 산업, 기업 배경, 그리고 crewai의 잠재적 활용 사례에 대해 예비 조사를 수행합니다. 리드 스코어링 및 crewai 피치 전략 수립에 도움이 되는 관련 데이터를 중심으로 조사하세요. 금융 산업은 디지털 고객 참여, 리스크 관리, 규제 준수와 같은 분야에서 crewai와 같은 AI 솔루션을 적용하기에 매우 적합한 환경을 제공합니다. 리드에 맞춤화된 crewai 솔루션을 제안하기 위해 추가적인 접촉을 권장합니다.",
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0"
}
```
</Tab>
<Tab title="Crew Webhook">
`crewWebhookUrl` - crew 실행 종료 시 호출되는 콜백
```json
{
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0",
"result": {
"lead_score": "고객 서비스 향상 및 컴플라이언스가 특히 관련성이 높습니다.",
"talking_points": [
"crewai의 AI 솔루션이 자동화된 맞춤형 경험과 24/7 지원으로 고객 서비스를 혁신하고, 고객 만족도와 운영 효율성을 모두 개선할 수 있음을 강조하세요.",
"crewai가 더 나은 데이터 분석 및 의사 결정으로 기관의 지속 가능성 목표 달성(책임 투자 및 친환경 이니셔티브 기여)에 도움이 될 수 있음을 논의하세요.",
"지속적으로 변화하는 규정에 효율적인 데이터 처리 및 보고 기능으로 crewai가 컴플라이언스 준수를 강화하고, 위반 시 발생할 수 있는 벌금을 줄일 수 있음을 강조하세요.",
"crewai의 뛰어난 적응성으로 인해 대규모 다국적 운영뿐 아니라 소규모 맞춤형 프로젝트도 지원하여, 기관의 성장과 함께 솔루션도 확장될 수 있음을 강조하세요."
]
}
}
```
</Tab>
</Tabs>

View File

@@ -0,0 +1,103 @@
---
title: "Zapier 트리거"
description: "Zapier 워크플로우에서 CrewAI crew를 트리거하여 앱 간 워크플로우를 자동화합니다"
icon: "bolt"
---
이 가이드는 CrewAI Enterprise용 Zapier 트리거를 설정하는 과정을 안내합니다. 이를 통해 CrewAI Enterprise와 기타 애플리케이션 간의 워크플로우를 자동화할 수 있습니다.
## 사전 요구 사항
- CrewAI Enterprise 계정
- Zapier 계정
- Slack 계정 (이 특정 예시에 해당)
## 단계별 설정
<Steps>
<Step title="Slack 트리거 설정">
- Zapier에서 새 Zap을 만듭니다.
<Frame>
<img src="/images/enterprise/zapier-1.png" alt="Zapier 1" />
</Frame>
</Step>
<Step title="트리거 앱으로 Slack 선택">
<Frame>
<img src="/images/enterprise/zapier-2.png" alt="Zapier 2" />
</Frame>
- 트리거 이벤트로 `New Pushed Message`를 선택합니다.
- 아직 Slack 계정을 연결하지 않았다면 연결하세요.
</Step>
<Step title="CrewAI Enterprise 액션 구성">
- Zap에 새 액션 단계를 추가합니다.
- CrewAI+를 액션 앱으로, Kickoff를 액션 이벤트로 선택합니다.
<Frame>
<img src="/images/enterprise/zapier-3.png" alt="Zapier 5" />
</Frame>
</Step>
<Step title="CrewAI Enterprise 계정 연결">
- CrewAI Enterprise 계정을 연결하세요.
- 워크플로에 적합한 Crew를 선택하세요.
<Frame>
<img src="/images/enterprise/zapier-4.png" alt="Zapier 6" />
</Frame>
- Slack 메시지의 데이터를 사용하여 Crew의 입력값을 구성하세요.
</Step>
<Step title="CrewAI Enterprise 출력 포맷팅">
- CrewAI Enterprise에서 출력된 텍스트를 포맷팅하기 위해 추가 액션 단계를 추가합니다.
- Zapier의 포매팅 도구를 사용하여 Markdown 출력을 HTML로 변환합니다.
<Frame>
<img src="/images/enterprise/zapier-5.png" alt="Zapier 8" />
</Frame>
<Frame>
<img src="/images/enterprise/zapier-6.png" alt="Zapier 9" />
</Frame>
</Step>
<Step title="출력 이메일로 전송">
- 포맷팅된 출력을 이메일로 전송하는 마지막 액션 단계를 추가합니다.
- 원하는 이메일 서비스를 선택하세요 (예: Gmail, Outlook).
- 수신자, 제목, 본문 등 이메일 상세 정보를 구성하세요.
- 포맷팅된 CrewAI Enterprise 출력을 이메일 본문에 삽입합니다.
<Frame>
<img src="/images/enterprise/zapier-7.png" alt="Zapier 7" />
</Frame>
</Step>
<Step title="Slack에서 crew 실행">
- Slack 채널에 텍스트를 입력하세요.
<Frame>
<img src="/images/enterprise/zapier-7b.png" alt="Zapier 10" />
</Frame>
- 3점 버튼을 선택한 후 'Push to Zapier'를 선택하세요.
<Frame>
<img src="/images/enterprise/zapier-8.png" alt="Zapier 11" />
</Frame>
</Step>
<Step title="crew 선택 후 Kick Off로 Push">
<Frame>
<img src="/images/enterprise/zapier-9.png" alt="Zapier 12" />
</Frame>
</Step>
</Steps>
## 성공을 위한 팁
- CrewAI Enterprise 입력값이 Slack 메시지에서 올바르게 매핑되었는지 확인하세요.
- Zap을 활성화하기 전에 철저히 테스트하여 잠재적인 문제를 미리 파악하세요.
- 워크플로우 내에서 발생할 수 있는 실패 상황을 관리하기 위해 오류 처리 단계를 추가하는 것을 고려하세요.
이 단계를 따르면 Slack 메시지로 트리거되는 자동화된 워크플로우와 CrewAI Enterprise 출력이 포함된 이메일 알림을 설정할 수 있습니다.

View File

@@ -0,0 +1,253 @@
---
title: Asana 연동
description: "CrewAI를 위한 Asana 연동으로 팀 작업 및 프로젝트 조정."
icon: "circle"
---
## 개요
에이전트가 Asana를 통해 업무, 프로젝트, 팀 협업을 관리할 수 있도록 지원하세요. 작업 생성, 프로젝트 상태 업데이트, 담당 할당 관리, AI 기반 자동화를 통한 팀의 워크플로우 최적화를 손쉽게 할 수 있습니다.
## 사전 준비 사항
Asana 연동을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 Asana 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Asana 계정 연결
## 아사나(Asana) 연동 설정
### 1. Asana 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **Asana**를 찾습니다.
3. **Connect**를 클릭하고 OAuth 플로우를 완료합니다.
4. 작업 및 프로젝트 관리를 위한 필요한 권한을 부여합니다.
5. [계정 설정](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="ASANA_CREATE_COMMENT">
**설명:** Asana에 댓글을 생성합니다.
**매개변수:**
- `task` (string, 필수): 작업 ID - 댓글이 추가될 작업의 ID입니다. 댓글 작성자는 현재 인증된 사용자입니다.
- `text` (string, 필수): 텍스트 (예: "This is a comment.").
</Accordion>
<Accordion title="ASANA_CREATE_PROJECT">
**설명:** Asana에 프로젝트를 생성합니다.
**매개변수:**
- `name` (string, 필수): 이름 (예: "Stuff to buy").
- `workspace` (string, 필수): 워크스페이스 - Connect Portal Workflow 설정을 사용해 사용자가 프로젝트를 생성할 워크스페이스를 선택할 수 있도록 합니다. 공란인 경우 기본적으로 사용자의 첫 번째 워크스페이스가 선택됩니다.
- `team` (string, 선택): 팀 - Connect Portal Workflow 설정을 사용해 사용자가 이 프로젝트를 공유할 팀을 선택할 수 있도록 합니다. 공란인 경우 기본적으로 사용자의 첫 번째 팀이 선택됩니다.
- `notes` (string, 선택): 노트 (예: "These are things we need to purchase.").
</Accordion>
<Accordion title="ASANA_GET_PROJECTS">
**설명:** Asana의 프로젝트 목록을 가져옵니다.
**매개변수:**
- `archived` (string, 선택): 보관됨 - 보관된 프로젝트를 보려면 "true", 활성 프로젝트만 보려면 "false", 보관됨과 활성 모두 보려면 "default"를 선택합니다.
- 옵션: `default`, `true`, `false`
</Accordion>
<Accordion title="ASANA_GET_PROJECT_BY_ID">
**설명:** Asana에서 ID로 프로젝트를 가져옵니다.
**매개변수:**
- `projectFilterId` (string, 필수): 프로젝트 ID.
</Accordion>
<Accordion title="ASANA_CREATE_TASK">
**설명:** Asana에 작업을 생성합니다.
**매개변수:**
- `name` (string, 필수): 이름 (예: "Task Name").
- `workspace` (string, 선택): 워크스페이스 - Connect Portal Workflow 설정을 사용해 사용자가 작업을 생성할 워크스페이스를 선택할 수 있도록 합니다. 공란인 경우 기본적으로 사용자의 첫 번째 워크스페이스가 선택됩니다.
- `project` (string, 선택): 프로젝트 - Connect Portal Workflow 설정을 사용해 사용자가 이 작업을 생성할 프로젝트를 선택할 수 있도록 합니다.
- `notes` (string, 선택): 노트.
- `dueOnDate` (string, 선택): 마감일 - 이 작업이 완료되어야 하는 날짜입니다. Due At과 함께 사용할 수 없습니다. (예: "YYYY-MM-DD").
- `dueAtDate` (string, 선택): 마감 시각 - 이 작업이 완료되어야 하는 날짜와 시간 (ISO 타임스탬프) 입니다. Due On과 함께 사용할 수 없습니다. (예: "2019-09-15T02:06:58.147Z").
- `assignee` (string, 선택): 담당자 - 이 작업이 할당될 Asana 사용자의 ID입니다. Connect Portal Workflow 설정을 사용해 사용자가 담당자를 선택할 수 있도록 합니다.
- `gid` (string, 선택): 외부 ID - 이 작업과 연결할 애플리케이션의 ID입니다. 이 ID를 사용하여 이후 작업 업데이트를 동기화할 수 있습니다.
</Accordion>
<Accordion title="ASANA_UPDATE_TASK">
**설명:** Asana의 작업을 업데이트합니다.
**매개변수:**
- `taskId` (string, 필수): 작업 ID - 업데이트할 작업의 ID입니다.
- `completeStatus` (string, 선택): 완료 상태.
- 옵션: `true`, `false`
- `name` (string, 선택): 이름 (예: "Task Name").
- `notes` (string, 선택): 노트.
- `dueOnDate` (string, 선택): 마감일 - 이 작업이 완료되어야 하는 날짜입니다. Due At과 함께 사용할 수 없습니다. (예: "YYYY-MM-DD").
- `dueAtDate` (string, 선택): 마감 시각 - 이 작업이 완료되어야 하는 날짜와 시간 (ISO 타임스탬프) 입니다. Due On과 함께 사용할 수 없습니다. (예: "2019-09-15T02:06:58.147Z").
- `assignee` (string, 선택): 담당자 - 이 작업이 할당될 Asana 사용자의 ID입니다. Connect Portal Workflow 설정을 사용해 사용자가 담당자를 선택할 수 있도록 합니다.
- `gid` (string, 선택): 외부 ID - 이 작업과 연결할 애플리케이션의 ID입니다. 이 ID를 사용하여 이후 작업 업데이트를 동기화할 수 있습니다.
</Accordion>
<Accordion title="ASANA_GET_TASKS">
**설명:** Asana의 작업 목록을 가져옵니다.
**매개변수:**
- `workspace` (string, 선택): 워크스페이스 - 작업을 필터링할 워크스페이스의 ID입니다. Connect Portal Workflow 설정을 사용해 사용자가 워크스페이스를 선택할 수 있도록 합니다.
- `project` (string, 선택): 프로젝트 - 작업을 필터링할 프로젝트의 ID입니다. Connect Portal Workflow 설정을 사용해 사용자가 프로젝트를 선택할 수 있도록 합니다.
- `assignee` (string, 선택): 담당자 - 작업을 필터링할 담당자의 ID입니다. Connect Portal Workflow 설정을 사용해 사용자가 담당자를 선택할 수 있도록 합니다.
- `completedSince` (string, 선택): 이후 완료됨 - 미완료이거나 해당 시간(ISO 또는 Unix 타임스탬프) 이후에 완료된 작업만 반환합니다. (예: "2014-04-25T16:15:47-04:00").
</Accordion>
<Accordion title="ASANA_GET_TASKS_BY_ID">
**설명:** Asana에서 ID로 작업 목록을 가져옵니다.
**매개변수:**
- `taskId` (string, 필수): 작업 ID.
</Accordion>
<Accordion title="ASANA_GET_TASK_BY_EXTERNAL_ID">
**설명:** Asana에서 외부 ID로 작업을 가져옵니다.
**매개변수:**
- `gid` (string, 필수): 외부 ID - 이 작업이 애플리케이션과 연동(또는 동기화)된 ID입니다.
</Accordion>
<Accordion title="ASANA_ADD_TASK_TO_SECTION">
**설명:** Asana에서 섹션에 작업을 추가합니다.
**매개변수:**
- `sectionId` (string, 필수): 섹션 ID - 작업을 추가할 섹션의 ID입니다.
- `taskId` (string, 필수): 작업 ID - 작업의 ID입니다. (예: "1204619611402340").
- `beforeTaskId` (string, 선택): 이전 작업 ID - 이 작업이 삽입될 섹션 내의 작업 ID입니다. 이후 작업 ID와 함께 사용할 수 없습니다. (예: "1204619611402340").
- `afterTaskId` (string, 선택): 이후 작업 ID - 이 작업이 삽입될 섹션 내의 작업 ID입니다. 이전 작업 ID와 함께 사용할 수 없습니다. (예: "1204619611402340").
</Accordion>
<Accordion title="ASANA_GET_TEAMS">
**설명:** Asana에서 팀 목록을 가져옵니다.
**매개변수:**
- `workspace` (string, 필수): 워크스페이스 - 인증된 사용자가 볼 수 있는 이 워크스페이스 내의 팀을 반환합니다.
</Accordion>
<Accordion title="ASANA_GET_WORKSPACES">
**설명:** Asana에서 워크스페이스 목록을 가져옵니다.
**매개변수:** 필요 없음.
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Asana 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Asana tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Asana capabilities
asana_agent = Agent(
role="Project Manager",
goal="Manage tasks and projects in Asana efficiently",
backstory="An AI assistant specialized in project management and task coordination.",
tools=[enterprise_tools]
)
# Task to create a new project
create_project_task = Task(
description="Create a new project called 'Q1 Marketing Campaign' in the Marketing workspace",
agent=asana_agent,
expected_output="Confirmation that the project was created successfully with project ID"
)
# Run the task
crew = Crew(
agents=[asana_agent],
tasks=[create_project_task]
)
crew.kickoff()
```
### 특정 Asana 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Asana tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["asana_create_task", "asana_update_task", "asana_get_tasks"]
)
task_manager_agent = Agent(
role="Task Manager",
goal="Create and manage tasks efficiently",
backstory="An AI assistant that focuses on task creation and management.",
tools=enterprise_tools
)
# Task to create and assign a task
task_management = Task(
description="Create a task called 'Review quarterly reports' and assign it to the appropriate team member",
agent=task_manager_agent,
expected_output="Task created and assigned successfully"
)
crew = Crew(
agents=[task_manager_agent],
tasks=[task_management]
)
crew.kickoff()
```
### 고급 프로젝트 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_coordinator = Agent(
role="Project Coordinator",
goal="Coordinate project activities and track progress",
backstory="An experienced project coordinator who ensures projects run smoothly.",
tools=[enterprise_tools]
)
# Complex task involving multiple Asana operations
coordination_task = Task(
description="""
1. Get all active projects in the workspace
2. For each project, get the list of incomplete tasks
3. Create a summary report task in the 'Management Reports' project
4. Add comments to overdue tasks to request status updates
""",
agent=project_coordinator,
expected_output="Summary report created and status update requests sent for overdue tasks"
)
crew = Crew(
agents=[project_coordinator],
tasks=[coordination_task]
)
crew.kickoff()
```

View File

@@ -0,0 +1,268 @@
---
title: Box 통합
description: "CrewAI용 Box 통합을 통한 파일 저장 및 문서 관리."
icon: "box"
---
## 개요
에이전트가 Box를 통해 파일, 폴더, 문서를 관리할 수 있도록 지원하세요. 파일을 업로드하고, 폴더 구조를 조직하며, 콘텐츠를 검색하고, AI 기반 자동화를 통해 팀의 문서 관리를 효율적으로 진행할 수 있습니다.
## 사전 준비 사항
Box 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 Box 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Box 계정 연결
## Box 통합 설정
### 1. Box 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **Box**를 찾습니다.
3. **Connect**를 클릭하고 OAuth 흐름을 완료합니다.
4. 파일 및 폴더 관리를 위한 필요한 권한을 부여합니다.
5. [Account Settings](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 액션
<AccordionGroup>
<Accordion title="BOX_SAVE_FILE">
**설명:** Box에서 URL로부터 파일을 저장합니다.
**파라미터:**
- `fileAttributes` (object, 필수): 속성 - 이름, 상위 폴더, 타임스탬프 등 파일 메타데이터.
```json
{
"content_created_at": "2012-12-12T10:53:43-08:00",
"content_modified_at": "2012-12-12T10:53:43-08:00",
"name": "qwerty.png",
"parent": { "id": "1234567" }
}
```
- `file` (string, 필수): 파일 URL - 파일 크기는 50MB 미만이어야 합니다. (예시: "https://picsum.photos/200/300").
</Accordion>
<Accordion title="BOX_SAVE_FILE_FROM_OBJECT">
**설명:** Box에 파일을 저장합니다.
**파라미터:**
- `file` (string, 필수): 파일 - 파일 데이터를 포함하는 파일 객체를 허용합니다. 파일 크기는 50MB 미만이어야 합니다.
- `fileName` (string, 필수): 파일명 (예시: "qwerty.png").
- `folder` (string, 선택): 폴더 - Connect Portal Workflow Settings를 사용하여 사용자가 파일의 폴더 목적지를 선택할 수 있도록 합니다. 비워두면 기본적으로 사용자의 루트 폴더에 저장됩니다.
</Accordion>
<Accordion title="BOX_GET_FILE_BY_ID">
**설명:** Box에서 ID로 파일을 가져옵니다.
**파라미터:**
- `fileId` (string, 필수): 파일 ID - 파일을 나타내는 고유 식별자. (예시: "12345").
</Accordion>
<Accordion title="BOX_LIST_FILES">
**설명:** Box에서 파일 목록을 조회합니다.
**파라미터:**
- `folderId` (string, 필수): 폴더 ID - 폴더를 나타내는 고유 식별자. (예시: "0").
- `filterFormula` (object, 선택): 쿼리 normal form (DNF)의 필터 - 단일 조건의 AND 그룹의 OR.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "direction",
"operator": "$stringExactlyMatches",
"value": "ASC"
}
]
}
]
}
```
</Accordion>
<Accordion title="BOX_CREATE_FOLDER">
**설명:** Box에 폴더를 생성합니다.
**파라미터:**
- `folderName` (string, 필수): 이름 - 새 폴더의 이름. (예시: "New Folder").
- `folderParent` (object, 필수): 상위 폴더 - 새 폴더가 생성될 상위 폴더.
```json
{
"id": "123456"
}
```
</Accordion>
<Accordion title="BOX_MOVE_FOLDER">
**설명:** Box에서 폴더를 이동합니다.
**파라미터:**
- `folderId` (string, 필수): 폴더 ID - 폴더를 나타내는 고유 식별자. (예시: "0").
- `folderName` (string, 필수): 이름 - 폴더의 이름. (예시: "New Folder").
- `folderParent` (object, 필수): 상위 폴더 - 새 상위 폴더 목적지.
```json
{
"id": "123456"
}
```
</Accordion>
<Accordion title="BOX_GET_FOLDER_BY_ID">
**설명:** Box에서 ID로 폴더를 가져옵니다.
**파라미터:**
- `folderId` (string, 필수): 폴더 ID - 폴더를 나타내는 고유 식별자. (예시: "0").
</Accordion>
<Accordion title="BOX_SEARCH_FOLDERS">
**설명:** Box에서 폴더를 검색합니다.
**파라미터:**
- `folderId` (string, 필수): 폴더 ID - 검색할 폴더.
- `filterFormula` (object, 선택): 쿼리 normal form (DNF)의 필터 - 단일 조건의 AND 그룹의 OR.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "sort",
"operator": "$stringExactlyMatches",
"value": "name"
}
]
}
]
}
```
</Accordion>
<Accordion title="BOX_DELETE_FOLDER">
**설명:** Box에서 폴더를 삭제합니다.
**파라미터:**
- `folderId` (string, 필수): 폴더 ID - 폴더를 나타내는 고유 식별자. (예시: "0").
- `recursive` (boolean, 선택): 재귀적 삭제 - 폴더가 비어 있지 않을 경우, 폴더와 그 모든 내용을 재귀적으로 삭제합니다.
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Box Agent 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Box tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Box capabilities
box_agent = Agent(
role="Document Manager",
goal="Manage files and folders in Box efficiently",
backstory="An AI assistant specialized in document management and file organization.",
tools=[enterprise_tools]
)
# Task to create a folder structure
create_structure_task = Task(
description="Create a folder called 'Project Files' in the root directory and upload a document from URL",
agent=box_agent,
expected_output="Folder created and file uploaded successfully"
)
# Run the task
crew = Crew(
agents=[box_agent],
tasks=[create_structure_task]
)
crew.kickoff()
```
### 특정 Box 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Box tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["box_create_folder", "box_save_file", "box_list_files"]
)
file_organizer_agent = Agent(
role="File Organizer",
goal="Organize and manage file storage efficiently",
backstory="An AI assistant that focuses on file organization and storage management.",
tools=enterprise_tools
)
# Task to organize files
organization_task = Task(
description="Create a folder structure for the marketing team and organize existing files",
agent=file_organizer_agent,
expected_output="Folder structure created and files organized"
)
crew = Crew(
agents=[file_organizer_agent],
tasks=[organization_task]
)
crew.kickoff()
```
### 고급 파일 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
file_manager = Agent(
role="File Manager",
goal="Maintain organized file structure and manage document lifecycle",
backstory="An experienced file manager who ensures documents are properly organized and accessible.",
tools=[enterprise_tools]
)
# Complex task involving multiple Box operations
management_task = Task(
description="""
1. List all files in the root folder
2. Create monthly archive folders for the current year
3. Move old files to appropriate archive folders
4. Generate a summary report of the file organization
""",
agent=file_manager,
expected_output="Files organized into archive structure with summary report"
)
crew = Crew(
agents=[file_manager],
tasks=[management_task]
)
crew.kickoff()
```

View File

@@ -0,0 +1,293 @@
---
title: ClickUp 연동
description: "CrewAI를 위한 ClickUp 연동을 통한 작업 및 생산성 관리."
icon: "list-check"
---
## 개요
에이전트가 ClickUp을 통해 작업, 프로젝트 및 생산성 워크플로우를 관리할 수 있도록 지원하세요. 작업을 생성 및 업데이트하고, 프로젝트를 구성하며, 팀 할당을 관리하고, AI 기반 자동화를 통해 생산성 관리를 간소화할 수 있습니다.
## 사전 준비사항
ClickUp 통합을 사용하기 전에 다음을 준비해야 합니다:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 ClickUp 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 ClickUp 계정 연결
## ClickUp 통합 설정
### 1. ClickUp 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **ClickUp**을 찾습니다.
3. **Connect**를 클릭하고 OAuth 과정을 완료합니다.
4. 작업 및 프로젝트 관리에 필요한 권한을 부여합니다.
5. [계정 설정](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 동작
<AccordionGroup>
<Accordion title="CLICKUP_SEARCH_TASKS">
**설명:** 고급 필터를 사용하여 ClickUp에서 작업을 검색합니다.
**파라미터:**
- `taskFilterFormula` (object, 선택): 이항 표준형(DNF)의 필터 - 단일 조건의 AND 그룹들의 OR.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "statuses%5B%5D",
"operator": "$stringExactlyMatches",
"value": "open"
}
]
}
]
}
```
사용 가능한 필드: `space_ids%5B%5D`, `project_ids%5B%5D`, `list_ids%5B%5D`, `statuses%5B%5D`, `include_closed`, `assignees%5B%5D`, `tags%5B%5D`, `due_date_gt`, `due_date_lt`, `date_created_gt`, `date_created_lt`, `date_updated_gt`, `date_updated_lt`
</Accordion>
<Accordion title="CLICKUP_GET_TASK_IN_LIST">
**설명:** ClickUp의 특정 목록에서 작업을 가져옵니다.
**파라미터:**
- `listId` (string, 필수): 목록 - 작업을 가져올 목록을 선택합니다. 사용자가 ClickUp 목록을 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `taskFilterFormula` (string, 선택): 지정된 필터와 일치하는 작업을 검색합니다. 예: name=task1.
</Accordion>
<Accordion title="CLICKUP_CREATE_TASK">
**설명:** ClickUp에 작업을 생성합니다.
**파라미터:**
- `listId` (string, 필수): 목록 - 이 작업을 생성할 목록을 선택합니다. 사용자가 ClickUp 목록을 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `name` (string, 필수): 이름 - 작업 이름.
- `description` (string, 선택): 설명 - 작업 설명.
- `status` (string, 선택): 상태 - 이 작업에 대한 상태를 선택합니다. 사용자가 ClickUp 상태를 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `assignees` (string, 선택): 담당자 - 이 작업에 할당할 멤버(또는 멤버 ID 배열)를 선택합니다. 사용자가 ClickUp 멤버를 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `dueDate` (string, 선택): 마감일 - 이 작업의 마감일을 지정합니다.
- `additionalFields` (string, 선택): 추가 필드 - 이 작업에 포함할 추가 필드를 JSON으로 지정합니다.
</Accordion>
<Accordion title="CLICKUP_UPDATE_TASK">
**설명:** ClickUp의 작업을 업데이트합니다.
**파라미터:**
- `taskId` (string, 필수): 작업 ID - 업데이트할 작업의 ID입니다.
- `listId` (string, 필수): 목록 - 이 작업을 생성할 목록을 선택합니다. 사용자가 ClickUp 목록을 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `name` (string, 선택): 이름 - 작업 이름.
- `description` (string, 선택): 설명 - 작업 설명.
- `status` (string, 선택): 상태 - 이 작업에 대한 상태를 선택합니다. 사용자가 ClickUp 상태를 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `assignees` (string, 선택): 담당자 - 이 작업에 할당할 멤버(또는 멤버 ID 배열)를 선택합니다. 사용자가 ClickUp 멤버를 선택할 수 있도록 Connect Portal 사용자 설정을 사용하세요.
- `dueDate` (string, 선택): 마감일 - 이 작업의 마감일을 지정합니다.
- `additionalFields` (string, 선택): 추가 필드 - 이 작업에 포함할 추가 필드를 JSON으로 지정합니다.
</Accordion>
<Accordion title="CLICKUP_DELETE_TASK">
**설명:** ClickUp에서 작업을 삭제합니다.
**파라미터:**
- `taskId` (string, 필수): 작업 ID - 삭제할 작업의 ID입니다.
</Accordion>
<Accordion title="CLICKUP_GET_LIST">
**설명:** ClickUp에서 목록 정보를 가져옵니다.
**파라미터:**
- `spaceId` (string, 필수): 스페이스 ID - 목록이 포함된 스페이스의 ID입니다.
</Accordion>
<Accordion title="CLICKUP_GET_CUSTOM_FIELDS_IN_LIST">
**설명:** ClickUp에서 목록의 사용자 정의 필드를 가져옵니다.
**파라미터:**
- `listId` (string, 필수): 목록 ID - 사용자 정의 필드를 가져올 목록의 ID입니다.
</Accordion>
<Accordion title="CLICKUP_GET_ALL_FIELDS_IN_LIST">
**설명:** ClickUp에서 목록의 모든 필드를 가져옵니다.
**파라미터:**
- `listId` (string, 필수): 목록 ID - 모든 필드를 가져올 목록의 ID입니다.
</Accordion>
<Accordion title="CLICKUP_GET_SPACE">
**설명:** ClickUp에서 스페이스 정보를 가져옵니다.
**파라미터:**
- `spaceId` (string, 선택): 스페이스 ID - 조회할 스페이스의 ID입니다.
</Accordion>
<Accordion title="CLICKUP_GET_FOLDERS">
**설명:** ClickUp에서 폴더를 가져옵니다.
**파라미터:**
- `spaceId` (string, 필수): 스페이스 ID - 폴더가 포함된 스페이스의 ID입니다.
</Accordion>
<Accordion title="CLICKUP_GET_MEMBER">
**설명:** ClickUp에서 멤버 정보를 가져옵니다.
**파라미터:** 필요 없음.
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 ClickUp 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (ClickUp tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with ClickUp capabilities
clickup_agent = Agent(
role="Task Manager",
goal="Manage tasks and projects in ClickUp efficiently",
backstory="An AI assistant specialized in task management and productivity coordination.",
tools=[enterprise_tools]
)
# Task to create a new task
create_task = Task(
description="Create a task called 'Review Q1 Reports' in the Marketing list with high priority",
agent=clickup_agent,
expected_output="Task created successfully with task ID"
)
# Run the task
crew = Crew(
agents=[clickup_agent],
tasks=[create_task]
)
crew.kickoff()
```
### 특정 ClickUp 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific ClickUp tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["clickup_create_task", "clickup_update_task", "clickup_search_tasks"]
)
task_coordinator = Agent(
role="Task Coordinator",
goal="Create and manage tasks efficiently",
backstory="An AI assistant that focuses on task creation and status management.",
tools=enterprise_tools
)
# Task to manage task workflow
task_workflow = Task(
description="Create a task for project planning and assign it to the development team",
agent=task_coordinator,
expected_output="Task created and assigned successfully"
)
crew = Crew(
agents=[task_coordinator],
tasks=[task_workflow]
)
crew.kickoff()
```
### 고급 프로젝트 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_manager = Agent(
role="Project Manager",
goal="Coordinate project activities and track team productivity",
backstory="An experienced project manager who ensures projects are delivered on time.",
tools=[enterprise_tools]
)
# Complex task involving multiple ClickUp operations
project_coordination = Task(
description="""
1. Get all open tasks in the current space
2. Identify overdue tasks and update their status
3. Create a weekly report task summarizing project progress
4. Assign the report task to the team lead
""",
agent=project_manager,
expected_output="Project status updated and weekly report task created and assigned"
)
crew = Crew(
agents=[project_manager],
tasks=[project_coordination]
)
crew.kickoff()
```
### 작업 검색 및 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
task_analyst = Agent(
role="Task Analyst",
goal="Analyze task patterns and optimize team productivity",
backstory="An AI assistant that analyzes task data to improve team efficiency.",
tools=[enterprise_tools]
)
# Task to analyze and optimize task distribution
task_analysis = Task(
description="""
Search for all tasks assigned to team members in the last 30 days,
analyze completion patterns, and create optimization recommendations
""",
agent=task_analyst,
expected_output="Task analysis report with optimization recommendations"
)
crew = Crew(
agents=[task_analyst],
tasks=[task_analysis]
)
crew.kickoff()
```
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
ClickUp 연동 설정 또는 문제 해결에 대한 지원이 필요하신 경우 저희 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,323 @@
---
title: GitHub 통합
description: "CrewAI를 위한 GitHub 통합을 통한 리포지토리 및 이슈 관리."
icon: "github"
---
## 개요
에이전트가 GitHub를 통해 리포지토리, 이슈, 릴리스를 관리할 수 있도록 지원합니다. 이슈를 생성 및 업데이트하고, 릴리스를 관리하고, 프로젝트 개발을 추적하며, AI 기반 자동화를 통해 소프트웨어 개발 워크플로우를 효율화하세요.
## 사전 요구 사항
GitHub 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 해당 리포지토리에 대한 적절한 권한이 있는 GitHub 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 GitHub 계정 연결 완료
## GitHub 연동 설정
### 1. GitHub 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **GitHub**을 찾습니다.
3. **Connect**를 클릭하고 OAuth 흐름을 완료합니다.
4. 리포지토리 및 이슈 관리를 위한 필수 권한을 부여합니다.
5. [계정 설정](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="GITHUB_CREATE_ISSUE">
**설명:** GitHub에 이슈를 생성합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 이슈와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 이슈와 연관된 저장소 이름을 지정합니다.
- `title` (string, 필수): 이슈 제목 - 생성할 이슈의 제목을 지정합니다.
- `body` (string, 선택): 이슈 본문 - 생성할 이슈의 본문 내용을 지정합니다.
- `assignees` (string, 선택): 담당자 - 이 이슈의 담당자 GitHub 로그인을 문자열 배열로 지정합니다. (예시: `["octocat"]`).
</Accordion>
<Accordion title="GITHUB_UPDATE_ISSUE">
**설명:** GitHub에서 이슈를 업데이트합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 이슈와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 이슈와 연관된 저장소 이름을 지정합니다.
- `issue_number` (string, 필수): 이슈 번호 - 업데이트할 이슈의 번호를 지정합니다.
- `title` (string, 필수): 이슈 제목 - 업데이트할 이슈의 제목을 지정합니다.
- `body` (string, 선택): 이슈 본문 - 업데이트할 이슈의 본문 내용을 지정합니다.
- `assignees` (string, 선택): 담당자 - 이 이슈의 담당자 GitHub 로그인을 문자열 배열로 지정합니다. (예시: `["octocat"]`).
- `state` (string, 선택): 상태 - 이슈의 변경된 상태를 지정합니다.
- 옵션: `open`, `closed`
</Accordion>
<Accordion title="GITHUB_GET_ISSUE_BY_NUMBER">
**설명:** GitHub에서 번호로 이슈를 조회합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 이슈와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 이슈와 연관된 저장소 이름을 지정합니다.
- `issue_number` (string, 필수): 이슈 번호 - 가져올 이슈의 번호를 지정합니다.
</Accordion>
<Accordion title="GITHUB_LOCK_ISSUE">
**설명:** GitHub에서 이슈를 잠급니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 이슈와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 이슈와 연관된 저장소 이름을 지정합니다.
- `issue_number` (string, 필수): 이슈 번호 - 잠글 이슈의 번호를 지정합니다.
- `lock_reason` (string, 필수): 잠금 사유 - 이슈 또는 풀 리퀘스트 대화에 대한 잠금 이유를 지정합니다.
- 옵션: `off-topic`, `too heated`, `resolved`, `spam`
</Accordion>
<Accordion title="GITHUB_SEARCH_ISSUE">
**설명:** GitHub에서 이슈를 검색합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 이슈와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 이슈와 연관된 저장소 이름을 지정합니다.
- `filter` (object, 필수): 불리언 표준형의 필터 - 단일 조건의 AND 그룹의 OR 조합.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "assignee",
"operator": "$stringExactlyMatches",
"value": "octocat"
}
]
}
]
}
```
사용 가능한 필드: `assignee`, `creator`, `mentioned`, `labels`
</Accordion>
<Accordion title="GITHUB_CREATE_RELEASE">
**설명:** GitHub에 릴리스를 생성합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 릴리스와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 릴리스와 연관된 저장소 이름을 지정합니다.
- `tag_name` (string, 필수): 이름 - 생성할 릴리스 태그의 이름을 지정합니다. (예시: "v1.0.0").
- `target_commitish` (string, 선택): 대상 - 릴리스의 대상을 지정합니다. 브랜치 이름이나 커밋 SHA가 될 수 있으며, 기본값은 메인 브랜치입니다. (예시: "master").
- `body` (string, 선택): 본문 - 이 릴리스에 대한 설명을 지정합니다.
- `draft` (string, 선택): 초안 - 생성할 릴리스를 초안(비공개) 릴리스로 지정할지 여부를 지정합니다.
- 옵션: `true`, `false`
- `prerelease` (string, 선택): 프리릴리스 - 생성할 릴리스를 프리릴리스로 지정할지 여부를 지정합니다.
- 옵션: `true`, `false`
- `discussion_category_name` (string, 선택): 토론 카테고리 이름 - 지정 시, 해당 카테고리의 토론이 생성되어 릴리스와 연결됩니다. 값은 저장소에 이미 존재하는 카테고리여야 합니다.
- `generate_release_notes` (string, 선택): 릴리스 노트 - 지정한 이름과 본문을 사용하여 릴리스 노트를 자동으로 생성할지 여부를 지정합니다.
- 옵션: `true`, `false`
</Accordion>
<Accordion title="GITHUB_UPDATE_RELEASE">
**설명:** GitHub에서 릴리스를 업데이트합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 릴리스와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 릴리스와 연관된 저장소 이름을 지정합니다.
- `id` (string, 필수): 릴리스 ID - 업데이트할 릴리스의 ID를 지정합니다.
- `tag_name` (string, 선택): 이름 - 업데이트할 릴리스 태그의 이름을 지정합니다. (예시: "v1.0.0").
- `target_commitish` (string, 선택): 대상 - 릴리스의 대상을 지정합니다. 브랜치 이름이나 커밋 SHA가 될 수 있으며, 기본값은 메인 브랜치입니다. (예시: "master").
- `body` (string, 선택): 본문 - 이 릴리스에 대한 설명을 지정합니다.
- `draft` (string, 선택): 초안 - 생성할 릴리스를 초안(비공개) 릴리스로 지정할지 여부를 지정합니다.
- 옵션: `true`, `false`
- `prerelease` (string, 선택): 프리릴리스 - 생성할 릴리스를 프리릴리스로 지정할지 여부를 지정합니다.
- 옵션: `true`, `false`
- `discussion_category_name` (string, 선택): 토론 카테고리 이름 - 지정 시, 해당 카테고리의 토론이 생성되어 릴리스와 연결됩니다. 값은 저장소에 이미 존재하는 카테고리여야 합니다.
- `generate_release_notes` (string, 선택): 릴리스 노트 - 지정한 이름과 본문을 사용하여 릴리스 노트를 자동으로 생성할지 여부를 지정합니다.
- 옵션: `true`, `false`
</Accordion>
<Accordion title="GITHUB_GET_RELEASE_BY_ID">
**설명:** GitHub에서 ID로 릴리스를 조회합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 릴리스와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 릴리스와 연관된 저장소 이름을 지정합니다.
- `id` (string, 필수): 릴리스 ID - 조회할 릴리스의 ID를 지정합니다.
</Accordion>
<Accordion title="GITHUB_GET_RELEASE_BY_TAG_NAME">
**설명:** GitHub에서 태그 이름으로 릴리스를 조회합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 릴리스와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 릴리스와 연관된 저장소 이름을 지정합니다.
- `tag_name` (string, 필수): 이름 - 가져올 릴리스의 태그를 지정합니다. (예시: "v1.0.0").
</Accordion>
<Accordion title="GITHUB_DELETE_RELEASE">
**설명:** GitHub에서 릴리스를 삭제합니다.
**파라미터:**
- `owner` (string, 필수): 소유자 - 이 릴리스와 연관된 저장소의 계정 소유자 이름을 지정합니다. (예시: "abc").
- `repo` (string, 필수): 저장소 - 이 릴리스와 연관된 저장소 이름을 지정합니다.
- `id` (string, 필수): 릴리스 ID - 삭제할 릴리스의 ID를 지정합니다.
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 GitHub 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (GitHub tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with GitHub capabilities
github_agent = Agent(
role="Repository Manager",
goal="Manage GitHub repositories, issues, and releases efficiently",
backstory="An AI assistant specialized in repository management and issue tracking.",
tools=[enterprise_tools]
)
# Task to create a new issue
create_issue_task = Task(
description="Create a bug report issue for the login functionality in the main repository",
agent=github_agent,
expected_output="Issue created successfully with issue number"
)
# Run the task
crew = Crew(
agents=[github_agent],
tasks=[create_issue_task]
)
crew.kickoff()
```
### 특정 GitHub 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific GitHub tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["github_create_issue", "github_update_issue", "github_search_issue"]
)
issue_manager = Agent(
role="Issue Manager",
goal="Create and manage GitHub issues efficiently",
backstory="An AI assistant that focuses on issue tracking and management.",
tools=enterprise_tools
)
# Task to manage issue workflow
issue_workflow = Task(
description="Create a feature request issue and assign it to the development team",
agent=issue_manager,
expected_output="Feature request issue created and assigned successfully"
)
crew = Crew(
agents=[issue_manager],
tasks=[issue_workflow]
)
crew.kickoff()
```
### 릴리즈 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
release_manager = Agent(
role="Release Manager",
goal="Manage software releases and versioning",
backstory="An experienced release manager who handles version control and release processes.",
tools=[enterprise_tools]
)
# Task to create a new release
release_task = Task(
description="""
Create a new release v2.1.0 for the project with:
- Auto-generated release notes
- Target the main branch
- Include a description of new features and bug fixes
""",
agent=release_manager,
expected_output="Release v2.1.0 created successfully with release notes"
)
crew = Crew(
agents=[release_manager],
tasks=[release_task]
)
crew.kickoff()
```
### 이슈 추적 및 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_coordinator = Agent(
role="Project Coordinator",
goal="Track and coordinate project issues and development progress",
backstory="An AI assistant that helps coordinate development work and track project progress.",
tools=[enterprise_tools]
)
# Complex task involving multiple GitHub operations
coordination_task = Task(
description="""
1. Search for all open issues assigned to the current milestone
2. Identify overdue issues and update their priority labels
3. Create a weekly progress report issue
4. Lock resolved issues that have been inactive for 30 days
""",
agent=project_coordinator,
expected_output="Project coordination completed with progress report and issue management"
)
crew = Crew(
agents=[project_coordinator],
tasks=[coordination_task]
)
crew.kickoff()
```
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
GitHub 통합 설정 또는 문제 해결에 대해 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,356 @@
---
title: Gmail 연동
description: "CrewAI를 위한 Gmail 연동을 통한 이메일 및 연락처 관리."
icon: "envelope"
---
## 개요
에이전트가 Gmail을 통해 이메일, 연락처, 임시 저장 메시지를 관리할 수 있도록 합니다. 이메일을 보내고, 메시지를 검색하며, 연락처를 관리하고, 임시 저장 메시지를 작성하며, AI 기반 자동화를 통해 이메일 커뮤니케이션을 효율화하세요.
## 사전 준비 사항
Gmail 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 Gmail 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Gmail 계정 연결
## Gmail 연동 설정
### 1. Gmail 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **Gmail**을 찾습니다.
3. **Connect**를 클릭하고 OAuth 흐름을 완료합니다.
4. 이메일 및 연락처 관리를 위한 필요한 권한을 부여합니다.
5. [Account Settings](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="GMAIL_SEND_EMAIL">
**설명:** Gmail에서 이메일을 보냅니다.
**파라미터:**
- `toRecipients` (array, 필수): 받는 사람 - 하나의 문자열 또는 JSON 배열로 받는 사람을 지정합니다.
```json
[
"recipient1@domain.com",
"recipient2@domain.com"
]
```
- `from` (string, 필수): 보내는 사람 - 발신자의 이메일을 지정합니다.
- `subject` (string, 필수): 제목 - 메시지의 제목을 지정합니다.
- `messageContent` (string, 필수): 메시지 내용 - 이메일 메시지의 내용을 일반 텍스트 또는 HTML로 지정합니다.
- `attachments` (string, 선택): 첨부파일 - 단일 파일 객체 또는 파일 객체의 JSON 배열을 허용합니다.
- `additionalHeaders` (object, 선택): 추가 헤더 - 추가 헤더 필드를 지정할 수 있습니다.
```json
{
"reply-to": "Sender Name <sender@domain.com>"
}
```
</Accordion>
<Accordion title="GMAIL_GET_EMAIL_BY_ID">
**설명:** Gmail에서 ID로 이메일을 조회합니다.
**파라미터:**
- `userId` (string, 필수): 사용자 ID - 사용자의 이메일 주소를 지정합니다. (예: "user@domain.com").
- `messageId` (string, 필수): 메시지 ID - 조회할 메시지의 ID를 지정합니다.
</Accordion>
<Accordion title="GMAIL_SEARCH_FOR_EMAIL">
**설명:** 고급 필터를 사용하여 Gmail에서 이메일을 검색합니다.
**파라미터:**
- `emailFilterFormula` (object, 선택): 불리언 식(OR로 연결된 AND 그룹의 단일 조건)으로 된 필터.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "from",
"operator": "$stringContains",
"value": "example@domain.com"
}
]
}
]
}
```
사용 가능한 필드: `from`, `to`, `date`, `label`, `subject`, `cc`, `bcc`, `category`, `deliveredto:`, `size`, `filename`, `older_than`, `newer_than`, `list`, `is:important`, `is:unread`, `is:snoozed`, `is:starred`, `is:read`, `has:drive`, `has:document`, `has:spreadsheet`, `has:presentation`, `has:attachment`, `has:youtube`, `has:userlabels`
- `paginationParameters` (object, 선택): 페이지네이션 파라미터.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GMAIL_DELETE_EMAIL">
**설명:** Gmail에서 이메일을 삭제합니다.
**파라미터:**
- `userId` (string, 필수): 사용자 ID - 사용자의 이메일 주소를 지정합니다. (예: "user@domain.com").
- `messageId` (string, 필수): 메시지 ID - 휴지통으로 보낼 메시지의 ID를 지정합니다.
</Accordion>
<Accordion title="GMAIL_CREATE_A_CONTACT">
**설명:** Gmail에서 연락처를 생성합니다.
**파라미터:**
- `givenName` (string, 필수): 이름 - 생성할 연락처의 이름을 지정합니다. (예: "John").
- `familyName` (string, 필수): 성 - 생성할 연락처의 성을 지정합니다. (예: "Doe").
- `email` (string, 필수): 이메일 - 생성할 연락처의 이메일 주소를 지정합니다.
- `additionalFields` (object, 선택): 추가 필드 - 기타 연락처 정보를 입력할 수 있습니다.
```json
{
"addresses": [
{
"streetAddress": "1000 North St.",
"city": "Los Angeles"
}
]
}
```
</Accordion>
<Accordion title="GMAIL_GET_CONTACT_BY_RESOURCE_NAME">
**설명:** Gmail에서 리소스 이름으로 연락처를 조회합니다.
**파라미터:**
- `resourceName` (string, 필수): 리소스 이름 - 조회할 연락처의 리소스 이름을 지정합니다.
</Accordion>
<Accordion title="GMAIL_SEARCH_FOR_CONTACT">
**설명:** Gmail에서 연락처를 검색합니다.
**파라미터:**
- `searchTerm` (string, 필수): 검색어 - 이름, 닉네임, 이메일 주소, 전화번호 또는 조직 연락처 속성에서 유사하거나 정확히 일치하는 항목을 검색할 검색어를 지정합니다.
</Accordion>
<Accordion title="GMAIL_DELETE_CONTACT">
**설명:** Gmail에서 연락처를 삭제합니다.
**파라미터:**
- `resourceName` (string, 필수): 리소스 이름 - 삭제할 연락처의 리소스 이름을 지정합니다.
</Accordion>
<Accordion title="GMAIL_CREATE_DRAFT">
**설명:** Gmail에서 임시 저장 메일을 만듭니다.
**파라미터:**
- `toRecipients` (array, 선택): 받는 사람 - 하나의 문자열 또는 JSON 배열로 받는 사람을 지정합니다.
```json
[
"recipient1@domain.com",
"recipient2@domain.com"
]
```
- `from` (string, 선택): 보내는 사람 - 발신자의 이메일을 지정합니다.
- `subject` (string, 선택): 제목 - 메시지의 제목을 지정합니다.
- `messageContent` (string, 선택): 메시지 내용 - 이메일 메시지의 내용을 일반 텍스트 또는 HTML로 지정합니다.
- `attachments` (string, 선택): 첨부파일 - 단일 파일 객체 또는 파일 객체의 JSON 배열을 허용합니다.
- `additionalHeaders` (object, 선택): 추가 헤더 - 추가 헤더 필드를 지정할 수 있습니다.
```json
{
"reply-to": "Sender Name <sender@domain.com>"
}
```
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Gmail 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Gmail tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Gmail capabilities
gmail_agent = Agent(
role="Email Manager",
goal="Manage email communications and contacts efficiently",
backstory="An AI assistant specialized in email management and communication.",
tools=[enterprise_tools]
)
# Task to send a follow-up email
send_email_task = Task(
description="Send a follow-up email to john@example.com about the project update meeting",
agent=gmail_agent,
expected_output="Email sent successfully with confirmation"
)
# Run the task
crew = Crew(
agents=[gmail_agent],
tasks=[send_email_task]
)
crew.kickoff()
```
### 특정 Gmail 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Gmail tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["gmail_send_email", "gmail_search_for_email", "gmail_create_draft"]
)
email_coordinator = Agent(
role="Email Coordinator",
goal="Coordinate email communications and manage drafts",
backstory="An AI assistant that focuses on email coordination and draft management.",
tools=enterprise_tools
)
# Task to prepare and send emails
email_coordination = Task(
description="Search for emails from the marketing team, create a summary draft, and send it to stakeholders",
agent=email_coordinator,
expected_output="Summary email sent to stakeholders"
)
crew = Crew(
agents=[email_coordinator],
tasks=[email_coordination]
)
crew.kickoff()
```
### 연락처 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
contact_manager = Agent(
role="Contact Manager",
goal="Manage and organize email contacts efficiently",
backstory="An experienced contact manager who maintains organized contact databases.",
tools=[enterprise_tools]
)
# Task to manage contacts
contact_task = Task(
description="""
1. 'example.com' 도메인에서 연락처를 검색합니다.
2. 연락처 목록에 없는 최근 이메일 발신자에 대해 새 연락처를 생성합니다.
3. 최근 상호 작용 데이터를 반영하여 연락처 정보를 업데이트합니다.
""",
agent=contact_manager,
expected_output="새 연락처와 최근 상호 작용으로 연락처 데이터베이스가 업데이트됨"
)
crew = Crew(
agents=[contact_manager],
tasks=[contact_task]
)
crew.kickoff()
```
### 이메일 검색 및 분석
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
email_analyst = Agent(
role="Email Analyst",
goal="Analyze email patterns and provide insights",
backstory="An AI assistant that analyzes email data to provide actionable insights.",
tools=[enterprise_tools]
)
# Task to analyze email patterns
analysis_task = Task(
description="""
Search for all unread emails from the last 7 days,
categorize them by sender domain,
and create a summary report of communication patterns
""",
agent=email_analyst,
expected_output="Email analysis report with communication patterns and recommendations"
)
crew = Crew(
agents=[email_analyst],
tasks=[analysis_task]
)
crew.kickoff()
```
### 자동화된 이메일 워크플로우
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
workflow_manager = Agent(
role="Email Workflow Manager",
goal="Automate email workflows and responses",
backstory="An AI assistant that manages automated email workflows and responses.",
tools=[enterprise_tools]
)
# Complex task involving multiple Gmail operations
workflow_task = Task(
description="""
1. 지난 24시간 동안 제목에 'urgent'가 포함된 이메일 검색
2. 각 긴급 이메일에 대한 답장 초안 생성
3. 발신자에게 자동 확인 이메일 전송
4. 주의가 필요한 긴급 항목의 요약 보고서 작성
""",
agent=workflow_manager,
expected_output="긴급 이메일이 자동 응답 및 요약 보고서와 함께 처리됨"
)
crew = Crew(
agents=[workflow_manager],
tasks=[workflow_task]
)
crew.kickoff()
```
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Gmail 통합 설정 또는 문제 해결에 대한 지원이 필요하시다면 저희 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,391 @@
---
title: Google 캘린더 연동
description: "CrewAI를 위한 Google 캘린더 연동을 통한 이벤트 및 일정 관리."
icon: "calendar"
---
## 개요
에이전트가 Google Calendar를 통해 캘린더 이벤트, 일정, 가용 시간을 관리할 수 있도록 지원합니다. 이벤트를 생성 및 업데이트하고 참석자를 관리하며, 가용성을 확인하고 AI 기반 자동화로 일정 관리 워크플로우를 효율적으로 운영하세요.
## 필수 조건
Google Calendar 통합을 사용하기 전에 다음을 준비해야 합니다:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- Google Calendar에 접근 가능한 Google 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Google 계정을 연결 완료
## Google Calendar 연동 설정
### 1. Google 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **Google Calendar**를 찾습니다.
3. **Connect**를 클릭하고 OAuth 과정을 완료합니다.
4. 캘린더 및 연락처 접근 권한을 허용합니다.
5. [Account Settings](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="GOOGLE_CALENDAR_CREATE_EVENT">
**설명:** Google 캘린더에 이벤트를 생성합니다.
**파라미터:**
- `eventName` (string, 필수): 이벤트 이름.
- `startTime` (string, 필수): 시작 시간 - Unix 타임스탬프 또는 ISO8601 날짜 형식 허용.
- `endTime` (string, 선택): 종료 시간 - 비워두면 시작 시간 기준 1시간 후로 기본 설정됩니다.
- `calendar` (string, 선택): 캘린더 - Connect Portal Workflow Settings를 사용하여 사용자가 이벤트를 추가할 캘린더를 선택할 수 있도록 합니다. 비워두면 사용자의 기본 캘린더로 기본 설정됩니다.
- `attendees` (string, 선택): 참석자 - 이메일 주소 배열 또는 쉼표로 구분된 이메일 주소 허용.
- `eventLocation` (string, 선택): 이벤트 위치.
- `eventDescription` (string, 선택): 이벤트 설명.
- `eventId` (string, 선택): 이벤트 ID - 이 이벤트와 연결할 애플리케이션의 ID입니다. 이후 이 ID를 사용하여 이벤트를 동기화할 수 있습니다.
- `includeMeetLink` (boolean, 선택): Google Meet 링크 포함 여부? - 이 이벤트에 대해 Google Meet 컨퍼런스 링크를 자동으로 생성합니다.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_UPDATE_EVENT">
**설명:** Google 캘린더에서 기존 이벤트를 업데이트합니다.
**파라미터:**
- `eventId` (string, 필수): 이벤트 ID - 업데이트할 이벤트의 ID입니다.
- `eventName` (string, 선택): 이벤트 이름.
- `startTime` (string, 선택): 시작 시간 - Unix 타임스탬프 또는 ISO8601 날짜 형식 허용.
- `endTime` (string, 선택): 종료 시간 - 비워두면 시작 시간 기준 1시간 후로 기본 설정됩니다.
- `calendar` (string, 선택): 캘린더 - Connect Portal Workflow Settings를 사용하여 사용자가 이벤트를 추가할 캘린더를 선택할 수 있도록 합니다. 비워두면 사용자의 기본 캘린더로 기본 설정됩니다.
- `attendees` (string, 선택): 참석자 - 이메일 주소 배열 또는 쉼표로 구분된 이메일 주소 허용.
- `eventLocation` (string, 선택): 이벤트 위치.
- `eventDescription` (string, 선택): 이벤트 설명.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_LIST_EVENTS">
**설명:** Google 캘린더에서 이벤트 목록을 가져옵니다.
**파라미터:**
- `calendar` (string, 선택): 캘린더 - Connect Portal Workflow Settings를 사용하여 사용자가 이벤트를 추가할 캘린더를 선택할 수 있도록 합니다. 비워두면 사용자의 기본 캘린더로 기본 설정됩니다.
- `after` (string, 선택): 이후 - 제공된 날짜 이후에 시작하는 이벤트를 필터링합니다 (밀리초 단위의 Unix 또는 ISO 타임스탬프). (예시: "2025-04-12T10:00:00Z 또는 1712908800000").
- `before` (string, 선택): 이전 - 제공된 날짜 이전에 종료되는 이벤트를 필터링합니다 (밀리초 단위의 Unix 또는 ISO 타임스탬프). (예시: "2025-04-12T10:00:00Z 또는 1712908800000").
</Accordion>
<Accordion title="GOOGLE_CALENDAR_GET_EVENT_BY_ID">
**설명:** Google 캘린더에서 ID로 특정 이벤트를 가져옵니다.
**파라미터:**
- `eventId` (string, 필수): 이벤트 ID.
- `calendar` (string, 선택): 캘린더 - Connect Portal Workflow Settings를 사용하여 사용자가 이벤트를 추가할 캘린더를 선택할 수 있도록 합니다. 비워두면 사용자의 기본 캘린더로 기본 설정됩니다.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_DELETE_EVENT">
**설명:** Google 캘린더에서 이벤트를 삭제합니다.
**파라미터:**
- `eventId` (string, 필수): 이벤트 ID - 삭제할 캘린더 이벤트의 ID입니다.
- `calendar` (string, 선택): 캘린더 - Connect Portal Workflow Settings를 사용하여 사용자가 이벤트를 추가할 캘린더를 선택할 수 있도록 합니다. 비워두면 사용자의 기본 캘린더로 기본 설정됩니다.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_GET_CONTACTS">
**설명:** Google 캘린더에서 연락처를 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 페이지네이션 파라미터.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_SEARCH_CONTACTS">
**설명:** Google 캘린더에서 연락처를 검색합니다.
**파라미터:**
- `query` (string, 선택): 연락처를 검색할 검색 쿼리.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_LIST_DIRECTORY_PEOPLE">
**설명:** 디렉토리 구성원 목록을 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 페이지네이션 파라미터.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_SEARCH_DIRECTORY_PEOPLE">
**설명:** 디렉토리 구성원을 검색합니다.
**파라미터:**
- `query` (string, 필수): 연락처를 검색할 검색 쿼리.
- `paginationParameters` (object, 선택): 페이지네이션 파라미터.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_LIST_OTHER_CONTACTS">
**설명:** 기타 연락처 목록을 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 페이지네이션 파라미터.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_SEARCH_OTHER_CONTACTS">
**설명:** 기타 연락처를 검색합니다.
**파라미터:**
- `query` (string, 선택): 연락처를 검색할 검색 쿼리.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_GET_AVAILABILITY">
**설명:** 캘린더의 가용성 정보를 가져옵니다.
**파라미터:**
- `timeMin` (string, 필수): 기간의 시작. ISO 형식.
- `timeMax` (string, 필수): 기간의 끝. ISO 형식.
- `timeZone` (string, 선택): 응답에 사용되는 시간대. 선택 사항입니다. 기본값은 UTC입니다.
- `items` (array, 선택): 조회할 캘린더 및/또는 그룹 목록. 비워두면 사용자 기본 캘린더가 기본값입니다.
```json
[
{
"id": "calendar_id_1"
},
{
"id": "calendar_id_2"
}
]
```
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 캘린더 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Google Calendar tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Google Calendar capabilities
calendar_agent = Agent(
role="Schedule Manager",
goal="Manage calendar events and scheduling efficiently",
backstory="An AI assistant specialized in calendar management and scheduling coordination.",
tools=[enterprise_tools]
)
# Task to create a meeting
create_meeting_task = Task(
description="Create a team standup meeting for tomorrow at 9 AM with the development team",
agent=calendar_agent,
expected_output="Meeting created successfully with Google Meet link"
)
# Run the task
crew = Crew(
agents=[calendar_agent],
tasks=[create_meeting_task]
)
crew.kickoff()
```
### 특정 캘린더 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Google Calendar tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["google_calendar_create_event", "google_calendar_list_events", "google_calendar_get_availability"]
)
meeting_coordinator = Agent(
role="Meeting Coordinator",
goal="Coordinate meetings and check availability",
backstory="An AI assistant that focuses on meeting scheduling and availability management.",
tools=enterprise_tools
)
# Task to schedule a meeting with availability check
schedule_meeting = Task(
description="Check availability for next week and schedule a project review meeting with stakeholders",
agent=meeting_coordinator,
expected_output="Meeting scheduled after checking availability of all participants"
)
crew = Crew(
agents=[meeting_coordinator],
tasks=[schedule_meeting]
)
crew.kickoff()
```
### 이벤트 관리 및 업데이트
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
event_manager = Agent(
role="Event Manager",
goal="Manage and update calendar events efficiently",
backstory="An experienced event manager who handles event logistics and updates.",
tools=[enterprise_tools]
)
# Task to manage event updates
event_management = Task(
description="""
1. List all events for this week
2. Update any events that need location changes to include video conference links
3. Send calendar invitations to new team members for recurring meetings
""",
agent=event_manager,
expected_output="Weekly events updated with proper locations and new attendees added"
)
crew = Crew(
agents=[event_manager],
tasks=[event_management]
)
crew.kickoff()
```
### 연락처 및 가용성 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
availability_coordinator = Agent(
role="Availability Coordinator",
goal="Coordinate availability and manage contacts for scheduling",
backstory="An AI assistant that specializes in availability management and contact coordination.",
tools=[enterprise_tools]
)
# Task to coordinate availability
availability_task = Task(
description="""
1. 엔지니어링 부서의 연락처를 검색합니다.
2. 다음 주 금요일 오후에 모든 엔지니어의 가용성을 확인합니다.
3. 가장 먼저 가능한 2시간 슬롯에 팀 미팅을 만듭니다.
4. Google Meet 링크를 포함하고 초대장을 발송합니다.
""",
agent=availability_coordinator,
expected_output="가용성에 따라 팀 미팅이 일정 예약되고 모든 엔지니어가 초대됨"
)
crew = Crew(
agents=[availability_coordinator],
tasks=[availability_task]
)
crew.kickoff()
```
### 자동화된 일정 관리 워크플로우
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
scheduling_automator = Agent(
role="Scheduling Automator",
goal="Automate scheduling workflows and calendar management",
backstory="An AI assistant that automates complex scheduling scenarios and calendar workflows.",
tools=[enterprise_tools]
)
# Complex scheduling automation task
automation_task = Task(
description="""
1. 앞으로 2주간 예정된 모든 이벤트를 나열합니다.
2. 일정 충돌 또는 연이어 배정된 미팅을 식별합니다.
3. 가용 시간을 확인하여 최적의 미팅 시간을 제안합니다.
4. 필요한 경우 미팅 사이에 버퍼 시간을 생성합니다.
5. 아젠다 항목 및 미팅 링크가 포함된 이벤트 설명을 업데이트합니다.
""",
agent=scheduling_automator,
expected_output="일정 충돌이 해결되고 버퍼 타임 및 미팅 세부 정보가 업데이트된 최적화된 캘린더"
)
crew = Crew(
agents=[scheduling_automator],
tasks=[automation_task]
)
crew.kickoff()
```
## 문제 해결
### 일반적인 문제
**인증 오류**
- Google 계정에 캘린더 접근에 필요한 권한이 있는지 확인하세요
- OAuth 연결에 Google Calendar API에 필요한 모든 범위가 포함되어 있는지 확인하세요
- 캘린더 공유 설정이 필요한 접근 수준을 허용하는지 확인하세요
**이벤트 생성 문제**
- 시간 형식이 올바른지(ISO8601 또는 Unix 타임스탬프) 확인하세요
- 참석자 이메일 주소가 올바르게 형식화되어 있는지 확인하세요
- 대상 캘린더가 존재하며 접근 가능한지 확인하세요
- 올바른 시간대가 지정되어 있는지 확인하세요
**가용성 및 시간 충돌**
- 가용성 확인 시 시간 범위에 올바른 ISO 형식을 사용하세요
- 모든 작업에서 시간대가 일관성 있는지 확인하세요
- 여러 캘린더를 확인할 때 캘린더 ID가 올바른지 확인하세요
**연락처 및 사용자 검색**
- 검색 쿼리가 올바르게 형식화되어 있는지 확인하세요
- 디렉터리 접근 권한이 부여되었는지 확인하세요
- 연락처 정보가 최신이며 접근 가능한지 확인하세요
**이벤트 업데이트 및 삭제**
- 이벤트 ID가 올바르며 이벤트가 존재하는지 확인하세요
- 이벤트를 편집할 수 있는 권한이 있는지 확인하세요
- 캘린더 소유권이 수정 작업을 허용하는지 확인하세요
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Google Calendar 연동 설정 또는 문제 해결에 대한 지원이 필요하면 저희 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,321 @@
---
title: Google Sheets 연동
description: "CrewAI를 위한 Google Sheets 연동을 통해 스프레드시트 데이터 동기화."
icon: "google"
---
## 개요
에이전트가 Google Sheets를 통해 스프레드시트 데이터를 관리할 수 있도록 합니다. 행을 읽고, 새 항목을 생성하며, 기존 데이터를 업데이트하고, AI 기반 자동화를 통해 데이터 관리 워크플로우를 간소화하세요. 데이터 추적, 보고, 협업 데이터 관리에 최적화되어 있습니다.
## 사전 준비 사항
Google Sheets 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 되어 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- Google Sheets에 액세스할 수 있는 Google 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Google 계정 연결
- 데이터 작업을 위한 올바른 열 헤더가 있는 스프레드시트
## Google Sheets 통합 설정
### 1. Google 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **Google Sheets**를 찾습니다.
3. **Connect**를 클릭하고 OAuth 흐름을 완료합니다.
4. 스프레드시트 접근에 필요한 권한을 허용합니다.
5. [Account Settings](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="GOOGLE_SHEETS_GET_ROW">
**설명:** Google Sheets 스프레드시트에서 행을 가져옵니다.
**매개변수:**
- `spreadsheetId` (string, 필수): 스프레드시트 - Connect Portal Workflow Settings를 사용하여 사용자가 스프레드시트를 선택할 수 있도록 합니다. 선택한 스프레드시트의 첫 번째 워크시트를 기본값으로 사용합니다.
- `limit` (string, 선택): 행 제한 - 반환할 최대 행 수를 제한합니다.
</Accordion>
<Accordion title="GOOGLE_SHEETS_CREATE_ROW">
**설명:** Google Sheets 스프레드시트에 새로운 행을 만듭니다.
**매개변수:**
- `spreadsheetId` (string, 필수): 스프레드시트 - Connect Portal Workflow Settings를 사용하여 사용자가 스프레드시트를 선택할 수 있도록 합니다. 선택한 스프레드시트의 첫 번째 워크시트를 기본값으로 사용합니다.
- `worksheet` (string, 필수): 워크시트 - 워크시트에는 반드시 열 헤더가 있어야 합니다.
- `additionalFields` (object, 필수): 필드 - 추가할 행의 필드를 열 이름을 key로 하는 객체로 포함합니다. Connect Portal Workflow Settings를 사용하여 사용자가 열 매핑을 선택할 수 있도록 합니다.
```json
{
"columnName1": "columnValue1",
"columnName2": "columnValue2",
"columnName3": "columnValue3",
"columnName4": "columnValue4"
}
```
</Accordion>
<Accordion title="GOOGLE_SHEETS_UPDATE_ROW">
**설명:** Google Sheets 스프레드시트의 기존 행을 업데이트합니다.
**매개변수:**
- `spreadsheetId` (string, 필수): 스프레드시트 - Connect Portal Workflow Settings를 사용하여 사용자가 스프레드시트를 선택할 수 있도록 합니다. 선택한 스프레드시트의 첫 번째 워크시트를 기본값으로 사용합니다.
- `worksheet` (string, 필수): 워크시트 - 워크시트에는 반드시 열 헤더가 있어야 합니다.
- `filterFormula` (object, 선택): 필터 - 업데이트할 행을 식별하기 위한 단일 조건의 AND 그룹으로 이루어진 OR의 형태(분리 정규형)로 작성합니다.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "status",
"operator": "$stringExactlyMatches",
"value": "pending"
}
]
}
]
}
```
사용 가능한 연산자: `$stringContains`, `$stringDoesNotContain`, `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringStartsWith`, `$stringDoesNotStartWith`, `$stringEndsWith`, `$stringDoesNotEndWith`, `$numberGreaterThan`, `$numberLessThan`, `$numberEquals`, `$numberDoesNotEqual`, `$dateTimeAfter`, `$dateTimeBefore`, `$dateTimeEquals`, `$booleanTrue`, `$booleanFalse`, `$exists`, `$doesNotExist`
- `additionalFields` (object, 필수): 필드 - 업데이트할 필드를 열 이름을 key로 하는 객체로 포함합니다. Connect Portal Workflow Settings를 사용하여 사용자가 열 매핑을 선택할 수 있도록 합니다.
```json
{
"columnName1": "newValue1",
"columnName2": "newValue2",
"columnName3": "newValue3",
"columnName4": "newValue4"
}
```
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Google Sheets 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Google Sheets tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Google Sheets capabilities
sheets_agent = Agent(
role="Data Manager",
goal="Manage spreadsheet data and track information efficiently",
backstory="An AI assistant specialized in data management and spreadsheet operations.",
tools=[enterprise_tools]
)
# Task to add new data to a spreadsheet
data_entry_task = Task(
description="Add a new customer record to the customer database spreadsheet with name, email, and signup date",
agent=sheets_agent,
expected_output="New customer record added successfully to the spreadsheet"
)
# Run the task
crew = Crew(
agents=[sheets_agent],
tasks=[data_entry_task]
)
crew.kickoff()
```
### 특정 Google Sheets 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Google Sheets tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["google_sheets_get_row", "google_sheets_create_row"]
)
data_collector = Agent(
role="Data Collector",
goal="Collect and organize data in spreadsheets",
backstory="An AI assistant that focuses on data collection and organization.",
tools=enterprise_tools
)
# Task to collect and organize data
data_collection = Task(
description="Retrieve current inventory data and add new product entries to the inventory spreadsheet",
agent=data_collector,
expected_output="Inventory data retrieved and new products added successfully"
)
crew = Crew(
agents=[data_collector],
tasks=[data_collection]
)
crew.kickoff()
```
### 데이터 분석 및 보고
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
data_analyst = Agent(
role="Data Analyst",
goal="Analyze spreadsheet data and generate insights",
backstory="An experienced data analyst who extracts insights from spreadsheet data.",
tools=[enterprise_tools]
)
# Task to analyze data and create reports
analysis_task = Task(
description="""
1. Retrieve all sales data from the current month's spreadsheet
2. Analyze the data for trends and patterns
3. Create a summary report in a new row with key metrics
""",
agent=data_analyst,
expected_output="Sales data analyzed and summary report created with key insights"
)
crew = Crew(
agents=[data_analyst],
tasks=[analysis_task]
)
crew.kickoff()
```
### 자동화된 데이터 업데이트
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
data_updater = Agent(
role="Data Updater",
goal="Automatically update and maintain spreadsheet data",
backstory="An AI assistant that maintains data accuracy and updates records automatically.",
tools=[enterprise_tools]
)
# Task to update data based on conditions
update_task = Task(
description="""
1. 주문 스프레드시트에서 모든 보류 중인 주문을 찾으세요
2. 해당 주문의 상태를 'processing'으로 업데이트하세요
3. 상태가 업데이트된 시점의 타임스탬프를 추가하세요
4. 변경 사항을 별도의 추적 시트에 기록하세요
""",
agent=data_updater,
expected_output="모든 보류 중인 주문이 processing 상태로 업데이트되고, 타임스탬프가 기록됨"
)
crew = Crew(
agents=[data_updater],
tasks=[update_task]
)
crew.kickoff()
```
### 복잡한 데이터 관리 워크플로우
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
workflow_manager = Agent(
role="Data Workflow Manager",
goal="Manage complex data workflows across multiple spreadsheets",
backstory="An AI assistant that orchestrates complex data operations across multiple spreadsheets.",
tools=[enterprise_tools]
)
# Complex workflow task
workflow_task = Task(
description="""
1. 메인 고객 스프레드시트에서 모든 고객 데이터를 가져옵니다
2. 활성 고객에 대한 월별 요약 항목을 생성합니다
3. 최근 30일간의 활동을 기반으로 고객 상태를 업데이트합니다
4. 고객 지표가 포함된 월간 보고서를 생성합니다
5. 비활성 고객 기록을 별도의 시트로 보관합니다
""",
agent=workflow_manager,
expected_output="월간 고객 워크플로우가 완료되어 상태가 업데이트되고 보고서가 생성됨"
)
crew = Crew(
agents=[workflow_manager],
tasks=[workflow_task]
)
crew.kickoff()
```
## 문제 해결
### 일반적인 문제
**권한 오류**
- Google 계정이 대상 스프레드시트에 대해 편집 권한이 있는지 확인하세요
- OAuth 연결에 Google Sheets API에 필요한 scope가 포함되어 있는지 검증하세요
- 스프레드시트가 인증된 계정과 공유되어 있는지 확인하세요
**스프레드시트 구조 문제**
- 행을 생성하거나 업데이트하기 전에 워크시트에 올바른 열 헤더가 있는지 확인하세요
- `additionalFields`의 열 이름이 실제 열 헤더와 일치하는지 검증하세요
- 지정된 워크시트가 스프레드시트에 존재하는지 확인하세요
**데이터 유형 및 형식 문제**
- 데이터 값이 각 열에 대해 예상되는 형식과 일치하는지 확인하세요
- 날짜 열에는 올바른 날짜 형식(ISO 형식 권장)을 사용하세요
- 숫자 열에 입력되는 값이 적절한 형식인지 검증하세요
**필터 수식 문제**
- 필터 수식이 부정 정규형(disjunctive normal form)의 올바른 JSON 구조를 따르는지 확인하세요
- 실제 열 헤더와 일치하는 유효한 필드명을 사용하세요
- 복잡한 다중 조건 쿼리를 작성하기 전에 간단한 필터로 테스트하세요
- 연산자 유형이 열의 데이터 유형과 일치하는지 검증하세요
**행 제한 및 성능**
- `GOOGLE_SHEETS_GET_ROW`를 사용할 때 행 제한에 유의하세요
- 대용량 데이터셋의 경우 페이지네이션을 고려하세요
- 처리되는 데이터의 양을 줄이기 위해 구체적인 필터를 사용하세요
**업데이트 작업**
- 필터 조건이 업데이트하려는 행을 정확하게 식별하는지 확인하세요
- 대규모 업데이트 전에 작은 데이터셋으로 필터 조건을 테스트하세요
- 모든 필수 필드가 업데이트 작업에 포함되어 있는지 검증하세요
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Google Sheets 통합 설정 또는 문제 해결에 대한 지원이 필요하시면 저희 지원팀으로 문의해 주세요.
</Card>

View File

@@ -0,0 +1,579 @@
---
title: "HubSpot 연동"
description: "CrewAI로 HubSpot에서 회사 및 연락처를 관리하세요."
icon: "briefcase"
---
## 개요
에이전트가 HubSpot 내에서 회사 및 연락처를 관리할 수 있도록 지원합니다. 새로운 레코드를 생성하고 AI 기반 자동화로 CRM 프로세스를 효율화하세요.
## 사전 준비 사항
HubSpot 통합을 사용하기 전에 다음을 확인하세요.
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 HubSpot 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 HubSpot 계정이 연결되어 있음
## HubSpot 통합 설정
### 1. HubSpot 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합 섹션에서 **HubSpot**을 찾습니다.
3. **Connect**를 클릭하고 OAuth 플로우를 완료합니다.
4. 회사 및 연락처 관리를 위한 필요한 권한을 부여합니다.
5. [계정 설정](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 액션
<AccordionGroup>
<Accordion title="HUBSPOT_CREATE_RECORD_COMPANIES">
**설명:** HubSpot에서 새로운 회사 레코드를 생성합니다.
**파라미터:**
- `name` (string, 필수): 회사명.
- `domain` (string, 선택): 회사 도메인명.
- `industry` (string, 선택): 산업군. HubSpot에서 미리 정의된 값 중 하나여야 합니다.
- `phone` (string, 선택): 전화번호.
- `hubspot_owner_id` (string, 선택): 회사 소유자 ID.
- `type` (string, 선택): 회사 유형. 사용 가능한 값: `PROSPECT`, `PARTNER`, `RESELLER`, `VENDOR`, `OTHER`.
- `city` (string, 선택): 도시.
- `state` (string, 선택): 주/지역.
- `zip` (string, 선택): 우편번호.
- `numberofemployees` (number, 선택): 직원 수.
- `annualrevenue` (number, 선택): 연간 매출.
- `timezone` (string, 선택): 시간대.
- `description` (string, 선택): 설명.
- `linkedin_company_page` (string, 선택): LinkedIn 회사 페이지 URL.
- `company_email` (string, 선택): 회사 이메일.
- `first_name` (string, 선택): 회사 연락처의 이름.
- `last_name` (string, 선택): 회사 연락처의 성.
- `about_us` (string, 선택): 회사 소개.
- `hs_csm_sentiment` (string, 선택): CSM 만족도. 사용 가능한 값: `at_risk`, `neutral`, `healthy`.
- `closedate` (string, 선택): 마감일.
- `hs_keywords` (string, 선택): 회사 키워드. 미리 정의된 값 중 하나여야 합니다.
- `country` (string, 선택): 국가/지역.
- `hs_country_code` (string, 선택): 국가/지역 코드.
- `hs_employee_range` (string, 선택): 직원 범위.
- `facebook_company_page` (string, 선택): Facebook 회사 페이지 URL.
- `facebookfans` (number, 선택): Facebook 팬 수.
- `hs_gps_coordinates` (string, 선택): GPS 좌표.
- `hs_gps_error` (string, 선택): GPS 오류.
- `googleplus_page` (string, 선택): Google Plus 페이지 URL.
- `owneremail` (string, 선택): HubSpot 소유자 이메일.
- `ownername` (string, 선택): HubSpot 소유자 이름.
- `hs_ideal_customer_profile` (string, 선택): 이상적인 고객 프로필 티어. 사용 가능한 값: `tier_1`, `tier_2`, `tier_3`.
- `hs_industry_group` (string, 선택): 산업 그룹.
- `is_public` (boolean, 선택): 공개 여부.
- `hs_last_metered_enrichment_timestamp` (string, 선택): 마지막 enrichment 타임스탬프.
- `hs_lead_status` (string, 선택): 리드 상태. 사용 가능한 값: `NEW`, `OPEN`, `IN_PROGRESS`, `OPEN_DEAL`, `UNQUALIFIED`, `ATTEMPTED_TO_CONTACT`, `CONNECTED`, `BAD_TIMING`.
- `lifecyclestage` (string, 선택): 라이프사이클 단계. 사용 가능한 값: `subscriber`, `lead`, `marketingqualifiedlead`, `salesqualifiedlead`, `opportunity`, `customer`, `evangelist`, `other`.
- `linkedinbio` (string, 선택): LinkedIn 바이오.
- `hs_linkedin_handle` (string, 선택): LinkedIn 핸들.
- `hs_live_enrichment_deadline` (string, 선택): 라이브 enrichment 기한.
- `hs_logo_url` (string, 선택): 로고 URL.
- `hs_analytics_source` (string, 선택): 원래 유입 경로.
- `hs_pinned_engagement_id` (number, 선택): 고정된 참여 ID.
- `hs_quick_context` (string, 선택): 간략한 컨텍스트.
- `hs_revenue_range` (string, 선택): 매출 범위.
- `hs_state_code` (string, 선택): 주/지역 코드.
- `address` (string, 선택): 거리 주소.
- `address2` (string, 선택): 거리 주소 2.
- `hs_is_target_account` (boolean, 선택): 타깃 계정 여부.
- `hs_target_account` (string, 선택): 타깃 계정 티어. 사용 가능한 값: `tier_1`, `tier_2`, `tier_3`.
- `hs_target_account_recommendation_snooze_time` (string, 선택): 타깃 계정 추천 일시중지 시간.
- `hs_target_account_recommendation_state` (string, 선택): 타깃 계정 추천 상태. 사용 가능한 값: `DISMISSED`, `NONE`, `SNOOZED`.
- `total_money_raised` (string, 선택): 총 조달 금액.
- `twitterbio` (string, 선택): 트위터 바이오.
- `twitterfollowers` (number, 선택): 트위터 팔로워 수.
- `twitterhandle` (string, 선택): 트위터 핸들.
- `web_technologies` (string, 선택): 사용한 웹 기술. 미리 정의된 값 중 하나여야 합니다.
- `website` (string, 선택): 웹사이트 URL.
- `founded_year` (string, 선택): 설립 연도.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_CONTACTS">
**설명:** HubSpot에서 새로운 연락처 레코드를 생성합니다.
**파라미터:**
- `email` (string, 필수): 연락처 이메일 주소.
- `firstname` (string, 선택): 이름.
- `lastname` (string, 선택): 성.
- `phone` (string, 선택): 전화번호.
- `hubspot_owner_id` (string, 선택): 연락처 소유자.
- `lifecyclestage` (string, 선택): 라이프사이클 단계. 사용 가능한 값: `subscriber`, `lead`, `marketingqualifiedlead`, `salesqualifiedlead`, `opportunity`, `customer`, `evangelist`, `other`.
- `hs_lead_status` (string, 선택): 리드 상태. 사용 가능한 값: `NEW`, `OPEN`, `IN_PROGRESS`, `OPEN_DEAL`, `UNQUALIFIED`, `ATTEMPTED_TO_CONTACT`, `CONNECTED`, `BAD_TIMING`.
- `annualrevenue` (string, 선택): 연간 매출.
- `hs_buying_role` (string, 선택): 구매 역할.
- `cc_emails` (string, 선택): 참조(CC) 이메일.
- `ch_customer_id` (string, 선택): Chargify 고객 ID.
- `ch_customer_reference` (string, 선택): Chargify 고객 참조.
- `chargify_sites` (string, 선택): Chargify 사이트(들).
- `city` (string, 선택): 도시.
- `hs_facebook_ad_clicked` (boolean, 선택): Facebook 광고 클릭 여부.
- `hs_linkedin_ad_clicked` (string, 선택): LinkedIn 광고 클릭 여부.
- `hs_clicked_linkedin_ad` (string, 선택): LinkedIn 광고 클릭 여부.
- `closedate` (string, 선택): 마감일.
- `company` (string, 선택): 회사명.
- `company_size` (string, 선택): 회사 규모.
- `country` (string, 선택): 국가/지역.
- `hs_country_region_code` (string, 선택): 국가/지역 코드.
- `date_of_birth` (string, 선택): 생년월일.
- `degree` (string, 선택): 학위.
- `hs_email_customer_quarantined_reason` (string, 선택): 이메일 주소 격리 사유.
- `hs_role` (string, 선택): 고용 역할. 미리 정의된 값 중 하나여야 합니다.
- `hs_seniority` (string, 선택): 고용 직급. 미리 정의된 값 중 하나여야 합니다.
- `hs_sub_role` (string, 선택): 고용 하위 역할. 미리 정의된 값 중 하나여야 합니다.
- `hs_employment_change_detected_date` (string, 선택): 고용 변경 감지 날짜.
- `hs_enriched_email_bounce_detected` (boolean, 선택): 향상된 이메일 바운스 감지됨.
- `hs_facebookid` (string, 선택): Facebook ID.
- `hs_facebook_click_id` (string, 선택): Facebook 클릭 ID.
- `fax` (string, 선택): 팩스번호.
- `field_of_study` (string, 선택): 전공.
- `followercount` (number, 선택): 팔로워 수.
- `gender` (string, 선택): 성별.
- `hs_google_click_id` (string, 선택): Google 광고 클릭 ID.
- `graduation_date` (string, 선택): 졸업 날짜.
- `owneremail` (string, 선택): HubSpot 소유자 이메일(레거시).
- `ownername` (string, 선택): HubSpot 소유자 이름(레거시).
- `industry` (string, 선택): 산업군.
- `hs_inferred_language_codes` (string, 선택): 추정 언어 코드. 미리 정의된 값 중 하나여야 합니다.
- `jobtitle` (string, 선택): 직책.
- `hs_job_change_detected_date` (string, 선택): 직장 변경 감지 날짜.
- `job_function` (string, 선택): 직무.
- `hs_journey_stage` (string, 선택): 여정 단계. 미리 정의된 값 중 하나여야 합니다.
- `kloutscoregeneral` (number, 선택): Klout 점수.
- `hs_last_metered_enrichment_timestamp` (string, 선택): 마지막 enrichment 타임스탬프.
- `hs_latest_source` (string, 선택): 최신 유입 경로.
- `hs_latest_source_timestamp` (string, 선택): 최신 유입 경로 날짜.
- `hs_legal_basis` (string, 선택): 연락처 데이터 처리를 위한 법적 근거.
- `linkedinbio` (string, 선택): LinkedIn 바이오.
- `linkedinconnections` (number, 선택): LinkedIn 연결 수.
- `hs_linkedin_url` (string, 선택): LinkedIn URL.
- `hs_linkedinid` (string, 선택): LinkedIn ID.
- `hs_live_enrichment_deadline` (string, 선택): 라이브 enrichment 기한.
- `marital_status` (string, 선택): 결혼 상태.
- `hs_content_membership_email` (string, 선택): 멤버 이메일.
- `hs_content_membership_notes` (string, 선택): 멤버십 노트.
- `message` (string, 선택): 메시지.
- `military_status` (string, 선택): 군복무 상태.
- `mobilephone` (string, 선택): 휴대전화 번호.
- `numemployees` (string, 선택): 직원 수.
- `hs_analytics_source` (string, 선택): 원래 유입 경로.
- `photo` (string, 선택): 사진.
- `hs_pinned_engagement_id` (number, 선택): 고정된 참여 ID.
- `zip` (string, 선택): 우편번호.
- `hs_language` (string, 선택): 선호 언어. 미리 정의된 값 중 하나여야 합니다.
- `associatedcompanyid` (number, 선택): 기본 연결된 회사 ID.
- `hs_email_optout_survey_reason` (string, 선택): 이메일 수신 거부 사유.
- `relationship_status` (string, 선택): 관계 상태.
- `hs_returning_to_office_detected_date` (string, 선택): 사무실 복귀 감지 날짜.
- `salutation` (string, 선택): 호칭.
- `school` (string, 선택): 학교.
- `seniority` (string, 선택): 직급.
- `hs_feedback_show_nps_web_survey` (boolean, 선택): NPS 웹 설문조사를 표시할지 여부.
- `start_date` (string, 선택): 시작일.
- `state` (string, 선택): 주/지역.
- `hs_state_code` (string, 선택): 주/지역 코드.
- `hs_content_membership_status` (string, 선택): 상태.
- `address` (string, 선택): 거리 주소.
- `tax_exempt` (string, 선택): 세금 면제.
- `hs_timezone` (string, 선택): 시간대. 미리 정의된 값 중 하나여야 합니다.
- `twitterbio` (string, 선택): 트위터 바이오.
- `hs_twitterid` (string, 선택): 트위터 ID.
- `twitterprofilephoto` (string, 선택): 트위터 프로필 사진.
- `twitterhandle` (string, 선택): 트위터 사용자명.
- `vat_number` (string, 선택): 부가가치세 번호.
- `ch_verified` (string, 선택): ACH/eCheck 결제 인증됨.
- `website` (string, 선택): 웹사이트 URL.
- `hs_whatsapp_phone_number` (string, 선택): WhatsApp 전화번호.
- `work_email` (string, 선택): 업무용 이메일.
- `hs_googleplusid` (string, 선택): googleplus ID.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_DEALS">
**설명:** HubSpot에서 새로운 거래(deal) 레코드를 생성합니다.
**파라미터:**
- `dealname` (string, 필수): 거래 이름.
- `amount` (number, 선택): 거래 금액.
- `dealstage` (string, 선택): 거래의 파이프라인 단계.
- `pipeline` (string, 선택): 거래가 속한 파이프라인.
- `closedate` (string, 선택): 예상 마감일.
- `hubspot_owner_id` (string, 선택): 거래 소유자.
- `dealtype` (string, 선택): 거래 유형. 사용 가능한 값: `newbusiness`, `existingbusiness`.
- `description` (string, 선택): 거래 설명.
- `hs_priority` (string, 선택): 거래 우선순위. 사용 가능한 값: `low`, `medium`, `high`.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_ENGAGEMENTS">
**설명:** HubSpot에서 새로운 참여(예: 노트, 이메일, 통화, 미팅, 작업)를 생성합니다.
**파라미터:**
- `engagementType` (string, 필수): 참여 유형. 사용 가능한 값: `NOTE`, `EMAIL`, `CALL`, `MEETING`, `TASK`.
- `hubspot_owner_id` (string, 선택): 이 활동이 할당된 사용자.
- `hs_timestamp` (string, 선택): 활동 날짜 및 시간.
- `hs_note_body` (string, 선택): 노트 본문. (`NOTE`에서 사용)
- `hs_task_subject` (string, 선택): 작업 제목. (`TASK`에서 사용)
- `hs_task_body` (string, 선택): 작업 노트. (`TASK`에서 사용)
- `hs_task_status` (string, 선택): 작업 상태. (`TASK`에서 사용)
- `hs_meeting_title` (string, 선택): 미팅 제목. (`MEETING`에서 사용)
- `hs_meeting_body` (string, 선택): 미팅 설명. (`MEETING`에서 사용)
- `hs_meeting_start_time` (string, 선택): 미팅 시작 시간. (`MEETING`에서 사용)
- `hs_meeting_end_time` (string, 선택): 미팅 종료 시간. (`MEETING`에서 사용)
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_COMPANIES">
**설명:** HubSpot에서 기존 회사 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 회사의 ID.
- `name` (string, 선택): 회사명.
- `domain` (string, 선택): 회사 도메인명.
- `industry` (string, 선택): 산업군.
- `phone` (string, 선택): 전화번호.
- `city` (string, 선택): 도시.
- `state` (string, 선택): 주/지역.
- `zip` (string, 선택): 우편번호.
- `numberofemployees` (number, 선택): 직원 수.
- `annualrevenue` (number, 선택): 연간 매출.
- `description` (string, 선택): 설명.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_ANY">
**설명:** HubSpot에서 지정된 오브젝트 타입의 레코드를 생성합니다.
**파라미터:**
- `recordType` (string, 필수): 커스텀 오브젝트의 오브젝트 타입 ID.
- 추가 파라미터는 커스텀 오브젝트의 스키마에 따라 다릅니다.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_CONTACTS">
**설명:** HubSpot에서 기존 연락처 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 연락처의 ID.
- `firstname` (string, 선택): 이름.
- `lastname` (string, 선택): 성.
- `email` (string, 선택): 이메일 주소.
- `phone` (string, 선택): 전화번호.
- `company` (string, 선택): 회사명.
- `jobtitle` (string, 선택): 직책.
- `lifecyclestage` (string, 선택): 라이프사이클 단계.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_DEALS">
**설명:** HubSpot에서 기존 거래 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 거래의 ID.
- `dealname` (string, 선택): 거래 이름.
- `amount` (number, 선택): 거래 금액.
- `dealstage` (string, 선택): 거래의 파이프라인 단계.
- `pipeline` (string, 선택): 거래가 속한 파이프라인.
- `closedate` (string, 선택): 예상 마감일.
- `dealtype` (string, 선택): 거래 유형.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_ENGAGEMENTS">
**설명:** HubSpot에서 기존 참여(engagement)를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 참여의 ID.
- `hs_note_body` (string, 선택): 노트 본문.
- `hs_task_subject` (string, 선택): 작업 제목.
- `hs_task_body` (string, 선택): 작업 노트.
- `hs_task_status` (string, 선택): 작업 상태.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_ANY">
**설명:** HubSpot에서 지정된 오브젝트 타입의 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 레코드의 ID.
- `recordType` (string, 필수): 커스텀 오브젝트의 오브젝트 타입 ID.
- 추가 파라미터는 커스텀 오브젝트의 스키마에 따라 다릅니다.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_COMPANIES">
**설명:** HubSpot에서 회사 레코드 목록을 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_CONTACTS">
**설명:** HubSpot에서 연락처 레코드 목록을 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_DEALS">
**설명:** HubSpot에서 거래 레코드 목록을 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_ENGAGEMENTS">
**설명:** HubSpot에서 참여(engagement) 레코드 목록을 가져옵니다.
**파라미터:**
- `objectName` (string, 필수): 가져올 참여 유형(예: "notes").
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_ANY">
**설명:** HubSpot에서 지정된 오브젝트 타입의 레코드 목록을 가져옵니다.
**파라미터:**
- `recordType` (string, 필수): 커스텀 오브젝트의 오브젝트 타입 ID.
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_COMPANIES">
**설명:** ID로 단일 회사 레코드를 가져옵니다.
**파라미터:**
- `recordId` (string, 필수): 가져올 회사의 ID.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_CONTACTS">
**설명:** ID로 단일 연락처 레코드를 가져옵니다.
**파라미터:**
- `recordId` (string, 필수): 가져올 연락처의 ID.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_DEALS">
**설명:** ID로 단일 거래 레코드를 가져옵니다.
**파라미터:**
- `recordId` (string, 필수): 가져올 거래의 ID.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_ENGAGEMENTS">
**설명:** ID로 단일 참여(engagement) 레코드를 가져옵니다.
**파라미터:**
- `recordId` (string, 필수): 가져올 참여의 ID.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_ANY">
**설명:** 지정된 오브젝트 타입의 단일 레코드를 ID로 가져옵니다.
**파라미터:**
- `recordType` (string, 필수): 커스텀 오브젝트의 오브젝트 타입 ID.
- `recordId` (string, 필수): 가져올 레코드의 ID.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_COMPANIES">
**설명:** 필터 수식을 사용해 HubSpot에서 회사 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 분리 정규형(OR of ANDs) 필터.
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_CONTACTS">
**설명:** 필터 수식을 사용해 HubSpot에서 연락처 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 분리 정규형(OR of ANDs) 필터.
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_DEALS">
**설명:** 필터 수식을 사용해 HubSpot에서 거래 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 분리 정규형(OR of ANDs) 필터.
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_ENGAGEMENTS">
**설명:** 필터 수식을 사용해 HubSpot에서 참여(engagement) 레코드를 검색합니다.
**파라미터:**
- `engagementFilterFormula` (object, 선택): 참여 필터.
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_ANY">
**설명:** HubSpot에서 지정된 오브젝트 타입의 레코드를 검색합니다.
**파라미터:**
- `recordType` (string, 필수): 검색할 오브젝트 타입 ID.
- `filterFormula` (string, 선택): 적용할 필터 수식.
- `paginationParameters` (object, 선택): 다음 페이지를 가져오려면 `pageCursor`를 사용하세요.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_COMPANIES">
**설명:** ID로 회사 레코드를 삭제합니다.
**파라미터:**
- `recordId` (string, 필수): 삭제할 회사의 ID.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_CONTACTS">
**설명:** ID로 연락처 레코드를 삭제합니다.
**파라미터:**
- `recordId` (string, 필수): 삭제할 연락처의 ID.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_DEALS">
**설명:** ID로 거래 레코드를 삭제합니다.
**파라미터:**
- `recordId` (string, 필수): 삭제할 거래의 ID.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_ENGAGEMENTS">
**설명:** ID로 참여(engagement) 레코드를 삭제합니다.
**파라미터:**
- `recordId` (string, 필수): 삭제할 참여의 ID.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_ANY">
**설명:** 지정된 오브젝트 타입의 레코드를 ID로 삭제합니다.
**파라미터:**
- `recordType` (string, 필수): 커스텀 오브젝트의 오브젝트 타입 ID.
- `recordId` (string, 필수): 삭제할 레코드의 ID.
</Accordion>
<Accordion title="HUBSPOT_GET_CONTACTS_BY_LIST_ID">
**설명:** 지정된 리스트 ID로부터 연락처 목록을 가져옵니다.
**파라미터:**
- `listId` (string, 필수): 연락처를 가져올 리스트의 ID.
- `paginationParameters` (object, 선택): 이후 페이지를 위해 `pageCursor` 사용.
</Accordion>
<Accordion title="HUBSPOT_DESCRIBE_ACTION_SCHEMA">
**설명:** 특정 오브젝트 타입 및 작업에 대한 예상 스키마를 가져옵니다.
**파라미터:**
- `recordType` (string, 필수): 오브젝트 타입 ID(예: 'companies').
- `operation` (string, 필수): 작업 유형(예: 'CREATE_RECORD').
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 HubSpot 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (HubSpot tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with HubSpot capabilities
hubspot_agent = Agent(
role="CRM Manager",
goal="Manage company and contact records in HubSpot",
backstory="An AI assistant specialized in CRM management.",
tools=[enterprise_tools]
)
# Task to create a new company
create_company_task = Task(
description="Create a new company in HubSpot with name 'Innovate Corp' and domain 'innovatecorp.com'.",
agent=hubspot_agent,
expected_output="Company created successfully with confirmation"
)
# Run the task
crew = Crew(
agents=[hubspot_agent],
tasks=[create_company_task]
)
crew.kickoff()
```
### 특정 HubSpot 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only the tool to create contacts
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["hubspot_create_record_contacts"]
)
contact_creator = Agent(
role="Contact Creator",
goal="Create new contacts in HubSpot",
backstory="An AI assistant that focuses on creating new contact entries in the CRM.",
tools=[enterprise_tools]
)
# Task to create a contact
create_contact = Task(
description="Create a new contact for 'John Doe' with email 'john.doe@example.com'.",
agent=contact_creator,
expected_output="Contact created successfully in HubSpot."
)
crew = Crew(
agents=[contact_creator],
tasks=[create_contact]
)
crew.kickoff()
```
### 연락처 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
crm_manager = Agent(
role="CRM Manager",
goal="Manage and organize HubSpot contacts efficiently.",
backstory="An experienced CRM manager who maintains an organized contact database.",
tools=[enterprise_tools]
)
# Task to manage contacts
contact_task = Task(
description="Create a new contact for 'Jane Smith' at 'Global Tech Inc.' with email 'jane.smith@globaltech.com'.",
agent=crm_manager,
expected_output="Contact database updated with the new contact."
)
crew = Crew(
agents=[crm_manager],
tasks=[contact_task]
)
crew.kickoff()
```
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
HubSpot 연동 설정 또는 문제 해결에 도움이 필요하시면 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,394 @@
---
title: Jira 연동
description: "CrewAI를 위한 Jira 연동을 통한 이슈 추적 및 프로젝트 관리."
icon: "bug"
---
## 개요
에이전트가 Jira를 통해 이슈, 프로젝트, 워크플로우를 관리할 수 있도록 합니다. 이슈를 생성 및 업데이트하고, 프로젝트 진행 상황을 추적하며, 할당 작업을 관리하고, AI 기반 자동화로 프로젝트 관리를 효율화하세요.
## 사전 준비 사항
Jira 통합을 사용하기 전에 다음을 준비하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 프로젝트 권한이 있는 Jira 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Jira 계정 연결
## Jira 연동 설정
### 1. Jira 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. **Jira**를 인증 통합 섹션에서 찾습니다.
3. **Connect**를 클릭하고 OAuth 절차를 완료합니다.
4. 이슈 및 프로젝트 관리를 위한 필요한 권한을 부여합니다.
5. [Account Settings](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="JIRA_CREATE_ISSUE">
**설명:** Jira에서 이슈를 생성합니다.
**파라미터:**
- `summary` (string, 필수): 요약 - 이슈에 대한 간단한 한 줄 요약입니다. (예시: "프린터가 작동을 멈췄습니다").
- `project` (string, 선택): 프로젝트 - 이슈가 속한 프로젝트입니다. 제공되지 않으면 사용자의 첫 번째 프로젝트로 기본 설정됩니다. 사용자가 프로젝트를 선택할 수 있도록 Connect Portal Workflow Settings를 사용하세요.
- `issueType` (string, 선택): 이슈 유형 - 제공되지 않으면 기본값은 Task입니다.
- `jiraIssueStatus` (string, 선택): 상태 - 제공되지 않으면 프로젝트의 첫 번째 상태가 기본입니다.
- `assignee` (string, 선택): 담당자 - 제공되지 않으면 인증된 사용자로 기본 설정됩니다.
- `descriptionType` (string, 선택): 설명 유형 - 설명 유형을 선택하세요.
- 옵션: `description`, `descriptionJSON`
- `description` (string, 선택): 설명 - 이슈에 대한 자세한 설명입니다. 이 필드는 'descriptionType'이 'description'일 때만 나타납니다.
- `additionalFields` (string, 선택): 추가 필드 - 포함해야 하는 다른 필드를 JSON 형식으로 지정하세요. 사용자가 업데이트할 이슈 필드를 선택할 수 있도록 Connect Portal Workflow Settings를 사용하세요.
```json
{
"customfield_10001": "value"
}
```
</Accordion>
<Accordion title="JIRA_UPDATE_ISSUE">
**설명:** Jira에서 이슈를 업데이트합니다.
**파라미터:**
- `issueKey` (string, 필수): 이슈 키 (예시: "TEST-1234").
- `summary` (string, 선택): 요약 - 이슈에 대한 간단한 한 줄 요약입니다. (예시: "프린터가 작동을 멈췄습니다").
- `issueType` (string, 선택): 이슈 유형 - 사용자가 이슈 유형을 선택할 수 있도록 Connect Portal Workflow Settings를 사용하세요.
- `jiraIssueStatus` (string, 선택): 상태 - 사용자가 상태를 선택할 수 있도록 Connect Portal Workflow Settings를 사용하세요.
- `assignee` (string, 선택): 담당자 - 사용자가 담당자를 선택할 수 있도록 Connect Portal Workflow Settings를 사용하세요.
- `descriptionType` (string, 선택): 설명 유형 - 설명 유형을 선택하세요.
- 옵션: `description`, `descriptionJSON`
- `description` (string, 선택): 설명 - 이슈에 대한 자세한 설명입니다. 이 필드는 'descriptionType'이 'description'일 때만 나타납니다.
- `additionalFields` (string, 선택): 추가 필드 - 포함해야 하는 다른 필드를 JSON 형식으로 지정하세요.
</Accordion>
<Accordion title="JIRA_GET_ISSUE_BY_KEY">
**설명:** Jira에서 키로 이슈를 조회합니다.
**파라미터:**
- `issueKey` (string, 필수): 이슈 키 (예시: "TEST-1234").
</Accordion>
<Accordion title="JIRA_FILTER_ISSUES">
**설명:** 필터를 사용하여 Jira에서 이슈를 검색합니다.
**파라미터:**
- `jqlQuery` (object, 선택): 불리언 합정규형(OR의 AND 그룹)으로 구성된 필터.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "status",
"operator": "$stringExactlyMatches",
"value": "Open"
}
]
}
]
}
```
사용 가능한 연산자: `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringIsIn`, `$stringIsNotIn`, `$stringContains`, `$stringDoesNotContain`, `$stringGreaterThan`, `$stringLessThan`
- `limit` (string, 선택): 결과 제한 - 반환되는 최대 이슈 수를 제한합니다. 입력하지 않으면 기본값은 10입니다.
</Accordion>
<Accordion title="JIRA_SEARCH_BY_JQL">
**설명:** Jira에서 JQL로 이슈를 검색합니다.
**파라미터:**
- `jqlQuery` (string, 필수): JQL 쿼리 (예시: "project = PROJECT").
- `paginationParameters` (object, 선택): 페이지네이션 결과를 위한 파라미터.
```json
{
"pageCursor": "cursor_string"
}
```
</Accordion>
<Accordion title="JIRA_UPDATE_ISSUE_ANY">
**설명:** Jira에서 임의의 이슈를 업데이트합니다. 이 기능의 속성 스키마를 얻으려면 DESCRIBE_ACTION_SCHEMA를 사용하세요.
**파라미터:** 특정 파라미터 없음 - 예상 스키마를 먼저 확인하려면 JIRA_DESCRIBE_ACTION_SCHEMA를 사용하세요.
</Accordion>
<Accordion title="JIRA_DESCRIBE_ACTION_SCHEMA">
**설명:** 이슈 유형에 대한 예상 스키마를 가져옵니다. 사용하려는 이슈 유형과 일치하는 다른 기능이 없을 경우 먼저 이 기능을 사용하세요.
**파라미터:**
- `issueTypeId` (string, 필수): 이슈 유형 ID.
- `projectKey` (string, 필수): 프로젝트 키.
- `operation` (string, 필수): 작업 유형 값(예: CREATE_ISSUE 또는 UPDATE_ISSUE).
</Accordion>
<Accordion title="JIRA_GET_PROJECTS">
**설명:** Jira에서 프로젝트를 가져옵니다.
**파라미터:**
- `paginationParameters` (object, 선택): 페이지네이션 파라미터.
```json
{
"pageCursor": "cursor_string"
}
```
</Accordion>
<Accordion title="JIRA_GET_ISSUE_TYPES_BY_PROJECT">
**설명:** Jira에서 프로젝트별 이슈 유형을 조회합니다.
**파라미터:**
- `project` (string, 필수): 프로젝트 키.
</Accordion>
<Accordion title="JIRA_GET_ISSUE_TYPES">
**설명:** Jira에서 모든 이슈 유형을 조회합니다.
**파라미터:** 필요 없음.
</Accordion>
<Accordion title="JIRA_GET_ISSUE_STATUS_BY_PROJECT">
**설명:** 주어진 프로젝트의 이슈 상태를 조회합니다.
**파라미터:**
- `project` (string, 필수): 프로젝트 키.
</Accordion>
<Accordion title="JIRA_GET_ALL_ASSIGNEES_BY_PROJECT">
**설명:** 주어진 프로젝트의 담당자 목록을 조회합니다.
**파라미터:**
- `project` (string, 필수): 프로젝트 키.
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Jira 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Jira tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Jira capabilities
jira_agent = Agent(
role="Issue Manager",
goal="Manage Jira issues and track project progress efficiently",
backstory="An AI assistant specialized in issue tracking and project management.",
tools=[enterprise_tools]
)
# Task to create a bug report
create_bug_task = Task(
description="Create a bug report for the login functionality with high priority and assign it to the development team",
agent=jira_agent,
expected_output="Bug report created successfully with issue key"
)
# Run the task
crew = Crew(
agents=[jira_agent],
tasks=[create_bug_task]
)
crew.kickoff()
```
### 특정 Jira 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Jira tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["jira_create_issue", "jira_update_issue", "jira_search_by_jql"]
)
issue_coordinator = Agent(
role="Issue Coordinator",
goal="Create and manage Jira issues efficiently",
backstory="An AI assistant that focuses on issue creation and management.",
tools=enterprise_tools
)
# Task to manage issue workflow
issue_workflow = Task(
description="Create a feature request issue and update the status of related issues",
agent=issue_coordinator,
expected_output="Feature request created and related issues updated"
)
crew = Crew(
agents=[issue_coordinator],
tasks=[issue_workflow]
)
crew.kickoff()
```
### 프로젝트 분석 및 보고
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_analyst = Agent(
role="Project Analyst",
goal="Analyze project data and generate insights from Jira",
backstory="An experienced project analyst who extracts insights from project management data.",
tools=[enterprise_tools]
)
# Task to analyze project status
analysis_task = Task(
description="""
1. Get all projects and their issue types
2. Search for all open issues across projects
3. Analyze issue distribution by status and assignee
4. Create a summary report issue with findings
""",
agent=project_analyst,
expected_output="Project analysis completed with summary report created"
)
crew = Crew(
agents=[project_analyst],
tasks=[analysis_task]
)
crew.kickoff()
```
### 자동화된 이슈 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
automation_manager = Agent(
role="Automation Manager",
goal="Automate issue management and workflow processes",
backstory="An AI assistant that automates repetitive issue management tasks.",
tools=[enterprise_tools]
)
# Task to automate issue management
automation_task = Task(
description="""
1. Search for all unassigned issues using JQL
2. Get available assignees for each project
3. Automatically assign issues based on workload and expertise
4. Update issue priorities based on age and type
5. Create weekly sprint planning issues
""",
agent=automation_manager,
expected_output="Issues automatically assigned and sprint planning issues created"
)
crew = Crew(
agents=[automation_manager],
tasks=[automation_task]
)
crew.kickoff()
```
### 고급 스키마 기반 작업
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
schema_specialist = Agent(
role="Schema Specialist",
goal="Handle complex Jira operations using dynamic schemas",
backstory="An AI assistant that can work with dynamic Jira schemas and custom issue types.",
tools=[enterprise_tools]
)
# Task using schema-based operations
schema_task = Task(
description="""
1. 모든 프로젝트와 해당 커스텀 이슈 유형을 가져옵니다
2. 각 커스텀 이슈 유형에 대해, 액션 스키마를 설명합니다
3. 복잡한 커스텀 필드를 위한 동적 스키마를 사용해 이슈를 생성합니다
4. 비즈니스 규칙에 따라 커스텀 필드 값을 사용해 이슈를 업데이트합니다
""",
agent=schema_specialist,
expected_output="동적 스키마를 사용하여 커스텀 이슈가 생성되고 업데이트됨"
)
crew = Crew(
agents=[schema_specialist],
tasks=[schema_task]
)
crew.kickoff()
```
## 문제 해결
### 일반적인 문제
**권한 오류**
- Jira 계정이 대상 프로젝트에 필요한 권한을 가지고 있는지 확인하세요
- OAuth 연결에 Jira API에 필요한 범위가 포함되어 있는지 확인하세요
- 지정된 프로젝트에서 이슈 생성/편집 권한이 있는지 확인하세요
**잘못된 프로젝트 또는 이슈 키**
- 프로젝트 키와 이슈 키가 올바른 형식(예: "PROJ-123")인지 다시 확인하세요
- 프로젝트가 존재하며 계정으로 접근 가능한지 확인하세요
- 이슈 키가 실제로 존재하는 이슈를 참조하는지 확인하세요
**이슈 유형 및 상태 관련 문제**
- 프로젝트에 대한 유효한 이슈 유형을 얻으려면 JIRA_GET_ISSUE_TYPES_BY_PROJECT를 사용하세요
- 유효한 상태를 얻으려면 JIRA_GET_ISSUE_STATUS_BY_PROJECT를 사용하세요
- 이슈 유형과 상태가 대상 프로젝트에 제공되는지 확인하세요
**JQL 쿼리 문제**
- API 호출에 사용하기 전에 Jira의 이슈 검색에서 JQL 쿼리를 테스트하세요
- JQL에 사용된 필드명이 정확하게 철자되어 있고, Jira 인스턴스에 존재하는지 확인하세요
- 복잡한 쿼리에는 올바른 JQL 문법을 사용하세요
**커스텀 필드 및 스키마 문제**
- 복잡한 이슈 유형에 대해 올바른 스키마를 얻으려면 JIRA_DESCRIBE_ACTION_SCHEMA를 사용하세요
- 커스텀 필드 ID가 정확한지 확인하세요 (예: "customfield_10001")
- 커스텀 필드가 대상 프로젝트와 이슈 유형에서 사용 가능한지 확인하세요
**필터 공식 문제**
- 필터 공식이 올바른 JSON 구조(불리언 합의 정규형)를 따르는지 확인하세요
- Jira 구성에 존재하는 유효한 필드명을 사용하세요
- 복잡한 다중 조건 쿼리를 만들기 전에 간단한 필터를 테스트하세요
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Jira 연동 설정 또는 문제 해결에 대한 지원이 필요하시면 저희 지원팀에 문의하십시오.
</Card>

View File

@@ -0,0 +1,453 @@
---
title: Linear 연동
description: "CrewAI를 위한 Linear 연동을 통한 소프트웨어 프로젝트 및 버그 추적."
icon: "list-check"
---
## 개요
에이전트가 Linear를 통해 이슈, 프로젝트, 개발 워크플로우를 관리할 수 있도록 지원합니다. 이슈를 생성 및 업데이트하고, 프로젝트 타임라인을 관리하며, 팀을 조직하고, AI 기반 자동화로 소프트웨어 개발 프로세스를 간소화할 수 있습니다.
## 필수 조건
Linear 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 워크스페이스 권한이 있는 Linear 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)에서 Linear 계정 연결
## 리니어 통합 설정
### 1. Linear 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합( Authentication Integrations ) 섹션에서 **Linear**를 찾습니다.
3. **Connect**를 클릭하고 OAuth 절차를 완료합니다.
4. 이슈 및 프로젝트 관리를 위한 필수 권한을 부여합니다.
5. [계정 설정](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 작업
<AccordionGroup>
<Accordion title="LINEAR_CREATE_ISSUE">
**설명:** Linear에서 새로운 이슈를 생성합니다.
**파라미터:**
- `teamId` (string, 필수): 팀 ID - 이 새로운 이슈의 상위 팀 ID를 지정합니다. Connect Portal Workflow Settings를 사용하여 사용자가 팀 ID를 선택할 수 있도록 하세요. (예: "a70bdf0f-530a-4887-857d-46151b52b47c").
- `title` (string, 필수): 제목 - 이 이슈의 제목을 지정합니다.
- `description` (string, 선택): 설명 - 이 이슈의 설명을 지정합니다.
- `statusId` (string, 선택): 상태 - 이 이슈의 상태를 지정합니다.
- `priority` (string, 선택): 우선순위 - 이 이슈의 우선순위를 정수로 지정합니다.
- `dueDate` (string, 선택): 마감일 - 이 이슈의 마감일을 ISO 8601 형식으로 지정합니다.
- `cycleId` (string, 선택): 사이클 ID - 이 이슈가 속한 사이클을 지정합니다.
- `additionalFields` (object, 선택): 추가 필드.
```json
{
"assigneeId": "a70bdf0f-530a-4887-857d-46151b52b47c",
"labelIds": ["a70bdf0f-530a-4887-857d-46151b52b47c"]
}
```
</Accordion>
<Accordion title="LINEAR_UPDATE_ISSUE">
**설명:** Linear에서 이슈를 업데이트합니다.
**파라미터:**
- `issueId` (string, 필수): 이슈 ID - 업데이트할 이슈의 ID를 지정합니다. (예: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
- `title` (string, 선택): 제목 - 이 이슈의 제목을 지정합니다.
- `description` (string, 선택): 설명 - 이 이슈의 설명을 지정합니다.
- `statusId` (string, 선택): 상태 - 이 이슈의 상태를 지정합니다.
- `priority` (string, 선택): 우선순위 - 이 이슈의 우선순위를 정수로 지정합니다.
- `dueDate` (string, 선택): 마감일 - 이 이슈의 마감일을 ISO 8601 형식으로 지정합니다.
- `cycleId` (string, 선택): 사이클 ID - 이 이슈가 속한 사이클을 지정합니다.
- `additionalFields` (object, 선택): 추가 필드.
```json
{
"assigneeId": "a70bdf0f-530a-4887-857d-46151b52b47c",
"labelIds": ["a70bdf0f-530a-4887-857d-46151b52b47c"]
}
```
</Accordion>
<Accordion title="LINEAR_GET_ISSUE_BY_ID">
**설명:** Linear에서 ID로 이슈를 가져옵니다.
**파라미터:**
- `issueId` (string, 필수): 이슈 ID - 가져올 이슈의 레코드 ID를 지정합니다. (예: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
</Accordion>
<Accordion title="LINEAR_GET_ISSUE_BY_ISSUE_IDENTIFIER">
**설명:** Linear에서 이슈 식별자로 이슈를 가져옵니다.
**파라미터:**
- `externalId` (string, 필수): 외부 ID - 가져올 이슈의 사람이 읽을 수 있는 이슈 식별자를 지정합니다. (예: "ABC-1").
</Accordion>
<Accordion title="LINEAR_SEARCH_ISSUE">
**설명:** Linear에서 이슈를 검색합니다.
**파라미터:**
- `queryTerm` (string, 필수): 검색어 - 찾을 검색어입니다.
- `issueFilterFormula` (object, 선택): 부정합적 정규형(DNF)의 필터 - 단일 조건의 AND 그룹들에 대한 OR.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "title",
"operator": "$stringContains",
"value": "bug"
}
]
}
]
}
```
사용 가능한 필드: `title`, `number`, `project`, `createdAt`
사용 가능한 연산자: `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringIsIn`, `$stringIsNotIn`, `$stringStartsWith`, `$stringDoesNotStartWith`, `$stringEndsWith`, `$stringDoesNotEndWith`, `$stringContains`, `$stringDoesNotContain`, `$stringGreaterThan`, `$stringLessThan`, `$numberGreaterThanOrEqualTo`, `$numberLessThanOrEqualTo`, `$numberGreaterThan`, `$numberLessThan`, `$dateTimeAfter`, `$dateTimeBefore`
</Accordion>
<Accordion title="LINEAR_DELETE_ISSUE">
**설명:** Linear에서 이슈를 삭제합니다.
**파라미터:**
- `issueId` (string, 필수): 이슈 ID - 삭제할 이슈의 레코드 ID를 지정합니다. (예: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
</Accordion>
<Accordion title="LINEAR_ARCHIVE_ISSUE">
**설명:** Linear에서 이슈를 아카이브합니다.
**파라미터:**
- `issueId` (string, 필수): 이슈 ID - 아카이브할 이슈의 레코드 ID를 지정합니다. (예: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
</Accordion>
<Accordion title="LINEAR_CREATE_SUB_ISSUE">
**설명:** Linear에서 하위 이슈를 생성합니다.
**파라미터:**
- `parentId` (string, 필수): 상위 ID - 이 새로운 이슈의 상위 이슈 ID를 지정합니다.
- `teamId` (string, 필수): 팀 ID - 이 새로운 하위 이슈의 상위 팀 ID를 지정합니다. Connect Portal Workflow Settings를 사용하여 사용자가 팀 ID를 선택할 수 있도록 하세요. (예: "a70bdf0f-530a-4887-857d-46151b52b47c").
- `title` (string, 필수): 제목 - 이 이슈의 제목을 지정합니다.
- `description` (string, 선택): 설명 - 이 이슈의 설명을 지정합니다.
- `additionalFields` (object, 선택): 추가 필드.
```json
{
"lead": "linear_user_id"
}
```
</Accordion>
<Accordion title="LINEAR_CREATE_PROJECT">
**설명:** Linear에서 새로운 프로젝트를 생성합니다.
**파라미터:**
- `teamIds` (object, 필수): 팀 ID - 이 프로젝트와 연관된 팀 ID 혹은 팀 ID의 JSON 배열을 문자열로 지정합니다. Connect Portal User Settings를 사용하여 사용자가 팀 ID를 선택할 수 있도록 하세요.
```json
[
"a70bdf0f-530a-4887-857d-46151b52b47c",
"4ac7..."
]
```
- `projectName` (string, 필수): 프로젝트 이름 - 프로젝트의 이름을 지정합니다. (예: "My Linear Project").
- `description` (string, 선택): 프로젝트 설명 - 프로젝트에 대한 설명을 지정합니다.
- `additionalFields` (object, 선택): 추가 필드.
```json
{
"state": "planned",
"description": ""
}
```
</Accordion>
<Accordion title="LINEAR_UPDATE_PROJECT">
**설명:** Linear에서 프로젝트를 업데이트합니다.
**파라미터:**
- `projectId` (string, 필수): 프로젝트 ID - 업데이트할 프로젝트의 ID를 지정합니다. (예: "a6634484-6061-4ac7-9739-7dc5e52c796b").
- `projectName` (string, 선택): 프로젝트 이름 - 업데이트할 프로젝트의 이름을 지정합니다. (예: "My Linear Project").
- `description` (string, 선택): 프로젝트 설명 - 프로젝트에 대한 설명을 지정합니다.
- `additionalFields` (object, 선택): 추가 필드.
```json
{
"state": "planned",
"description": ""
}
```
</Accordion>
<Accordion title="LINEAR_GET_PROJECT_BY_ID">
**설명:** Linear에서 ID로 프로젝트를 가져옵니다.
**파라미터:**
- `projectId` (string, 필수): 프로젝트 ID - 가져올 프로젝트의 프로젝트 ID를 지정합니다. (예: "a6634484-6061-4ac7-9739-7dc5e52c796b").
</Accordion>
<Accordion title="LINEAR_DELETE_PROJECT">
**설명:** Linear에서 프로젝트를 삭제합니다.
**파라미터:**
- `projectId` (string, 필수): 프로젝트 ID - 삭제할 프로젝트의 프로젝트 ID를 지정합니다. (예: "a6634484-6061-4ac7-9739-7dc5e52c796b").
</Accordion>
<Accordion title="LINEAR_SEARCH_TEAMS">
**설명:** Linear에서 팀을 검색합니다.
**파라미터:**
- `teamFilterFormula` (object, 선택): 부정합적 정규형(DNF)의 필터 - 단일 조건의 AND 그룹들에 대한 OR.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "name",
"operator": "$stringContains",
"value": "Engineering"
}
]
}
]
}
```
사용 가능한 필드: `id`, `name`
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Linear 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Linear tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Linear capabilities
linear_agent = Agent(
role="Development Manager",
goal="Manage Linear issues and track development progress efficiently",
backstory="An AI assistant specialized in software development project management.",
tools=[enterprise_tools]
)
# Task to create a bug report
create_bug_task = Task(
description="Create a high-priority bug report for the authentication system and assign it to the backend team",
agent=linear_agent,
expected_output="Bug report created successfully with issue ID"
)
# Run the task
crew = Crew(
agents=[linear_agent],
tasks=[create_bug_task]
)
crew.kickoff()
```
### 특정 Linear 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Linear tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["linear_create_issue", "linear_update_issue", "linear_search_issue"]
)
issue_manager = Agent(
role="Issue Manager",
goal="Create and manage Linear issues efficiently",
backstory="An AI assistant that focuses on issue creation and lifecycle management.",
tools=enterprise_tools
)
# Task to manage issue workflow
issue_workflow = Task(
description="Create a feature request issue and update the status of related issues to reflect current progress",
agent=issue_manager,
expected_output="Feature request created and related issues updated"
)
crew = Crew(
agents=[issue_manager],
tasks=[issue_workflow]
)
crew.kickoff()
```
### 프로젝트 및 팀 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_coordinator = Agent(
role="Project Coordinator",
goal="Coordinate projects and teams in Linear efficiently",
backstory="An experienced project coordinator who manages development cycles and team workflows.",
tools=[enterprise_tools]
)
# Task to coordinate project setup
project_coordination = Task(
description="""
1. Search for engineering teams in Linear
2. Create a new project for Q2 feature development
3. Associate the project with relevant teams
4. Create initial project milestones as issues
""",
agent=project_coordinator,
expected_output="Q2 project created with teams assigned and initial milestones established"
)
crew = Crew(
agents=[project_coordinator],
tasks=[project_coordination]
)
crew.kickoff()
```
### 이슈 계층 구조 및 하위 작업 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
task_organizer = Agent(
role="Task Organizer",
goal="Organize complex issues into manageable sub-tasks",
backstory="An AI assistant that breaks down complex development work into organized sub-tasks.",
tools=[enterprise_tools]
)
# Task to create issue hierarchy
hierarchy_task = Task(
description="""
1. 세분화가 필요한 대형 기능 이슈를 검색합니다
2. 각 복잡한 이슈에 대해 다양한 컴포넌트별로 하위 이슈를 생성합니다
3. 부모 이슈를 적절한 설명과 하위 이슈에 대한 링크로 업데이트합니다
4. 전문성에 따라 적합한 팀원에게 하위 이슈를 할당합니다
""",
agent=task_organizer,
expected_output="복잡한 이슈가 적절히 할당된 관리 가능한 하위 작업 단위로 분해됨"
)
crew = Crew(
agents=[task_organizer],
tasks=[hierarchy_task]
)
crew.kickoff()
```
### 자동화된 개발 워크플로우
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
workflow_automator = Agent(
role="Workflow Automator",
goal="Automate development workflow processes in Linear",
backstory="An AI assistant that automates repetitive development workflow tasks.",
tools=[enterprise_tools]
)
# Complex workflow automation task
automation_task = Task(
description="""
1. 7일 이상 진행 중인 이슈를 검색합니다
2. 마감일과 프로젝트 중요도에 따라 우선순위를 업데이트합니다
3. 각 팀을 위한 주간 스프린트 계획 이슈를 생성합니다
4. 이전 사이클에서 완료된 이슈를 보관합니다
5. 프로젝트 상태 보고서를 새로운 이슈로 생성합니다
""",
agent=workflow_automator,
expected_output="우선순위, 스프린트 계획, 상태 보고서가 업데이트된 자동화된 개발 워크플로우"
)
crew = Crew(
agents=[workflow_automator],
tasks=[automation_task]
)
crew.kickoff()
```
## 문제 해결
### 일반적인 문제
**권한 오류**
- Linear 계정이 대상 워크스페이스에 필요한 권한을 가지고 있는지 확인하세요
- OAuth 연결에 Linear API에 필요한 스코프가 포함되어 있는지 확인하세요
- 워크스페이스에서 이슈 및 프로젝트를 생성/편집할 권한이 있는지 확인하세요
**잘못된 ID 및 참조**
- 팀 ID, 이슈 ID, 프로젝트 ID가 올바른 UUID 형식인지 다시 한번 확인하세요
- 참조된 엔티티(팀, 프로젝트, 사이클)가 존재하며 접근 가능한지 확인하세요
- 이슈 식별자가 올바른 형식(예: "ABC-1")을 따르는지 검증하세요
**팀 및 프로젝트 연관 문제**
- 이슈나 프로젝트를 생성하기 전에 LINEAR_SEARCH_TEAMS를 사용하여 유효한 팀 ID를 조회하세요
- 워크스페이스 내에 팀이 존재하고 활성화되어 있는지 확인하세요
- 팀 ID가 올바르게 UUID 형식으로 구성되어 있는지 검증하세요
**이슈 상태 및 우선순위 문제**
- 상태 ID가 팀의 유효한 워크플로우 상태를 참조하는지 확인하세요
- 우선순위 값이 Linear 구성에서 허용된 범위 내에 있는지 확인하세요
- 참조하기 전에 사용자 지정 필드와 라벨이 존재하는지 검증하세요
**날짜 및 시간 형식 문제**
- 마감일 및 타임스탬프에 ISO 8601 형식을 사용하세요
- 마감일 계산 시 타임존을 올바로 처리하는지 확인하세요
- 마감일의 날짜 값이 유효하며 미래인지 검증하세요
**검색 및 필터 문제**
- 검색 쿼리가 올바르게 형식화되어 있으며 비어 있지 않은지 확인하세요
- 필터 공식에서 유효한 필드 이름을 사용하세요: `title`, `number`, `project`, `createdAt`
- 복잡한 다중 조건 쿼리를 만들기 전에 단순한 필터를 먼저 테스트해 보세요
- 연산자 타입이 필터링 대상 필드의 데이터 타입과 일치하는지 확인하세요
**서브이슈 생성 문제**
- 상위 이슈 ID가 유효하고 접근 가능한지 확인하세요
- 서브이슈의 팀 ID가 상위 이슈 팀과 일치하거나 호환되는지 검증하세요
- 상위 이슈가 이미 보관/삭제되지 않았는지 확인하세요
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Linear 연동 설정 또는 문제 해결에 대해 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,509 @@
---
title: Notion 연동
description: "CrewAI를 위한 Notion 연동을 통한 페이지 및 데이터베이스 관리."
icon: "book"
---
## 개요
에이전트가 Notion을 통해 페이지, 데이터베이스, 콘텐츠를 관리할 수 있도록 지원합니다. 페이지 생성 및 업데이트, 콘텐츠 블록 관리, 지식 베이스 구성, AI 기반 자동화를 통해 문서화 작업 흐름을 효율화할 수 있습니다.
## 필수 조건
Notion 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 워크스페이스 권한이 있는 Notion 계정
- [통합 페이지](https://app.crewai.com/crewai_plus/connectors)를 통해 Notion 계정을 연결함
## Notion 연동 설정
### 1. Notion 계정 연결하기
1. [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)로 이동합니다.
2. 인증 통합(Auhtentication Integrations) 섹션에서 **Notion**을(를) 찾습니다.
3. **Connect**를 클릭하고 OAuth 플로우를 완료합니다.
4. 페이지 및 데이터베이스 관리를 위한 필요한 권한을 부여합니다.
5. [Account Settings](https://app.crewai.com/crewai_plus/settings/account)에서 Enterprise Token을 복사합니다.
### 2. 필수 패키지 설치
```bash
uv add crewai-tools
```
## 사용 가능한 액션
<AccordionGroup>
<Accordion title="NOTION_CREATE_PAGE">
**설명:** Notion에서 페이지를 생성합니다.
**파라미터:**
- `parent` (object, 필수): 상위 - 새 페이지가 삽입될 상위 페이지 또는 데이터베이스를 나타내는 JSON 객체로, page_id 또는 database_id 키를 포함합니다.
```json
{
"database_id": "DATABASE_ID"
}
```
- `properties` (object, 필수): 속성 - 페이지 속성의 값입니다. 상위가 데이터베이스인 경우, 스키마는 상위 데이터베이스의 속성과 일치해야 합니다.
```json
{
"title": [
{
"text": {
"content": "My Page"
}
}
]
}
```
- `icon` (object, 필수): 아이콘 - 페이지 아이콘입니다.
```json
{
"emoji": "🥬"
}
```
- `children` (object, 선택): 자식 - 페이지에 추가할 콘텐츠 블록입니다.
```json
[
{
"object": "block",
"type": "heading_2",
"heading_2": {
"rich_text": [
{
"type": "text",
"text": {
"content": "Lacinato kale"
}
}
]
}
}
]
```
- `cover` (object, 선택): 표지 - 페이지 표지 이미지입니다.
```json
{
"external": {
"url": "https://upload.wikimedia.org/wikipedia/commons/6/62/Tuscankale.jpg"
}
}
```
</Accordion>
<Accordion title="NOTION_UPDATE_PAGE">
**설명:** Notion에서 페이지를 업데이트합니다.
**파라미터:**
- `pageId` (string, 필수): 페이지 ID - 업데이트할 페이지의 ID를 지정합니다. (예: "59833787-2cf9-4fdf-8782-e53db20768a5").
- `icon` (object, 필수): 아이콘 - 페이지 아이콘입니다.
```json
{
"emoji": "🥬"
}
```
- `archived` (boolean, 선택): 보관됨 - 페이지가 보관(삭제)되었는지 여부입니다. true로 설정하면 페이지를 보관합니다. false로 설정하면 보관 해제(복원)합니다.
- `properties` (object, 선택): 속성 - 페이지에서 업데이트할 속성 값입니다.
```json
{
"title": [
{
"text": {
"content": "My Updated Page"
}
}
]
}
```
- `cover` (object, 선택): 표지 - 페이지 표지 이미지입니다.
```json
{
"external": {
"url": "https://upload.wikimedia.org/wikipedia/commons/6/62/Tuscankale.jpg"
}
}
```
</Accordion>
<Accordion title="NOTION_GET_PAGE_BY_ID">
**설명:** Notion에서 ID로 페이지를 가져옵니다.
**파라미터:**
- `pageId` (string, 필수): 페이지 ID - 가져올 페이지의 ID를 지정합니다. (예: "59833787-2cf9-4fdf-8782-e53db20768a5").
</Accordion>
<Accordion title="NOTION_ARCHIVE_PAGE">
**설명:** Notion에서 페이지를 보관합니다.
**파라미터:**
- `pageId` (string, 필수): 페이지 ID - 보관할 페이지의 ID를 지정합니다. (예: "59833787-2cf9-4fdf-8782-e53db20768a5").
</Accordion>
<Accordion title="NOTION_SEARCH_PAGES">
**설명:** 필터를 사용하여 Notion에서 페이지를 검색합니다.
**파라미터:**
- `searchByTitleFilterSearch` (object, 선택): 불리언 정규형(OR 조건 그룹의 AND 그룹) 형태의 필터입니다.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "query",
"operator": "$stringExactlyMatches",
"value": "meeting notes"
}
]
}
]
}
```
사용 가능한 필드: `query`, `filter.value`, `direction`, `page_size`
</Accordion>
<Accordion title="NOTION_GET_PAGE_CONTENT">
**설명:** Notion에서 페이지 콘텐츠(블록)를 가져옵니다.
**파라미터:**
- `blockId` (string, 필수): 페이지 ID - 해당 블록이나 페이지의 모든 자식 블록을 순서대로 가져오기 위해 Block 또는 Page ID를 지정합니다. (예: "59833787-2cf9-4fdf-8782-e53db20768a5").
</Accordion>
<Accordion title="NOTION_UPDATE_BLOCK">
**설명:** Notion에서 블록을 업데이트합니다.
**파라미터:**
- `blockId` (string, 필수): 블록 ID - 업데이트할 블록의 ID를 지정합니다. (예: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
- `archived` (boolean, 선택): 보관됨 - true로 설정하면 블록을 보관(삭제)합니다. false로 설정하면 보관 해제(복원)합니다.
- `paragraph` (object, 선택): 단락 콘텐츠.
```json
{
"rich_text": [
{
"type": "text",
"text": {
"content": "Lacinato kale",
"link": null
}
}
],
"color": "default"
}
```
- `image` (object, 선택): 이미지 블록.
```json
{
"type": "external",
"external": {
"url": "https://website.domain/images/image.png"
}
}
```
- `bookmark` (object, 선택): 북마크 블록.
```json
{
"caption": [],
"url": "https://companywebsite.com"
}
```
- `code` (object, 선택): 코드 블록.
```json
{
"rich_text": [
{
"type": "text",
"text": {
"content": "const a = 3"
}
}
],
"language": "javascript"
}
```
- `pdf` (object, 선택): PDF 블록.
```json
{
"type": "external",
"external": {
"url": "https://website.domain/files/doc.pdf"
}
}
```
- `table` (object, 선택): 테이블 블록.
```json
{
"table_width": 2,
"has_column_header": false,
"has_row_header": false
}
```
- `tableOfContent` (object, 선택): 목차 블록.
```json
{
"color": "default"
}
```
- `additionalFields` (object, 선택): 추가 블록 유형.
```json
{
"child_page": {
"title": "Lacinato kale"
},
"child_database": {
"title": "My database"
}
}
```
</Accordion>
<Accordion title="NOTION_GET_BLOCK_BY_ID">
**설명:** Notion에서 ID로 블록을 가져옵니다.
**파라미터:**
- `blockId` (string, 필수): 블록 ID - 가져올 블록의 ID를 지정합니다. (예: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
</Accordion>
<Accordion title="NOTION_DELETE_BLOCK">
**설명:** Notion에서 블록을 삭제합니다.
**파라미터:**
- `blockId` (string, 필수): 블록 ID - 삭제할 블록의 ID를 지정합니다. (예: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Notion Agent 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Notion tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Notion capabilities
notion_agent = Agent(
role="Documentation Manager",
goal="Manage documentation and knowledge base in Notion efficiently",
backstory="An AI assistant specialized in content management and documentation.",
tools=[enterprise_tools]
)
# Task to create a meeting notes page
create_notes_task = Task(
description="Create a new meeting notes page in the team database with today's date and agenda items",
agent=notion_agent,
expected_output="Meeting notes page created successfully with structured content"
)
# Run the task
crew = Crew(
agents=[notion_agent],
tasks=[create_notes_task]
)
crew.kickoff()
```
### 특정 Notion 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Notion tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["notion_create_page", "notion_update_block", "notion_search_pages"]
)
content_manager = Agent(
role="Content Manager",
goal="Create and manage content pages efficiently",
backstory="An AI assistant that focuses on content creation and management.",
tools=enterprise_tools
)
# Task to manage content workflow
content_workflow = Task(
description="Create a new project documentation page and add structured content blocks for requirements and specifications",
agent=content_manager,
expected_output="Project documentation created with organized content sections"
)
crew = Crew(
agents=[content_manager],
tasks=[content_workflow]
)
crew.kickoff()
```
### 지식 베이스 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
knowledge_curator = Agent(
role="Knowledge Curator",
goal="Curate and organize knowledge base content in Notion",
backstory="An experienced knowledge manager who organizes and maintains comprehensive documentation.",
tools=[enterprise_tools]
)
# Task to curate knowledge base
curation_task = Task(
description="""
1. 새로운 제품 기능과 관련된 기존 문서 페이지를 검색합니다.
2. 적절한 구조로 포괄적인 기능 문서 페이지를 생성합니다.
3. 코드 예제, 이미지 및 관련 리소스에 대한 링크를 추가합니다.
4. 기존 페이지를 업데이트하여 새 문서에 대한 교차 참조를 추가합니다.
""",
agent=knowledge_curator,
expected_output="Feature documentation created and integrated with existing knowledge base"
)
crew = Crew(
agents=[knowledge_curator],
tasks=[curation_task]
)
crew.kickoff()
```
### 콘텐츠 구조 및 구성
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
content_organizer = Agent(
role="Content Organizer",
goal="Organize and structure content blocks for optimal readability",
backstory="An AI assistant that specializes in content structure and user experience.",
tools=[enterprise_tools]
)
# Task to organize content structure
organization_task = Task(
description="""
1. Get content from existing project pages
2. Analyze the structure and identify improvement opportunities
3. Update content blocks to use proper headings, tables, and formatting
4. Add table of contents and improve navigation between related pages
5. Create templates for future documentation consistency
""",
agent=content_organizer,
expected_output="Content reorganized with improved structure and navigation"
)
crew = Crew(
agents=[content_organizer],
tasks=[organization_task]
)
crew.kickoff()
```
### 자동화된 문서화 워크플로우
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
doc_automator = Agent(
role="Documentation Automator",
goal="Automate documentation workflows and maintenance",
backstory="An AI assistant that automates repetitive documentation tasks.",
tools=[enterprise_tools]
)
# Complex documentation automation task
automation_task = Task(
description="""
1. 최근 30일 이내에 업데이트되지 않은 페이지 검색
2. 오래된 콘텐츠 블록 검토 및 업데이트
3. 일관된 포맷으로 주간 팀 업데이트 페이지 생성
4. 프로젝트 페이지에 상태 표시기 및 진행 상황 추적 추가
5. 월간 문서 헬스 리포트 생성
6. 완료된 프로젝트 페이지를 아카이브 섹션에 정리 및 보관
""",
agent=doc_automator,
expected_output="업데이트된 콘텐츠, 주간 리포트, 정리된 아카이브로 문서화 자동화 완료"
)
crew = Crew(
agents=[doc_automator],
tasks=[automation_task]
)
crew.kickoff()
```
## 문제 해결
### 일반적인 문제
**권한 오류**
- Notion 계정이 대상 워크스페이스에 대한 편집 권한이 있는지 확인하세요
- OAuth 연결에 Notion API에 필요한 범위가 포함되어 있는지 확인하세요
- 페이지와 데이터베이스가 인증된 통합에 공유되어 있는지 확인하세요
**잘못된 페이지 및 블록 ID**
- 페이지 ID 및 블록 ID가 올바른 UUID 형식인지 다시 확인하세요
- 참조되는 페이지와 블록이 존재하고 접근 가능한지 확인하세요
- 새 페이지를 생성할 때 상위 페이지 또는 데이터베이스 ID가 유효한지 검증하세요
**속성 스키마 문제**
- 데이터베이스에 페이지를 생성할 때 페이지 속성이 데이터베이스 스키마와 일치하는지 확인하세요
- 대상 데이터베이스에 대해 속성 이름과 타입이 올바른지 확인하세요
- 페이지를 생성하거나 업데이트할 때 필수 속성이 포함되어 있는지 확인하세요
**콘텐츠 블록 구조**
- 블록 콘텐츠가 Notion의 리치 텍스트 형식 사양을 따르는지 확인하세요
- 중첩된 블록 구조가 올바르게 포맷되어 있는지 확인하세요
- 미디어 URL이 접근 가능하며 올바른 형식인지 확인하세요
**검색 및 필터 문제**
- 검색 쿼리가 올바르게 포맷되어 있고 비어 있지 않은지 확인하세요
- 필터 공식에서 유효한 필드명을 사용하세요: `query`, `filter.value`, `direction`, `page_size`
- 복잡한 필터 조건을 만들기 전에 간단한 검색을 테스트하세요
**상위-하위 관계**
- 하위 페이지를 생성하기 전에 상위 페이지 또는 데이터베이스가 존재하는지 확인하세요
- 상위 컨테이너에 대한 적절한 권한이 있는지 확인하세요
- 데이터베이스 스키마가 설정하려는 속성을 허용하는지 확인하세요
**리치 텍스트 및 미디어 콘텐츠**
- 외부 이미지, PDF, 북마크의 URL이 접근 가능한지 확인하세요
- 리치 텍스트 포매팅이 Notion의 API 사양을 따르는지 확인하세요
- 코드 블록의 언어 타입이 Notion에서 지원되는지 확인하세요
**아카이브 및 삭제 작업**
- 아카이브(복구 가능)와 삭제(영구적)의 차이를 이해하세요
- 대상 콘텐츠를 아카이브 또는 삭제할 수 있는 권한이 있는지 확인하세요
- 여러 페이지 또는 블록에 영향을 줄 수 있는 대량 작업은 신중히 진행하세요
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Notion 연동 설정 또는 문제 해결에 대해 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,632 @@
---
title: Salesforce 통합
description: "CrewAI를 위한 Salesforce 통합을 통한 CRM 및 영업 자동화."
icon: "salesforce"
---
## 개요
에이전트가 Salesforce를 통해 고객 관계, 영업 프로세스 및 데이터를 관리할 수 있도록 합니다. 레코드를 생성 및 업데이트하고, 리드와 기회를 관리하며, SOQL 쿼리를 실행하고, AI 기반 자동화로 CRM 워크플로를 간소화하세요.
## 사전 준비 사항
Salesforce 통합을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 Salesforce 계정
- [통합 페이지](https://app.crewai.com/integrations)를 통해 Salesforce 계정 연결
## 사용 가능한 도구
### **레코드 관리**
<AccordionGroup>
<Accordion title="SALESFORCE_CREATE_RECORD_CONTACT">
**설명:** Salesforce에서 새로운 Contact 레코드를 생성합니다.
**파라미터:**
- `FirstName` (string, 선택): 이름
- `LastName` (string, 필수): 성 - 이 필드는 필수입니다
- `accountId` (string, 선택): Account ID - 이 Contact가 소속된 Account
- `Email` (string, 선택): 이메일 주소
- `Title` (string, 선택): 담당자의 직함(예: CEO 또는 Vice President 등)
- `Description` (string, 선택): Contact에 대한 설명
- `additionalFields` (object, 선택): 사용자 정의 Contact 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_LEAD">
**설명:** Salesforce에서 새로운 Lead 레코드를 생성합니다.
**파라미터:**
- `FirstName` (string, 선택): 이름
- `LastName` (string, 필수): 성 - 이 필드는 필수입니다
- `Company` (string, 필수): 회사명 - 이 필드는 필수입니다
- `Email` (string, 선택): 이메일 주소
- `Phone` (string, 선택): 전화번호
- `Website` (string, 선택): 웹사이트 URL
- `Title` (string, 선택): 담당자의 직함(예: CEO 또는 Vice President 등)
- `Status` (string, 선택): 리드 상태 - 리드 상태를 선택하려면 Connect Portal Workflow 설정을 사용하세요
- `Description` (string, 선택): Lead에 대한 설명
- `additionalFields` (object, 선택): 사용자 정의 Lead 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_OPPORTUNITY">
**설명:** Salesforce에서 새로운 Opportunity 레코드를 생성합니다.
**파라미터:**
- `Name` (string, 필수): Opportunity 이름 - 이 필드는 필수입니다
- `StageName` (string, 선택): Opportunity 단계 - 단계를 선택하려면 Connect Portal Workflow 설정을 사용하세요
- `CloseDate` (string, 선택): 마감일(YYYY-MM-DD 형식) - 기본값은 현재 날짜로부터 30일 이후
- `AccountId` (string, 선택): 이 Opportunity가 소속된 Account
- `Amount` (string, 선택): 예상 전체 판매 금액
- `Description` (string, 선택): Opportunity에 대한 설명
- `OwnerId` (string, 선택): 이 Opportunity를 담당하는 Salesforce 사용자
- `NextStep` (string, 선택): Opportunity 마감을 위한 다음 작업의 설명
- `additionalFields` (object, 선택): 사용자 정의 Opportunity 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_TASK">
**설명:** Salesforce에서 새로운 Task 레코드를 생성합니다.
**파라미터:**
- `whatId` (string, 선택): 관련 ID - 이 Task가 관련된 Account 또는 Opportunity의 ID
- `whoId` (string, 선택): 이름 ID - 이 Task가 관련된 Contact 또는 Lead의 ID
- `subject` (string, 필수): 작업 제목
- `activityDate` (string, 선택): 작업 날짜(YYYY-MM-DD 형식)
- `description` (string, 선택): Task에 대한 설명
- `taskSubtype` (string, 필수): Task 하위 유형 - 선택 항목: task, email, listEmail, call
- `Status` (string, 선택): 상태 - 선택 항목: Not Started, In Progress, Completed
- `ownerId` (string, 선택): 담당자 ID - 이 Task를 담당하는 Salesforce 사용자
- `callDurationInSeconds` (string, 선택): 통화 시간(초)
- `isReminderSet` (boolean, 선택): 알림 설정 여부
- `reminderDateTime` (string, 선택): 알림 날짜/시간(ISO 형식)
- `additionalFields` (object, 선택): 사용자 정의 Task 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_ACCOUNT">
**설명:** Salesforce에서 새로운 Account 레코드를 생성합니다.
**파라미터:**
- `Name` (string, 필수): Account 이름 - 이 필드는 필수입니다
- `OwnerId` (string, 선택): 이 Account를 담당하는 Salesforce 사용자
- `Website` (string, 선택): 웹사이트 URL
- `Phone` (string, 선택): 전화번호
- `Description` (string, 선택): Account 설명
- `additionalFields` (object, 선택): 사용자 정의 Account 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_ANY">
**설명:** Salesforce에서 모든 오브젝트 유형의 레코드를 생성합니다.
**참고:** 이 기능은 사용자 정의 또는 알려지지 않은 오브젝트 유형의 레코드를 생성할 때 유연하게 사용할 수 있습니다.
</Accordion>
</AccordionGroup>
### **레코드 업데이트**
<AccordionGroup>
<Accordion title="SALESFORCE_UPDATE_RECORD_CONTACT">
**설명:** Salesforce에서 기존 연락처(Contact) 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 레코드의 ID
- `FirstName` (string, 선택): 이름
- `LastName` (string, 선택): 성
- `accountId` (string, 선택): 계정 ID - 연락처가 속한 계정
- `Email` (string, 선택): 이메일 주소
- `Title` (string, 선택): 연락처의 직함
- `Description` (string, 선택): 연락처에 대한 설명
- `additionalFields` (object, 선택): 커스텀 연락처 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_LEAD">
**설명:** Salesforce에서 기존 리드(Lead) 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 레코드의 ID
- `FirstName` (string, 선택): 이름
- `LastName` (string, 선택): 성
- `Company` (string, 선택): 회사명
- `Email` (string, 선택): 이메일 주소
- `Phone` (string, 선택): 전화번호
- `Website` (string, 선택): 웹사이트 URL
- `Title` (string, 선택): 연락처의 직함
- `Status` (string, 선택): 리드 상태
- `Description` (string, 선택): 리드에 대한 설명
- `additionalFields` (object, 선택): 커스텀 리드 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_OPPORTUNITY">
**설명:** Salesforce에서 기존 기회(Opportunity) 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 레코드의 ID
- `Name` (string, 선택): 기회명
- `StageName` (string, 선택): 기회 단계
- `CloseDate` (string, 선택): 마감 날짜 (YYYY-MM-DD 형식)
- `AccountId` (string, 선택): 기회가 속한 계정
- `Amount` (string, 선택): 예상 총 판매 금액
- `Description` (string, 선택): 기회에 대한 설명
- `OwnerId` (string, 선택): 이 기회를 담당하는 Salesforce 사용자
- `NextStep` (string, 선택): 기회 마감을 위한 다음 작업의 설명
- `additionalFields` (object, 선택): 커스텀 기회 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_TASK">
**설명:** Salesforce에서 기존 작업(Task) 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 레코드의 ID
- `whatId` (string, 선택): 관련 ID - 이 작업이 연결된 계정 또는 기회의 ID
- `whoId` (string, 선택): 이름 ID - 이 작업이 연결된 연락처 또는 리드의 ID
- `subject` (string, 선택): 작업의 주제
- `activityDate` (string, 선택): 활동 날짜 (YYYY-MM-DD 형식)
- `description` (string, 선택): 작업에 대한 설명
- `Status` (string, 선택): 상태 - 옵션: Not Started, In Progress, Completed
- `ownerId` (string, 선택): 담당자 ID - 이 작업을 할당받은 Salesforce 사용자
- `callDurationInSeconds` (string, 선택): 통화 시간(초)
- `isReminderSet` (boolean, 선택): 알림 설정 여부
- `reminderDateTime` (string, 선택): 알림 날짜/시간 (ISO 형식)
- `additionalFields` (object, 선택): 커스텀 작업 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_ACCOUNT">
**설명:** Salesforce에서 기존 계정(Account) 레코드를 업데이트합니다.
**파라미터:**
- `recordId` (string, 필수): 업데이트할 레코드의 ID
- `Name` (string, 선택): 계정 이름
- `OwnerId` (string, 선택): 이 계정에 할당된 Salesforce 사용자
- `Website` (string, 선택): 웹사이트 URL
- `Phone` (string, 선택): 전화번호
- `Description` (string, 선택): 계정 설명
- `additionalFields` (object, 선택): 커스텀 계정 필드를 위한 JSON 형식의 추가 필드
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_ANY">
**설명:** Salesforce에서 어떤 객체 유형이든 레코드를 업데이트합니다.
**참고:** 이는 커스텀 또는 미확인 객체 유형의 레코드 업데이트를 위한 유연한 도구입니다.
</Accordion>
</AccordionGroup>
### **레코드 조회**
<AccordionGroup>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_CONTACT">
**설명:** ID로 Contact 레코드를 조회합니다.
**파라미터:**
- `recordId` (string, 필수): Contact의 레코드 ID
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_LEAD">
**설명:** ID로 Lead 레코드를 조회합니다.
**파라미터:**
- `recordId` (string, 필수): Lead의 레코드 ID
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_OPPORTUNITY">
**설명:** ID로 Opportunity 레코드를 조회합니다.
**파라미터:**
- `recordId` (string, 필수): Opportunity의 레코드 ID
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_TASK">
**설명:** ID로 Task 레코드를 조회합니다.
**파라미터:**
- `recordId` (string, 필수): Task의 레코드 ID
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_ACCOUNT">
**설명:** ID로 Account 레코드를 조회합니다.
**파라미터:**
- `recordId` (string, 필수): Account의 레코드 ID
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_ANY">
**설명:** ID로 임의 객체 유형의 레코드를 조회합니다.
**파라미터:**
- `recordType` (string, 필수): 레코드 유형 (예: "CustomObject__c")
- `recordId` (string, 필수): 레코드 ID
</Accordion>
</AccordionGroup>
### **레코드 검색**
<AccordionGroup>
<Accordion title="SALESFORCE_SEARCH_RECORDS_CONTACT">
**설명:** 고급 필터링으로 연락처(Contact) 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 필드별 연산자가 지정된 분리적 정규형(Disjunctive Normal Form)의 고급 필터
- `sortBy` (string, 선택): 정렬 기준 필드 (예: "CreatedDate")
- `sortDirection` (string, 선택): 정렬 방향 - 옵션: ASC, DESC
- `includeAllFields` (boolean, 선택): 결과에 모든 필드를 포함
- `paginationParameters` (object, 선택): pageCursor를 포함한 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_LEAD">
**설명:** 고급 필터링으로 리드(Lead) 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 필드별 연산자가 지정된 분리적 정규형의 고급 필터
- `sortBy` (string, 선택): 정렬 기준 필드 (예: "CreatedDate")
- `sortDirection` (string, 선택): 정렬 방향 - 옵션: ASC, DESC
- `includeAllFields` (boolean, 선택): 결과에 모든 필드를 포함
- `paginationParameters` (object, 선택): pageCursor를 포함한 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_OPPORTUNITY">
**설명:** 고급 필터링으로 기회(Opportunity) 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 필드별 연산자가 지정된 분리적 정규형의 고급 필터
- `sortBy` (string, 선택): 정렬 기준 필드 (예: "CreatedDate")
- `sortDirection` (string, 선택): 정렬 방향 - 옵션: ASC, DESC
- `includeAllFields` (boolean, 선택): 결과에 모든 필드를 포함
- `paginationParameters` (object, 선택): pageCursor를 포함한 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_TASK">
**설명:** 고급 필터링으로 작업(Task) 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 필드별 연산자가 지정된 분리적 정규형의 고급 필터
- `sortBy` (string, 선택): 정렬 기준 필드 (예: "CreatedDate")
- `sortDirection` (string, 선택): 정렬 방향 - 옵션: ASC, DESC
- `includeAllFields` (boolean, 선택): 결과에 모든 필드를 포함
- `paginationParameters` (object, 선택): pageCursor를 포함한 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_ACCOUNT">
**설명:** 고급 필터링으로 계정(Account) 레코드를 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 필드별 연산자가 지정된 분리적 정규형의 고급 필터
- `sortBy` (string, 선택): 정렬 기준 필드 (예: "CreatedDate")
- `sortDirection` (string, 선택): 정렬 방향 - 옵션: ASC, DESC
- `includeAllFields` (boolean, 선택): 결과에 모든 필드를 포함
- `paginationParameters` (object, 선택): pageCursor를 포함한 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_ANY">
**설명:** 모든 오브젝트 유형의 레코드를 검색합니다.
**파라미터:**
- `recordType` (string, 필수): 검색할 레코드 유형
- `filterFormula` (string, 선택): 필터 검색 조건
- `includeAllFields` (boolean, 선택): 결과에 모든 필드를 포함
- `paginationParameters` (object, 선택): pageCursor를 포함한 페이지네이션 설정
</Accordion>
</AccordionGroup>
### **리스트 뷰 조회**
<AccordionGroup>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_CONTACT">
**설명:** 특정 리스트 뷰에서 Contact 레코드를 가져옵니다.
**파라미터:**
- `listViewId` (string, 필수): 리스트 뷰 ID
- `paginationParameters` (object, 선택): pageCursor와 함께 사용하는 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_LEAD">
**설명:** 특정 리스트 뷰에서 Lead 레코드를 가져옵니다.
**파라미터:**
- `listViewId` (string, 필수): 리스트 뷰 ID
- `paginationParameters` (object, 선택): pageCursor와 함께 사용하는 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_OPPORTUNITY">
**설명:** 특정 리스트 뷰에서 Opportunity 레코드를 가져옵니다.
**파라미터:**
- `listViewId` (string, 필수): 리스트 뷰 ID
- `paginationParameters` (object, 선택): pageCursor와 함께 사용하는 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_TASK">
**설명:** 특정 리스트 뷰에서 Task 레코드를 가져옵니다.
**파라미터:**
- `listViewId` (string, 필수): 리스트 뷰 ID
- `paginationParameters` (object, 선택): pageCursor와 함께 사용하는 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_ACCOUNT">
**설명:** 특정 리스트 뷰에서 Account 레코드를 가져옵니다.
**파라미터:**
- `listViewId` (string, 필수): 리스트 뷰 ID
- `paginationParameters` (object, 선택): pageCursor와 함께 사용하는 페이지네이션 설정
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_ANY">
**설명:** 특정 리스트 뷰에서 임의의 객체 유형의 레코드를 가져옵니다.
**파라미터:**
- `recordType` (string, 필수): 레코드 유형
- `listViewId` (string, 필수): 리스트 뷰 ID
- `paginationParameters` (object, 선택): pageCursor와 함께 사용하는 페이지네이션 설정
</Accordion>
</AccordionGroup>
### **커스텀 필드**
<AccordionGroup>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_CONTACT">
**설명:** Contact 오브젝트에 대한 커스텀 필드를 배포합니다.
**파라미터:**
- `label` (string, 필수): 표시 및 내부 참조를 위한 필드 라벨
- `type` (string, 필수): 필드 유형 - 옵션: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
- `defaultCheckboxValue` (boolean, 선택): 체크박스 필드의 기본값
- `length` (string, 필수): 숫자/텍스트 필드의 길이
- `decimalPlace` (string, 필수): 숫자 필드의 소수 자릿수
- `pickListValues` (string, 필수): 피클리스트 필드의 값(줄바꿈으로 구분)
- `visibleLines` (string, 필수): 멀티셀렉트/텍스트 영역 필드의 표시 줄 수
- `description` (string, 선택): 필드 설명
- `helperText` (string, 선택): 마우스를 올렸을 때 표시되는 도움말 텍스트
- `defaultFieldValue` (string, 선택): 필드의 기본값
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_LEAD">
**설명:** Lead 오브젝트에 대한 커스텀 필드를 배포합니다.
**파라미터:**
- `label` (string, 필수): 표시 및 내부 참조를 위한 필드 라벨
- `type` (string, 필수): 필드 유형 - 옵션: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
- `defaultCheckboxValue` (boolean, 선택): 체크박스 필드의 기본값
- `length` (string, 필수): 숫자/텍스트 필드의 길이
- `decimalPlace` (string, 필수): 숫자 필드의 소수 자릿수
- `pickListValues` (string, 필수): 피클리스트 필드의 값(줄바꿈으로 구분)
- `visibleLines` (string, 필수): 멀티셀렉트/텍스트 영역 필드의 표시 줄 수
- `description` (string, 선택): 필드 설명
- `helperText` (string, 선택): 마우스를 올렸을 때 표시되는 도움말 텍스트
- `defaultFieldValue` (string, 선택): 필드의 기본값
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_OPPORTUNITY">
**설명:** Opportunity 오브젝트에 대한 커스텀 필드를 배포합니다.
**파라미터:**
- `label` (string, 필수): 표시 및 내부 참조를 위한 필드 라벨
- `type` (string, 필수): 필드 유형 - 옵션: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
- `defaultCheckboxValue` (boolean, 선택): 체크박스 필드의 기본값
- `length` (string, 필수): 숫자/텍스트 필드의 길이
- `decimalPlace` (string, 필수): 숫자 필드의 소수 자릿수
- `pickListValues` (string, 필수): 피클리스트 필드의 값(줄바꿈으로 구분)
- `visibleLines` (string, 필수): 멀티셀렉트/텍스트 영역 필드의 표시 줄 수
- `description` (string, 선택): 필드 설명
- `helperText` (string, 선택): 마우스를 올렸을 때 표시되는 도움말 텍스트
- `defaultFieldValue` (string, 선택): 필드의 기본값
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_TASK">
**설명:** Task 오브젝트에 대한 커스텀 필드를 배포합니다.
**파라미터:**
- `label` (string, 필수): 표시 및 내부 참조를 위한 필드 라벨
- `type` (string, 필수): 필드 유형 - 옵션: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, Time, Url
- `defaultCheckboxValue` (boolean, 선택): 체크박스 필드의 기본값
- `length` (string, 필수): 숫자/텍스트 필드의 길이
- `decimalPlace` (string, 필수): 숫자 필드의 소수 자릿수
- `pickListValues` (string, 필수): 피클리스트 필드의 값(줄바꿈으로 구분)
- `visibleLines` (string, 필수): 멀티셀렉트 필드의 표시 줄 수
- `description` (string, 선택): 필드 설명
- `helperText` (string, 선택): 마우스를 올렸을 때 표시되는 도움말 텍스트
- `defaultFieldValue` (string, 선택): 필드의 기본값
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_ACCOUNT">
**설명:** Account 오브젝트에 대한 커스텀 필드를 배포합니다.
**파라미터:**
- `label` (string, 필수): 표시 및 내부 참조를 위한 필드 라벨
- `type` (string, 필수): 필드 유형 - 옵션: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
- `defaultCheckboxValue` (boolean, 선택): 체크박스 필드의 기본값
- `length` (string, 필수): 숫자/텍스트 필드의 길이
- `decimalPlace` (string, 필수): 숫자 필드의 소수 자릿수
- `pickListValues` (string, 필수): 피클리스트 필드의 값(줄바꿈으로 구분)
- `visibleLines` (string, 필수): 멀티셀렉트/텍스트 영역 필드의 표시 줄 수
- `description` (string, 선택): 필드 설명
- `helperText` (string, 선택): 마우스를 올렸을 때 표시되는 도움말 텍스트
- `defaultFieldValue` (string, 선택): 필드의 기본값
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_ANY">
**설명:** 모든 오브젝트 타입에 대한 커스텀 필드를 배포합니다.
**참고:** 커스텀 또는 미지의 오브젝트 타입에 커스텀 필드를 생성할 수 있는 유연한 도구입니다.
</Accordion>
</AccordionGroup>
### **고급 작업**
<AccordionGroup>
<Accordion title="SALESFORCE_WRITE_SOQL_QUERY">
**설명:** Salesforce 데이터에 대해 커스텀 SOQL 쿼리를 실행합니다.
**파라미터:**
- `query` (string, 필수): SOQL 쿼리 (예: "SELECT Id, Name FROM Account WHERE Name = 'Example'")
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_OBJECT">
**설명:** Salesforce에 새로운 커스텀 오브젝트를 배포합니다.
**파라미터:**
- `label` (string, 필수): 탭, 페이지 레이아웃, 리포트에 사용되는 오브젝트 라벨
- `pluralLabel` (string, 필수): 복수형 라벨 (예: "Accounts")
- `description` (string, 선택): 커스텀 오브젝트에 대한 설명
- `recordName` (string, 필수): 레이아웃과 검색에 표시되는 레코드 이름 (예: "Account Name")
</Accordion>
<Accordion title="SALESFORCE_DESCRIBE_ACTION_SCHEMA">
**설명:** 특정 오브젝트 타입에 대한 작업의 예상 스키마를 가져옵니다.
**파라미터:**
- `recordType` (string, 필수): 설명할 레코드 타입
- `operation` (string, 필수): 작업 타입 (예: "CREATE_RECORD" 또는 "UPDATE_RECORD")
**참고:** 커스텀 오브젝트 작업 시, 해당 스키마를 이해하기 위해 제일 먼저 이 기능을 사용하세요.
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Salesforce 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Salesforce tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Salesforce capabilities
salesforce_agent = Agent(
role="CRM Manager",
goal="Manage customer relationships and sales processes efficiently",
backstory="An AI assistant specialized in CRM operations and sales automation.",
tools=[enterprise_tools]
)
# Task to create a new lead
create_lead_task = Task(
description="Create a new lead for John Doe from Example Corp with email john.doe@example.com",
agent=salesforce_agent,
expected_output="Lead created successfully with lead ID"
)
# Run the task
crew = Crew(
agents=[salesforce_agent],
tasks=[create_lead_task]
)
crew.kickoff()
```
### 특정 Salesforce 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Salesforce tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["salesforce_create_record_lead", "salesforce_update_record_opportunity", "salesforce_search_records_contact"]
)
sales_manager = Agent(
role="Sales Manager",
goal="Manage leads and opportunities in the sales pipeline",
backstory="An experienced sales manager who handles lead qualification and opportunity management.",
tools=enterprise_tools
)
# Task to manage sales pipeline
pipeline_task = Task(
description="Create a qualified lead and convert it to an opportunity with $50,000 value",
agent=sales_manager,
expected_output="Lead created and opportunity established successfully"
)
crew = Crew(
agents=[sales_manager],
tasks=[pipeline_task]
)
crew.kickoff()
```
### 연락처 및 계정 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
account_manager = Agent(
role="Account Manager",
goal="Manage customer accounts and maintain strong relationships",
backstory="An AI assistant that specializes in account management and customer relationship building.",
tools=[enterprise_tools]
)
# Task to manage customer accounts
account_task = Task(
description="""
1. Create a new account for TechCorp Inc.
2. Add John Doe as the primary contact for this account
3. Create a follow-up task for next week to check on their project status
""",
agent=account_manager,
expected_output="Account, contact, and follow-up task created successfully"
)
crew = Crew(
agents=[account_manager],
tasks=[account_task]
)
crew.kickoff()
```
### 고급 SOQL 쿼리 및 리포팅
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
data_analyst = Agent(
role="Sales Data Analyst",
goal="Generate insights from Salesforce data using SOQL queries",
backstory="An analytical AI that excels at extracting meaningful insights from CRM data.",
tools=[enterprise_tools]
)
# Complex task involving SOQL queries and data analysis
analysis_task = Task(
description="""
1. Execute a SOQL query to find all opportunities closing this quarter
2. Search for contacts at companies with opportunities over $100K
3. Create a summary report of the sales pipeline status
4. Update high-value opportunities with next steps
""",
agent=data_analyst,
expected_output="Comprehensive sales pipeline analysis with actionable insights"
)
crew = Crew(
agents=[data_analyst],
tasks=[analysis_task]
)
crew.kickoff()
```
이 포괄적인 문서는 모든 Salesforce 도구를 기능별로 정리하여, 사용자가 CRM 자동화 작업에 필요한 특정 작업을 쉽게 찾을 수 있도록 도와줍니다.
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Salesforce 통합 설정 또는 문제 해결에 대해 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,382 @@
---
title: Shopify 연동
description: "CrewAI를 위한 Shopify 연동을 통한 전자상거래 및 온라인 스토어 관리."
icon: "shopify"
---
## 개요
에이전트가 Shopify를 통해 전자상거래 운영을 관리할 수 있게 하세요. 고객, 주문, 제품, 재고 및 스토어 분석을 처리하여 AI 기반 자동화를 통해 온라인 비즈니스를 간소화할 수 있습니다.
## 사전 요구 사항
Shopify 연동을 사용하기 전에 다음을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 관리자 권한이 있는 Shopify 스토어
- [통합 페이지](https://app.crewai.com/integrations)를 통해 Shopify 스토어 연결
## 사용 가능한 도구
### **고객 관리**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_CUSTOMERS">
**설명:** Shopify 스토어에서 고객 목록을 조회합니다.
**파라미터:**
- `customerIds` (string, 선택): 필터링할 고객 ID의 쉼표로 구분된 목록 (예: "207119551, 207119552")
- `createdAtMin` (string, 선택): 이 날짜 이후에 생성된 고객만 반환 (ISO 또는 Unix 타임스탬프)
- `createdAtMax` (string, 선택): 이 날짜 이전에 생성된 고객만 반환 (ISO 또는 Unix 타임스탬프)
- `updatedAtMin` (string, 선택): 이 날짜 이후에 업데이트된 고객만 반환 (ISO 또는 Unix 타임스탬프)
- `updatedAtMax` (string, 선택): 이 날짜 이전에 업데이트된 고객만 반환 (ISO 또는 Unix 타임스탬프)
- `limit` (string, 선택): 반환할 최대 고객 수 (기본값 250)
</Accordion>
<Accordion title="SHOPIFY_SEARCH_CUSTOMERS">
**설명:** 고급 필터링 기준을 사용하여 고객을 검색합니다.
**파라미터:**
- `filterFormula` (object, 선택): 필드별 연산자가 포함된 불리언 합정규형의 고급 필터
- `limit` (string, 선택): 반환할 최대 고객 수 (기본값 250)
</Accordion>
<Accordion title="SHOPIFY_CREATE_CUSTOMER">
**설명:** Shopify 스토어에 새로운 고객을 생성합니다.
**파라미터:**
- `firstName` (string, 필수): 고객의 이름
- `lastName` (string, 필수): 고객의 성
- `email` (string, 필수): 고객의 이메일 주소
- `company` (string, 선택): 회사명
- `streetAddressLine1` (string, 선택): 거리 주소
- `streetAddressLine2` (string, 선택): 거리 주소 2
- `city` (string, 선택): 도시
- `state` (string, 선택): 주 또는 도 코드
- `country` (string, 선택): 국가
- `zipCode` (string, 선택): 우편번호
- `phone` (string, 선택): 전화번호
- `tags` (string, 선택): 배열 또는 쉼표로 구분된 태그 목록
- `note` (string, 선택): 고객 메모
- `sendEmailInvite` (boolean, 선택): 이메일 초대장 전송 여부
- `metafields` (object, 선택): 추가 메타필드(JSON 형식)
</Accordion>
<Accordion title="SHOPIFY_UPDATE_CUSTOMER">
**설명:** Shopify 스토어에 기존 고객을 업데이트합니다.
**파라미터:**
- `customerId` (string, 필수): 업데이트할 고객의 ID
- `firstName` (string, 선택): 고객의 이름
- `lastName` (string, 선택): 고객의 성
- `email` (string, 선택): 고객의 이메일 주소
- `company` (string, 선택): 회사명
- `streetAddressLine1` (string, 선택): 거리 주소
- `streetAddressLine2` (string, 선택): 거리 주소 2
- `city` (string, 선택): 도시
- `state` (string, 선택): 주 또는 도 코드
- `country` (string, 선택): 국가
- `zipCode` (string, 선택): 우편번호
- `phone` (string, 선택): 전화번호
- `tags` (string, 선택): 배열 또는 쉼표로 구분된 태그 목록
- `note` (string, 선택): 고객 메모
- `sendEmailInvite` (boolean, 선택): 이메일 초대장 전송 여부
- `metafields` (object, 선택): 추가 메타필드(JSON 형식)
</Accordion>
</AccordionGroup>
### **주문 관리**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_ORDERS">
**설명:** Shopify 스토어에서 주문 목록을 조회합니다.
**파라미터:**
- `orderIds` (string, optional): 필터링할 주문 ID의 콤마로 구분된 목록 (예: "450789469, 450789470")
- `createdAtMin` (string, optional): 이 날짜 이후에 생성된 주문만 반환 (ISO 또는 Unix 타임스탬프)
- `createdAtMax` (string, optional): 이 날짜 이전에 생성된 주문만 반환 (ISO 또는 Unix 타임스탬프)
- `updatedAtMin` (string, optional): 이 날짜 이후에 업데이트된 주문만 반환 (ISO 또는 Unix 타임스탬프)
- `updatedAtMax` (string, optional): 이 날짜 이전에 업데이트된 주문만 반환 (ISO 또는 Unix 타임스탬프)
- `limit` (string, optional): 반환할 주문의 최대 개수 (기본값: 250)
</Accordion>
<Accordion title="SHOPIFY_CREATE_ORDER">
**설명:** Shopify 스토어에 새 주문을 생성합니다.
**파라미터:**
- `email` (string, required): 고객 이메일 주소
- `lineItems` (object, required): title, price, quantity, variant_id가 포함된 JSON 형식의 주문 아이템
- `sendReceipt` (boolean, optional): 주문 영수증을 발송할지 여부
- `fulfillmentStatus` (string, optional): 주문 이행 상태 - 옵션: fulfilled, null, partial, restocked
- `financialStatus` (string, optional): 결제 상태 - 옵션: pending, authorized, partially_paid, paid, partially_refunded, refunded, voided
- `inventoryBehaviour` (string, optional): 인벤토리 동작 - 옵션: bypass, decrement_ignoring_policy, decrement_obeying_policy
- `note` (string, optional): 주문 메모
</Accordion>
<Accordion title="SHOPIFY_UPDATE_ORDER">
**설명:** Shopify 스토어에서 기존 주문을 업데이트합니다.
**파라미터:**
- `orderId` (string, required): 업데이트할 주문의 ID
- `email` (string, optional): 고객 이메일 주소
- `lineItems` (object, optional): JSON 형식의 업데이트된 주문 아이템
- `sendReceipt` (boolean, optional): 주문 영수증을 발송할지 여부
- `fulfillmentStatus` (string, optional): 주문 이행 상태 - 옵션: fulfilled, null, partial, restocked
- `financialStatus` (string, optional): 결제 상태 - 옵션: pending, authorized, partially_paid, paid, partially_refunded, refunded, voided
- `inventoryBehaviour` (string, optional): 인벤토리 동작 - 옵션: bypass, decrement_ignoring_policy, decrement_obeying_policy
- `note` (string, optional): 주문 메모
</Accordion>
<Accordion title="SHOPIFY_GET_ABANDONED_CARTS">
**설명:** Shopify 스토어에서 방치된 장바구니를 조회합니다.
**파라미터:**
- `createdWithInLast` (string, optional): 지정된 기간 내에 생성된 체크아웃 결과만 제한
- `createdAfterId` (string, optional): 지정된 ID 이후 결과로 제한
- `status` (string, optional): 주어진 상태의 체크아웃만 표시 - 옵션: open, closed (기본값: open)
- `createdAtMin` (string, optional): 이 날짜 이후에 생성된 장바구니만 반환 (ISO 또는 Unix 타임스탬프)
- `createdAtMax` (string, optional): 이 날짜 이전에 생성된 장바구니만 반환 (ISO 또는 Unix 타임스탬프)
- `limit` (string, optional): 반환할 장바구니의 최대 개수 (기본값: 250)
</Accordion>
</AccordionGroup>
### **제품 관리 (REST API)**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_PRODUCTS">
**설명:** REST API를 사용하여 Shopify 스토어에서 제품 목록을 조회합니다.
**파라미터:**
- `productIds` (string, optional): 필터링할 제품 ID의 콤마(,)로 구분된 목록 (예: "632910392, 632910393")
- `title` (string, optional): 제품 제목으로 필터링
- `productType` (string, optional): 제품 유형으로 필터링
- `vendor` (string, optional): 공급업체로 필터링
- `status` (string, optional): 상태별 필터링 - 옵션: active, archived, draft
- `createdAtMin` (string, optional): 해당 날짜(ISO 혹은 Unix 타임스탬프) 이후에 생성된 제품만 반환
- `createdAtMax` (string, optional): 해당 날짜(ISO 혹은 Unix 타임스탬프) 이전에 생성된 제품만 반환
- `updatedAtMin` (string, optional): 해당 날짜(ISO 혹은 Unix 타임스탬프) 이후에 수정된 제품만 반환
- `updatedAtMax` (string, optional): 해당 날짜(ISO 혹은 Unix 타임스탬프) 이전에 수정된 제품만 반환
- `limit` (string, optional): 반환할 최대 제품 수 (기본값: 250)
</Accordion>
<Accordion title="SHOPIFY_CREATE_PRODUCT">
**설명:** REST API를 사용하여 Shopify 스토어에 새로운 제품을 생성합니다.
**파라미터:**
- `title` (string, required): 제품 제목
- `productType` (string, required): 제품 유형/카테고리
- `vendor` (string, required): 제품 공급업체
- `productDescription` (string, optional): 제품 설명 (일반 텍스트 또는 HTML 가능)
- `tags` (string, optional): 배열 또는 콤마(,)로 구분된 태그 목록
- `price` (string, optional): 제품 가격
- `inventoryPolicy` (string, optional): 재고 정책 - 옵션: deny, continue
- `imageUrl` (string, optional): 제품 이미지 URL
- `isPublished` (boolean, optional): 제품 공개 여부
- `publishToPointToSale` (boolean, optional): 포인트 오브 세일(Point of Sale)에 공개 여부
</Accordion>
<Accordion title="SHOPIFY_UPDATE_PRODUCT">
**설명:** REST API를 사용하여 Shopify 스토어의 기존 제품을 업데이트합니다.
**파라미터:**
- `productId` (string, required): 업데이트할 제품 ID
- `title` (string, optional): 제품 제목
- `productType` (string, optional): 제품 유형/카테고리
- `vendor` (string, optional): 제품 공급업체
- `productDescription` (string, optional): 제품 설명 (일반 텍스트 또는 HTML 가능)
- `tags` (string, optional): 배열 또는 콤마(,)로 구분된 태그 목록
- `price` (string, optional): 제품 가격
- `inventoryPolicy` (string, optional): 재고 정책 - 옵션: deny, continue
- `imageUrl` (string, optional): 제품 이미지 URL
- `isPublished` (boolean, optional): 제품 공개 여부
- `publishToPointToSale` (boolean, optional): 포인트 오브 세일(Point of Sale)에 공개 여부
</Accordion>
</AccordionGroup>
### **제품 관리 (GraphQL)**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_PRODUCTS_GRAPHQL">
**설명:** 고급 GraphQL 필터링 기능을 사용하여 제품을 조회합니다.
**파라미터:**
- `productFilterFormula` (object, 선택): id, title, vendor, status, handle, tag, created_at, updated_at, published_at와 같은 필드를 지원하는 불리언 정규합형(DNF) 기반의 고급 필터
</Accordion>
<Accordion title="SHOPIFY_CREATE_PRODUCT_GRAPHQL">
**설명:** 미디어 지원이 강화된 GraphQL API를 사용하여 새 제품을 생성합니다.
**파라미터:**
- `title` (string, 필수): 제품 제목
- `productType` (string, 필수): 제품 유형/카테고리
- `vendor` (string, 필수): 제품 공급업체
- `productDescription` (string, 선택): 제품 설명 (일반 텍스트 또는 HTML 허용)
- `tags` (string, 선택): 배열 또는 쉼표로 구분된 리스트 형태의 제품 태그
- `media` (object, 선택): 대체 텍스트, 콘텐츠 유형 및 소스 URL을 가진 미디어 객체
- `additionalFields` (object, 선택): status, requiresSellingPlan, giftCard와 같은 추가 제품 필드
</Accordion>
<Accordion title="SHOPIFY_UPDATE_PRODUCT_GRAPHQL">
**설명:** 미디어 지원이 강화된 GraphQL API를 사용하여 기존 제품을 업데이트합니다.
**파라미터:**
- `productId` (string, 필수): 업데이트할 제품의 GraphQL ID (예: "gid://shopify/Product/913144112")
- `title` (string, 선택): 제품 제목
- `productType` (string, 선택): 제품 유형/카테고리
- `vendor` (string, 선택): 제품 공급업체
- `productDescription` (string, 선택): 제품 설명 (일반 텍스트 또는 HTML 허용)
- `tags` (string, 선택): 배열 또는 쉼표로 구분된 리스트 형태의 제품 태그
- `media` (object, 선택): 대체 텍스트, 콘텐츠 유형 및 소스 URL을 포함한 업데이트된 미디어 객체
- `additionalFields` (object, 선택): status, requiresSellingPlan, giftCard와 같은 추가 제품 필드
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Shopify 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Shopify tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Shopify capabilities
shopify_agent = Agent(
role="E-commerce Manager",
goal="Manage online store operations and customer relationships efficiently",
backstory="An AI assistant specialized in e-commerce operations and online store management.",
tools=[enterprise_tools]
)
# Task to create a new customer
create_customer_task = Task(
description="Create a new VIP customer Jane Smith with email jane.smith@example.com and phone +1-555-0123",
agent=shopify_agent,
expected_output="Customer created successfully with customer ID"
)
# Run the task
crew = Crew(
agents=[shopify_agent],
tasks=[create_customer_task]
)
crew.kickoff()
```
### 특정 Shopify 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Shopify tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["shopify_create_customer", "shopify_create_order", "shopify_get_products"]
)
store_manager = Agent(
role="Store Manager",
goal="Manage customer orders and product catalog",
backstory="An experienced store manager who handles customer relationships and inventory management.",
tools=enterprise_tools
)
# Task to manage store operations
store_task = Task(
description="Create a new customer and process their order for 2 Premium Coffee Mugs",
agent=store_manager,
expected_output="Customer created and order processed successfully"
)
crew = Crew(
agents=[store_manager],
tasks=[store_task]
)
crew.kickoff()
```
### GraphQL을 활용한 제품 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
product_manager = Agent(
role="Product Manager",
goal="Manage product catalog and inventory with advanced GraphQL capabilities",
backstory="An AI assistant that specializes in product management and catalog optimization.",
tools=[enterprise_tools]
)
# Task to manage product catalog
catalog_task = Task(
description="""
1. Coffee Co 공급업체의 신규 제품 "Premium Coffee Mug"을(를) 생성하세요.
2. 고품질 제품 이미지와 설명을 추가하세요.
3. 동일한 공급업체의 유사 제품을 검색하세요.
4. 제품 태그와 가격 전략을 업데이트하세요.
""",
agent=product_manager,
expected_output="Product created and catalog optimized successfully"
)
crew = Crew(
agents=[product_manager],
tasks=[catalog_task]
)
crew.kickoff()
```
### 주문 및 고객 분석
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
analytics_agent = Agent(
role="E-commerce Analyst",
goal="Analyze customer behavior and order patterns to optimize store performance",
backstory="An analytical AI that excels at extracting insights from e-commerce data.",
tools=[enterprise_tools]
)
# Complex task involving multiple operations
analytics_task = Task(
description="""
1. 최근 고객 데이터 및 주문 내역 조회
2. 최근 7일간의 장바구니 이탈 식별
3. 상품 성과 및 재고 수준 분석
4. 고객 유지를 위한 추천 사항 생성
""",
agent=analytics_agent,
expected_output="실행 가능한 인사이트를 제공하는 종합 이커머스 분석 보고서"
)
crew = Crew(
agents=[analytics_agent],
tasks=[analytics_task]
)
crew.kickoff()
```
### 도움 받기
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Shopify 연동 설정 또는 문제 해결에 관한 지원이 필요하시면 고객 지원팀에 문의해 주세요.
</Card>

View File

@@ -0,0 +1,293 @@
---
title: Slack 연동
description: "CrewAI를 위한 Slack 연동으로 팀 커뮤니케이션 및 협업 지원."
icon: "slack"
---
## 개요
에이전트가 Slack을 통해 팀 커뮤니케이션을 관리할 수 있도록 지원합니다. 메시지를 보내고, 대화를 검색하며, 채널을 관리하고, AI 기반 자동화를 통해 팀 활동을 조율하여 협업 워크플로우를 효율적으로 최적화하세요.
## 사전 준비 사항
Slack 통합을 사용하기 전에 다음을 확인하십시오:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 권한이 있는 Slack 워크스페이스
- [통합 페이지](https://app.crewai.com/integrations)를 통해 Slack 워크스페이스를 연결함
## 사용 가능한 도구
### **사용자 관리**
<AccordionGroup>
<Accordion title="SLACK_LIST_MEMBERS">
**설명:** Slack 채널의 모든 멤버를 나열합니다.
**파라미터:**
- 파라미터 없음 - 모든 채널 멤버를 조회합니다
</Accordion>
<Accordion title="SLACK_GET_USER_BY_EMAIL">
**설명:** 이메일 주소로 Slack 워크스페이스에서 사용자를 찾습니다.
**파라미터:**
- `email` (string, 필수): 워크스페이스 내 사용자의 이메일 주소
</Accordion>
<Accordion title="SLACK_GET_USERS_BY_NAME">
**설명:** 이름 또는 표시 이름으로 사용자를 검색합니다.
**파라미터:**
- `name` (string, 필수): 검색할 사용자의 실제 이름
- `displayName` (string, 필수): 검색할 사용자의 표시 이름
- `paginationParameters` (object, 선택): 페이지네이션 설정
- `pageCursor` (string, 선택): 페이지네이션을 위한 페이지 커서
</Accordion>
</AccordionGroup>
### **채널 관리**
<AccordionGroup>
<Accordion title="SLACK_LIST_CHANNELS">
**설명:** Slack 워크스페이스의 모든 채널을 나열합니다.
**파라미터:**
- 파라미터가 필요하지 않습니다 - 접근 가능한 모든 채널을 조회합니다
</Accordion>
</AccordionGroup>
### **메시징**
<AccordionGroup>
<Accordion title="SLACK_SEND_MESSAGE">
**설명:** Slack 채널에 메시지를 전송합니다.
**파라미터:**
- `channel` (string, 필수): 채널 이름 또는 ID - Connect Portal Workflow Settings를 사용하여 사용자가 채널을 선택하도록 하거나, 채널 이름을 입력하여 새 채널을 생성할 수 있습니다.
- `message` (string, 필수): 전송할 메시지 텍스트
- `botName` (string, 필수): 이 메시지를 전송하는 봇의 이름
- `botIcon` (string, 필수): 봇 아이콘 - 이미지 URL 또는 이모지(e.g., ":dog:") 모두 가능합니다.
- `blocks` (object, 선택): 첨부파일 및 인터랙티브 요소 등이 포함된 풍부한 메시지 포맷팅을 위한 Slack Block Kit JSON
- `authenticatedUser` (boolean, 선택): true이면 메시지가 애플리케이션이 아니라 인증된 Slack 사용자로부터 보낸 것처럼 표시됩니다(기본값은 false)
</Accordion>
<Accordion title="SLACK_SEND_DIRECT_MESSAGE">
**설명:** Slack에서 특정 사용자에게 다이렉트 메시지를 전송합니다.
**파라미터:**
- `memberId` (string, 필수): 수신자 사용자 ID - Connect Portal Workflow Settings를 사용하여 사용자가 워크스페이스 멤버를 선택하도록 합니다.
- `message` (string, 필수): 전송할 메시지 텍스트
- `botName` (string, 필수): 이 메시지를 전송하는 봇의 이름
- `botIcon` (string, 필수): 봇 아이콘 - 이미지 URL 또는 이모지(e.g., ":dog:") 모두 가능합니다.
- `blocks` (object, 선택): 첨부파일 및 인터랙티브 요소 등이 포함된 풍부한 메시지 포맷팅을 위한 Slack Block Kit JSON
- `authenticatedUser` (boolean, 선택): true이면 메시지가 애플리케이션이 아니라 인증된 Slack 사용자로부터 보낸 것처럼 표시됩니다(기본값은 false)
</Accordion>
</AccordionGroup>
### **검색 및 탐색**
<AccordionGroup>
<Accordion title="SLACK_SEARCH_MESSAGES">
**설명:** Slack 워크스페이스 전체에서 메시지를 검색합니다.
**매개변수:**
- `query` (string, 필수): 지정된 기준과 일치하는 메시지를 찾기 위해 Slack 검색 구문을 사용한 검색 쿼리
**검색 쿼리 예시:**
- `"project update"` - "project update"가 포함된 메시지 검색
- `from:@john in:#general` - #general 채널에서 John이 보낸 메시지 검색
- `has:link after:2023-01-01` - 2023년 1월 1일 이후에 링크가 포함된 메시지 검색
- `in:@channel before:yesterday` - 특정 채널에서 어제 이전에 작성된 메시지 검색
</Accordion>
</AccordionGroup>
## Block Kit 통합
Slack의 Block Kit을 사용하면 풍부하고 상호작용이 가능한 메시지를 생성할 수 있습니다. 다음은 `blocks` 매개변수를 사용하는 방법에 대한 몇 가지 예시입니다:
### 첨부 파일이 있는 간단한 텍스트
```json
[
{
"text": "I am a test message",
"attachments": [
{
"text": "And here's an attachment!"
}
]
}
]
```
### 섹션을 활용한 리치 포매팅
```json
[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*프로젝트 업데이트*\n상태: ✅ 완료"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "모든 작업이 성공적으로 완료되었습니다."
}
}
]
```
## 사용 예시
### 기본 Slack 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Slack tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Slack capabilities
slack_agent = Agent(
role="Team Communication Manager",
goal="Facilitate team communication and coordinate collaboration efficiently",
backstory="An AI assistant specialized in team communication and workspace coordination.",
tools=[enterprise_tools]
)
# Task to send project updates
update_task = Task(
description="Send a project status update to the #general channel with current progress",
agent=slack_agent,
expected_output="Project update message sent successfully to team channel"
)
# Run the task
crew = Crew(
agents=[slack_agent],
tasks=[update_task]
)
crew.kickoff()
```
### 특정 Slack 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Slack tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["slack_send_message", "slack_send_direct_message", "slack_search_messages"]
)
communication_manager = Agent(
role="Communication Coordinator",
goal="Manage team communications and ensure important messages reach the right people",
backstory="An experienced communication coordinator who handles team messaging and notifications.",
tools=enterprise_tools
)
# Task to coordinate team communication
coordination_task = Task(
description="Send task completion notifications to team members and update project channels",
agent=communication_manager,
expected_output="Team notifications sent and project channels updated successfully"
)
crew = Crew(
agents=[communication_manager],
tasks=[coordination_task]
)
crew.kickoff()
```
### Block Kit을 활용한 고급 메시징
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
notification_agent = Agent(
role="Notification Manager",
goal="Create rich, interactive notifications and manage workspace communication",
backstory="An AI assistant that specializes in creating engaging team notifications and updates.",
tools=[enterprise_tools]
)
# Task to send rich notifications
notification_task = Task(
description="""
1. Send a formatted project completion message to #general with progress charts
2. Send direct messages to team leads with task summaries
3. Create interactive notification with action buttons for team feedback
""",
agent=notification_agent,
expected_output="Rich notifications sent with interactive elements and formatted content"
)
crew = Crew(
agents=[notification_agent],
tasks=[notification_task]
)
crew.kickoff()
```
### 메시지 검색 및 분석
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
analytics_agent = Agent(
role="Communication Analyst",
goal="Analyze team communication patterns and extract insights from conversations",
backstory="An analytical AI that excels at understanding team dynamics through communication data.",
tools=[enterprise_tools]
)
# Complex task involving search and analysis
analysis_task = Task(
description="""
1. 모든 채널에서 최근 프로젝트 관련 메시지 검색
2. 이메일로 사용자를 찾아 팀 구성원 식별
3. 커뮤니케이션 패턴 및 응답 시간 분석
4. 주간 팀 커뮤니케이션 요약 생성
""",
agent=analytics_agent,
expected_output="팀 인사이트 및 권장사항이 포함된 종합적인 커뮤니케이션 분석"
)
crew = Crew(
agents=[analytics_agent],
tasks=[analysis_task]
)
crew.kickoff()
```
## 지원 문의
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
Slack 연동 설정 또는 문제 해결에 대해 지원팀에 문의하세요.
</Card>

View File

@@ -0,0 +1,305 @@
---
title: Stripe 연동
description: "CrewAI를 위한 Stripe 연동을 통한 결제 처리 및 구독 관리."
icon: "stripe"
---
## 개요
에이전트가 Stripe를 통해 결제, 구독 및 고객 청구 관리를 할 수 있도록 지원합니다. 고객 데이터 처리, 구독 관리, 상품 관리, 재무 거래 추적 등을 통해 AI 기반 자동화로 결제 워크플로를 효율화하세요.
## 사전 준비 사항
Stripe 통합을 사용하기 전에 다음 사항을 확인하세요:
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 API 권한이 있는 Stripe 계정
- [통합 페이지](https://app.crewai.com/integrations)를 통해 Stripe 계정 연결
## 사용 가능한 도구
### **고객 관리**
<AccordionGroup>
<Accordion title="STRIPE_CREATE_CUSTOMER">
**설명:** Stripe 계정에 새로운 고객을 생성합니다.
**파라미터:**
- `emailCreateCustomer` (string, 필수): 고객의 이메일 주소
- `name` (string, 선택): 고객의 전체 이름
- `description` (string, 선택): 내부 참조용 고객 설명
- `metadataCreateCustomer` (object, 선택): 추가 메타데이터를 key-value 쌍으로 입력 (예: `{"field1": 1, "field2": 2}`)
</Accordion>
<Accordion title="STRIPE_GET_CUSTOMER_BY_ID">
**설명:** Stripe 고객 ID로 특정 고객을 조회합니다.
**파라미터:**
- `idGetCustomer` (string, 필수): 조회할 Stripe 고객 ID
</Accordion>
<Accordion title="STRIPE_GET_CUSTOMERS">
**설명:** 필터링 옵션과 함께 고객 리스트를 조회합니다.
**파라미터:**
- `emailGetCustomers` (string, 선택): 이메일 주소로 고객 필터링
- `createdAfter` (string, 선택): 이 날짜 이후 생성된 고객 필터링 (유닉스 타임스탬프)
- `createdBefore` (string, 선택): 이 날짜 이전 생성된 고객 필터링 (유닉스 타임스탬프)
- `limitGetCustomers` (string, 선택): 반환할 최대 고객 수 (기본값 10)
</Accordion>
<Accordion title="STRIPE_UPDATE_CUSTOMER">
**설명:** 기존 고객의 정보를 업데이트합니다.
**파라미터:**
- `customerId` (string, 필수): 업데이트할 고객의 ID
- `emailUpdateCustomer` (string, 선택): 업데이트할 이메일 주소
- `name` (string, 선택): 업데이트할 고객 이름
- `description` (string, 선택): 업데이트할 고객 설명
- `metadataUpdateCustomer` (object, 선택): 업데이트할 메타데이터를 key-value 쌍으로 입력
</Accordion>
</AccordionGroup>
### **구독 관리**
<AccordionGroup>
<Accordion title="STRIPE_CREATE_SUBSCRIPTION">
**설명:** 고객을 위한 새로운 구독을 생성합니다.
**파라미터:**
- `customerIdCreateSubscription` (string, 필수): 구독이 생성될 고객 ID
- `plan` (string, 필수): 구독을 위한 플랜 ID - 사용자가 플랜을 선택할 수 있도록 Connect Portal Workflow Settings를 사용하세요
- `metadataCreateSubscription` (object, 선택): 구독에 대한 추가 메타데이터
</Accordion>
<Accordion title="STRIPE_GET_SUBSCRIPTIONS">
**설명:** 선택적 필터링으로 구독을 조회합니다.
**파라미터:**
- `customerIdGetSubscriptions` (string, 선택): 고객 ID로 구독을 필터링
- `subscriptionStatus` (string, 선택): 구독 상태별 필터링 - 옵션: incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid
- `limitGetSubscriptions` (string, 선택): 반환할 구독의 최대 개수(기본값은 10)
</Accordion>
</AccordionGroup>
### **제품 관리**
<AccordionGroup>
<Accordion title="STRIPE_CREATE_PRODUCT">
**설명:** Stripe 카탈로그에 새 제품을 생성합니다.
**파라미터:**
- `productName` (string, 필수): 제품 이름
- `description` (string, 선택): 제품 설명
- `metadataProduct` (object, 선택): 키-값 쌍으로 구성된 추가 제품 메타데이터
</Accordion>
<Accordion title="STRIPE_GET_PRODUCT_BY_ID">
**설명:** Stripe 제품 ID로 특정 제품을 조회합니다.
**파라미터:**
- `productId` (string, 필수): 조회할 Stripe 제품 ID
</Accordion>
<Accordion title="STRIPE_GET_PRODUCTS">
**설명:** 선택적 필터링을 통해 제품 목록을 조회합니다.
**파라미터:**
- `createdAfter` (string, 선택): 이 날짜 이후 생성된 제품만 필터링 (Unix 타임스탬프)
- `createdBefore` (string, 선택): 이 날짜 이전 생성된 제품만 필터링 (Unix 타임스탬프)
- `limitGetProducts` (string, 선택): 반환할 최대 제품 수 (기본값 10)
</Accordion>
</AccordionGroup>
### **금융 운영**
<AccordionGroup>
<Accordion title="STRIPE_GET_BALANCE_TRANSACTIONS">
**설명:** Stripe 계정에서 잔액 거래를 조회합니다.
**매개변수:**
- `balanceTransactionType` (string, 선택 사항): 거래 유형별 필터 - 옵션: charge, refund, payment, payment_refund
- `paginationParameters` (object, 선택 사항): 페이지네이션 설정
- `pageCursor` (string, 선택 사항): 페이지네이션을 위한 페이지 커서
</Accordion>
<Accordion title="STRIPE_GET_PLANS">
**설명:** Stripe 계정에서 구독 플랜을 조회합니다.
**매개변수:**
- `isPlanActive` (boolean, 선택 사항): 플랜 상태별 필터 - true는 활성 플랜, false는 비활성 플랜
- `paginationParameters` (object, 선택 사항): 페이지네이션 설정
- `pageCursor` (string, 선택 사항): 페이지네이션을 위한 페이지 커서
</Accordion>
</AccordionGroup>
## 사용 예시
### 기본 Stripe 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Stripe tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Stripe capabilities
stripe_agent = Agent(
role="Payment Manager",
goal="Manage customer payments, subscriptions, and billing operations efficiently",
backstory="An AI assistant specialized in payment processing and subscription management.",
tools=[enterprise_tools]
)
# Task to create a new customer
create_customer_task = Task(
description="Create a new premium customer John Doe with email john.doe@example.com",
agent=stripe_agent,
expected_output="Customer created successfully with customer ID"
)
# Run the task
crew = Crew(
agents=[stripe_agent],
tasks=[create_customer_task]
)
crew.kickoff()
```
### 특정 Stripe 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Stripe tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["stripe_create_customer", "stripe_create_subscription", "stripe_get_balance_transactions"]
)
billing_manager = Agent(
role="Billing Manager",
goal="Handle customer billing, subscriptions, and payment processing",
backstory="An experienced billing manager who handles subscription lifecycle and payment operations.",
tools=enterprise_tools
)
# Task to manage billing operations
billing_task = Task(
description="Create a new customer and set up their premium subscription plan",
agent=billing_manager,
expected_output="Customer created and subscription activated successfully"
)
crew = Crew(
agents=[billing_manager],
tasks=[billing_task]
)
crew.kickoff()
```
### 구독 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
subscription_manager = Agent(
role="Subscription Manager",
goal="Manage customer subscriptions and optimize recurring revenue",
backstory="An AI assistant that specializes in subscription lifecycle management and customer retention.",
tools=[enterprise_tools]
)
# Task to manage subscription operations
subscription_task = Task(
description="""
1. 고급 기능이 포함된 새로운 제품 "Premium Service Plan" 생성
2. 다양한 등급의 구독 플랜 설정
3. 고객을 생성하고 적절한 플랜에 할당
4. 구독 상태를 모니터링하고 결제 문제 처리
""",
agent=subscription_manager,
expected_output="고객과 활성 플랜이 구성된 구독 관리 시스템"
)
crew = Crew(
agents=[subscription_manager],
tasks=[subscription_task]
)
crew.kickoff()
```
### 금융 분석 및 보고
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
financial_analyst = Agent(
role="Financial Analyst",
goal="Analyze payment data and generate financial insights",
backstory="An analytical AI that excels at extracting insights from payment and subscription data.",
tools=[enterprise_tools]
)
# Complex task involving financial analysis
analytics_task = Task(
description="""
1. Retrieve balance transactions for the current month
2. Analyze customer payment patterns and subscription trends
3. Identify high-value customers and subscription performance
4. Generate monthly financial performance report
""",
agent=financial_analyst,
expected_output="Comprehensive financial analysis with payment insights and recommendations"
)
crew = Crew(
agents=[financial_analyst],
tasks=[analytics_task]
)
crew.kickoff()
```
## 구독 상태 참조
구독 상태 이해하기:
- **incomplete** - 결제 수단 또는 결제 확인이 필요한 구독
- **incomplete_expired** - 결제가 확인되기 전에 만료된 구독
- **trialing** - 체험 기간 중인 구독
- **active** - 활성화되어 현재 사용 중인 구독
- **past_due** - 결제에 실패했지만 여전히 활성화된 구독
- **canceled** - 취소된 구독
- **unpaid** - 결제에 실패하여 더 이상 활성화되지 않은 구독
## 메타데이터 사용
메타데이터를 사용하면 고객, 구독, 제품에 대한 추가 정보를 저장할 수 있습니다:
```json
{
"customer_segment": "enterprise",
"acquisition_source": "google_ads",
"lifetime_value": "high",
"custom_field_1": "value1"
}
```
이 통합을 통해 결제 및 구독 관리 자동화를 포괄적으로 구현할 수 있으며, AI 에이전트가 Stripe 생태계 내에서 청구 작업을 원활하게 처리할 수 있습니다.

View File

@@ -0,0 +1,343 @@
---
title: Zendesk 통합
description: "CrewAI를 위한 Zendesk 통합으로 고객 지원 및 헬프데스크 관리."
icon: "headset"
---
## 개요
에이전트가 Zendesk를 통해 고객 지원 운영을 관리할 수 있도록 지원합니다. 티켓 생성 및 업데이트, 사용자 관리, 지원 지표 추적, 그리고 AI 기반 자동화를 통해 고객 서비스 워크플로우를 간소화할 수 있습니다.
## 사전 준비 사항
Zendesk 통합을 사용하기 전에 다음을 확인하세요.
- 활성 구독이 있는 [CrewAI Enterprise](https://app.crewai.com) 계정
- 적절한 API 권한이 있는 Zendesk 계정
- [통합 페이지](https://app.crewai.com/integrations)를 통해 Zendesk 계정 연결
## 사용 가능한 도구
### **티켓 관리**
<AccordionGroup>
<Accordion title="ZENDESK_CREATE_TICKET">
**설명:** Zendesk에 새로운 지원 티켓을 생성합니다.
**매개변수:**
- `ticketSubject` (string, 필수): 티켓 제목 줄 (예: "도와주세요, 프린터에 불이 났어요!")
- `ticketDescription` (string, 필수): 티켓에 표시될 첫 번째 댓글 (예: "연기가 정말 화려하네요.")
- `requesterName` (string, 필수): 지원 요청자의 이름 (예: "Jane Customer")
- `requesterEmail` (string, 필수): 지원 요청자의 이메일 (예: "jane@example.com")
- `assigneeId` (string, 선택): 이 티켓에 할당된 Zendesk 에이전트 ID - 사용자가 담당자를 선택할 수 있도록 Connect Portal Workflow Settings 를 사용하세요
- `ticketType` (string, 선택): 티켓 유형 - 옵션: problem, incident, question, task
- `ticketPriority` (string, 선택): 우선순위 수준 - 옵션: urgent, high, normal, low
- `ticketStatus` (string, 선택): 티켓 상태 - 옵션: new, open, pending, hold, solved, closed
- `ticketDueAt` (string, 선택): task 유형 티켓의 마감일 (ISO 8601 타임스탬프)
- `ticketTags` (string, 선택): 적용할 태그 배열 (예: `["enterprise", "other_tag"]`)
- `ticketExternalId` (string, 선택): 티켓을 로컬 레코드와 연결할 외부 ID
- `ticketCustomFields` (object, 선택): JSON 형식의 사용자 정의 필드 값
</Accordion>
<Accordion title="ZENDESK_UPDATE_TICKET">
**설명:** Zendesk의 기존 지원 티켓을 업데이트합니다.
**매개변수:**
- `ticketId` (string, 필수): 업데이트할 티켓의 ID (예: "35436")
- `ticketSubject` (string, 선택): 업데이트된 티켓 제목
- `requesterName` (string, 필수): 이 티켓을 요청한 사용자의 이름
- `requesterEmail` (string, 필수): 이 티켓을 요청한 사용자의 이메일
- `assigneeId` (string, 선택): 업데이트된 담당자 ID - Connect Portal Workflow Settings 를 사용하세요
- `ticketType` (string, 선택): 업데이트된 티켓 유형 - 옵션: problem, incident, question, task
- `ticketPriority` (string, 선택): 업데이트된 우선순위 - 옵션: urgent, high, normal, low
- `ticketStatus` (string, 선택): 업데이트된 상태 - 옵션: new, open, pending, hold, solved, closed
- `ticketDueAt` (string, 선택): 업데이트된 마감일 (ISO 8601 타임스탬프)
- `ticketTags` (string, 선택): 업데이트된 태그 배열
- `ticketExternalId` (string, 선택): 업데이트된 외부 ID
- `ticketCustomFields` (object, 선택): 업데이트된 사용자 정의 필드 값
</Accordion>
<Accordion title="ZENDESK_GET_TICKET_BY_ID">
**설명:** ID로 특정 티켓을 조회합니다.
**매개변수:**
- `ticketId` (string, 필수): 조회할 티켓의 ID (예: "35436")
</Accordion>
<Accordion title="ZENDESK_ADD_COMMENT_TO_TICKET">
**설명:** 기존 티켓에 댓글이나 내부 노트를 추가합니다.
**매개변수:**
- `ticketId` (string, 필수): 댓글을 추가할 티켓의 ID (예: "35436")
- `commentBody` (string, 필수): 댓글 메시지 (일반 텍스트 또는 HTML 지원, 예: "도움을 주셔서 감사합니다!")
- `isInternalNote` (boolean, 선택): 공개 답글 대신 내부 노트로 설정하려면 true (기본값: false)
- `isPublic` (boolean, 선택): 공개 댓글이면 true, 내부 노트이면 false
</Accordion>
<Accordion title="ZENDESK_SEARCH_TICKETS">
**설명:** 다양한 필터 및 조건을 사용하여 티켓을 검색합니다.
**매개변수:**
- `ticketSubject` (string, 선택): 티켓 제목 내 텍스트로 필터링
- `ticketDescription` (string, 선택): 티켓 설명 및 댓글 내 텍스트로 필터링
- `ticketStatus` (string, 선택): 상태로 필터링 - 옵션: new, open, pending, hold, solved, closed
- `ticketType` (string, 선택): 유형으로 필터링 - 옵션: problem, incident, question, task, no_type
- `ticketPriority` (string, 선택): 우선순위로 필터링 - 옵션: urgent, high, normal, low, no_priority
- `requesterId` (string, 선택): 요청자 사용자 ID로 필터링
- `assigneeId` (string, 선택): 담당 에이전트 ID로 필터링
- `recipientEmail` (string, 선택): 원래 수신자 이메일 주소로 필터링
- `ticketTags` (string, 선택): 티켓 태그로 필터링
- `ticketExternalId` (string, 선택): 외부 ID로 필터링
- `createdDate` (object, 선택): 생성일로 필터링 (연산자: EQUALS, LESS_THAN_EQUALS, GREATER_THAN_EQUALS, 값)
- `updatedDate` (object, 선택): 업데이트 날짜로 필터링 (연산자와 값)
- `dueDate` (object, 선택): 마감일로 필터링 (연산자와 값)
- `sort_by` (string, 선택): 정렬 필드 - 옵션: created_at, updated_at, priority, status, ticket_type
- `sort_order` (string, 선택): 정렬 방향 - 옵션: asc, desc
</Accordion>
</AccordionGroup>
### **사용자 관리**
<AccordionGroup>
<Accordion title="ZENDESK_CREATE_USER">
**설명:** Zendesk에서 새로운 사용자를 생성합니다.
**매개변수:**
- `name` (string, 필수): 사용자의 전체 이름
- `email` (string, 선택): 사용자의 이메일 주소 (예: "jane@example.com")
- `phone` (string, 선택): 사용자의 전화번호
- `role` (string, 선택): 사용자 역할 - 옵션: admin, agent, end-user
- `externalId` (string, 선택): 다른 시스템의 고유 식별자
- `details` (string, 선택): 추가 사용자 정보
- `notes` (string, 선택): 사용자에 대한 내부 메모
</Accordion>
<Accordion title="ZENDESK_UPDATE_USER">
**설명:** 기존 사용자의 정보를 업데이트합니다.
**매개변수:**
- `userId` (string, 필수): 업데이트할 사용자의 ID
- `name` (string, 선택): 업데이트할 사용자 이름
- `email` (string, 선택): 업데이트할 이메일 (업데이트 시 보조 이메일로 추가됨)
- `phone` (string, 선택): 업데이트할 전화번호
- `role` (string, 선택): 업데이트할 역할 - 옵션: admin, agent, end-user
- `externalId` (string, 선택): 업데이트된 외부 ID
- `details` (string, 선택): 업데이트된 사용자 상세 정보
- `notes` (string, 선택): 업데이트된 내부 메모
</Accordion>
<Accordion title="ZENDESK_GET_USER_BY_ID">
**설명:** ID로 특정 사용자를 조회합니다.
**매개변수:**
- `userId` (string, 필수): 조회할 사용자 ID
</Accordion>
<Accordion title="ZENDESK_SEARCH_USERS">
**설명:** 다양한 기준으로 사용자를 검색합니다.
**매개변수:**
- `name` (string, 선택): 사용자 이름으로 필터링
- `email` (string, 선택): 사용자 이메일로 필터링 (예: "jane@example.com")
- `role` (string, 선택): 역할로 필터링 - 옵션: admin, agent, end-user
- `externalId` (string, 선택): 외부 ID로 필터링
- `sort_by` (string, 선택): 정렬 필드 - 옵션: created_at, updated_at
- `sort_order` (string, 선택): 정렬 방향 - 옵션: asc, desc
</Accordion>
</AccordionGroup>
### **관리 도구**
<AccordionGroup>
<Accordion title="ZENDESK_GET_TICKET_FIELDS">
**설명:** 티켓에 사용할 수 있는 모든 표준 및 맞춤 필드를 검색합니다.
**파라미터:**
- `paginationParameters` (object, 선택 사항): 페이지네이션 설정
- `pageCursor` (string, 선택 사항): 페이지네이션을 위한 페이지 커서
</Accordion>
<Accordion title="ZENDESK_GET_TICKET_AUDITS">
**설명:** 티켓의 감사 기록(읽기 전용 이력)을 가져옵니다.
**파라미터:**
- `ticketId` (string, 선택 사항): 특정 티켓의 감사를 조회합니다(비워두면 모든 비보관된 티켓의 감사를 조회, 예: "1234")
- `paginationParameters` (object, 선택 사항): 페이지네이션 설정
- `pageCursor` (string, 선택 사항): 페이지네이션을 위한 페이지 커서
</Accordion>
</AccordionGroup>
## 커스텀 필드
커스텀 필드를 사용하면 조직에 특화된 추가 정보를 저장할 수 있습니다:
```json
[
{ "id": 27642, "value": "745" },
{ "id": 27648, "value": "yes" }
]
```
## 티켓 우선순위 레벨
우선순위 레벨 이해하기:
- **긴급** - 즉각적인 조치가 필요한 치명적 이슈
- **높음** - 신속하게 해결해야 하는 중요한 이슈
- **보통** - 대부분의 티켓에 해당하는 표준 우선순위
- **낮음** - 여유가 있을 때 처리해도 되는 사소한 이슈
## 티켓 상태 워크플로우
표준 티켓 상태 진행:
- **new** - 최근에 생성됨, 아직 할당되지 않음
- **open** - 현재 작업 중
- **pending** - 고객 응답 또는 외부 조치 대기 중
- **hold** - 일시 중지됨
- **solved** - 문제가 해결되어 고객 확인 대기 중
- **closed** - 티켓이 완료되어 종료됨
## 사용 예시
### 기본 Zendesk 에이전트 설정
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Zendesk tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Zendesk capabilities
zendesk_agent = Agent(
role="Support Manager",
goal="Manage customer support tickets and provide excellent customer service",
backstory="An AI assistant specialized in customer support operations and ticket management.",
tools=[enterprise_tools]
)
# Task to create a new support ticket
create_ticket_task = Task(
description="Create a high-priority support ticket for John Smith who is unable to access his account after password reset",
agent=zendesk_agent,
expected_output="Support ticket created successfully with ticket ID"
)
# Run the task
crew = Crew(
agents=[zendesk_agent],
tasks=[create_ticket_task]
)
crew.kickoff()
```
### 특정 Zendesk 도구 필터링
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Zendesk tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["zendesk_create_ticket", "zendesk_update_ticket", "zendesk_add_comment_to_ticket"]
)
support_agent = Agent(
role="Customer Support Agent",
goal="Handle customer inquiries and resolve support issues efficiently",
backstory="An experienced support agent who specializes in ticket resolution and customer communication.",
tools=enterprise_tools
)
# Task to manage support workflow
support_task = Task(
description="Create a ticket for login issues, add troubleshooting comments, and update status to resolved",
agent=support_agent,
expected_output="Support ticket managed through complete resolution workflow"
)
crew = Crew(
agents=[support_agent],
tasks=[support_task]
)
crew.kickoff()
```
### 고급 티켓 관리
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
ticket_manager = Agent(
role="Ticket Manager",
goal="Manage support ticket workflows and ensure timely resolution",
backstory="An AI assistant that specializes in support ticket triage and workflow optimization.",
tools=[enterprise_tools]
)
# Task to manage ticket lifecycle
ticket_workflow = Task(
description="""
1. 계정 접근 문제에 대한 새로운 지원 티켓을 생성합니다.
2. 문제 해결 단계를 내부 노트에 추가합니다.
3. 고객 등급에 따라 티켓 우선순위를 업데이트합니다.
4. 해결 코멘트를 추가하고 티켓을 종료합니다.
""",
agent=ticket_manager,
expected_output="티켓 생성부터 해결까지 전체 생명주기 관리"
)
crew = Crew(
agents=[ticket_manager],
tasks=[ticket_workflow]
)
crew.kickoff()
```
### 지원 분석 및 보고
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
support_analyst = Agent(
role="Support Analyst",
goal="Analyze support metrics and generate insights for team performance",
backstory="An analytical AI that excels at extracting insights from support data and ticket patterns.",
tools=[enterprise_tools]
)
# Complex task involving analytics and reporting
analytics_task = Task(
description="""
1. Search for all open tickets from the last 30 days
2. Analyze ticket resolution times and customer satisfaction
3. Identify common issues and support patterns
4. Generate weekly support performance report
""",
agent=support_analyst,
expected_output="Comprehensive support analytics report with performance insights and recommendations"
)
crew = Crew(
agents=[support_analyst],
tasks=[analytics_task]
)
crew.kickoff()
```

View File

@@ -0,0 +1,99 @@
---
title: "CrewAI 엔터프라이즈"
description: "AI 에이전트 워크플로우를 배포, 모니터링 및 확장하세요"
icon: "globe"
---
## 소개
CrewAI Enterprise는 프로덕션 환경에서 crew와 agent를 배포, 모니터링, 확장할 수 있는 플랫폼을 제공합니다.
<Frame>
<img src="/images/enterprise/crewai-enterprise-dashboard.png" alt="CrewAI Enterprise Dashboard" />
</Frame>
CrewAI Enterprise는 오픈 소스 프레임워크의 강력함에 프로덕션 배포, 협업, 확장성을 위한 기능을 더했습니다. crew를 관리형 인프라에 배포하고, 실행을 실시간으로 모니터링하세요.
## 주요 기능
<CardGroup cols={2}>
<Card title="Crew Deployments" icon="rocket">
몇 번의 클릭만으로 관리형 인프라에 crew를 배포하세요
</Card>
<Card title="API Access" icon="code">
기존 시스템과의 통합을 위해 REST API를 통해 배포된 crew에 접근하세요
</Card>
<Card title="Observability" icon="chart-line">
상세한 실행 추적과 로그로 crew를 모니터링하세요
</Card>
<Card title="Tool Repository" icon="toolbox">
crew의 역량을 강화할 수 있도록 도구를 게시하고 설치하세요
</Card>
<Card title="Webhook Streaming" icon="webhook">
실시간 이벤트와 업데이트를 시스템으로 스트리밍하세요
</Card>
<Card title="Crew Studio" icon="paintbrush">
노코드/로코드 인터페이스로 crew를 생성 및 커스터마이즈하세요
</Card>
</CardGroup>
## 배포 옵션
<CardGroup cols={3}>
<Card title="GitHub 통합" icon="github">
코드 배포를 위해 GitHub 리포지토리에 직접 연결하세요
</Card>
<Card title="Crew Studio" icon="palette">
코드 없는 Crew Studio 인터페이스를 통해 생성된 crew를 배포하세요
</Card>
<Card title="CLI 배포" icon="terminal">
더 고급 배포 워크플로우를 위해 CrewAI CLI를 사용하세요
</Card>
</CardGroup>
## 시작하기
<Steps>
<Step title="계정 가입하기">
[app.crewai.com](https://app.crewai.com)에서 계정을 생성하세요
<Card
title="가입하기"
icon="user"
href="https://app.crewai.com/signup"
>
가입하기
</Card>
</Step>
<Step title="첫 번째 crew 만들기">
코드 또는 Crew Studio를 사용하여 crew를 만드세요
<Card
title="Crew 만들기"
icon="paintbrush"
href="/ko/enterprise/guides/build-crew"
>
Crew 만들기
</Card>
</Step>
<Step title="crew 배포하기">
crew를 Enterprise 플랫폼에 배포하세요
<Card
title="Crew 배포"
icon="rocket"
href="/ko/enterprise/guides/deploy-crew"
>
Crew 배포
</Card>
</Step>
<Step title="crew에 접근하기">
생성된 API 엔드포인트를 통해 crew와 연동하세요
<Card
title="API 접근"
icon="code"
href="/ko/enterprise/guides/kickoff-crew"
>
Crew API 사용
</Card>
</Step>
</Steps>
자세한 안내를 원하시면 [배포 가이드](/ko/enterprise/guides/deploy-crew)를 확인하거나 아래 버튼을 클릭해 시작하세요.

View File

@@ -0,0 +1,151 @@
---
title: 자주 묻는 질문
description: "CrewAI Enterprise에 대한 자주 묻는 질문"
icon: "circle-question"
---
<AccordionGroup>
<Accordion title="계층적 프로세스에서 작업 실행은 어떻게 처리됩니까?">
계층적 프로세스에서는 매니저 에이전트가 자동으로 생성되어 워크플로우를 조정하고, 작업을 위임하며 결과를 검증하여 효율적이고 체계적으로 작업이 수행되도록 합니다. 매니저 에이전트는 하위 에이전트에게 작업을 위임하고 실행을 지원하기 위해 도구를 활용합니다. 매니저 LLM은 계층적 프로세스에서 매우 중요하며, 적절한 작동을 위해 반드시 올바르게 설정되어야 합니다.
</Accordion>
<Accordion title="가장 최신의 CrewAI 문서는 어디에서 확인할 수 있습니까?">
CrewAI에 대한 최신 문서는 공식 문서 사이트에서 확인하실 수 있습니다: https://docs.crewai.com/
<Card href="https://docs.crewai.com/" icon="books">CrewAI 문서</Card>
</Accordion>
<Accordion title="CrewAI의 계층적 프로세스와 순차적 프로세스의 주요 차이점은 무엇입니까?">
#### 계층적 프로세스:
- 명확한 지휘 체계에 따라 작업이 위임 및 실행됨
- 매니저 에이전트에 대해 manager language model(`manager_llm`)을 반드시 지정해야 함
- 매니저 에이전트가 작업 실행, 계획, 위임, 검증을 총괄함
- 작업이 사전에 지정되지 않으며, 매니저가 각 에이전트의 역량에 따라 작업을 할당함
#### 순차적 프로세스:
- 작업이 순서대로 하나씩 실행되어 작업들이 순차적으로 진행됨
- 이전 작업의 결과가 다음 작업의 맥락이 됨
- 작업 실행이 작업 리스트에 정의된 순서대로 진행됨
#### 복잡한 프로젝트에 더 적합한 프로세스는 무엇입니까?
계층적 프로세스는 다음과 같은 이유로 복잡한 프로젝트에 더 적합합니다:
- **동적 작업 할당과 위임**: 매니저 에이전트가 에이전트의 역량에 따라 작업을 할당할 수 있음
- **구조화된 검증과 감독**: 매니저 에이전트가 작업 결과를 검토하고 완료를 보장함
- **복잡한 작업 관리**: 에이전트 수준에서의 도구 사용 제어 등 세밀한 관리 가능
</Accordion>
<Accordion title="CrewAI 프레임워크에서 메모리를 사용할 때의 이점은 무엇입니까?">
- **적응적 학습**: crew는 시간이 지날수록 더 효율적으로 적응하며, 새로운 정보에 맞춰 작업 방식을 개선하게 됩니다.
- **개인화된 경험 강화**: 메모리를 통해 에이전트가 사용자 선호도나 과거 상호작용을 기억하여 더욱 개인화된 경험을 제공합니다.
- **문제 해결력 향상**: 풍부한 메모리 접근을 통해 과거의 학습이나 맥락적 인사이트를 적용하여 에이전트가 더 나은 결정을 내릴 수 있습니다.
</Accordion>
<Accordion title="에이전트의 최대 RPM 제한을 설정하는 목적은 무엇입니까?">
에이전트의 최대 RPM 제한을 설정하면 외부 서비스에 과도하게 요청을 보내지 않도록 하여, 제한에 걸리는 일을 예방하고 성능을 향상시킬 수 있습니다.
</Accordion>
<Accordion title="CrewAI crew 내에서 작업 실행 시 인간 입력은 어떤 역할을 하나요?">
인간 입력을 통해 에이전트는 필요할 때 추가 정보나 설명을 요청할 수 있습니다. 이 기능은 복잡한 의사결정 과정이나, 에이전트가 작업을 효과적으로 완료하는 데 더 많은 세부 정보가 필요할 때 매우 중요합니다.
에이전트 실행에 인간 입력을 통합하려면 작업 정의에서 `human_input` 플래그를 설정하세요. 활성화하면, 에이전트가 최종 답변을 제공하기 전에 사용자에게 입력을 요청합니다. 이 입력은 추가 맥락을 제공하거나, 애매함을 해소하거나, 에이전트의 출력을 검증해야 할 때 활용될 수 있습니다.
자세한 구현 방법은 [Human-in-the-Loop 가이드](/ko/how-to/human-in-the-loop)를 참고해 주세요.
</Accordion>
<Accordion title="CrewAI에서 에이전트의 행동과 역량을 맞춤화하고 향상시키기 위한 고급 커스터마이징 옵션에는 어떤 것이 있나요?">
CrewAI는 다양한 고급 커스터마이징 옵션을 제공합니다:
- **Language Model 커스터마이징**: 에이전트별로 특정 language model(`llm`) 및 function-calling language model(`function_calling_llm`)을 지정 가능
- **성능 및 디버깅 설정**: 에이전트의 성능을 조정하고 동작을 모니터링할 수 있음
- **Verbose 모드**: 에이전트의 작업 로그를 자세하게 기록하여 디버깅 및 최적화에 활용할 수 있음
- **RPM 제한**: 분당 최대 요청 수(`max_rpm`) 설정
- **최대 반복 횟수**: `max_iter` 속성으로 에이전트가 한 작업에서 허용되는 반복 횟수를 지정
- **위임 및 자율성 제어**: `allow_delegation` 속성(기본값: True)으로 에이전트의 위임 또는 질문 가능 여부 제어
- **인간 입력 통합**: 필요 시 추가 정보나 설명을 사용자에게 요청할 수 있음
</Accordion>
<Accordion title="에이전트 실행 시 어떤 상황에서 인간 입력이 특히 유용합니까?">
인간 입력이 특히 유용한 경우는 다음과 같습니다:
- **에이전트가 추가 정보나 설명이 필요할 때**: 에이전트가 애매하거나 불완전한 데이터를 만날 때
- **에이전트가 복잡하거나 민감한 결정을 내려야 할 때**: 윤리적이거나 미묘한 결정이 필요한 경우 인간 입력이 보조할 수 있음
- **에이전트 출력의 감독 및 검증이 필요할 때**: 결과 검증과 오류 방지에 도움
- **에이전트 행동을 커스터마이징 할 때**: 피드백을 통해 에이전트의 응답을 지속적으로 개선
- **오류 및 한계 식별 및 해결 시**: 에이전트의 한계점이나 오류를 인간 입력으로 해결 가능
</Accordion>
<Accordion title="crewAI에서 사용할 수 있는 메모리의 종류는 무엇입니까?">
CrewAI에서 제공되는 메모리의 종류는 다음과 같습니다:
- **단기 메모리**: 즉각적인 맥락을 위한 임시 저장소
- **장기 메모리**: 학습된 패턴 및 정보의 영구 저장소
- **엔티티 메모리**: 특정 엔티티와 그 속성에 집중하는 저장소
- **컨텍스추얼 메모리**: 상호작용 간 맥락을 유지하는 메모리
다른 메모리 유형에 대해 자세히 알아보려면:
<Card href="https://docs.crewai.com/concepts/memory" icon="brain">CrewAI 메모리</Card>
</Accordion>
<Accordion title="작업에서 Output Pydantic을 사용하는 방법은 무엇입니까?">
작업에서 Output Pydantic을 사용하려면, 해당 작업의 예상 결과를 Pydantic 모델로 정의해야 합니다. 빠른 예시는 다음과 같습니다:
<Steps>
<Step title="Pydantic 모델 정의하기">
```python
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
```
</Step>
<Step title="Output Pydantic으로 작업 생성하기">
```python
from crewai import Task, Crew, Agent
from my_models import User
task = Task(
description="Create a user with the provided name and age",
expected_output=User, # This is the Pydantic model
agent=agent,
tools=[tool1, tool2]
)
```
</Step>
<Step title="에이전트에서 output_pydantic 속성 설정">
```python
from crewai import Agent
from my_models import User
agent = Agent(
role='User Creator',
goal='Create users',
backstory='I am skilled in creating user accounts',
tools=[tool1, tool2],
output_pydantic=User
)
```
</Step>
</Steps>
에이전트가 항상 구조화된 출력을 내도록 만드는 방법 관련 튜토리얼은 아래 영상을 참고하세요:
<Frame>
<iframe
height="400"
width="100%"
src="https://www.youtube.com/embed/dNpKQk5uxHw"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</Frame>
</Accordion>
<Accordion title="CrewAI 에이전트를 위한 커스텀 도구는 어떻게 만들 수 있습니까?">
CrewAI에서 제공하는 `BaseTool` 클래스를 상속받아 커스텀 도구를 직접 만들거나, tool 데코레이터를 활용할 수 있습니다. 상속 방식은 `BaseTool`을 상속하는 새로운 클래스를 정의해 이름, 설명, 그리고 실제 논리를 처리하는 `_run` 메서드를 작성합니다. tool 데코레이터를 사용하면 필수 속성과 운영 로직만 정의해 바로 `Tool` 객체를 만들 수 있습니다.
<Card href="https://docs.crewai.com/how-to/create-custom-tools" icon="code">CrewAI 도구 가이드</Card>
</Accordion>
<Accordion title="전체 crew가 수행할 수 있는 분당 최대 요청 수는 어떻게 제한할 수 있나요?">
`max_rpm` 속성을 설정하면 crew 전체가 분당 보낼 수 있는 최대 요청 수를 제한할 수 있습니다. 이를 설정하면 개별 에이전트의 `max_rpm` 값보다 우선적으로 적용됩니다.
</Accordion>
</AccordionGroup>

View File

@@ -0,0 +1,62 @@
---
title: CrewAI 예시
description: CrewAI 프레임워크를 사용하여 워크플로우를 자동화하는 방법을 보여주는 예시 모음입니다.
icon: rocket-launch
---
<CardGroup cols={3}>
<Card
title="마케팅 전략"
color="#F3A78B"
href="https://github.com/crewAIInc/crewAI-examples/tree/main/marketing_strategy"
icon="bullhorn"
iconType="solid"
>
CrewAI로 마케팅 전략 생성을 자동화하세요.
</Card>
<Card
title="깜짝 여행"
color="#F3A78B"
href="https://github.com/crewAIInc/crewAI-examples/tree/main/surprise_trip"
icon="plane"
iconType="duotone"
>
CrewAI로 깜짝 여행 일정표를 만들어보세요.
</Card>
<Card
title="프로필과 포지션 매칭"
color="#F3A78B"
href="https://github.com/crewAIInc/crewAI-examples/tree/main/match_profile_to_positions"
icon="linkedin"
iconType="duotone"
>
CrewAI로 프로필을 채용 포지션에 매칭하세요.
</Card>
<Card
title="채용 공고 생성"
color="#F3A78B"
href="https://github.com/crewAIInc/crewAI-examples/tree/main/job-posting"
icon="newspaper"
iconType="duotone"
>
CrewAI로 채용 공고를 만드세요.
</Card>
<Card
title="게임 생성기"
color="#F3A78B"
href="https://github.com/crewAIInc/crewAI-examples/tree/main/game-builder-crew"
icon="gamepad"
iconType="duotone"
>
CrewAI로 게임을 만들어보세요.
</Card>
<Card
title="채용 후보자 찾기"
color="#F3A78B"
href="https://github.com/crewAIInc/crewAI-examples/tree/main/recruitment"
icon="user-group"
iconType="duotone"
>
CrewAI로 채용 후보자를 찾으세요.
</Card>
</CardGroup>

View File

@@ -0,0 +1,316 @@
---
title: 프롬프트 커스터마이징
description: CrewAI를 위한 저수준 프롬프트 커스터마이징에 대해 자세히 알아보고, 다양한 모델과 언어에 대해 매우 맞춤화되고 복잡한 사용 사례를 구현할 수 있습니다.
icon: message-pen
---
## 프롬프트를 커스터마이즈해야 하는 이유
CrewAI의 기본 프롬프트는 많은 시나리오에서 잘 작동하지만, 저수준 커스터마이징은 훨씬 더 유연하고 강력한 에이전트 행동으로 이어집니다. 더 깊은 제어를 통해 얻을 수 있는 이점은 다음과 같습니다:
1. **특정 LLM에 맞게 최적화** GPT-4, Claude, Llama와 같은 다양한 모델은 각자의 고유한 아키텍처에 맞는 프롬프트 형식에서 최고의 성능을 발휘합니다.
2. **언어 변경** 영어를 넘어서는 언어로만 작동하는 에이전트를 구축하여 미묘한 뉘앙스도 정확하게 처리할 수 있습니다.
3. **복잡한 도메인에 특화** 헬스케어, 금융, 법률 등 매우 전문적인 산업군에 맞춰 프롬프트를 조정할 수 있습니다.
4. **톤과 스타일 조정** 에이전트의 톤과 스타일을 좀 더 형식적, 캐주얼, 창의적, 혹은 분석적으로 만들 수 있습니다.
5. **초고도 커스텀 사례 지원** 복잡하고 프로젝트에 특화된 요구사항을 충족하기 위해 고급 프롬프트 구조 및 포맷을 활용할 수 있습니다.
이 가이드에서는 CrewAI의 프롬프트를 더 낮은 레벨에서 활용하여, 에이전트의 사고 및 상호작용 방식을 세밀하게 제어하는 방법을 다룹니다.
## CrewAI의 Prompt 시스템 이해하기
내부적으로 CrewAI는 광범위하게 커스터마이즈할 수 있는 모듈식 prompt 시스템을 사용합니다:
- **Agent 템플릿** 각 agent가 할당된 역할을 수행하는 방식을 결정합니다.
- **Prompt 슬라이스** 작업, 도구 사용, 출력 구조와 같은 특수한 동작을 제어합니다.
- **오류 처리** agent가 실패, 예외, 또는 타임아웃에 어떻게 반응할지 지정합니다.
- **도구별 prompt** 도구가 호출되거나 사용되는 방법에 대한 상세 지침을 정의합니다.
이 요소들이 어떻게 구성되어 있는지 보려면 [CrewAI 저장소의 원본 prompt 템플릿](https://github.com/crewAIInc/crewAI/blob/main/src/crewai/translations/en.json)을 확인하세요. 여기서 필요에 따라 오버라이드하거나 수정하여 고급 동작을 구현할 수 있습니다.
## 기본 시스템 지침 이해하기
<Warning>
**프로덕션 투명성 문제**: CrewAI는 여러분이 인지하지 못하는 사이에 기본 지침을 프롬프트에 자동으로 삽입합니다. 이 섹션에서는 내부적으로 어떤 일이 일어나고 있는지와 완전한 제어권을 얻는 방법을 설명합니다.
</Warning>
여러분이 `role`, `goal`, `backstory`로 에이전트를 정의할 때, CrewAI는 형식 및 동작을 제어하는 추가 시스템 지침을 자동으로 추가합니다. 이러한 기본 삽입을 이해하는 것은 완전한 프롬프트 투명성이 필요한 프로덕션 시스템에서 매우 중요합니다.
### CrewAI가 자동으로 삽입하는 내용
에이전트 구성에 따라 CrewAI는 다양한 기본 지침을 추가합니다:
#### 도구가 없는 에이전트를 위한 안내
```text
"I MUST use these formats, my job depends on it!"
```
#### 도구가 있는 에이전트를 위한 안내
```text
"IMPORTANT: Use the following format in your response:
Thought: you should always think about what to do
Action: the action to take, only one name of [tool_names]
Action Input: the input to the action, just a simple JSON object...
```
#### 구조화된 출력(JSON/Pydantic)의 경우
```text
"Ensure your final answer contains only the content in the following format: {output_format}
Ensure the final output does not include any code block markers like ```json or ```python."
```
### 전체 시스템 프롬프트 보기
LLM에 전달되는 프롬프트가 정확히 무엇인지 확인하려면, 생성된 프롬프트를 확인할 수 있습니다:
```python
from crewai import Agent, Crew, Task
from crewai.utilities.prompts import Prompts
# 에이전트 생성
agent = Agent(
role="Data Analyst",
goal="Analyze data and provide insights",
backstory="You are an expert data analyst with 10 years of experience.",
verbose=True
)
# 샘플 태스크 생성
task = Task(
description="Analyze the sales data and identify trends",
expected_output="A detailed analysis with key insights and trends",
agent=agent
)
# 프롬프트 생성기 생성
prompt_generator = Prompts(
agent=agent,
has_tools=len(agent.tools) > 0,
use_system_prompt=agent.use_system_prompt
)
# 실제 프롬프트 생성 및 확인
generated_prompt = prompt_generator.task_execution()
# LLM에 전달될 전체 시스템 프롬프트 출력
if "system" in generated_prompt:
print("=== SYSTEM PROMPT ===")
print(generated_prompt["system"])
print("\n=== USER PROMPT ===")
print(generated_prompt["user"])
else:
print("=== COMPLETE PROMPT ===")
print(generated_prompt["prompt"])
# 태스크 설명이 어떻게 포맷되는지도 확인할 수 있습니다
print("\n=== TASK CONTEXT ===")
print(f"Task Description: {task.description}")
print(f"Expected Output: {task.expected_output}")
```
### 기본 지침 재정의
프롬프트에 대한 완전한 제어를 얻기 위해 여러 가지 옵션이 있습니다:
#### 옵션 1: 커스텀 템플릿 (권장)
```python
from crewai import Agent
# Define your own system template without default instructions
custom_system_template = """You are {role}. {backstory}
Your goal is: {goal}
Respond naturally and conversationally. Focus on providing helpful, accurate information."""
custom_prompt_template = """Task: {input}
Please complete this task thoughtfully."""
agent = Agent(
role="Research Assistant",
goal="Help users find accurate information",
backstory="You are a helpful research assistant.",
system_template=custom_system_template,
prompt_template=custom_prompt_template,
use_system_prompt=True # Use separate system/user messages
)
```
#### 옵션 2: 사용자 지정 프롬프트 파일
특정 프롬프트 슬라이스를 오버라이드하려면 `custom_prompts.json` 파일을 생성하세요:
```json
{
"slices": {
"no_tools": "\nProvide your best answer in a natural, conversational way.",
"tools": "\nYou have access to these tools: {tools}\n\nUse them when helpful, but respond naturally.",
"formatted_task_instructions": "Format your response as: {output_format}"
}
}
```
그런 다음 crew에서 사용하세요:
```python
crew = Crew(
agents=[agent],
tasks=[task],
prompt_file="custom_prompts.json",
verbose=True
)
```
#### 옵션 3: o1 모델에 대한 시스템 프롬프트 비활성화
```python
agent = Agent(
role="Analyst",
goal="Analyze data",
backstory="Expert analyst",
use_system_prompt=False # Disables system prompt separation
)
```
### 관측 도구를 활용한 디버깅
프로덕션 투명성을 위해 관측 플랫폼과 통합하여 모든 prompt 및 LLM 상호작용을 모니터링하세요. 이를 통해 LLM에 어떤 prompt(기본 지침 포함)가 전송되고 있는지 정확히 확인할 수 있습니다.
다양한 플랫폼(Langfuse, MLflow, Weights & Biases, 커스텀 로깅 솔루션 등)과의 통합에 대한 자세한 가이드는 [관측 문서](/ko/observability/overview)를 참고하세요.
### 프로덕션을 위한 모범 사례
1. **프로덕션에 배포하기 전에 반드시 생성된 prompt를 점검하세요**
2. **prompt 내용을 완전히 제어해야 할 경우에는 커스텀 템플릿을 사용하세요**
3. **지속적인 prompt 모니터링을 위해 관측 도구를 통합하세요** ([Observability 문서](/ko/observability/overview) 참고)
4. **서로 다른 LLM으로 테스트하세요**. 기본 instruction은 모델마다 다르게 작동할 수 있습니다
5. **팀 투명성을 위해 prompt 커스터마이징을 문서화하세요**
<Tip>
기본 instruction은 일관된 agent 동작을 보장하기 위해 존재하지만, 도메인 특화 요구사항과 충돌할 수 있습니다. 위의 커스터마이징 옵션을 사용하여 프로덕션 시스템에서 agent의 동작을 완전히 제어할 수 있습니다.
</Tip>
## 프롬프트 파일 관리 모범 사례
저수준 프롬프트 커스터마이징을 수행할 때는 다음 지침을 따라 조직적이고 유지 관리가 용이하도록 하세요:
1. **파일 분리** 커스터마이징한 프롬프트는 메인 코드베이스 외부의 전용 JSON 파일에 저장하세요.
2. **버전 관리** 리포지토리 내에서 변경 사항을 추적하여 프롬프트 조정 내역이 명확히 문서화되도록 하세요.
3. **모델 또는 언어별 정리** `prompts_llama.json` 또는 `prompts_es.json`과 같이 네이밍 스킴을 사용해 특화된 구성을 빠르게 식별할 수 있도록 하세요.
4. **변경 사항 문서화** 주석을 추가하거나 README를 유지 관리하여 커스터마이징의 목적과 범위를 상세히 기술하세요.
5. **수정 최소화** 실제로 조정이 필요한 특정 부분만 오버라이드하고, 나머지 부분은 기본 기능을 유지하세요.
## 프롬프트를 커스터마이즈하는 가장 간단한 방법
가장 간단한 접근 방법 중 하나는 오버라이드하려는 프롬프트에 대한 JSON 파일을 생성한 다음, 해당 파일을 Crew에 지정하는 것입니다.
1. 업데이트된 프롬프트 슬라이스로 JSON 파일을 만드세요.
2. Crew의 `prompt_file` 파라미터를 통해 그 파일을 참조하세요.
그러면 CrewAI가 기본값과 사용자가 지정한 내용을 병합하므로, 모든 프롬프트를 다시 정의할 필요가 없습니다. 방법은 다음과 같습니다:
### 예시: 기본 프롬프트 커스터마이징
수정하고 싶은 프롬프트를 포함하는 `custom_prompts.json` 파일을 생성하세요. 변경 사항만이 아니라 포함해야 하는 모든 최상위 프롬프트를 반드시 나열해야 합니다:
```json
{
"slices": {
"format": "When responding, follow this structure:\n\nTHOUGHTS: Your step-by-step thinking\nACTION: Any tool you're using\nRESULT: Your final answer or conclusion"
}
}
```
그 다음 아래와 같이 통합하세요:
```python
from crewai import Agent, Crew, Task, Process
# 평소와 같이 에이전트와 태스크를 생성
researcher = Agent(
role="Research Specialist",
goal="Find information on quantum computing",
backstory="You are a quantum physics expert",
verbose=True
)
research_task = Task(
description="Research quantum computing applications",
expected_output="A summary of practical applications",
agent=researcher
)
# 커스텀 프롬프트 파일로 crew를 생성
crew = Crew(
agents=[researcher],
tasks=[research_task],
prompt_file="path/to/custom_prompts.json",
verbose=True
)
# crew 실행
result = crew.kickoff()
```
이 몇 가지 간단한 수정으로, agent가 소통하고 태스크를 해결하는 방식을 세밀하게 제어할 수 있습니다.
## 특정 모델에 맞춘 최적화
모델마다 잘 동작하는 프롬프트의 구조가 다릅니다. 프롬프트를 모델의 뉘앙스에 맞게 더욱 깊이 있게 조정하면 성능이 크게 향상될 수 있습니다.
### 예시: Llama 3.3 프롬프트 템플릿
예를 들어, Meta의 Llama 3.3과 작업할 때는 더 깊은 수준의 커스터마이징이 다음에 설명된 권장 구조를 반영할 수 있습니다:
https://www.llama.com/docs/model-cards-and-prompt-formats/llama3_1/#prompt-template
다음은 Llama 3.3을 코드에서 활용하도록 Agent를 세밀하게 튜닝하는 방법을 보여주는 예시입니다:
```python
from crewai import Agent, Crew, Task, Process
from crewai_tools import DirectoryReadTool, FileReadTool
# Define templates for system, user (prompt), and assistant (response) messages
system_template = """<|begin_of_text|><|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|>"""
# Create an Agent using Llama-specific layouts
principal_engineer = Agent(
role="Principal Engineer",
goal="Oversee AI architecture and make high-level decisions",
backstory="You are the lead engineer responsible for critical AI systems",
verbose=True,
llm="groq/llama-3.3-70b-versatile", # Using the Llama 3 model
system_template=system_template,
prompt_template=prompt_template,
response_template=response_template,
tools=[DirectoryReadTool(), FileReadTool()]
)
# Define a sample task
engineering_task = Task(
description="Review AI implementation files for potential improvements",
expected_output="A summary of key findings and recommendations",
agent=principal_engineer
)
# Create a Crew for the task
llama_crew = Crew(
agents=[principal_engineer],
tasks=[engineering_task],
process=Process.sequential,
verbose=True
)
# Execute the crew
result = llama_crew.kickoff()
print(result.raw)
```
이와 같이 더 심도 있는 설정을 통해 별도의 JSON 파일 없이도 Llama 기반 워크플로에 대해 포괄적이고 저수준의 제어를 할 수 있습니다.
## 결론
CrewAI에서의 저수준 prompt 커스터마이제이션은 매우 맞춤화되고 복잡한 사용 사례에 대한 문을 엽니다. 잘 구성된 prompt 파일(또는 직접 작성한 인라인 템플릿)을 구축함으로써 다양한 모델, 언어, 특화된 도메인을 수용할 수 있습니다. 이러한 수준의 유연성 덕분에 원하는 AI 동작을 정확하게 설계할 수 있으며, override하지 않을 경우에도 CrewAI가 신뢰할 수 있는 기본값을 제공한다는 점에서 안심할 수 있습니다.
<Check>
이제 CrewAI에서 고급 prompt 커스터마이징을 위한 기초를 갖추었습니다. 모델별 구조나 도메인별 제약에 맞춰 적용하든, 이러한 저수준 접근 방식은 agent 상호작용을 매우 전문적으로 조정할 수 있게 해줍니다.
</Check>

View File

@@ -0,0 +1,133 @@
---
title: 지문 인식
description: CrewAI의 지문 인식 시스템을 사용하여 컴포넌트를 전체 라이프사이클 동안 고유하게 식별하고 추적하는 방법을 알아보세요.
icon: fingerprint
---
## 개요
CrewAI의 Fingerprints는 컴포넌트를 고유하게 식별하고 그 생애주기를 추적할 수 있는 방법을 제공합니다. 각 `Agent`, `Crew`, `Task`는 생성 시 자동으로 고유한 fingerprint를 부여받으며, 이는 수동으로 변경할 수 없습니다.
이러한 fingerprints는 다음과 같은 용도로 사용할 수 있습니다:
- 컴포넌트 사용 감사 및 추적
- 컴포넌트 식별 무결성 보장
- 컴포넌트에 메타데이터 첨부
- 추적 가능한 작업 체인 생성
## 지문(Fingerprints)의 작동 방식
지문(fingerprint)은 `crewai.security` 모듈의 `Fingerprint` 클래스의 인스턴스입니다. 각 지문에는 다음과 같은 정보가 포함되어 있습니다:
- UUID 문자열: 컴포넌트의 고유 식별자로, 자동으로 생성되며 수동으로 설정할 수 없습니다.
- 생성 타임스탬프: 지문이 생성된 시점을 나타내며, 자동으로 설정되고 수동으로 수정할 수 없습니다.
- 메타데이터: 추가 정보를 담은 사전(dictionary)으로, 사용자 정의가 가능합니다.
지문은 컴포넌트가 생성될 때 자동으로 생성되어 할당됩니다. 각 컴포넌트는 읽기 전용 속성을 통해 자신의 지문을 제공합니다.
## 기본 사용법
### 지문 접근하기
```python
from crewai import Agent, Crew, Task
# Create components - fingerprints are automatically generated
agent = Agent(
role="Data Scientist",
goal="Analyze data",
backstory="Expert in data analysis"
)
crew = Crew(
agents=[agent],
tasks=[]
)
task = Task(
description="Analyze customer data",
expected_output="Insights from data analysis",
agent=agent
)
# Access the fingerprints
agent_fingerprint = agent.fingerprint
crew_fingerprint = crew.fingerprint
task_fingerprint = task.fingerprint
# Print the UUID strings
print(f"Agent fingerprint: {agent_fingerprint.uuid_str}")
print(f"Crew fingerprint: {crew_fingerprint.uuid_str}")
print(f"Task fingerprint: {task_fingerprint.uuid_str}")
```
### 지문 메타데이터 작업
지문에 추가적인 맥락 정보를 제공하기 위해 메타데이터를 추가할 수 있습니다:
```python
# Add metadata to the agent's fingerprint
agent.security_config.fingerprint.metadata = {
"version": "1.0",
"department": "Data Science",
"project": "Customer Analysis"
}
# Access the metadata
print(f"Agent metadata: {agent.fingerprint.metadata}")
```
## 지문(Fingerprint) 지속성
지문은 컴포넌트의 생애 주기 전체에 걸쳐 지속되고 변하지 않도록 설계되었습니다. 컴포넌트를 수정하더라도 지문은 동일하게 유지됩니다:
```python
original_fingerprint = agent.fingerprint.uuid_str
# Modify the agent
agent.goal = "New goal for analysis"
# The fingerprint remains unchanged
assert agent.fingerprint.uuid_str == original_fingerprint
```
## 결정론적 지문
UUID와 생성 타임스탬프를 직접 설정할 수는 없지만, `generate` 메서드와 시드(seed)를 사용하여 결정론적 지문을 만들 수 있습니다:
```python
from crewai.security import Fingerprint
# 시드 문자열을 사용하여 결정론적 지문 생성
deterministic_fingerprint = Fingerprint.generate(seed="my-agent-id")
# 동일한 시드로 항상 동일한 지문이 생성됨
same_fingerprint = Fingerprint.generate(seed="my-agent-id")
assert deterministic_fingerprint.uuid_str == same_fingerprint.uuid_str
# 메타데이터도 설정할 수 있음
custom_fingerprint = Fingerprint.generate(
seed="my-agent-id",
metadata={"version": "1.0"}
)
```
## 고급 사용
### Fingerprint 구조
각 fingerprint는 다음과 같은 구조를 가지고 있습니다:
```python
from crewai.security import Fingerprint
fingerprint = agent.fingerprint
# UUID 문자열 - 고유 식별자 (자동 생성)
uuid_str = fingerprint.uuid_str # e.g., "123e4567-e89b-12d3-a456-426614174000"
# 생성 타임스탬프 (자동 생성)
created_at = fingerprint.created_at # datetime 객체
# 메타데이터 - 추가 정보용 (사용자 지정 가능)
metadata = fingerprint.metadata # 딕셔너리, 기본값은 {}
```

View File

@@ -0,0 +1,453 @@
---
title: 효과적인 에이전트 제작
description: 복잡한 문제를 효과적으로 해결하기 위해 협업하는 강력하고 전문화된 AI 에이전트를 설계하는 모범 사례를 배워보세요.
icon: robot
---
## 에이전트 설계의 예술과 과학
CrewAI의 핵심에는 에이전트가 있습니다. 에이전트는 협업 프레임워크 내에서 특정 역할을 수행하도록 설계된 전문화된 AI 엔터티입니다. 기본적인 에이전트를 만드는 것은 간단하지만, 진정으로 효과적이고 탁월한 결과를 만들어내는 에이전트를 설계하려면 주요 설계 원칙과 모범 사례를 이해해야 합니다.
이 가이드는 여러분이 에이전트 설계의 예술을 마스터할 수 있도록 도와줍니다. 이를 통해 효과적으로 협업하고, 비판적으로 사고하며, 특정 요구에 맞춤화된 고품질 결과물을 만들어내는 전문화된 AI 페르소나를 설계할 수 있게 됩니다.
### 에이전트 설계가 중요한 이유
에이전트를 정의하는 방식은 다음에 중대한 영향을 미칩니다:
1. **출력 품질**: 잘 설계된 에이전트는 더 관련성 높고, 품질이 뛰어난 결과를 생성합니다
2. **협업 효율성**: 상호 보완적인 역량을 가진 에이전트들이 함께 더 효율적으로 작업합니다
3. **작업 성과**: 명확한 역할과 목표를 가진 에이전트가 작업을 더 효과적으로 수행합니다
4. **시스템 확장성**: 신중하게 설계된 에이전트는 여러 crew와 다양한 컨텍스트에서 재사용될 수 있습니다
이러한 측면에서 뛰어난 에이전트를 만들기 위한 모범 사례를 함께 살펴보겠습니다.
## 80/20 법칙: 에이전트보다 작업에 집중하세요
효과적인 AI 시스템을 구축할 때 이 중요한 원칙을 기억하세요: **노력의 80%는 작업 설계에, 20%만 에이전트 정의에 투자해야 합니다**.
왜일까요? 아무리 완벽하게 정의된 에이전트라도 잘못된 작업 설계에서는 실패하지만, 잘 설계된 작업은 단순한 에이전트까지도 뛰어나게 만들 수 있기 때문입니다. 즉,
- 대부분의 시간을 명확한 작업 지침 작성에 할애하세요
- 상세한 입력과 예상 결과를 정의하세요
- 실행을 안내할 예시와 컨텍스트를 추가하세요
- 남은 시간에는 에이전트 역할, 목표, 배경에 집중하세요
이는 에이전트 설계가 중요하지 않다는 의미가 아닙니다. 분명히 중요합니다. 하지만 실행 실패의 대부분은 작업 설계에서 발생하므로, 그에 따라 우선순위를 두어야 합니다.
## 효과적인 에이전트 설계의 핵심 원칙
### 1. 역할-목표-배경 이야기 프레임워크
CrewAI에서 가장 강력한 에이전트는 세 가지 핵심 요소의 탄탄한 기반 위에 구축됩니다:
#### 역할: 에이전트의 전문화된 기능
역할은 에이전트가 수행하는 일과 전문 분야를 정의합니다. 역할을 설계할 때는 다음을 준수하세요:
- **구체적이고 전문적으로 작성하세요**: "작가" 대신 "기술 문서 전문가"나 "창의적 스토리텔러"처럼 명확하게 표현하세요.
- **현실 세계의 직업과 일치시키세요**: 역할을 잘 알려진 직업 유형에 기반하세요.
- **도메인 전문성을 포함하세요**: 에이전트의 지식 분야를 명확히 하세요 (예: "시장 동향에 특화된 금융 분석가").
**효과적인 역할 예시:**
```yaml
role: "Senior UX Researcher specializing in user interview analysis"
role: "Full-Stack Software Architect with expertise in distributed systems"
role: "Corporate Communications Director specializing in crisis management"
```
#### 목표: 에이전트의 목적과 동기
목표는 에이전트의 노력을 이끌고 의사 결정 과정을 형성합니다. 효과적인 목표는 다음과 같아야 합니다:
- **명확하고 결과 중심적이어야 함**: 에이전트가 달성하려는 것이 무엇인지 정의합니다.
- **품질 기준을 강조해야 함**: 작업의 품질에 대한 기대치를 포함합니다.
- **성공 기준을 통합해야 함**: "좋음"이 무엇인지 에이전트가 이해할 수 있도록 도와줍니다.
**효과적인 목표의 예시:**
```yaml
goal: "Uncover actionable user insights by analyzing interview data and identifying recurring patterns, unmet needs, and improvement opportunities"
goal: "Design robust, scalable system architectures that balance performance, maintainability, and cost-effectiveness"
goal: "Craft clear, empathetic crisis communications that address stakeholder concerns while protecting organizational reputation"
```
#### 배경 이야기: 에이전트의 경험과 관점
배경 이야기는 에이전트에게 깊이를 부여하며, 문제를 해결하고 타인과 상호작용하는 방식에 영향을 미칩니다. 좋은 배경 이야기는 다음과 같습니다:
- **전문성과 경험을 확립**: 에이전트가 어떻게 자신의 기술을 습득했는지 설명합니다.
- **업무 스타일 및 가치를 정의**: 에이전트가 일에 어떻게 접근하는지 설명합니다.
- **통합된 페르소나 생성**: 배경 이야기의 모든 요소가 역할과 목표에 부합하는지 확인합니다.
**효과적인 배경 이야기 예시:**
```yaml
backstory: "You have spent 15 years conducting and analyzing user research for top tech companies. You have a talent for reading between the lines and identifying patterns that others miss. You believe that good UX is invisible and that the best insights come from listening to what users don't say as much as what they do say."
backstory: "With 20+ years of experience building distributed systems at scale, you've developed a pragmatic approach to software architecture. You've seen both successful and failed systems and have learned valuable lessons from each. You balance theoretical best practices with practical constraints and always consider the maintenance and operational aspects of your designs."
backstory: "As a seasoned communications professional who has guided multiple organizations through high-profile crises, you understand the importance of transparency, speed, and empathy in crisis response. You have a methodical approach to crafting messages that address concerns while maintaining organizational credibility."
```
### 2. 전문가가 일반가보다 우수함
에이전트는 일반적인 역할보다 전문화된 역할을 부여할 때 훨씬 더 우수한 성능을 보입니다. 고도로 집중된 에이전트는 더 정확하고 관련성 높은 결과물을 제공합니다:
**일반적 (효과 적음):**
```yaml
role: "Writer"
```
**전문화 (효과 좋음):**
```yaml
role: "Technical Blog Writer specializing in explaining complex AI concepts to non-technical audiences"
```
**전문가의 이점:**
- 기대되는 출력물에 대한 더 명확한 이해
- 더 일관된 성과
- 특정 작업과의 더 나은 정렬
- 도메인별 판단능력 향상
### 3. 전문화와 다재다능성의 균형
효과적인 에이전트는 전문성(한 가지를 매우 잘하는 것)과 다재다능성(다양한 상황에 적응할 수 있는 것) 사이에서 적절한 균형을 이룹니다:
- **역할에 전문화하고, 적용에는 다재다능하게**: 여러 맥락에서 적용할 수 있는 전문 기술을 가진 에이전트를 만드세요
- **지나치게 좁은 정의는 피하기**: 에이전트가 자신이 전문으로 하는 영역 내에서 다양한 변형을 처리할 수 있도록 하세요
- **협업 맥락을 고려하기**: 함께 일하게 될 다른 에이전트들과 전문 분야가 상호 보완될 수 있도록 에이전트를 설계하세요
### 4. 적절한 전문성 수준 설정
에이전트에게 할당하는 전문성 수준은 작업 접근 방식에 영향을 미칩니다:
- **초급 에이전트**: 단순한 작업, 브레인스토밍, 초기 초안에 적합
- **중급 에이전트**: 대부분의 표준 작업에서 신뢰성 있는 실행에 적합
- **전문가 에이전트**: 깊이와 세밀함이 요구되는 복잡하고 전문적인 작업에 최적
- **월드 클래스 에이전트**: 예외적인 품질이 필요한 중요한 작업에 할당
작업의 복잡성과 품질 요구 사항에 따라 적합한 전문성 수준을 선택하세요. 대부분의 협업 crew에서는 다양한 전문성 수준이 어우러지는 것이 가장 효과적이며, 핵심 전문 기능에는 더 높은 전문성을 배정하는 것이 좋습니다.
## 실제 예시: 적용 전과 적용 후
이러한 모범 사례를 적용하기 전과 후의 agent 정의 예시를 살펴보겠습니다:
### 예시 1: 콘텐츠 제작 에이전트
**이전:**
```yaml
role: "Writer"
goal: "Write good content"
backstory: "You are a writer who creates content for websites."
```
**이후:**
```yaml
role: "B2B Technology Content Strategist"
goal: "Create compelling, technically accurate content that explains complex topics in accessible language while driving reader engagement and supporting business objectives"
backstory: "You have spent a decade creating content for leading technology companies, specializing in translating technical concepts for business audiences. You excel at research, interviewing subject matter experts, and structuring information for maximum clarity and impact. You believe that the best B2B content educates first and sells second, building trust through genuine expertise rather than marketing hype."
```
### 예시 2: 리서치 에이전트
**변경 전:**
```yaml
role: "Researcher"
goal: "Find information"
backstory: "You are good at finding information online."
```
**변경 후:**
```yaml
role: "Academic Research Specialist in Emerging Technologies"
goal: "Discover and synthesize cutting-edge research, identifying key trends, methodologies, and findings while evaluating the quality and reliability of sources"
backstory: "With a background in both computer science and library science, you've mastered the art of digital research. You've worked with research teams at prestigious universities and know how to navigate academic databases, evaluate research quality, and synthesize findings across disciplines. You're methodical in your approach, always cross-referencing information and tracing claims to primary sources before drawing conclusions."
```
## 에이전트를 위한 효과적인 작업 설계하기
에이전트 설계도 중요하지만, 작업 설계는 성공적인 실행을 위해 매우 중요합니다. 에이전트가 성공할 수 있도록 작업을 설계할 때 참고할 수 있는 모범 사례는 다음과 같습니다:
### 효과적인 작업의 구조
잘 설계된 작업은 서로 다른 목적을 가진 두 가지 주요 구성 요소를 가지고 있습니다:
#### 작업 설명: 프로세스
설명은 무엇을 어떻게 해야 하는지에 초점을 맞춰야 하며, 아래를 포함해야 합니다:
- 실행을 위한 상세 지침
- 맥락 및 배경 정보
- 범위 및 제약 조건
- 따라야 할 프로세스 단계
#### 예상 산출물: 결과물
예상 산출물은 최종 결과가 어떻게 보여야 하는지 정의해야 합니다:
- 형식 명세(마크다운, JSON 등)
- 구조 요구사항
- 품질 기준
- 좋은 결과물의 예시(가능할 경우)
### 작업 설계 모범 사례
#### 1. 단일 목적, 단일 산출물
작업은 하나의 명확한 목표에 집중할 때 가장 좋은 성과를 냅니다:
**나쁜 예시(너무 광범위함):**
```yaml
task_description: "Research market trends, analyze the data, and create a visualization."
```
**좋은 예시(집중됨):**
```yaml
# Task 1
research_task:
description: "Research the top 5 market trends in the AI industry for 2024."
expected_output: "A markdown list of the 5 trends with supporting evidence."
# Task 2
analysis_task:
description: "Analyze the identified trends to determine potential business impacts."
expected_output: "A structured analysis with impact ratings (High/Medium/Low)."
# Task 3
visualization_task:
description: "Create a visual representation of the analyzed trends."
expected_output: "A description of a chart showing trends and their impact ratings."
```
#### 2. 입력 및 출력 명시
항상 작업에 사용할 입력값과 출력이 어떻게 보여야 하는지 명확하게 지정하세요:
**예시:**
```yaml
analysis_task:
description: >
Analyze the customer feedback data from the CSV file.
Focus on identifying recurring themes related to product usability.
Consider sentiment and frequency when determining importance.
expected_output: >
A markdown report with the following sections:
1. Executive summary (3-5 bullet points)
2. Top 3 usability issues with supporting data
3. Recommendations for improvement
```
#### 3. 목적 및 맥락 포함
작업이 왜 중요한지, 더 큰 워크플로우에서 어떻게 맞물리는지 설명하세요:
**예시:**
```yaml
competitor_analysis_task:
description: >
Analyze our three main competitors' pricing strategies.
This analysis will inform our upcoming pricing model revision.
Focus on identifying patterns in how they price premium features
and how they structure their tiered offerings.
```
#### 4. 구조화된 출력 도구 사용하기
기계가 읽을 수 있는 출력을 위해서, 포맷을 명확히 지정하세요:
**예시:**
```yaml
data_extraction_task:
description: "Extract key metrics from the quarterly report."
expected_output: "JSON object with the following keys: revenue, growth_rate, customer_acquisition_cost, and retention_rate."
```
## 피해야 할 일반적인 실수
실제 구현에서 얻은 교훈을 바탕으로, 에이전트 및 태스크 설계에서 가장 흔한 실수는 다음과 같습니다:
### 1. 불명확한 작업 지시
**문제:** 작업에 충분한 세부 정보가 없어 에이전트가 효과적으로 실행하기 어렵습니다.
**잘못 설계된 예시:**
```yaml
research_task:
description: "Research AI trends."
expected_output: "A report on AI trends."
```
**개선된 버전:**
```yaml
research_task:
description: >
Research the top emerging AI trends for 2024 with a focus on:
1. Enterprise adoption patterns
2. Technical breakthroughs in the past 6 months
3. Regulatory developments affecting implementation
For each trend, identify key companies, technologies, and potential business impacts.
expected_output: >
A comprehensive markdown report with:
- Executive summary (5 bullet points)
- 5-7 major trends with supporting evidence
- For each trend: definition, examples, and business implications
- References to authoritative sources
```
### 2. 너무 많은 작업을 시도하는 "God Tasks"
**문제:** 여러 복잡한 작업을 하나의 지시 세트로 결합하는 태스크.
**잘못된 설계 예시:**
```yaml
comprehensive_task:
description: "Research market trends, analyze competitor strategies, create a marketing plan, and design a launch timeline."
```
**개선된 버전:**
이 작업을 순차적이고 집중된 태스크로 분리하세요:
```yaml
# Task 1: Research
market_research_task:
description: "Research current market trends in the SaaS project management space."
expected_output: "A markdown summary of key market trends."
# Task 2: Competitive Analysis
competitor_analysis_task:
description: "Analyze strategies of the top 3 competitors based on the market research."
expected_output: "A comparison table of competitor strategies."
context: [market_research_task]
# Continue with additional focused tasks...
```
### 3. 설명과 기대 출력 불일치
**문제:** 작업 설명에서 요구하는 내용과 기대 출력이 서로 다릅니다.
**설계가 미흡한 예시:**
```yaml
analysis_task:
description: "Analyze customer feedback to find areas of improvement."
expected_output: "A marketing plan for the next quarter."
```
**개선된 버전:**
```yaml
analysis_task:
description: "Analyze customer feedback to identify the top 3 areas for product improvement."
expected_output: "A report listing the 3 priority improvement areas with supporting customer quotes and data points."
```
### 4. 당신이 직접 프로세스를 이해하지 못함
**문제:** 당신이 완전히 이해하지 못하는 작업을 에이전트에게 수행하도록 요청함.
**해결책:**
1. 먼저 직접 작업을 수동으로 수행해보세요
2. 프로세스, 의사결정 지점, 정보 출처를 문서화하세요
3. 이 문서를 작업 설명의 기초로 사용하세요
### 5. 계층 구조의 조기 사용
**문제:** 순차적인 프로세스만으로도 충분한 경우에 불필요하게 복잡한 에이전트 계층 구조를 만드는 것.
**해결 방법:** 우선 순차적 프로세스부터 시작하고, 워크플로우의 복잡성이 정말로 필요할 때만 계층적 모델로 전환하세요.
### 6. 모호하거나 일반적인 에이전트 정의
**문제:** 일반적인 에이전트 정의는 일반적인 결과로 이어집니다.
**잘못된 설계 예시:**
```yaml
agent:
role: "Business Analyst"
goal: "Analyze business data"
backstory: "You are good at business analysis."
```
**개선된 버전:**
```yaml
agent:
role: "SaaS Metrics Specialist focusing on growth-stage startups"
goal: "Identify actionable insights from business data that can directly impact customer retention and revenue growth"
backstory: "With 10+ years analyzing SaaS business models, you've developed a keen eye for the metrics that truly matter for sustainable growth. You've helped numerous companies identify the leverage points that turned around their business trajectory. You believe in connecting data to specific, actionable recommendations rather than general observations."
```
## 고급 에이전트 설계 전략
### 협업을 위한 설계
여러 agent가 crew 내에서 함께 작업할 때 다음 사항을 고려하십시오:
- **상호 보완적인 스킬**: 각기 다르지만 상호 보완되는 능력을 가진 agent를 설계하세요.
- **업무 인계 시점**: agent 간에 작업이 어떻게 전달될지 명확한 인터페이스를 정의하세요.
- **건설적인 긴장감**: 때때로 약간씩 다른 관점을 가진 agent를 만들면 생산적인 대화를 통해 더 나은 결과를 이끌어낼 수 있습니다.
예를 들어, 콘텐츠 제작 crew는 다음과 같이 구성될 수 있습니다:
```yaml
# Research Agent
role: "Research Specialist for technical topics"
goal: "Gather comprehensive, accurate information from authoritative sources"
backstory: "You are a meticulous researcher with a background in library science..."
# Writer Agent
role: "Technical Content Writer"
goal: "Transform research into engaging, clear content that educates and informs"
backstory: "You are an experienced writer who excels at explaining complex concepts..."
# Editor Agent
role: "Content Quality Editor"
goal: "Ensure content is accurate, well-structured, and polished while maintaining consistency"
backstory: "With years of experience in publishing, you have a keen eye for detail..."
```
### 전문화된 도구 사용자 생성
일부 agent는 특정 도구를 효과적으로 활용하도록 특별히 설계될 수 있습니다:
```yaml
role: "Data Analysis Specialist"
goal: "Derive meaningful insights from complex datasets through statistical analysis"
backstory: "With a background in data science, you excel at working with structured and unstructured data..."
tools: [PythonREPLTool, DataVisualizationTool, CSVAnalysisTool]
```
### LLM 기능에 맞춘 에이전트 맞춤화
다양한 LLM은 서로 다른 강점을 가지고 있습니다. 이러한 기능을 염두에 두고 에이전트를 설계하세요:
```yaml
# For complex reasoning tasks
analyst:
role: "Data Insights Analyst"
goal: "..."
backstory: "..."
llm: openai/gpt-4o
# For creative content
writer:
role: "Creative Content Writer"
goal: "..."
backstory: "..."
llm: anthropic/claude-3-opus
```
## 에이전트 설계 테스트 및 반복
에이전트 설계는 종종 반복적인 과정입니다. 다음은 실용적인 접근 방식입니다:
1. **프로토타입으로 시작하기**: 초기 에이전트 정의 생성
2. **샘플 작업으로 테스트하기**: 대표적인 작업에서 성능 평가
3. **출력물 분석**: 강점과 약점 파악
4. **정의 수정**: 관찰에 따라 역할, 목표, 백스토리 조정
5. **협업 테스트**: 에이전트가 crew 환경에서 어떻게 작동하는지 평가
## 결론
효과적인 agent를 만드는 것은 예술이자 과학입니다. 여러분의 특정 요구에 맞춘 역할, 목표, 그리고 backstory를 신중하게 정의하고, 잘 설계된 task와 결합함으로써 뛰어난 결과를 만들어내는 전문화된 AI 협업자를 만들 수 있습니다.
agent와 task의 설계는 반복적인 과정임을 기억하세요. 이러한 모범 사례로 시작하여 agent가 실제로 동작하는 모습을 관찰하고, 배운 점을 바탕으로 접근 방식을 개선하세요. 그리고 항상 80/20 법칙을 명심하세요. agent로부터 최고의 결과를 얻기 위해서는 명확하고 집중된 task를 만드는 데 대부분의 노력을 집중하는 것이 중요합니다.
<Check>
축하합니다! 이제 효과적인 agent 설계의 원칙과 실천법을 이해하셨습니다. 이 기술들을 적용하여 강력하고 전문화된 agent들이 복잡한 task를 매끄럽게 협력하여 완수할 수 있도록 만드세요.
</Check>
## 다음 단계
- 특정 사용 사례에 맞는 다양한 agent 구성을 실험해 보세요
- [첫 crew 만들기](/ko/guides/crews/first-crew)에 대해 배우며 agent들이 어떻게 함께 작동하는지 확인해 보세요
- 더 발전된 오케스트레이션을 위해 [CrewAI Flows](/ko/guides/flows/first-flow)를 탐색해 보세요

View File

@@ -0,0 +1,503 @@
---
title: CrewAI 사용 사례 평가
description: AI 애플리케이션 요구 사항을 평가하고 복잡성과 정밀도 요구 사항에 따라 Crews와 Flows 중 올바른 접근 방식을 선택하는 방법을 알아보세요.
icon: scale-balanced
---
## 의사결정 프레임워크 이해하기
CrewAI로 AI 애플리케이션을 구축할 때 가장 중요한 결정 중 하나는 특정 사용 사례에 적합한 방식을 선택하는 것입니다. Crew를 사용할까요? Flow를 사용할까요? 아니면 둘의 조합을 사용할까요? 이 가이드는 요구 사항을 평가하고 정보에 기반한 아키텍처 결정을 내리는 데 도움이 됩니다.
이 결정의 핵심은 애플리케이션에서의 **복잡성**과 **정밀성**의 관계를 이해하는 것입니다:
<Frame caption="CrewAI 애플리케이션을 위한 복잡성 vs. 정밀성 매트릭스">
<img src="/images/complexity_precision.png" alt="복잡성 vs. 정밀성 매트릭스" />
</Frame>
이 매트릭스를 통해 다양한 방식이 복잡성과 정밀성에 대한 요구 사항과 어떻게 일치하는지 시각적으로 확인할 수 있습니다. 각 사분면이 의미하는 바와 그것이 아키텍처 선택에 어떻게 도움이 되는지 함께 살펴보겠습니다.
## 복잡성-정밀도 행렬 설명
### 복잡성이란 무엇인가?
CrewAI 애플리케이션의 맥락에서 **복잡성**은 다음을 의미합니다:
- 요구되는 뚜렷한 단계 또는 작업 수
- 수행해야 할 작업의 다양성
- 서로 다른 구성 요소 간의 상호 의존성
- 조건부 로직과 분기의 필요성
- 전체 워크플로우의 정교함
### 정밀성이란 무엇인가?
**정밀성**은 이 맥락에서 다음을 의미합니다:
- 최종 결과물에 요구되는 정확성
- 구조화되고 예측 가능한 결과의 필요성
- 재현성의 중요성
- 각 단계에 대한 통제 수준
- 출력의 변동 허용치
### 네 가지 사분면
#### 1. 낮은 복잡도, 낮은 정밀도
**특징:**
- 단순하고 직관적인 작업
- 출력 결과의 일부 변형 허용
- 제한된 단계 수
- 창의적이거나 탐색적인 응용
**권장 접근법:** 최소한의 에이전트를 가진 Simple Crews
**예시 사용 사례:**
- 기본 콘텐츠 생성
- 아이디어 브레인스토밍
- 간단한 요약 작업
- 창의적 글쓰기 보조
#### 2. 낮은 복잡성, 높은 정밀도
**특징:**
- 정확하고 구조화된 결과물이 요구되는 단순한 워크플로우
- 재현 가능한 결과가 필요한 경우
- 단계는 제한적이지만, 높은 정확도가 요구됨
- 주로 데이터 처리 또는 변환이 포함됨
**권장 방식:** 직접적인 LLM 호출이나 구조화된 출력이 있는 간단한 Crew 사용
**예시 활용 사례:**
- 데이터 추출 및 변환
- 양식 작성 및 검증
- 구조화된 콘텐츠 생성(JSON, XML)
- 단순 분류 작업
#### 3. 높은 복잡성, 낮은 정밀도
**특징:**
- 여러 단계로 이루어진 다단계 프로세스
- 창의적이거나 탐색적인 출력물
- 구성 요소 간의 복잡한 상호작용
- 최종 결과의 변동성 허용
**권장 접근 방식:** 여러 전문화된 agent가 포함된 Complex Crew
**예시 사용 사례:**
- 연구 및 분석
- 콘텐츠 생성 파이프라인
- 탐색적 데이터 분석
- 창의적 문제 해결
#### 4. 높은 복잡성, 높은 정밀도
**특징:**
- 구조화된 산출물이 요구되는 복잡한 워크플로
- 엄격한 정확성 요구사항을 가진 여러 상호 의존적인 단계
- 정교한 처리와 정밀한 결과 모두 필요
- 종종 임무에 중요한 애플리케이션
**권장 접근 방식:** 검증 단계를 포함한 여러 Crew를 오케스트레이션하는 Flows
**예시 사용 사례:**
- 엔터프라이즈 의사결정 지원 시스템
- 복잡한 데이터 처리 파이프라인
- 다단계 문서 처리
- 규제 산업 애플리케이션
## 크루와 플로우 중에서 선택하기
### Crews를 선택해야 할 때
Crews는 다음과 같은 경우에 이상적입니다:
1. **협업 지능이 필요할 때** - 서로 다른 전문성을 가진 여러 agent들이 함께 작업해야 할 때
2. **문제가 창발적 사고를 요구할 때** - 다양한 관점과 접근 방식에서의 해결책이 이득이 될 때
3. **작업이 주로 창의적이거나 분석적일 때** - 작업이 리서치, 콘텐츠 제작, 분석을 포함할 때
4. **엄격한 구조보다는 적응력을 중시할 때** - agent의 자율성이 workflow에 도움이 될 때
5. **출력 형식이 다소 유연할 수 있을 때** - 출력 구조에 약간의 변동이 허용될 때
```python
# Example: Research Crew for market analysis
from crewai import Agent, Crew, Process, Task
# Create specialized agents
researcher = Agent(
role="Market Research Specialist",
goal="Find comprehensive market data on emerging technologies",
backstory="You are an expert at discovering market trends and gathering data."
)
analyst = Agent(
role="Market Analyst",
goal="Analyze market data and identify key opportunities",
backstory="You excel at interpreting market data and spotting valuable insights."
)
# Define their tasks
research_task = Task(
description="Research the current market landscape for AI-powered healthcare solutions",
expected_output="Comprehensive market data including key players, market size, and growth trends",
agent=researcher
)
analysis_task = Task(
description="Analyze the market data and identify the top 3 investment opportunities",
expected_output="Analysis report with 3 recommended investment opportunities and rationale",
agent=analyst,
context=[research_task]
)
# Create the crew
market_analysis_crew = Crew(
agents=[researcher, analyst],
tasks=[research_task, analysis_task],
process=Process.sequential,
verbose=True
)
# Run the crew
result = market_analysis_crew.kickoff()
```
### 플로우를 선택해야 할 때
플로우는 다음과 같은 경우에 이상적입니다:
1. **실행에 대한 정밀한 제어가 필요할 때** - 워크플로우에 정확한 순서 지정과 상태 관리가 필요한 경우
2. **애플리케이션에 복잡한 상태 요구사항이 있을 때** - 여러 단계에 걸쳐 상태를 유지하고 변환해야 하는 경우
3. **구조화되고 예측 가능한 출력이 필요할 때** - 애플리케이션에서 일관되고 포맷된 결과가 필요한 경우
4. **워크플로우에 조건부 로직이 포함될 때** - 중간 결과에 따라 다른 경로를 선택해야 하는 경우
5. **AI와 절차적 코드를 결합해야 할 때** - 솔루션에 AI 기능과 전통적인 프로그래밍이 모두 필요한 경우
```python
# Example: Customer Support Flow with structured processing
from crewai.flow.flow import Flow, listen, router, start
from pydantic import BaseModel
from typing import List, Dict
# Define structured state
class SupportTicketState(BaseModel):
ticket_id: str = ""
customer_name: str = ""
issue_description: str = ""
category: str = ""
priority: str = "medium"
resolution: str = ""
satisfaction_score: int = 0
class CustomerSupportFlow(Flow[SupportTicketState]):
@start()
def receive_ticket(self):
# In a real app, this might come from an API
self.state.ticket_id = "TKT-12345"
self.state.customer_name = "Alex Johnson"
self.state.issue_description = "Unable to access premium features after payment"
return "Ticket received"
@listen(receive_ticket)
def categorize_ticket(self, _):
# Use a direct LLM call for categorization
from crewai import LLM
llm = LLM(model="openai/gpt-4o-mini")
prompt = f"""
Categorize the following customer support issue into one of these categories:
- Billing
- Account Access
- Technical Issue
- Feature Request
- Other
Issue: {self.state.issue_description}
Return only the category name.
"""
self.state.category = llm.call(prompt).strip()
return self.state.category
@router(categorize_ticket)
def route_by_category(self, category):
# Route to different handlers based on category
return category.lower().replace(" ", "_")
@listen("billing")
def handle_billing_issue(self):
# Handle billing-specific logic
self.state.priority = "high"
# More billing-specific processing...
return "Billing issue handled"
@listen("account_access")
def handle_access_issue(self):
# Handle access-specific logic
self.state.priority = "high"
# More access-specific processing...
return "Access issue handled"
# Additional category handlers...
@listen("billing", "account_access", "technical_issue", "feature_request", "other")
def resolve_ticket(self, resolution_info):
# Final resolution step
self.state.resolution = f"Issue resolved: {resolution_info}"
return self.state.resolution
# Run the flow
support_flow = CustomerSupportFlow()
result = support_flow.kickoff()
```
### 크루와 플로우를 결합해야 할 때
가장 정교한 애플리케이션은 종종 크루와 플로우를 결합할 때 이점을 얻습니다:
1. **복잡한 다단계 프로세스** - 플로우를 사용해 전체 프로세스를 오케스트레이션하고, 크루를 통해 복잡한 하위 작업을 처리합니다.
2. **창의성과 구조가 모두 필요한 애플리케이션** - 창의적인 작업에는 크루를 사용하고, 구조적인 처리는 플로우로 처리합니다.
3. **엔터프라이즈급 AI 애플리케이션** - 플로우로 상태 및 프로세스 흐름을 관리하면서, 크루를 활용해 특화된 작업을 수행합니다.
```python
# Example: Content Production Pipeline combining Crews and Flows
from crewai.flow.flow import Flow, listen, start
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
from typing import List, Dict
class ContentState(BaseModel):
topic: str = ""
target_audience: str = ""
content_type: str = ""
outline: Dict = {}
draft_content: str = ""
final_content: str = ""
seo_score: int = 0
class ContentProductionFlow(Flow[ContentState]):
@start()
def initialize_project(self):
# Set initial parameters
self.state.topic = "Sustainable Investing"
self.state.target_audience = "Millennial Investors"
self.state.content_type = "Blog Post"
return "Project initialized"
@listen(initialize_project)
def create_outline(self, _):
# Use a research crew to create an outline
researcher = Agent(
role="Content Researcher",
goal=f"Research {self.state.topic} for {self.state.target_audience}",
backstory="You are an expert researcher with deep knowledge of content creation."
)
outliner = Agent(
role="Content Strategist",
goal=f"Create an engaging outline for a {self.state.content_type}",
backstory="You excel at structuring content for maximum engagement."
)
research_task = Task(
description=f"Research {self.state.topic} focusing on what would interest {self.state.target_audience}",
expected_output="Comprehensive research notes with key points and statistics",
agent=researcher
)
outline_task = Task(
description=f"Create an outline for a {self.state.content_type} about {self.state.topic}",
expected_output="Detailed content outline with sections and key points",
agent=outliner,
context=[research_task]
)
outline_crew = Crew(
agents=[researcher, outliner],
tasks=[research_task, outline_task],
process=Process.sequential,
verbose=True
)
# Run the crew and store the result
result = outline_crew.kickoff()
# Parse the outline (in a real app, you might use a more robust parsing approach)
import json
try:
self.state.outline = json.loads(result.raw)
except:
# Fallback if not valid JSON
self.state.outline = {"sections": result.raw}
return "Outline created"
@listen(create_outline)
def write_content(self, _):
# Use a writing crew to create the content
writer = Agent(
role="Content Writer",
goal=f"Write engaging content for {self.state.target_audience}",
backstory="You are a skilled writer who creates compelling content."
)
editor = Agent(
role="Content Editor",
goal="Ensure content is polished, accurate, and engaging",
backstory="You have a keen eye for detail and a talent for improving content."
)
writing_task = Task(
description=f"Write a {self.state.content_type} about {self.state.topic} following this outline: {self.state.outline}",
expected_output="Complete draft content in markdown format",
agent=writer
)
editing_task = Task(
description="Edit and improve the draft content for clarity, engagement, and accuracy",
expected_output="Polished final content in markdown format",
agent=editor,
context=[writing_task]
)
writing_crew = Crew(
agents=[writer, editor],
tasks=[writing_task, editing_task],
process=Process.sequential,
verbose=True
)
# Run the crew and store the result
result = writing_crew.kickoff()
self.state.final_content = result.raw
return "Content created"
@listen(write_content)
def optimize_for_seo(self, _):
# Use a direct LLM call for SEO optimization
from crewai import LLM
llm = LLM(model="openai/gpt-4o-mini")
prompt = f"""
Analyze this content for SEO effectiveness for the keyword "{self.state.topic}".
Rate it on a scale of 1-100 and provide 3 specific recommendations for improvement.
Content: {self.state.final_content[:1000]}... (truncated for brevity)
Format your response as JSON with the following structure:
{{
"score": 85,
"recommendations": [
"Recommendation 1",
"Recommendation 2",
"Recommendation 3"
]
}}
"""
seo_analysis = llm.call(prompt)
# Parse the SEO analysis
import json
try:
analysis = json.loads(seo_analysis)
self.state.seo_score = analysis.get("score", 0)
return analysis
except:
self.state.seo_score = 50
return {"score": 50, "recommendations": ["Unable to parse SEO analysis"]}
# Run the flow
content_flow = ContentProductionFlow()
result = content_flow.kickoff()
```
## 실용적인 평가 프레임워크
특정 사용 사례에 맞는 올바른 접근 방식을 결정하려면 다음 단계별 평가 프레임워크를 따르세요:
### 1단계: 복잡성 평가
아래와 같은 기준으로 애플리케이션의 복잡성을 1~10점 척도로 평가하세요:
1. **단계 수**: 얼마나 많은 개별 작업이 필요한가요?
- 1-3단계: 낮은 복잡성 (1-3)
- 4-7단계: 중간 복잡성 (4-7)
- 8단계 이상: 높은 복잡성 (8-10)
2. **상호 의존성**: 서로 다른 부분 간의 연결성은 어느 정도인가요?
- 의존성이 거의 없음: 낮은 복잡성 (1-3)
- 다소 의존성 있음: 중간 복잡성 (4-7)
- 복잡한 다중 의존성: 높은 복잡성 (8-10)
3. **조건부 논리**: 얼마나 많은 분기 및 의사결정이 필요한가요?
- 선형 프로세스: 낮은 복잡성 (1-3)
- 분기가 일부 있음: 중간 복잡성 (4-7)
- 복잡한 결정 트리: 높은 복잡성 (8-10)
4. **도메인 지식**: 요구되는 지식의 전문성은 어느 정도인가요?
- 일반적인 지식: 낮은 복잡성 (1-3)
- 일부 전문 지식 필요: 중간 복잡성 (4-7)
- 여러 도메인에 대한 깊은 전문성 필요: 높은 복잡성 (8-10)
평균 점수를 계산하여 전체 복잡성을 결정하세요.
### 2단계: 정밀도 요구사항 평가
정밀도 요구사항을 1-10점 척도로 평가하세요. 다음을 고려합니다:
1. **출력 구조**: 출력이 얼마나 구조화되어야 합니까?
- 자유형 텍스트: 낮은 정밀도 (1-3)
- 반구조화: 중간 정밀도 (4-7)
- 엄격한 포맷(JSON, XML): 높은 정밀도 (8-10)
2. **정확성 필요성**: 사실적 정확성이 얼마나 중요합니까?
- 창의적 콘텐츠: 낮은 정밀도 (1-3)
- 정보성 콘텐츠: 중간 정밀도 (4-7)
- 중요한 정보: 높은 정밀도 (8-10)
3. **재현성**: 실행마다 결과가 얼마나 일관되어야 합니까?
- 변동 허용: 낮은 정밀도 (1-3)
- 어느 정도 일관성 필요: 중간 정밀도 (4-7)
- 정확한 재현성 필요: 높은 정밀도 (8-10)
4. **오류 허용도**: 오류의 영향은 어느 정도입니까?
- 영향 적음: 낮은 정밀도 (1-3)
- 영향 보통: 중간 정밀도 (4-7)
- 영향 큼: 높은 정밀도 (8-10)
평균 점수를 계산하여 전체 정밀도 요구사항을 결정하세요.
### 3단계: 매트릭스에 매핑하기
복잡도와 정밀도 점수를 매트릭스에 표시하세요:
- **낮은 복잡도(1-4), 낮은 정밀도(1-4)**: Simple Crews
- **낮은 복잡도(1-4), 높은 정밀도(5-10)**: 직접적인 LLM 호출이 있는 Flows
- **높은 복잡도(5-10), 낮은 정밀도(1-4)**: Complex Crews
- **높은 복잡도(5-10), 높은 정밀도(5-10)**: Crews를 오케스트레이션하는 Flows
### 4단계: 추가 요소 고려
복잡성과 정밀성 외에도 다음을 고려하세요:
1. **개발 시간**: crew는 프로토타입을 더 빠르게 만들 수 있습니다
2. **유지보수 필요**: flow는 장기적인 유지보수에 더 적합합니다
3. **팀 전문성**: 팀이 다양한 접근법에 얼마나 익숙한지 고려하세요
4. **확장성 요구 사항**: flow는 일반적으로 복잡한 애플리케이션에 더 잘 확장됩니다
5. **통합 필요**: 솔루션이 기존 시스템과 어떻게 통합될지 고려하세요
## 결론
Crews와 Flows 중에서 선택하거나 결합하는 것은 CrewAI 애플리케이션의 효과성, 유지 관리성, 확장성에 영향을 미치는 중요한 아키텍처적 결정입니다. 복잡성과 정밀성이라는 차원에서 사용 사례를 평가함으로써, 귀하의 특정 요구 사항에 부합하는 정보에 기반한 결정을 내릴 수 있습니다.
가장 좋은 접근방식은 애플리케이션이 성숙해지면서 종종 진화한다는 점을 기억하세요. 귀하의 요구를 충족하는 가장 간단한 해결책으로 시작하고, 경험이 쌓이고 요구 사항이 명확해지면 아키텍처를 개선할 준비를 하세요.
<Check>
이제 CrewAI 사용 사례를 평가하고, 복잡성과 정밀성 요구 사항에 따라 올바른 접근법을 선택할 수 있는 프레임워크를 갖추게 되었습니다. 이를 통해 보다 효과적이고 유지 관리 가능하며 확장성 있는 AI 애플리케이션을 구축할 수 있습니다.
</Check>
## 다음 단계
- [효과적인 에이전트 만들기](/ko/guides/agents/crafting-effective-agents)에 대해 더 알아보기
- [처음으로 crew 만들기](/ko/guides/crews/first-crew) 살펴보기
- [flow 상태 관리 마스터하기](/ko/guides/flows/mastering-flow-state)에 깊이 파고들기
- 더 깊은 이해를 위해 [핵심 개념](/ko/concepts/agents) 확인하기

View File

@@ -0,0 +1,391 @@
---
title: 첫 번째 크루 만들기
description: 복잡한 문제를 함께 해결할 수 있는 협업 AI 팀을 만드는 단계별 튜토리얼입니다.
icon: users-gear
---
## 협업 AI의 힘을 발휘하기
여러 AI 에이전트가 각자의 전문성을 바탕으로 원활하게 협력하며 복잡한 문제를 해결한다고 상상해 보세요. 각자 고유한 기술을 발휘해 공동의 목표를 달성합니다. 이것이 바로 CrewAI의 힘입니다. CrewAI 프레임워크를 통해 단일 AI로는 달성할 수 없는 과업을 협업 AI 시스템으로 실현할 수 있습니다.
이 가이드에서는 연구 크루를 만들어 주제를 조사 및 분석하고, 종합적인 보고서를 작성하는 과정을 안내합니다. 이 실용적인 예시는 AI 에이전트들이 어떻게 협력하여 복잡한 작업을 수행할 수 있는지 보여 주지만, CrewAI로 실현할 수 있는 가능성의 시작에 불과합니다.
### 무엇을 만들고 배우게 될까요
이 가이드를 마치면 다음을 할 수 있게 됩니다:
1. **특화된 AI 연구팀 조직**: 각기 다른 역할과 책임을 가진 연구팀을 만듭니다
2. **여러 AI 에이전트 간의 협업 조율**
3. **정보 수집, 분석, 보고서 생성을 포함한 복잡한 workflow 자동화**
4. **더 야심찬 프로젝트에도 적용할 수 있는 기초 역량 구축**
이 가이드에서는 간단한 research crew를 만들지만, 동일한 패턴과 기법을 활용하여 다음과 같은 훨씬 더 정교한 팀도 만들 수 있습니다:
- 전문 writer, editor, fact-checker가 참여하는 다단계 콘텐츠 생성
- 단계별 지원 에이전트가 있는 복잡한 고객 서비스 시스템
- 데이터 수집, 시각화, 인사이트 생성까지 하는 자율 business analyst
- 아이디어 구상, 디자인, 구현 계획까지 진행하는 product development 팀
이제 여러분의 첫 crew를 만들어 봅시다!
### 필수 조건
시작하기 전에 다음을 확인하세요:
1. [설치 가이드](/ko/installation)를 참고하여 CrewAI를 설치했는지 확인하세요.
2. [LLM 설정 가이드](/ko/concepts/llms#setting-up-your-llm)를 참고하여 환경에 LLM API 키를 설정했는지 확인하세요.
3. Python에 대한 기본적인 이해
## 1단계: 새로운 CrewAI 프로젝트 생성
먼저, CLI를 사용하여 새로운 CrewAI 프로젝트를 생성해봅시다. 이 명령어는 필요한 모든 파일을 포함한 전체 프로젝트 구조를 설정해 주어, 보일러플레이트 코드를 설정하는 대신 에이전트와 그들의 작업 정의에 집중할 수 있습니다.
```bash
crewai create crew research_crew
cd research_crew
```
이렇게 하면 crew에 필요한 기본 구조를 갖춘 프로젝트가 생성됩니다. CLI는 다음을 자동으로 생성합니다:
- 필요한 파일이 포함된 프로젝트 디렉터리
- 에이전트와 작업에 대한 구성 파일
- 기본 crew 구현
- crew를 실행하는 메인 스크립트
<Frame caption="CrewAI 프레임워크 개요">
<img src="/images/crews.png" alt="CrewAI Framework Overview" />
</Frame>
## 2단계: 프로젝트 구조 살펴보기
CLI가 생성한 프로젝트 구조를 이해하는 시간을 가져봅시다. CrewAI는 Python 프로젝트의 모범 사례를 따르므로, crew가 더 복잡해질수록 코드를 쉽게 유지 관리하고 확장할 수 있습니다.
```
research_crew/
├── .gitignore
├── pyproject.toml
├── README.md
├── .env
└── src/
└── research_crew/
├── __init__.py
├── main.py
├── crew.py
├── tools/
│ ├── custom_tool.py
│ └── __init__.py
└── config/
├── agents.yaml
└── tasks.yaml
```
이 구조는 Python 프로젝트의 모범 사례를 따르며, 코드를 체계적으로 구성할 수 있도록 해줍니다. 설정 파일(YAML)과 구현 코드(Python)의 분리로 인해, 기본 코드를 변경하지 않고도 crew의 동작을 쉽게 수정할 수 있습니다.
## 3단계: 에이전트 구성하기
이제 재미있는 단계가 시작됩니다 - 여러분의 AI 에이전트를 정의하는 것입니다! CrewAI에서 에이전트는 특정 역할, 목표 및 배경을 가진 전문화된 엔터티로, 이들이 어떻게 행동할지를 결정합니다. 각각 고유한 성격과 목적을 지닌 연극의 등장인물로 생각하면 됩니다.
우리의 리서치 crew를 위해 두 명의 에이전트를 만들겠습니다:
1. 정보를 찾아 정리하는 데 뛰어난 **리서처**
2. 연구 결과를 해석하고 통찰력 있는 보고서를 작성할 수 있는 **애널리스트**
이러한 전문화된 에이전트를 정의하기 위해 `agents.yaml` 파일을 수정해봅시다. `llm` 항목은 사용 중인 제공업체에 맞게 설정하세요.
```yaml
# src/research_crew/config/agents.yaml
researcher:
role: >
Senior Research Specialist for {topic}
goal: >
Find comprehensive and accurate information about {topic}
with a focus on recent developments and key insights
backstory: >
You are an experienced research specialist with a talent for
finding relevant information from various sources. You excel at
organizing information in a clear and structured manner, making
complex topics accessible to others.
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
analyst:
role: >
Data Analyst and Report Writer for {topic}
goal: >
Analyze research findings and create a comprehensive, well-structured
report that presents insights in a clear and engaging way
backstory: >
You are a skilled analyst with a background in data interpretation
and technical writing. You have a talent for identifying patterns
and extracting meaningful insights from research data, then
communicating those insights effectively through well-crafted reports.
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
```
각 에이전트가 고유한 역할, 목표, 그리고 배경을 가지고 있다는 점에 주목하세요. 이 요소들은 단순한 설명 그 이상으로, 실제로 에이전트가 자신의 과업을 어떻게 접근하는지에 적극적으로 영향을 미칩니다. 이러한 부분을 신중하게 설계함으로써 서로 보완하는 전문적인 역량과 관점을 가진 에이전트를 만들 수 있습니다.
## 4단계: 작업 정의하기
이제 agent들을 정의했으니, 이들에게 수행할 구체적인 작업을 지정해야 합니다. CrewAI의 작업(task)은 agent가 수행할 구체적인 업무를 나타내며, 자세한 지침과 예상 결과물이 포함됩니다.
연구 crew를 위해 두 가지 주요 작업을 정의하겠습니다:
1. 포괄적인 정보 수집을 위한 **연구 작업**
2. 인사이트 있는 보고서 생성을 위한 **분석 작업**
`tasks.yaml` 파일을 다음과 같이 수정해 보겠습니다:
```yaml
# src/research_crew/config/tasks.yaml
research_task:
description: >
{topic}에 대해 철저한 연구를 수행하세요. 다음에 중점을 두세요:
1. 주요 개념 및 정의
2. 역사적 발전과 최근 동향
3. 주요 과제와 기회
4. 주목할 만한 적용 사례 또는 케이스 스터디
5. 향후 전망과 잠재적 발전
반드시 명확한 섹션으로 구성된 구조화된 형식으로 결과를 정리하세요.
expected_output: >
{topic}의 모든 요구 사항을 다루는, 잘 구성된 섹션이 포함된 포괄적인 연구 문서.
필요에 따라 구체적인 사실, 수치, 예시를 포함하세요.
agent: researcher
analysis_task:
description: >
연구 결과를 분석하고 {topic}에 대한 포괄적인 보고서를 작성하세요.
보고서에는 다음 내용이 포함되어야 합니다:
1. 간결한 요약(executive summary)으로 시작
2. 연구의 모든 주요 정보 포함
3. 동향과 패턴에 대한 통찰력 있는 분석 제공
4. 추천사항 또는 미래 고려 사항 제시
5. 명확한 제목과 함께 전문적이고 읽기 쉬운 형식으로 작성
expected_output: >
연구 결과와 추가 분석, 인사이트를 포함한 {topic}에 대한 정제되고 전문적인 보고서.
보고서는 간결한 요약, 본문, 결론 등으로 잘 구조화되어 있어야 합니다.
agent: analyst
context:
- research_task
output_file: output/report.md
```
분석 작업 내의 `context` 필드에 주목하세요. 이 강력한 기능을 통해 analyst가 연구 작업의 결과물을 참조할 수 있습니다. 이를 통해 정보가 human team에서처럼 agent 간에 자연스럽게 흐르는 워크플로우가 만들어집니다.
## 5단계: 크루 구성 설정하기
이제 크루를 구성하여 모든 것을 하나로 모을 시간입니다. 크루는 에이전트들이 함께 작업을 완료하는 방식을 조율하는 컨테이너 역할을 합니다.
`crew.py` 파일을 다음과 같이 수정해보겠습니다:
```python
# src/research_crew/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class ResearchCrew():
"""Research crew for comprehensive topic analysis and reporting"""
agents: List[BaseAgent]
tasks: List[Task]
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'], # type: ignore[index]
verbose=True,
tools=[SerperDevTool()]
)
@agent
def analyst(self) -> Agent:
return Agent(
config=self.agents_config['analyst'], # type: ignore[index]
verbose=True
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'] # type: ignore[index]
)
@task
def analysis_task(self) -> Task:
return Task(
config=self.tasks_config['analysis_task'], # type: ignore[index]
output_file='output/report.md'
)
@crew
def crew(self) -> Crew:
"""Creates the research crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
```
이 코드에서는 다음을 수행합니다:
1. researcher 에이전트를 생성하고, SerperDevTool을 장착하여 웹 검색 기능을 추가합니다.
2. analyst 에이전트를 생성합니다.
3. research와 analysis 작업(task)을 설정합니다.
4. 크루가 작업을 순차적으로 수행하도록 설정합니다(analyst가 researcher가 끝날 때까지 대기).
여기서 마법이 일어납니다. 몇 줄의 코드만으로도, 특화된 에이전트들이 조율된 프로세스 내에서 협업하는 협동 AI 시스템을 정의할 수 있습니다.
## 6단계: 메인 스크립트 설정
이제 우리 crew를 실행할 메인 스크립트를 설정해 보겠습니다. 이곳에서 crew가 리서치할 구체적인 주제를 지정합니다.
```python
#!/usr/bin/env python
# src/research_crew/main.py
import os
from research_crew.crew import ResearchCrew
# Create output directory if it doesn't exist
os.makedirs('output', exist_ok=True)
def run():
"""
Run the research crew.
"""
inputs = {
'topic': 'Artificial Intelligence in Healthcare'
}
# Create and run the crew
result = ResearchCrew().crew().kickoff(inputs=inputs)
# Print the result
print("\n\n=== FINAL REPORT ===\n\n")
print(result.raw)
print("\n\nReport has been saved to output/report.md")
if __name__ == "__main__":
run()
```
이 스크립트는 환경을 준비하고, 리서치 주제를 지정하며, crew의 작업을 시작합니다. CrewAI의 강력함은 이 코드가 얼마나 간단한지에서 드러납니다. 여러 AI 에이전트를 관리하는 모든 복잡함이 프레임워크에 의해 처리됩니다.
## 7단계: 환경 변수 설정하기
프로젝트 루트에 `.env` 파일을 생성하고 API 키를 입력하세요:
```sh
SERPER_API_KEY=your_serper_api_key
# Add your provider's API key here too.
```
선택한 provider를 구성하는 방법에 대한 자세한 내용은 [LLM 설정 가이드](/ko/concepts/llms#setting-up-your-llm)를 참고하세요. Serper API 키는 [Serper.dev](https://serper.dev/)에서 받을 수 있습니다.
## 8단계: 필수 종속성 설치
CrewAI CLI를 사용하여 필요한 종속성을 설치하세요:
```bash
crewai install
```
이 명령어는 다음을 수행합니다:
1. 프로젝트 구성에서 종속성을 읽어옵니다
2. 필요하다면 가상 환경을 생성합니다
3. 모든 필수 패키지를 설치합니다
## 9단계: Crew 실행하기
이제 흥미로운 순간입니다 - crew를 실행하여 AI 협업이 어떻게 이루어지는지 직접 확인해보세요!
```bash
crewai run
```
이 명령어를 실행하면 crew가 즉시 작동하는 모습을 볼 수 있습니다. researcher는 지정된 주제에 대한 정보를 수집하고, analyst가 그 연구를 바탕으로 종합 보고서를 작성합니다. 에이전트들의 사고 과정, 행동, 결과물이 실시간으로 표시되며 서로 협력하여 작업을 완수하는 모습을 확인할 수 있습니다.
## 10단계: 결과물 검토
crew가 작업을 완료하면, 최종 보고서는 `output/report.md` 파일에서 확인할 수 있습니다. 보고서에는 다음과 같은 내용이 포함됩니다:
1. 요약 보고서
2. 주제에 대한 상세 정보
3. 분석 및 인사이트
4. 권장사항 또는 향후 고려사항
지금까지 달성한 것을 잠시 돌아보세요. 여러분은 여러 AI 에이전트가 협업하여 각자의 전문적인 기술을 발휘함으로써, 단일 에이전트가 혼자서 이루어낼 수 있는 것보다 더 뛰어난 결과를 만들어내는 시스템을 구축한 것입니다.
## 기타 CLI 명령어 탐색
CrewAI는 crew 작업을 위한 몇 가지 유용한 CLI 명령어를 추가로 제공합니다:
```bash
# 모든 사용 가능한 명령어 보기
crewai --help
# crew 실행
crewai run
# crew 테스트
crewai test
# crew 메모리 초기화
crewai reset-memories
# 특정 task에서 재실행
crewai replay -t <task_id>
```
## 가능한 것의 예술: 당신의 첫 crew를 넘어서
이 가이드에서 구축한 것은 시작에 불과합니다. 여러분이 배운 기술과 패턴은 점점 더 정교한 AI 시스템을 만드는 데 적용할 수 있습니다. 다음은 이 기본 research crew를 확장할 수 있는 몇 가지 방법입니다:
### 팀원 확장하기
더 전문화된 에이전트를 팀원으로 추가할 수 있습니다:
- 연구 결과를 검증하는 **팩트체커**
- 차트와 그래프를 만드는 **데이터 시각화 담당자**
- 특정 분야에 전문 지식을 가진 **도메인 전문가**
- 분석의 약점을 파악하는 **비평가**
### 도구 및 기능 추가
에이전트에 추가 도구를 통해 기능을 확장할 수 있습니다:
- 실시간 연구를 위한 웹 브라우징 도구
- 데이터 분석을 위한 CSV/데이터베이스 도구
- 데이터 처리를 위한 코드 실행 도구
- 외부 서비스와의 API 연결
### 더 복잡한 워크플로우 생성
더 정교한 프로세스를 구현할 수 있습니다:
- 매니저 에이전트가 워커 에이전트에게 위임하는 계층적 프로세스
- 반복적 피드백 루프로 정제하는 반복 프로세스
- 여러 에이전트가 동시에 작업하는 병렬 프로세스
- 중간 결과에 따라 적응하는 동적 프로세스
### 다양한 도메인에 적용하기
동일한 패턴은 다음과 같은 분야에서 crew를 구성하는 데 적용할 수 있습니다:
- **콘텐츠 제작**: 작가, 에디터, 팩트체커, 디자이너가 함께 협업
- **고객 서비스**: 분류 담당자, 전문가, 품질 관리자가 함께 협업
- **제품 개발**: 연구원, 디자이너, 기획자가 협업
- **데이터 분석**: 데이터 수집가, 분석가, 시각화 전문가
## 다음 단계
이제 첫 crew를 구축했으니, 다음과 같은 작업을 시도해 볼 수 있습니다:
1. 다양한 에이전트 구성 및 성격을 실험해 보세요
2. 더 복잡한 작업 구조와 워크플로우를 시도해 보세요
3. 맞춤 도구를 구현하여 에이전트에게 새로운 기능을 제공하세요
4. crew를 다양한 주제나 문제 도메인에 적용해 보세요
5. [CrewAI Flows](/ko/guides/flows/first-flow)를 탐색하여 절차적 프로그래밍을 활용한 더 고급 워크플로우를 경험해 보세요
<Check>
축하합니다! 이제 주어진 모든 주제를 조사하고 분석할 수 있는 첫 번째 CrewAI crew를 성공적으로 구축하셨습니다. 이 기본적인 경험은 협업 인텔리전스를 통해 복잡하고 다단계의 문제를 해결할 수 있는 점점 더 정교한 AI 시스템을 제작하는 데 필요한 역량을 갖추는 데 도움이 됩니다.
</Check>

View File

@@ -0,0 +1,612 @@
---
title: 첫 Flow 빌드하기
description: 정밀한 실행 제어가 가능한 구조화된 이벤트 기반 워크플로우를 만드는 방법을 배웁니다.
icon: diagram-project
---
## Flows로 AI 워크플로우 제어하기
CrewAI Flows는 AI 오케스트레이션의 새로운 수준을 제공합니다. 즉, AI agent crew의 협업 능력과 절차적 프로그래밍의 정밀성 및 유연성을 결합합니다. crew가 agent 협업에서 탁월하다면, flow는 AI 시스템의 다양한 구성요소가 어떻게 그리고 언제 상호작용하는지에 대해 세밀하게 제어할 수 있게 해줍니다.
이 가이드에서는 원하는 주제에 대한 포괄적인 학습 가이드를 생성하는 강력한 CrewAI Flow를 만드는 과정을 소개합니다. 이 튜토리얼을 통해 Flow가 일반 코드, 직접적인 LLM 호출, crew 기반 처리 등을 결합하여 AI 워크플로우에 구조적이고 이벤트 기반의 제어를 제공하는 방법을 시연할 것입니다.
### 플로우의 강력한 점
플로우를 통해 다음과 같은 작업을 할 수 있습니다:
1. **다양한 AI 상호작용 패턴 결합** - 복잡한 협업 작업에는 crew를 사용하고, 더 단순한 작업에는 직접적인 LLM 호출과 절차적 논리에는 일반 코드를 사용하세요.
2. **이벤트 기반 시스템 구축** - 구성 요소가 특정 이벤트와 데이터 변경에 어떻게 반응할지 정의할 수 있습니다.
3. **구성 요소 간 상태 유지** - 애플리케이션의 다양한 부분 간에 데이터를 공유하고 변환할 수 있습니다.
4. **외부 시스템과 통합** - 데이터베이스, API, 사용자 인터페이스와 같은 외부 시스템과 AI 워크플로우를 원활하게 연동할 수 있습니다.
5. **복잡한 실행 경로 생성** - 조건부 분기, 병렬 처리 및 동적인 워크플로우를 설계할 수 있습니다.
### 무엇을 구축하고 배우게 될까요
이 가이드가 끝나면 여러분은 다음을 달성할 수 있습니다:
1. **사용자 입력, AI 계획, 그리고 멀티 에이전트 콘텐츠 생성이 결합된 정교한 콘텐츠 생성 시스템을 구축**했습니다.
2. **시스템의 다양한 구성 요소 간 정보 흐름을 오케스트레이션(조율)**했습니다.
3. **이전 단계의 완료에 따라 각 단계가 반응하는 이벤트 기반 아키텍처를 구현**했습니다.
4. **더 복잡한 AI 애플리케이션을 확장하고 맞춤화할 수 있는 기반을 구축**했습니다.
이번 가이드의 creator flow는 다음과 같은 훨씬 더 발전된 애플리케이션에 적용할 수 있는 기본 패턴을 보여줍니다:
- 여러 전문화된 하위 시스템을 결합하는 대화형 AI assistant
- AI 기반 변환을 포함한 복잡한 데이터 처리 파이프라인
- 외부 서비스 및 API와 통합되는 자율적 에이전트
- 인간이 개입하는 프로세스를 포함한 다단계 의사결정 시스템
함께 여러분의 첫 번째 flow를 만들어 봅시다!
## 사전 준비 사항
시작하기 전에 다음을 확인하세요:
1. [설치 가이드](/ko/installation)에 따라 CrewAI를 설치했는지 확인하십시오.
2. [LLM 설정 가이드](/ko/concepts/llms#setting-up-your-llm)에 따라 환경에 LLM API 키를 설정했는지 확인하십시오.
3. Python에 대한 기본적인 이해
## 1단계: 새로운 CrewAI Flow 프로젝트 생성
먼저, CLI를 사용하여 새로운 CrewAI Flow 프로젝트를 생성해봅시다. 이 명령어는 필요한 모든 디렉터리와 템플릿 파일이 포함된 기본 프로젝트 구조를 만들어줍니다.
```bash
crewai create flow guide_creator_flow
cd guide_creator_flow
```
이렇게 하면 flow에 필요한 기본 구조를 가진 프로젝트가 생성됩니다.
<Frame caption="CrewAI Framework 개요">
<img src="/images/flows.png" alt="CrewAI Framework 개요" />
</Frame>
## 2단계: 프로젝트 구조 이해하기
생성된 프로젝트는 다음과 같은 구조를 가지고 있습니다. 잠시 시간을 내어 이 구조에 익숙해지세요. 구조를 이해하면 앞으로 더 복잡한 flow를 만드는 데 도움이 됩니다.
```
guide_creator_flow/
├── .gitignore
├── pyproject.toml
├── README.md
├── .env
├── main.py
├── crews/
│ └── poem_crew/
│ ├── config/
│ │ ├── agents.yaml
│ │ └── tasks.yaml
│ └── poem_crew.py
└── tools/
└── custom_tool.py
```
이 구조는 flow의 다양한 구성 요소를 명확하게 분리해줍니다:
- `main.py` 파일의 main flow 로직
- `crews` 디렉터리의 특화된 crew들
- `tools` 디렉터리의 custom tool들
이제 이 구조를 수정하여 guide creator flow를 만들 것입니다. 이 flow는 포괄적인 학습 가이드 생성을 조직하는 역할을 합니다.
## 3단계: Content Writer Crew 추가
우리 flow에는 콘텐츠 생성 프로세스를 처리할 전문화된 crew가 필요합니다. CrewAI CLI를 사용하여 content writer crew를 추가해봅시다:
```bash
crewai flow add-crew content-crew
```
이 명령어는 자동으로 crew에 필요한 디렉터리와 템플릿 파일을 생성합니다. content writer crew는 가이드의 각 섹션을 작성하고 검토하는 역할을 담당하며, 메인 애플리케이션에 의해 조율되는 전체 flow 내에서 작업하게 됩니다.
## 4단계: 콘텐츠 작가 Crew 구성
이제 콘텐츠 작가 crew를 위해 생성된 파일을 수정해보겠습니다. 우리는 가이드의 고품질 콘텐츠를 만들기 위해 협업하는 두 명의 전문 에이전트 - 작가와 리뷰어 - 를 설정할 것입니다.
1. 먼저, 에이전트 구성 파일을 업데이트하여 콘텐츠 제작 팀을 정의합니다:
`llm`을 사용 중인 공급자로 설정해야 함을 기억하세요.
```yaml
# src/guide_creator_flow/crews/content_crew/config/agents.yaml
content_writer:
role: >
교육 콘텐츠 작가
goal: >
할당된 주제를 철저히 설명하고 독자에게 소중한 통찰력을 제공하는 흥미롭고 유익한 콘텐츠를 제작합니다
backstory: >
당신은 명확하고 흥미로운 콘텐츠를 만드는 데 능숙한 교육 전문 작가입니다. 복잡한 개념도 쉽게 설명하며,
정보를 독자가 이해하기 쉽게 조직할 수 있습니다.
llm: provider/model-id # 예: openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
content_reviewer:
role: >
교육 콘텐츠 검토자 및 에디터
goal: >
콘텐츠가 정확하고, 포괄적이며, 잘 구조화되어 있고, 이전에 작성된 섹션과의 일관성을 유지하도록 합니다
backstory: >
당신은 수년간 교육 콘텐츠를 검토해 온 꼼꼼한 에디터입니다. 세부 사항, 명확성, 일관성에 뛰어나며,
원 저자의 목소리를 유지하면서도 콘텐츠의 품질을 향상시키는 데 능숙합니다.
llm: provider/model-id # 예: openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
```
이 에이전트 정의는 AI 에이전트가 콘텐츠 제작을 접근하는 전문화된 역할과 관점을 구성합니다. 각 에이전트가 뚜렷한 목적과 전문성을 지니고 있음을 확인하세요.
2. 다음으로, 작업 구성 파일을 업데이트하여 구체적인 작성 및 검토 작업을 정의합니다:
```yaml
# src/guide_creator_flow/crews/content_crew/config/tasks.yaml
write_section_task:
description: >
주제에 대한 포괄적인 섹션을 작성하세요: "{section_title}"
섹션 설명: {section_description}
대상 독자: {audience_level} 수준 학습자
작성 시 아래 사항을 반드시 지켜주세요:
1. 섹션 주제에 대한 간략한 소개로 시작
2. 모든 주요 개념을 예시와 함께 명확하게 설명
3. 적절하다면 실용적인 활용 사례나 연습문제 포함
4. 주요 포인트 요약으로 마무리
5. 대략 500-800단어 분량
콘텐츠는 적절한 제목, 목록, 강조를 포함해 Markdown 형식으로 작성하세요.
이전에 작성된 섹션:
{previous_sections}
반드시 콘텐츠가 이전에 쓴 섹션과 일관성을 유지하고 앞에서 설명된 개념을 바탕으로 작성되도록 하세요.
expected_output: >
주제를 철저히 설명하고 대상 독자에게 적합한, 구조가 잘 잡힌 Markdown 형식의 포괄적 섹션
agent: content_writer
review_section_task:
description: >
아래 "{section_title}" 섹션의 내용을 검토하고 개선하세요:
{draft_content}
대상 독자: {audience_level} 수준 학습자
이전에 작성된 섹션:
{previous_sections}
검토 시 아래 사항을 반드시 지켜주세요:
1. 문법/철자 오류 수정
2. 명확성 및 가독성 향상
3. 내용이 포괄적이고 정확한지 확인
4. 이전에 쓴 섹션과 일관성 유지
5. 구조와 흐름 강화
6. 누락된 핵심 정보 추가
개선된 버전의 섹션을 Markdown 형식으로 제공하세요.
expected_output: >
원래의 구조를 유지하면서도 명확성, 정확성, 일관성을 향상시킨 세련된 개선본
agent: content_reviewer
context:
- write_section_task
```
이 작업 정의는 에이전트에게 세부적인 지침을 제공하여 우리의 품질 기준에 부합하는 콘텐츠를 생산하게 합니다. review 작업의 `context` 파라미터를 통해 리뷰어가 작가의 결과물에 접근할 수 있는 워크플로우가 생성됨에 주의하세요.
3. 이제 crew 구현 파일을 업데이트하여 에이전트와 작업이 어떻게 연동되는지 정의합니다:
```python
# src/guide_creator_flow/crews/content_crew/content_crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class ContentCrew():
"""Content writing crew"""
agents: List[BaseAgent]
tasks: List[Task]
@agent
def content_writer(self) -> Agent:
return Agent(
config=self.agents_config['content_writer'], # type: ignore[index]
verbose=True
)
@agent
def content_reviewer(self) -> Agent:
return Agent(
config=self.agents_config['content_reviewer'], # type: ignore[index]
verbose=True
)
@task
def write_section_task(self) -> Task:
return Task(
config=self.tasks_config['write_section_task'] # type: ignore[index]
)
@task
def review_section_task(self) -> Task:
return Task(
config=self.tasks_config['review_section_task'], # type: ignore[index]
context=[self.write_section_task()]
)
@crew
def crew(self) -> Crew:
"""Creates the content writing crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
```
이 crew 정의는 에이전트와 작업 간의 관계를 설정하여, 콘텐츠 작가가 초안을 작성하고 리뷰어가 이를 개선하는 순차적 과정을 만듭니다. 이 crew는 독립적으로도 작동할 수 있지만, 우리의 플로우에서 더 큰 시스템의 일부로 오케스트레이션될 예정입니다.
## 5단계: 플로우(Flow) 생성
이제 가장 흥미로운 부분입니다 - 전체 가이드 생성 과정을 오케스트레이션할 플로우를 만드는 단계입니다. 이곳에서 우리는 일반 Python 코드, 직접적인 LLM 호출, 그리고 우리의 컨텐츠 제작 crew를 결합하여 일관된 시스템으로 만듭니다.
우리의 플로우는 다음과 같은 일을 수행합니다:
1. 주제와 대상 독자 수준에 대한 사용자 입력을 받습니다.
2. 구조화된 가이드 개요를 만들기 위해 직접 LLM 호출을 합니다.
3. 컨텐츠 writer crew를 사용하여 각 섹션을 순차적으로 처리합니다.
4. 모든 내용을 결합하여 최종 종합 문서를 완성합니다.
`main.py` 파일에 우리의 플로우를 생성해봅시다:
```python
#!/usr/bin/env python
import json
import os
from typing import List, Dict
from pydantic import BaseModel, Field
from crewai import LLM
from crewai.flow.flow import Flow, listen, start
from guide_creator_flow.crews.content_crew.content_crew import ContentCrew
# Define our models for structured data
class Section(BaseModel):
title: str = Field(description="Title of the section")
description: str = Field(description="Brief description of what the section should cover")
class GuideOutline(BaseModel):
title: str = Field(description="Title of the guide")
introduction: str = Field(description="Introduction to the topic")
target_audience: str = Field(description="Description of the target audience")
sections: List[Section] = Field(description="List of sections in the guide")
conclusion: str = Field(description="Conclusion or summary of the guide")
# Define our flow state
class GuideCreatorState(BaseModel):
topic: str = ""
audience_level: str = ""
guide_outline: GuideOutline = None
sections_content: Dict[str, str] = {}
class GuideCreatorFlow(Flow[GuideCreatorState]):
"""Flow for creating a comprehensive guide on any topic"""
@start()
def get_user_input(self):
"""Get input from the user about the guide topic and audience"""
print("\n=== Create Your Comprehensive Guide ===\n")
# Get user input
self.state.topic = input("What topic would you like to create a guide for? ")
# Get audience level with validation
while True:
audience = input("Who is your target audience? (beginner/intermediate/advanced) ").lower()
if audience in ["beginner", "intermediate", "advanced"]:
self.state.audience_level = audience
break
print("Please enter 'beginner', 'intermediate', or 'advanced'")
print(f"\nCreating a guide on {self.state.topic} for {self.state.audience_level} audience...\n")
return self.state
@listen(get_user_input)
def create_guide_outline(self, state):
"""Create a structured outline for the guide using a direct LLM call"""
print("Creating guide outline...")
# Initialize the LLM
llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline)
# Create the messages for the outline
messages = [
{"role": "system", "content": "You are a helpful assistant designed to output JSON."},
{"role": "user", "content": f"""
Create a detailed outline for a comprehensive guide on "{state.topic}" for {state.audience_level} level learners.
The outline should include:
1. A compelling title for the guide
2. An introduction to the topic
3. 4-6 main sections that cover the most important aspects of the topic
4. A conclusion or summary
For each section, provide a clear title and a brief description of what it should cover.
"""}
]
# Make the LLM call with JSON response format
response = llm.call(messages=messages)
# Parse the JSON response
outline_dict = json.loads(response)
self.state.guide_outline = GuideOutline(**outline_dict)
# Ensure output directory exists before saving
os.makedirs("output", exist_ok=True)
# Save the outline to a file
with open("output/guide_outline.json", "w") as f:
json.dump(outline_dict, f, indent=2)
print(f"Guide outline created with {len(self.state.guide_outline.sections)} sections")
return self.state.guide_outline
@listen(create_guide_outline)
def write_and_compile_guide(self, outline):
"""Write all sections and compile the guide"""
print("Writing guide sections and compiling...")
completed_sections = []
# Process sections one by one to maintain context flow
for section in outline.sections:
print(f"Processing section: {section.title}")
# Build context from previous sections
previous_sections_text = ""
if completed_sections:
previous_sections_text = "# Previously Written Sections\n\n"
for title in completed_sections:
previous_sections_text += f"## {title}\n\n"
previous_sections_text += self.state.sections_content.get(title, "") + "\n\n"
else:
previous_sections_text = "No previous sections written yet."
# Run the content crew for this section
result = ContentCrew().crew().kickoff(inputs={
"section_title": section.title,
"section_description": section.description,
"audience_level": self.state.audience_level,
"previous_sections": previous_sections_text,
"draft_content": ""
})
# Store the content
self.state.sections_content[section.title] = result.raw
completed_sections.append(section.title)
print(f"Section completed: {section.title}")
# Compile the final guide
guide_content = f"# {outline.title}\n\n"
guide_content += f"## Introduction\n\n{outline.introduction}\n\n"
# Add each section in order
for section in outline.sections:
section_content = self.state.sections_content.get(section.title, "")
guide_content += f"\n\n{section_content}\n\n"
# Add conclusion
guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
# Save the guide
with open("output/complete_guide.md", "w") as f:
f.write(guide_content)
print("\nComplete guide compiled and saved to output/complete_guide.md")
return "Guide creation completed successfully"
def kickoff():
"""Run the guide creator flow"""
GuideCreatorFlow().kickoff()
print("\n=== Flow Complete ===")
print("Your comprehensive guide is ready in the output directory.")
print("Open output/complete_guide.md to view it.")
def plot():
"""Generate a visualization of the flow"""
flow = GuideCreatorFlow()
flow.plot("guide_creator_flow")
print("Flow visualization saved to guide_creator_flow.html")
if __name__ == "__main__":
kickoff()
```
이 플로우에서 일어나는 과정을 분석해봅시다:
1. 구조화된 데이터에 대한 Pydantic 모델을 정의하여 타입 안전성과 명확한 데이터 표현을 보장합니다.
2. 플로우 단계별로 데이터를 유지하기 위한 state 클래스를 생성합니다.
3. 세 가지 주요 플로우 단계를 구현합니다:
- `@start()` 데코레이터로 사용자 입력을 받습니다.
- 직접 LLM 호출로 가이드 개요를 생성합니다.
- content crew로 각 섹션을 처리합니다.
4. `@listen()` 데코레이터를 활용해 단계 간 이벤트 기반 관계를 설정합니다.
이것이 바로 flows의 힘입니다 - 다양한 처리 유형(사용자 상호작용, 직접적인 LLM 호출, crew 기반 작업)을 하나의 일관된 이벤트 기반 시스템으로 결합할 수 있습니다.
## 6단계: 환경 변수 설정하기
프로젝트 루트에 `.env` 파일을 생성하고 API 키를 입력하세요. 공급자 구성에 대한 자세한 내용은 [LLM 설정 가이드](/ko/concepts/llms#setting-up-your-llm)를 참고하세요.
```sh .env
OPENAI_API_KEY=your_openai_api_key
# or
GEMINI_API_KEY=your_gemini_api_key
# or
ANTHROPIC_API_KEY=your_anthropic_api_key
```
## 7단계: 의존성 설치
필수 의존성을 설치합니다:
```bash
crewai install
```
## 8단계: Flow 실행하기
이제 여러분의 flow가 실제로 작동하는 모습을 볼 차례입니다! CrewAI CLI를 사용하여 flow를 실행하세요:
```bash
crewai flow kickoff
```
이 명령어를 실행하면 flow가 다음과 같이 작동하는 것을 확인할 수 있습니다:
1. 주제와 대상 수준을 입력하라는 메시지가 표시됩니다.
2. 가이드의 체계적인 개요를 생성합니다.
3. 각 섹션을 처리할 때 content writer와 reviewer가 협업합니다.
4. 마지막으로 모든 내용을 종합하여 완성도 높은 가이드를 만듭니다.
이는 여러 구성요소(인공지능 및 비인공지능 모두)가 포함된 복잡한 프로세스를 flows가 어떻게 조정할 수 있는지 보여줍니다.
## 9단계: Flow 시각화하기
flow의 강력한 기능 중 하나는 구조를 시각화할 수 있다는 점입니다.
```bash
crewai flow plot
```
이 명령은 flow의 구조를 보여주는 HTML 파일을 생성하며, 각 단계 간의 관계와 그 사이에 흐르는 데이터를 확인할 수 있습니다. 이러한 시각화는 복잡한 flow를 이해하고 디버깅하는 데 매우 유용합니다.
## 10단계: 출력물 검토하기
flow가 완료되면 `output` 디렉토리에서 두 개의 파일을 찾을 수 있습니다:
1. `guide_outline.json`: 가이드의 구조화된 개요가 포함되어 있습니다
2. `complete_guide.md`: 모든 섹션이 포함된 종합적인 가이드입니다
이 파일들을 잠시 검토하고 여러분이 구축한 시스템을 되돌아보세요. 이 시스템은 사용자 입력, 직접적인 AI 상호작용, 협업 에이전트 작업을 결합하여 복잡하고 고품질의 결과물을 만들어냅니다.
## 가능한 것의 예술: 첫 번째 Flow 그 이상
이 가이드에서 배운 내용은 훨씬 더 정교한 AI 시스템을 만드는 데 기반이 됩니다. 다음은 이 기본 flow를 확장할 수 있는 몇 가지 방법입니다:
### 사용자 상호작용 향상
더욱 인터랙티브한 플로우를 만들 수 있습니다:
- 입력 및 출력을 위한 웹 인터페이스
- 실시간 진행 상황 업데이트
- 인터랙티브한 피드백 및 개선 루프
- 다단계 사용자 상호작용
### 추가 처리 단계 추가하기
다음과 같은 추가 단계로 flow를 확장할 수 있습니다:
- 개요 작성 전 사전 리서치
- 일러스트를 위한 이미지 생성
- 기술 가이드용 코드 스니펫 생성
- 최종 품질 보증 및 사실 확인
### 더 복잡한 Flows 생성하기
더 정교한 flow 패턴을 구현할 수 있습니다:
- 사용자 선호도나 콘텐츠 유형에 따른 조건 분기
- 독립적인 섹션의 병렬 처리
- 피드백과 함께하는 반복적 개선 루프
- 외부 API 및 서비스와의 통합
### 다양한 도메인에 적용하기
동일한 패턴을 사용하여 다음과 같은 flow를 만들 수 있습니다:
- **대화형 스토리텔링**: 사용자 입력을 바탕으로 개인화된 이야기를 생성
- **비즈니스 인텔리전스**: 데이터를 처리하고, 인사이트를 도출하며, 리포트를 생성
- **제품 개발**: 아이디어 구상, 디자인, 기획을 지원
- **교육 시스템**: 개인화된 학습 경험을 제공
## 주요 특징 시연
이 guide creator flow에서는 CrewAI의 여러 강력한 기능을 시연합니다:
1. **사용자 상호작용**: flow는 사용자로부터 직접 입력을 수집합니다
2. **직접적인 LLM 호출**: 효율적이고 단일 목적의 AI 상호작용을 위해 LLM 클래스를 사용합니다
3. **Pydantic을 통한 구조화된 데이터**: 타입 안정성을 보장하기 위해 Pydantic 모델을 사용합니다
4. **컨텍스트를 활용한 순차 처리**: 섹션을 순서대로 작성하면서 이전 섹션을 컨텍스트로 제공합니다
5. **멀티 에이전트 crew**: 콘텐츠 생성을 위해 특화된 에이전트(writer 및 reviewer)를 활용합니다
6. **상태 관리**: 프로세스의 다양한 단계에 걸쳐 상태를 유지합니다
7. **이벤트 기반 아키텍처**: 이벤트에 응답하기 위해 `@listen` 데코레이터를 사용합니다
## 플로우 구조 이해하기
플로우의 주요 구성 요소를 분해하여 자신만의 플로우를 만드는 방법을 이해할 수 있도록 도와드리겠습니다:
### 1. 직접 LLM 호출
Flow를 사용하면 간단하고 구조화된 응답이 필요할 때 언어 모델에 직접 호출할 수 있습니다:
```python
llm = LLM(
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
response_format=GuideOutline
)
response = llm.call(messages=messages)
```
특정하고 구조화된 출력이 필요할 때 crew를 사용하는 것보다 더 효율적입니다.
### 2. 이벤트 기반 아키텍처
Flows는 데코레이터를 사용하여 컴포넌트 간의 관계를 설정합니다:
```python
@start()
def get_user_input(self):
# First step in the flow
# ...
@listen(get_user_input)
def create_guide_outline(self, state):
# This runs when get_user_input completes
# ...
```
이렇게 하면 애플리케이션에 명확하고 선언적인 구조가 만들어집니다.
### 3. 상태 관리
flow는 단계 간 상태를 유지하여 데이터를 쉽게 공유할 수 있습니다:
```python
class GuideCreatorState(BaseModel):
topic: str = ""
audience_level: str = ""
guide_outline: GuideOutline = None
sections_content: Dict[str, str] = {}
```
이 방식은 flow 전반에 걸쳐 데이터를 추적하고 변환하는 타입 안전(type-safe)한 방법을 제공합니다.
### 4. Crew 통합
Flow는 복잡한 협업 작업을 위해 crew와 원활하게 통합될 수 있습니다:
```python
result = ContentCrew().crew().kickoff(inputs={
"section_title": section.title,
# ...
})
```
이를 통해 애플리케이션의 각 부분에 적합한 도구를 사용할 수 있습니다. 단순한 작업에는 직접적인 LLM 호출을, 복잡한 협업에는 crew를 사용할 수 있습니다.
## 다음 단계
이제 첫 번째 flow를 구축했으니 다음을 시도해 볼 수 있습니다:
1. 더 복잡한 flow 구조와 패턴을 실험해 보세요.
2. `@router()`를 사용하여 flow에서 조건부 분기를 만들어 보세요.
3. 더 복잡한 병렬 실행을 위해 `and_` 및 `or_` 함수를 탐색해 보세요.
4. flow를 외부 API, 데이터베이스 또는 사용자 인터페이스에 연결해 보세요.
5. 여러 전문화된 crew를 하나의 flow에서 결합해 보세요.
<Check>
축하합니다! 정규 코드, 직접적인 LLM 호출, crew 기반 처리를 결합하여 포괄적인 가이드를 생성하는 첫 번째 CrewAI Flow를 성공적으로 구축하셨습니다. 이러한 기초적인 역량을 바탕으로 절차적 제어와 협업적 인텔리전스를 결합하여 복잡하고 다단계의 문제를 해결할 수 있는 점점 더 정교한 AI 애플리케이션을 만들 수 있습니다.
</Check>

View File

@@ -0,0 +1,770 @@
---
title: 플로우 상태 관리 마스터하기
description: 견고한 AI 애플리케이션 구축을 위한 CrewAI 플로우에서 상태를 관리, 유지 및 활용하는 종합 가이드입니다.
icon: diagram-project
---
## 플로우에서 State의 힘 이해하기
State 관리는 모든 고급 AI 워크플로우의 중추입니다. CrewAI Flows에서 state 시스템은 컨텍스트를 유지하고, 단계 간 데이터를 공유하며, 복잡한 애플리케이션 로직을 구축할 수 있도록 해줍니다. State 관리에 능숙해지는 것은 신뢰할 수 있고, 유지보수가 용이하며, 강력한 AI 애플리케이션을 만들기 위해 필수적입니다.
이 가이드는 CrewAI Flows에서 state를 관리하는 데 꼭 알아야 할 기본 개념부터 고급 기법까지, 실용적인 코드 예제와 함께 단계별로 안내합니다.
### 상태 관리가 중요한 이유
효과적인 상태 관리는 다음을 가능하게 합니다:
1. **실행 단계 간의 컨텍스트 유지** - 워크플로의 다양한 단계 간에 정보를 원활하게 전달할 수 있습니다.
2. **복잡한 조건부 논리 구성** - 누적된 데이터를 기반으로 의사 결정을 내릴 수 있습니다.
3. **지속적인 애플리케이션 생성** - 워크플로 진행 상황을 저장하고 복원할 수 있습니다.
4. **에러를 우아하게 처리** - 더 견고한 애플리케이션을 위한 복구 패턴을 구현할 수 있습니다.
5. **애플리케이션 확장** - 적절한 데이터 조직을 통해 복잡한 워크플로를 지원할 수 있습니다.
6. **대화형 애플리케이션 활성화** - 컨텍스트 기반 AI 상호작용을 위해 대화 내역을 저장하고 접근할 수 있습니다.
이러한 기능을 효과적으로 활용하는 방법을 살펴보겠습니다.
## 상태 관리 기본 사항
### Flow 상태 라이프사이클
CrewAI Flow에서 상태는 예측 가능한 라이프사이클을 따릅니다:
1. **초기화** - flow가 생성될 때, 상태는 초기화됩니다(빈 딕셔너리 또는 Pydantic 모델 인스턴스로)
2. **수정** - flow 메서드는 실행되는 동안 상태에 접근하고 이를 수정합니다
3. **전달** - 상태는 flow 메서드들 사이에 자동으로 전달됩니다
4. **영속화** (선택 사항) - 상태는 스토리지에 저장될 수 있고 나중에 다시 불러올 수 있습니다
5. **완료** - 최종 상태는 모든 실행된 메서드의 누적 변경 사항을 반영합니다
이 라이프사이클을 이해하는 것은 효과적인 flow를 설계하는 데 매우 중요합니다.
### 상태 관리의 두 가지 접근 방식
CrewAI에서는 흐름에서 상태를 관리하는 두 가지 방법을 제공합니다:
1. **비구조적 상태** - 유연성을 위해 딕셔너리와 유사한 객체 사용
2. **구조적 상태** - 타입 안전성과 검증을 위해 Pydantic 모델 사용
각 접근 방식을 자세히 살펴보겠습니다.
## 비구조적 상태 관리
비구조적 상태는 사전(dictionary)과 유사한 방식을 사용하여, 단순한 애플리케이션에 유연성과 단순성을 제공합니다.
### 작동 방식
비구조화된 상태의 경우:
- `self.state`를 통해 상태에 접근하며, 이는 딕셔너리처럼 동작합니다
- 언제든지 키를 자유롭게 추가, 수정, 삭제할 수 있습니다
- 모든 상태는 모든 flow 메서드에서 자동으로 사용할 수 있습니다
### 기본 예제
다음은 비구조적 상태 관리를 보여주는 간단한 예제입니다:
```python
from crewai.flow.flow import Flow, listen, start
class UnstructuredStateFlow(Flow):
@start()
def initialize_data(self):
print("Initializing flow data")
# Add key-value pairs to state
self.state["user_name"] = "Alex"
self.state["preferences"] = {
"theme": "dark",
"language": "English"
}
self.state["items"] = []
# The flow state automatically gets a unique ID
print(f"Flow ID: {self.state['id']}")
return "Initialized"
@listen(initialize_data)
def process_data(self, previous_result):
print(f"Previous step returned: {previous_result}")
# Access and modify state
user = self.state["user_name"]
print(f"Processing data for {user}")
# Add items to a list in state
self.state["items"].append("item1")
self.state["items"].append("item2")
# Add a new key-value pair
self.state["processed"] = True
return "Processed"
@listen(process_data)
def generate_summary(self, previous_result):
# Access multiple state values
user = self.state["user_name"]
theme = self.state["preferences"]["theme"]
items = self.state["items"]
processed = self.state.get("processed", False)
summary = f"User {user} has {len(items)} items with {theme} theme. "
summary += "Data is processed." if processed else "Data is not processed."
return summary
# Run the flow
flow = UnstructuredStateFlow()
result = flow.kickoff()
print(f"Final result: {result}")
print(f"Final state: {flow.state}")
```
### 비구조적 상태를 사용할 때
비구조적 상태는 다음과 같은 경우에 이상적입니다:
- 빠른 프로토타이핑 및 간단한 플로우
- 동적으로 변화하는 상태 요구
- 구조가 사전에 알려지지 않을 수 있는 경우
- 간단한 상태 요구가 있는 플로우
비구조적 상태는 유연하지만, 타입 검사 및 스키마 검증이 없기 때문에 복잡한 애플리케이션에서 오류가 발생할 수 있습니다.
## 구조화된 상태 관리
구조화된 상태는 Pydantic 모델을 사용하여 flow의 상태에 대한 스키마를 정의함으로써 타입 안전성, 검증, 그리고 더 나은 개발자 경험을 제공합니다.
### 작동 방식
구조화된 상태에서는:
- 상태 구조를 나타내는 Pydantic 모델을 정의합니다.
- 이 모델 타입을 유형 매개변수로 Flow 클래스에 전달합니다.
- `self.state`를 통해 상태에 접근할 수 있으며, 이는 Pydantic 모델 인스턴스처럼 동작합니다.
- 모든 필드는 정의된 타입에 따라 검증됩니다.
- IDE 자동 완성 및 타입 체크 지원을 받을 수 있습니다.
### 기본 예제
구조화된 상태 관리를 구현하는 방법은 다음과 같습니다:
```python
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel, Field
from typing import List, Dict, Optional
# Define your state model
class UserPreferences(BaseModel):
theme: str = "light"
language: str = "English"
class AppState(BaseModel):
user_name: str = ""
preferences: UserPreferences = UserPreferences()
items: List[str] = []
processed: bool = False
completion_percentage: float = 0.0
# Create a flow with typed state
class StructuredStateFlow(Flow[AppState]):
@start()
def initialize_data(self):
print("Initializing flow data")
# Set state values (type-checked)
self.state.user_name = "Taylor"
self.state.preferences.theme = "dark"
# The ID field is automatically available
print(f"Flow ID: {self.state.id}")
return "Initialized"
@listen(initialize_data)
def process_data(self, previous_result):
print(f"Processing data for {self.state.user_name}")
# Modify state (with type checking)
self.state.items.append("item1")
self.state.items.append("item2")
self.state.processed = True
self.state.completion_percentage = 50.0
return "Processed"
@listen(process_data)
def generate_summary(self, previous_result):
# Access state (with autocompletion)
summary = f"User {self.state.user_name} has {len(self.state.items)} items "
summary += f"with {self.state.preferences.theme} theme. "
summary += "Data is processed." if self.state.processed else "Data is not processed."
summary += f" Completion: {self.state.completion_percentage}%"
return summary
# Run the flow
flow = StructuredStateFlow()
result = flow.kickoff()
print(f"Final result: {result}")
print(f"Final state: {flow.state}")
```
### 구조화된 상태의 이점
구조화된 상태를 사용하면 여러 가지 장점이 있습니다:
1. **타입 안정성** - 개발 단계에서 타입 오류를 잡을 수 있습니다
2. **자체 문서화** - 상태 모델이 어떤 데이터가 사용 가능한지 명확히 문서화합니다
3. **검증** - 데이터 타입과 제약 조건을 자동으로 검증합니다
4. **IDE 지원** - 자동 완성과 인라인 문서화를 받을 수 있습니다
5. **기본값** - 누락된 데이터에 대한 대체값을 쉽게 정의할 수 있습니다
### 구조화된 상태를 사용할 때
구조화된 상태는 다음과 같은 경우에 권장됩니다:
- 명확하게 정의된 데이터 스키마를 가진 복잡한 플로우
- 여러 개발자가 동일한 코드를 작업하는 팀 프로젝트
- 데이터 검증이 중요한 애플리케이션
- 특정 데이터 타입 및 제약 조건을 강제로 적용해야 하는 플로우
## 자동 상태 ID
비구조화 상태와 구조화 상태 모두 상태 인스턴스를 추적하고 관리하는 데 도움이 되는 고유한 식별자(UUID)를 자동으로 부여받습니다.
### 작동 방식
- 비구조화 state의 경우, ID는 `self.state["id"]`로 접근할 수 있습니다.
- 구조화 state의 경우, ID는 `self.state.id`로 접근할 수 있습니다.
- 이 ID는 flow가 생성될 때 자동으로 생성됩니다.
- ID는 flow의 생명주기 동안 동일하게 유지됩니다.
- ID는 추적, 로깅, 저장된 state의 조회에 사용할 수 있습니다.
이 UUID는 persistence를 구현하거나 여러 flow 실행을 추적할 때 특히 유용합니다.
## 동적 상태 업데이트
구조화된 상태를 사용하든 비구조화된 상태를 사용하든, flow의 실행 중 언제든지 상태를 동적으로 업데이트할 수 있습니다.
### 단계 간 데이터 전달
Flow 메서드는 값을 반환할 수 있으며, 이러한 반환값은 리스닝 메서드의 인자로 전달됩니다:
```python
from crewai.flow.flow import Flow, listen, start
class DataPassingFlow(Flow):
@start()
def generate_data(self):
# This return value will be passed to listening methods
return "Generated data"
@listen(generate_data)
def process_data(self, data_from_previous_step):
print(f"Received: {data_from_previous_step}")
# You can modify the data and pass it along
processed_data = f"{data_from_previous_step} - processed"
# Also update state
self.state["last_processed"] = processed_data
return processed_data
@listen(process_data)
def finalize_data(self, processed_data):
print(f"Received processed data: {processed_data}")
# Access both the passed data and state
last_processed = self.state.get("last_processed", "")
return f"Final: {processed_data} (from state: {last_processed})"
```
이 패턴을 사용하면 직접적인 데이터 전달과 state 업데이트를 결합하여 최대한 유연하게 작업할 수 있습니다.
## 플로우 상태 지속
CrewAI의 가장 강력한 기능 중 하나는 실행 간에 플로우 상태를 지속할 수 있다는 점입니다. 이를 통해 중단, 재개, 심지어 실패 후에도 복구할 수 있는 워크플로우를 구현할 수 있습니다.
### @persist() 데코레이터
`@persist()` 데코레이터는 상태 지속을 자동화하여 flow의 상태를 실행의 주요 지점마다 저장합니다.
#### 클래스 수준 지속성
클래스 수준에서 `@persist()`를 적용하면 모든 메서드 실행 후 상태가 저장됩니다:
```python
from crewai.flow.flow import Flow, listen, start
from crewai.flow.persistence import persist
from pydantic import BaseModel
class CounterState(BaseModel):
value: int = 0
@persist() # Apply to the entire flow class
class PersistentCounterFlow(Flow[CounterState]):
@start()
def increment(self):
self.state.value += 1
print(f"Incremented to {self.state.value}")
return self.state.value
@listen(increment)
def double(self, value):
self.state.value = value * 2
print(f"Doubled to {self.state.value}")
return self.state.value
# First run
flow1 = PersistentCounterFlow()
result1 = flow1.kickoff()
print(f"First run result: {result1}")
# Second run - state is automatically loaded
flow2 = PersistentCounterFlow()
result2 = flow2.kickoff()
print(f"Second run result: {result2}") # Will be higher due to persisted state
```
#### 메서드 수준 지속성
더 세밀한 제어를 위해 `@persist()`를 특정 메서드에 적용할 수 있습니다:
```python
from crewai.flow.flow import Flow, listen, start
from crewai.flow.persistence import persist
class SelectivePersistFlow(Flow):
@start()
def first_step(self):
self.state["count"] = 1
return "First step"
@persist() # Only persist after this method
@listen(first_step)
def important_step(self, prev_result):
self.state["count"] += 1
self.state["important_data"] = "This will be persisted"
return "Important step completed"
@listen(important_step)
def final_step(self, prev_result):
self.state["count"] += 1
return f"Complete with count {self.state['count']}"
```
## 고급 상태 패턴
### 상태 기반 조건부 로직
state를 사용하여 flow에서 복잡한 조건부 로직을 구현할 수 있습니다:
```python
from crewai.flow.flow import Flow, listen, router, start
from pydantic import BaseModel
class PaymentState(BaseModel):
amount: float = 0.0
is_approved: bool = False
retry_count: int = 0
class PaymentFlow(Flow[PaymentState]):
@start()
def process_payment(self):
# Simulate payment processing
self.state.amount = 100.0
self.state.is_approved = self.state.amount < 1000
return "Payment processed"
@router(process_payment)
def check_approval(self, previous_result):
if self.state.is_approved:
return "approved"
elif self.state.retry_count < 3:
return "retry"
else:
return "rejected"
@listen("approved")
def handle_approval(self):
return f"Payment of ${self.state.amount} approved!"
@listen("retry")
def handle_retry(self):
self.state.retry_count += 1
print(f"Retrying payment (attempt {self.state.retry_count})...")
# Could implement retry logic here
return "Retry initiated"
@listen("rejected")
def handle_rejection(self):
return f"Payment of ${self.state.amount} rejected after {self.state.retry_count} retries."
```
### 복잡한 상태 변환 처리
복잡한 상태 변환의 경우, 전용 메서드를 만들어 처리할 수 있습니다.
```python
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel
from typing import List, Dict
class UserData(BaseModel):
name: str
active: bool = True
login_count: int = 0
class ComplexState(BaseModel):
users: Dict[str, UserData] = {}
active_user_count: int = 0
class TransformationFlow(Flow[ComplexState]):
@start()
def initialize(self):
# Add some users
self.add_user("alice", "Alice")
self.add_user("bob", "Bob")
self.add_user("charlie", "Charlie")
return "Initialized"
@listen(initialize)
def process_users(self, _):
# Increment login counts
for user_id in self.state.users:
self.increment_login(user_id)
# Deactivate one user
self.deactivate_user("bob")
# Update active count
self.update_active_count()
return f"Processed {len(self.state.users)} users"
# Helper methods for state transformations
def add_user(self, user_id: str, name: str):
self.state.users[user_id] = UserData(name=name)
self.update_active_count()
def increment_login(self, user_id: str):
if user_id in self.state.users:
self.state.users[user_id].login_count += 1
def deactivate_user(self, user_id: str):
if user_id in self.state.users:
self.state.users[user_id].active = False
self.update_active_count()
def update_active_count(self):
self.state.active_user_count = sum(
1 for user in self.state.users.values() if user.active
)
```
이와 같은 헬퍼 메서드 생성 패턴은 flow 메서드를 깔끔하게 유지하면서 복잡한 상태 조작을 가능하게 해줍니다.
## Crews로 상태 관리하기
CrewAI에서 가장 강력한 패턴 중 하나는 flow 상태 관리와 crew 실행을 결합하는 것입니다.
### 크루에 상태 전달하기
플로우 상태를 사용하여 크루에 매개변수를 전달할 수 있습니다:
```python
from crewai.flow.flow import Flow, listen, start
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
class ResearchState(BaseModel):
topic: str = ""
depth: str = "medium"
results: str = ""
class ResearchFlow(Flow[ResearchState]):
@start()
def get_parameters(self):
# In a real app, this might come from user input
self.state.topic = "Artificial Intelligence Ethics"
self.state.depth = "deep"
return "Parameters set"
@listen(get_parameters)
def execute_research(self, _):
# Create agents
researcher = Agent(
role="Research Specialist",
goal=f"Research {self.state.topic} in {self.state.depth} detail",
backstory="You are an expert researcher with a talent for finding accurate information."
)
writer = Agent(
role="Content Writer",
goal="Transform research into clear, engaging content",
backstory="You excel at communicating complex ideas clearly and concisely."
)
# Create tasks
research_task = Task(
description=f"Research {self.state.topic} with {self.state.depth} analysis",
expected_output="Comprehensive research notes in markdown format",
agent=researcher
)
writing_task = Task(
description=f"Create a summary on {self.state.topic} based on the research",
expected_output="Well-written article in markdown format",
agent=writer,
context=[research_task]
)
# Create and run crew
research_crew = Crew(
agents=[researcher, writer],
tasks=[research_task, writing_task],
process=Process.sequential,
verbose=True
)
# Run crew and store result in state
result = research_crew.kickoff()
self.state.results = result.raw
return "Research completed"
@listen(execute_research)
def summarize_results(self, _):
# Access the stored results
result_length = len(self.state.results)
return f"Research on {self.state.topic} completed with {result_length} characters of results."
```
### State에서 Crew 출력 처리하기
Crew가 완료되면, 해당 출력을 처리하여 flow state에 저장할 수 있습니다:
```python
@listen(execute_crew)
def process_crew_results(self, _):
# Parse the raw results (assuming JSON output)
import json
try:
results_dict = json.loads(self.state.raw_results)
self.state.processed_results = {
"title": results_dict.get("title", ""),
"main_points": results_dict.get("main_points", []),
"conclusion": results_dict.get("conclusion", "")
}
return "Results processed successfully"
except json.JSONDecodeError:
self.state.error = "Failed to parse crew results as JSON"
return "Error processing results"
```
## 상태 관리 모범 사례
### 1. 상태를 집중적으로 유지하세요
상태를 설계할 때 꼭 필요한 내용만 포함하도록 하세요:
```python
# Too broad
class BloatedState(BaseModel):
user_data: Dict = {}
system_settings: Dict = {}
temporary_calculations: List = []
debug_info: Dict = {}
# ...many more fields
# Better: Focused state
class FocusedState(BaseModel):
user_id: str
preferences: Dict[str, str]
completion_status: Dict[str, bool]
```
### 2. 복잡한 플로우를 위한 구조화된 상태 사용
플로우의 복잡도가 증가할수록 구조화된 상태의 가치는 점점 커집니다:
```python
# Simple flow can use unstructured state
class SimpleGreetingFlow(Flow):
@start()
def greet(self):
self.state["name"] = "World"
return f"Hello, {self.state['name']}!"
# Complex flow benefits from structured state
class UserRegistrationState(BaseModel):
username: str
email: str
verification_status: bool = False
registration_date: datetime = Field(default_factory=datetime.now)
last_login: Optional[datetime] = None
class RegistrationFlow(Flow[UserRegistrationState]):
# Methods with strongly-typed state access
```
### 3. 문서 상태 전이
복잡한 흐름의 경우, 실행 중에 상태가 어떻게 변하는지 문서화하세요:
```python
@start()
def initialize_order(self):
"""
Initialize order state with empty values.
State before: {}
State after: {order_id: str, items: [], status: 'new'}
"""
self.state.order_id = str(uuid.uuid4())
self.state.items = []
self.state.status = "new"
return "Order initialized"
```
### 4. 상태 오류를 정상적으로 처리하기
상태 접근에 대한 오류 처리를 구현하세요:
```python
@listen(previous_step)
def process_data(self, _):
try:
# Try to access a value that might not exist
user_preference = self.state.preferences.get("theme", "default")
except (AttributeError, KeyError):
# Handle the error gracefully
self.state.errors = self.state.get("errors", [])
self.state.errors.append("Failed to access preferences")
user_preference = "default"
return f"Used preference: {user_preference}"
```
### 5. 상태를 사용하여 진행 상황 추적
긴 실행 흐름에서 진행 상황을 추적하기 위해 상태를 활용하세요:
```python
class ProgressTrackingFlow(Flow):
@start()
def initialize(self):
self.state["total_steps"] = 3
self.state["current_step"] = 0
self.state["progress"] = 0.0
self.update_progress()
return "Initialized"
def update_progress(self):
"""Helper method to calculate and update progress"""
if self.state.get("total_steps", 0) > 0:
self.state["progress"] = (self.state.get("current_step", 0) /
self.state["total_steps"]) * 100
print(f"Progress: {self.state['progress']:.1f}%")
@listen(initialize)
def step_one(self, _):
# Do work...
self.state["current_step"] = 1
self.update_progress()
return "Step 1 complete"
# Additional steps...
```
### 6. 가능한 경우 불변(Immutable) 연산 사용하기
특히 구조화된 상태에서는 명확성을 위해 불변 연산을 선호하세요:
```python
# 리스트를 즉시 수정하는 대신:
self.state.items.append(new_item) # 변경 가능한 연산
# 새로운 상태를 생성하는 것을 고려하세요:
from pydantic import BaseModel
from typing import List
class ItemState(BaseModel):
items: List[str] = []
class ImmutableFlow(Flow[ItemState]):
@start()
def add_item(self):
# 추가된 항목과 함께 새로운 리스트 생성
self.state.items = [*self.state.items, "new item"]
return "Item added"
```
## 플로우 상태 디버깅
### 상태 변경 로깅
개발할 때 상태 변화를 추적하기 위해 로깅을 추가하세요:
```python
import logging
logging.basicConfig(level=logging.INFO)
class LoggingFlow(Flow):
def log_state(self, step_name):
logging.info(f"State after {step_name}: {self.state}")
@start()
def initialize(self):
self.state["counter"] = 0
self.log_state("initialize")
return "Initialized"
@listen(initialize)
def increment(self, _):
self.state["counter"] += 1
self.log_state("increment")
return f"Incremented to {self.state['counter']}"
```
### 상태 시각화
디버깅을 위해 상태를 시각화하는 메서드를 추가할 수 있습니다:
```python
def visualize_state(self):
"""Create a simple visualization of the current state"""
import json
from rich.console import Console
from rich.panel import Panel
console = Console()
if hasattr(self.state, "model_dump"):
# Pydantic v2
state_dict = self.state.model_dump()
elif hasattr(self.state, "dict"):
# Pydantic v1
state_dict = self.state.dict()
else:
# Unstructured state
state_dict = dict(self.state)
# Remove id for cleaner output
if "id" in state_dict:
state_dict.pop("id")
state_json = json.dumps(state_dict, indent=2, default=str)
console.print(Panel(state_json, title="Current Flow State"))
```
## 결론
CrewAI Flows에서 상태 관리를 마스터하면 컨텍스트를 유지하고, 복잡한 결정을 내리며, 일관된 결과를 제공하는 정교하고 견고한 AI 애플리케이션을 구축할 수 있는 힘을 얻게 됩니다.
비구조화 상태든 구조화 상태든 적절한 상태 관리 방식을 구현하면 유지 관리가 용이하고, 확장 가능하며, 실제 문제를 효과적으로 해결할 수 있는 플로우를 만들 수 있습니다.
더 복잡한 플로우를 개발할수록 좋은 상태 관리는 유연성과 구조성 사이의 올바른 균형을 찾는 것임을 기억하세요. 이를 통해 코드가 강력하면서도 이해하기 쉬워집니다.
<Check>
이제 CrewAI Flows에서 상태 관리의 개념과 실습을 마스터하셨습니다! 이 지식을 통해 컨텍스트를 효과적으로 유지하고, 단계 간 데이터를 공유하며, 정교한 애플리케이션 로직을 구현하는 견고한 AI 워크플로우를 만들 수 있습니다.
</Check>
## 다음 단계
- flow에서 구조화된 state와 비구조화된 state를 모두 실험해 보세요
- 장기 실행 워크플로를 위해 state 영속성을 구현해 보세요
- [첫 crew 만들기](/ko/guides/crews/first-crew)를 탐색하여 crew와 flow가 어떻게 함께 작동하는지 확인해 보세요
- 더 고급 기능을 원한다면 [Flow 참고 문서](/ko/concepts/flows)를 확인해 보세요

198
docs/ko/installation.mdx Normal file
View File

@@ -0,0 +1,198 @@
---
title: 설치
description: CrewAI 시작하기 - 설치, 구성, 그리고 첫 번째 AI crew 구축하기
icon: wrench
---
## 비디오 튜토리얼
설치 과정을 단계별로 시연하는 비디오 튜토리얼을 시청하세요:
<iframe
width="100%"
height="400"
src="https://www.youtube.com/embed/-kSOTtYzgEw"
title="CrewAI Installation Guide"
frameborder="0"
style={{ borderRadius: '10px' }}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
## 텍스트 튜토리얼
<Note>
**Python 버전 요구 사항**
CrewAI는 `Python >=3.10 및 <3.14`가 필요합니다. 버전을 확인하는 방법은 다음과 같습니다:
```bash
python3 --version
```
Python을 업데이트해야 하는 경우, [python.org/downloads](https://python.org/downloads)를 방문하세요.
</Note>
CrewAI는 의존성 관리와 패키지 처리를 위해 `uv`를 사용합니다. 프로젝트 설정과 실행을 간소화하여 원활한 경험을 제공합니다.
아직 `uv`를 설치하지 않았다면 **1단계**를 따라 빠르게 시스템에 설치할 수 있습니다. 이미 설치되어 있다면 **2단계**로 건너뛸 수 있습니다.
<Steps>
<Step title="uv 설치하기">
- **macOS/Linux에서:**
`curl`을 이용해 스크립트를 다운로드하고 `sh`로 실행하세요:
```shell
curl -LsSf https://astral.sh/uv/install.sh | sh
```
시스템에 `curl`이 없다면, `wget`을 사용할 수 있습니다:
```shell
wget -qO- https://astral.sh/uv/install.sh | sh
```
- **Windows에서:**
`irm`으로 스크립트를 다운로드하고 `iex`로 실행하세요:
```shell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```
문제가 발생하면 [UV 설치 가이드](https://docs.astral.sh/uv/getting-started/installation/)를 참고하세요.
</Step>
<Step title="CrewAI 설치 🚀">
- 다음 명령어를 실행하여 `crewai` CLI를 설치하세요:
```shell
uv tool install crewai
```
<Warning>
`PATH` 경고가 발생하면 쉘을 업데이트하기 위해 아래 명령어를 실행하세요:
```shell
uv tool update-shell
```
</Warning>
<Warning>
Windows에서 `chroma-hnswlib==0.7.6` 빌드 오류(`fatal error C1083: Cannot open include file: 'float.h'`)가 발생하면, [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/)에서 *C++를 사용한 데스크톱 개발*을 설치하세요.
</Warning>
- `crewai`가 정상적으로 설치되었는지 확인하려면 다음을 실행하세요:
```shell
uv tool list
```
- 다음과 같이 표시되어야 합니다:
```shell
crewai v0.102.0
- crewai
```
- `crewai`를 업데이트해야 하는 경우, 다음을 실행하세요:
```shell
uv tool install crewai --upgrade
```
<Check>설치가 완료되었습니다! 이제 첫 번째 crew를 만들 준비가 되었습니다! 🎉</Check>
</Step>
</Steps>
# CrewAI 프로젝트 생성하기
에이전트 및 태스크를 정의할 때 구조적인 접근 방식을 위해 `YAML` 템플릿 스캐폴딩을 사용하는 것을 권장합니다. 다음은 시작 방법입니다:
<Steps>
<Step title="프로젝트 스캐폴딩 생성">
- `crewai` CLI 명령어를 실행하세요:
```shell
crewai create crew <your_project_name>
```
- 이 명령어를 실행하면 다음과 같은 구조로 새로운 프로젝트가 생성됩니다:
```
my_project/
├── .gitignore
├── knowledge/
├── pyproject.toml
├── README.md
├── .env
└── src/
└── my_project/
├── __init__.py
├── main.py
├── crew.py
├── tools/
│ ├── custom_tool.py
│ └── __init__.py
└── config/
├── agents.yaml
└── tasks.yaml
```
</Step>
<Step title="프로젝트 커스터마이즈">
- 프로젝트에는 다음과 같은 주요 파일들이 포함되어 있습니다:
| 파일 | 용도 |
| --- | --- |
| `agents.yaml` | AI 에이전트 및 역할 정의 |
| `tasks.yaml` | 에이전트 태스크 및 워크플로우 설정 |
| `.env` | API 키 및 환경 변수 저장 |
| `main.py` | 프로젝트 진입점 및 실행 흐름 |
| `crew.py` | Crew 오케스트레이션 및 코디네이션 |
| `tools/` | 커스텀 에이전트 도구 디렉터리 |
| `knowledge/` | 지식 베이스 디렉터리 |
- `agents.yaml` 및 `tasks.yaml`을 편집하여 crew의 동작을 정의하는 것부터 시작하세요.
- API 키와 같은 민감한 정보는 `.env` 파일에 보관하세요.
</Step>
<Step title="Crew 실행하기">
- crew를 실행하기 전에 아래 명령을 먼저 실행하세요:
```bash
crewai install
```
- 추가 패키지를 설치해야 하는 경우 다음을 사용하세요:
```shell
uv add <package-name>
```
- crew를 실행하려면 프로젝트 루트에서 아래 명령을 실행하세요:
```bash
crewai run
```
</Step>
</Steps>
## 엔터프라이즈 설치 옵션
<Note type="info">
팀과 조직을 위해, CrewAI는 설치 복잡성을 없애는 엔터프라이즈 배포 옵션을 제공합니다:
### CrewAI Enterprise (SaaS)
- 설치가 전혀 필요하지 않습니다 - [app.crewai.com](https://app.crewai.com)에서 무료로 가입하세요
- 자동 업데이트 및 유지 보수
- 관리형 인프라 및 확장성 지원
- 코딩 없이 Crew 생성
### CrewAI Factory (자가 호스팅)
- 귀하의 인프라를 위한 컨테이너화된 배포
- 온프레미스 배포를 포함하여 모든 하이퍼스케일러 지원
- 기존 보안 시스템과의 통합
<Card title="엔터프라이즈 옵션 살펴보기" icon="building" href="https://crewai.com/enterprise">
CrewAI의 엔터프라이즈 서비스에 대해 알아보고 데모를 예약하세요
</Card>
</Note>
## 다음 단계
<CardGroup cols={2}>
<Card
title="첫 번째 Agent 만들기"
icon="code"
href="/ko/quickstart"
>
빠른 시작 가이드를 따라 CrewAI 에이전트를 처음 만들어보고 직접 경험해 보세요.
</Card>
<Card
title="커뮤니티 참여하기"
icon="comments"
href="https://community.crewai.com"
>
다른 개발자들과 소통하고, 도움을 받으며, CrewAI 경험을 공유하세요.
</Card>
</CardGroup>

163
docs/ko/introduction.mdx Normal file
View File

@@ -0,0 +1,163 @@
---
title: 소개
description: 함께 협력하여 복잡한 작업을 해결하는 AI 에이전트 팀 구축
icon: handshake
---
# CrewAI란 무엇인가?
**CrewAI는 완전히 독립적으로, LangChain이나 기타 agent 프레임워크에 의존하지 않고 처음부터 스크래치로 개발된 가볍고 매우 빠른 Python 프레임워크입니다.**
CrewAI는 고수준의 간편함과 정밀한 저수준 제어를 모두 제공하여, 어떤 시나리오에도 맞춤화된 자율 AI agent를 만드는 데 이상적입니다:
- **[CrewAI Crews](/ko/guides/crews/first-crew)**: 자율성과 협업 지능을 극대화하여, 각 agent가 특정 역할, 도구, 목표를 가진 AI 팀을 만들 수 있습니다.
- **[CrewAI Flows](/ko/guides/flows/first-flow)**: 세밀한 이벤트 기반 제어와 단일 LLM 호출을 통한 정확한 작업 오케스트레이션을 가능하게 하며 Crews를 네이티브로 지원합니다.
10만 명이 넘는 개발자가 커뮤니티 과정을 통해 인증을 받았으며, CrewAI는 기업용 AI 자동화의 표준으로 빠르게 자리잡고 있습니다.
## 크루 작동 방식
<Note>
회사가 비즈니스 목표를 달성하기 위해 여러 부서(영업, 엔지니어링, 마케팅 등)가 리더십 아래에서 함께 일하는 것처럼, CrewAI는 복잡한 작업을 달성하기 위해 전문화된 역할의 AI 에이전트들이 협력하는 조직을 만들 수 있도록 도와줍니다.
</Note>
<Frame caption="CrewAI 프레임워크 개요">
<img src="/images/crews.png" alt="CrewAI Framework Overview" />
</Frame>
| 구성 요소 | 설명 | 주요 특징 |
|:--------------|:---------------------:|:----------|
| **크루** | 최상위 조직 | • AI 에이전트 팀 관리<br/>• 워크플로우 감독<br/>• 협업 보장<br/>• 결과 전달 |
| **AI 에이전트** | 전문 팀원 | • 특정 역할 보유(연구원, 작가 등)<br/>• 지정된 도구 사용<br/>• 작업 위임 가능<br/>• 자율적 의사결정 가능 |
| **프로세스** | 워크플로우 관리 시스템 | • 협업 패턴 정의<br/>• 작업 할당 제어<br/>• 상호작용 관리<br/>• 효율적 실행 보장 |
| **작업** | 개별 할당 | • 명확한 목표 보유<br/>• 특정 도구 사용<br/>• 더 큰 프로세스에 기여<br/>• 실행 가능한 결과 도출 |
### 어떻게 모두 함께 작동하는가
1. **Crew**가 전체 운영을 조직합니다
2. **AI Agents**가 자신들의 전문 작업을 수행합니다
3. **Process**가 원활한 협업을 보장합니다
4. **Tasks**가 완료되어 목표를 달성합니다
## 주요 기능
<CardGroup cols={2}>
<Card title="역할 기반 에이전트" icon="users">
연구원, 분석가, 작가 등 다양한 역할, 전문성, 목표를 가진 전문 에이전트를 생성할 수 있습니다
</Card>
<Card title="유연한 도구" icon="screwdriver-wrench">
에이전트에게 외부 서비스 및 데이터 소스와 상호작용할 수 있는 맞춤형 도구와 API를 제공합니다
</Card>
<Card title="지능형 협업" icon="people-arrows">
에이전트가 함께 작업하며, 인사이트를 공유하고 작업을 조율하여 복잡한 목표를 달성합니다
</Card>
<Card title="작업 관리" icon="list-check">
순차적 또는 병렬 워크플로우를 정의할 수 있으며, 에이전트가 작업 의존성을 자동으로 처리합니다
</Card>
</CardGroup>
## 플로우의 작동 원리
<Note>
crew는 자율 협업에 탁월한 반면, 플로우는 구조화된 자동화를 제공하여 워크플로우 실행에 대한 세밀한 제어를 제공합니다. 플로우는 조건부 로직, 반복문, 동적 상태 관리를 정확하게 처리하면서 작업이 신뢰성 있게, 안전하게, 효율적으로 실행되도록 보장합니다. 플로우는 crew와 원활하게 통합되어 높은 자율성과 엄격한 제어의 균형을 이룰 수 있게 해줍니다.
</Note>
<Frame caption="CrewAI Framework Overview">
<img src="/images/flows.png" alt="CrewAI Framework Overview" />
</Frame>
| 구성 요소 | 설명 | 주요 기능 |
|:----------|:-----------:|:------------|
| **Flow** | 구조화된 워크플로우 오케스트레이션 | • 실행 경로 관리<br/>• 상태 전환 처리<br/>• 작업 순서 제어<br/>• 신뢰성 있는 실행 보장 |
| **Events** | 워크플로우 액션 트리거 | • 특정 프로세스 시작<br/>• 동적 응답 가능<br/>• 조건부 분기 지원<br/>• 실시간 적응 허용 |
| **States** | 워크플로우 실행 컨텍스트 | • 실행 데이터 유지<br/>• 데이터 영속성 지원<br/>• 재개 가능성 보장<br/>• 실행 무결성 확보 |
| **Crew Support** | 워크플로우 자동화 강화 | • 필요할 때 agency 삽입<br/>• 구조화된 워크플로우 보완<br/>• 자동화와 인텔리전스의 균형<br/>• 적응적 의사결정 지원 |
### 주요 기능
<CardGroup cols={2}>
<Card title="이벤트 기반 오케스트레이션" icon="bolt">
이벤트에 동적으로 반응하여 정밀한 실행 경로 정의
</Card>
<Card title="세밀한 제어" icon="sliders">
워크플로우 상태와 조건부 실행을 안전하고 효율적으로 관리
</Card>
<Card title="네이티브 Crew 통합" icon="puzzle-piece">
Crews와 손쉽게 결합하여 자율성과 지능 강화
</Card>
<Card title="결정론적 실행" icon="route">
명시적 제어 흐름과 오류 처리로 예측 가능한 결과 보장
</Card>
</CardGroup>
## 크루(Crews)와 플로우(Flows)를 언제 사용할까
<Note>
[크루](/ko/guides/crews/first-crew)와 [플로우](/ko/guides/flows/first-flow)를 언제 사용할지 이해하는 것은 CrewAI의 잠재력을 애플리케이션에서 극대화하는 데 핵심적입니다.
</Note>
| 사용 사례 | 권장 접근 방식 | 이유 |
|:---------|:---------------------|:-----|
| **개방형 연구** | [크루](/ko/guides/crews/first-crew) | 과제가 창의적인 사고, 탐색, 적응이 필요할 때 |
| **콘텐츠 생성** | [크루](/ko/guides/crews/first-crew) | 기사, 보고서, 마케팅 자료 등 협업형 생성 시 |
| **의사결정 워크플로우** | [플로우](/ko/guides/flows/first-flow) | 예측 가능하고 감사 가능한 의사결정 경로 및 정밀 제어가 필요할 때 |
| **API 오케스트레이션** | [플로우](/ko/guides/flows/first-flow) | 특정 순서로 여러 외부 서비스에 신뢰성 있게 통합할 때 |
| **하이브리드 애플리케이션** | 혼합 접근 방식 | [플로우](/ko/guides/flows/first-flow)로 전체 프로세스를 오케스트레이션하고, [크루](/ko/guides/crews/first-crew)로 복잡한 하위 작업을 처리 |
### 의사결정 프레임워크
- **[Crews](/ko/guides/crews/first-crew)를 선택할 때:** 자율적인 문제 해결, 창의적 협업 또는 탐구적 작업이 필요할 때
- **[Flows](/ko/guides/flows/first-flow)를 선택할 때:** 결정론적 결과, 감사 가능성, 또는 실행에 대한 정밀한 제어가 필요할 때
- **둘 다 결합할 때:** 애플리케이션에 구조화된 프로세스와 자율적 지능이 모두 필요할 때
## CrewAI를 선택해야 하는 이유?
- 🧠 **자율적 운영**: 에이전트가 자신의 역할과 사용 가능한 도구를 바탕으로 지능적인 결정을 내립니다
- 📝 **자연스러운 상호작용**: 에이전트가 인간 팀원처럼 소통하고 협업합니다
- 🛠️ **확장 가능한 설계**: 새로운 도구, 역할, 기능을 쉽게 추가할 수 있습니다
- 🚀 **프로덕션 준비 완료**: 실제 환경에서의 신뢰성과 확장성을 고려하여 구축되었습니다
- 🔒 **보안 중심**: 엔터프라이즈 보안 요구 사항을 고려하여 설계되었습니다
- 💰 **비용 효율적**: 토큰 사용량과 API 호출을 최소화하도록 최적화되었습니다
## 지금 바로 빌드를 시작해보세요!
<CardGroup cols={2}>
<Card
title="첫 번째 Crew 만들기"
icon="users-gear"
href="/ko/guides/crews/first-crew"
>
복잡한 문제를 함께 해결하는 협업 AI 팀을 단계별로 만드는 튜토리얼입니다.
</Card>
<Card
title="첫 번째 Flow 만들기"
icon="diagram-project"
href="/ko/guides/flows/first-flow"
>
실행을 정밀하게 제어할 수 있는 구조화된, 이벤트 기반 워크플로우를 만드는 방법을 배워보세요.
</Card>
</CardGroup>
<CardGroup cols={3}>
<Card
title="CrewAI 설치하기"
icon="wrench"
href="/ko/installation"
>
개발 환경에서 CrewAI를 시작하세요.
</Card>
<Card
title="빠른 시작"
icon="bolt"
href="ko/quickstart"
>
빠른 시작 가이드를 따라 첫 번째 CrewAI 에이전트를 만들고 직접 경험해 보세요.
</Card>
<Card
title="커뮤니티 가입하기"
icon="comments"
href="https://community.crewai.com"
>
다른 개발자와 소통하며, 도움을 받고 CrewAI 경험을 공유해보세요.
</Card>
</CardGroup>

View File

@@ -0,0 +1,60 @@
---
title: 킥오프 전후 후크(Before and After Kickoff Hooks)
description: CrewAI에서 킥오프 전후 후크를 사용하는 방법을 알아보세요
---
CrewAI는 crew의 kickoff 전후에 코드를 실행할 수 있는 hook을 제공합니다. 이러한 hook은 입력값을 사전 처리하거나 결과를 사후 처리하는 데 유용합니다.
## 킥오프 이전 훅
킥오프 이전 훅은 크루가 작업을 시작하기 전에 실행됩니다. 이 훅은 입력 딕셔너리를 받아 이를 수정한 후 크루에 전달할 수 있습니다. 이 훅을 사용하여 환경을 설정하거나, 필요한 데이터를 불러오거나, 입력값을 전처리할 수 있습니다. 입력 데이터가 크루에 의해 처리되기 전에 보완 또는 검증이 필요한 경우에 유용합니다.
다음은 `crew.py`에서 킥오프 이전 함수를 정의하는 예시입니다:
```python
from crewai import CrewBase
from crewai.project import before_kickoff
@CrewBase
class MyCrew:
@before_kickoff
def prepare_data(self, inputs):
# Preprocess or modify inputs
inputs['processed'] = True
return inputs
#...
```
이 예시에서, prepare_data 함수는 입력값에 입력이 이미 처리되었음을 나타내는 새로운 키-값 쌍을 추가하여 입력값을 수정합니다.
## 킥오프 후 훅
킥오프 후 훅은 crew의 작업이 완료된 후에 실행됩니다. 이 훅은 crew 실행의 출력값을 담은 result 객체를 전달받습니다. 이 훅은 로깅, 데이터 변환 또는 추가 분석과 같이 결과를 후처리하는 데 이상적입니다.
`crew.py`에서 킥오프 후 함수를 정의하는 방법은 다음과 같습니다.
```python
from crewai import CrewBase
from crewai.project import after_kickoff
@CrewBase
class MyCrew:
@after_kickoff
def log_results(self, result):
# Log or modify the results
print("Crew execution completed with result:", result)
return result
# ...
```
`log_results` 함수에서는 crew 실행 결과가 단순히 출력됩니다. 이를 확장하여 알림 전송이나 다른 서비스와의 연동과 같은 더 복잡한 작업을 수행할 수도 있습니다.
## 두 후크 모두 활용하기
두 가지 후크를 함께 사용하면 crew의 실행을 위한 포괄적인 설정과 해제 프로세스를 제공할 수 있습니다. 이들은 관심사의 분리를 통해 코드 아키텍처를 깔끔하게 유지하고, CrewAI 구현의 모듈성을 향상하는 데 특히 유용합니다.
## 결론
CrewAI의 kickoff 전후 훅은 crew 실행의 생명주기에 강력하게 개입할 수 있는 방법을 제공합니다. 이러한 훅을 이해하고 활용함으로써, AI agent의 견고성과 유연성을 크게 향상시킬 수 있습니다.

View File

@@ -0,0 +1,439 @@
---
title: 에이전트 직접 가져오기
description: Crew 내에서 작동하는 자체 에이전트를 가져오는 방법을 알아보세요.
icon: robots
---
상호 운용성은 CrewAI의 핵심 개념입니다. 이 가이드에서는 Crew 내에서 작동하는 여러분만의 에이전트를 어떻게 도입할 수 있는지 보여줍니다.
## 에이전트 직접 가져오기 어댑터 가이드 (Langgraph Agents, OpenAI Agents 등...)
다양한 프레임워크의 에이전트를 crew에서 작동하도록 하려면 3가지 어댑터가 필요합니다.
1. BaseAgentAdapter
2. BaseToolAdapter
3. BaseConverter
## BaseAgentAdapter
이 추상 클래스는 모든 agent adapter가 구현해야 하는 공통 인터페이스와 기능을 정의합니다. BaseAgent를 확장하여 CrewAI 프레임워크와의 호환성을 유지하면서 adapter별 요구 사항을 추가합니다.
필수 메서드:
1. `def configure_tools`
2. `def configure_structured_output`
## 자신만의 Adapter 생성하기
다른 프레임워크(예: LangGraph, Autogen, OpenAI Assistants)의 agent를 CrewAI에 통합하려면, `BaseAgentAdapter`를 상속하여 커스텀 adapter를 생성해야 합니다. 이 adapter는 호환성 계층 역할을 하며 CrewAI 인터페이스와 외부 agent의 특정 요구사항 사이를 변환합니다.
커스텀 adapter를 구현하는 방법은 다음과 같습니다:
1. **`BaseAgentAdapter` 상속하기**:
```python
from crewai.agents.agent_adapters.base_agent_adapter import BaseAgentAdapter
from crewai.tools import BaseTool
from typing import List, Optional, Any, Dict
class MyCustomAgentAdapter(BaseAgentAdapter):
# ... implementation details ...
```
2. **`__init__` 구현하기**:
생성자는 부모 클래스 생성자 `super().__init__(**kwargs)`를 호출하고, 외부 agent에 특화된 초기화를 수행해야 합니다. CrewAI의 `Agent` 초기화 시 사용할 수 있는 선택적 `agent_config` 딕셔너리를 이용하여 adapter와 하위 agent를 구성할 수 있습니다.
```python
def __init__(self, agent_config: Optional[Dict[str, Any]] = None, **kwargs: Any):
super().__init__(agent_config=agent_config, **kwargs)
# Initialize your external agent here, possibly using agent_config
# Example: self.external_agent = initialize_my_agent(agent_config)
print(f"Initializing MyCustomAgentAdapter with config: {agent_config}")
```
3. **`configure_tools` 구현하기**:
이 추상 메서드는 매우 중요합니다. CrewAI `BaseTool` 인스턴스 리스트를 받습니다. 구현 시, 이 도구들을 외부 agent 프레임워크에서 기대하는 형식으로 변환 또는 적응시켜야 합니다. 래핑하거나, 특정 속성 추출, 혹은 외부 agent 인스턴스에 등록하는 작업이 필요할 수 있습니다.
```python
def configure_tools(self, tools: Optional[List[BaseTool]] = None) -> None:
if tools:
adapted_tools = []
for tool in tools:
# Adapt CrewAI BaseTool to the format your agent expects
# Example: adapted_tool = adapt_to_my_framework(tool)
# adapted_tools.append(adapted_tool)
pass # Replace with your actual adaptation logic
# Configure the external agent with the adapted tools
# Example: self.external_agent.set_tools(adapted_tools)
print(f"Configuring tools for MyCustomAgentAdapter: {adapted_tools}") # Placeholder
else:
# Handle the case where no tools are provided
# Example: self.external_agent.set_tools([])
print("No tools provided for MyCustomAgentAdapter.")
```
4. **`configure_structured_output` 구현하기**:
CrewAI `Agent`가 구조화된 출력 요구사항(예: `output_json` 또는 `output_pydantic`)으로 구성될 때 이 메서드가 호출됩니다. adapter에서 외부 agent가 이러한 요구사항을 준수하도록 설정해야 합니다. 이는 외부 agent에 특정 파라미터를 설정하거나, 해당 모델이 요청된 형식을 지원하는지 확인하는 것이 포함될 수 있습니다. 외부 agent가 CrewAI의 기대에 맞는 방식으로 구조화된 출력을 지원하지 않을 경우, 변환 처리를 하거나 적절한 오류를 발생시켜야 할 수 있습니다.
```python
def configure_structured_output(self, structured_output: Any) -> None:
# Configure your external agent to produce output in the specified format
# Example: self.external_agent.set_output_format(structured_output)
self.adapted_structured_output = True # Signal that structured output is handled
print(f"Configuring structured output for MyCustomAgentAdapter: {structured_output}")
```
이러한 메서드들을 구현함으로써, `MyCustomAgentAdapter`는 커스텀 agent 구현이 CrewAI crew 내에서 올바로 동작할 수 있도록 하여, task 및 도구들과 매끄럽게 상호작용할 수 있게 됩니다. 예시 주석 및 print문은 실제로 통합하려는 외부 agent 프레임워크에 맞춘 로직으로 교체해야 한다는 점을 기억하세요.
## BaseToolAdapter 구현
`BaseToolAdapter` 클래스는 CrewAI의 기본 `BaseTool` 객체를 외부 에이전트 프레임워크가 이해하고 활용할 수 있는 형식으로 변환하는 역할을 합니다. 각각의 에이전트 프레임워크(LangGraph, OpenAI Assistants 등)는 도구를 정의하고 처리하는 고유한 방식을 가지고 있으며, `BaseToolAdapter`는 이들 간의 변환자 역할을 합니다.
사용자 정의 툴 어댑터를 구현하는 방법은 다음과 같습니다:
1. **`BaseToolAdapter`를 상속하세요**:
```python
from crewai.agents.agent_adapters.base_tool_adapter import BaseToolAdapter
from crewai.tools import BaseTool
from typing import List, Any
class MyCustomToolAdapter(BaseToolAdapter):
# ... implementation details ...
```
2. **`configure_tools` 구현**:
이 메소드는 반드시 구현해야 하는 핵심 추상 메소드입니다. 에이전트에 제공된 CrewAI `BaseTool` 인스턴스의 리스트를 인자로 받으며, 각 리스트를 순회하면서 각 `BaseTool`을 외부 프레임워크가 기대하는 형식으로 변환하고, 변환된 도구들을 `self.converted_tools` 리스트(기본 클래스 생성자에서 초기화됨)에 담아야 합니다.
```python
def configure_tools(self, tools: List[BaseTool]) -> None:
"""Configure and convert CrewAI tools for the specific implementation."""
self.converted_tools = [] # Reset in case it's called multiple times
for tool in tools:
# Sanitize the tool name if required by the target framework
sanitized_name = self.sanitize_tool_name(tool.name)
# --- Your Conversion Logic Goes Here ---
# Example: Convert BaseTool to a dictionary format for LangGraph
# converted_tool = {
# "name": sanitized_name,
# "description": tool.description,
# "parameters": tool.args_schema.schema() if tool.args_schema else {},
# # Add any other framework-specific fields
# }
# Example: Convert BaseTool to an OpenAI function definition
# converted_tool = {
# "type": "function",
# "function": {
# "name": sanitized_name,
# "description": tool.description,
# "parameters": tool.args_schema.schema() if tool.args_schema else {"type": "object", "properties": {}},
# }
# }
# --- Replace above examples with your actual adaptation ---
converted_tool = self.adapt_tool_to_my_framework(tool, sanitized_name) # Placeholder
self.converted_tools.append(converted_tool)
print(f"Adapted tool '{tool.name}' to '{sanitized_name}' for MyCustomToolAdapter") # Placeholder
print(f"MyCustomToolAdapter finished configuring tools: {len(self.converted_tools)} adapted.") # Placeholder
# --- Helper method for adaptation (Example) ---
def adapt_tool_to_my_framework(self, tool: BaseTool, sanitized_name: str) -> Any:
# Replace this with the actual logic to convert a CrewAI BaseTool
# to the format needed by your specific external agent framework.
# This will vary greatly depending on the target framework.
adapted_representation = {
"framework_specific_name": sanitized_name,
"framework_specific_description": tool.description,
"inputs": tool.args_schema.schema() if tool.args_schema else None,
"implementation_reference": tool.run # Or however the framework needs to call it
}
# Also ensure the tool works both sync and async
async def async_tool_wrapper(*args, **kwargs):
output = tool.run(*args, **kwargs)
if inspect.isawaitable(output):
return await output
else:
return output
adapted_tool = MyFrameworkTool(
name=sanitized_name,
description=tool.description,
inputs=tool.args_schema.schema() if tool.args_schema else None,
implementation_reference=async_tool_wrapper
)
return adapted_representation
```
3. **어댑터 사용하기**:
일반적으로, `MyCustomAgentAdapter`의 `configure_tools` 메소드 내에서 `MyCustomToolAdapter`를 인스턴스화하여 도구를 처리하고, 외부 에이전트를 구성하기 전에 도구들을 변환합니다.
```python
# Inside MyCustomAgentAdapter.configure_tools
def configure_tools(self, tools: Optional[List[BaseTool]] = None) -> None:
if tools:
tool_adapter = MyCustomToolAdapter() # Instantiate your tool adapter
tool_adapter.configure_tools(tools) # Convert the tools
adapted_tools = tool_adapter.tools() # Get the converted tools
# Now configure your external agent with the adapted_tools
# Example: self.external_agent.set_tools(adapted_tools)
print(f"Configuring external agent with adapted tools: {adapted_tools}") # Placeholder
else:
# Handle no tools case
print("No tools provided for MyCustomAgentAdapter.")
```
`BaseToolAdapter`를 생성하면 도구 변환 로직을 에이전트 어댑테이션과 분리할 수 있어, 통합 작업을 더 깔끔하고 모듈화된 구조로 만들 수 있습니다. 반드시 예시 부분을 실제로 요구되는 외부 에이전트 프레임워크의 변환 로직으로 대체해야 함을 명심하세요.
## BaseConverter
`BaseConverterAdapter`는 CrewAI의 `Task`에서 에이전트가 JSON이나 Pydantic 모델과 같이 특정 구조화된 포맷으로 최종 출력을 반환해야 할 때 중요한 역할을 합니다. 이 어댑터는 CrewAI의 구조화된 출력 요구사항과 외부 에이전트의 기능 사이를 이어주는 다리 역할을 합니다.
주요 책임은 다음과 같습니다:
1. **에이전트의 구조화된 출력 구성:** `Task`의 요구사항(`output_json` 또는 `output_pydantic`)에 따라 연결된 `BaseAgentAdapter`(그리고 간접적으로 외부 에이전트)에게 어떤 포맷이 요구되는지 지시합니다.
2. **시스템 프롬프트 확장:** 에이전트의 시스템 프롬프트를 수정하여 필요한 구조로 출력물을 생성하는 방법에 대한 명확한 지침을 추가합니다.
3. **결과 후처리:** 에이전트로부터 받은 원시 출력을 받아, 요구되는 구조에 따라 파싱, 검증 및 포맷팅을 시도한 후, 최종적으로 문자열(예: JSON 문자열) 형태로 반환합니다.
사용자 지정 컨버터 어댑터를 구현하는 방법은 다음과 같습니다:
1. **`BaseConverterAdapter` 상속**:
```python
from crewai.agents.agent_adapters.base_converter_adapter import BaseConverterAdapter
# Assuming you have your MyCustomAgentAdapter defined
# from .my_custom_agent_adapter import MyCustomAgentAdapter
from crewai.task import Task
from typing import Any
class MyCustomConverterAdapter(BaseConverterAdapter):
# Store the expected output type (e.g., 'json', 'pydantic', 'text')
_output_type: str = 'text'
_output_schema: Any = None # Store JSON schema or Pydantic model
# ... implementation details ...
```
2. **`__init__` 구현**:
생성자는 함께 사용할 `agent_adapter` 인스턴스를 받아야 합니다.
```python
def __init__(self, agent_adapter: Any): # Use your specific AgentAdapter type hint
self.agent_adapter = agent_adapter
print(f"Initializing MyCustomConverterAdapter for agent adapter: {type(agent_adapter).__name__}")
```
3. **`configure_structured_output` 구현**:
이 메서드는 CrewAI `Task` 객체를 받습니다. 작업의 `output_json` 및 `output_pydantic` 속성을 확인하여 요구되는 출력 구조를 결정해야 합니다. 해당 정보(예: `_output_type` 및 `_output_schema`)를 저장하고, 필요하다면 외부 에이전트가 구조화된 출력에 대해 별도의 설정이 필요한 경우 `self.agent_adapter`에 구성 메서드를 호출할 수 있습니다(일부는 agent adapter의 `configure_structured_output`에서 이미 부분적으로 처리되었을 수 있습니다).
```python
def configure_structured_output(self, task: Task) -> None:
"""Configure the expected structured output based on the task."""
if task.output_pydantic:
self._output_type = 'pydantic'
self._output_schema = task.output_pydantic
print(f"Converter: Configured for Pydantic output: {self._output_schema.__name__}")
elif task.output_json:
self._output_type = 'json'
self._output_schema = task.output_json
print(f"Converter: Configured for JSON output with schema: {self._output_schema}")
else:
self._output_type = 'text'
self._output_schema = None
print("Converter: Configured for standard text output.")
# Optionally, inform the agent adapter if needed
# self.agent_adapter.set_output_mode(self._output_type, self._output_schema)
```
4. **`enhance_system_prompt` 구현**:
이 메서드는 에이전트의 기본 시스템 프롬프트 문자열을 받아, 현재 구성된 `_output_type` 및 `_output_schema`에 맞춘 지침을 추가해야 합니다. 목적은 에이전트를 구동하는 LLM이 올바른 포맷으로 출력을 생성하도록 안내하는 것입니다.
```python
def enhance_system_prompt(self, base_prompt: str) -> str:
"""Enhance the system prompt with structured output instructions."""
if self._output_type == 'text':
return base_prompt # No enhancement needed for plain text
instructions = "\n\nYour final answer MUST be formatted as "
if self._output_type == 'json':
schema_str = json.dumps(self._output_schema, indent=2)
instructions += f"a JSON object conforming to the following schema:\n```json\n{schema_str}\n```"
elif self._output_type == 'pydantic':
schema_str = json.dumps(self._output_schema.model_json_schema(), indent=2)
instructions += f"a JSON object conforming to the Pydantic model '{self._output_schema.__name__}' with the following schema:\n```json\n{schema_str}\n```"
instructions += "\nEnsure your entire response is ONLY the valid JSON object, without any introductory text, explanations, or concluding remarks."
print(f"Converter: Enhancing prompt for {self._output_type} output.")
return base_prompt + instructions
```
*참고: 실제 프롬프트 엔지니어링은 사용하는 에이전트/LLM에 따라 조정이 필요할 수 있습니다.*
5. **`post_process_result` 구현**:
이 메서드는 에이전트로부터 받은 원시 문자열 출력을 받습니다. 구조화된 출력(`json` 또는 `pydantic`)이 요청된 경우, 문자열을 예상되는 포맷으로 파싱을 시도해야 합니다. 파싱 오류를 처리(예: 로그 남기기, 간단한 수정 시도, 예외 발생 등)해야 하며, 이 메서드는 **항상 문자열**을 반환해야 합니다. 중간 형식이 딕셔너리나 Pydantic 객체라도 이를 다시 JSON 문자열로 변환하여 반환해야 합니다.
```python
import json
from pydantic import ValidationError
def post_process_result(self, result: str) -> str:
"""Post-process the agent's result to ensure it matches the expected format."""
print(f"Converter: Post-processing result for {self._output_type} output.")
if self._output_type == 'json':
try:
# Attempt to parse and re-serialize to ensure validity and consistent format
parsed_json = json.loads(result)
# Optional: Validate against self._output_schema if it's a JSON schema dictionary
# from jsonschema import validate
# validate(instance=parsed_json, schema=self._output_schema)
return json.dumps(parsed_json)
except json.JSONDecodeError as e:
print(f"Error: Failed to parse JSON output: {e}\nRaw output:\n{result}")
# Handle error: return raw, raise exception, or try to fix
return result # Example: return raw output on failure
# except Exception as e: # Catch validation errors if using jsonschema
# print(f"Error: JSON output failed schema validation: {e}\nRaw output:\n{result}")
# return result
elif self._output_type == 'pydantic':
try:
# Attempt to parse into the Pydantic model
model_instance = self._output_schema.model_validate_json(result)
# Return the model serialized back to JSON
return model_instance.model_dump_json()
except ValidationError as e:
print(f"Error: Failed to validate Pydantic output: {e}\nRaw output:\n{result}")
# Handle error
return result # Example: return raw output on failure
except json.JSONDecodeError as e:
print(f"Error: Failed to parse JSON for Pydantic model: {e}\nRaw output:\n{result}")
return result
else: # 'text'
return result # No processing needed for plain text
```
이러한 메서드를 구현함으로써, `MyCustomConverterAdapter`는 CrewAI 작업의 구조화된 출력 요청이 통합된 외부 에이전트에서 올바르게 처리될 수 있게 하여, 사용자가 CrewAI 프레임워크 내에서 맞춤형 에이전트를 더욱 신뢰성 있고 유용하게 사용할 수 있도록 합니다.
## 기본 제공 어댑터
다음 프레임워크에 대해 기본 제공 어댑터를 제공합니다:
1. LangGraph
2. OpenAI Agents
## 적응형 에이전트로 crew 시작하기:
```python
import json
import os
from typing import List
from crewai_tools import SerperDevTool
from src.crewai import Agent, Crew, Task
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
from crewai.agents.agent_adapters.langgraph.langgraph_adapter import (
LangGraphAgentAdapter,
)
from crewai.agents.agent_adapters.openai_agents.openai_adapter import OpenAIAgentAdapter
# CrewAI Agent
code_helper_agent = Agent(
role="Code Helper",
goal="Help users solve coding problems effectively and provide clear explanations.",
backstory="You are an experienced programmer with deep knowledge across multiple programming languages and frameworks. You specialize in solving complex coding challenges and explaining solutions clearly.",
allow_delegation=False,
verbose=True,
)
# OpenAI Agent Adapter
link_finder_agent = OpenAIAgentAdapter(
role="Link Finder",
goal="Find the most relevant and high-quality resources for coding tasks.",
backstory="You are a research specialist with a talent for finding the most helpful resources. You're skilled at using search tools to discover documentation, tutorials, and examples that directly address the user's coding needs.",
tools=[SerperDevTool()],
allow_delegation=False,
verbose=True,
)
# LangGraph Agent Adapter
reporter_agent = LangGraphAgentAdapter(
role="Reporter",
goal="Report the results of the tasks.",
backstory="You are a reporter who reports the results of the other tasks",
llm=ChatOpenAI(model="gpt-4o"),
allow_delegation=True,
verbose=True,
)
class Code(BaseModel):
code: str
task = Task(
description="Give an answer to the coding question: {task}",
expected_output="A thorough answer to the coding question: {task}",
agent=code_helper_agent,
output_json=Code,
)
task2 = Task(
description="Find links to resources that can help with coding tasks. Use the serper tool to find resources that can help.",
expected_output="A list of links to resources that can help with coding tasks",
agent=link_finder_agent,
)
class Report(BaseModel):
code: str
links: List[str]
task3 = Task(
description="Report the results of the tasks.",
expected_output="A report of the results of the tasks. this is the code produced and then the links to the resources that can help with the coding task.",
agent=reporter_agent,
output_json=Report,
)
# Use in CrewAI
crew = Crew(
agents=[code_helper_agent, link_finder_agent, reporter_agent],
tasks=[task, task2, task3],
verbose=True,
)
result = crew.kickoff(
inputs={"task": "How do you implement an abstract class in python?"}
)
# Print raw result first
print("Raw result:", result)
# Handle result based on its type
if hasattr(result, "json_dict") and result.json_dict:
json_result = result.json_dict
print("\nStructured JSON result:")
print(f"{json.dumps(json_result, indent=2)}")
# Access fields safely
if isinstance(json_result, dict):
if "code" in json_result:
print("\nCode:")
print(
json_result["code"][:200] + "..."
if len(json_result["code"]) > 200
else json_result["code"]
)
if "links" in json_result:
print("\nLinks:")
for link in json_result["links"][:5]: # Print first 5 links
print(f"- {link}")
if len(json_result["links"]) > 5:
print(f"...and {len(json_result['links']) - 5} more links")
elif hasattr(result, "pydantic") and result.pydantic:
print("\nPydantic model result:")
print(result.pydantic.model_dump_json(indent=2))
else:
# Fallback to raw output
print("\nNo structured result available, using raw output:")
print(result.raw[:500] + "..." if len(result.raw) > 500 else result.raw)
```

View File

@@ -0,0 +1,95 @@
---
title: 코딩 에이전트
description: CrewAI 에이전트가 코드를 작성하고 실행할 수 있도록 하는 방법과, 향상된 기능을 위한 고급 기능을 알아보세요.
icon: rectangle-code
---
## 소개
CrewAI 에이전트는 이제 코드를 작성하고 실행할 수 있는 강력한 기능을 갖추게 되어 문제 해결 능력이 크게 향상되었습니다. 이 기능은 계산적 또는 프로그래밍적 해결책이 필요한 작업에 특히 유용합니다.
## 코드 실행 활성화
에이전트에서 코드 실행을 활성화하려면, 에이전트를 생성할 때 `allow_code_execution` 매개변수를 `True`로 설정하면 됩니다.
예시는 다음과 같습니다:
```python Code
from crewai import Agent
coding_agent = Agent(
role="Senior Python Developer",
goal="Craft well-designed and thought-out code",
backstory="You are a senior Python developer with extensive experience in software architecture and best practices.",
allow_code_execution=True
)
```
<Note>
`allow_code_execution` 매개변수의 기본값은 `False`임을 참고하세요.
</Note>
## 중요한 고려 사항
1. **모델 선택**: 코드 실행을 활성화할 때 Claude 3.5 Sonnet 및 GPT-4와 같은 더 강력한 모델을 사용하는 것이 강력히 권장됩니다.
이러한 모델은 프로그래밍 개념에 대해 더 잘 이해하고 있으며, 올바르고 효율적인 코드를 생성할 가능성이 높습니다.
2. **오류 처리**: 코드 실행 기능에는 오류 처리가 포함되어 있습니다. 실행된 코드에서 예외가 발생하면, 에이전트는 오류 메시지를 받아보고 코드를 수정하거나
대체 솔루션을 제공할 수 있습니다. 기본값이 2인 `max_retry_limit` 파라미터는 작업에 대한 최대 재시도 횟수를 제어합니다.
3. **종속성**: 코드 실행 기능을 사용하려면 `crewai_tools` 패키지를 설치해야 합니다. 설치되지 않은 경우, 에이전트는 다음과 같은 정보 메시지를 기록합니다:
"Coding tools not available. Install crewai_tools."
## 코드 실행 프로세스
코드 실행이 활성화된 agent가 프로그래밍이 요구되는 작업을 만났을 때:
<Steps>
<Step title="작업 분석">
agent는 작업을 분석하고 코드 실행이 필요하다는 것을 판단합니다.
</Step>
<Step title="코드 작성">
문제를 해결하는 데 필요한 Python 코드를 작성합니다.
</Step>
<Step title="코드 실행">
해당 코드는 내부 코드 실행 도구(`CodeInterpreterTool`)로 전송됩니다.
</Step>
<Step title="결과 해석">
agent는 결과를 해석하여 응답에 반영하거나 추가 문제 해결에 활용합니다.
</Step>
</Steps>
## 예제 사용법
여기 코드 실행 기능이 있는 agent를 생성하고 이를 task에서 사용하는 자세한 예제가 있습니다:
```python Code
from crewai import Agent, Task, Crew
# Create an agent with code execution enabled
coding_agent = Agent(
role="Python Data Analyst",
goal="Analyze data and provide insights using Python",
backstory="You are an experienced data analyst with strong Python skills.",
allow_code_execution=True
)
# Create a task that requires code execution
data_analysis_task = Task(
description="Analyze the given dataset and calculate the average age of participants.",
agent=coding_agent
)
# Create a crew and add the task
analysis_crew = Crew(
agents=[coding_agent],
tasks=[data_analysis_task]
)
# Execute the crew
result = analysis_crew.kickoff()
print(result)
```
이 예제에서 `coding_agent`는 데이터 분석 작업을 수행하기 위해 Python 코드를 작성하고 실행할 수 있습니다.

View File

@@ -0,0 +1,89 @@
---
title: 조건부 태스크
description: crewAI kickoff에서 조건부 태스크를 사용하는 방법을 알아보세요
icon: diagram-subtask
---
## 소개
crewAI의 조건부 작업(Conditional Tasks)은 이전 작업의 결과에 따라 동적으로 워크플로우를 조정할 수 있도록 합니다.
이 강력한 기능을 통해 crew는 선택적으로 결정을 내리고 작업을 수행할 수 있어, AI 기반 프로세스의 유연성과 효율성이 향상됩니다.
## 예제 사용법
```python Code
from typing import List
from pydantic import BaseModel
from crewai import Agent, Crew
from crewai.tasks.conditional_task import ConditionalTask
from crewai.tasks.task_output import TaskOutput
from crewai.task import Task
from crewai_tools import SerperDevTool
# Define a condition function for the conditional task
# If false, the task will be skipped, if true, then execute the task.
def is_data_missing(output: TaskOutput) -> bool:
return len(output.pydantic.events) < 10 # this will skip this task
# Define the agents
data_fetcher_agent = Agent(
role="Data Fetcher",
goal="Fetch data online using Serper tool",
backstory="Backstory 1",
verbose=True,
tools=[SerperDevTool()]
)
data_processor_agent = Agent(
role="Data Processor",
goal="Process fetched data",
backstory="Backstory 2",
verbose=True
)
summary_generator_agent = Agent(
role="Summary Generator",
goal="Generate summary from fetched data",
backstory="Backstory 3",
verbose=True
)
class EventOutput(BaseModel):
events: List[str]
task1 = Task(
description="Fetch data about events in San Francisco using Serper tool",
expected_output="List of 10 things to do in SF this week",
agent=data_fetcher_agent,
output_pydantic=EventOutput,
)
conditional_task = ConditionalTask(
description="""
Check if data is missing. If we have less than 10 events,
fetch more events using Serper tool so that
we have a total of 10 events in SF this week..
""",
expected_output="List of 10 Things to do in SF this week",
condition=is_data_missing,
agent=data_processor_agent,
)
task3 = Task(
description="Generate summary of events in San Francisco from fetched data",
expected_output="A complete report on the customer and their customers and competitors, including their demographics, preferences, market positioning and audience engagement.",
agent=summary_generator_agent,
)
# Create a crew with the tasks
crew = Crew(
agents=[data_fetcher_agent, data_processor_agent, summary_generator_agent],
tasks=[task1, conditional_task, task3],
verbose=True,
planning=True
)
# Run the crew
result = crew.kickoff()
print("results", result)
```

View File

@@ -0,0 +1,66 @@
---
title: 커스텀 도구 생성
description: CrewAI 프레임워크 내에서 커스텀 도구를 제작, 사용 및 관리하는 종합 가이드로, 신규 기능과 오류 처리를 포함합니다.
icon: hammer
---
## CrewAI에서 툴 생성 및 활용
이 가이드는 CrewAI 프레임워크를 위한 커스텀 툴을 생성하는 방법과 최신 기능(툴 위임, 오류 처리, 동적 툴 호출 등)을 통합하여 이러한 툴을 효율적으로 관리하고 활용하는 방법에 대해 자세히 안내합니다. 또한 협업 툴의 중요성을 강조하며, 에이전트가 다양한 작업을 수행할 수 있도록 지원합니다.
### `BaseTool` 서브클래싱
개인화된 툴을 생성하려면 `BaseTool`을 상속받고, 입력 검증을 위한 `args_schema`와 `_run` 메서드를 포함한 필요한 속성들을 정의해야 합니다.
```python Code
from typing import Type
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class MyToolInput(BaseModel):
"""Input schema for MyCustomTool."""
argument: str = Field(..., description="Description of the argument.")
class MyCustomTool(BaseTool):
name: str = "Name of my tool"
description: str = "What this tool does. It's vital for effective utilization."
args_schema: Type[BaseModel] = MyToolInput
def _run(self, argument: str) -> str:
# Your tool's logic here
return "Tool's result"
```
### `tool` 데코레이터 사용하기
또는 tool 데코레이터 `@tool`을 사용할 수 있습니다. 이 방법은 함수 내에서 도구의 속성과 기능을 직접 정의할 수 있도록 하며, 귀하의 필요에 맞춘 특화된 도구를 간결하고 효율적으로 생성할 수 있는 방법을 제공합니다.
```python Code
from crewai.tools import tool
@tool("Tool Name")
def my_simple_tool(question: str) -> str:
"""Tool description for clarity."""
# Tool logic here
return "Tool output"
```
### 도구를 위한 캐시 함수 정의하기
도구의 성능을 캐싱으로 최적화하려면, `cache_function` 속성을 사용하여 사용자 맞춤 캐싱 전략을 정의할 수 있습니다.
```python Code
@tool("Tool with Caching")
def cached_tool(argument: str) -> str:
"""Tool functionality description."""
return "Cacheable result"
def my_cache_strategy(arguments: dict, result: str) -> bool:
# Define custom caching logic
return True if some_condition else False
cached_tool.cache_function = my_cache_strategy
```
이 가이드라인을 준수하고 새로운 기능과 협업 도구를 도구 생성 및 관리 프로세스에 통합함으로써,
CrewAI 프레임워크의 모든 기능을 활용할 수 있으며, AI agent의 개발 경험과 효율성을 모두 높일 수 있습니다.

View File

@@ -0,0 +1,350 @@
---
title: 커스텀 LLM 구현
description: CrewAI에서 커스텀 LLM 구현을 만드는 방법을 알아보세요.
icon: code
---
## 개요
CrewAI는 `BaseLLM` 추상 기반 클래스를 통해 커스텀 LLM 구현을 지원합니다. 이를 통해 LiteLLM에 내장 지원이 없는 모든 LLM 제공자를 통합하거나, 커스텀 인증 메커니즘을 구현할 수 있습니다.
## 빠른 시작
여기 최소한의 커스텀 LLM 구현 예시가 있습니다:
```python
from crewai import BaseLLM
from typing import Any, Dict, List, Optional, Union
import requests
class CustomLLM(BaseLLM):
def __init__(self, model: str, api_key: str, endpoint: str, temperature: Optional[float] = None):
# IMPORTANT: Call super().__init__() with required parameters
super().__init__(model=model, temperature=temperature)
self.api_key = api_key
self.endpoint = endpoint
def call(
self,
messages: Union[str, List[Dict[str, str]]],
tools: Optional[List[dict]] = None,
callbacks: Optional[List[Any]] = None,
available_functions: Optional[Dict[str, Any]] = None,
) -> Union[str, Any]:
"""Call the LLM with the given messages."""
# Convert string to message format if needed
if isinstance(messages, str):
messages = [{"role": "user", "content": messages}]
# Prepare request
payload = {
"model": self.model,
"messages": messages,
"temperature": self.temperature,
}
# Add tools if provided and supported
if tools and self.supports_function_calling():
payload["tools"] = tools
# Make API call
response = requests.post(
self.endpoint,
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json=payload,
timeout=30
)
response.raise_for_status()
result = response.json()
return result["choices"][0]["message"]["content"]
def supports_function_calling(self) -> bool:
"""Override if your LLM supports function calling."""
return True # Change to False if your LLM doesn't support tools
def get_context_window_size(self) -> int:
"""Return the context window size of your LLM."""
return 8192 # Adjust based on your model's actual context window
```
## 사용자 지정 LLM 사용하기
```python
from crewai import Agent, Task, Crew
# Assuming you have the CustomLLM class defined above
# Create your custom LLM
custom_llm = CustomLLM(
model="my-custom-model",
api_key="your-api-key",
endpoint="https://api.example.com/v1/chat/completions",
temperature=0.7
)
# Use with an agent
agent = Agent(
role="Research Assistant",
goal="Find and analyze information",
backstory="You are a research assistant.",
llm=custom_llm
)
# Create and execute tasks
task = Task(
description="Research the latest developments in AI",
expected_output="A comprehensive summary",
agent=agent
)
crew = Crew(agents=[agent], tasks=[task])
result = crew.kickoff()
```
## 필수 메서드
### 생성자: `__init__()`
**중요**: 반드시 필수 매개변수와 함께 `super().__init__(model, temperature)`을 호출해야 합니다:
```python
def __init__(self, model: str, api_key: str, temperature: Optional[float] = None):
# 필수: 부모 생성자를 model과 temperature로 호출
super().__init__(model=model, temperature=temperature)
# 사용자 정의 초기화
self.api_key = api_key
```
### 추상 메서드: `call()`
`call()` 메서드는 LLM 구현의 핵심입니다. 반드시 다음을 수행해야 합니다:
- 메시지(문자열 또는 'role'과 'content'가 포함된 딕셔너리 리스트)를 받아들임
- 문자열 응답을 반환함
- 지원하는 경우 도구 및 함수 호출을 처리함
- 오류 발생 시 적절한 예외를 발생시킴
### 선택적 메서드
```python
def supports_function_calling(self) -> bool:
"""Return True if your LLM supports function calling."""
return True # Default is True
def supports_stop_words(self) -> bool:
"""Return True if your LLM supports stop sequences."""
return True # Default is True
def get_context_window_size(self) -> int:
"""Return the context window size."""
return 4096 # Default is 4096
```
## 공통 패턴
### 오류 처리
```python
import requests
def call(self, messages, tools=None, callbacks=None, available_functions=None):
try:
response = requests.post(
self.endpoint,
headers={"Authorization": f"Bearer {self.api_key}"},
json=payload,
timeout=30
)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except requests.Timeout:
raise TimeoutError("LLM request timed out")
except requests.RequestException as e:
raise RuntimeError(f"LLM request failed: {str(e)}")
except (KeyError, IndexError) as e:
raise ValueError(f"Invalid response format: {str(e)}")
```
### 커스텀 인증
```python
from crewai import BaseLLM
from typing import Optional
class CustomAuthLLM(BaseLLM):
def __init__(self, model: str, auth_token: str, endpoint: str, temperature: Optional[float] = None):
super().__init__(model=model, temperature=temperature)
self.auth_token = auth_token
self.endpoint = endpoint
def call(self, messages, tools=None, callbacks=None, available_functions=None):
headers = {
"Authorization": f"Custom {self.auth_token}", # Custom auth format
"Content-Type": "application/json"
}
# Rest of implementation...
```
### 스톱 워드 지원
CrewAI는 에이전트의 동작을 제어하기 위해 `"\nObservation:"`를 스톱 워드로 자동 추가합니다. 만약 사용 중인 LLM이 스톱 워드를 지원한다면:
```python
def call(self, messages, tools=None, callbacks=None, available_functions=None):
payload = {
"model": self.model,
"messages": messages,
"stop": self.stop # Include stop words in API call
}
# Make API call...
def supports_stop_words(self) -> bool:
return True # Your LLM supports stop sequences
```
만약 사용 중인 LLM이 스톱 워드를 기본적으로 지원하지 않는다면:
```python
def call(self, messages, tools=None, callbacks=None, available_functions=None):
response = self._make_api_call(messages, tools)
content = response["choices"][0]["message"]["content"]
# Manually truncate at stop words
if self.stop:
for stop_word in self.stop:
if stop_word in content:
content = content.split(stop_word)[0]
break
return content
def supports_stop_words(self) -> bool:
return False # Tell CrewAI we handle stop words manually
```
## 함수 호출
LLM이 함수 호출을 지원하는 경우, 전체 플로우를 구현하세요:
```python
import json
def call(self, messages, tools=None, callbacks=None, available_functions=None):
# Convert string to message format
if isinstance(messages, str):
messages = [{"role": "user", "content": messages}]
# Make API call
response = self._make_api_call(messages, tools)
message = response["choices"][0]["message"]
# Check for function calls
if "tool_calls" in message and available_functions:
return self._handle_function_calls(
message["tool_calls"], messages, tools, available_functions
)
return message["content"]
def _handle_function_calls(self, tool_calls, messages, tools, available_functions):
"""Handle function calling with proper message flow."""
for tool_call in tool_calls:
function_name = tool_call["function"]["name"]
if function_name in available_functions:
# Parse and execute function
function_args = json.loads(tool_call["function"]["arguments"])
function_result = available_functions[function_name](**function_args)
# Add function call and result to message history
messages.append({
"role": "assistant",
"content": None,
"tool_calls": [tool_call]
})
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"name": function_name,
"content": str(function_result)
})
# Call LLM again with updated context
return self.call(messages, tools, None, available_functions)
return "Function call failed"
```
## 문제 해결
### 일반적인 문제
**생성자 오류**
```python
# ❌ Wrong - missing required parameters
def __init__(self, api_key: str):
super().__init__()
# ✅ Correct
def __init__(self, model: str, api_key: str, temperature: Optional[float] = None):
super().__init__(model=model, temperature=temperature)
```
**함수 호출이 작동하지 않음**
- `supports_function_calling()`이 `True`를 반환하는지 확인하세요
- 응답에서 `tool_calls`를 처리하는지 확인하세요
- `available_functions` 매개변수가 올바르게 사용되는지 검증하세요
**인증 실패**
- API 키 형식과 권한을 확인하세요
- 인증 헤더 형식을 점검하세요
- 엔드포인트 URL이 올바른지 확인하세요
**응답 파싱 오류**
- 중첩된 필드에 접근하기 전에 응답 구조를 검증하세요
- content가 None일 수 있는 경우를 처리하세요
- 잘못된 응답에 대한 적절한 오류 처리를 추가하세요
## 커스텀 LLM 테스트하기
```python
from crewai import Agent, Task, Crew
def test_custom_llm():
llm = CustomLLM(
model="test-model",
api_key="test-key",
endpoint="https://api.test.com"
)
# Test basic call
result = llm.call("Hello, world!")
assert isinstance(result, str)
assert len(result) > 0
# Test with CrewAI agent
agent = Agent(
role="Test Agent",
goal="Test custom LLM",
backstory="A test agent.",
llm=llm
)
task = Task(
description="Say hello",
expected_output="A greeting",
agent=agent
)
crew = Crew(agents=[agent], tasks=[task])
result = crew.kickoff()
assert "hello" in result.raw.lower()
```
이 가이드는 CrewAI에서 커스텀 LLM을 구현하는 주요 사항을 다룹니다.

View File

@@ -0,0 +1,90 @@
---
title: 커스텀 매니저 에이전트
description: CrewAI에서 커스텀 에이전트를 매니저로 설정하여 작업 관리 및 조정을 보다 세밀하게 제어하는 방법을 알아보세요.
icon: user-shield
---
# CrewAI에서 특정 에이전트를 매니저로 설정하기
CrewAI는 사용자가 crew의 매니저로 특정 에이전트를 설정할 수 있도록 하여, 작업의 관리 및 조정에 대한 더 많은 제어권을 제공합니다.
이 기능을 통해 프로젝트의 요구 사항에 더 적합하게 매니저 역할을 맞춤화할 수 있습니다.
## `manager_agent` 속성 사용하기
### 커스텀 매니저 에이전트
`manager_agent` 속성을 사용하면 crew를 관리할 커스텀 에이전트를 정의할 수 있습니다. 이 에이전트는 전체 프로세스를 감독하여 작업이 효율적이고 최고의 기준에 맞춰 완료되도록 보장합니다.
### 예시
```python Code
import os
from crewai import Agent, Task, Crew, Process
# Define your agents
researcher = Agent(
role="Researcher",
goal="Conduct thorough research and analysis on AI and AI agents",
backstory="You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.",
allow_delegation=False,
)
writer = Agent(
role="Senior Writer",
goal="Create compelling content about AI and AI agents",
backstory="You're a senior writer, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently writing content for a new client.",
allow_delegation=False,
)
# Define your task
task = Task(
description="Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.",
expected_output="5 bullet points, each with a paragraph and accompanying notes.",
)
# Define the manager agent
manager = Agent(
role="Project Manager",
goal="Efficiently manage the crew and ensure high-quality task completion",
backstory="You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.",
allow_delegation=True,
)
# Instantiate your crew with a custom manager
crew = Crew(
agents=[researcher, writer],
tasks=[task],
manager_agent=manager,
process=Process.hierarchical,
)
# Start the crew's work
result = crew.kickoff()
```
## 맞춤형 Manager 에이전트의 이점
- **향상된 제어**: 프로젝트의 구체적인 요구 사항에 맞게 관리 방식을 조정할 수 있습니다.
- **향상된 조정**: 경험 많은 에이전트를 통해 효율적인 작업 조정 및 관리가 가능합니다.
- **맞춤형 관리**: 프로젝트 목표에 부합하는 관리자 역할과 책임을 정의할 수 있습니다.
## 매니저 LLM 설정하기
계층적 프로세스를 사용하고 있으며 커스텀 매니저 에이전트를 설정하지 않으려는 경우, 매니저에 사용할 언어 모델을 지정할 수 있습니다:
```python Code
from crewai import LLM
manager_llm = LLM(model="gpt-4o")
crew = Crew(
agents=[researcher, writer],
tasks=[task],
process=Process.hierarchical,
manager_llm=manager_llm
)
```
<Note>
계층적 프로세스를 사용할 때는 `manager_agent` 또는 `manager_llm` 중 하나를 반드시 설정해야 합니다.
</Note>

View File

@@ -0,0 +1,110 @@
---
title: 에이전트 맞춤화
description: CrewAI 프레임워크 내에서 특정 역할, 작업 및 고급 맞춤화를 위해 에이전트를 조정하는 종합 가이드입니다.
icon: user-pen
---
## 사용자 지정 가능 속성
효율적인 CrewAI 팀을 구성하려면 AI 에이전트를 프로젝트의 고유한 요구 사항에 맞게 동적으로 조정할 수 있어야 합니다. 이 섹션에서는 사용자 지정할 수 있는 기본 속성에 대해 다룹니다.
### 커스터마이징을 위한 주요 속성
| 속성 | 설명 |
|:-----------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Role** | crew 내에서 에이전트의 직무를 지정합니다. 예: 'Analyst', 'Customer Service Rep' 등. |
| **Goal** | 에이전트의 목표를 정의하며, 이는 해당 role 및 crew의 전체 미션과 조화됩니다. |
| **Backstory** | 에이전트의 페르소나에 깊이를 더해, crew 내에서의 동기 부여와 참여도를 높입니다. |
| **Tools** *(선택 사항)* | 에이전트가 작업을 수행할 때 사용하는 기능이나 방법을 나타냅니다. 단순한 함수부터 복잡한 통합까지 포함될 수 있습니다. |
| **Cache** *(선택 사항)* | 에이전트가 tool 사용 시 캐시를 이용할지 여부를 결정합니다. |
| **Max RPM** | 분당 최대 요청 수(`max_rpm`)를 설정합니다. 외부 서비스에 제한 없는 요청을 원할 경우 `None`으로 설정할 수 있습니다. |
| **Verbose** *(선택 사항)* | 디버깅 및 최적화를 위한 상세 로그를 활성화하며, 실행 과정에 대한 인사이트를 제공합니다. |
| **Allow Delegation** *(선택 사항)* | 다른 에이전트로의 작업 위임을 제어합니다. 기본값은 `False`입니다. |
| **Max Iter** *(선택 사항)* | 무한 루프를 방지하기 위해 작업의 최대 반복 횟수(`max_iter`)를 제한합니다. 기본값은 25입니다. |
| **Max Execution Time** *(선택 사항)* | 에이전트가 작업을 완료하는 데 허용되는 최대 시간을 설정합니다. |
| **System Template** *(선택 사항)* | 에이전트의 시스템 형식을 정의합니다. |
| **Prompt Template** *(선택 사항)* | 에이전트의 프롬프트 형식을 정의합니다. |
| **Response Template** *(선택 사항)* | 에이전트의 응답 형식을 정의합니다. |
| **Use System Prompt** *(선택 사항)* | 작업 수행 중 에이전트가 system prompt를 사용할지 여부를 제어합니다. |
| **Respect Context Window** | 기본적으로 슬라이딩 context 윈도우를 활성화하여(context size를 유지) 설정합니다. |
| **Max Retry Limit** | 오류 발생 시 에이전트의 최대 재시도 횟수(`max_retry_limit`)를 설정합니다. |
## 고급 커스터마이징 옵션
기본 속성 외에도, CrewAI는 에이전트의 행동과 능력을 크게 향상시킬 수 있는 더 깊은 커스터마이징을 허용합니다.
### 언어 모델 커스터마이제이션
에이전트는 특정 언어 모델(`llm`)과 함수 호출 언어 모델(`function_calling_llm`)로 커스터마이즈할 수 있어, 처리 및 의사결정 능력을 고급 수준으로 제어할 수 있습니다.
`function_calling_llm`을 설정하면 기본 crew 함수 호출 언어 모델을 오버라이드할 수 있으므로, 더 높은 수준의 커스터마이제이션이 가능합니다.
## 성능 및 디버깅 설정
에이전트의 성능을 조정하고 운영을 모니터링하는 것은 효율적인 작업 수행을 위해 매우 중요합니다.
### 자세한 모드(Verbose Mode) 및 RPM 제한
- **자세한 모드(Verbose Mode)**: 에이전트의 동작을 자세히 기록하는 로깅을 활성화하여 디버깅과 최적화에 유용합니다. 특히, 에이전트 실행 프로세스에 대한 인사이트를 제공하여 성능 최적화에 도움이 됩니다.
- **RPM 제한**: 분당 최대 요청 수(`max_rpm`)를 설정합니다. 이 속성은 선택 사항이며, 제한이 필요 없을 경우 `None`으로 설정하면 외부 서비스에 무제한 쿼리를 허용할 수 있습니다.
### 작업 실행을 위한 최대 반복 횟수
`max_iter` 속성은 사용자가 하나의 작업에 대해 agent가 수행할 수 있는 최대 반복 횟수를 정의할 수 있게 하여, 무한 루프나 지나치게 긴 실행을 방지해줍니다.
기본값은 25로 설정되어 있어 철저함과 효율성 사이의 균형을 제공합니다. agent가 이 숫자에 가까워질 때, 최선의 답변을 제공하기 위해 노력하게 됩니다.
## 에이전트 및 도구 커스터마이징
에이전트는 초기화 시 속성과 도구를 정의하여 커스터마이징합니다. 도구는 에이전트의 기능에 매우 중요하며, 특정 작업을 수행할 수 있게 해줍니다.
`tools` 속성은 에이전트가 사용할 수 있는 도구의 배열이어야 하며, 기본값으로는 빈 리스트로 초기화됩니다. 도구는 새로운 요구 사항에 맞추어 에이전트 초기화 이후에도 추가하거나 수정할 수 있습니다.
```shell
pip install 'crewai[tools]'
```
### 예시: 에이전트에 도구 할당하기
```python Code
import os
from crewai import Agent
from crewai_tools import SerperDevTool
# Set API keys for tool initialization
os.environ["OPENAI_API_KEY"] = "Your Key"
os.environ["SERPER_API_KEY"] = "Your Key"
# Initialize a search tool
search_tool = SerperDevTool()
# Initialize the agent with advanced options
agent = Agent(
role='Research Analyst',
goal='Provide up-to-date market analysis',
backstory='An expert analyst with a keen eye for market trends.',
tools=[search_tool],
memory=True, # Enable memory
verbose=True,
max_rpm=None, # No limit on requests per minute
max_iter=25, # Default value for maximum iterations
)
```
## 위임 및 자율성
에이전트가 작업을 위임하거나 질문을 할 수 있는 능력을 제어하는 것은 CrewAI 프레임워크 내에서 자율성과 협업 역학을 맞춤화하는 데 매우 중요합니다. 기본적으로
`allow_delegation` 속성은 이제 `False`로 설정되어 있어, 에이전트가 필요에 따라 도움을 요청하거나 작업을 위임하는 것이 비활성화됩니다. 이 기본 동작은 CrewAI 생태계 내에서 협동적 문제 해결과
효율성을 촉진하기 위해 변경될 수 있습니다. 필요할 경우, 특정 운영 요구 사항에 맞게 위임을 활성화할 수 있습니다.
### 예시: 에이전트에 대한 위임 비활성화
```python Code
agent = Agent(
role='Content Writer',
goal='Write engaging content on market trends',
backstory='A seasoned writer with expertise in market analysis.',
allow_delegation=True # Enabling delegation
)
```
## 결론
CrewAI에서 에이전트의 역할, 목표, 배경 이야기, 도구를 설정하고, 언어 모델 커스터마이징, 메모리, 성능 설정, 위임 선호도와 같은 고급 옵션을 함께 활용하면 복잡한 과제에 대응할 준비가 된 세밀하고 유능한 AI 팀을 구성할 수 있습니다.

View File

@@ -0,0 +1,73 @@
---
title: "DALL-E를 활용한 이미지 생성"
description: "CrewAI 프로젝트에서 AI 기반 이미지 생성을 위해 DALL-E를 활용하는 방법을 알아보세요"
icon: "image"
---
CrewAI는 OpenAI의 DALL-E와의 통합을 지원하여, AI 에이전트가 작업의 일환으로 이미지를 생성할 수 있습니다. 이 가이드에서는 CrewAI 프로젝트에서 DALL-E 도구를 설정하고 사용하는 방법을 단계별로 안내합니다.
## 사전 요구 사항
- crewAI가 설치되어 있음 (최신 버전)
- DALL-E에 접근 가능한 OpenAI API 키
## DALL-E 도구 설정하기
<Steps>
<Step title="DALL-E 도구 임포트하기">
```python
from crewai_tools import DallETool
```
</Step>
<Step title="DALL-E 도구를 에이전트 구성에 추가하기">
```python
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[SerperDevTool(), DallETool()], # Add DallETool to the list of tools
allow_delegation=False,
verbose=True
)
```
</Step>
</Steps>
## DALL-E 도구 사용하기
DALL-E 도구를 에이전트에 추가하면 텍스트 프롬프트를 기반으로 이미지를 생성할 수 있습니다. 도구는 생성된 이미지의 URL을 반환하며, 이 URL은 에이전트의 출력에 사용하거나 다른 에이전트에게 전달하여 추가 처리를 할 수 있습니다.
### 예시 에이전트 구성
```yaml
role: >
LinkedIn 프로필 시니어 데이터 연구원
goal: >
제공된 이름 {name}과 도메인 {domain}을 기반으로 자세한 LinkedIn 프로필을 찾아냅니다
도메인 {domain}을 기반으로 Dall-e 이미지를 생성합니다
backstory: >
당신은 관련성이 높은 LinkedIn 프로필을 찾아내는 데 능숙한 숙련된 연구원입니다.
LinkedIn을 효율적으로 탐색하는 능력으로 잘 알려져 있으며, 전문적인 정보를
명확하고 간결하게 수집하고 제시하는 데 뛰어납니다.
```
### 예상 결과
DALL-E 도구를 사용하는 agent는 이미지를 생성하고 응답에 URL을 제공할 수 있습니다. 그런 다음 이미지를 다운로드할 수 있습니다.
<Frame>
<img src="/images/enterprise/dall-e-image.png" alt="DALL-E Image" />
</Frame>
## 모범 사례
1. **이미지 생성 프롬프트를 구체적으로 작성하세요**. 그래야 최상의 결과를 얻을 수 있습니다.
2. **생성 시간을 고려하세요** - 이미지 생성에는 시간이 걸릴 수 있으므로 작업 계획에 이를 반영하세요.
3. **사용 정책을 준수하세요** - 이미지를 생성할 때 항상 OpenAI의 사용 정책을 준수해야 합니다.
## 문제 해결
1. **API 접근 확인** - OpenAI API 키가 DALL-E에 접근 권한이 있는지 확인하세요.
2. **버전 호환성** - 최신 버전의 crewAI와 crewai-tools를 사용하고 있는지 확인하세요.
3. **도구 구성** - DALL-E 도구가 agent의 도구 목록에 올바르게 추가되어 있는지 확인하세요.

View File

@@ -0,0 +1,50 @@
---
title: 도구 출력 결과로 강제 지정하기
description: CrewAI에서 에이전트의 작업에서 도구 출력을 결과로 강제 지정하는 방법을 알아봅니다.
icon: wrench-simple
---
## 소개
CrewAI에서는 도구의 출력을 에이전트 작업의 결과로 강제로 사용할 수 있습니다.
이 기능은 작업 실행 중에 에이전트가 출력을 수정하지 못하도록 하고, 도구의 출력이 반드시 캡처되어 작업 결과로 반환되도록 보장하고 싶을 때 유용합니다.
## 도구 출력을 결과로 강제 지정하기
도구의 출력을 에이전트 작업의 결과로 강제 지정하려면, 에이전트에 도구를 추가할 때 `result_as_answer` 매개변수를 `True`로 설정해야 합니다.
이 매개변수는 도구의 출력이 에이전트에 의해 수정되지 않고 작업 결과로 캡처되어 반환되도록 보장합니다.
다음은 에이전트 작업의 결과로 도구 출력을 강제 지정하는 방법의 예시입니다:
```python Code
from crewai.agent import Agent
from my_tool import MyCustomTool
# Create a coding agent with the custom tool
coding_agent = Agent(
role="Data Scientist",
goal="Produce amazing reports on AI",
backstory="You work with data and AI",
tools=[MyCustomTool(result_as_answer=True)],
)
# Assuming the tool's execution and result population occurs within the system
task_result = coding_agent.execute_task(task)
```
## 워크플로우 실행
<Steps>
<Step title="작업 실행">
에이전트는 제공된 도구를 사용하여 작업을 수행합니다.
</Step>
<Step title="도구 출력">
도구가 출력을 생성하며, 이는 작업 결과로 캡처됩니다.
</Step>
<Step title="에이전트 상호작용">
에이전트는 도구에서 학습하고 반영할 수 있지만, 출력은 수정되지 않습니다.
</Step>
<Step title="결과 반환">
도구 출력은 어떠한 수정 없이 작업 결과로 반환됩니다.
</Step>
</Steps>

View File

@@ -0,0 +1,109 @@
---
title: 계층적 프로세스
description: 최신 코딩 관행 및 기능을 반영하여 CrewAI 프로젝트 내에서 계층적 프로세스를 이해하고 적용하는 종합 가이드입니다.
icon: sitemap
---
## 소개
CrewAI의 계층적 프로세스는 효율적인 작업 위임 및 실행을 위해 전통적인 조직의 계층 구조를 모방하는 구조화된 작업 관리 방식을 도입합니다.
이러한 체계적인 워크플로우는 작업이 최적의 효율성과 정확성으로 처리될 수 있도록 하여 프로젝트 성과를 향상시킵니다.
<Tip>
계층적 프로세스는 GPT-4와 같은 고급 모델을 활용하도록 설계되었으며, 복잡한 작업을 보다 효율적으로 처리하는 동시에 토큰 사용을 최적화합니다.
</Tip>
## 계층적 프로세스 개요
기본적으로 CrewAI에서 task는 순차적인 프로세스를 통해 관리됩니다. 그러나 계층적 접근 방식을 채택하면 명확한 계층 구조의 task 관리를 할 수 있습니다.
이 방식에서는 'manager' agent가 workflow를 조정하고, task를 위임하며, 결과를 검증하여 효율적이고 원활한 실행을 가능하게 합니다. 이 manager agent는 이제 CrewAI에서 자동으로 생성되거나 사용자가 명시적으로 설정할 수 있습니다.
### 주요 기능
- **작업 위임**: 매니저 에이전트가 역할과 역량에 따라 crew 멤버에게 작업을 할당합니다.
- **결과 검증**: 매니저가 결과물을 평가하여 요구되는 기준을 충족하는지 확인합니다.
- **효율적인 워크플로우**: 기업 구조를 모방하여 체계적인 작업 관리 방식을 제공합니다.
- **시스템 프롬프트 처리**: 시스템이 사전 정의된 prompt를 사용할지 옵션으로 지정할 수 있습니다.
- **불용어 제어**: 불용어 사용 여부를 옵션으로 지정할 수 있으며, o1 모델 등 다양한 모델을 지원합니다.
- **컨텍스트 윈도우 존중**: 중요한 컨텍스트를 우선시하며, 컨텍스트 윈도우를 존중하는 것이 기본 동작입니다.
- **위임 제어**: 사용자에게 명확한 제어권을 주기 위해 기본적으로 위임이 비활성화되어 있습니다.
- **분당 최대 요청 수**: 분당 최대 요청 수를 설정할 수 있는 구성 옵션입니다.
- **최대 반복 횟수**: 최종 답변을 얻기 위한 최대 반복 횟수를 제한합니다.
## 계층적 프로세스 구현하기
계층적 프로세스를 활용하려면, 프로세스 속성을 반드시 `Process.hierarchical`로 명시적으로 설정해야 합니다. 기본 동작은 `Process.sequential`입니다.
매니저가 지정된 crew를 정의하고, 명확한 명령 체계를 구축하세요.
<Tip>
도구는 agent 수준에서 할당하여, 매니저의 지시에 따라 지정된 agent가 작업 위임 및 실행을 원활히 수행할 수 있도록 하십시오.
도구는 작업 수준에서도 지정할 수 있어, 작업 수행 시 도구 가용성을 정밀하게 제어할 수 있습니다.
</Tip>
<Tip>
계층적 프로세스에서는 `manager_llm` 파라미터 설정이 매우 중요합니다.
시스템이 올바르게 작동하려면 매니저 LLM이 반드시 설정되어야 하며, 이를 통해 맞춤형 의사결정이 가능합니다.
</Tip>
```python Code
from crewai import Crew, Process, Agent
# Agents are defined with attributes for backstory, cache, and verbose mode
researcher = Agent(
role='Researcher',
goal='Conduct in-depth analysis',
backstory='Experienced data analyst with a knack for uncovering hidden trends.',
)
writer = Agent(
role='Writer',
goal='Create engaging content',
backstory='Creative writer passionate about storytelling in technical domains.',
)
# Establishing the crew with a hierarchical process and additional configurations
project_crew = Crew(
tasks=[...], # Tasks to be delegated and executed under the manager's supervision
agents=[researcher, writer],
manager_llm="gpt-4o", # Specify which LLM the manager should use
process=Process.hierarchical,
planning=True,
)
```
### 커스텀 매니저 에이전트 사용하기
또 다른 방법으로, 프로젝트의 관리 요구 사항에 맞게 맞춤형 속성을 가진 커스텀 매니저 에이전트를 생성할 수 있습니다. 이를 통해 매니저의 동작 및 기능을 보다 세밀하게 제어할 수 있습니다.
```python
# Define a custom manager agent
manager = Agent(
role="Project Manager",
goal="Efficiently manage the crew and ensure high-quality task completion",
backstory="You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success.",
allow_delegation=True,
)
# Use the custom manager in your crew
project_crew = Crew(
tasks=[...],
agents=[researcher, writer],
manager_agent=manager, # Use your custom manager agent
process=Process.hierarchical,
planning=True,
)
```
<Tip>
매니저 에이전트 생성 및 맞춤화에 대한 자세한 내용은 [커스텀 매니저 에이전트 문서](https://docs.crewai.com/how-to/custom-manager-agent#custom-manager-agent)를 참고하세요.
</Tip>
### 워크플로우 실행
1. **작업 할당**: 매니저는 각 에이전트의 역량과 사용 가능한 도구를 고려하여 전략적으로 작업을 할당합니다.
2. **실행 및 검토**: 에이전트는 비동기 실행 옵션과 콜백 함수로 작업을 완료하여 워크플로우를 효율적으로 진행할 수 있습니다.
3. **순차적 작업 진행**: 계층적 프로세스임에도 불구하고, 매니저의 감독 하에 작업은 원활한 진행을 위해 논리적인 순서를 따릅니다.
## 결론
CrewAI에서 계층적 프로세스를 올바른 구성과 시스템 기능에 대한 이해와 함께 도입하면, 조직적이고 효율적인 프로젝트 관리가 가능합니다.
고급 기능과 커스터마이징을 활용하여 워크플로우를 특정 요구에 맞게 맞춤화함으로써, 최적의 작업 실행과 프로젝트 성공을 보장할 수 있습니다.

View File

@@ -0,0 +1,78 @@
---
title: "Human-in-the-Loop (HITL) 워크플로우"
description: "CrewAI에서 Human-in-the-Loop 워크플로우를 구현하여 의사결정을 향상시키는 방법을 알아보세요"
icon: "user-check"
---
휴먼 인 더 루프(HITL, Human-in-the-Loop)는 인공지능과 인간의 전문 지식을 결합하여 의사결정을 강화하고 작업 결과를 향상시키는 강력한 접근 방식입니다. 이 가이드에서는 CrewAI 내에서 HITL을 구현하는 방법을 안내합니다.
## HITL 워크플로우 설정
<Steps>
<Step title="작업 구성">
human input이 활성화된 상태로 작업을 설정하세요:
<Frame>
<img src="/images/enterprise/crew-human-input.png" alt="Crew Human Input" />
</Frame>
</Step>
<Step title="Webhook URL 제공">
crew를 시작할 때, human input을 위한 webhook URL을 포함하세요:
<Frame>
<img src="/images/enterprise/crew-webhook-url.png" alt="Crew Webhook URL" />
</Frame>
</Step>
<Step title="Webhook 알림 수신">
crew가 human input이 필요한 작업을 완료하면, 다음 내용을 포함하는 webhook 알림을 받게 됩니다:
- 실행 ID
- 작업 ID
- 작업 출력
</Step>
<Step title="작업 출력 검토">
시스템이 `Pending Human Input` 상태에서 일시정지됩니다. 작업 출력을 신중하게 검토하세요.
</Step>
<Step title="Human Feedback 제출">
다음 정보를 포함하여 crew의 resume endpoint를 호출하세요:
<Frame>
<img src="/images/enterprise/crew-resume-endpoint.png" alt="Crew Resume Endpoint" />
</Frame>
<Warning>
**피드백이 작업 실행에 미치는 영향**:
피드백의 전체 내용이 추가 컨텍스트로서 이후 작업 실행에 통합되므로, 피드백 제공 시 신중을 기하는 것이 매우 중요합니다.
</Warning>
즉:
- 피드백에 포함된 모든 정보가 작업의 컨텍스트의 일부가 됩니다.
- 관련 없는 세부 정보는 작업에 부정적인 영향을 미칠 수 있습니다.
- 간결하고 관련성 높은 피드백이 작업의 집중력과 효율성을 유지하는 데 도움이 됩니다.
- 제출 전에 피드백을 항상 꼼꼼히 검토하여 작업 실행을 긍정적으로 이끌 수 있는 정보만 포함되어 있는지 확인하세요.
</Step>
<Step title="부정적 피드백 처리">
부정적인 피드백을 제공할 경우:
- crew는 피드백에서 얻은 추가 컨텍스트로 작업을 재시도합니다.
- 추가 검토를 위한 또 다른 webhook 알림을 받게 됩니다.
- 만족할 때까지 4-6단계를 반복하세요.
</Step>
<Step title="실행 계속">
긍정적인 피드백을 제출하면 실행이 다음 단계로 진행됩니다.
</Step>
</Steps>
## 모범 사례
- **구체적으로 작성하세요**: 해당 작업에 직접적으로 관련된 명확하고 실행 가능한 피드백을 제공하세요
- **관련성을 유지하세요**: 작업 수행 개선에 도움이 되는 정보만 포함하세요
- **시기적절하게 응답하세요**: 워크플로우 지연을 방지하기 위해 HITL 프롬프트에 신속하게 응답하세요
- **신중하게 검토하세요**: 제출 전 피드백을 다시 확인하여 정확성을 확보하세요
## 일반적인 사용 사례
HITL 워크플로우는 다음과 같은 경우에 특히 유용합니다:
- 품질 보증 및 검증
- 복잡한 의사결정 시나리오
- 민감하거나 고위험 작업
- 인간의 판단이 필요한 창의적 과제
- 컴플라이언스 및 규제 검토

View File

@@ -0,0 +1,98 @@
---
title: 실행 중 인간 입력
description: 복잡한 의사결정 과정에서 실행 중 CrewAI와 인간 입력을 통합하고, 에이전트의 속성과 도구의 모든 기능을 활용하는 방법.
icon: user-check
---
## 에이전트 실행에서의 인간 입력
인간 입력은 여러 에이전트 실행 시나리오에서 매우 중요하며, 에이전트가 필요할 때 추가 정보나 설명을 요청할 수 있게 해줍니다.
이 기능은 특히 복잡한 의사결정 과정이나 에이전트가 작업을 효과적으로 완료하기 위해 더 많은 세부 정보가 필요할 때 유용하게 사용됩니다.
## CrewAI에서 인간 입력 사용하기
에이전트 실행에 인간 입력을 통합하려면, 태스크 정의에서 `human_input` 플래그를 설정하세요. 이 기능이 활성화되면 에이전트는 최종 답변을 제공하기 전에 사용자에게 입력을 요청합니다.
이 입력은 추가적인 컨텍스트를 제공하거나, 모호성을 해소하거나, 에이전트의 출력을 검증하는 데 사용할 수 있습니다.
### 예시:
```shell
pip install crewai
```
```python Code
import os
from crewai import Agent, Task, Crew
from crewai_tools import SerperDevTool
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
os.environ["OPENAI_API_KEY"] = "Your Key"
# Loading Tools
search_tool = SerperDevTool()
# Define your agents with roles, goals, tools, and additional attributes
researcher = Agent(
role='Senior Research Analyst',
goal='Uncover cutting-edge developments in AI and data science',
backstory=(
"You are a Senior Research Analyst at a leading tech think tank. "
"Your expertise lies in identifying emerging trends and technologies in AI and data science. "
"You have a knack for dissecting complex data and presenting actionable insights."
),
verbose=True,
allow_delegation=False,
tools=[search_tool]
)
writer = Agent(
role='Tech Content Strategist',
goal='Craft compelling content on tech advancements',
backstory=(
"You are a renowned Tech Content Strategist, known for your insightful and engaging articles on technology and innovation. "
"With a deep understanding of the tech industry, you transform complex concepts into compelling narratives."
),
verbose=True,
allow_delegation=True,
tools=[search_tool],
cache=False, # Disable cache for this agent
)
# Create tasks for your agents
task1 = Task(
description=(
"Conduct a comprehensive analysis of the latest advancements in AI in 2025. "
"Identify key trends, breakthrough technologies, and potential industry impacts. "
"Compile your findings in a detailed report. "
"Make sure to check with a human if the draft is good before finalizing your answer."
),
expected_output='A comprehensive full report on the latest AI advancements in 2025, leave nothing out',
agent=researcher,
human_input=True
)
task2 = Task(
description=(
"Using the insights from the researcher\'s report, develop an engaging blog post that highlights the most significant AI advancements. "
"Your post should be informative yet accessible, catering to a tech-savvy audience. "
"Aim for a narrative that captures the essence of these breakthroughs and their implications for the future."
),
expected_output='A compelling 3 paragraphs blog post formatted as markdown about the latest AI advancements in 2025',
agent=writer,
human_input=True
)
# Instantiate your crew with a sequential process
crew = Crew(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=True,
memory=True,
planning=True # Enable planning feature for the crew
)
# Get your crew to work!
result = crew.kickoff()
print("######################")
print(result)
```

View File

@@ -0,0 +1,123 @@
---
title: Crew 비동기 시작
description: Crew를 비동기로 시작하기
icon: rocket-launch
---
## 소개
CrewAI는 crew를 비동기적으로 시작할 수 있는 기능을 제공합니다. 이를 통해 crew 실행을 블로킹(blocking) 없이 시작할 수 있습니다.
이 기능은 여러 개의 crew를 동시에 실행하거나 crew가 실행되는 동안 다른 작업을 수행해야 할 때 특히 유용합니다.
## 비동기 Crew 실행
Crew를 비동기적으로 시작하려면 `kickoff_async()` 메서드를 사용하세요. 이 메서드는 별도의 스레드에서 crew 실행을 시작하여, 메인 스레드가 다른 작업을 계속 실행할 수 있도록 합니다.
### 메서드 시그니처
```python Code
def kickoff_async(self, inputs: dict) -> CrewOutput:
```
### 매개변수
- `inputs` (dict): 작업에 필요한 입력 데이터를 포함하는 딕셔너리입니다.
### 반환
- `CrewOutput`: crew 실행 결과를 나타내는 객체입니다.
## 잠재적 사용 사례
- **병렬 콘텐츠 생성**: 여러 개의 독립적인 crew를 비동기적으로 시작하여, 각 crew가 다른 주제에 대한 콘텐츠 생성을 담당합니다. 예를 들어, 한 crew는 AI 트렌드에 대한 기사 조사 및 초안을 작성하는 반면, 또 다른 crew는 신제품 출시와 관련된 소셜 미디어 게시물을 생성할 수 있습니다. 각 crew는 독립적으로 운영되므로 콘텐츠 생산을 효율적으로 확장할 수 있습니다.
- **동시 시장 조사 작업**: 여러 crew를 비동기적으로 시작하여 시장 조사를 병렬로 수행합니다. 한 crew는 업계 동향을 분석하고, 또 다른 crew는 경쟁사 전략을 조사하며, 또 다른 crew는 소비자 감정을 평가할 수 있습니다. 각 crew는 독립적으로 자신의 작업을 완료하므로 더 빠르고 포괄적인 인사이트를 얻을 수 있습니다.
- **독립적인 여행 계획 모듈**: 각각 독립적으로 여행의 다양한 측면을 계획하도록 crew를 따로 실행합니다. 한 crew는 항공편 옵션을, 다른 crew는 숙박을, 세 번째 crew는 활동 계획을 담당할 수 있습니다. 각 crew는 비동기적으로 작업하므로 여행의 다양한 요소를 동시에 그리고 독립적으로 더 빠르게 계획할 수 있습니다.
## 예시: 단일 비동기 crew 실행
다음은 asyncio를 사용하여 crew를 비동기적으로 시작하고 결과를 await하는 방법의 예시입니다:
```python Code
import asyncio
from crewai import Crew, Agent, Task
# Create an agent with code execution enabled
coding_agent = Agent(
role="Python Data Analyst",
goal="Analyze data and provide insights using Python",
backstory="You are an experienced data analyst with strong Python skills.",
allow_code_execution=True
)
# Create a task that requires code execution
data_analysis_task = Task(
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
agent=coding_agent,
expected_output="The average age of the participants."
)
# Create a crew and add the task
analysis_crew = Crew(
agents=[coding_agent],
tasks=[data_analysis_task]
)
# Async function to kickoff the crew asynchronously
async def async_crew_execution():
result = await analysis_crew.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
print("Crew Result:", result)
# Run the async function
asyncio.run(async_crew_execution())
```
## 예제: 다중 비동기 Crew 실행
이 예제에서는 여러 Crew를 비동기적으로 시작하고 `asyncio.gather()`를 사용하여 모두 완료될 때까지 기다리는 방법을 보여줍니다:
```python Code
import asyncio
from crewai import Crew, Agent, Task
# Create an agent with code execution enabled
coding_agent = Agent(
role="Python Data Analyst",
goal="Analyze data and provide insights using Python",
backstory="You are an experienced data analyst with strong Python skills.",
allow_code_execution=True
)
# Create tasks that require code execution
task_1 = Task(
description="Analyze the first dataset and calculate the average age of participants. Ages: {ages}",
agent=coding_agent,
expected_output="The average age of the participants."
)
task_2 = Task(
description="Analyze the second dataset and calculate the average age of participants. Ages: {ages}",
agent=coding_agent,
expected_output="The average age of the participants."
)
# Create two crews and add tasks
crew_1 = Crew(agents=[coding_agent], tasks=[task_1])
crew_2 = Crew(agents=[coding_agent], tasks=[task_2])
# Async function to kickoff multiple crews asynchronously and wait for all to finish
async def async_multiple_crews():
# Create coroutines for concurrent execution
result_1 = crew_1.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
result_2 = crew_2.kickoff_async(inputs={"ages": [20, 22, 24, 28, 30]})
# Wait for both crews to finish
results = await asyncio.gather(result_1, result_2)
for i, result in enumerate(results, 1):
print(f"Crew {i} Result:", result)
# Run the async function
asyncio.run(async_multiple_crews())
```

View File

@@ -0,0 +1,53 @@
---
title: 각 항목에 대한 Kickoff Crew
description: 목록의 각 항목에 대한 Kickoff Crew
icon: at
---
## 소개
CrewAI는 목록의 각 항목에 대해 crew를 시작할 수 있는 기능을 제공하여, 목록의 각 항목에 대해 crew를 실행할 수 있게 합니다.
이 기능은 여러 항목에 대해 동일한 작업 세트를 수행해야 할 때 특히 유용합니다.
## 각 항목에 대해 크루 시작하기
리스트의 각 항목에 대해 크루를 시작하려면 `kickoff_for_each()` 메서드를 사용하세요.
이 메서드는 리스트의 각 항목에 대해 크루를 실행하여 여러 항목을 효율적으로 처리할 수 있도록 합니다.
아래는 리스트의 각 항목에 대해 크루를 시작하는 방법의 예시입니다:
```python Code
from crewai import Crew, Agent, Task
# Create an agent with code execution enabled
coding_agent = Agent(
role="Python Data Analyst",
goal="Analyze data and provide insights using Python",
backstory="You are an experienced data analyst with strong Python skills.",
allow_code_execution=True
)
# Create a task that requires code execution
data_analysis_task = Task(
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
agent=coding_agent,
expected_output="The average age calculated from the dataset"
)
# Create a crew and add the task
analysis_crew = Crew(
agents=[coding_agent],
tasks=[data_analysis_task],
verbose=True,
memory=False
)
datasets = [
{ "ages": [25, 30, 35, 40, 45] },
{ "ages": [20, 25, 30, 35, 40] },
{ "ages": [30, 35, 40, 45, 50] }
]
# Execute the crew
result = analysis_crew.kickoff_for_each(inputs=datasets)
```

View File

@@ -0,0 +1,205 @@
---
title: 모든 LLM에 연결하기
description: LiteLLM을 사용하여 CrewAI를 다양한 대형 언어 모델(LLM)과 통합하는 방법에 대한 종합적인 가이드로, 지원되는 제공자와 구성 옵션을 포함합니다.
icon: brain-circuit
---
## CrewAI를 LLM에 연결하기
CrewAI는 LiteLLM을 사용하여 다양한 언어 모델(LLM)에 연결합니다. 이 통합은 높은 다양성을 제공하여, 여러 공급자의 모델을 간단하고 통합된 인터페이스로 사용할 수 있게 해줍니다.
<Note>
기본적으로 CrewAI는 `gpt-4o-mini` 모델을 사용합니다. 이는 `OPENAI_MODEL_NAME` 환경 변수에 의해 결정되며, 설정되지 않은 경우 기본값은 "gpt-4o-mini"입니다.
본 가이드에 설명된 대로 다른 모델이나 공급자를 사용하도록 에이전트를 쉽게 설정할 수 있습니다.
</Note>
## 지원되는 프로바이더
LiteLLM은 다음을 포함하되 이에 국한되지 않는 다양한 프로바이더를 지원합니다:
- OpenAI
- Anthropic
- Google (Vertex AI, Gemini)
- Azure OpenAI
- AWS (Bedrock, SageMaker)
- Cohere
- VoyageAI
- Hugging Face
- Ollama
- Mistral AI
- Replicate
- Together AI
- AI21
- Cloudflare Workers AI
- DeepInfra
- Groq
- SambaNova
- Nebius AI Studio
- [NVIDIA NIMs](https://docs.api.nvidia.com/nim/reference/models-1)
- 그리고 더 많은 프로바이더!
지원되는 프로바이더의 전체 및 최신 목록은 [LiteLLM 프로바이더 문서](https://docs.litellm.ai/docs/providers)를 참조하세요.
## LLM 변경하기
CrewAI agent에서 다른 LLM을 사용하려면 여러 가지 방법이 있습니다:
<Tabs>
<Tab title="문자열 식별자 사용">
agent를 초기화할 때 모델 이름을 문자열로 전달하세요:
<CodeGroup>
```python Code
from crewai import Agent
# OpenAI의 GPT-4 사용
openai_agent = Agent(
role='OpenAI Expert',
goal='Provide insights using GPT-4',
backstory="An AI assistant powered by OpenAI's latest model.",
llm='gpt-4'
)
# Anthropic의 Claude 사용
claude_agent = Agent(
role='Anthropic Expert',
goal='Analyze data using Claude',
backstory="An AI assistant leveraging Anthropic's language model.",
llm='claude-2'
)
```
</CodeGroup>
</Tab>
<Tab title="LLM 클래스 사용">
더 자세한 설정을 위해 LLM 클래스를 사용하세요:
<CodeGroup>
```python Code
from crewai import Agent, LLM
llm = LLM(
model="gpt-4",
temperature=0.7,
base_url="https://api.openai.com/v1",
api_key="your-api-key-here"
)
agent = Agent(
role='Customized LLM Expert',
goal='Provide tailored responses',
backstory="An AI assistant with custom LLM settings.",
llm=llm
)
```
</CodeGroup>
</Tab>
</Tabs>
## 구성 옵션
에이전트를 위해 LLM을 구성할 때 다양한 매개변수를 사용할 수 있습니다:
| 매개변수 | 유형 | 설명 |
|:----------|:-----:|:-------------|
| **model** | `str` | 사용할 모델의 이름 (예: "gpt-4", "claude-2") |
| **temperature** | `float` | 출력의 무작위성 제어 (0.0 ~ 1.0) |
| **max_tokens** | `int` | 생성할 최대 토큰 수 |
| **top_p** | `float` | 출력 다양성 제어 (0.0 ~ 1.0) |
| **frequency_penalty** | `float` | 지금까지의 텍스트에서 빈도에 따라 새로운 토큰에 패널티 부여 |
| **presence_penalty** | `float` | 지금까지의 텍스트에 이미 존재하는지에 따라 새로운 토큰에 패널티 부여 |
| **stop** | `str`, `List[str]` | 생성을 중단할 시퀀스(들) |
| **base_url** | `str` | API 엔드포인트의 기본 URL |
| **api_key** | `str` | 인증용 API 키 |
매개변수와 그 설명의 전체 목록은 LLM 클래스 문서를 참고하십시오.
## OpenAI 호환 LLM에 연결하기
OpenAI 호환 LLM에 연결하려면 환경 변수를 사용하거나 LLM 클래스에서 특정 속성을 설정할 수 있습니다:
<Tabs>
<Tab title="환경 변수 사용하기">
<CodeGroup>
```python Generic
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"
os.environ["OPENAI_API_BASE"] = "https://api.your-provider.com/v1"
os.environ["OPENAI_MODEL_NAME"] = "your-model-name"
```
```python Google
import os
# Gemini의 OpenAI 호환 API 예시입니다.
os.environ["OPENAI_API_KEY"] = "your-gemini-key" # AIza...로 시작해야 합니다.
os.environ["OPENAI_API_BASE"] = "https://generativelanguage.googleapis.com/v1beta/openai/"
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-2.0-flash" # Gemini 모델을 여기에 추가하세요. openai/ 하위에 위치.
```
</CodeGroup>
</Tab>
<Tab title="LLM 클래스 속성 사용하기">
<CodeGroup>
```python Generic
llm = LLM(
model="custom-model-name",
api_key="your-api-key",
base_url="https://api.your-provider.com/v1"
)
agent = Agent(llm=llm, ...)
```
```python Google
# Gemini의 OpenAI 호환 API 예시
llm = LLM(
model="openai/gemini-2.0-flash",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key="your-gemini-key", # AIza...로 시작해야 합니다.
)
agent = Agent(llm=llm, ...)
```
</CodeGroup>
</Tab>
</Tabs>
## Ollama와 함께 로컬 모델 사용하기
Ollama에서 제공하는 로컬 모델의 경우:
<Steps>
<Step title="Ollama 다운로드 및 설치">
[여기를 클릭하여 Ollama를 다운로드 및 설치하세요](https://ollama.com/download)
</Step>
<Step title="원하는 모델 가져오기">
예를 들어, `ollama pull llama3.2`를 실행하여 모델을 다운로드합니다.
</Step>
<Step title="에이전트 구성">
<CodeGroup>
```python Code
agent = Agent(
role='Local AI Expert',
goal='Process information using a local model',
backstory="An AI assistant running on local hardware.",
llm=LLM(model="ollama/llama3.2", base_url="http://localhost:11434")
)
```
</CodeGroup>
</Step>
</Steps>
## 기본 API URL 변경하기
어떤 LLM provider든 `base_url` 파라미터를 설정하여 기본 API URL을 변경할 수 있습니다:
```python Code
llm = LLM(
model="custom-model-name",
base_url="https://api.your-provider.com/v1",
api_key="your-api-key"
)
agent = Agent(llm=llm, ...)
```
이 기능은 OpenAI 호환 API를 사용할 때나 선택한 provider에 대해 다른 endpoint를 지정해야 할 때 특히 유용합니다.
## 결론
LiteLLM을 활용함으로써 CrewAI는 다양한 LLM과의 원활한 통합을 제공합니다. 이러한 유연성 덕분에 성능, 비용 효율성 또는 로컬 배포 등 귀하의 특정 요구 사항에 가장 적합한 모델을 선택할 수 있습니다. 지원되는 모델과 구성 옵션에 대한 최신 정보는 반드시 [LiteLLM 문서](https://docs.litellm.ai/docs/)를 참고하시기 바랍니다.

View File

@@ -0,0 +1,729 @@
---
title: '전략적 LLM 선택 가이드'
description: 'CrewAI AI 에이전트를 위한 적합한 LLM 선택 및 효과적인 작업과 에이전트 정의 작성에 대한 전략적 프레임워크'
icon: 'brain-circuit'
---
## CrewAI의 LLM 선택 접근 방식
처방적인 모델 추천보다는, **사고 프레임워크**를 제안하여 특정 사용 사례, 제약 조건, 요구 사항에 따라 정보에 입각한 결정을 내릴 수 있도록 돕고자 합니다. LLM 환경은 빠르게 변화하고 있으며, 새로운 모델이 정기적으로 등장하고 기존 모델도 자주 업데이트되고 있습니다. 가장 중요한 것은 어떤 특정 모델이 제공되는지와 상관없이 평가를 위한 체계적인 접근법을 개발하는 것입니다.
<Note>
이 가이드는 LLM 환경이 빠르게 변화하고 있기 때문에 특정 모델 추천보다는 전략적 사고에 초점을 맞추고 있습니다.
</Note>
## 빠른 결정 프레임워크
<Steps>
<Step title="작업 분석">
먼저, 작업이 실제로 무엇을 요구하는지 깊이 이해하세요. 필요한 인지 복잡성, 요구되는 추론의 깊이, 기대되는 출력 형식, 모델이 처리해야 할 맥락의 양을 고려합니다. 이러한 기본 분석이 이후의 모든 결정을 안내할 것입니다.
</Step>
<Step title="모델 역량 매핑">
요구 사항을 이해한 후, 이를 모델의 강점에 매핑하세요. 서로 다른 모델 계열은 작업 유형에 따라 특화되어 있습니다. 일부는 추론 및 분석에 최적화되어 있고, 일부는 창의성이나 콘텐츠 생성, 또 다른 일부는 속도와 효율성에 최적화되어 있습니다.
</Step>
<Step title="제약 조건 고려">
예산 제한, 지연 시간 요구사항, 데이터 프라이버시 필요성, 인프라 역량 등 실제 운영상의 제약 조건을 반영하세요. 이론적으로 가장 좋은 모델이 실제로는 최선의 선택이 아닐 수 있습니다.
</Step>
<Step title="테스트 및 반복">
신뢰할 수 있고 잘 이해된 모델로 시작하여, 특정 사용 사례에서 실제 성능을 바탕으로 최적화하세요. 실제 결과는 이론적 벤치마크와 다를 수 있으므로, 경험적 테스트가 매우 중요합니다.
</Step>
</Steps>
## 코어 선택 프레임워크
### a. Task-First Thinking
LLM을 선택할 때 가장 중요한 단계는 실제로 여러분의 작업이 무엇을 요구하는지 이해하는 것입니다. 너무 자주 팀들은 특정 요구 사항을 면밀하게 분석하지 않고, 일반적인 평판이나 벤치마크 점수를 기반으로 모델을 선택합니다. 이런 접근 방식은 단순한 작업에 비싸고 복잡한 모델을 과도하게 적용하거나, 정교한 업무에 필요한 기능이 부족한 모델을 선택하게 만들어 결과적으로 과소 성능 문제를 야기합니다.
<Tabs>
<Tab title="Reasoning Complexity">
- **Simple Tasks**는 대부분의 일상적인 AI 작업을 대표하며, 기본 명령 수행, 간단한 데이터 처리, 단순한 포맷팅 작업 등을 포함합니다. 이러한 작업은 일반적으로 명확한 입력과 출력을 가지고 있으며 모호성이 거의 없습니다. 인지적 부하는 낮고, 모델은 복잡한 추론보다는 명확한 지시에 따라 움직이면 됩니다.
- **Complex Tasks**는 다단계 추론, 전략적 사고, 모호하거나 불완전한 정보를 처리하는 능력을 필요로 합니다. 여러 데이터 소스를 분석하거나, 포괄적 전략을 개발하거나, 더 작은 구성 요소로 분해해야 하는 문제 해결 작업 등이 이에 해당합니다. 모델은 여러 추론 단계를 거치는 동안 맥락을 유지해야 하며, 명시적으로 언급되지 않은 내용을 추론해야 할 때가 많습니다.
- **Creative Tasks**는 새롭고, 흥미로우며, 맥락에 적합한 콘텐츠를 생성하는 데 중점을 둔 새로운 인지적 능력을 요구합니다. 여기에는 스토리텔링, 마케팅 카피 작성, 창의적 문제 해결이 포함됩니다. 모델은 뉘앙스, 톤, 대상 청중을 이해하고, 공식적이지 않고 진정성 있고 흥미로운 콘텐츠를 제작해야 합니다.
</Tab>
<Tab title="Output Requirements">
- **Structured Data** 작업은 포맷 규칙 준수의 정확성과 일관성을 요구합니다. JSON, XML, 데이터베이스 포맷 등을 다루는 경우, 모델은 구문적으로 올바른 출력을 안정적으로 생성할 수 있어야 하며, 이는 프로그램적으로 처리 가능해야 합니다. 이런 작업에는 엄격한 검증 요구 사항이 있으며 포맷 에러에 대한 허용 오차가 매우 적기 때문에, 창의성보다는 신뢰성이 더 중요합니다.
- **Creative Content** 출력은 기술적 역량과 창의적 감각의 균형을 필요로 합니다. 모델은 대상 청중, 톤, 브랜드 보이스를 이해하고, 독자의 관심을 끌며 특정 커뮤니케이션 목표를 달성하는 콘텐츠를 제작할 수 있어야 합니다. 이 영역의 품질은 주관적인 경우가 많으며, 다양한 맥락과 목적에 맞게 글쓰기 스타일을 조정할 수 있는 모델이 필요합니다.
- **Technical Content**는 구조화된 데이터와 창의적 콘텐츠의 중간에 위치하며, 정확성과 명확성을 모두 필요로 합니다. 문서화, 코드 생성, 기술 분석 등은 정밀하면서도 포괄적으로 작성되어야 하며, 대상이 되는 청중에게 효과적으로 전달되어야 합니다. 모델은 복잡한 기술 개념을 이해하고 이를 명확하게 설명할 수 있어야 합니다.
</Tab>
<Tab title="Context Needs">
- **Short Context** 시나리오는 모델이 한정된 정보를 신속하게 처리해야 하는 즉각적이고 집중된 업무를 포함합니다. 이는 대체로 속도와 효율성이 심도 있는 이해보다 더 중요한 거래성 상호작용에서 주로 발생합니다. 모델은 긴 대화 내역이나 대용량 문서를 유지할 필요가 없습니다.
- **Long Context** 요구 사항은 방대한 문서 작업, 장기간 대화, 복잡한 다중 파트 작업을 처리할 때 발생합니다. 모델은 수천 토큰에 걸쳐 일관성을 유지해야 하며, 앞선 정보를 정확히 참조할 수 있어야 합니다. 이는 문서 분석, 포괄적 연구, 정교한 대화 시스템에 매우 중요한 기능입니다.
- **Very Long Context** 시나리오는 현재 가능한 한계를 뛰어넘는 경우로, 대규모 문서 처리, 광범위한 연구 종합, 복잡한 다중 세션 상호작용 등이 있습니다. 이러한 활용 사례는 확장된 컨텍스트 처리를 위해 특별히 설계된 모델이 필요하며, 종종 컨텍스트 길이와 처리 속도 간의 절충이 발생합니다.
</Tab>
</Tabs>
### b. 모델 역량 매핑
모델 역량을 이해하기 위해서는 마케팅 주장이나 벤치마크 점수 너머를 바라보고, 다양한 모델 구조와 학습 접근법의 근본적인 강점과 한계를 파악해야 합니다.
<AccordionGroup>
<Accordion title="Reasoning Models" icon="brain">
Reasoning 모델은 복잡하고 다단계의 사고가 필요한 작업을 위해 특별히 설계된 특수 카테고리를 나타냅니다. 이러한 모델은 문제를 신중하게 분석하거나 전략적으로 계획을 세우거나 체계적으로 문제를 분해해야 하는 경우에 뛰어납니다. 일반적으로 chain-of-thought reasoning 혹은 tree-of-thought processing과 같은 기법을 사용하여 복잡한 문제를 단계별로 해결합니다.
Reasoning 모델의 강점은 확장된 reasoning 체인에서 논리적 일관성을 유지하고, 복잡한 문제를 관리 가능한 구성 요소로 나눌 수 있다는 점에 있습니다. 전략적 계획, 복잡한 분석, 그리고 응답 속도보다 reasoning의 질이 더 중요한 상황에서 특히 가치가 있습니다.
하지만 reasoning 모델은 속도와 비용 면에서 트레이드오프가 따르는 경우가 많습니다. 또한 그들의 고도화된 reasoning 역량이 필요 없는 창의적인 작업이나 간단한 작업에는 덜 적합할 수 있습니다. 체계적이고 단계적인 분석이 요구되는 진정한 복잡성이 관련된 작업에서 이러한 모델을 고려하십시오.
</Accordion>
<Accordion title="General Purpose Models" icon="microchip">
General purpose 모델은 LLM 선택에서 가장 균형 잡힌 접근 방식을 제공하며, 특정 영역에 극단적으로 특화되지 않으면서도 다양한 작업에 대해 견고한 성능을 제공합니다. 이러한 모델은 다양한 데이터셋으로 학습되었으며, 특정 도메인에서의 최고 성능보다는 다재다능함에 최적화되어 있습니다.
General purpose 모델의 주요 장점은 다양한 유형의 작업에서 예측 가능한 신뢰성과 일관성입니다. 조사, 분석, 콘텐츠 제작, 데이터 처리 등 대부분의 표준 비즈니스 작업을 충분히 처리할 수 있습니다. 이로 인해 다양한 워크플로우 전반에서 일관된 성능이 필요한 팀에 매우 적합한 선택이 됩니다.
General purpose 모델은 특정 도메인에서 특화된 대안들이 보여주는 최고 성능에는 미치지 않을 수 있지만, 운영의 단순성과 모델 관리의 복잡성 감소라는 이점이 있습니다. 신규 프로젝트의 시작점으로 가장 좋은 선택인 경우가 많으며, 팀이 구체적인 필요를 이해하고 나서 특화 모델로 최적화할 수 있습니다.
</Accordion>
<Accordion title="Fast & Efficient Models" icon="bolt">
Fast and efficient 모델은 고도화된 reasoning 역량보다 속도, 비용 효율, 리소스 효율성을 우선순위에 둡니다. 이러한 모델은 빠른 응답성과 낮은 운영비용이 중요하고, 미묘한 이해나 복잡한 reasoning이 덜 요구되는 고처리량 시나리오에 최적화되어 있습니다.
이러한 모델은 일상적인 운영, 간단한 데이터 처리, 함수 호출, 대용량 작업 등 인지적 요구가 비교적 단순한 시나리오에서 뛰어납니다. 많은 요청을 신속하게 처리해야 하거나 예산 제약 내에서 운영되어야 하는 애플리케이션에 특히 유용합니다.
효율적인 모델에서 가장 중요한 고려사항은 그들의 역량이 귀하의 작업 요구와 일치하는지 확인하는 것입니다. 많은 일상적 작업은 효과적으로 처리할 수 있지만, Nuanced한 이해, 복잡한 reasoning, 혹은 고도화된 콘텐츠 생성이 필요한 작업에는 어려움을 겪을 수 있습니다. 정교함보다 속도와 비용이 더 중요한 명확하고 일상적인 작업에 가장 적합합니다.
</Accordion>
<Accordion title="Creative Models" icon="pen">
Creative 모델은 콘텐츠 생성, 글쓰기 품질, 창의적 사고가 요구되는 작업에 특별히 최적화되어 있습니다. 이러한 모델은 뉘앙스, 톤, 스타일을 이해하면서도 자연스럽고 진정성 있게 느껴지는 매력적이고 맥락에 맞는 콘텐츠를 생성하는 데 뛰어납니다.
Creative 모델의 강점은 다양한 대상에 맞춰 글쓰기 스타일을 조정하고, 일관된 목소리와 톤을 유지하며, 독자를 효과적으로 사로잡는 콘텐츠를 생성할 수 있다는 점입니다. 스토리텔링, 마케팅 카피, 브랜드 커뮤니케이션 등 창의성과 몰입이 주요 목적이 되는 콘텐츠 작업에서 더 우수한 성과를 보입니다.
Creative 모델을 선택할 때는 단순한 텍스트 생성 능력뿐 아니라, 대상, 맥락, 목적에 대한 이해력도 함께 고려해야 합니다. 최상의 creative 모델은 특정 브랜드 목소리에 맞게 출력 내용을 조정하고, 다양한 대상 그룹을 타깃팅하며, 긴 콘텐츠에서도 일관성을 유지할 수 있습니다.
</Accordion>
<Accordion title="Open Source Models" icon="code">
Open source 모델은 비용 통제, 맞춤화 가능성, 데이터 프라이버시, 배포 유연성 측면에서 독특한 이점을 제공합니다. 이러한 모델은 로컬이나 사설 인프라에서 운용이 가능하여 데이터 처리 및 모델 동작에 대해 완전한 통제권을 제공합니다.
Open source 모델의 주요 이점으로는 토큰당 비용의 제거, 특정 용도에 맞춘 파인튜닝 가능성, 완전한 데이터 프라이버시, 외부 API 제공자에 대한 의존성 해소가 있습니다. 특히 엄격한 데이터 프라이버시 요구사항, 예산 제약, 특정 맞춤화 필요가 있는 조직에 매우 유용합니다.
그러나 open source 모델은 효과적으로 배포 및 유지관리하기 위해 더 많은 기술 전문성이 필요합니다. 팀에서는 인프라 비용, 모델 관리 복잡성, 지속적인 모델 업데이트 및 최적화를 위한 지속적인 노력을 고려해야 합니다. 기술적 오버헤드를 감안하면 전체 소유 비용이 클라우드 기반 대안보다 높을 수 있습니다.
</Accordion>
</AccordionGroup>
## 전략적 구성 패턴
### a. 멀티-모델 접근 방식
<Tip>
동일 crew 내에서 다양한 목적에 맞는 서로 다른 모델을 사용해 성능과 비용을 모두 최적화할 수 있습니다.
</Tip>
가장 정교하게 구현된 CrewAI의 경우, 여러 개의 모델을 전략적으로 활용하여 각 agent의 역할과 요구 사항에 맞는 모델을 지정합니다. 이 접근 방식은 각 작업 유형에 가장 적합한 모델을 사용함으로써 성능과 비용을 모두 최적화할 수 있게 해줍니다.
planning agent는 복잡한 전략적 사고와 다단계 분석을 처리할 수 있는 reasoning 모델을 활용할 때 이점을 얻습니다. 이 agent들은 운영의 “두뇌” 역할을 하며, 전략 수립과 다른 agent들의 작업을 조정합니다. 반면 content agent는 글의 품질과 독자 참여에 뛰어난 creative 모델을 통해 최고의 성능을 발휘합니다. 일상적인 작업과 운영을 담당하는 processing agent는 속도와 비용 효율을 우선시하는 효율적인 모델을 사용할 수 있습니다.
**예시: Research and Analysis Crew**
```python
from crewai import Agent, Task, Crew, LLM
# High-capability reasoning model for strategic planning
manager_llm = LLM(model="gemini-2.5-flash-preview-05-20", temperature=0.1)
# Creative model for content generation
content_llm = LLM(model="claude-3-5-sonnet-20241022", temperature=0.7)
# Efficient model for data processing
processing_llm = LLM(model="gpt-4o-mini", temperature=0)
research_manager = Agent(
role="Research Strategy Manager",
goal="Develop comprehensive research strategies and coordinate team efforts",
backstory="Expert research strategist with deep analytical capabilities",
llm=manager_llm, # High-capability model for complex reasoning
verbose=True
)
content_writer = Agent(
role="Research Content Writer",
goal="Transform research findings into compelling, well-structured reports",
backstory="Skilled writer who excels at making complex topics accessible",
llm=content_llm, # Creative model for engaging content
verbose=True
)
data_processor = Agent(
role="Data Analysis Specialist",
goal="Extract and organize key data points from research sources",
backstory="Detail-oriented analyst focused on accuracy and efficiency",
llm=processing_llm, # Fast, cost-effective model for routine tasks
verbose=True
)
crew = Crew(
agents=[research_manager, content_writer, data_processor],
tasks=[...], # Your specific tasks
manager_llm=manager_llm, # Manager uses the reasoning model
verbose=True
)
```
성공적인 멀티-모델 구현의 핵심은 서로 다른 agent들이 어떻게 상호작용하는지를 이해하고, 모델의 역량이 agent의 책임에 부합하는지 확인하는 것입니다. 이를 위해 신중한 기획이 필요하지만, 그 결과로 산출물의 품질과 운영 효율성 모두에서 큰 개선을 이끌어낼 수 있습니다.
### b. 구성요소별 선택
<Tabs>
<Tab title="Manager LLM">
Manager LLM은 계층적 CrewAI 프로세스에서 중요한 역할을 하며, 여러 에이전트와 작업을 조정하는 중심점으로 작동합니다. 이 모델은 위임, 작업 우선순위 지정, 여러 동시 작업 간의 컨텍스트 유지에 뛰어나야 합니다.
효과적인 Manager LLM은 올바른 위임 결정을 내리기 위한 강력한 추론 능력, 예측 가능한 조정을 보장하는 일관된 성능, 여러 에이전트의 상태를 동시에 추적하기 위한 탁월한 컨텍스트 관리가 필요합니다. 이 모델은 다양한 에이전트의 역량과 한계를 이해하고, 효율성과 품질을 최적화하기 위해 작업 할당을 최적화해야 합니다.
Manager LLM은 모든 작업에 관여하기 때문에 비용 고려가 특히 중요합니다. 모델은 효과적인 조정을 위한 충분한 역량을 제공하면서도, 잦은 사용에도 비용 효율적이어야 합니다. 이는 종종 가장 정교한 모델의 높은 가격 없이도 충분한 추론 능력을 제공하는 모델을 찾는 것을 의미합니다.
</Tab>
<Tab title="Function Calling LLM">
Function calling LLM은 모든 에이전트 간 도구 사용을 처리하므로, 외부 도구와 API에 크게 의존하는 crew에서 매우 중요합니다. 이 모델은 도구의 역량을 이해하고, 파라미터를 정확하게 추출하며, 도구 응답을 효과적으로 처리하는 데 특화되어야 합니다.
Function calling LLM에서 가장 중요한 특성은 창의성이나 정교한 추론력보다는 정확성과 신뢰성입니다. 모델은 자연어 요청에서 올바른 파라미터를 일관되게 추출하고, 도구 응답을 적절히 처리해야 합니다. 도구 사용은 여러 번의 왕복 작업이 수반될 수 있으므로 속도도 중요합니다.
많은 팀들은, 창의적이거나 추론에 특화된 모델보다는, 특화된 function calling 모델이나 도구 지원이 강력한 범용 모델이 이 역할에 더 적합하다는 것을 발견합니다. 핵심은 모델이 자연어 지침과 구조화된 도구 호출 간의 간극을 신뢰성 있게 연결할 수 있도록 하는 것입니다.
</Tab>
<Tab title="Agent-Specific Overrides">
개별 에이전트는 특정 요구가 일반적인 crew 요구와 크게 다를 때, crew 단위 LLM 설정을 재정의할 수 있습니다. 이 기능을 통해 대부분의 에이전트에는 운영 단순성을 유지하면서, 미세한 최적화가 가능합니다.
에이전트별 재정의를 고려해야 하는 경우는 에이전트의 역할이 다른 crew 구성원과 본질적으로 다른 역량을 요구할 때입니다. 예를 들어, 창의적 글쓰기에 특화된 에이전트는 콘텐츠 생성에 최적화된 모델이 도움이 될 수 있고, 데이터 분석 에이전트는 추론에 중점을 둔 모델로 더 나은 성과를 거둘 수 있습니다.
에이전트별 재정의를 적용할 때의 과제는 최적화와 운영 복잡도 간의 균형을 유지하는 것입니다. 모델이 하나 추가될 때마다 배포, 모니터링, 비용 관리의 복잡성이 늘어납니다. 따라서 팀은 성능 향상 효과가 추가 복잡성을 정당화할 수 있는 에이전트에만 재정의를 집중해야 합니다.
</Tab>
</Tabs>
## 작업 정의 프레임워크
### a. 복잡성보다 명확성에 집중하기
CrewAI 출력의 품질을 결정하는 데 있어 모델 선택보다 효과적인 작업 정의가 더 중요한 경우가 많습니다. 잘 정의된 작업은 명확한 방향과 맥락을 제공하여 심지어 보통 수준의 모델도 좋은 성능을 낼 수 있게 해주지만, 잘못 정의된 작업은 고도화된 모델조차 만족스럽지 않은 결과를 만들 수 있습니다.
<AccordionGroup>
<Accordion title="효과적인 작업 설명" icon="list-check">
최고의 작업 설명은 적절한 세부 정보 제공과 명확성 유지를 균형 있게 조화시킵니다. 작업의 구체적인 목표를 성공이 어떤 모습인지에 대한 모호함 없이 명확하게 정의해야 하며, 접근 방식이나 방법론을 충분히 설명하여 에이전트가 어떻게 진행해야 하는지 이해할 수 있도록 해야 합니다.
효과적인 작업 설명은 에이전트가 더 넓은 목적과 그들이 반드시 지켜야 할 제한사항을 이해할 수 있도록 관련 맥락 및 제약 조건을 포함합니다. 복잡한 작업을 체계적으로 실행할 수 있는 집중된 단계로 분할하여, 여러 측면이 뒤섞이고 접근하기 어려운 압도적인 목표로 제시하지 않습니다.
일반적인 실수로는 목표가 너무 모호하다거나, 필요한 맥락을 제공하지 않는다거나, 성공 기준이 불분명하다거나, 관련 없는 여러 작업을 하나의 설명으로 결합하는 경우가 있습니다. 목표는 단일의 명확한 목적에 집중하며, 에이전트가 성공할 수 있을 정도로 충분한 정보를 제공하는 것입니다.
</Accordion>
<Accordion title="예상 산출물 가이드라인" icon="bullseye">
예상 산출물 가이드라인은 작업 정의와 에이전트 간의 계약 역할을 하며, 산출물이 어떤 모습이어야 하며 어떻게 평가될 것인지 명확하게 지정합니다. 이러한 가이드라인은 필요한 형식과 구조뿐만 아니라 산출물이 완전하다고 간주되기 위해 반드시 포함되어야 하는 핵심 요소도 설명해야 합니다.
최고의 산출물 가이드라인은 품질 지표에 대한 구체적인 예시를 제공하고, 완료 기준을 에이전트와 인간 평가자 모두가 작업의 성공적 완료 여부를 평가할 수 있을 만큼 명확하게 정의합니다. 이는 모호함을 줄이고 여러 작업 실행 간 일관된 결과를 보장하는 데 도움이 됩니다.
어떤 작업에나 적용할 수 있을 정도로 일반적인 산출물 설명, 에이전트가 구조를 추측해야 하는 형식 명세 누락, 평가가 어려운 불분명한 품질 기준, 에이전트가 기대치를 이해하도록 도와주는 예시 또는 템플릿 미제공 등은 피해야 합니다.
</Accordion>
</AccordionGroup>
### b. 작업 순서 지정 전략
<Tabs>
<Tab title="순차적 의존성">
작업이 이전 산출물에 기반을 두거나, 정보가 한 작업에서 다른 작업으로 흐르거나, 품질이 선행 작업의 완료에 의존할 때 순차적 작업 의존성이 필수적입니다. 이 접근 방식은 각 작업이 성공적으로 수행되는 데 필요한 정보와 맥락에 접근할 수 있도록 보장합니다.
순차적 의존성을 효과적으로 구현하기 위해서는 context 파라미터를 사용하여 관련 작업을 연쇄시키고, 작업의 진행을 통해 점진적으로 복잡성을 구축하며, 각 작업이 다음 작업에 의미 있는 입력값이 될 수 있는 산출물을 생성하도록 해야 합니다. 목표는 의존된 작업 간의 논리적 흐름을 유지하면서 불필요한 병목을 피하는 것입니다.
순차적 의존성은 한 작업에서 다른 작업으로 명확한 논리적 진행이 있고, 한 작업의 산출물이 다음 작업의 품질이나 실행 가능성을 실제로 향상시킬 때 가장 효과적입니다. 그러나 적절히 관리되지 않을 경우 병목 현상이 발생할 수 있으니, 반드시 진정으로 필요한 의존성과 단순히 편의상 설정된 의존성을 구분해야 합니다.
</Tab>
<Tab title="병렬 실행">
병렬 실행은 작업 간에 상호 독립적이거나, 시간 효율성이 중요하거나, 서로 다른 전문 분야가 협업 없이 각자의 역량을 발휘할 수 있을 때 가치가 있습니다. 이 방식은 전체 실행 시간을 크게 줄일 수 있으며, 각 전문 에이전트가 자신의 강점을 동시에 발휘할 수 있습니다.
성공적인 병렬 실행을 위해서는 실제로 독립적으로 수행이 가능한 작업을 식별하고, 관련되지만 분리된 작업 스트림을 효과적으로 그룹화하며, 병렬로 진행된 작업을 최종 결과물로 통합해야 할 때 결과 통합을 계획해야 합니다. 핵심은 병렬 작업이 전체 품질을 저하하는 충돌이나 중복을 만들지 않도록 하는 것입니다.
여러 개의 독립적인 연구 스트림이나 서로 의존하지 않는 다양한 분석, 동시에 개발이 가능한 콘텐츠 생성 작업이 있을 때 병렬 실행을 고려하십시오. 다만, 자원 할당에 주의하고, 병렬 실행이 모델의 가용 용량이나 예산을 초과하지 않도록 해야 합니다.
</Tab>
</Tabs>
## LLM 성능을 위한 에이전트 구성 최적화
### a. 역할 기반 LLM 선택
<Warning>
일반적인 에이전트 역할은 올바른 LLM을 선택할 수 없게 만듭니다. 구체적인 역할은 목표에 맞춘 모델 최적화를 가능하게 합니다.
</Warning>
에이전트 역할의 구체성은 최적의 성능을 위해 어떤 LLM의 능력이 가장 중요한지를 직접적으로 결정합니다. 이는 에이전트의 책임에 정확히 맞는 모델 강점을 연결할 수 있는 전략적 기회를 만듭니다.
**일반 역할 vs. 구체적 역할이 LLM 선택에 미치는 영향:**
역할을 정의할 때 에이전트가 다룰 작업에 가장 가치 있는 특정 도메인 지식, 작업 방식, 의사결정 프레임워크를 고려하세요. 역할 정의가 더 구체적이고 상황에 맞을수록 모델이 그 역할을 효과적으로 구현할 수 있습니다.
```python
# ✅ 특정 역할 - 명확한 LLM 요구
specific_agent = Agent(
role="SaaS Revenue Operations Analyst", # 명확한 도메인 전문성 필요
goal="Analyze recurring revenue metrics and identify growth opportunities",
backstory="Specialist in SaaS business models with deep understanding of ARR, churn, and expansion revenue",
llm=LLM(model="gpt-4o") # 복잡한 분석에 적합한 reasoning 모델
)
```
**역할-모델 매핑 전략:**
- **"Research Analyst"** → 복잡한 분석을 위한 reasoning 모델 (GPT-4o, Claude Sonnet)
- **"Content Editor"** → 작문 품질을 위한 creative 모델 (Claude, GPT-4o)
- **"Data Processor"** → 구조화된 태스크를 위한 효율적인 모델 (GPT-4o-mini, Gemini Flash)
- **"API Coordinator"** → 도구 사용을 위한 function-calling 최적화 모델 (GPT-4o, Claude)
### b. 모델 컨텍스트 증폭기로서의 백스토리
<Info>
전략적으로 구성된 백스토리는 도메인 특화 컨텍스트를 제공하여 일반적인 프롬프트로는 달성할 수 없는 수준으로 선택한 LLM의 효율성을 획기적으로 높여줍니다.
</Info>
잘 설계된 백스토리는 LLM을 단순한 범용 모델에서 전문적인 전문가로 탈바꿈시켜 줍니다. 이는 비용 최적화 관점에서 특히 중요합니다. 효율적인 모델이라도 컨텍스트가 잘 구축되면, 적절한 컨텍스트 없이 고가의 모델보다 더 뛰어난 성능을 발휘할 수 있습니다.
**컨텍스트 기반 퍼포먼스 예시:**
```python
# Context amplifies model effectiveness
domain_expert = Agent(
role="B2B SaaS Marketing Strategist",
goal="Develop comprehensive go-to-market strategies for enterprise software",
backstory="""
You have 10+ years of experience scaling B2B SaaS companies from Series A to IPO.
You understand the nuances of enterprise sales cycles, the importance of product-market
fit in different verticals, and how to balance growth metrics with unit economics.
You've worked with companies like Salesforce, HubSpot, and emerging unicorns, giving
you perspective on both established and disruptive go-to-market strategies.
""",
llm=LLM(model="claude-3-5-sonnet", temperature=0.3) # Balanced creativity with domain knowledge
)
# This context enables Claude to perform like a domain expert
# Without it, even it would produce generic marketing advice
```
**LLM 성능을 높여주는 백스토리 요소:**
- **도메인 경험**: "10년 이상의 엔터프라이즈 SaaS 영업 경력"
- **특정 전문성**: "시리즈 B+ 라운드의 기술 실사 전문"
- **업무 스타일**: "명확한 문서화와 데이터 기반 의사결정을 선호"
- **품질 기준**: "출처 인용과 분석 근거 제시를 중시"
### c. 총체적 Agent-LLM 최적화
가장 효과적인 agent 구성은 역할 특이성, 백스토리 깊이, 그리고 LLM 선택 간의 시너지를 창출합니다. 각 요소는 서로를 강화하여 모델 성능을 극대화합니다.
**최적화 프레임워크:**
```python
# Example: Technical Documentation Agent
tech_writer = Agent(
role="API Documentation Specialist", # Specific role for clear LLM requirements
goal="Create comprehensive, developer-friendly API documentation",
backstory="""
You're a technical writer with 8+ years documenting REST APIs, GraphQL endpoints,
and SDK integration guides. You've worked with developer tools companies and
understand what developers need: clear examples, comprehensive error handling,
and practical use cases. You prioritize accuracy and usability over marketing fluff.
""",
llm=LLM(
model="claude-3-5-sonnet", # Excellent for technical writing
temperature=0.1 # Low temperature for accuracy
),
tools=[code_analyzer_tool, api_scanner_tool],
verbose=True
)
```
**정렬 체크리스트:**
- ✅ **역할 특이성**: 명확한 도메인과 책임
- ✅ **LLM 적합도**: 모델의 강점이 역할 요구사항과 일치
- ✅ **백스토리 깊이**: LLM이 활용할 수 있는 도메인 맥락 제공
- ✅ **도구 통합**: 도구가 agent의 특수 기능을 지원
- ✅ **파라미터 튜닝**: 온도 및 설정이 역할에 최적화
핵심은 모든 구성 선택이 LLM 선택 전략을 강화하여 성능을 극대화하면서 비용을 최적화하는 agent를 만드는 것입니다.
## 실무 구현 체크리스트
전략적 프레임워크를 반복하는 대신, CrewAI에서 LLM 선택 결정을 실행하는 데 사용할 수 있는 전술적 체크리스트를 제공합니다:
<Steps>
<Step title="현재 셋업 점검" icon="clipboard-check">
**검토할 사항:**
- 모든 agent가 기본적으로 동일한 LLM을 사용하고 있습니까?
- 어떤 agent가 가장 복잡한 reasoning 작업을 처리합니까?
- 어떤 agent가 주로 데이터 처리 또는 포매팅을 담당합니까?
- 도구에 크게 의존하는 agent가 있습니까?
**Action**: 현재 agent 역할을 문서화하고 최적화 기회를 식별하세요.
</Step>
<Step title="Crew 수준 전략 구현" icon="users-gear">
**기본값 설정:**
```python
# crew에 신뢰할 수 있는 기본값으로 시작합니다
default_crew_llm = LLM(model="gpt-4o-mini") # 비용 효율적인 기준점
crew = Crew(
agents=[...],
tasks=[...],
memory=True
)
```
**Action**: 개별 agent 최적화 전에 crew의 기본 LLM을 설정하세요.
</Step>
<Step title="고임팩트 agent 최적화" icon="star">
**핵심 agent 식별 및 업그레이드:**
```python
# Manager 또는 coordination agent
manager_agent = Agent(
role="Project Manager",
llm=LLM(model="gemini-2.5-flash-preview-05-20"), # 조율을 위한 프리미엄
# ... 나머지 설정
)
# Creative 또는 고객 대응 agent
content_agent = Agent(
role="Content Creator",
llm=LLM(model="claude-3-5-sonnet"), # 글쓰기에 최적
# ... 나머지 설정
)
```
**Action**: 복잡도의 80%를 처리하는 agent 20%를 업그레이드하세요.
</Step>
<Step title="엔터프라이즈 테스트로 검증" icon="test-tube">
**agent를 프로덕션에 배포한 후:**
- [CrewAI Enterprise platform](https://app.crewai.com)을 활용하여 모델 선택을 A/B 테스트하세요
- 실제 입력으로 여러 번 반복 테스트하여 일관성과 성능을 측정하세요
- 최적화된 셋업 전반의 비용과 성능을 비교하세요
- 팀과 결과를 공유하여 협업 의사결정을 지원하세요
**Action**: 테스트 플랫폼을 활용해 추측이 아닌 데이터 기반 검증을 실행하세요.
</Step>
</Steps>
### 다양한 모델 유형을 사용할 시기
<Tabs>
<Tab title="Reasoning Models">
reasoning 모델은 진정한 다단계 논리적 사고, 전략적 계획 수립, 또는 체계적인 분석이 필요한 고수준의 의사결정이 요구되는 작업에서 필수적입니다. 이러한 모델은 문제를 구성 요소로 분해하고 체계적으로 분석해야 할 때, 단순한 패턴 매칭이나 지시 사항 이행만으로는 해결할 수 없는 경우에 뛰어난 성능을 발휘합니다.
예를 들어, 비즈니스 전략 개발, 여러 출처에서 인사이트를 도출해야 하는 복잡한 데이터 분석, 각 단계가 이전 분석을 기반으로 해야 하는 다단계 문제 해결, 다양한 변수 및 이들의 상호작용을 고려해야 하는 전략적 계획 수립 업무에 reasoning 모델을 고려해 보세요.
그러나 reasoning 모델은 일반적으로 더 높은 비용과 느린 응답 시간을 수반하므로, 복잡한 사고가 필요한 작업에서 실질적인 가치를 제공할 때에만 사용하는 것이 좋으며, 복잡한 reasoning이 필요하지 않은 단순한 작업에는 권장되지 않습니다.
</Tab>
<Tab title="Creative Models">
creative 모델은 콘텐츠 생성이 주요 결과물이고 콘텐츠의 품질, 스타일, 참여도가 성공에 직접적으로 영향을 미칠 때 유용합니다. 이 모델들은 글의 질과 스타일이 매우 중요하거나, 창의적인 아이디어 창출 또는 브레인스토밍이 필요하거나, 브랜드의 목소리와 톤이 중요한 경우에 특히 뛰어납니다.
creative 모델은 블로그 포스트 작성 및 기사 생성, 독자를 끌어들이고 설득해야 하는 마케팅 카피, 창의적인 스토리텔링 및 내러티브 개발, 목소리와 톤이 중요한 브랜드 커뮤니케이션 등에 적합합니다. 이 모델은 일반 목적 모델보다 뉘앙스와 맥락을 더 잘 이해할 수 있습니다.
creative 모델은 정밀성과 사실적 정확성이 스타일이나 참여도보다 더 중요한 기술적 또는 분석적 작업에는 덜 적합할 수 있습니다. 결과물의 창의적·의사소통적 측면이 성공의 주요 요인일 때 사용하는 것이 가장 좋습니다.
</Tab>
<Tab title="Efficient Models">
efficient 모델은 빠른 속도와 비용 최적화가 우선순위인 고빈도, 반복 작업에 이상적입니다. 이러한 모델은 작업의 매개변수가 명확하고 잘 정의되어 있으며, 복잡한 reasoning이나 창의적인 능력이 필요하지 않을 때 가장 잘 작동합니다.
efficient 모델은 데이터 처리 및 변환 작업, 단순한 서식 지정 및 정리 작업, 정밀성이 중요하고 복잡함보다는 정확성이 필요한 함수 호출 및 도구 사용, 1회 작업당 비용이 중대한 고볼륨 작업에 적합합니다.
efficient 모델에서는 해당 모델의 역량이 작업 요구 사항과 일치하는지 확인하는 것이 핵심입니다. 다양한 반복 작업을 효과적으로 처리할 수 있지만, 뉘앙스 이해, 복잡한 reasoning, 고도화된 콘텐츠 생성이 필요한 작업에서는 한계가 있을 수 있습니다.
</Tab>
<Tab title="Open Source Models">
open source 모델은 예산 제약이 크거나, 데이터 프라이버시 요구 사항이 있거나, 맞춤화가 중요하거나, 운영·컴플라이언스 목적상 로컬 배포가 필요한 경우에 매력적인 선택이 됩니다.
예를 들어, 데이터 프라이버시가 최우선인 사내 도구, 외부 API를 사용할 수 없는 프라이버시 민감형 애플리케이션, 토큰 단위 가격이 부담스러운 비용 최적화 배포, 모델 수정 또는 파인튜닝이 필요한 상황에서 open source 모델을 고려해 보세요.
단, open source 모델은 효과적으로 배포하고 유지하기 위해 더 많은 기술 전문성이 요구됩니다. 인프라, 기술적 오버헤드, 지속적인 유지보수를 포함한 전체 소유 비용을 종합적으로 평가해야 합니다.
</Tab>
</Tabs>
## CrewAI 모델 선택에서 흔히 발생하는 실수
<AccordionGroup>
<Accordion title="‘하나의 모델로 모두 해결’ 함정" icon="triangle-exclamation">
**문제점**: 각 agent의 역할과 책임과 상관없이 모든 agent에 동일한 LLM을 사용하는 것. 대부분 기본적으로 선택되는 접근 방식이지만, 최적의 결과가 나오지 않는 경우가 많음.
**실제 예시**: 전략 기획 매니저와 데이터 추출 agent 모두에게 GPT-4o를 사용하는 경우. 매니저는 높은 추론 성능이 필요해 프리미엄 모델이 적합하나, 데이터 추출 업무는 저렴한 GPT-4o-mini만으로도 충분한 성능을 낼 수 있음.
**CrewAI 솔루션**: agent별 LLM 설정을 활용해, agent의 역할에 맞는 모델 역량을 매칭:
```python
# 전략 agent는 프리미엄 모델 사용
manager = Agent(role="Strategy Manager", llm=LLM(model="gpt-4o"))
# 처리 agent는 효율적인 모델 사용
processor = Agent(role="Data Processor", llm=LLM(model="gpt-4o-mini"))
```
</Accordion>
<Accordion title="Crew 수준과 Agent 수준 LLM 계층 혼동" icon="shuffle">
**문제점**: CrewAI의 LLM 계층 구조(crew LLM, manager LLM, agent LLM)를 이해하지 못해 설정이 충돌하거나 적절히 조정되지 않음.
**실제 예시**: crew에는 Claude를, agent에는 GPT 모델을 설정해 일관성 없는 동작과 불필요한 모델 전환 오버헤드가 발생하는 경우.
**CrewAI 솔루션**: LLM 계층 구조를 전략적으로 설계:
```python
crew = Crew(
agents=[agent1, agent2],
tasks=[task1, task2],
manager_llm=LLM(model="gpt-4o"), # crew 조정용
process=Process.hierarchical # manager_llm 사용 시
)
# agent는 특별히 지정하지 않으면 crew LLM을 상속받음
agent1 = Agent(llm=LLM(model="claude-3-5-sonnet")) # 특정 요구에 따라 오버라이드
```
</Accordion>
<Accordion title="함수 호출 모델 미스매치" icon="screwdriver-wrench">
**문제점**: 기능 위주(함수 호출, 툴 활용 등) CrewAI workflow에서 필요한 함수 호출 성능을 무시한 채, 일반적인 모델 특성(예: 창의성)만을 보고 모델을 선택하는 실수.
**실제 예시**: 주로 API 호출, 검색 툴, 구조화 데이터 처리가 필요한 agent에 창의성 위주의 모델을 선택해, 도구 파라미터 추출과 신뢰성 있는 함수 호출에 실패하는 경우.
**CrewAI 솔루션**: 도구 중심 agent는 함수 호출 성능 위주로 모델을 선택:
```python
# 다양한 도구를 사용하는 agent의 경우
tool_agent = Agent(
role="API Integration Specialist",
tools=[search_tool, api_tool, data_tool],
llm=LLM(model="gpt-4o"), # 함수 호출에 우수
# OR
llm=LLM(model="claude-3-5-sonnet") # 도구 사용에 강점
)
```
</Accordion>
<Accordion title="테스트 없는 조기 최적화" icon="gear">
**문제점**: 실제 CrewAI workflow 및 업무 테스트 없이 이론상 성능만으로 복잡하게 모델을 선정하고 구성하는 실수.
**실제 예시**: 업무 유형별로 복잡한 모델 전환 로직을 구현하지만, 실제 성능 향상이 운영 복잡성을 정당화하지 못하는 경우.
**CrewAI 솔루션**: 단순한 구조로 시작해서, 실제 성능 데이터를 바탕으로 점진적으로 최적화:
```python
# 이렇게 시작
crew = Crew(agents=[...], tasks=[...], llm=LLM(model="gpt-4o-mini"))
# 성능을 테스트하고, 필요에 따라 특정 agent만 최적화
# Enterprise 플랫폼 테스트를 통해 개선 사항 검증
```
</Accordion>
<Accordion title="컨텍스트·메모리 한계 간과" icon="brain">
**문제점**: 모델의 컨텍스트 윈도(window)와 CrewAI의 메모리, agent 간 컨텍스트 공유 방식을 고려하지 않는 실수.
**실제 예시**: 여러 차례 반복되는 업무나 agent 간 활발한 소통이 필요한 crew에 대화 내역을 오래 유지해야 하는데, 짧은 컨텍스트 모델을 사용한 경우.
**CrewAI 솔루션**: crew의 소통 패턴에 맞춰 컨텍스트 처리 능력을 갖춘 모델을 선택.
</Accordion>
</AccordionGroup>
## 테스트 및 반복 전략
<Steps>
<Step title="간단하게 시작하기" icon="play">
신뢰할 수 있고, 잘 알려져 있으며, 널리 지원되는 범용 모델로 시작하세요. 이것은 최적화된 특수한 필요에 집중하기 전에 귀하의 특정 요구사항과 성능 기대치를 이해할 수 있는 안정적인 기초를 제공합니다.
</Step>
<Step title="중요한 것 측정하기" icon="chart-line">
일반적인 벤치마크에만 의존하지 말고, 귀하의 특정 사용 사례와 비즈니스 요구에 부합하는 지표를 개발하세요. 이론적 성능 지표가 아니라 성공에 직접적으로 영향을 미치는 결과 측정에 집중하세요.
</Step>
<Step title="결과에 기반한 반복" icon="arrows-rotate">
이론적 고려사항이나 일반적인 권장사항이 아니라, 귀하의 특정 상황에서 관찰된 성능에 따라 모델을 변경하세요. 실제 성능은 벤치마크 결과나 일반적인 평판과는 크게 다를 수 있습니다.
</Step>
<Step title="총 비용 고려하기" icon="calculator">
모델 비용, 개발 시간, 유지 보수 오버헤드, 운영 복잡성 등 소유에 드는 전체 비용을 평가하세요. 토큰당 가장 저렴한 모델이 모든 요소를 고려했을 때 반드시 가장 비용 효율적이지는 않을 수 있습니다.
</Step>
</Steps>
<Tip>
먼저 귀하의 요구사항을 이해하는 데 집중한 후, 그 요구와 가장 잘 맞는 모델을 선택하세요. 최상의 LLM 선택은 운영상의 제약 조건 내에서 꾸준히 원하는 결과를 제공하는 것입니다.
</Tip>
### 엔터프라이즈급 모델 검증
LLM 선택을 최적화하고자 하는 팀을 위해 **CrewAI Enterprise 플랫폼**은 기본적인 CLI 테스트를 훨씬 능가하는 정교한 테스트 기능을 제공합니다. 이 플랫폼은 데이터 기반의 LLM 전략 의사결정을 지원하는 종합적인 모델 평가를 가능하게 합니다.
<Frame>
![엔터프라이즈 테스트 인터페이스](/images/enterprise/enterprise-testing.png)
</Frame>
**고급 테스트 기능:**
- **다중 모델 비교**: 동일한 작업과 입력에 대해 여러 LLM을 동시에 테스트할 수 있습니다. GPT-4o, Claude, Llama, Groq, Cerebras 및 기타 선도적인 모델의 성능을 병렬로 비교하여 특정 사용 사례에 가장 적합한 모델을 식별할 수 있습니다.
- **통계적 엄밀성**: 일관된 입력값으로 여러 번 테스트를 구성하여 신뢰성과 성능 편차를 측정할 수 있습니다. 이를 통해 단순히 잘하는 모델이 아닌, 여러 번 실행해도 안정적으로 동작하는 모델을 식별할 수 있습니다.
- **실제 환경 검증**: 합성 벤치마크가 아닌 실제 crew 입력값과 시나리오를 사용할 수 있습니다. 플랫폼을 통해 산업 환경, 회사 정보, 실제 사용 사례 등 특정 맥락에 맞는 테스트가 가능하여 보다 정확한 평가가 이뤄집니다.
- **종합 분석 도구**: 테스트한 모든 모델의 세부 성능 지표, 실행 시간, 비용 분석을 확인할 수 있습니다. 이로써 모델의 일반적인 평판이나 이론적 능력에 기대지 않고 데이터 기반으로 의사결정을 내릴 수 있습니다.
- **팀 협업**: 팀 내에서 테스트 결과와 모델 성능 데이터를 공유할 수 있어, 협업적 의사결정과 프로젝트 전반에서 일관된 모델 선택 전략을 수립할 수 있습니다.
지금 [app.crewai.com](https://app.crewai.com)에서 시작하세요!
<Info>
Enterprise 플랫폼은 모델 선택을 단순한 추측이 아닌 데이터 기반 프로세스로 혁신하여, 본 가이드의 원칙을 실제 사용 사례와 요구 사항에 맞게 검증할 수 있도록 해줍니다.
</Info>
## 주요 원칙 요약
<CardGroup cols={2}>
<Card title="작업 중심 선택" icon="bullseye">
이론적 능력이나 일반적인 평판이 아니라, 작업에 실제로 필요한 것에 따라 모델을 선택하세요.
</Card>
<Card title="능력 일치" icon="puzzle-piece">
최적의 성능을 위해 모델의 강점을 agent의 역할 및 책임과 일치시키세요.
</Card>
<Card title="전략적 일관성" icon="link">
관련 구성 요소와 워크플로 전반에 걸쳐 일관된 모델 선택 전략을 유지하세요.
</Card>
<Card title="실용적 테스트" icon="flask">
벤치마크에만 의존하지 말고 실제 사용을 통해 선택을 검증하세요.
</Card>
<Card title="반복적 개선" icon="arrow-up">
단순하게 시작하고 실제 성능과 필요에 따라 최적화하세요.
</Card>
<Card title="운영적 균형" icon="scale-balanced">
성능 요구사항과 비용 및 복잡성 제약을 균형 있게 맞추세요.
</Card>
</CardGroup>
<Check>
기억하세요: 최고의 LLM 선택이란 운영상의 제약 내에서 일관되게 필요한 결과를 제공하는 모델입니다. 먼저 요구사항을 정확히 이해하는 데 집중한 후, 그에 가장 잘 맞는 모델을 선택하세요.
</Check>
## 현재 모델 현황 (2025년 6월)
<Warning>
**특정 시점의 스냅샷**: 아래 모델 순위는 2025년 6월 기준으로, [LMSys Arena](https://arena.lmsys.org/), [Artificial Analysis](https://artificialanalysis.ai/) 및 기타 주요 벤치마크에서 집계된 최신 리더보드 결과입니다. LLM의 성능, 가용성, 가격은 빠르게 변동됩니다. 항상 귀하의 특정 사용 사례와 데이터로 직접 평가를 진행하시기 바랍니다.
</Warning>
### 카테고리별 주요 모델
아래 표는 다양한 카테고리에서 현재 최고의 성능을 보이는 대표적인 모델들을 보여주며, CrewAI 에이전트에 적합한 모델 선택에 대한 가이드를 제공합니다:
<Note>
이 표와 지표는 각 카테고리에서 선별된 주요 모델을 보여주기 위한 것으로, 전체를 포괄하지 않습니다. 여기 소개되지 않은 훌륭한 모델들도 많이 존재합니다. 이 표의 목적은 완전한 목록을 제공하는 것이 아니라, 어떤 능력을 갖춘 모델을 찾아야 하는지 예시를 제시하는 것입니다.
</Note>
<Tabs>
<Tab title="Reasoning & Planning">
**매니저 LLM 및 복잡한 분석에 최적**
| Model | Intelligence Score | Cost ($/M tokens) | Speed | Best Use in CrewAI |
|:------|:------------------|:------------------|:------|:------------------|
| **o3** | 70 | $17.50 | 빠름 | 복잡한 멀티 에이전트 조정용 매니저 LLM |
| **Gemini 2.5 Pro** | 69 | $3.44 | 빠름 | 전략 기획 에이전트, 연구 조정 |
| **DeepSeek R1** | 68 | $0.96 | 보통 | 예산을 중시하는 팀을 위한 비용 효율적 reasoning |
| **Claude 4 Sonnet** | 53 | $6.00 | 빠름 | 세밀한 이해가 필요한 분석 에이전트 |
| **Qwen3 235B (Reasoning)** | 62 | $2.63 | 보통 | reasoning 작업을 위한 오픈소스 대안 |
이 모델들은 다단계 reasoning에 뛰어나며, 전략을 개발하거나 다른 에이전트를 조정하거나 복잡한 정보를 분석해야 하는 에이전트에 이상적입니다.
</Tab>
<Tab title="Coding & Technical">
**개발 및 도구 중심의 워크플로우에 최적**
| Model | Coding Performance | Tool Use Score | Cost ($/M tokens) | Best Use in CrewAI |
|:------|:------------------|:---------------|:------------------|:------------------|
| **Claude 4 Sonnet** | 우수 | 72.7% | $6.00 | 주력 코딩 에이전트, 기술 문서화 |
| **Claude 4 Opus** | 우수 | 72.5% | $30.00 | 복잡한 소프트웨어 아키텍처, 코드 리뷰 |
| **DeepSeek V3** | 매우 좋음 | 높음 | $0.48 | 일상적 개발을 위한 비용 효율적 코딩 |
| **Qwen2.5 Coder 32B** | 매우 좋음 | 보통 | $0.15 | 예산 친화적 코딩 에이전트 |
| **Llama 3.1 405B** | 좋음 | 81.1% | $3.50 | 도구 사용이 많은 워크플로우를 위한 function calling LLM |
이 모델들은 코드 생성, 디버깅, 기술 문제 해결에 최적화되어 있어, 개발 중심 팀에 적합합니다.
</Tab>
<Tab title="Speed & Efficiency">
**대량 처리 및 실시간 애플리케이션에 최적**
| Model | Speed (tokens/s) | Latency (TTFT) | Cost ($/M tokens) | Best Use in CrewAI |
|:------|:-----------------|:---------------|:------------------|:------------------|
| **Llama 4 Scout** | 2,600 | 0.33s | $0.27 | 대량 처리 에이전트 |
| **Gemini 2.5 Flash** | 376 | 0.30s | $0.26 | 실시간 응답 에이전트 |
| **DeepSeek R1 Distill** | 383 | 가변 | $0.04 | 비용 최적화 고속 처리 |
| **Llama 3.3 70B** | 2,500 | 0.52s | $0.60 | 균형 잡힌 속도와 기능 |
| **Nova Micro** | 높음 | 0.30s | $0.04 | 단순·빠른 작업 처리 |
이 모델들은 속도와 효율을 우선시하며, 일상적 운영 또는 신속한 응답이 필요한 에이전트에게 최적입니다. **팁**: 이러한 모델을 Groq와 같은 빠른 추론 제공자와 함께 사용하면 더욱 우수한 성능을 낼 수 있습니다. 특히 Llama와 같은 오픈소스 모델에 적합합니다.
</Tab>
<Tab title="Balanced Performance">
**일반 팀을 위한 최고의 다목적 모델**
| Model | Overall Score | Versatility | Cost ($/M tokens) | Best Use in CrewAI |
|:------|:--------------|:------------|:------------------|:------------------|
| **GPT-4.1** | 53 | 탁월 | $3.50 | 범용 팀 LLM |
| **Claude 3.7 Sonnet** | 48 | 매우 좋음 | $6.00 | 균형 잡힌 reasoning 및 창의력 |
| **Gemini 2.0 Flash** | 48 | 좋음 | $0.17 | 비용 효율적인 범용 용도 |
| **Llama 4 Maverick** | 51 | 좋음 | $0.37 | 오픈소스 범용 모델 |
| **Qwen3 32B** | 44 | 좋음 | $1.23 | 예산 친화적 다재다능성 |
이 모델들은 다양한 측면에서 우수한 성능을 제공하며, 여러 작업이 혼합된 팀에 적합합니다.
</Tab>
</Tabs>
### 현재 모델을 위한 선택 프레임워크
<AccordionGroup>
<Accordion title="High-Performance Crews" icon="rocket">
**퍼포먼스가 우선 순위일 때**: 매니저 LLM 또는 중요한 에이전트 역할에는 **o3**, **Gemini 2.5 Pro**, **Claude 4 Sonnet**과 같은 최상위 모델을 사용하세요. 이 모델들은 복잡한 reasoning 및 coordination에 탁월하지만 비용이 더 높습니다.
**전략**: 프리미엄 모델이 전략적 사고를 담당하고, 효율적인 모델이 일상적 operation을 처리하는 멀티 모델 접근법을 구현하세요.
</Accordion>
<Accordion title="Cost-Conscious Crews" icon="dollar-sign">
**예산이 주요 제약일 때**: **DeepSeek R1**, **Llama 4 Scout**, **Gemini 2.0 Flash**와 같은 모델에 집중하세요. 이 모델들은 훨씬 낮은 비용으로 강력한 퍼포먼스를 제공합니다.
**전략**: 대부분의 에이전트에는 비용 효율이 높은 모델을 사용하고, 가장 중요한 decision-making 역할에만 프리미엄 모델을 남겨두세요.
</Accordion>
<Accordion title="Specialized Workflows" icon="screwdriver-wrench">
**특정 도메인 전문성이 필요할 때**: 주된 사용 사례에 최적화된 모델을 선택하세요. 코딩에는 **Claude 4** 시리즈, 리서치에는 **Gemini 2.5 Pro**, function calling에는 **Llama 405B**를 사용하세요.
**전략**: crew의 주요 기능에 따라 모델을 선택해, 핵심 역량이 모델의 강점과 일치하도록 하세요.
</Accordion>
<Accordion title="Enterprise & Privacy" icon="shield">
**데이터 민감한 operation의 경우**: 로컬에서 배포 가능하면서 경쟁력 있는 퍼포먼스를 유지하는 오픈 소스 모델인 **Llama 4** 시리즈, **DeepSeek V3**, **Qwen3** 등을 고려하세요.
**전략**: 사설 인프라에 오픈 소스 모델을 배포하여, 데이터 제어를 위해 필요한 퍼포먼스 손실을 감수하세요.
</Accordion>
</AccordionGroup>
### 모델 선택을 위한 주요 고려사항
- **성능 동향**: 현재 시장에서는 reasoning에 초점을 맞춘 모델(o3, Gemini 2.5 Pro)과 균형 잡힌 모델(Claude 4, GPT-4.1) 간의 치열한 경쟁이 있습니다. DeepSeek R1과 같은 특화 모델은 우수한 비용-성능 비율을 제공합니다.
- **속도와 지능 간의 트레이드오프**: Llama 4 Scout와 같은 모델은 합리적인 지능을 유지하면서도 빠른 속도(2,600 tokens/s)를 우선시하며, o3와 같은 모델은 속도와 가격을 희생해 reasoning 능력을 극대화합니다.
- **오픈 소스의 실효성**: 오픈 소스와 독점 모델 간의 격차가 계속 좁혀지고 있으며, Llama 4 Maverick 및 DeepSeek V3와 같은 모델이 매력적인 가격대에서 경쟁력 있는 성능을 제공합니다. 특히 빠른 추론을 제공하는 업체들은 오픈 소스 모델과 함께 탁월한 속도-비용 비율을 제공하는 경우가 많아 독점 모델보다 우위에 서기도 합니다.
<Info>
**테스트는 필수입니다**: 리더보드 순위는 일반적인 가이드라인을 제공하지만, 귀하의 특정 사용 사례, 프롬프트 스타일, 평가 기준에 따라 결과가 달라질 수 있습니다. 최종 결정을 내리기 전에 반드시 실제 작업과 데이터로 후보 모델을 테스트해 보세요.
</Info>
### 실질적인 구현 전략
<Steps>
<Step title="검증된 모델로 시작하기">
여러 차원에서 우수한 성능을 제공하며 실제 환경에서 광범위하게 검증된 **GPT-4.1**, **Claude 3.7 Sonnet**, **Gemini 2.0 Flash**와 같은 잘 알려진 모델부터 시작하십시오.
</Step>
<Step title="특화된 요구 사항 식별">
crew에 코드 작성, reasoning, 속도 등 특정 요구가 있는지 확인하고, 이러한 요구에 부합하는 **Claude 4 Sonnet**(개발용) 또는 **o3**(복잡한 분석용)과 같은 특화 모델을 고려하십시오. 속도가 중요한 애플리케이션의 경우, 모델 선택과 더불어 **Groq**와 같은 빠른 추론 제공자를 고려할 수 있습니다.
</Step>
<Step title="다중 모델 전략 구현">
각 에이전트의 역할에 따라 다양한 모델을 사용하세요. 관리자와 복잡한 작업에는 고성능 모델을, 일상적 운영에는 효율적인 모델을 적용합니다.
</Step>
<Step title="모니터링 및 최적화">
사용 사례와 관련된 성능 지표를 추적하고, 새로운 모델이 출시되거나 가격이 변동될 때 모델 선택을 조정할 준비를 하십시오.
</Step>
</Steps>

View File

@@ -0,0 +1,140 @@
---
title: 멀티모달 에이전트 사용하기
description: CrewAI 프레임워크 내에서 이미지 및 기타 비텍스트 콘텐츠를 처리하기 위해 에이전트에서 멀티모달 기능을 활성화하고 사용하는 방법을 알아보세요.
icon: video
---
## 멀티모달 에이전트 사용하기
CrewAI는 텍스트뿐만 아니라 이미지와 같은 비텍스트 콘텐츠도 처리할 수 있는 멀티모달 에이전트를 지원합니다. 이 가이드에서는 에이전트에서 멀티모달 기능을 활성화하고 사용하는 방법을 안내합니다.
### 멀티모달 기능 활성화
멀티모달 에이전트를 생성하려면, 에이전트를 초기화할 때 `multimodal` 파라미터를 `True`로 설정하면 됩니다:
```python
from crewai import Agent
agent = Agent(
role="Image Analyst",
goal="Analyze and extract insights from images",
backstory="An expert in visual content interpretation with years of experience in image analysis",
multimodal=True # This enables multimodal capabilities
)
```
`multimodal=True`로 설정하면, 에이전트는 자동으로 비텍스트 콘텐츠를 처리하는 데 필요한 도구들(예: `AddImageTool`)과 함께 구성됩니다.
### 이미지 작업하기
멀티모달 에이전트는 이미지를 처리할 수 있는 `AddImageTool`이 사전 구성되어 포함되어 있습니다. 이 도구를 수동으로 추가할 필요가 없으며, 멀티모달 기능을 활성화하면 자동으로 포함됩니다.
아래는 멀티모달 에이전트를 사용하여 이미지를 분석하는 방법을 보여주는 전체 예제입니다:
```python
from crewai import Agent, Task, Crew
# Create a multimodal agent
image_analyst = Agent(
role="Product Analyst",
goal="Analyze product images and provide detailed descriptions",
backstory="Expert in visual product analysis with deep knowledge of design and features",
multimodal=True
)
# Create a task for image analysis
task = Task(
description="Analyze the product image at https://example.com/product.jpg and provide a detailed description",
expected_output="A detailed description of the product image",
agent=image_analyst
)
# Create and run the crew
crew = Crew(
agents=[image_analyst],
tasks=[task]
)
result = crew.kickoff()
```
### 컨텍스트를 활용한 고급 사용법
멀티모달 agent를 위한 task를 생성할 때 추가적인 컨텍스트나 이미지에 대한 구체적인 질문을 제공할 수 있습니다. task 설명에는 agent가 집중해야 할 특정 측면을 포함할 수 있습니다.
```python
from crewai import Agent, Task, Crew
# Create a multimodal agent for detailed analysis
expert_analyst = Agent(
role="Visual Quality Inspector",
goal="Perform detailed quality analysis of product images",
backstory="Senior quality control expert with expertise in visual inspection",
multimodal=True # AddImageTool is automatically included
)
# Create a task with specific analysis requirements
inspection_task = Task(
description="""
Analyze the product image at https://example.com/product.jpg with focus on:
1. Quality of materials
2. Manufacturing defects
3. Compliance with standards
Provide a detailed report highlighting any issues found.
""",
expected_output="A detailed report highlighting any issues found",
agent=expert_analyst
)
# Create and run the crew
crew = Crew(
agents=[expert_analyst],
tasks=[inspection_task]
)
result = crew.kickoff()
```
### 도구 세부 정보
멀티모달 에이전트를 사용할 때, `AddImageTool`은 다음 스키마로 자동 구성됩니다:
```python
class AddImageToolSchema:
image_url: str # Required: The URL or path of the image to process
action: Optional[str] = None # Optional: Additional context or specific questions about the image
```
멀티모달 에이전트는 내장 도구를 통해 자동으로 이미지 처리를 수행하므로 다음과 같은 작업이 가능합니다:
- URL 또는 로컬 파일 경로를 통해 이미지 접근
- 선택적 컨텍스트나 구체적인 질문을 포함하여 이미지 내용 처리
- 시각적 정보와 작업 요구사항에 따른 분석 및 인사이트 제공
### 모범 사례
멀티모달 에이전트를 사용할 때 다음의 모범 사례를 염두에 두세요:
1. **이미지 접근성**
- 에이전트가 접근할 수 있는 URL을 통해 이미지를 제공해야 합니다.
- 로컬 이미지는 임시로 호스팅하거나 절대 파일 경로를 사용하는 것을 고려하세요.
- 작업을 실행하기 전에 이미지 URL이 유효하고 접근 가능한지 확인하세요.
2. **작업 설명**
- 에이전트가 이미지의 어떤 부분을 분석하기를 원하는지 구체적으로 명시하세요.
- 작업 설명에 명확한 질문이나 요구사항을 포함하세요.
- 집중된 분석이 필요한 경우 선택적인 `action` 파라미터 사용을 고려하세요.
3. **리소스 관리**
- 이미지 처리는 텍스트 전용 작업보다 더 많은 컴퓨팅 자원을 필요로 할 수 있습니다.
- 일부 언어 모델은 이미지 데이터를 base64로 인코딩해야 할 수 있습니다.
- 성능 최적화를 위해 여러 이미지를 일괄 처리하는 방법을 고려하세요.
4. **환경 설정**
- 이미지 처리를 위한 필수 의존성이 환경에 설치되어 있는지 확인하세요.
- 사용하는 언어 모델이 멀티모달 기능을 지원하는지 확인하세요.
- 설정을 검증하기 위해 작은 이미지를 먼저 테스트하세요.
5. **오류 처리**
- 이미지 로딩 실패에 대한 적절한 오류 처리를 구현하세요.
- 이미지 처리 실패 시를 대비한 예비 전략을 마련하세요.
- 디버깅을 위해 이미지 처리 작업을 모니터링하고 로그를 남기세요.

158
docs/ko/learn/overview.mdx Normal file
View File

@@ -0,0 +1,158 @@
---
title: "개요"
description: "포괄적인 가이드와 튜토리얼을 통해 CrewAI 애플리케이션을 빌드하고, 맞춤화하며, 최적화하는 방법을 알아보세요."
icon: "face-smile"
---
## CrewAI 배우기
이 섹션은 CrewAI를 마스터하는 데 도움이 되는 종합적인 가이드와 튜토리얼을 제공합니다. 기본 개념부터 고급 기술까지 다루며, 이제 막 시작하는 분이든 기존 구현을 최적화하려는 분이든, 이 자료들은 강력한 AI 에이전트 워크플로우를 구축하는 모든 측면을 안내해 드립니다.
## 시작하기 안내
### 핵심 개념
<CardGroup cols={2}>
<Card title="순차적 프로세스" icon="list-ol" href="/ko/learn/sequential-process">
구조화된 워크플로우를 위해 작업을 순차적으로 실행하는 방법을 학습합니다.
</Card>
<Card title="계층적 프로세스" icon="sitemap" href="/ko/learn/hierarchical-process">
매니저 에이전트가 워크플로우를 감독하며 계층적으로 작업을 실행합니다.
</Card>
<Card title="조건부 작업" icon="code-branch" href="/ko/learn/conditional-tasks">
결과에 따라 조건부로 작업을 실행하여 동적인 워크플로우를 만듭니다.
</Card>
<Card title="비동기 시작" icon="bolt" href="/ko/learn/kickoff-async">
향상된 성능과 동시성을 위해 crew를 비동기로 실행합니다.
</Card>
</CardGroup>
### 에이전트 개발
<CardGroup cols={2}>
<Card title="에이전트 커스터마이징" icon="user-gear" href="/ko/learn/customizing-agents">
에이전트의 동작 방식, 역할, 역량을 커스터마이즈하는 방법을 배워보세요.
</Card>
<Card title="에이전트 코딩" icon="code" href="/ko/learn/coding-agents">
코드 작성, 실행, 디버깅을 자동으로 수행할 수 있는 에이전트를 구축하세요.
</Card>
<Card title="멀티모달 에이전트" icon="images" href="/ko/learn/multimodal-agents">
텍스트, 이미지, 기타 미디어 유형을 처리할 수 있는 에이전트를 만들어보세요.
</Card>
<Card title="커스텀 매니저 에이전트" icon="user-tie" href="/ko/learn/custom-manager-agent">
복잡한 계층적 워크플로우를 위한 커스텀 매니저 에이전트를 구현하세요.
</Card>
</CardGroup>
## 고급 기능
### 워크플로 제어
<CardGroup cols={2}>
<Card title="Human in the Loop" icon="user-check" href="/ko/learn/human-in-the-loop">
에이전트 워크플로에 인간의 감독과 개입을 통합하세요.
</Card>
<Card title="Human Input on Execution" icon="hand-paper" href="/ko/learn/human-input-on-execution">
작업 실행 중에 인간의 입력을 허용하여 동적인 의사결정을 지원합니다.
</Card>
<Card title="Replay Tasks" icon="rotate-left" href="/ko/learn/replay-tasks-from-latest-crew-kickoff">
이전 crew 실행으로부터 작업을 다시 실행하고 재개하세요.
</Card>
<Card title="Kickoff for Each" icon="repeat" href="/ko/learn/kickoff-for-each">
서로 다른 입력으로 crew를 효율적으로 여러 번 실행하세요.
</Card>
</CardGroup>
### 맞춤화 및 통합
<CardGroup cols={2}>
<Card title="커스텀 LLM" icon="brain" href="/ko/learn/custom-llm">
CrewAI와 커스텀 언어 모델 및 공급자를 통합하세요.
</Card>
<Card title="LLM 연결" icon="link" href="/ko/learn/llm-connections">
다양한 LLM 공급자에 대한 연결을 구성하고 관리하세요.
</Card>
<Card title="커스텀 도구 생성" icon="wrench" href="/ko/learn/create-custom-tools">
에이전트의 기능을 확장할 수 있는 커스텀 도구를 빌드하세요.
</Card>
<Card title="주석 사용하기" icon="at" href="/ko/learn/using-annotations">
더 깔끔하고 유지 관리하기 쉬운 코드를 위해 Python 주석을 사용하세요.
</Card>
</CardGroup>
## 특수화된 애플리케이션
### 콘텐츠 & 미디어
<CardGroup cols={2}>
<Card title="DALL-E 이미지 생성" icon="image" href="/ko/learn/dalle-image-generation">
에이전트와의 DALL-E 통합을 사용하여 이미지를 생성하세요.
</Card>
<Card title="내 에이전트 가져오기" icon="user-plus" href="/ko/learn/bring-your-own-agent">
기존 에이전트와 모델을 CrewAI 워크플로우에 통합하세요.
</Card>
</CardGroup>
### 도구 관리
<CardGroup cols={2}>
<Card title="도구 출력을 결과로 강제" icon="hammer" href="/ko/learn/force-tool-output-as-result">
도구를 구성하여 출력값을 작업 결과로 직접 반환하도록 합니다.
</Card>
</CardGroup>
## 학습 경로 추천
### 초보자를 위한 안내
1. 기본 워크플로 실행을 이해하려면 **Sequential Process**로 시작하세요.
2. 효과적인 에이전트 구성을 만들기 위해 **Customizing Agents**를 학습하세요.
3. 기능 확장을 위해 **Create Custom Tools**을(를) 탐색하세요.
4. 인터랙티브 워크플로를 위해 **Human in the Loop**을(를) 시도해 보세요.
### 중급 사용자를 위한 안내
1. 복잡한 다중 에이전트 시스템을 위해 **계층적 프로세스** 마스터하기
2. 동적 워크플로우를 위해 **조건부 태스크** 구현하기
3. 성능 최적화를 위해 **비동기 시작** 사용하기
4. 특화된 모델을 위해 **커스텀 LLM** 통합하기
### 고급 사용자용
1. 복잡한 미디어 처리를 위한 **멀티모달 에이전트** 빌드
2. 정교한 오케스트레이션을 위한 **커스텀 매니저 에이전트** 생성
3. 하이브리드 시스템을 위한 **BYOA(Bring Your Own Agent)** 구현
4. 견고한 오류 복구를 위한 **리플레이 태스크** 사용
## 모범 사례
### 개발
- **간단하게 시작하세요**: 복잡성을 추가하기 전에 기본적인 순차 워크플로우부터 시작하세요
- **점진적으로 테스트하세요**: 더 큰 시스템에 통합하기 전에 각 구성 요소를 테스트하세요
- **애노테이션 사용**: 더 깔끔하고 유지보수가 쉬운 코드를 위해 Python 애노테이션을 활용하세요
- **커스텀 도구**: 다양한 agent에서 공유할 수 있는 재사용 가능한 도구를 만드세요
### 운영 환경
- **오류 처리**: 강력한 오류 처리 및 복구 메커니즘 구현
- **성능**: 비동기 실행을 사용하고 더 나은 성능을 위해 LLM 호출 최적화
- **모니터링**: 에이전트 성능 추적을 위해 가시성 도구 통합
- **인간 감독**: 중요한 의사결정을 위한 인간 점검 지점 포함
### 최적화
- **리소스 관리**: 토큰 사용량과 API 비용을 모니터링하고 최적화합니다.
- **워크플로우 설계**: 불필요한 LLM 호출을 최소화하는 워크플로우를 설계합니다.
- **도구 효율성**: 최소한의 오버헤드로 최대 가치를 제공하는 효율적인 도구를 만듭니다.
- **반복적 개선**: 피드백과 메트릭을 활용하여 에이전트 성능을 지속적으로 개선합니다.
## 도움 받기
- **문서**: 각 가이드에는 자세한 예시와 설명이 포함되어 있습니다
- **커뮤니티**: 토론과 지원을 위해 [CrewAI 포럼](https://community.crewai.com)에 참여하세요
- **예제**: 완전한 작동 구현을 보려면 예제 섹션을 확인하세요
- **지원**: 기술 지원이 필요하면 [support@crewai.com](mailto:support@crewai.com)으로 문의하세요
현재 필요에 맞는 가이드부터 시작하고, 기본 사항에 익숙해지면 점차 더 고급 주제를 탐색해보세요.

View File

@@ -0,0 +1,78 @@
---
title: 최신 Crew Kickoff에서 작업 다시 실행하기
description: 최신 crew.kickoff(...)에서 작업을 다시 실행합니다.
icon: arrow-right
---
## 소개
CrewAI는 최신 crew 킥오프에서 지정된 태스크를 다시 실행할 수 있는 기능을 제공합니다. 이 기능은 킥오프를 완료한 후 특정 태스크를 다시 시도하고 싶거나 데이터를 다시 가져올 필요 없이 이미 에이전트들이 킥오프 실행에서 컨텍스트를 저장한 경우, 원하는 태스크만 다시 실행(Replay)하면 될 때 특히 유용합니다.
<Note>
태스크를 다시 실행하기 전에 반드시 `crew.kickoff()`을 실행해야 합니다.
현재는 최신 킥오프만 지원되므로, `kickoff_for_each`를 사용하는 경우에도 가장 최근의 crew 실행만 다시 실행할 수 있습니다.
</Note>
다음은 태스크에서 다시 실행하는 방법의 예시입니다:
### CLI를 사용하여 특정 Task에서 재실행하기
재실행 기능을 사용하려면 다음 단계를 따르세요:
<Steps>
<Step title="터미널 또는 명령 프롬프트를 엽니다."></Step>
<Step title="CrewAI 프로젝트가 위치한 디렉터리로 이동합니다."></Step>
<Step title="다음 명령어를 실행합니다:">
최신 kickoff task_id를 확인하려면 아래를 사용하세요:
```shell
crewai log-tasks-outputs
```
재실행할 `task_id`를 확인했다면, 아래를 사용하세요:
```shell
crewai replay -t <task_id>
```
</Step>
</Steps>
<Note>
개발 환경에 `crewai`가 정상적으로 설치 및 구성되어 있는지 확인하세요.
</Note>
### 작업에서 프로그래밍 방식으로 리플레이하기
작업에서 프로그래밍 방식으로 리플레이하려면 다음 단계를 따르세요:
<Steps>
<Step title="리플레이 프로세스를 위한 `task_id`와 입력 파라미터를 지정합니다.">
리플레이 프로세스를 위한 `task_id`와 입력 파라미터를 지정합니다.
</Step>
<Step title="잠재적인 오류를 처리하기 위해 try-except 블록 내에서 리플레이 명령을 실행합니다.">
잠재적인 오류를 처리하기 위해 try-except 블록 내에서 리플레이 명령을 실행합니다.
<CodeGroup>
```python Code
def replay():
"""
Replay the crew execution from a specific task.
"""
task_id = '<task_id>'
inputs = {"topic": "CrewAI Training"} # This is optional; you can pass in the inputs you want to replay; otherwise, it uses the previous kickoff's inputs.
try:
YourCrewName_Crew().crew().replay(task_id=task_id, inputs=inputs)
except subprocess.CalledProcessError as e:
raise Exception(f"An error occurred while replaying the crew: {e}")
except Exception as e:
raise Exception(f"An unexpected error occurred: {e}")
```
</CodeGroup>
</Step>
</Steps>
## 결론
위의 개선 사항과 세부적인 기능으로 CrewAI에서 특정 작업을 재실행하는 것이 더욱 효율적이고 견고해졌습니다.
이러한 기능을 최대한 활용하려면 명령어와 단계를 정확하게 따라주시기 바랍니다.

View File

@@ -0,0 +1,127 @@
---
title: 순차 프로세스
description: CrewAI 프로젝트에서 작업 실행을 위한 순차 프로세스를 활용하는 방법에 대한 종합 가이드입니다.
icon: forward
---
## 소개
CrewAI는 순차적 및 계층적 프로세스를 모두 지원하는 구조화된 방식으로 작업을 실행할 수 있는 유연한 프레임워크를 제공합니다.
이 가이드에서는 효율적인 작업 실행과 프로젝트 완수를 보장하기 위해 이러한 프로세스를 효과적으로 구현하는 방법을 설명합니다.
## 순차적 프로세스 개요
순차적 프로세스는 작업이 선형적인 진행 방식으로 하나씩 차례로 실행되도록 보장합니다.
이 접근 방식은 특정 순서로 작업이 완료되어야 하는 프로젝트에 이상적입니다.
### 주요 기능
- **선형 작업 흐름**: 미리 정해진 순서대로 작업을 처리하여 체계적인 진행을 보장합니다.
- **단순성**: 명확하고 단계별 작업이 있는 프로젝트에 가장 적합합니다.
- **쉬운 모니터링**: 작업 완료 및 프로젝트 진행 상황을 쉽게 추적할 수 있습니다.
## 순차적 프로세스 구현하기
순차적 프로세스를 사용하려면 crew를 구성하고 수행되어야 하는 순서대로 작업을 정의하세요.
```python Code
from crewai import Crew, Process, Agent, Task, TaskOutput, CrewOutput
# Define your agents
researcher = Agent(
role='Researcher',
goal='Conduct foundational research',
backstory='An experienced researcher with a passion for uncovering insights'
)
analyst = Agent(
role='Data Analyst',
goal='Analyze research findings',
backstory='A meticulous analyst with a knack for uncovering patterns'
)
writer = Agent(
role='Writer',
goal='Draft the final report',
backstory='A skilled writer with a talent for crafting compelling narratives'
)
# Define your tasks
research_task = Task(
description='Gather relevant data...',
agent=researcher,
expected_output='Raw Data'
)
analysis_task = Task(
description='Analyze the data...',
agent=analyst,
expected_output='Data Insights'
)
writing_task = Task(
description='Compose the report...',
agent=writer,
expected_output='Final Report'
)
# Form the crew with a sequential process
report_crew = Crew(
agents=[researcher, analyst, writer],
tasks=[research_task, analysis_task, writing_task],
process=Process.sequential
)
# Execute the crew
result = report_crew.kickoff()
# Accessing the type-safe output
task_output: TaskOutput = result.tasks[0].output
crew_output: CrewOutput = result.output
```
### 참고:
순차적 프로세스의 각 작업에는 **반드시** 에이전트가 할당되어야 합니다. 모든 `Task`에 `agent` 파라미터가 포함되어 있는지 확인하세요.
### 워크플로우 실행
1. **초기 작업**: 순차적인 프로세스에서 첫 번째 agent가 자신의 작업을 완료하고 완료 신호를 보냅니다.
2. **이후 작업들**: agent들은 프로세스 유형에 따라 작업을 수행하며, 이전 작업의 결과나 지침이 실행을 안내합니다.
3. **완료**: 최종 작업이 실행되면 프로세스가 종료되어 프로젝트가 완료됩니다.
## 고급 기능
### 작업 위임
순차적 프로세스에서, 에이전트가 `allow_delegation`이 `True`로 설정되어 있으면 해당 에이전트는 crew 내의 다른 에이전트에게 작업을 위임할 수 있습니다.
이 기능은 crew에 여러 에이전트가 있을 때 자동으로 설정됩니다.
### 비동기 실행
작업은 비동기로 실행될 수 있어, 적절할 때 병렬 처리가 가능합니다.
비동기 작업을 생성하려면 작업을 정의할 때 `async_execution=True`로 설정하세요.
### 메모리 및 캐싱
CrewAI는 메모리와 캐싱 기능을 모두 지원합니다:
- **메모리**: Crew를 생성할 때 `memory=True`로 설정하면 활성화됩니다. 이를 통해 에이전트가 작업 간 정보를 유지할 수 있습니다.
- **캐싱**: 기본적으로 캐싱이 활성화되어 있습니다. 비활성화하려면 `cache=False`로 설정하세요.
### 콜백
콜백은 작업(task) 수준과 단계(step) 수준 모두에서 설정할 수 있습니다:
- `task_callback`: 각 작업이 완료된 후 실행됩니다.
- `step_callback`: 에이전트의 각 단계 실행 후에 실행됩니다.
### 사용량 메트릭
CrewAI는 모든 task와 agent 전반에 걸쳐 토큰 사용량을 추적합니다. 이 메트릭은 실행 후에 확인할 수 있습니다.
## 순차적 프로세스를 위한 모범 사례
1. **순서가 중요함**: 각 작업이 이전 작업을 기반으로 쌓일 수 있도록 논리적인 순서로 작업을 배열하세요.
2. **명확한 작업 설명**: 각 작업에 대해 에이전트를 효과적으로 안내할 수 있도록 상세한 설명을 제공하세요.
3. **적절한 에이전트 선정**: 각 작업의 요구사항에 맞게 에이전트의 역량과 역할을 매칭하세요.
4. **컨텍스트 활용**: 이전 작업에서 얻은 컨텍스트를 다음 작업에 활용하세요.
이 업데이트된 문서는 코드베이스의 최신 변경 사항을 정확하게 반영하고, 새로운 기능 및 설정을 어떻게 활용할 수 있는지 명확하게 설명합니다.
내용이 간단하고 명확하여 쉽게 이해할 수 있도록 구성되었습니다.

View File

@@ -0,0 +1,141 @@
---
title: "crew.py에서 어노테이션 사용하기"
description: "CrewAI에서 에이전트, 태스크, 컴포넌트를 올바르게 구조화하기 위해 어노테이션을 사용하는 방법을 알아보세요."
icon: "at"
---
이 가이드는 `crew.py` 파일에서 **agent**, **task**, 및 기타 구성 요소를 올바르게 참조하기 위해 주석을 사용하는 방법을 설명합니다.
## 소개
CrewAI 프레임워크에서 어노테이션은 클래스와 메소드를 데코레이트하는 데 사용되며, crew의 다양한 컴포넌트에 메타데이터와 기능을 제공합니다. 이러한 어노테이션은 코드의 구성과 구조화를 돕고, 코드의 가독성과 유지 관리를 용이하게 만듭니다.
## 사용 가능한 어노테이션
CrewAI 프레임워크는 다음과 같은 어노테이션을 제공합니다:
- `@CrewBase`: 메인 crew 클래스를 데코레이트할 때 사용합니다.
- `@agent`: Agent 객체를 정의하고 반환하는 메서드를 데코레이트합니다.
- `@task`: Task 객체를 정의하고 반환하는 메서드를 데코레이트합니다.
- `@crew`: Crew 객체를 생성하고 반환하는 메서드를 데코레이트합니다.
- `@llm`: Language Model 객체를 초기화하고 반환하는 메서드를 데코레이트합니다.
- `@tool`: Tool 객체를 초기화하고 반환하는 메서드를 데코레이트합니다.
- `@callback`: 콜백 메서드를 정의할 때 사용합니다.
- `@output_json`: JSON 데이터를 출력하는 메서드에 사용합니다.
- `@output_pydantic`: Pydantic 모델을 출력하는 메서드에 사용합니다.
- `@cache_handler`: 캐시 처리 메서드를 정의할 때 사용합니다.
## 사용 예시
이러한 주석을 어떻게 사용하는지 예제를 통해 살펴보겠습니다:
### 1. Crew Base 클래스
```python
@CrewBase
class LinkedinProfileCrew():
"""LinkedinProfile crew"""
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'
```
`@CrewBase` 어노테이션은 메인 crew 클래스를 데코레이트하는 데 사용됩니다. 이 클래스는 일반적으로 agent, task, 그리고 crew 자체를 생성하기 위한 구성과 메서드를 포함합니다.
### 2. 도구 정의
```python
@tool
def myLinkedInProfileTool(self):
return LinkedInProfileTool()
```
`@tool` 애너테이션은 도구 객체를 반환하는 메서드를 데코레이터할 때 사용됩니다. 이러한 도구들은 에이전트가 특정 작업을 수행할 때 사용할 수 있습니다.
### 3. LLM 정의
```python
@llm
def groq_llm(self):
api_key = os.getenv('api_key')
return ChatGroq(api_key=api_key, temperature=0, model_name="mixtral-8x7b-32768")
```
`@llm` 애노테이션은 Language Model 객체를 초기화하고 반환하는 메서드를 데코레이팅하는 데 사용됩니다. 이러한 LLM은 에이전트가 자연어 처리 작업을 수행할 때 사용됩니다.
### 4. 에이전트 정의
```python
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher']
)
```
`@agent` 어노테이션은 에이전트 객체를 정의하고 반환하는 메서드를 데코레이트할 때 사용됩니다.
### 5. Task 정의
```python
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_linkedin_task'],
agent=self.researcher()
)
```
`@task` 어노테이션은 Task 객체를 정의하고 반환하는 메서드를 데코레이트하는 데 사용됩니다. 이러한 메서드는 task 구성과 해당 task를 담당하는 agent를 지정합니다.
### 6. Crew 생성
```python
@crew
def crew(self) -> Crew:
"""Creates the LinkedinProfile crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
```
`@crew` 어노테이션은 `Crew` 객체를 생성하고 반환하는 메서드를 데코레이션하는 데 사용됩니다. 이 메서드는 모든 구성 요소(agents와 tasks)를 기능적인 crew로 조합합니다.
## YAML 구성
에이전트 구성은 일반적으로 YAML 파일에 저장됩니다. 아래는 연구원 에이전트에 대한 `agents.yaml` 파일 예시입니다.
```yaml
researcher:
role: >
LinkedIn Profile Senior Data Researcher
goal: >
Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}
Generate a Dall-E image based on domain {domain}
backstory: >
You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.
Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting
professional information clearly and concisely.
allow_delegation: False
verbose: True
llm: groq_llm
tools:
- myLinkedInProfileTool
- mySerperDevTool
- myDallETool
```
이 YAML 구성은 `LinkedinProfileCrew` 클래스에 정의된 연구원 에이전트에 해당합니다. 구성에는 에이전트의 역할, 목표, 배경 이야기와 사용하는 LLM 및 도구와 같은 기타 속성이 명시되어 있습니다.
YAML 파일의 `llm`과 `tools`가 Python 클래스에서 `@llm` 및 `@tool`로 데코레이션된 메서드와 어떻게 대응되는지 주목하세요.
## 모범 사례
- **일관성 있는 명명**: 메서드에 대해 명확하고 일관성 있는 명명 규칙을 사용하세요. 예를 들어, agent 메서드는 역할에 따라 이름을 지정할 수 있습니다(예: researcher, reporting_analyst).
- **환경 변수**: API 키와 같은 민감한 정보를 위해 환경 변수를 사용하세요.
- **유연성**: agent와 task를 쉽게 추가 및 제거할 수 있도록 crew를 유연하게 설계하세요.
- **YAML-코드 일치**: YAML 파일의 이름과 구조가 Python 코드의 데코레이터가 적용된 메서드와 정확히 일치하는지 확인하세요.
이 지침을 따르고 주석을 올바르게 사용하면 CrewAI 프레임워크를 이용해 구조적이고 유지보수가 쉬운 crew를 만들 수 있습니다.

View File

@@ -0,0 +1,64 @@
---
title: 여러 MCP 서버에 연결하기
description: CrewAI에서 MCPServerAdapter를 사용하여 여러 MCP 서버에 동시에 연결하고 해당 도구를 집계하는 방법을 알아봅니다.
icon: layer-group
---
## 개요
`crewai-tools`의 `MCPServerAdapter`는 여러 MCP 서버에 동시에 연결할 수 있게 해줍니다. 이는 에이전트가 서로 다른 서비스나 환경에 분산된 도구에 접근해야 할 때 유용합니다. 어댑터는 지정된 모든 서버에서 도구를 집계하여 CrewAI 에이전트가 사용할 수 있게 합니다.
## 구성
여러 서버에 연결하려면 서버 파라미터 딕셔너리의 리스트를 `MCPServerAdapter`에 제공합니다. 리스트에 있는 각 딕셔너리는 하나의 MCP 서버에 대한 파라미터를 정의해야 합니다.
각 서버에 대해 지원되는 transport 타입은 `stdio`, `sse`, 그리고 `streamable-http`입니다.
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
from mcp import StdioServerParameters # Needed for Stdio example
# 여러 MCP 서버의 파라미터 정의
server_params_list = [
# Streamable HTTP 서버
{
"url": "http://localhost:8001/mcp",
"transport": "streamable-http"
},
# SSE 서버
{
"url": "http://localhost:8000/sse",
"transport": "sse"
},
# StdIO 서버
StdioServerParameters(
command="python3",
args=["servers/your_stdio_server.py"],
env={"UV_PYTHON": "3.12", **os.environ},
)
]
try:
with MCPServerAdapter(server_params_list) as aggregated_tools:
print(f"Available aggregated tools: {[tool.name for tool in aggregated_tools]}")
multi_server_agent = Agent(
role="Versatile Assistant",
goal="Utilize tools from local Stdio, remote SSE, and remote HTTP MCP servers.",
backstory="An AI agent capable of leveraging a diverse set of tools from multiple sources.",
tools=aggregated_tools, # All tools are available here
verbose=True,
)
... # Your other agent, tasks, and crew code here
except Exception as e:
print(f"Error connecting to or using multiple MCP servers (Managed): {e}")
print("Ensure all MCP servers are running and accessible with correct configurations.")
```
## 연결 관리
컨텍스트 매니저(`with` 문)를 사용할 때, `MCPServerAdapter`는 구성된 MCP 서버와의 모든 연결의 라이프사이클(시작 및 종료)을 관리합니다. 이를 통해 리소스 관리를 단순화하고, 컨텍스트를 종료할 때 모든 연결이 적절하게 닫히도록 보장할 수 있습니다.

263
docs/ko/mcp/overview.mdx Normal file
View File

@@ -0,0 +1,263 @@
---
title: 'CrewAI에서 MCP 서버를 도구로 활용하기'
description: '`crewai-tools` 라이브러리를 사용하여 MCP 서버를 CrewAI agent에 도구로 통합하는 방법을 알아봅니다.'
icon: plug
---
## 개요
[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP)는 AI 에이전트가 MCP 서버로 알려진 외부 서비스와 통신함으로써 LLM에 컨텍스트를 제공할 수 있도록 표준화된 방식을 제공합니다.
`crewai-tools` 라이브러리는 CrewAI의 기능을 확장하여, 이러한 MCP 서버에서 제공하는 툴을 에이전트에 원활하게 통합할 수 있도록 해줍니다.
이를 통해 여러분의 crew는 방대한 기능 에코시스템에 접근할 수 있습니다.
현재 다음과 같은 전송 메커니즘을 지원합니다:
- **Stdio**: 로컬 서버용 (동일 머신 내 프로세스 간 표준 입력/출력을 통한 통신)
- **Server-Sent Events (SSE)**: 원격 서버용 (서버에서 클라이언트로의 일방향, 실시간 데이터 스트리밍, HTTP 기반)
- **Streamable HTTP**: 원격 서버용 (유연하며 잠재적으로 양방향 통신이 가능, 주로 SSE를 활용한 서버-클라이언트 스트림 제공, HTTP 기반)
## 비디오 튜토리얼
CrewAI와 MCP 통합에 대한 종합적인 안내를 위해 이 비디오 튜토리얼을 시청하세요:
<iframe
width="100%"
height="400"
src="https://www.youtube.com/embed/TpQ45lAZh48"
title="CrewAI MCP Integration Guide"
frameborder="0"
style={{ borderRadius: '10px' }}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
## 설치
`crewai-tools`와 함께 MCP를 사용하기 전에, 아래 명령어를 통해 `mcp` 추가 `crewai-tools` 종속성을 설치해야 합니다:
```shell
uv pip install 'crewai-tools[mcp]'
```
## 주요 개념 및 시작하기
`crewai-tools`의 `MCPServerAdapter` 클래스는 MCP 서버에 연결하고 해당 도구들을 CrewAI 에이전트에서 사용할 수 있도록 하는 기본 방법입니다. 다양한 전송 메커니즘을 지원하며 연결 관리를 간소화합니다.
파이썬 컨텍스트 매니저(`with` 문)를 사용하는 것이 `MCPServerAdapter`를 위한 **권장 방법**입니다. 이를 통해 MCP 서버와의 연결 시작 및 종료가 자동으로 처리됩니다.
## 연결 구성
`MCPServerAdapter`는 연결 동작을 맞춤화할 수 있는 여러 구성 옵션을 지원합니다:
- **`connect_timeout`** (선택 사항): MCP 서버에 연결을 설정하기 위해 대기할 최대 시간(초 단위)입니다. 명시하지 않으면 기본값은 30초입니다. 응답 시간이 가변적인 원격 서버에 특히 유용합니다.
```python
# 사용자 지정 연결 타임아웃 예시
with MCPServerAdapter(server_params, connect_timeout=60) as tools:
# 60초 이내에 연결이 설정되지 않으면 타임아웃 발생
pass
```
```python
from crewai import Agent
from crewai_tools import MCPServerAdapter
from mcp import StdioServerParameters # Stdio 서버용
# 예시 server_params (서버 유형에 따라 하나 선택):
# 1. Stdio 서버:
server_params=StdioServerParameters(
command="python3",
args=["servers/your_server.py"],
env={"UV_PYTHON": "3.12", **os.environ},
)
# 2. SSE 서버:
server_params = {
"url": "http://localhost:8000/sse",
"transport": "sse"
}
# 3. 스트림 가능 HTTP 서버:
server_params = {
"url": "http://localhost:8001/mcp",
"transport": "streamable-http"
}
# 예시 사용법 (server_params 설정 후 주석 해제 및 적용):
with MCPServerAdapter(server_params, connect_timeout=60) as mcp_tools:
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
my_agent = Agent(
role="MCP Tool User",
goal="MCP 서버의 도구를 활용합니다.",
backstory="나는 MCP 서버에 연결하여 해당 도구를 사용할 수 있습니다.",
tools=mcp_tools, # 불러온 도구를 Agent에 전달
reasoning=True,
verbose=True
)
# ... 나머지 crew 설정 ...
```
이 일반적인 패턴은 도구를 통합하는 방법을 보여줍니다. 각 transport에 맞춘 구체적인 예시는 아래의 상세 가이드를 참고하세요.
## 필터링 도구
도구를 필터링하는 방법에는 두 가지가 있습니다:
1. 딕셔너리 스타일의 인덱싱을 사용하여 특정 도구에 접근하기.
2. 도구 이름 목록을 `MCPServerAdapter` 생성자에 전달하기.
### 딕셔너리 스타일 인덱싱을 사용하여 특정 도구에 접근하기
```python
with MCPServerAdapter(server_params, connect_timeout=60) as mcp_tools:
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
my_agent = Agent(
role="MCP Tool User",
goal="Utilize tools from an MCP server.",
backstory="I can connect to MCP servers and use their tools.",
tools=[mcp_tools["tool_name"]], # Pass the loaded tools to your agent
reasoning=True,
verbose=True
)
# ... rest of your crew setup ...
```
### `MCPServerAdapter` 생성자에 도구 이름의 리스트를 전달하세요.
```python
with MCPServerAdapter(server_params, "tool_name", connect_timeout=60) as mcp_tools:
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
my_agent = Agent(
role="MCP Tool User",
goal="Utilize tools from an MCP server.",
backstory="I can connect to MCP servers and use their tools.",
tools=mcp_tools, # Pass the loaded tools to your agent
reasoning=True,
verbose=True
)
# ... rest of your crew setup ...
```
## CrewBase와 함께 사용하기
CrewBase 클래스 내에서 MCPServer 도구를 사용하려면 `mcp_tools` 메서드를 사용하세요. 서버 구성은 mcp_server_params 속성을 통해 제공되어야 합니다. 단일 구성 또는 여러 서버 구성을 리스트 형태로 전달할 수 있습니다.
```python
@CrewBase
class CrewWithMCP:
# ... 에이전트 및 작업 구성 파일 정의 ...
mcp_server_params = [
# 스트리머블 HTTP 서버
{
"url": "http://localhost:8001/mcp",
"transport": "streamable-http"
},
# SSE 서버
{
"url": "http://localhost:8000/sse",
"transport": "sse"
},
# StdIO 서버
StdioServerParameters(
command="python3",
args=["servers/your_stdio_server.py"],
env={"UV_PYTHON": "3.12", **os.environ},
)
]
@agent
def your_agent(self):
return Agent(config=self.agents_config["your_agent"], tools=self.get_mcp_tools()) # 모든 사용 가능한 도구 가져오기
# ... 나머지 crew 설정 ...
```
`get_mcp_tools` 메서드에 도구 이름의 리스트를 전달하여, 에이전트에 제공되는 도구를 필터링할 수 있습니다.
```python
@agent
def another_agent(self):
return Agent(
config=self.agents_config["your_agent"],
tools=self.get_mcp_tools("tool_1", "tool_2") # 특정 도구만 가져오기
)
```
## MCP 통합 탐색
<CardGroup cols={2}>
<Card
title="Stdio 전송"
icon="server"
href="/ko/mcp/stdio"
color="#3B82F6"
>
표준 입력/출력을 통해 로컬 MCP 서버에 연결합니다. 스크립트와 로컬 실행 파일에 이상적입니다.
</Card>
<Card
title="SSE 전송"
icon="wifi"
href="/ko/mcp/sse"
color="#10B981"
>
실시간 데이터 스트리밍을 위해 Server-Sent Events를 사용하여 원격 MCP 서버와 통합합니다.
</Card>
<Card
title="스트림 가능한 HTTP 전송"
icon="globe"
href="/ko/mcp/streamable-http"
color="#F59E0B"
>
유연한 스트림 가능한 HTTP를 활용하여 원격 MCP 서버와 안정적으로 통신할 수 있습니다.
</Card>
<Card
title="다중 서버 연결"
icon="layer-group"
href="/ko/mcp/multiple-servers"
color="#8B5CF6"
>
하나의 어댑터를 사용하여 여러 MCP 서버의 도구를 동시에 통합할 수 있습니다.
</Card>
<Card
title="보안 고려사항"
icon="lock"
href="/ko/mcp/security"
color="#EF4444"
>
에이전트를 안전하게 보호하기 위한 MCP 통합의 중요한 보안 모범 사례를 검토하세요.
</Card>
</CardGroup>
CrewAI와의 MCP 통합에 대한 전체 데모와 예제를 보려면 이 저장소를 확인하세요! 👇
<Card
title="GitHub 저장소"
icon="github"
href="https://github.com/tonykipkemboi/crewai-mcp-demo"
target="_blank"
>
CrewAI MCP 데모
</Card>
## MCP와 함께 안전하게 사용하기
<Warning>
항상 MCP 서버를 사용하기 전에 해당 서버를 신뢰할 수 있는지 확인하세요.
</Warning>
#### 보안 경고: DNS 리바인딩 공격
SSE 전송은 적절하게 보안되지 않은 경우 DNS 리바인딩 공격에 취약할 수 있습니다.
이를 방지하려면 다음을 수행하세요:
1. **항상 Origin 헤더를 검증**하여 들어오는 SSE 연결이 예상한 소스에서 오는지 확인합니다.
2. **서버를 모든 네트워크 인터페이스**(0.0.0.0)에 바인딩하는 것을 피하고, 로컬에서 실행할 때는 localhost(127.0.0.1)에만 바인딩합니다.
3. **모든 SSE 연결에 대해 적절한 인증을 구현**합니다.
이러한 보호 조치가 없으면 공격자가 원격 웹사이트에서 로컬 MCP 서버와 상호작용하기 위해 DNS 리바인딩을 사용할 수 있습니다.
자세한 내용은 [Anthropic의 MCP 전송 보안 문서](https://modelcontextprotocol.io/docs/concepts/transports#security-considerations)를 참고하세요.
### 제한 사항
* **지원되는 프리미티브**: 현재 `MCPServerAdapter`는 주로 MCP `tools`를 어댑팅하는 기능을 지원합니다. 다른 MCP 프리미티브(예: `prompts` 또는 `resources`)는 현재 이 어댑터를 통해 CrewAI 컴포넌트로 직접 통합되어 있지 않습니다.
* **출력 처리**: 어댑터는 일반적으로 MCP tool의 주요 텍스트 출력(예: `.content[0].text`)을 처리합니다. 복잡하거나 멀티모달 출력의 경우 이 패턴에 맞지 않으면 별도의 커스텀 처리가 필요할 수 있습니다.

165
docs/ko/mcp/security.mdx Normal file
View File

@@ -0,0 +1,165 @@
---
title: MCP 보안 고려사항
description: MCP 서버를 CrewAI agent와 통합할 때 중요한 보안 모범 사례에 대해 알아보세요.
icon: lock
---
## 개요
<Warning>
MCP 보안에서 가장 중요한 측면은 **신뢰**입니다. 신뢰할 수 있다고 확신하는 MCP 서버에만 CrewAI 에이전트를 **연결해야 합니다**.
</Warning>
CrewAI 에이전트에 MCP(Model Context Protocol) 서버와 같은 외부 서비스를 통합할 때 보안이 가장 중요합니다.
MCP 서버는 노출한 도구를 기반으로 코드를 실행하거나 데이터에 접근하거나 다른 시스템과 상호작용할 수 있습니다.
응용 프로그램과 데이터를 보호하기 위해 그 영향력을 이해하고 모범 사례를 따르는 것이 매우 중요합니다.
### 위험
- 에이전트가 실행 중인 머신에서 임의의 코드를 실행할 수 있습니다(특히 서버가 실행되는 명령어를 제어할 수 있는 `Stdio` 전송 방식을 사용할 경우).
- 에이전트나 그 환경에서 민감한 데이터가 노출될 수 있습니다.
- 예기치 않은 방식으로 에이전트의 동작이 조작되어, 본인 동의 없이 API 호출이 이루어질 수 있습니다.
- 정교한 프롬프트 인젝션 기법(아래 참조)을 통해 에이전트의 reasoning 프로세스가 탈취될 수 있습니다.
### 1. MCP 서버 신뢰하기
<Warning>
**신뢰할 수 있는 MCP 서버에만 연결하십시오.**
</Warning>
`MCPServerAdapter`를 MCP 서버에 연결하도록 구성하기 전에 다음을 반드시 확인하십시오:
- **서버 운영자는 누구입니까?** 신뢰할 수 있는 잘 알려진 서비스이거나 여러분이 직접 제어하는 내부 서버입니까?
- **어떤 도구를 노출합니까?** 도구의 기능을 이해해야 합니다. 공격자가 제어권을 얻거나 서버 자체가 악의적이라면 이 도구들이 오용될 수 있습니까?
- **어떤 데이터를 접근하거나 처리합니까?** MCP 서버에 전송되거나 처리될 수 있는 민감한 정보가 있는지 반드시 파악하십시오.
특히 에이전트가 민감한 작업이나 데이터를 처리하는 경우, 알 수 없거나 검증되지 않은 MCP 서버에는 연결하지 마십시오.
### 2. Tool Metadata를 통한 보안 프롬프트 인젝션: "Model Control Protocol"의 위험성
중요하면서도 미묘한 위험 중 하나는 툴 메타데이터를 통한 프롬프트 인젝션 가능성입니다. 그 과정은 다음과 같습니다:
1. CrewAI 에이전트가 MCP 서버에 연결하면, 일반적으로 사용 가능한 툴 목록을 요청합니다.
2. MCP 서버는 각 툴에 대한 메타데이터를 이름, 설명, 파라미터 설명과 함께 응답합니다.
3. 에이전트의 언더라이잉 Language Model(LLM)은 해당 메타데이터를 활용해 언제, 어떻게 툴을 사용할지 이해합니다. 이 메타데이터는 LLM의 시스템 프롬프트나 컨텍스트에 포함되는 경우가 많습니다.
4. 악의적인 MCP 서버는 툴의 메타데이터(이름, 설명 등)에 숨겨진 또는 노골적인 명령어를 삽입할 수 있습니다. 이러한 명령은 프롬프트 인젝션으로 동작하여, LLM에게 특정 방식으로 동작하라고 지시하거나, 민감한 정보를 공개하게 하거나, 악의적인 행동을 수행하게 만들 수 있습니다.
**중요하게도, 이 공격은 에이전트가 해당 툴을 실제로 *사용*하지 않더라도 단순히 악성 서버에 연결해 툴 목록을 조회하는 것만으로도 발생할 수 있습니다.** 악의적인 메타데이터에 노출되는 것만으로도 에이전트의 행동이 손상될 수 있습니다.
**완화 방안:**
* **신뢰되지 않은 서버에 대한 극도의 주의:** 반복합니다. *완전히 신뢰하지 않는 MCP 서버에는 절대 연결하지 마십시오.* 메타데이터 인젝션의 위험성 때문에 이 점이 매우 중요합니다.
### Stdio 전송 보안
Stdio(표준 입력/출력) 전송은 일반적으로 CrewAI 애플리케이션과 동일한 머신에서 실행되는 로컬 MCP 서버에 사용됩니다.
- **프로세스 격리**: 기본적으로 네트워크에 노출되지 않아 일반적으로 더 안전하지만, `StdioServerParameters`로 실행되는 스크립트나 명령어가 신뢰할 수 있는 소스에서 왔으며 적절한 파일 시스템 권한을 가지고 있는지 확인해야 합니다. 악의적인 Stdio 서버 스크립트는 여전히 로컬 시스템에 피해를 줄 수 있습니다.
- **입력값 정제**: Stdio 서버 스크립트가 에이전트 상호작용에서 파생된 복잡한 입력을 받는 경우, 스크립트 자체에서 이러한 입력값을 정제하여 명령어 삽입이나 스크립트 논리 내 다른 취약점이 발생하지 않도록 해야 합니다.
- **리소스 제한**: 로컬 Stdio 서버 프로세스는 로컬 자원(CPU, 메모리)을 소모하므로, 반드시 정상적으로 동작하는지, 시스템 자원을 소모하지 않는지 주의 깊게 관리해야 합니다.
### 혼동된 대리인(Confused Deputy) 공격
[혼동된 대리인 문제(Confused Deputy Problem)](https://en.wikipedia.org/wiki/Confused_deputy_problem)는 고전적인 보안 취약점으로, MCP 통합에서 특히 MCP 서버가 다른 서드파티 서비스(예: Google Calendar, GitHub)와 OAuth 2.0을 통한 인증을 할 때 프록시 역할을 할 경우 나타날 수 있습니다.
**시나리오:**
1. MCP 서버(여기서는 `MCP-Proxy`라고 부르겠습니다)가 에이전트가 `ThirdPartyAPI`와 상호작용할 수 있도록 허용합니다.
2. `MCP-Proxy`는 `ThirdPartyAPI`의 인증 서버와 통신할 때 자체의 단일 고정 `client_id`를 사용합니다.
3. 사용자(즉, 여러분)는 정당하게 `MCP-Proxy`가 여러분을 대신해 `ThirdPartyAPI`에 접근할 수 있도록 승인합니다. 이 과정에서 `ThirdPartyAPI`의 인증 서버는 여러분의 브라우저에 `MCP-Proxy`의 `client_id`에 대한 동의 쿠키를 설정할 수 있습니다.
4. 공격자는 악의적인 링크를 만듭니다. 이 링크는 `MCP-Proxy`와의 OAuth 플로우를 시작하지만, `ThirdPartyAPI`의 인증 서버를 속이도록 설계되어 있습니다.
5. 여러분이 이 링크를 클릭하고, `ThirdPartyAPI`의 인증 서버가 이미 존재하는 `MCP-Proxy`의 `client_id`에 대한 동의 쿠키를 확인하면, 다시 동의를 묻지 않고 *건너뛰기* 할 수 있습니다.
6. 그러면 `MCP-Proxy`가 (공격자에게) 인증 코드를 전달하도록 속거나, 공격자가 여러분을 가장해 `MCP-Proxy`에 사용할 수 있는 MCP 인증 코드를 받게 될 수 있습니다.
**대응 방안(주로 MCP 서버 개발자용):**
* 다운스트림 서비스를 위해 정적 client ID를 사용하는 MCP 프록시 서버는 **각 클라이언트 애플리케이션 또는 에이전트별**로 명시적인 사용자 동의를 반드시 받아야 합니다. 이 동의는 서드파티 서비스와의 OAuth 플로우 시작 *이전*에 이루어져야 하며, `MCP-Proxy` 자체가 동의 화면을 표시하도록 해야 합니다.
**CrewAI 사용자 주의사항:**
* MCP 서버가 여러 번 OAuth 인증을 위해 리디렉션하는 경우, 특히 예상치 않거나 요청된 권한이 과도하게 넓다면 주의해야 합니다.
* 자신과 프록시할 수 있는 서드파티 서비스의 구분을 명확하게 하는 MCP 서버를 선호하는 것이 좋습니다.
### 원격 전송 보안 (SSE & Streamable HTTP)
Server-Sent Events(SSE) 또는 Streamable HTTP를 통해 원격 MCP 서버에 연결할 때, 표준 웹 보안 관행이 필수적입니다.
### SSE 보안 고려사항
### a. DNS 리바인딩 공격 (특히 SSE의 경우)
<Critical>
**DNS 리바인딩 공격으로부터 보호하세요.**
</Critical>
DNS 리바인딩은 공격자가 제어하는 웹사이트가 동일 출처 정책(same-origin policy)을 우회하여 사용자의 로컬 네트워크(예: `localhost`) 또는 인트라넷에 있는 서버에 요청을 보낼 수 있도록 합니다. 이는 MCP 서버를 로컬(예: 개발용)로 실행하고 브라우저와 유사한 환경에서 agent를 사용하는 경우(일반적인 CrewAI 백엔드 구성에서는 드물지만) 또는 MCP 서버가 내부 네트워크상에 있을 경우 특히 위험할 수 있습니다.
**MCP 서버 구현자를 위한 대응 전략:**
- **`Origin` 및 `Host` 헤더 검증**: MCP 서버(특히 SSE 서버)는 `Origin` 및/또는 `Host` HTTP 헤더를 검증하여 요청이 예상되는 도메인/클라이언트로부터 오는지 확인해야 합니다.
- **`localhost`(127.0.0.1)로 바인딩**: 개발을 위해 MCP 서버를 로컬에서 실행할 때는 `0.0.0.0` 대신 `127.0.0.1`로 바인딩하세요. 이를 통해 네트워크의 다른 기기에서 접근하지 못하도록 막을 수 있습니다.
- **인증(Authentication)**: MCP 서버가 공개된 익명 접근을 목적으로 하지 않는 한 모든 연결에 대해 인증을 요구하세요.
### b. HTTPS 사용
- **전송 중 데이터 암호화**: 원격 MCP 서버의 URL에는 항상 HTTPS(HTTP Secure)를 사용하세요. 이는 CrewAI 애플리케이션과 MCP 서버 간의 통신을 암호화하여 도청 및 중간자 공격으로부터 보호합니다. `MCPServerAdapter`는 URL에 제공된 스킴(`http` 또는 `https`)을 그대로 따릅니다.
### c. 토큰 패스스루(Token Passthrough) (안티 패턴)
이 문제는 주로 MCP 서버 개발자들에게 해당되지만, 이를 이해하는 것은 안전한 서버를 선택하는 데 도움이 됩니다.
"토큰 패스스루"란, MCP 서버가 CrewAI agent로부터 받은 액세스 토큰(예를 들어 `ServiceA`를 위한 토큰일 수도 있음)을 별도의 적절한 검증 없이 다른 하위 API(`ServiceB`)로 그대로 전달하는 것을 의미합니다. 특히, `ServiceB`(또는 MCP 서버 자체)는 명시적으로 *자신들을 위해* 발급된 토큰만 받아야 합니다(즉, 토큰 내의 'audience' 클레임이 해당 서버/서비스와 일치해야 함).
**위험성:**
* MCP 서버나 하위 API의 보안 제어(예 : 속도 제한, 세밀한 권한 부여 등)를 우회할 수 있습니다.
* 감사 추적 및 책임성을 저해할 수 있습니다.
* 탈취된 토큰의 악용을 허용할 수 있습니다.
**대응 방안 (MCP 서버 개발자용):**
* MCP 서버는 **명시적으로 자신을 위해 발급된 토큰만** 받아야 합니다. 토큰의 audience 클레임을 반드시 검증해야 합니다.
**CrewAI 사용자에게 미치는 영향:**
* 사용자가 직접적으로 제어할 수는 없지만, 보안 모범 사례를 준수하는 잘 설계된 MCP 서버에 연결하는 것이 중요함을 강조합니다.
#### 인증 및 인가
- **신원 확인**: MCP 서버가 민감한 도구 또는 비공개 데이터에 대한 액세스를 제공하는 경우, 클라이언트(귀하의 CrewAI 애플리케이션)의 신원을 확인하기 위해 강력한 인증 메커니즘을 반드시 구현해야 합니다. 이는 API 키, OAuth 토큰 또는 기타 표준 방법을 포함할 수 있습니다.
- **최소 권한 원칙**: `MCPServerAdapter`에서 사용하는 자격 증명(있는 경우)은 필요한 도구에 접근하는 데 꼭 필요한 권한만 가지고 있도록 해야 합니다.
### d. 입력 검증 및 정제
- **입력 검증은 매우 중요합니다**: MCP 서버는 에이전트로부터 받은 모든 입력을 처리하거나 도구에 전달하기 *전에* 철저하게 검증해야 합니다. 이는 많은 일반적인 취약점에 대한 1차 방어선입니다:
- **명령어 삽입:** 도구가 입력을 기반으로 셸 명령, SQL 쿼리 또는 기타 해석형 언어 문장을 구성하는 경우, 서버는 악의적 명령어 주입 및 실행을 방지하기 위해 이 입력을 꼼꼼하게 정제해야 합니다.
- **경로 탐색:** 도구가 입력 매개변수에 따라 파일에 접근하는 경우, 서버는 미허가 파일 또는 디렉터리에 접근하지 못하도록 이 경로를 검증 및 정제해야 합니다(예: `../` 시퀀스 차단).
- **데이터 타입 및 범위 검사:** 서버는 입력 데이터가 기대하는 데이터 타입(예: 문자열, 숫자, 불리언)에 부합하는지, 허용 범위 내에 있거나 정의된 형식(예: URL에 대한 정규식)에 맞는지 확인해야 합니다.
- **JSON 스키마 검증:** 모든 도구 매개변수는 정의된 JSON 스키마에 엄격하게 맞춰 검증되어야 합니다. 이를 통해 잘못된 요청을 조기에 차단할 수 있습니다.
- **클라이언트 측 인지**: 서버 측 검증이 가장 중요하지만, CrewAI 사용자는 특히 신뢰도가 낮은 또는 새로운 MCP 서버와 상호작용할 때 자신의 에이전트가 MCP 도구에 전달하도록 설계된 데이터에 각별히 유의해야 합니다.
### e. 속도 제한 및 리소스 관리
- **오용 방지**: MCP 서버는 악의적(서비스 거부 공격 등)이든 비의도적(예: 잘못 구성된 agent가 과도한 요청을 보내는 경우)이든 오용을 방지하기 위해 속도 제한을 구현해야 합니다.
- **클라이언트 측 재시도**: 일시적인 네트워크 문제나 서버의 속도 제한이 예상될 경우, CrewAI 작업에서 합리적인 재시도 로직을 구현하되, 서버 부하를 가중시킬 수 있는 과도한 재시도는 피해야 합니다.
## 4. 보안 MCP 서버 구현 권장 사항 (개발자용)
CrewAI 에이전트가 연결할 수 있는 MCP 서버를 개발하고 있다면, 위의 내용에 추가하여 다음과 같은 모범 사례를 고려하세요:
- **안전한 코딩 관행 준수**: 선택한 언어 및 프레임워크에 대한 표준 안전 코딩 원칙(예: OWASP Top 10)을 준수하세요.
- **최소 권한 원칙**: MCP 서버를 실행하는 프로세스(특히 `Stdio`의 경우)는 작업에 필요한 최소 권한만 보유하도록 하세요. 툴 자체도 자신의 기능 수행에 필요한 최소한의 권한만으로 동작해야 합니다.
- **종속성 관리**: 운영 체제 패키지, 언어 런타임, 써드파티 라이브러리 등 모든 서버 측 종속성을 최신 상태로 유지하여 알려진 취약점을 패치하세요. 취약한 종속성을 스캔하는 도구를 사용하세요.
- **안전한 기본값**: 서버와 그 도구를 기본적으로 안전하게 설계하세요. 예를 들어, 위험할 수 있는 기능은 기본적으로 꺼져 있거나 명확한 경고와 함께 명시적으로 opt-in 하도록 해야 합니다.
- **툴에 대한 접근 제어**: 인증 및 권한이 부여된 에이전트 또는 사용자만 특정 툴(특히 강력하거나 민감하거나 비용이 발생하는 툴)에 접근할 수 있도록 강력한 메커니즘을 구현하세요.
- **안전한 오류 처리**: 서버는 클라이언트에게 상세한 내부 오류 메시지, 스택 트레이스 또는 디버깅 정보를 노출해서는 안 됩니다. 이러한 정보는 내부 동작이나 잠재적 취약점을 드러낼 수 있습니다. 오류는 서버 측에서 진단을 목적으로 포괄적으로 기록하세요.
- **포괄적인 로깅 및 모니터링**: 보안 관련 이벤트(예: 인증 시도, 툴 호출, 오류, 권한 변경)에 대해 상세하게 로깅하세요. 이런 로그를 모니터링하여 의심스러운 활동이나 악용 패턴을 파악하세요.
- **MCP 인증 사양 준수**: 인증 및 권한 부여를 구현할 경우, [MCP Authorization specification](https://modelcontextprotocol.io/specification/draft/basic/authorization) 및 관련 [OAuth 2.0 security best practices](https://datatracker.ietf.org/doc/html/rfc9700)를 엄격히 준수하세요.
- **정기적인 보안 감사**: MCP 서버가 민감한 데이터를 처리하거나, 중요한 작업을 수행하거나, 대외적으로 노출된 경우 자격을 갖춘 전문가의 정기적인 보안 감사를 고려하세요.
## 5. 추가 참고 자료
MCP 보안에 대한 자세한 내용은 공식 문서를 참고하세요:
- **[MCP 전송 보안](https://modelcontextprotocol.io/docs/concepts/transports#security-considerations)**
이러한 보안 고려사항을 이해하고 모범 사례를 구현하면 CrewAI 프로젝트에서 MCP 서버의 강력한 기능을 안전하게 활용할 수 있습니다.
여기서 다루는 내용이 모든 것을 포괄하는 것은 아니지만, 가장 일반적이고 중요한 보안 문제들을 포함하고 있습니다.
위협은 계속 진화하기 때문에 지속적으로 정보를 확인하고 그에 맞춰 보안 조치를 조정하는 것이 중요합니다.

150
docs/ko/mcp/sse.mdx Normal file
View File

@@ -0,0 +1,150 @@
---
title: SSE 트랜스포트
description: 서버 전송 이벤트(SSE)를 사용하여 CrewAI를 원격 MCP 서버에 연결하여 실시간 통신을 구현하는 방법을 알아보세요.
icon: wifi
---
## 개요
Server-Sent Events(SSE)는 웹 서버가 하나의 장기 실행 HTTP 연결을 통해 클라이언트에 업데이트를 전송할 수 있는 표준 방식을 제공합니다. MCP의 맥락에서 SSE는 원격 서버가 데이터(예: tool 응답)를 실시간으로 CrewAI 애플리케이션에 스트리밍하는 데 사용됩니다.
## 주요 개념
- **원격 서버**: SSE는 원격에 호스팅된 MCP 서버에 적합합니다.
- **단방향 스트림**: 일반적으로 SSE는 서버에서 클라이언트로의 단방향 통신 채널입니다.
- **`MCPServerAdapter` 구성**: SSE의 경우, 서버의 URL을 제공하고 전송 유형을 지정해야 합니다.
## SSE를 통한 연결
SSE 기반 MCP 서버에 연결하려면 연결 수명 주기를 관리하는 두 가지 주요 접근 방식을 사용할 수 있습니다.
### 1. 완전 관리형 연결(권장)
Python 컨텍스트 매니저(`with` 문)를 사용하는 것이 권장되는 접근 방식입니다. 이 방법은 SSE MCP 서버에 대한 연결의 생성과 종료를 자동으로 처리합니다.
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
server_params = {
"url": "http://localhost:8000/sse", # Replace with your actual SSE server URL
"transport": "sse"
}
# Using MCPServerAdapter with a context manager
try:
with MCPServerAdapter(server_params) as tools:
print(f"Available tools from SSE MCP server: {[tool.name for tool in tools]}")
# Example: Using a tool from the SSE MCP server
sse_agent = Agent(
role="Remote Service User",
goal="Utilize a tool provided by a remote SSE MCP server.",
backstory="An AI agent that connects to external services via SSE.",
tools=tools,
reasoning=True,
verbose=True,
)
sse_task = Task(
description="Fetch real-time stock updates for 'AAPL' using an SSE tool.",
expected_output="The latest stock price for AAPL.",
agent=sse_agent,
markdown=True
)
sse_crew = Crew(
agents=[sse_agent],
tasks=[sse_task],
verbose=True,
process=Process.sequential
)
if tools: # Only kickoff if tools were loaded
result = sse_crew.kickoff() # Add inputs={'stock_symbol': 'AAPL'} if tool requires it
print("\nCrew Task Result (SSE - Managed):\n", result)
else:
print("Skipping crew kickoff as tools were not loaded (check server connection).")
except Exception as e:
print(f"Error connecting to or using SSE MCP server (Managed): {e}")
print("Ensure the SSE MCP server is running and accessible at the specified URL.")
```
<Note>
`"http://localhost:8000/sse"`를 실제 SSE MCP 서버의 URL로 교체하십시오.
</Note>
### 2. 수동 연결 라이프사이클
더 세밀한 제어가 필요한 경우, `MCPServerAdapter`의 연결 라이프사이클을 수동으로 관리할 수 있습니다.
<Info>
연결이 종료되고 리소스가 해제되도록 반드시 `mcp_server_adapter.stop()`을 호출해야 합니다. `try...finally` 블록을 사용하는 것을 강력히 권장합니다.
</Info>
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
server_params = {
"url": "http://localhost:8000/sse", # Replace with your actual SSE server URL
"transport": "sse"
}
mcp_server_adapter = None
try:
mcp_server_adapter = MCPServerAdapter(server_params)
mcp_server_adapter.start()
tools = mcp_server_adapter.tools
print(f"Available tools (manual SSE): {[tool.name for tool in tools]}")
manual_sse_agent = Agent(
role="Remote Data Analyst",
goal="Analyze data fetched from a remote SSE MCP server using manual connection management.",
backstory="An AI skilled in handling SSE connections explicitly.",
tools=tools,
verbose=True
)
analysis_task = Task(
description="Fetch and analyze the latest user activity trends from the SSE server.",
expected_output="A summary report of user activity trends.",
agent=manual_sse_agent
)
analysis_crew = Crew(
agents=[manual_sse_agent],
tasks=[analysis_task],
verbose=True,
process=Process.sequential
)
result = analysis_crew.kickoff()
print("\nCrew Task Result (SSE - Manual):\n", result)
except Exception as e:
print(f"An error occurred during manual SSE MCP integration: {e}")
print("Ensure the SSE MCP server is running and accessible.")
finally:
if mcp_server_adapter and mcp_server_adapter.is_connected:
print("Stopping SSE MCP server connection (manual)...")
mcp_server_adapter.stop() # **Crucial: Ensure stop is called**
elif mcp_server_adapter:
print("SSE MCP server adapter was not connected. No stop needed or start failed.")
```
## SSE를 위한 보안 고려사항
<Warning>
**DNS 리바인딩 공격**: SSE 전송 방식은 MCP 서버가 적절하게 보안 조치되지 않은 경우 DNS 리바인딩 공격에 취약할 수 있습니다. 이로 인해 악의적인 웹사이트가 로컬 또는 인트라넷 기반 MCP 서버와 상호 작용할 수 있습니다.
</Warning>
이 위험을 완화하려면:
- MCP 서버 구현에서는 들어오는 SSE 연결의 **`Origin` 헤더를 검증**해야 합니다.
- 개발 환경에서 로컬 SSE MCP 서버를 실행할 때에는 모든 네트워크 인터페이스(`0.0.0.0`)가 아닌, **`localhost`(`127.0.0.1`)에만 바인딩**해야 합니다.
- 민감한 도구나 데이터를 노출하는 SSE 연결에는 **적절한 인증**을 구현해야 합니다.
보안 모범 사례에 대한 포괄적인 개요는 [보안 고려사항](./security.mdx) 페이지와 공식 [MCP 전송 보안 문서](https://modelcontextprotocol.io/docs/concepts/transports#security-considerations)를 참고하시기 바랍니다.

134
docs/ko/mcp/stdio.mdx Normal file
View File

@@ -0,0 +1,134 @@
---
title: Stdio 전송
description: Stdio(표준 입력/출력) 전송 메커니즘을 사용하여 CrewAI를 로컬 MCP 서버에 연결하는 방법을 알아보세요.
icon: server
---
## 개요
Stdio(표준 입력/출력) 트랜스포트는 `MCPServerAdapter`를 로컬 MCP 서버에 연결하기 위해 설계되었습니다. 이 MCP 서버는 표준 입력 및 출력 스트림을 통해 통신합니다. 이는 일반적으로 MCP 서버가 CrewAI 애플리케이션과 동일한 머신에서 실행되는 스크립트나 실행 파일일 때 사용됩니다.
## 주요 개념
- **로컬 실행**: Stdio 전송은 MCP 서버를 위한 로컬에서 실행 중인 프로세스를 관리합니다.
- **`StdioServerParameters`**: `mcp` 라이브러리의 이 클래스는 Stdio 서버를 실행하기 위한 명령어, 인수, 환경 변수를 구성하는 데 사용됩니다.
## Stdio를 통한 연결
연결 수명 주기를 관리하기 위한 두 가지 주요 접근 방식으로 Stdio 기반 MCP 서버에 연결할 수 있습니다.
### 1. 완전 관리형 연결(권장)
Python 컨텍스트 관리자(`with` 문)를 사용하는 것이 권장되는 방법입니다. 이 방식은 MCP 서버 프로세스의 시작과 컨텍스트 종료 시 자동 종료를 처리합니다.
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
from mcp import StdioServerParameters
import os
# Create a StdioServerParameters object
server_params=StdioServerParameters(
command="python3",
args=["servers/your_stdio_server.py"],
env={"UV_PYTHON": "3.12", **os.environ},
)
with MCPServerAdapter(server_params) as tools:
print(f"Available tools from Stdio MCP server: {[tool.name for tool in tools]}")
# Example: Using the tools from the Stdio MCP server in a CrewAI Agent
research_agent = Agent(
role="Local Data Processor",
goal="Process data using a local Stdio-based tool.",
backstory="An AI that leverages local scripts via MCP for specialized tasks.",
tools=tools,
reasoning=True,
verbose=True,
)
processing_task = Task(
description="Process the input data file 'data.txt' and summarize its contents.",
expected_output="A summary of the processed data.",
agent=research_agent,
markdown=True
)
data_crew = Crew(
agents=[research_agent],
tasks=[processing_task],
verbose=True,
process=Process.sequential
)
result = data_crew.kickoff()
print("\nCrew Task Result (Stdio - Managed):\n", result)
```
### 2. 수동 연결 라이프사이클
Stdio MCP 서버 프로세스가 시작되고 중지되는 시점을 더 세밀하게 제어해야 하는 경우, `MCPServerAdapter`의 라이프사이클을 수동으로 관리할 수 있습니다.
<Info>
서버 프로세스가 종료되고 자원이 해제되도록 **반드시** `mcp_server_adapter.stop()`을 호출해야 합니다. `try...finally` 블록을 사용하는 것을 강력히 추천합니다.
</Info>
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
from mcp import StdioServerParameters
import os
# Create a StdioServerParameters object
stdio_params=StdioServerParameters(
command="python3",
args=["servers/your_stdio_server.py"],
env={"UV_PYTHON": "3.12", **os.environ},
)
mcp_server_adapter = MCPServerAdapter(server_params=stdio_params)
try:
mcp_server_adapter.start() # Manually start the connection and server process
tools = mcp_server_adapter.tools
print(f"Available tools (manual Stdio): {[tool.name for tool in tools]}")
# Example: Using the tools with your Agent, Task, Crew setup
manual_agent = Agent(
role="Local Task Executor",
goal="Execute a specific local task using a manually managed Stdio tool.",
backstory="An AI proficient in controlling local processes via MCP.",
tools=tools,
verbose=True
)
manual_task = Task(
description="Execute the 'perform_analysis' command via the Stdio tool.",
expected_output="Results of the analysis.",
agent=manual_agent
)
manual_crew = Crew(
agents=[manual_agent],
tasks=[manual_task],
verbose=True,
process=Process.sequential
)
result = manual_crew.kickoff() # Actual inputs depend on your tool
print("\nCrew Task Result (Stdio - Manual):\n", result)
except Exception as e:
print(f"An error occurred during manual Stdio MCP integration: {e}")
finally:
if mcp_server_adapter and mcp_server_adapter.is_connected: # Check if connected before stopping
print("Stopping Stdio MCP server connection (manual)...")
mcp_server_adapter.stop() # **Crucial: Ensure stop is called**
elif mcp_server_adapter: # If adapter exists but not connected (e.g. start failed)
print("Stdio MCP server adapter was not connected. No stop needed or start failed.")
```
플레이스홀더 경로 및 명령어를 실제 Stdio 서버 정보로 교체해야 합니다. `StdioServerParameters`의 `env` 파라미터는
서버 프로세스용 환경 변수를 설정할 때 사용할 수 있습니다. 이는 서버의 동작을 구성하거나 필요한 경로(예: `PYTHONPATH`)를 제공하는 데 유용할 수 있습니다.

View File

@@ -0,0 +1,135 @@
---
title: 스트리머블 HTTP 전송
description: 유연한 스트리머블 HTTP 전송을 사용하여 CrewAI를 원격 MCP 서버에 연결하는 방법을 알아보세요.
icon: globe
---
## 개요
Streamable HTTP 전송은 원격 MCP 서버에 연결할 수 있는 유연한 방법을 제공합니다. 이는 종종 HTTP를 기반으로 구축되며, 요청-응답 및 스트리밍을 포함한 다양한 통신 패턴을 지원할 수 있습니다. 때때로 더 넓은 HTTP 상호작용 내에서 서버-클라이언트 스트림을 위해 Server-Sent Events(SSE)를 활용하기도 합니다.
## 주요 개념
- **원격 서버**: 원격에 호스팅된 MCP 서버용으로 설계되었습니다.
- **유연성**: 단순 SSE보다 더 복잡한 상호작용 패턴을 지원할 수 있으며, 서버가 구현한 경우 양방향 통신도 가능할 수 있습니다.
- **`MCPServerAdapter` 구성**: MCP 통신을 위한 서버의 기본 URL을 제공하고, 전송 유형으로 `"streamable-http"`를 지정해야 합니다.
## 스트리머블 HTTP를 통한 연결
Streamable HTTP MCP 서버와의 연결 라이프사이클을 관리하는 주요 방법에는 두 가지가 있습니다:
### 1. 완전히 관리되는 연결(추천)
추천되는 방법은 Python 컨텍스트 매니저(`with` 문)을 사용하는 것으로, 연결의 설정과 해제를 자동으로 처리합니다.
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
server_params = {
"url": "http://localhost:8001/mcp", # 실제 Streamable HTTP 서버 URL로 교체하세요
"transport": "streamable-http"
}
try:
with MCPServerAdapter(server_params) as tools:
print(f"Available tools from Streamable HTTP MCP server: {[tool.name for tool in tools]}")
http_agent = Agent(
role="HTTP Service Integrator",
goal="Utilize tools from a remote MCP server via Streamable HTTP.",
backstory="An AI agent adept at interacting with complex web services.",
tools=tools,
verbose=True,
)
http_task = Task(
description="Perform a complex data query using a tool from the Streamable HTTP server.",
expected_output="The result of the complex data query.",
agent=http_agent,
)
http_crew = Crew(
agents=[http_agent],
tasks=[http_task],
verbose=True,
process=Process.sequential
)
result = http_crew.kickoff()
print("\nCrew Task Result (Streamable HTTP - Managed):\n", result)
except Exception as e:
print(f"Error connecting to or using Streamable HTTP MCP server (Managed): {e}")
print("Ensure the Streamable HTTP MCP server is running and accessible at the specified URL.")
```
**참고:** `"http://localhost:8001/mcp"`은 실제 사용 중인 Streamable HTTP MCP 서버의 URL로 교체해야 합니다.
### 2. 수동 연결 라이프사이클
보다 명시적인 제어가 필요한 시나리오에서는 `MCPServerAdapter` 연결을 직접 관리할 수 있습니다.
<Info>
연결을 종료하고 리소스를 해제하려면 작업이 끝난 후 반드시 `mcp_server_adapter.stop()`을 호출하는 것이 **매우 중요**합니다. 이를 보장하는 가장 안전한 방법은 `try...finally` 블록을 사용하는 것입니다.
</Info>
```python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter
server_params = {
"url": "http://localhost:8001/mcp", # Replace with your actual Streamable HTTP server URL
"transport": "streamable-http"
}
mcp_server_adapter = None
try:
mcp_server_adapter = MCPServerAdapter(server_params)
mcp_server_adapter.start()
tools = mcp_server_adapter.tools
print(f"Available tools (manual Streamable HTTP): {[tool.name for tool in tools]}")
manual_http_agent = Agent(
role="Advanced Web Service User",
goal="Interact with an MCP server using manually managed Streamable HTTP connections.",
backstory="An AI specialist in fine-tuning HTTP-based service integrations.",
tools=tools,
verbose=True
)
data_processing_task = Task(
description="Submit data for processing and retrieve results via Streamable HTTP.",
expected_output="Processed data or confirmation.",
agent=manual_http_agent
)
data_crew = Crew(
agents=[manual_http_agent],
tasks=[data_processing_task],
verbose=True,
process=Process.sequential
)
result = data_crew.kickoff()
print("\nCrew Task Result (Streamable HTTP - Manual):\n", result)
except Exception as e:
print(f"An error occurred during manual Streamable HTTP MCP integration: {e}")
print("Ensure the Streamable HTTP MCP server is running and accessible.")
finally:
if mcp_server_adapter and mcp_server_adapter.is_connected:
print("Stopping Streamable HTTP MCP server connection (manual)...")
mcp_server_adapter.stop() # **Crucial: Ensure stop is called**
elif mcp_server_adapter:
print("Streamable HTTP MCP server adapter was not connected. No stop needed or start failed.")
```
## 보안 고려사항
Streamable HTTP 전송을 사용할 때는 일반적인 웹 보안 모범 사례가 매우 중요합니다:
- **HTTPS 사용**: 데이터 전송을 암호화하기 위해 항상 MCP 서버 URL에 HTTPS(HTTP Secure)를 사용하는 것이 좋습니다.
- **인증**: MCP 서버가 민감한 도구나 데이터를 노출하는 경우 강력한 인증 메커니즘을 구현하세요.
- **입력 검증**: MCP 서버가 모든 수신 요청과 매개변수를 반드시 검증하도록 하십시오.
MCP 통합 보안에 대한 종합적인 안내는 [보안 고려사항](./security.mdx) 페이지와 공식 [MCP 전송 보안 문서](https://modelcontextprotocol.io/docs/concepts/transports#security-considerations)를 참고하시기 바랍니다.

View File

@@ -0,0 +1,124 @@
---
title: AgentOps 통합
description: AgentOps를 사용하여 에이전트 성능을 이해하고 로깅하기
icon: paperclip
---
# 소개
Observability는 대화형 AI 에이전트를 개발하고 배포하는 데 있어 핵심적인 요소입니다. 이는 개발자가 에이전트의 성능을 이해하고, 에이전트가 사용자와 어떻게 상호작용하는지, 그리고 에이전트가 외부 도구와 API를 어떻게 사용하는지를 파악할 수 있게 해줍니다.
AgentOps는 CrewAI와 독립적인 제품으로, 에이전트를 위한 종합적인 observability 솔루션을 제공합니다.
## AgentOps
[AgentOps](https://agentops.ai/?=crew)은 에이전트에 대한 세션 리플레이, 메트릭, 모니터링을 제공합니다.
AgentOps는 높은 수준에서 비용, 토큰 사용량, 대기 시간, 에이전트 실패, 세션 전체 통계 등 다양한 항목을 모니터링할 수 있는 기능을 제공합니다.
더 자세한 내용은 [AgentOps Repo](https://github.com/AgentOps-AI/agentops)를 확인하세요.
### 개요
AgentOps는 개발 및 프로덕션 환경에서 에이전트에 대한 모니터링을 제공합니다.
에이전트 성능, 세션 리플레이, 맞춤형 리포팅을 추적할 수 있는 대시보드를 제공합니다.
또한, AgentOps는 Crew 에이전트 상호작용, LLM 호출, 툴 사용을 실시간으로 볼 수 있는 세션 드릴다운 기능을 제공합니다.
이 기능은 에이전트가 사용자 및 다른 에이전트와 어떻게 상호작용하는지 디버깅하고 이해하는 데 유용합니다.
![선택된 에이전트 세션 실행 시리즈의 개요](/images/agentops-overview.png)
![에이전트 실행을 조사하기 위한 세션 드릴다운 개요](/images/agentops-session.png)
![단계별 에이전트 리플레이 실행 그래프 보기](/images/agentops-replay.png)
### 특징
- **LLM 비용 관리 및 추적**: 기반 모델 공급자와의 지출을 추적합니다.
- **재생 분석**: 단계별 에이전트 실행 그래프를 시청할 수 있습니다.
- **재귀적 사고 감지**: 에이전트가 무한 루프에 빠졌는지 식별합니다.
- **맞춤형 보고서**: 에이전트 성능에 대한 맞춤형 분석을 생성합니다.
- **분석 대시보드**: 개발 및 운영 중인 에이전트에 대한 상위 수준 통계를 모니터링합니다.
- **공개 모델 테스트**: 벤치마크 및 리더보드를 통해 에이전트를 테스트할 수 있습니다.
- **맞춤형 테스트**: 도메인별 테스트로 에이전트를 실행합니다.
- **타임 트래블 디버깅**: 체크포인트에서 세션을 재시작합니다.
- **컴플라이언스 및 보안**: 감사 로그를 생성하고 욕설 및 PII 유출과 같은 잠재적 위협을 감지합니다.
- **프롬프트 인젝션 감지**: 잠재적 코드 인젝션 및 시크릿 유출을 식별합니다.
### AgentOps 사용하기
<Steps>
<Step title="API 키 생성">
사용자 API 키를 여기서 생성하세요: [API 키 생성](https://app.agentops.ai/account)
</Step>
<Step title="환경 설정">
API 키를 환경 변수에 추가하세요:
```bash
AGENTOPS_API_KEY=<YOUR_AGENTOPS_API_KEY>
```
</Step>
<Step title="AgentOps 설치">
다음 명령어로 AgentOps를 설치하세요:
```bash
pip install 'crewai[agentops]'
```
또는
```bash
pip install agentops
```
</Step>
<Step title="AgentOps 초기화">
스크립트에서 `Crew`를 사용하기 전에 다음 코드를 포함하세요:
```python
import agentops
agentops.init()
```
이렇게 하면 AgentOps 세션이 시작되고 Crew 에이전트가 자동으로 추적됩니다. 더 복잡한 agentic 시스템을 구성하는 방법에 대한 자세한 정보는 [AgentOps 문서](https://docs.agentops.ai) 또는 [Discord](https://discord.gg/j4f3KbeH)를 참조하세요.
</Step>
</Steps>
### Crew + AgentOps 예시
<CardGroup cols={3}>
<Card
title="Job Posting"
color="#F3A78B"
href="https://github.com/joaomdmoura/crewAI-examples/tree/main/job-posting"
icon="briefcase"
iconType="solid"
>
채용 공고를 생성하는 Crew agent의 예시입니다.
</Card>
<Card
title="Markdown Validator"
color="#F3A78B"
href="https://github.com/joaomdmoura/crewAI-examples/tree/main/markdown_validator"
icon="markdown"
iconType="solid"
>
Markdown 파일을 검증하는 Crew agent의 예시입니다.
</Card>
<Card
title="Instagram Post"
color="#F3A78B"
href="https://github.com/joaomdmoura/crewAI-examples/tree/main/instagram_post"
icon="square-instagram"
iconType="brands"
>
Instagram 게시물을 생성하는 Crew agent의 예시입니다.
</Card>
</CardGroup>
### 추가 정보
시작하려면 [AgentOps 계정](https://agentops.ai/?=crew)을 생성하세요.
기능 요청이나 버그 보고가 필요하시면 [AgentOps Repo](https://github.com/AgentOps-AI/agentops)에서 AgentOps 팀에 문의해 주세요.
#### 추가 링크
<a href="https://twitter.com/agentopsai/">🐦 트위터</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://discord.gg/JHPt4C7r">📢 디스코드</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://app.agentops.ai/?=crew">🖇️ AgentOps 대시보드</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://docs.agentops.ai/introduction">📙 문서화</a>

View File

@@ -0,0 +1,149 @@
---
title: Arize Phoenix
description: OpenTelemetry 및 OpenInference가 포함된 CrewAI용 Arize Phoenix 통합
icon: magnifying-glass-chart
---
# Arize Phoenix 통합
이 가이드는 [OpenInference](https://github.com/openinference/openinference) SDK를 통해 OpenTelemetry를 사용하여 **Arize Phoenix**를 **CrewAI**와 통합하는 방법을 보여줍니다. 이 가이드를 완료하면 CrewAI agent를 추적하고 agent를 쉽게 디버그할 수 있습니다.
> **Arize Phoenix란?** [Arize Phoenix](https://phoenix.arize.com)는 AI 애플리케이션을 위한 추적 및 평가 기능을 제공하는 LLM 가시성(observability) 플랫폼입니다.
[![Phoenix와의 통합 영상 데모 보기](https://storage.googleapis.com/arize-assets/fixtures/setup_crewai.png)](https://www.youtube.com/watch?v=Yc5q3l6F7Ww)
## 시작하기
CrewAI를 사용하고 OpenInference를 통해 OpenTelemetry와 Arize Phoenix를 연동하는 간단한 예제를 단계별로 안내합니다.
이 가이드는 [Google Colab](https://colab.research.google.com/github/Arize-ai/phoenix/blob/main/tutorials/tracing/crewai_tracing_tutorial.ipynb)에서도 확인하실 수 있습니다.
### 1단계: 의존성 설치
```bash
pip install openinference-instrumentation-crewai crewai crewai-tools arize-phoenix-otel
```
### 2단계: 환경 변수 설정
Phoenix Cloud API 키를 설정하고 OpenTelemetry를 구성하여 추적 정보를 Phoenix로 전송합니다. Phoenix Cloud는 Arize Phoenix의 호스팅 버전이지만, 이 통합을 사용하는 데 필수는 아닙니다.
무료 Serper API 키는 [여기](https://serper.dev/)에서 받을 수 있습니다.
```python
import os
from getpass import getpass
# Get your Phoenix Cloud credentials
PHOENIX_API_KEY = getpass("🔑 Enter your Phoenix Cloud API Key: ")
# Get API keys for services
OPENAI_API_KEY = getpass("🔑 Enter your OpenAI API key: ")
SERPER_API_KEY = getpass("🔑 Enter your Serper API key: ")
# Set environment variables
os.environ["PHOENIX_CLIENT_HEADERS"] = f"api_key={PHOENIX_API_KEY}"
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "https://app.phoenix.arize.com" # Phoenix Cloud, change this to your own endpoint if you are using a self-hosted instance
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
os.environ["SERPER_API_KEY"] = SERPER_API_KEY
```
### 3단계: Phoenix와 함께 OpenTelemetry 초기화하기
OpenInference OpenTelemetry 계측 SDK를 초기화하여 트레이스를 수집하고 Phoenix로 전송합니다.
```python
from phoenix.otel import register
tracer_provider = register(
project_name="crewai-tracing-demo",
auto_instrument=True,
)
```
### 4단계: CrewAI 애플리케이션 생성하기
두 명의 에이전트가 협력하여 AI 발전에 관한 블로그 글을 조사하고 작성하는 CrewAI 애플리케이션을 만들어 보겠습니다.
```python
from crewai import Agent, Crew, Process, Task
from crewai_tools import SerperDevTool
from openinference.instrumentation.crewai import CrewAIInstrumentor
from phoenix.otel import register
# crew에 대한 모니터링 설정
tracer_provider = register(
endpoint="http://localhost:6006/v1/traces")
CrewAIInstrumentor().instrument(skip_dep_check=True, tracer_provider=tracer_provider)
search_tool = SerperDevTool()
# 역할과 목표가 설정된 에이전트 정의
researcher = Agent(
role="Senior Research Analyst",
goal="AI 및 데이터 과학의 최첨단 발전 사항 발견",
backstory="""당신은 최고 수준의 기술 싱크탱크에서 근무합니다.
새로운 트렌드를 식별하는 데 전문성이 있습니다.
복잡한 데이터를 분석하고 실행 가능한 인사이트로 제시하는 데 뛰어납니다.""",
verbose=True,
allow_delegation=False,
# 원하는 모델을 지정할 수 있는 optional llm 속성을 전달할 수 있습니다.
# llm=ChatOpenAI(model_name="gpt-3.5", temperature=0.7),
tools=[search_tool],
)
writer = Agent(
role="Tech Content Strategist",
goal="기술 발전에 대한 매력적인 콘텐츠 작성",
backstory="""당신은 통찰력 있고 흥미로운 기사로 유명한 콘텐츠 전략가입니다.
복잡한 개념을 매력적인 스토리로 전환합니다.""",
verbose=True,
allow_delegation=True,
)
# 에이전트를 위한 task 생성
task1 = Task(
description="""2024년 AI 분야의 최신 발전 상황에 대한 포괄적인 분석을 수행하세요.
주요 트렌드, 획기적 기술, 산업에 미칠 잠재적 영향을 식별하세요.""",
expected_output="주요 내용을 불릿 포인트로 정리한 전체 분석 보고서",
agent=researcher,
)
task2 = Task(
description="""제공된 인사이트를 활용하여
가장 중요한 AI 발전 내용을 강조하는 흥미로운 블로그 글을 작성하세요.
글은 정보성 있고, 기술에 밝은 독자를 대상으로 하면서 읽기 쉽게 써야 합니다.
멋지게 들리도록 쓰되, 복잡한 단어는 피하여 AI처럼 들리지 않게 하세요.""",
expected_output="최소 4개의 단락으로 구성된 전체 블로그 글",
agent=writer,
)
# 순차 프로세스 방식으로 crew 인스턴스화
crew = Crew(
agents=[researcher, writer], tasks=[task1, task2], verbose=1, process=Process.sequential
)
# crew에게 작업 시작 지시!
result = crew.kickoff()
print("######################")
print(result)
```
### 5단계: Phoenix에서 트레이스 보기
에이전트를 실행한 후, Phoenix에서 CrewAI 애플리케이션에 의해 생성된 트레이스를 볼 수 있습니다. 에이전트 상호작용과 LLM 호출의 상세한 단계가 표시되어 AI 에이전트를 디버깅하고 최적화하는 데 도움이 됩니다.
Phoenix Cloud 계정에 로그인한 다음 `project_name` 파라미터에서 지정한 프로젝트로 이동하세요. 모든 에이전트 상호작용, 도구 사용 및 LLM 호출이 포함된 트레이스의 타임라인 보기를 확인할 수 있습니다.
![Phoenix에서 에이전트 상호작용을 보여주는 예시 트레이스](https://storage.googleapis.com/arize-assets/fixtures/crewai_traces.png)
### 버전 호환성 정보
- Python 3.8+
- CrewAI >= 0.86.0
- Arize Phoenix >= 7.0.1
- OpenTelemetry SDK >= 1.31.0
### 참고 자료
- [Phoenix 문서](https://docs.arize.com/phoenix/) - Phoenix 플랫폼 개요.
- [CrewAI 문서](https://docs.crewai.com/) - CrewAI 프레임워크 개요.
- [OpenTelemetry 문서](https://opentelemetry.io/docs/) - OpenTelemetry 가이드
- [OpenInference GitHub](https://github.com/openinference/openinference) - OpenInference SDK 소스 코드.

View File

@@ -0,0 +1,284 @@
---
title: LangDB 통합
description: LangDB AI Gateway로 CrewAI 워크플로우를 관리, 보안, 최적화하세요—350개 이상의 모델 액세스, 자동 라우팅, 비용 최적화, 완전한 가시성을 제공합니다.
icon: database
---
# 소개
[LangDB AI Gateway](https://langdb.ai)는 여러 대형 언어 모델과의 연결을 지원하는 OpenAI 호환 API를 제공하며, 350개 이상의 언어 모델에 접근할 수 있도록 해주는 관측 플랫폼입니다. 단 한 번의 `init()` 호출로 모든 에이전트 상호작용, 작업 실행 및 LLM 호출이 캡처되어, 애플리케이션을 위한 종합적인 관측성과 프로덕션 수준의 AI 인프라를 제공합니다.
<Frame caption="LangDB CrewAI 추적 예시">
<img src="/images/langdb-1.png" alt="LangDB CrewAI trace example" />
</Frame>
**확인:** [실시간 추적 예시 보기](https://app.langdb.ai/sharing/threads/3becbfed-a1be-ae84-ea3c-4942867a3e22)
## 기능
### AI 게이트웨이 기능
- **350개 이상의 LLM 접근**: 단일 통합을 통해 모든 주요 언어 모델에 연결
- **가상 모델**: 특정 매개변수와 라우팅 규칙으로 맞춤형 모델 구성 생성
- **가상 MCP**: 에이전트 간 향상된 통신을 위해 MCP(Model Context Protocol) 시스템과의 호환성 및 통합 지원
- **가드레일**: 에이전트 행동에 대한 안전 조치 및 컴플라이언스 제어 구현
### 가시성 및 추적
- **자동 추적**: 단일 `init()` 호출로 모든 CrewAI 상호작용을 캡처
- **엔드-투-엔드 가시성**: 에이전트 워크플로우를 시작부터 끝까지 모니터링
- **도구 사용 추적**: 에이전트가 사용하는 도구와 그 결과를 추적
- **모델 호출 모니터링**: LLM 상호작용에 대한 상세한 인사이트 제공
- **성능 분석**: 지연 시간, 토큰 사용량 및 비용 모니터링
- **디버깅 지원**: 문제 해결을 위한 단계별 실행
- **실시간 모니터링**: 라이브 트레이스 및 메트릭 대시보드
## 설치 안내
<Steps>
<Step title="LangDB 설치">
CrewAI 기능 플래그와 함께 LangDB 클라이언트를 설치하세요:
```bash
pip install 'pylangdb[crewai]'
```
</Step>
<Step title="환경 변수 설정">
LangDB 자격 증명을 구성하세요:
```bash
export LANGDB_API_KEY="<your_langdb_api_key>"
export LANGDB_PROJECT_ID="<your_langdb_project_id>"
export LANGDB_API_BASE_URL='https://api.us-east-1.langdb.ai'
```
</Step>
<Step title="추적(Tracing) 초기화">
CrewAI 코드를 설정하기 전에 LangDB를 임포트하고 초기화하세요:
```python
from pylangdb.crewai import init
# Initialize LangDB
init()
```
</Step>
<Step title="CrewAI와 LangDB 연동 설정">
LangDB 헤더와 함께 LLM을 설정하세요:
```python
from crewai import Agent, Task, Crew, LLM
import os
# Configure LLM with LangDB headers
llm = LLM(
model="openai/gpt-4o", # Replace with the model you want to use
api_key=os.getenv("LANGDB_API_KEY"),
base_url=os.getenv("LANGDB_API_BASE_URL"),
extra_headers={"x-project-id": os.getenv("LANGDB_PROJECT_ID")}
)
```
</Step>
</Steps>
## 빠른 시작 예제
여기 LangDB와 CrewAI를 시작하는 간단한 예제가 있습니다:
```python
import os
from pylangdb.crewai import init
from crewai import Agent, Task, Crew, LLM
# Initialize LangDB before any CrewAI imports
init()
def create_llm(model):
return LLM(
model=model,
api_key=os.environ.get("LANGDB_API_KEY"),
base_url=os.environ.get("LANGDB_API_BASE_URL"),
extra_headers={"x-project-id": os.environ.get("LANGDB_PROJECT_ID")}
)
# Define your agent
researcher = Agent(
role="Research Specialist",
goal="Research topics thoroughly",
backstory="Expert researcher with skills in finding information",
llm=create_llm("openai/gpt-4o"), # Replace with the model you want to use
verbose=True
)
# Create a task
task = Task(
description="Research the given topic and provide a comprehensive summary",
agent=researcher,
expected_output="Detailed research summary with key findings"
)
# Create and run the crew
crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
print(result)
```
## 완성된 예제: Research and Planning Agent
이 포괄적인 예제는 연구 및 기획 기능을 갖춘 multi-agent 워크플로우를 보여줍니다.
### 사전 준비 사항
```bash
pip install crewai 'pylangdb[crewai]' crewai_tools setuptools python-dotenv
```
### 환경 설정
```bash
# LangDB credentials
export LANGDB_API_KEY="<your_langdb_api_key>"
export LANGDB_PROJECT_ID="<your_langdb_project_id>"
export LANGDB_API_BASE_URL='https://api.us-east-1.langdb.ai'
# Additional API keys (optional)
export SERPER_API_KEY="<your_serper_api_key>" # For web search capabilities
```
### 전체 구현
```python
#!/usr/bin/env python3
import os
import sys
from pylangdb.crewai import init
init() # Initialize LangDB before any CrewAI imports
from dotenv import load_dotenv
from crewai import Agent, Task, Crew, Process, LLM
from crewai_tools import SerperDevTool
load_dotenv()
def create_llm(model):
return LLM(
model=model,
api_key=os.environ.get("LANGDB_API_KEY"),
base_url=os.environ.get("LANGDB_API_BASE_URL"),
extra_headers={"x-project-id": os.environ.get("LANGDB_PROJECT_ID")}
)
class ResearchPlanningCrew:
def researcher(self) -> Agent:
return Agent(
role="Research Specialist",
goal="Research topics thoroughly and compile comprehensive information",
backstory="Expert researcher with skills in finding and analyzing information from various sources",
tools=[SerperDevTool()],
llm=create_llm("openai/gpt-4o"),
verbose=True
)
def planner(self) -> Agent:
return Agent(
role="Strategic Planner",
goal="Create actionable plans based on research findings",
backstory="Strategic planner who breaks down complex challenges into executable plans",
reasoning=True,
max_reasoning_attempts=3,
llm=create_llm("openai/anthropic/claude-3.7-sonnet"),
verbose=True
)
def research_task(self) -> Task:
return Task(
description="Research the topic thoroughly and compile comprehensive information",
agent=self.researcher(),
expected_output="Comprehensive research report with key findings and insights"
)
def planning_task(self) -> Task:
return Task(
description="Create a strategic plan based on the research findings",
agent=self.planner(),
expected_output="Strategic execution plan with phases, goals, and actionable steps",
context=[self.research_task()]
)
def crew(self) -> Crew:
return Crew(
agents=[self.researcher(), self.planner()],
tasks=[self.research_task(), self.planning_task()],
verbose=True,
process=Process.sequential
)
def main():
topic = sys.argv[1] if len(sys.argv) > 1 else "Artificial Intelligence in Healthcare"
crew_instance = ResearchPlanningCrew()
# Update task descriptions with the specific topic
crew_instance.research_task().description = f"Research {topic} thoroughly and compile comprehensive information"
crew_instance.planning_task().description = f"Create a strategic plan for {topic} based on the research findings"
result = crew_instance.crew().kickoff()
print(result)
if __name__ == "__main__":
main()
```
### 예제 실행하기
```bash
python main.py "Sustainable Energy Solutions"
```
## LangDB에서 트레이스 보기
CrewAI 애플리케이션을 실행한 후, LangDB 대시보드에서 자세한 트레이스를 확인할 수 있습니다:
<Frame caption="LangDB 트레이스 대시보드">
<img src="/images/langdb-2.png" alt="LangDB 트레이스 대시보드에서 CrewAI 워크플로우 표시" />
</Frame>
### 볼 수 있는 내용
- **에이전트 상호작용**: 에이전트 대화 및 작업 인계의 전체 흐름
- **도구 사용**: 호출된 도구, 입력값 및 출력값
- **모델 호출**: 프롬프트 및 응답과 함께하는 상세 LLM 상호작용
- **성능 지표**: 지연 시간, 토큰 사용량, 비용 추적
- **실행 타임라인**: 전체 워크플로우의 단계별 보기
## 문제 해결
### 일반적인 문제
- **추적이 나타나지 않음**: `init()`이 CrewAI 임포트 이전에 호출되었는지 확인하세요
- **인증 오류**: LangDB API 키와 프로젝트 ID를 확인하세요
## 리소스
<CardGroup cols={3}>
<Card title="LangDB 문서" icon="book" href="https://docs.langdb.ai">
공식 LangDB 문서 및 가이드
</Card>
<Card title="LangDB 가이드" icon="graduation-cap" href="https://docs.langdb.ai/guides">
AI 에이전트 구축을 위한 단계별 튜토리얼
</Card>
<Card title="GitHub 예제" icon="github" href="https://github.com/langdb/langdb-samples/tree/main/examples/crewai" >
CrewAI 통합 전체 예제
</Card>
<Card title="LangDB 대시보드" icon="chart-line" href="https://app.langdb.ai">
트레이스 및 분석 액세스
</Card>
<Card title="모델 카탈로그" icon="list" href="https://app.langdb.ai/models">
350개 이상의 사용 가능한 언어 모델 살펴보기
</Card>
<Card title="엔터프라이즈 기능" icon="building" href="https://docs.langdb.ai/enterprise">
셀프 호스팅 옵션 및 엔터프라이즈 기능
</Card>
</CardGroup>
## 다음 단계
이 가이드에서는 LangDB AI Gateway를 CrewAI와 통합하는 기본 사항을 다루었습니다. AI 워크플로우를 더욱 강화하려면 다음을 탐색해보세요:
- **Virtual Models**: 라우팅 전략을 사용한 맞춤형 모델 구성 만들기
- **Guardrails & Safety**: 콘텐츠 필터링 및 컴플라이언스 제어 구현
- **Production Deployment**: 폴백, 재시도, 로드 밸런싱 구성
보다 고급 기능 및 사용 사례에 대해서는 [LangDB Documentation](https://docs.langdb.ai)을 방문하거나, [Model Catalog](https://app.langdb.ai/models)를 탐색하여 사용 가능한 모든 모델을 확인해 보세요.

View File

@@ -0,0 +1,109 @@
---
title: Langfuse 통합
description: OpenLit을 사용하여 OpenTelemetry를 통해 CrewAI와 Langfuse를 통합하는 방법을 알아보세요
icon: vials
---
# Langfuse와 CrewAI 통합하기
이 노트북은 **OpenLit** SDK를 통해 OpenTelemetry를 사용하여 **Langfuse**를 **CrewAI**와 통합하는 방법을 보여줍니다. 이 노트북을 마치면 Langfuse를 사용해 CrewAI 애플리케이션을 추적하여 가시성과 디버깅을 향상시킬 수 있습니다.
> **Langfuse란 무엇인가요?** [Langfuse](https://langfuse.com)는 오픈 소스 LLM 엔지니어링 플랫폼입니다. 이는 LLM 애플리케이션을 위한 추적 및 모니터링 기능을 제공하며, 개발자들이 AI 시스템을 디버그, 분석 및 최적화하는 데 도움을 줍니다. Langfuse는 네이티브 통합, OpenTelemetry, API/SDK를 통해 다양한 도구 및 프레임워크와 연동됩니다.
[![Langfuse Overview Video](https://github.com/user-attachments/assets/3926b288-ff61-4b95-8aa1-45d041c70866)](https://langfuse.com/watch-demo)
## 시작하기
CrewAI를 사용하고 OpenLit을 통해 OpenTelemetry로 Langfuse와 통합하는 간단한 예제를 함께 살펴보겠습니다.
### 1단계: 의존성 설치
```python
%pip install langfuse openlit crewai crewai_tools
```
### 2단계: 환경 변수 설정
Langfuse API 키를 설정하고 OpenTelemetry 내보내기 설정을 구성하여 trace를 Langfuse로 전송합니다. Langfuse OpenTelemetry 엔드포인트 `/api/public/otel` 및 인증과 관련된 자세한 내용은 [Langfuse OpenTelemetry 문서](https://langfuse.com/docs/opentelemetry/get-started)를 참고하십시오.
```python
import os
# 프로젝트에 대한 키를 프로젝트 설정 페이지에서 확인하세요: https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..."
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..."
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU 지역
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US 지역
# OpenAI 키
os.environ["OPENAI_API_KEY"] = "sk-proj-..."
```
환경 변수를 설정하면 이제 Langfuse 클라이언트를 초기화할 수 있습니다. get_client()는 환경 변수에 제공된 자격 증명을 사용하여 Langfuse 클라이언트를 초기화합니다.
```python
from langfuse import get_client
langfuse = get_client()
# 연결 확인
if langfuse.auth_check():
print("Langfuse 클라이언트가 인증되었으며 준비되었습니다!")
else:
print("인증에 실패했습니다. 자격 증명과 호스트를 확인하세요.")
```
### 3단계: OpenLit 초기화
OpenLit OpenTelemetry 계측 SDK를 초기화하여 OpenTelemetry 추적을 수집하기 시작합니다.
```python
import openlit
openlit.init()
```
### 4단계: 간단한 CrewAI 애플리케이션 만들기
여러 에이전트가 협력하여 사용자의 질문에 답하는 간단한 CrewAI 애플리케이션을 만들어보겠습니다.
```python
from crewai import Agent, Task, Crew
from crewai_tools import (
WebsiteSearchTool
)
web_rag_tool = WebsiteSearchTool()
writer = Agent(
role="Writer",
goal="You make math engaging and understandable for young children through poetry",
backstory="You're an expert in writing haikus but you know nothing of math.",
tools=[web_rag_tool],
)
task = Task(description=("What is {multiplication}?"),
expected_output=("Compose a haiku that includes the answer."),
agent=writer)
crew = Crew(
agents=[writer],
tasks=[task],
share_crew=False
)
```
### 5단계: Langfuse에서 트레이스 확인하기
에이전트를 실행한 후 [Langfuse](https://cloud.langfuse.com)에서 CrewAI 애플리케이션에서 생성된 트레이스를 확인할 수 있습니다. 여기서 LLM 상호작용의 자세한 단계들을 볼 수 있으며, 이를 통해 AI 에이전트의 디버깅 및 최적화에 도움이 됩니다.
![Langfuse의 CrewAI 예시 트레이스](https://langfuse.com/images/cookbook/integration_crewai/crewai-example-trace.png)
_[Langfuse의 공개 예시 트레이스](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/e2cf380ffc8d47d28da98f136140642b?timestamp=2025-02-05T15%3A12%3A02.717Z&observation=3b32338ee6a5d9af)_
## 참고 자료
- [Langfuse OpenTelemetry 문서](https://langfuse.com/docs/opentelemetry/get-started)

View File

@@ -0,0 +1,72 @@
---
title: Langtrace 연동
description: 외부 가시성 도구인 Langtrace를 사용하여 CrewAI 에이전트의 비용, 지연 시간 및 성능을 모니터링하는 방법.
icon: chart-line
---
# Langtrace 개요
Langtrace는 대형 언어 모델(LLM), LLM 프레임워크, 벡터 데이터베이스에 대한 관측 가능성과 평가를 설정할 수 있도록 도와주는 오픈소스 외부 도구입니다.
Langtrace는 CrewAI에 직접 내장되어 있지는 않지만, CrewAI와 함께 사용하여 CrewAI 에이전트의 비용, 지연 시간, 성능에 대해 깊이 있는 가시성을 확보할 수 있습니다.
이 통합을 통해 하이퍼파라미터를 기록하고, 성능 회귀를 모니터링하며, 에이전트의 지속적인 개선을 위한 프로세스를 수립할 수 있습니다.
![에이전트 세션 실행 시리즈 개요](/images/langtrace1.png)
![에이전트 트레이스 개요](/images/langtrace2.png)
![상세한 llm 트레이스 개요](/images/langtrace3.png)
## 설정 지침
<Steps>
<Step title="Langtrace에 가입하기">
[https://langtrace.ai/signup](https://langtrace.ai/signup)에서 가입하세요.
</Step>
<Step title="프로젝트 생성">
프로젝트 유형을 `CrewAI`로 설정하고 API 키를 생성하세요.
</Step>
<Step title="CrewAI 프로젝트에 Langtrace 설치하기">
다음 명령어를 사용하세요:
```bash
pip install langtrace-python-sdk
```
</Step>
<Step title="Langtrace 임포트하기">
스크립트의 시작 부분, CrewAI를 임포트하기 전에 Langtrace를 임포트하고 초기화하세요:
```python
from langtrace_python_sdk import langtrace
langtrace.init(api_key='<LANGTRACE_API_KEY>')
# 이제 CrewAI 모듈을 임포트하세요
from crewai import Agent, Task, Crew
```
</Step>
</Steps>
### 기능 및 CrewAI에의 적용
1. **LLM 토큰 및 비용 추적**
- 각 CrewAI 에이전트 상호작용에 대한 토큰 사용량과 관련 비용을 모니터링합니다.
2. **실행 단계에 대한 추적 그래프**
- CrewAI 작업의 실행 흐름을 시각화하며, 지연 시간과 로그를 포함합니다.
- 에이전트 워크플로우의 병목 지점을 파악하는 데 유용합니다.
3. **수동 주석을 통한 데이터셋 큐레이션**
- 미래의 학습 또는 평가를 위해 CrewAI 작업 출력으로부터 데이터셋을 생성합니다.
4. **프롬프트 버전 관리 및 관리**
- CrewAI 에이전트에서 사용된 다양한 프롬프트 버전을 추적합니다.
- A/B 테스트 및 에이전트 성능 최적화에 유용합니다.
5. **프롬프트 플레이그라운드 및 모델 비교**
- 배포 전에 CrewAI 에이전트에 사용할 다양한 프롬프트와 모델을 테스트 및 비교합니다.
6. **테스트 및 평가**
- CrewAI 에이전트 및 작업에 대한 자동화된 테스트를 설정합니다.

View File

@@ -0,0 +1,226 @@
---
title: "Maxim Integration"
description: "에이전트 모니터링, 평가 및 가시성 시작"
icon: "infinity"
---
# Maxim 개요
Maxim AI는 귀하의 CrewAI 애플리케이션을 위한 포괄적인 에이전트 모니터링, 평가 및 가시성을 제공합니다. Maxim의 원라인 통합을 통해 에이전트 상호작용, 성능 지표 등을 손쉽게 추적하고 분석할 수 있습니다.
## 특징
### 프롬프트 관리
Maxim의 프롬프트 관리 기능을 통해 CrewAI 에이전트를 위한 프롬프트를 생성, 조직, 최적화할 수 있습니다. 지침을 하드코딩하는 대신, Maxim의 SDK를 활용하여 버전 관리가 되는 프롬프트를 동적으로 가져오고 적용하세요.
<Tabs>
<Tab title="프롬프트 플레이그라운드">
플레이그라운드를 통해 프롬프트를 생성, 정제, 실험 및 배포할 수 있습니다. 폴더와 버전을 활용하여 프롬프트를 정리하고, 도구 및 컨텍스트를 연결하여 실제 사례로 실험해 보며, 맞춤형 로직을 기반으로 배포할 수 있습니다.
[**모델 구성**](https://www.getmaxim.ai/docs/introduction/quickstart/setting-up-workspace#add-model-api-keys)을 통해 여러 모델을 손쉽게 실험하고, 프롬프트 플레이그라운드 상단 드롭다운에서 원하는 모델을 선택하세요.
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/maxim_playground.png'> </img>
</Tab>
<Tab title="프롬프트 버전">
팀이 AI 애플리케이션을 개발할 때, 실험의 중요한 부분은 프롬프트 구조를 반복적으로 개선하는 것입니다. 효과적으로 협업하고 변경 사항을 명확히 정리할 수 있도록 Maxim은 프롬프트 버전 관리와 버전 간 비교 실행을 지원합니다.
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/maxim_versions.png'> </img>
</Tab>
<Tab title="프롬프트 비교">
AI 애플리케이션을 발전시켜 나가면서 프롬프트를 반복 개선하기 위해서는 모델, 프롬프트 구조 등 다양한 요소로 실험이 필요합니다. 버전 간 비교 및 변화에 대한 정보에 기반한 결정을 위해, 비교 플레이그라운드는 결과를 나란히 볼 수 있게 해줍니다.
## **프롬프트 비교를 왜 사용해야 하나요?**
프롬프트 비교는 여러 개의 단일 프롬프트를 하나의 뷰에서 볼 수 있도록 하여 다양한 워크플로에 streamlined 접근을 제공합니다:
1. **모델 비교**: 동일한 프롬프트에서 서로 다른 모델의 성능을 평가합니다.
2. **프롬프트 최적화**: 여러 버전의 프롬프트를 비교하여 가장 효과적인 구성을 식별합니다.
3. **교차 모델 일관성**: 동일한 프롬프트에 대해 여러 모델에서 일관된 출력을 보장합니다.
4. **성능 벤치마킹**: 다양한 모델과 프롬프트에 대해 지연 시간, 비용, 토큰 수 등의 지표를 분석합니다.
</Tab>
</Tabs>
### 관찰 가능성 & 평가
Maxim AI는 CrewAI 에이전트에 대한 포괄적인 관찰 가능성과 평가 기능을 제공하여, 각 실행 과정에서 무슨 일이 일어나고 있는지 정확히 파악할 수 있도록 지원합니다.
<Tabs>
<Tab title="Agent Tracing">
에이전트의 전체 라이프사이클(도구 호출, 에이전트 궤적, 결정 플로우 등)을 손쉽게 추적할 수 있습니다.
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/maxim_agent_tracking.png'> </img>
</Tab>
<Tab title="Analytics + Evals">
전체 트레이스 또는 개별 노드에 대해 상세 평가를 실행할 수 있으며, 다음 기능을 지원합니다:
- 다중 단계 상호작용 및 세분화된 트레이스 분석
- 세션 수준 평가
- 실제 환경 시뮬레이션 테스트
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/maxim_trace_eval.png'> </img>
<CardGroup cols={3}>
<Card title="로그 자동 평가" icon="e" href="https://www.getmaxim.ai/docs/observe/how-to/evaluate-logs/auto-evaluation">
<p>
필터 및 샘플링을 기준으로 UI에서 캡처된 로그를 자동으로 평가할 수 있습니다.
</p>
</Card>
<Card title="로그 수동 평가" icon="hand" href="https://www.getmaxim.ai/docs/observe/how-to/evaluate-logs/human-evaluation">
<p>
로그의 품질을 평가하고, 사람의 평가 또는 등급을 이용해 로그를 검토할 수 있습니다.
</p>
</Card>
<Card title="노드 수준 평가" icon="road" href="https://www.getmaxim.ai/docs/observe/how-to/evaluate-logs/node-level-evaluation">
<p>
트레이스 또는 로그의 모든 컴포넌트를 평가하여 에이전트의 행동에 대한 통찰을 얻을 수 있습니다.
</p>
</Card>
</CardGroup>
---
</Tab>
<Tab title="Alerting">
**오류**, **비용, 토큰 사용량, 사용자 피드백, 지연 시간**에 임계값을 설정하고, Slack 또는 PagerDuty를 통해 실시간 알림을 받아보세요.
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/maxim_alerts_1.png'> </img>
</Tab>
<Tab title="Dashboards">
시간 경과에 따른 트레이스, 사용량 측정지표, 지연 시간 및 오류율을 손쉽게 시각화할 수 있습니다.
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/maxim_dashboard_1.png'> </img>
</Tab>
</Tabs>
## 시작하기
### 사전 준비 사항
- Python 버전 \>=3.10
- Maxim 계정 ([여기에서 가입](https://getmaxim.ai/))
- Maxim API 키 생성
- CrewAI 프로젝트
### 설치
Maxim SDK를 pip을 통해 설치하세요:
```python
pip install maxim-py
```
또는 `requirements.txt`에 추가하세요:
```
maxim-py
```
### 기본 설정
### 1. 환경 변수 설정
```python
### Environment Variables Setup
# Create a `.env` file in your project root:
# Maxim API Configuration
MAXIM_API_KEY=your_api_key_here
MAXIM_LOG_REPO_ID=your_repo_id_here
```
### 2. 필수 패키지 임포트하기
```python
from crewai import Agent, Task, Crew, Process
from maxim import Maxim
from maxim.logger.crewai import instrument_crewai
```
### 3. API 키로 Maxim 초기화하기
```python {8}
# Instrument CrewAI with just one line
instrument_crewai(Maxim().logger())
```
### 4. 일반적으로 CrewAI 애플리케이션 생성 및 실행하기
```python
# Create your agent
researcher = Agent(
role='Senior Research Analyst',
goal='Uncover cutting-edge developments in AI',
backstory="You are an expert researcher at a tech think tank...",
verbose=True,
llm=llm
)
# Define the task
research_task = Task(
description="Research the latest AI advancements...",
expected_output="",
agent=researcher
)
# Configure and run the crew
crew = Crew(
agents=[researcher],
tasks=[research_task],
verbose=True
)
try:
result = crew.kickoff()
finally:
maxim.cleanup() # Ensure cleanup happens even if errors occur
```
이제 끝입니다! 모든 CrewAI 에이전트 상호작용이 Maxim 대시보드에 기록되고 확인할 수 있습니다.
간단한 참고를 위해 이 Google Colab Notebook을 확인하세요 - [Notebook](https://colab.research.google.com/drive/1ZKIZWsmgQQ46n8TH9zLsT1negKkJA6K8?usp=sharing)
## 트레이스 보기
CrewAI 애플리케이션을 실행한 후:
1. [Maxim 대시보드](https://app.getmaxim.ai/login)에 로그인하세요.
2. 리포지토리로 이동하세요.
3. 다음을 포함한 에이전트 트레이스를 상세하게 확인할 수 있습니다:
- 에이전트 대화 내역
- 도구 사용 패턴
- 성능 지표
- 비용 분석
<img src='https://raw.githubusercontent.com/akmadan/crewAI/docs_maxim_observability/docs/images/crewai_traces.gif'> </img>
## 문제 해결
### 흔한 문제
- **추적(trace)가 나타나지 않음**: API 키와 저장소 ID가 올바른지 확인하세요.
- crew를 실행하기 **_전에_** 반드시 **`instrument_crewai()`를 호출**했는지 확인하세요. 이 함수가 로깅 훅(logging hook)을 올바르게 초기화합니다.
- 내부 오류를 드러내기 위해 `instrument_crewai()` 호출 시 `debug=True`로 설정하세요:
```python
instrument_crewai(logger, debug=True)
```
- 에이전트에서 상세 로그를 캡처하기 위해 `verbose=True`로 설정하세요:
```python
agent = CrewAgent(..., verbose=True)
```
- `instrument_crewai()`가 에이전트를 생성하거나 실행하기 **전에** 호출되는지 다시 한 번 확인하세요. 너무 당연해 보일 수 있지만, 자주 발생하는 실수입니다.
## 리소스
<CardGroup cols="3">
<Card title="CrewAI Docs" icon="book" href="https://docs.crewai.com/">
공식 CrewAI 문서
</Card>
<Card title="Maxim Docs" icon="book" href="https://getmaxim.ai/docs">
공식 Maxim 문서
</Card>
<Card title="Maxim Github" icon="github" href="https://github.com/maximhq">
Maxim Github
</Card>
</CardGroup>

Some files were not shown because too many files have changed in this diff Show More