Compare commits
121 Commits
lg-agent-e
...
devin/1756
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf2b0c5864 | ||
|
|
3257d2757f | ||
|
|
045da4f030 | ||
|
|
3619d4dc50 | ||
|
|
3a54cc859a | ||
|
|
f0def350a4 | ||
|
|
f4f32b5f7f | ||
|
|
49a5ae0e16 | ||
|
|
d31ffdbb90 | ||
|
|
4555ada91e | ||
|
|
92d71f7f06 | ||
|
|
dada9f140f | ||
|
|
878c1a649a | ||
|
|
1b1a8fdbf4 | ||
|
|
2633b33afc | ||
|
|
e4c4b81e63 | ||
|
|
ec1eff02a8 | ||
|
|
0f1b764c3e | ||
|
|
6ee9db1d4a | ||
|
|
109de91d08 | ||
|
|
92b70e652d | ||
|
|
fc3f2c49d2 | ||
|
|
88d2968fd5 | ||
|
|
7addda9398 | ||
|
|
4b4a119a9f | ||
|
|
869bb115c8 | ||
|
|
7ac482c7c9 | ||
|
|
2e4bd3f49d | ||
|
|
c02997d956 | ||
|
|
f96b779df5 | ||
|
|
842bed4e9c | ||
|
|
1217935b31 | ||
|
|
641c156c17 | ||
|
|
7fdf9f9290 | ||
|
|
c0d2bf4c12 | ||
|
|
ed187b495b | ||
|
|
2773996b49 | ||
|
|
95923b78c6 | ||
|
|
7065ad4336 | ||
|
|
d6254918fd | ||
|
|
95e3d6db7a | ||
|
|
d7f8002baa | ||
|
|
d743e12a06 | ||
|
|
6068fe941f | ||
|
|
2a0cefc98b | ||
|
|
a4f65e4870 | ||
|
|
a1b3edd79c | ||
|
|
80b3d9689a | ||
|
|
ec03a53121 | ||
|
|
2fdf3f3a6a | ||
|
|
1d3d7ebf5e | ||
|
|
2c2196f415 | ||
|
|
c9f30b175c | ||
|
|
a17b93a7f8 | ||
|
|
0d3e462791 | ||
|
|
947c9552f0 | ||
|
|
04a03d332f | ||
|
|
992e093610 | ||
|
|
07f8e73958 | ||
|
|
66c2fa1623 | ||
|
|
7a52cc9667 | ||
|
|
8b686fb0c6 | ||
|
|
dc6771ae95 | ||
|
|
e9b1e5a8f6 | ||
|
|
57c787f919 | ||
|
|
a0eadf783b | ||
|
|
251ae00b8b | ||
|
|
a221295394 | ||
|
|
a92211f0ba | ||
|
|
f9481cf10d | ||
|
|
915857541e | ||
|
|
7c162411b7 | ||
|
|
8f4a6cc61c | ||
|
|
7dc86dc79a | ||
|
|
7ce20cfcc6 | ||
|
|
1d9523c98f | ||
|
|
9f1d7d1aa9 | ||
|
|
79b375f6fa | ||
|
|
75752479c2 | ||
|
|
477bc1f09e | ||
|
|
66567bdc2f | ||
|
|
0b31bbe957 | ||
|
|
246cf588cd | ||
|
|
88ed91561f | ||
|
|
9a347ad458 | ||
|
|
34c3075fdb | ||
|
|
498e8dc6e8 | ||
|
|
cb522cf500 | ||
|
|
017acc74f5 | ||
|
|
fab86d197a | ||
|
|
864e9bfb76 | ||
|
|
d3b45d197c | ||
|
|
579153b070 | ||
|
|
b1fdcdfa6e | ||
|
|
18d76a270c | ||
|
|
30541239ad | ||
|
|
9a65573955 | ||
|
|
27623a1d01 | ||
|
|
2593242234 | ||
|
|
2ab6c31544 | ||
|
|
3c55c8a22a | ||
|
|
424433ff58 | ||
|
|
2fd99503ed | ||
|
|
942014962e | ||
|
|
2ab79a7dd5 | ||
|
|
27c449c9c4 | ||
|
|
9737333ffd | ||
|
|
bf248d5118 | ||
|
|
2490e8cd46 | ||
|
|
9b67e5a15f | ||
|
|
6ebb6c9b63 | ||
|
|
53f674be60 | ||
|
|
11717a5213 | ||
|
|
b6d699f764 | ||
|
|
5b15061b87 | ||
|
|
1b6b2b36d9 | ||
|
|
3ada4053bd | ||
|
|
e7a5747c6b | ||
|
|
eec1262d4f | ||
|
|
c6caa763d7 | ||
|
|
08fa3797ca |
17
.github/workflows/linter.yml
vendored
@@ -15,8 +15,19 @@ jobs:
|
||||
- name: Fetch Target Branch
|
||||
run: git fetch origin $TARGET_BRANCH --depth=1
|
||||
|
||||
- name: Install Ruff
|
||||
run: pip install ruff
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
**/pyproject.toml
|
||||
**/uv.lock
|
||||
|
||||
- name: Set up Python
|
||||
run: uv python install 3.11
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --dev --no-install-project
|
||||
|
||||
- name: Get Changed Python Files
|
||||
id: changed-files
|
||||
@@ -33,4 +44,4 @@ jobs:
|
||||
echo "${{ steps.changed-files.outputs.files }}" \
|
||||
| tr ' ' '\n' \
|
||||
| grep -v 'src/crewai/cli/templates/' \
|
||||
| xargs -I{} ruff check "{}"
|
||||
| xargs -I{} uv run ruff check "{}"
|
||||
|
||||
16
.github/workflows/security-checker.yml
vendored
@@ -10,14 +10,20 @@ jobs:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
python-version: "3.11.9"
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
**/pyproject.toml
|
||||
**/uv.lock
|
||||
|
||||
- name: Set up Python
|
||||
run: uv python install 3.11
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install bandit
|
||||
run: uv sync --dev --no-install-project
|
||||
|
||||
- name: Run Bandit
|
||||
run: bandit -c pyproject.toml -r src/ -ll
|
||||
run: uv run bandit -c pyproject.toml -r src/ -ll
|
||||
|
||||
|
||||
20
.github/workflows/tests.yml
vendored
@@ -24,7 +24,7 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v3
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
@@ -37,25 +37,9 @@ jobs:
|
||||
- name: Install the project
|
||||
run: uv sync --dev --all-extras
|
||||
|
||||
- name: Install SQLite with FTS5 support
|
||||
run: |
|
||||
# WORKAROUND: GitHub Actions' Ubuntu runner uses SQLite without FTS5 support compiled in.
|
||||
# This is a temporary fix until the runner includes SQLite with FTS5 or Python's sqlite3
|
||||
# module is compiled with FTS5 support by default.
|
||||
# TODO: Remove this workaround once GitHub Actions runners include SQLite FTS5 support
|
||||
|
||||
# Install pysqlite3-binary which has FTS5 support
|
||||
uv pip install pysqlite3-binary
|
||||
# Create a sitecustomize.py to override sqlite3 with pysqlite3
|
||||
mkdir -p .pytest_sqlite_override
|
||||
echo "import sys; import pysqlite3; sys.modules['sqlite3'] = pysqlite3" > .pytest_sqlite_override/sitecustomize.py
|
||||
# Test FTS5 availability
|
||||
PYTHONPATH=.pytest_sqlite_override uv run python -c "import sqlite3; print(f'SQLite version: {sqlite3.sqlite_version}')"
|
||||
PYTHONPATH=.pytest_sqlite_override uv run python -c "import sqlite3; conn = sqlite3.connect(':memory:'); conn.execute('CREATE VIRTUAL TABLE test USING fts5(content)'); print('FTS5 module available')"
|
||||
|
||||
- name: Run tests (group ${{ matrix.group }} of 8)
|
||||
run: |
|
||||
PYTHONPATH=.pytest_sqlite_override uv run pytest \
|
||||
uv run pytest \
|
||||
--block-network \
|
||||
--timeout=30 \
|
||||
-vv \
|
||||
|
||||
75
.github/workflows/type-checker.yml
vendored
@@ -6,21 +6,78 @@ permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
type-checker:
|
||||
type-checker-matrix:
|
||||
name: type-checker (${{ matrix.python-version }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11.9"
|
||||
fetch-depth: 0 # Fetch all history for proper diff
|
||||
|
||||
- name: Install Requirements
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
**/pyproject.toml
|
||||
**/uv.lock
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
run: uv python install ${{ matrix.python-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --dev --no-install-project
|
||||
|
||||
- name: Get changed Python files
|
||||
id: changed-files
|
||||
run: |
|
||||
pip install mypy
|
||||
# Get the list of changed Python files compared to the base branch
|
||||
echo "Fetching changed files..."
|
||||
git diff --name-only --diff-filter=ACMRT origin/${{ github.base_ref }}...HEAD -- '*.py' > changed_files.txt
|
||||
|
||||
- name: Run type checks
|
||||
run: mypy src
|
||||
# Filter for files in src/ and tests/ directories
|
||||
grep -E "^(src/|tests/)" changed_files.txt > filtered_changed_files.txt || true
|
||||
|
||||
# Check if there are any changed files
|
||||
if [ -s filtered_changed_files.txt ]; then
|
||||
echo "Changed Python files in src/ and tests/:"
|
||||
cat filtered_changed_files.txt
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
# Convert newlines to spaces for mypy command
|
||||
echo "files=$(cat filtered_changed_files.txt | tr '\n' ' ')" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "No Python files changed in src/ or tests/"
|
||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Run type checks on changed files
|
||||
if: steps.changed-files.outputs.has_changes == 'true'
|
||||
run: |
|
||||
echo "Running mypy on changed files with Python ${{ matrix.python-version }}..."
|
||||
uv run mypy ${{ steps.changed-files.outputs.files }}
|
||||
|
||||
- name: No files to check
|
||||
if: steps.changed-files.outputs.has_changes == 'false'
|
||||
run: echo "No Python files in src/ or tests/ were modified - skipping type checks"
|
||||
|
||||
# Summary job to provide single status for branch protection
|
||||
type-checker:
|
||||
name: type-checker
|
||||
runs-on: ubuntu-latest
|
||||
needs: type-checker-matrix
|
||||
if: always()
|
||||
steps:
|
||||
- name: Check matrix results
|
||||
run: |
|
||||
if [ "${{ needs.type-checker-matrix.result }}" == "success" ] || [ "${{ needs.type-checker-matrix.result }}" == "skipped" ]; then
|
||||
echo "✅ All type checks passed"
|
||||
else
|
||||
echo "❌ Type checks failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
4
.gitignore
vendored
@@ -21,9 +21,9 @@ crew_tasks_output.json
|
||||
.mypy_cache
|
||||
.ruff_cache
|
||||
.venv
|
||||
agentops.log
|
||||
test_flow.html
|
||||
crewairules.mdc
|
||||
plan.md
|
||||
conceptual_plan.md
|
||||
build_image
|
||||
build_image
|
||||
chromadb-*.lock
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.8.2
|
||||
rev: v0.12.11
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: ["--fix"]
|
||||
args: ["--config", "pyproject.toml"]
|
||||
- id: ruff-format
|
||||
args: ["--config", "pyproject.toml"]
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.17.1
|
||||
hooks:
|
||||
- id: mypy
|
||||
args: ["--config-file", "pyproject.toml"]
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
exclude = [
|
||||
"templates",
|
||||
"__init__.py",
|
||||
]
|
||||
12
README.md
@@ -418,10 +418,10 @@ Choose CrewAI to easily build powerful, adaptable, and production-ready AI autom
|
||||
|
||||
You can test different real life examples of AI crews in the [CrewAI-examples repo](https://github.com/crewAIInc/crewAI-examples?tab=readme-ov-file):
|
||||
|
||||
- [Landing Page Generator](https://github.com/crewAIInc/crewAI-examples/tree/main/landing_page_generator)
|
||||
- [Landing Page Generator](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/landing_page_generator)
|
||||
- [Having Human input on the execution](https://docs.crewai.com/how-to/Human-Input-on-Execution)
|
||||
- [Trip Planner](https://github.com/crewAIInc/crewAI-examples/tree/main/trip_planner)
|
||||
- [Stock Analysis](https://github.com/crewAIInc/crewAI-examples/tree/main/stock_analysis)
|
||||
- [Trip Planner](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/trip_planner)
|
||||
- [Stock Analysis](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/stock_analysis)
|
||||
|
||||
### Quick Tutorial
|
||||
|
||||
@@ -429,19 +429,19 @@ You can test different real life examples of AI crews in the [CrewAI-examples re
|
||||
|
||||
### Write Job Descriptions
|
||||
|
||||
[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/job-posting) or watch a video below:
|
||||
[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/job-posting) or watch a video below:
|
||||
|
||||
[](https://www.youtube.com/watch?v=u98wEMz-9to "Jobs postings")
|
||||
|
||||
### Trip Planner
|
||||
|
||||
[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/trip_planner) or watch a video below:
|
||||
[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/trip_planner) or watch a video below:
|
||||
|
||||
[](https://www.youtube.com/watch?v=xis7rWp-hjs "Trip Planner")
|
||||
|
||||
### Stock Analysis
|
||||
|
||||
[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/stock_analysis) or watch a video below:
|
||||
[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/stock_analysis) or watch a video below:
|
||||
|
||||
[](https://www.youtube.com/watch?v=e0Uj4yWdaAg "Stock Analysis")
|
||||
|
||||
|
||||
501
docs/docs.json
@@ -9,12 +9,7 @@
|
||||
},
|
||||
"favicon": "/images/favicon.svg",
|
||||
"contextual": {
|
||||
"options": [
|
||||
"copy",
|
||||
"view",
|
||||
"chatgpt",
|
||||
"claude"
|
||||
]
|
||||
"options": ["copy", "view", "chatgpt", "claude"]
|
||||
},
|
||||
"navigation": {
|
||||
"languages": [
|
||||
@@ -37,11 +32,6 @@
|
||||
"href": "https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant",
|
||||
"icon": "robot"
|
||||
},
|
||||
{
|
||||
"anchor": "Get Help",
|
||||
"href": "mailto:support@crewai.com",
|
||||
"icon": "headset"
|
||||
},
|
||||
{
|
||||
"anchor": "Releases",
|
||||
"href": "https://github.com/crewAIInc/crewAI/releases",
|
||||
@@ -55,32 +45,22 @@
|
||||
"groups": [
|
||||
{
|
||||
"group": "Get Started",
|
||||
"pages": [
|
||||
"en/introduction",
|
||||
"en/installation",
|
||||
"en/quickstart"
|
||||
]
|
||||
"pages": ["en/introduction", "en/installation", "en/quickstart"]
|
||||
},
|
||||
{
|
||||
"group": "Guides",
|
||||
"pages": [
|
||||
{
|
||||
"group": "Strategy",
|
||||
"pages": [
|
||||
"en/guides/concepts/evaluating-use-cases"
|
||||
]
|
||||
"pages": ["en/guides/concepts/evaluating-use-cases"]
|
||||
},
|
||||
{
|
||||
"group": "Agents",
|
||||
"pages": [
|
||||
"en/guides/agents/crafting-effective-agents"
|
||||
]
|
||||
"pages": ["en/guides/agents/crafting-effective-agents"]
|
||||
},
|
||||
{
|
||||
"group": "Crews",
|
||||
"pages": [
|
||||
"en/guides/crews/first-crew"
|
||||
]
|
||||
"pages": ["en/guides/crews/first-crew"]
|
||||
},
|
||||
{
|
||||
"group": "Flows",
|
||||
@@ -94,7 +74,6 @@
|
||||
"pages": [
|
||||
"en/guides/advanced/customizing-prompts",
|
||||
"en/guides/advanced/fingerprinting"
|
||||
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -149,7 +128,9 @@
|
||||
"en/tools/file-document/jsonsearchtool",
|
||||
"en/tools/file-document/csvsearchtool",
|
||||
"en/tools/file-document/directorysearchtool",
|
||||
"en/tools/file-document/directoryreadtool"
|
||||
"en/tools/file-document/directoryreadtool",
|
||||
"en/tools/file-document/ocrtool",
|
||||
"en/tools/file-document/pdf-text-writing-tool"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -167,7 +148,8 @@
|
||||
"en/tools/web-scraping/stagehandtool",
|
||||
"en/tools/web-scraping/firecrawlcrawlwebsitetool",
|
||||
"en/tools/web-scraping/firecrawlscrapewebsitetool",
|
||||
"en/tools/web-scraping/oxylabsscraperstool"
|
||||
"en/tools/web-scraping/oxylabsscraperstool",
|
||||
"en/tools/web-scraping/brightdata-tools"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -182,7 +164,13 @@
|
||||
"en/tools/search-research/websitesearchtool",
|
||||
"en/tools/search-research/codedocssearchtool",
|
||||
"en/tools/search-research/youtubechannelsearchtool",
|
||||
"en/tools/search-research/youtubevideosearchtool"
|
||||
"en/tools/search-research/youtubevideosearchtool",
|
||||
"en/tools/search-research/tavilysearchtool",
|
||||
"en/tools/search-research/tavilyextractortool",
|
||||
"en/tools/search-research/arxivpapertool",
|
||||
"en/tools/search-research/serpapi-googlesearchtool",
|
||||
"en/tools/search-research/serpapi-googleshoppingtool",
|
||||
"en/tools/search-research/databricks-query-tool"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -194,7 +182,9 @@
|
||||
"en/tools/database-data/snowflakesearchtool",
|
||||
"en/tools/database-data/nl2sqltool",
|
||||
"en/tools/database-data/qdrantvectorsearchtool",
|
||||
"en/tools/database-data/weaviatevectorsearchtool"
|
||||
"en/tools/database-data/weaviatevectorsearchtool",
|
||||
"en/tools/database-data/mongodbvectorsearchtool",
|
||||
"en/tools/database-data/singlestoresearchtool"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -226,7 +216,8 @@
|
||||
"en/tools/automation/overview",
|
||||
"en/tools/automation/apifyactorstool",
|
||||
"en/tools/automation/composiotool",
|
||||
"en/tools/automation/multiontool"
|
||||
"en/tools/automation/multiontool",
|
||||
"en/tools/automation/zapieractionstool"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -235,17 +226,19 @@
|
||||
"group": "Observability",
|
||||
"pages": [
|
||||
"en/observability/overview",
|
||||
"en/observability/agentops",
|
||||
"en/observability/arize-phoenix",
|
||||
"en/observability/langdb",
|
||||
"en/observability/langfuse",
|
||||
"en/observability/langtrace",
|
||||
"en/observability/maxim",
|
||||
"en/observability/mlflow",
|
||||
"en/observability/neatlogs",
|
||||
"en/observability/openlit",
|
||||
"en/observability/opik",
|
||||
"en/observability/patronus-evaluation",
|
||||
"en/observability/portkey",
|
||||
"en/observability/weave"
|
||||
"en/observability/weave",
|
||||
"en/observability/truefoundry"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -274,9 +267,7 @@
|
||||
},
|
||||
{
|
||||
"group": "Telemetry",
|
||||
"pages": [
|
||||
"en/telemetry"
|
||||
]
|
||||
"pages": ["en/telemetry"]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -285,13 +276,12 @@
|
||||
"groups": [
|
||||
{
|
||||
"group": "Getting Started",
|
||||
"pages": [
|
||||
"en/enterprise/introduction"
|
||||
]
|
||||
"pages": ["en/enterprise/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "Features",
|
||||
"pages": [
|
||||
"en/enterprise/features/rbac",
|
||||
"en/enterprise/features/tool-repository",
|
||||
"en/enterprise/features/webhook-streaming",
|
||||
"en/enterprise/features/traces",
|
||||
@@ -330,6 +320,7 @@
|
||||
"en/enterprise/guides/update-crew",
|
||||
"en/enterprise/guides/enable-crew-studio",
|
||||
"en/enterprise/guides/azure-openai-setup",
|
||||
"en/enterprise/guides/automation-triggers",
|
||||
"en/enterprise/guides/hubspot-trigger",
|
||||
"en/enterprise/guides/react-component-export",
|
||||
"en/enterprise/guides/salesforce-trigger",
|
||||
@@ -342,9 +333,7 @@
|
||||
},
|
||||
{
|
||||
"group": "Resources",
|
||||
"pages": [
|
||||
"en/enterprise/resources/frequently-asked-questions"
|
||||
]
|
||||
"pages": ["en/enterprise/resources/frequently-asked-questions"]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -354,27 +343,23 @@
|
||||
{
|
||||
"group": "Getting Started",
|
||||
"pages": [
|
||||
"en/api-reference/introduction"
|
||||
"en/api-reference/introduction",
|
||||
"en/api-reference/inputs",
|
||||
"en/api-reference/kickoff",
|
||||
"en/api-reference/status"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Endpoints",
|
||||
"openapi": "enterprise-api.yaml"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Examples",
|
||||
"groups": [
|
||||
"groups": [
|
||||
{
|
||||
"group": "Examples",
|
||||
"pages": [
|
||||
"en/examples/example"
|
||||
]
|
||||
"pages": ["en/examples/example", "en/examples/cookbooks"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -396,11 +381,6 @@
|
||||
"href": "https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant",
|
||||
"icon": "robot"
|
||||
},
|
||||
{
|
||||
"anchor": "Obter Ajuda",
|
||||
"href": "mailto:support@crewai.com",
|
||||
"icon": "headset"
|
||||
},
|
||||
{
|
||||
"anchor": "Lançamentos",
|
||||
"href": "https://github.com/crewAIInc/crewAI/releases",
|
||||
@@ -425,21 +405,15 @@
|
||||
"pages": [
|
||||
{
|
||||
"group": "Estratégia",
|
||||
"pages": [
|
||||
"pt-BR/guides/concepts/evaluating-use-cases"
|
||||
]
|
||||
"pages": ["pt-BR/guides/concepts/evaluating-use-cases"]
|
||||
},
|
||||
{
|
||||
"group": "Agentes",
|
||||
"pages": [
|
||||
"pt-BR/guides/agents/crafting-effective-agents"
|
||||
]
|
||||
"pages": ["pt-BR/guides/agents/crafting-effective-agents"]
|
||||
},
|
||||
{
|
||||
"group": "Crews",
|
||||
"pages": [
|
||||
"pt-BR/guides/crews/first-crew"
|
||||
]
|
||||
"pages": ["pt-BR/guides/crews/first-crew"]
|
||||
},
|
||||
{
|
||||
"group": "Flows",
|
||||
@@ -593,8 +567,8 @@
|
||||
"group": "Observabilidade",
|
||||
"pages": [
|
||||
"pt-BR/observability/overview",
|
||||
"pt-BR/observability/agentops",
|
||||
"pt-BR/observability/arize-phoenix",
|
||||
"pt-BR/observability/langdb",
|
||||
"pt-BR/observability/langfuse",
|
||||
"pt-BR/observability/langtrace",
|
||||
"pt-BR/observability/maxim",
|
||||
@@ -603,7 +577,8 @@
|
||||
"pt-BR/observability/opik",
|
||||
"pt-BR/observability/patronus-evaluation",
|
||||
"pt-BR/observability/portkey",
|
||||
"pt-BR/observability/weave"
|
||||
"pt-BR/observability/weave",
|
||||
"pt-BR/observability/truefoundry"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -632,9 +607,7 @@
|
||||
},
|
||||
{
|
||||
"group": "Telemetria",
|
||||
"pages": [
|
||||
"pt-BR/telemetry"
|
||||
]
|
||||
"pages": ["pt-BR/telemetry"]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -643,13 +616,12 @@
|
||||
"groups": [
|
||||
{
|
||||
"group": "Começando",
|
||||
"pages": [
|
||||
"pt-BR/enterprise/introduction"
|
||||
]
|
||||
"pages": ["pt-BR/enterprise/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "Funcionalidades",
|
||||
"pages": [
|
||||
"pt-BR/enterprise/features/rbac",
|
||||
"pt-BR/enterprise/features/tool-repository",
|
||||
"pt-BR/enterprise/features/webhook-streaming",
|
||||
"pt-BR/enterprise/features/traces",
|
||||
@@ -687,6 +659,7 @@
|
||||
"pt-BR/enterprise/guides/update-crew",
|
||||
"pt-BR/enterprise/guides/enable-crew-studio",
|
||||
"pt-BR/enterprise/guides/azure-openai-setup",
|
||||
"pt-BR/enterprise/guides/automation-triggers",
|
||||
"pt-BR/enterprise/guides/hubspot-trigger",
|
||||
"pt-BR/enterprise/guides/react-component-export",
|
||||
"pt-BR/enterprise/guides/salesforce-trigger",
|
||||
@@ -711,27 +684,371 @@
|
||||
{
|
||||
"group": "Começando",
|
||||
"pages": [
|
||||
"pt-BR/api-reference/introduction"
|
||||
"pt-BR/api-reference/introduction",
|
||||
"pt-BR/api-reference/inputs",
|
||||
"pt-BR/api-reference/kickoff",
|
||||
"pt-BR/api-reference/status"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Endpoints",
|
||||
"openapi": "enterprise-api.yaml"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Exemplos",
|
||||
"groups": [
|
||||
"groups": [
|
||||
{
|
||||
"group": "Exemplos",
|
||||
"pages": [
|
||||
"pt-BR/examples/example"
|
||||
]
|
||||
"pages": ["pt-BR/examples/example", "pt-BR/examples/cookbooks"]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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": "도구 (Tools)",
|
||||
"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": "Observability",
|
||||
"pages": [
|
||||
"ko/observability/overview",
|
||||
"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": "Telemetry",
|
||||
"pages": ["ko/telemetry"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "엔터프라이즈",
|
||||
"groups": [
|
||||
{
|
||||
"group": "시작 안내",
|
||||
"pages": ["ko/enterprise/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "특징",
|
||||
"pages": [
|
||||
"ko/enterprise/features/rbac",
|
||||
"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": "How-To Guides",
|
||||
"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/automation-triggers",
|
||||
"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",
|
||||
"ko/api-reference/inputs",
|
||||
"ko/api-reference/kickoff",
|
||||
"ko/api-reference/status"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "예시",
|
||||
"groups": [
|
||||
{
|
||||
"group": "예시",
|
||||
"pages": ["ko/examples/example", "ko/examples/cookbooks"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -770,6 +1087,10 @@
|
||||
"indexing": "all"
|
||||
},
|
||||
"redirects": [
|
||||
{
|
||||
"source": "/api-reference",
|
||||
"destination": "/en/api-reference/introduction"
|
||||
},
|
||||
{
|
||||
"source": "/introduction",
|
||||
"destination": "/en/introduction"
|
||||
@@ -822,6 +1143,18 @@
|
||||
"source": "/api-reference/:path*",
|
||||
"destination": "/en/api-reference/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/en/api-reference",
|
||||
"destination": "/en/api-reference/introduction"
|
||||
},
|
||||
{
|
||||
"source": "/pt-BR/api-reference",
|
||||
"destination": "/pt-BR/api-reference/introduction"
|
||||
},
|
||||
{
|
||||
"source": "/ko/api-reference",
|
||||
"destination": "/ko/api-reference/introduction"
|
||||
},
|
||||
{
|
||||
"source": "/examples/:path*",
|
||||
"destination": "/en/examples/:path*"
|
||||
|
||||
7
docs/en/api-reference/inputs.mdx
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
title: "GET /inputs"
|
||||
description: "Get required inputs for your crew"
|
||||
openapi: "/enterprise-api.en.yaml GET /inputs"
|
||||
---
|
||||
|
||||
|
||||
7
docs/en/api-reference/kickoff.mdx
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
title: "POST /kickoff"
|
||||
description: "Start a crew execution"
|
||||
openapi: "/enterprise-api.en.yaml POST /kickoff"
|
||||
---
|
||||
|
||||
|
||||
7
docs/en/api-reference/status.mdx
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
title: "GET /status/{kickoff_id}"
|
||||
description: "Get execution status"
|
||||
openapi: "/enterprise-api.en.yaml GET /status/{kickoff_id}"
|
||||
---
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ crewai replay [OPTIONS]
|
||||
- `-t, --task_id TEXT`: Replay the crew from this task ID, including all subsequent tasks
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
```shell Terminal
|
||||
crewai replay -t task_123456
|
||||
```
|
||||
|
||||
@@ -134,7 +134,7 @@ crewai test [OPTIONS]
|
||||
- `-m, --model TEXT`: LLM Model to run the tests on the Crew (default: "gpt-4o-mini")
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
```shell Terminal
|
||||
crewai test -n 5 -m gpt-3.5-turbo
|
||||
```
|
||||
|
||||
@@ -151,7 +151,7 @@ Starting from version 0.103.0, the `crewai run` command can be used to run both
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
Make sure to run these commands from the directory where your CrewAI project is set up.
|
||||
Make sure to run these commands from the directory where your CrewAI project is set up.
|
||||
Some commands may require additional configuration or setup within your project structure.
|
||||
</Note>
|
||||
|
||||
@@ -235,7 +235,7 @@ You must be authenticated to CrewAI Enterprise to use these organization managem
|
||||
- **Deploy the Crew**: Once you are authenticated, you can deploy your crew or flow to CrewAI Enterprise.
|
||||
```shell Terminal
|
||||
crewai deploy push
|
||||
```
|
||||
```
|
||||
- Initiates the deployment process on the CrewAI Enterprise platform.
|
||||
- Upon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID).
|
||||
|
||||
@@ -282,7 +282,25 @@ Watch this video tutorial for a step-by-step demonstration of deploying your cre
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
|
||||
### 11. API Keys
|
||||
### 12. Login
|
||||
|
||||
Authenticate with CrewAI Enterprise using a secure device code flow (no email entry required).
|
||||
|
||||
```shell Terminal
|
||||
crewai login
|
||||
```
|
||||
|
||||
What happens:
|
||||
- A verification URL and short code are displayed in your terminal
|
||||
- Your browser opens to the verification URL
|
||||
- Enter/confirm the code to complete authentication
|
||||
|
||||
Notes:
|
||||
- The OAuth2 provider and domain are configured via `crewai config` (defaults use `login.crewai.com`)
|
||||
- After successful login, the CLI also attempts to authenticate to the Tool Repository automatically
|
||||
- If you reset your configuration, run `crewai login` again to re-authenticate
|
||||
|
||||
### 13. API Keys
|
||||
|
||||
When running ```crewai create crew``` command, the CLI will show you a list of available LLM providers to choose from, followed by model selection for your chosen provider.
|
||||
|
||||
@@ -309,3 +327,86 @@ When you select a provider, the CLI will prompt you to enter the Key name and th
|
||||
See the following link for each provider's key name:
|
||||
|
||||
* [LiteLLM Providers](https://docs.litellm.ai/docs/providers)
|
||||
|
||||
### 14. Configuration Management
|
||||
|
||||
Manage CLI configuration settings for CrewAI.
|
||||
|
||||
```shell Terminal
|
||||
crewai config [COMMAND] [OPTIONS]
|
||||
```
|
||||
|
||||
#### Commands:
|
||||
|
||||
- `list`: Display all CLI configuration parameters
|
||||
```shell Terminal
|
||||
crewai config list
|
||||
```
|
||||
|
||||
- `set`: Set a CLI configuration parameter
|
||||
```shell Terminal
|
||||
crewai config set <key> <value>
|
||||
```
|
||||
|
||||
- `reset`: Reset all CLI configuration parameters to default values
|
||||
```shell Terminal
|
||||
crewai config reset
|
||||
```
|
||||
|
||||
#### Available Configuration Parameters
|
||||
|
||||
- `enterprise_base_url`: Base URL of the CrewAI Enterprise instance
|
||||
- `oauth2_provider`: OAuth2 provider used for authentication (e.g., workos, okta, auth0)
|
||||
- `oauth2_audience`: OAuth2 audience value, typically used to identify the target API or resource
|
||||
- `oauth2_client_id`: OAuth2 client ID issued by the provider, used during authentication requests
|
||||
- `oauth2_domain`: OAuth2 provider's domain (e.g., your-org.auth0.com) used for issuing tokens
|
||||
|
||||
#### Examples
|
||||
|
||||
Display current configuration:
|
||||
```shell Terminal
|
||||
crewai config list
|
||||
```
|
||||
|
||||
Example output:
|
||||
```
|
||||
CrewAI CLI Configuration
|
||||
┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
|
||||
┃ Setting ┃ Value ┃ Description ┃
|
||||
┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
|
||||
│ enterprise_base_url│ https://app.crewai.com │ Base URL of the CrewAI Enterprise instance │
|
||||
│ org_name │ Not set │ Name of the currently active organization │
|
||||
│ org_uuid │ Not set │ UUID of the currently active organization │
|
||||
│ oauth2_provider │ workos │ OAuth2 provider used for authentication (e.g., workos, okta, auth0). │
|
||||
│ oauth2_audience │ client_01YYY │ OAuth2 audience value, typically used to identify the target API or resource. │
|
||||
│ oauth2_client_id │ client_01XXX │ OAuth2 client ID issued by the provider, used during authentication requests. │
|
||||
│ oauth2_domain │ login.crewai.com │ OAuth2 provider's domain (e.g., your-org.auth0.com) used for issuing tokens. │
|
||||
```
|
||||
|
||||
Set the enterprise base URL:
|
||||
```shell Terminal
|
||||
crewai config set enterprise_base_url https://my-enterprise.crewai.com
|
||||
```
|
||||
|
||||
Set OAuth2 provider:
|
||||
```shell Terminal
|
||||
crewai config set oauth2_provider auth0
|
||||
```
|
||||
|
||||
Set OAuth2 domain:
|
||||
```shell Terminal
|
||||
crewai config set oauth2_domain my-company.auth0.com
|
||||
```
|
||||
|
||||
Reset all configuration to defaults:
|
||||
```shell Terminal
|
||||
crewai config reset
|
||||
```
|
||||
|
||||
<Tip>
|
||||
After resetting configuration, re-run `crewai login` to authenticate again.
|
||||
</Tip>
|
||||
|
||||
<Note>
|
||||
Configuration settings are stored in `~/.config/crewai/settings.json`. Some settings like organization name and UUID are read-only and managed through authentication and organization commands. Tool repository related settings are hidden and cannot be set directly by users.
|
||||
</Note>
|
||||
|
||||
@@ -20,8 +20,7 @@ A crew in crewAI represents a collaborative group of agents working together to
|
||||
| **Function Calling LLM** _(optional)_ | `function_calling_llm` | If passed, the crew will use this LLM to do function calling for tools for all agents in the crew. Each agent can have its own LLM, which overrides the crew's LLM for function calling. |
|
||||
| **Config** _(optional)_ | `config` | Optional configuration settings for the crew, in `Json` or `Dict[str, Any]` format. |
|
||||
| **Max RPM** _(optional)_ | `max_rpm` | Maximum requests per minute the crew adheres to during execution. Defaults to `None`. |
|
||||
| **Memory** _(optional)_ | `memory` | Utilized for storing execution memories (short-term, long-term, entity memory). |
|
||||
| **Memory Config** _(optional)_ | `memory_config` | Configuration for the memory provider to be used by the crew. |
|
||||
| **Memory** _(optional)_ | `memory` | Utilized for storing execution memories (short-term, long-term, entity memory). | |
|
||||
| **Cache** _(optional)_ | `cache` | Specifies whether to use a cache for storing the results of tools' execution. Defaults to `True`. |
|
||||
| **Embedder** _(optional)_ | `embedder` | Configuration for the embedder to be used by the crew. Mostly used by memory for now. Default is `{"provider": "openai"}`. |
|
||||
| **Step Callback** _(optional)_ | `step_callback` | A function that is called after each step of every agent. This can be used to log the agent's actions or to perform other operations; it won't override the agent-specific `step_callback`. |
|
||||
@@ -32,6 +31,7 @@ A crew in crewAI represents a collaborative group of agents working together to
|
||||
| **Prompt File** _(optional)_ | `prompt_file` | Path to the prompt JSON file to be used for the crew. |
|
||||
| **Planning** *(optional)* | `planning` | Adds planning ability to the Crew. When activated before each Crew iteration, all Crew data is sent to an AgentPlanner that will plan the tasks and this plan will be added to each task description. |
|
||||
| **Planning LLM** *(optional)* | `planning_llm` | The language model used by the AgentPlanner in a planning process. |
|
||||
| **Knowledge Sources** _(optional)_ | `knowledge_sources` | Knowledge sources available at the crew level, accessible to all the agents. |
|
||||
|
||||
<Tip>
|
||||
**Crew Max RPM**: The `max_rpm` attribute sets the maximum number of requests per minute the crew can perform to avoid rate limits and will override individual agents' `max_rpm` settings if you set it.
|
||||
|
||||
@@ -44,12 +44,12 @@ To create a custom event listener, you need to:
|
||||
Here's a simple example of a custom event listener class:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
CrewKickoffStartedEvent,
|
||||
CrewKickoffCompletedEvent,
|
||||
AgentExecutionCompletedEvent,
|
||||
)
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.events import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def __init__(self):
|
||||
@@ -146,7 +146,7 @@ my_project/
|
||||
|
||||
```python
|
||||
# my_custom_listener.py
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.events import BaseEventListener
|
||||
# ... import events ...
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
@@ -177,14 +177,7 @@ class MyCustomCrew:
|
||||
# Your crew implementation...
|
||||
```
|
||||
|
||||
This is exactly how CrewAI's built-in `agentops_listener` is registered. In the CrewAI codebase, you'll find:
|
||||
|
||||
```python
|
||||
# src/crewai/utilities/events/third_party/__init__.py
|
||||
from .agentops_listener import agentops_listener
|
||||
```
|
||||
|
||||
This ensures the `agentops_listener` is loaded when the `crewai.utilities.events` package is imported.
|
||||
This is how third-party event listeners are registered in the CrewAI codebase.
|
||||
|
||||
## Available Event Types
|
||||
|
||||
@@ -280,84 +273,13 @@ The structure of the event object depends on the event type, but all events inhe
|
||||
|
||||
Additional fields vary by event type. For example, `CrewKickoffCompletedEvent` includes `crew_name` and `output` fields.
|
||||
|
||||
## Real-World Example: Integration with AgentOps
|
||||
|
||||
CrewAI includes an example of a third-party integration with [AgentOps](https://github.com/AgentOps-AI/agentops), a monitoring and observability platform for AI agents. Here's how it's implemented:
|
||||
|
||||
```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)
|
||||
```
|
||||
|
||||
This listener initializes an AgentOps session when a Crew starts, registers agents with AgentOps, tracks tool usage, and ends the session when the Crew completes.
|
||||
|
||||
The AgentOps listener is registered in CrewAI's event system through the import in `src/crewai/utilities/events/third_party/__init__.py`:
|
||||
|
||||
```python
|
||||
from .agentops_listener import agentops_listener
|
||||
```
|
||||
|
||||
This ensures the `agentops_listener` is loaded when the `crewai.utilities.events` package is imported.
|
||||
|
||||
## Advanced Usage: Scoped Handlers
|
||||
|
||||
For temporary event handling (useful for testing or specific operations), you can use the `scoped_handlers` context manager:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events import crewai_event_bus, CrewKickoffStartedEvent
|
||||
from crewai.events import crewai_event_bus, CrewKickoffStartedEvent
|
||||
|
||||
with crewai_event_bus.scoped_handlers():
|
||||
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
||||
|
||||
@@ -97,7 +97,13 @@ The state's unique ID and stored data can be useful for tracking flow executions
|
||||
|
||||
### @start()
|
||||
|
||||
The `@start()` decorator is used to mark a method as the starting point of a Flow. When a Flow is started, all the methods decorated with `@start()` are executed in parallel. You can have multiple start methods in a Flow, and they will all be executed when the Flow is started.
|
||||
The `@start()` decorator marks entry points for a Flow. You can:
|
||||
|
||||
- Declare multiple unconditional starts: `@start()`
|
||||
- Gate a start on a prior method or router label: `@start("method_or_label")`
|
||||
- Provide a callable condition to control when a start should fire
|
||||
|
||||
All satisfied `@start()` methods will execute (often in parallel) when the Flow begins or resumes.
|
||||
|
||||
### @listen()
|
||||
|
||||
|
||||
@@ -24,6 +24,41 @@ For file-based Knowledge Sources, make sure to place your files in a `knowledge`
|
||||
Also, use relative paths from the `knowledge` directory when creating the source.
|
||||
</Tip>
|
||||
|
||||
### Vector store (RAG) client configuration
|
||||
|
||||
CrewAI exposes a provider-neutral RAG client abstraction for vector stores. The default provider is ChromaDB, and Qdrant is supported as well. You can switch providers using configuration utilities.
|
||||
|
||||
Supported today:
|
||||
- ChromaDB (default)
|
||||
- Qdrant
|
||||
|
||||
```python Code
|
||||
from crewai.rag.config.utils import set_rag_config, get_rag_client, clear_rag_config
|
||||
|
||||
# ChromaDB (default)
|
||||
from crewai.rag.chromadb.config import ChromaDBConfig
|
||||
set_rag_config(ChromaDBConfig())
|
||||
chromadb_client = get_rag_client()
|
||||
|
||||
# Qdrant
|
||||
from crewai.rag.qdrant.config import QdrantConfig
|
||||
set_rag_config(QdrantConfig())
|
||||
qdrant_client = get_rag_client()
|
||||
|
||||
# Example operations (same API for any provider)
|
||||
client = qdrant_client # or chromadb_client
|
||||
client.create_collection(collection_name="docs")
|
||||
client.add_documents(
|
||||
collection_name="docs",
|
||||
documents=[{"id": "1", "content": "CrewAI enables collaborative AI agents."}],
|
||||
)
|
||||
results = client.search(collection_name="docs", query="collaborative agents", limit=3)
|
||||
|
||||
clear_rag_config() # optional reset
|
||||
```
|
||||
|
||||
This RAG client is separate from Knowledge’s built-in storage. Use it when you need direct vector-store control or custom retrieval pipelines.
|
||||
|
||||
### Basic String Knowledge Example
|
||||
|
||||
```python Code
|
||||
@@ -681,11 +716,11 @@ CrewAI emits events during the knowledge retrieval process that you can listen f
|
||||
#### Example: Monitoring Knowledge Retrieval
|
||||
|
||||
```python
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
KnowledgeRetrievalStartedEvent,
|
||||
KnowledgeRetrievalCompletedEvent,
|
||||
BaseEventListener,
|
||||
)
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
|
||||
class KnowledgeMonitorListener(BaseEventListener):
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
|
||||
@@ -270,7 +270,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-1.5-pro-latest",
|
||||
model="gemini-1.5-pro-latest", # or vertex_ai/gemini-1.5-pro-latest
|
||||
temperature=0.7,
|
||||
vertex_credentials=vertex_credentials_json
|
||||
)
|
||||
@@ -733,10 +733,10 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
|
||||
CrewAI emits events for each chunk received during streaming:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
LLMStreamChunkEvent
|
||||
)
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.events import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
@@ -758,8 +758,8 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
|
||||
|
||||
```python
|
||||
from crewai import LLM, Agent, Task, Crew
|
||||
from crewai.utilities.events import LLMStreamChunkEvent
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.events import LLMStreamChunkEvent
|
||||
from crewai.events import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
|
||||
@@ -9,8 +9,7 @@ icon: database
|
||||
The CrewAI framework provides a sophisticated memory system designed to significantly enhance AI agent capabilities. CrewAI offers **three distinct memory approaches** that serve different use cases:
|
||||
|
||||
1. **Basic Memory System** - Built-in short-term, long-term, and entity memory
|
||||
2. **User Memory** - User-specific memory with Mem0 integration (legacy approach)
|
||||
3. **External Memory** - Standalone external memory providers (new approach)
|
||||
2. **External Memory** - Standalone external memory providers
|
||||
|
||||
## Memory System Components
|
||||
|
||||
@@ -19,7 +18,7 @@ The CrewAI framework provides a sophisticated memory system designed to signific
|
||||
| **Short-Term Memory**| Temporarily stores recent interactions and outcomes using `RAG`, enabling agents to recall and utilize information relevant to their current context during the current executions.|
|
||||
| **Long-Term Memory** | Preserves valuable insights and learnings from past executions, allowing agents to build and refine their knowledge over time. |
|
||||
| **Entity Memory** | Captures and organizes information about entities (people, places, concepts) encountered during tasks, facilitating deeper understanding and relationship mapping. Uses `RAG` for storing entity information. |
|
||||
| **Contextual Memory**| Maintains the context of interactions by combining `ShortTermMemory`, `LongTermMemory`, and `EntityMemory`, aiding in the coherence and relevance of agent responses over a sequence of tasks or a conversation. |
|
||||
| **Contextual Memory**| Maintains the context of interactions by combining `ShortTermMemory`, `LongTermMemory`, `ExternalMemory` and `EntityMemory`, aiding in the coherence and relevance of agent responses over a sequence of tasks or a conversation. |
|
||||
|
||||
## 1. Basic Memory System (Recommended)
|
||||
|
||||
@@ -202,7 +201,7 @@ crew = Crew(
|
||||
tasks=[task],
|
||||
memory=True,
|
||||
embedder={
|
||||
"provider": "anthropic", # Match your LLM provider
|
||||
"provider": "anthropic", # Match your LLM provider
|
||||
"config": {
|
||||
"api_key": "your-anthropic-key",
|
||||
"model": "text-embedding-3-small"
|
||||
@@ -540,16 +539,71 @@ crew = Crew(
|
||||
)
|
||||
```
|
||||
|
||||
### Mem0 Provider
|
||||
|
||||
Short-Term Memory and Entity Memory both supports a tight integration with both Mem0 OSS and Mem0 Client as a provider. Here is how you can use Mem0 as a provider.
|
||||
|
||||
```python
|
||||
from crewai.memory.short_term.short_term_memory import ShortTermMemory
|
||||
from crewai.memory.entity_entity_memory import EntityMemory
|
||||
|
||||
mem0_oss_embedder_config = {
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"user_id": "john",
|
||||
"local_mem0_config": {
|
||||
"vector_store": {"provider": "qdrant","config": {"host": "localhost", "port": 6333}},
|
||||
"llm": {"provider": "openai","config": {"api_key": "your-api-key", "model": "gpt-4"}},
|
||||
"embedder": {"provider": "openai","config": {"api_key": "your-api-key", "model": "text-embedding-3-small"}}
|
||||
},
|
||||
"infer": True # Optional defaults to True
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
mem0_client_embedder_config = {
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"user_id": "john",
|
||||
"org_id": "my_org_id", # Optional
|
||||
"project_id": "my_project_id", # Optional
|
||||
"api_key": "custom-api-key" # Optional - overrides env var
|
||||
"run_id": "my_run_id", # Optional - for short-term memory
|
||||
"includes": "include1", # Optional
|
||||
"excludes": "exclude1", # Optional
|
||||
"infer": True # Optional defaults to True
|
||||
"custom_categories": new_categories # Optional - custom categories for user memory
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
short_term_memory_mem0_oss = ShortTermMemory(embedder_config=mem0_oss_embedder_config) # Short Term Memory with Mem0 OSS
|
||||
short_term_memory_mem0_client = ShortTermMemory(embedder_config=mem0_client_embedder_config) # Short Term Memory with Mem0 Client
|
||||
entity_memory_mem0_oss = EntityMemory(embedder_config=mem0_oss_embedder_config) # Entity Memory with Mem0 OSS
|
||||
entity_memory_mem0_client = EntityMemory(embedder_config=mem0_client_embedder_config) # Short Term Memory with Mem0 Client
|
||||
|
||||
crew = Crew(
|
||||
memory=True,
|
||||
short_term_memory=short_term_memory_mem0_oss, # or short_term_memory_mem0_client
|
||||
entity_memory=entity_memory_mem0_oss # or entity_memory_mem0_client
|
||||
)
|
||||
```
|
||||
|
||||
### Choosing the Right Embedding Provider
|
||||
|
||||
| Provider | Best For | Pros | Cons |
|
||||
|:---------|:----------|:------|:------|
|
||||
| **OpenAI** | General use, reliability | High quality, well-tested | Cost, requires API key |
|
||||
| **Ollama** | Privacy, cost savings | Free, local, private | Requires local setup |
|
||||
| **Google AI** | Google ecosystem | Good performance | Requires Google account |
|
||||
| **Azure OpenAI** | Enterprise, compliance | Enterprise features | Complex setup |
|
||||
| **Cohere** | Multilingual content | Great language support | Specialized use case |
|
||||
| **VoyageAI** | Retrieval tasks | Optimized for search | Newer provider |
|
||||
When selecting an embedding provider, consider factors like performance, privacy, cost, and integration needs.
|
||||
Below is a comparison to help you decide:
|
||||
|
||||
| Provider | Best For | Pros | Cons |
|
||||
| -------------- | ------------------------------ | --------------------------------- | ------------------------- |
|
||||
| **OpenAI** | General use, high reliability | High quality, widely tested | Paid service, API key required |
|
||||
| **Ollama** | Privacy-focused, cost savings | Free, runs locally, fully private | Requires local installation/setup |
|
||||
| **Google AI** | Integration in Google ecosystem| Strong performance, good support | Google account required |
|
||||
| **Azure OpenAI** | Enterprise & compliance needs| Enterprise-grade features, security | More complex setup process |
|
||||
| **Cohere** | Multilingual content handling | Excellent language support | More niche use cases |
|
||||
| **VoyageAI** | Information retrieval & search | Optimized for retrieval tasks | Relatively new provider |
|
||||
| **Mem0** | Per-user personalization | Search-optimized embeddings | Paid service, API key required |
|
||||
|
||||
|
||||
### Environment Variable Configuration
|
||||
|
||||
@@ -623,7 +677,7 @@ for provider in providers_to_test:
|
||||
**Model not found errors:**
|
||||
```python
|
||||
# Verify model availability
|
||||
from crewai.utilities.embedding_configurator import EmbeddingConfigurator
|
||||
from crewai.rag.embeddings.configurator import EmbeddingConfigurator
|
||||
|
||||
configurator = EmbeddingConfigurator()
|
||||
try:
|
||||
@@ -684,67 +738,29 @@ print(f"OpenAI: {openai_time:.2f}s")
|
||||
print(f"Ollama: {ollama_time:.2f}s")
|
||||
```
|
||||
|
||||
## 2. User Memory with Mem0 (Legacy)
|
||||
### Entity Memory batching behavior
|
||||
|
||||
<Warning>
|
||||
**Legacy Approach**: While fully functional, this approach is considered legacy. For new projects requiring user-specific memory, consider using External Memory instead.
|
||||
</Warning>
|
||||
Entity Memory supports batching when saving multiple entities at once. When you pass a list of `EntityMemoryItem`, the system:
|
||||
|
||||
User Memory integrates with [Mem0](https://mem0.ai/) to provide user-specific memory that persists across sessions and integrates with the crew's contextual memory system.
|
||||
- Emits a single MemorySaveStartedEvent with `entity_count`
|
||||
- Saves each entity internally, collecting any partial errors
|
||||
- Emits MemorySaveCompletedEvent with aggregate metadata (saved count, errors)
|
||||
- Raises a partial-save exception if some entities failed (includes counts)
|
||||
|
||||
### Prerequisites
|
||||
```bash
|
||||
pip install mem0ai
|
||||
```
|
||||
This improves performance and observability when writing many entities in one operation.
|
||||
|
||||
### Mem0 Cloud Configuration
|
||||
## 2. External Memory
|
||||
External Memory provides a standalone memory system that operates independently from the crew's built-in memory. This is ideal for specialized memory providers or cross-application memory sharing.
|
||||
|
||||
### Basic External Memory with Mem0
|
||||
```python
|
||||
import os
|
||||
from crewai import Crew, Process
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
|
||||
# Set your Mem0 API key
|
||||
os.environ["MEM0_API_KEY"] = "m0-your-api-key"
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True, # Required for contextual memory integration
|
||||
memory_config={
|
||||
"provider": "mem0",
|
||||
"config": {"user_id": "john"},
|
||||
"user_memory": {} # Required - triggers user memory initialization
|
||||
},
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
### Advanced Mem0 Configuration
|
||||
```python
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True,
|
||||
memory_config={
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"user_id": "john",
|
||||
"org_id": "my_org_id", # Optional
|
||||
"project_id": "my_project_id", # Optional
|
||||
"api_key": "custom-api-key" # Optional - overrides env var
|
||||
},
|
||||
"user_memory": {}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Local Mem0 Configuration
|
||||
```python
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True,
|
||||
memory_config={
|
||||
# Create external memory instance with local Mem0 Configuration
|
||||
external_memory = ExternalMemory(
|
||||
embedder_config={
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"user_id": "john",
|
||||
@@ -761,37 +777,60 @@ crew = Crew(
|
||||
"provider": "openai",
|
||||
"config": {"api_key": "your-api-key", "model": "text-embedding-3-small"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"infer": True # Optional defaults to True
|
||||
},
|
||||
"user_memory": {}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## 3. External Memory (New Approach)
|
||||
|
||||
External Memory provides a standalone memory system that operates independently from the crew's built-in memory. This is ideal for specialized memory providers or cross-application memory sharing.
|
||||
|
||||
### Basic External Memory with Mem0
|
||||
```python
|
||||
import os
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
|
||||
os.environ["MEM0_API_KEY"] = "your-api-key"
|
||||
|
||||
# Create external memory instance
|
||||
external_memory = ExternalMemory(
|
||||
embedder_config={
|
||||
"provider": "mem0",
|
||||
"config": {"user_id": "U-123"}
|
||||
}
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
external_memory=external_memory, # Separate from basic memory
|
||||
external_memory=external_memory, # Separate from basic memory
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
### Advanced External Memory with Mem0 Client
|
||||
When using Mem0 Client, you can customize the memory configuration further, by using parameters like 'includes', 'excludes', 'custom_categories', 'infer' and 'run_id' (this is only for short-term memory).
|
||||
You can find more details in the [Mem0 documentation](https://docs.mem0.ai/).
|
||||
|
||||
```python
|
||||
import os
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
|
||||
new_categories = [
|
||||
{"lifestyle_management_concerns": "Tracks daily routines, habits, hobbies and interests including cooking, time management and work-life balance"},
|
||||
{"seeking_structure": "Documents goals around creating routines, schedules, and organized systems in various life areas"},
|
||||
{"personal_information": "Basic information about the user including name, preferences, and personality traits"}
|
||||
]
|
||||
|
||||
os.environ["MEM0_API_KEY"] = "your-api-key"
|
||||
|
||||
# Create external memory instance with Mem0 Client
|
||||
external_memory = ExternalMemory(
|
||||
embedder_config={
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"user_id": "john",
|
||||
"org_id": "my_org_id", # Optional
|
||||
"project_id": "my_project_id", # Optional
|
||||
"api_key": "custom-api-key" # Optional - overrides env var
|
||||
"run_id": "my_run_id", # Optional - for short-term memory
|
||||
"includes": "include1", # Optional
|
||||
"excludes": "exclude1", # Optional
|
||||
"infer": True # Optional defaults to True
|
||||
"custom_categories": new_categories # Optional - custom categories for user memory
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
external_memory=external_memory, # Separate from basic memory
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
@@ -830,17 +869,18 @@ crew = Crew(
|
||||
)
|
||||
```
|
||||
|
||||
## Memory System Comparison
|
||||
## 🧠 Memory System Comparison
|
||||
|
||||
| **Category** | **Feature** | **Basic Memory** | **External Memory** |
|
||||
|---------------------|------------------------|-----------------------------|------------------------------|
|
||||
| **Ease of Use** | Setup Complexity | Simple | Moderate |
|
||||
| | Integration | Built-in (contextual) | Standalone |
|
||||
| **Persistence** | Storage | Local files | Custom / Mem0 |
|
||||
| | Cross-session Support | ✅ | ✅ |
|
||||
| **Personalization** | User-specific Memory | ❌ | ✅ |
|
||||
| | Custom Providers | Limited | Any provider |
|
||||
| **Use Case Fit** | Recommended For | Most general use cases | Specialized / custom needs |
|
||||
|
||||
| Feature | Basic Memory | User Memory (Legacy) | External Memory |
|
||||
|---------|-------------|---------------------|----------------|
|
||||
| **Setup Complexity** | Simple | Medium | Medium |
|
||||
| **Integration** | Built-in contextual | Contextual + User-specific | Standalone |
|
||||
| **Storage** | Local files | Mem0 Cloud/Local | Custom/Mem0 |
|
||||
| **Cross-session** | ✅ | ✅ | ✅ |
|
||||
| **User-specific** | ❌ | ✅ | ✅ |
|
||||
| **Custom providers** | Limited | Mem0 only | Any provider |
|
||||
| **Recommended for** | Most use cases | Legacy projects | Specialized needs |
|
||||
|
||||
## Supported Embedding Providers
|
||||
|
||||
@@ -1012,8 +1052,8 @@ CrewAI emits the following memory-related events:
|
||||
Track memory operation timing to optimize your application:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
BaseEventListener,
|
||||
MemoryQueryCompletedEvent,
|
||||
MemorySaveCompletedEvent
|
||||
)
|
||||
@@ -1047,8 +1087,8 @@ memory_monitor = MemoryPerformanceMonitor()
|
||||
Log memory operations for debugging and insights:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
BaseEventListener,
|
||||
MemorySaveStartedEvent,
|
||||
MemoryQueryStartedEvent,
|
||||
MemoryRetrievalCompletedEvent
|
||||
@@ -1088,8 +1128,8 @@ memory_logger = MemoryLogger()
|
||||
Capture and respond to memory errors:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
BaseEventListener,
|
||||
MemorySaveFailedEvent,
|
||||
MemoryQueryFailedEvent
|
||||
)
|
||||
@@ -1138,8 +1178,8 @@ error_tracker = MemoryErrorTracker(notify_email="admin@example.com")
|
||||
Memory events can be forwarded to analytics and monitoring platforms to track performance metrics, detect anomalies, and visualize memory usage patterns:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
from crewai.utilities.events import (
|
||||
from crewai.events import (
|
||||
BaseEventListener,
|
||||
MemoryQueryCompletedEvent,
|
||||
MemorySaveCompletedEvent
|
||||
)
|
||||
|
||||
@@ -54,9 +54,17 @@ crew = Crew(
|
||||
| **Markdown** _(optional)_ | `markdown` | `Optional[bool]` | Whether the task should instruct the agent to return the final answer formatted in Markdown. Defaults to False. |
|
||||
| **Config** _(optional)_ | `config` | `Optional[Dict[str, Any]]` | Task-specific configuration parameters. |
|
||||
| **Output File** _(optional)_ | `output_file` | `Optional[str]` | File path for storing the task output. |
|
||||
| **Create Directory** _(optional)_ | `create_directory` | `Optional[bool]` | Whether to create the directory for output_file if it doesn't exist. Defaults to True. |
|
||||
| **Output JSON** _(optional)_ | `output_json` | `Optional[Type[BaseModel]]` | A Pydantic model to structure the JSON output. |
|
||||
| **Output Pydantic** _(optional)_ | `output_pydantic` | `Optional[Type[BaseModel]]` | A Pydantic model for task output. |
|
||||
| **Callback** _(optional)_ | `callback` | `Optional[Any]` | Function/object to be executed after task completion. |
|
||||
| **Guardrail** _(optional)_ | `guardrail` | `Optional[Callable]` | Function to validate task output before proceeding to next task. |
|
||||
| **Guardrail Max Retries** _(optional)_ | `guardrail_max_retries` | `Optional[int]` | Maximum number of retries when guardrail validation fails. Defaults to 3. |
|
||||
|
||||
<Note type="warning" title="Deprecated: max_retries">
|
||||
The task attribute `max_retries` is deprecated and will be removed in v1.0.0.
|
||||
Use `guardrail_max_retries` instead to control retry attempts when a guardrail fails.
|
||||
</Note>
|
||||
|
||||
## Creating Tasks
|
||||
|
||||
@@ -332,9 +340,11 @@ Task guardrails provide a way to validate and transform task outputs before they
|
||||
are passed to the next task. This feature helps ensure data quality and provides
|
||||
feedback to agents when their output doesn't meet specific criteria.
|
||||
|
||||
### Using Task Guardrails
|
||||
Guardrails are implemented as Python functions that contain custom validation logic, giving you complete control over the validation process and ensuring reliable, deterministic results.
|
||||
|
||||
To add a guardrail to a task, provide a validation function through the `guardrail` parameter:
|
||||
### Function-Based Guardrails
|
||||
|
||||
To add a function-based guardrail to a task, provide a validation function through the `guardrail` parameter:
|
||||
|
||||
```python Code
|
||||
from typing import Tuple, Union, Dict, Any
|
||||
@@ -372,9 +382,7 @@ blog_task = Task(
|
||||
- On success: it returns a tuple of `(bool, Any)`. For example: `(True, validated_result)`
|
||||
- On Failure: it returns a tuple of `(bool, str)`. For example: `(False, "Error message explain the failure")`
|
||||
|
||||
### LLMGuardrail
|
||||
|
||||
The `LLMGuardrail` class offers a robust mechanism for validating task outputs.
|
||||
|
||||
### Error Handling Best Practices
|
||||
|
||||
@@ -429,7 +437,7 @@ When a guardrail returns `(False, error)`:
|
||||
2. The agent attempts to fix the issue
|
||||
3. The process repeats until:
|
||||
- The guardrail returns `(True, result)`
|
||||
- Maximum retries are reached
|
||||
- Maximum retries are reached (`guardrail_max_retries`)
|
||||
|
||||
Example with retry handling:
|
||||
```python Code
|
||||
@@ -450,7 +458,7 @@ task = Task(
|
||||
expected_output="A valid JSON object",
|
||||
agent=analyst,
|
||||
guardrail=validate_json_output,
|
||||
max_retries=3 # Limit retry attempts
|
||||
guardrail_max_retries=3 # Limit retry attempts
|
||||
)
|
||||
```
|
||||
|
||||
@@ -798,184 +806,91 @@ While creating and executing tasks, certain validation mechanisms are in place t
|
||||
|
||||
These validations help in maintaining the consistency and reliability of task executions within the crewAI framework.
|
||||
|
||||
## Task Guardrails
|
||||
|
||||
Task guardrails provide a powerful way to validate, transform, or filter task outputs before they are passed to the next task. Guardrails are optional functions that execute before the next task starts, allowing you to ensure that task outputs meet specific requirements or formats.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
#### Define your own logic to validate
|
||||
|
||||
```python Code
|
||||
from typing import Tuple, Union
|
||||
from crewai import Task
|
||||
|
||||
def validate_json_output(result: str) -> Tuple[bool, Union[dict, str]]:
|
||||
"""Validate that the output is valid JSON."""
|
||||
try:
|
||||
json_data = json.loads(result)
|
||||
return (True, json_data)
|
||||
except json.JSONDecodeError:
|
||||
return (False, "Output must be valid JSON")
|
||||
|
||||
task = Task(
|
||||
description="Generate JSON data",
|
||||
expected_output="Valid JSON object",
|
||||
guardrail=validate_json_output
|
||||
)
|
||||
```
|
||||
|
||||
#### Leverage a no-code approach for validation
|
||||
|
||||
```python Code
|
||||
from crewai import Task
|
||||
|
||||
task = Task(
|
||||
description="Generate JSON data",
|
||||
expected_output="Valid JSON object",
|
||||
guardrail="Ensure the response is a valid JSON object"
|
||||
)
|
||||
```
|
||||
|
||||
#### Using YAML
|
||||
|
||||
```yaml
|
||||
research_task:
|
||||
...
|
||||
guardrail: make sure each bullet contains a minimum of 100 words
|
||||
...
|
||||
```
|
||||
|
||||
```python Code
|
||||
@CrewBase
|
||||
class InternalCrew:
|
||||
agents_config = "config/agents.yaml"
|
||||
tasks_config = "config/tasks.yaml"
|
||||
|
||||
...
|
||||
@task
|
||||
def research_task(self):
|
||||
return Task(config=self.tasks_config["research_task"]) # type: ignore[index]
|
||||
...
|
||||
```
|
||||
|
||||
|
||||
#### Use custom models for code generation
|
||||
|
||||
```python Code
|
||||
from crewai import Task
|
||||
from crewai.llm import LLM
|
||||
|
||||
task = Task(
|
||||
description="Generate JSON data",
|
||||
expected_output="Valid JSON object",
|
||||
guardrail=LLMGuardrail(
|
||||
description="Ensure the response is a valid JSON object",
|
||||
llm=LLM(model="gpt-4o-mini"),
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### How Guardrails Work
|
||||
|
||||
1. **Optional Attribute**: Guardrails are an optional attribute at the task level, allowing you to add validation only where needed.
|
||||
2. **Execution Timing**: The guardrail function is executed before the next task starts, ensuring valid data flow between tasks.
|
||||
3. **Return Format**: Guardrails must return a tuple of `(success, data)`:
|
||||
- If `success` is `True`, `data` is the validated/transformed result
|
||||
- If `success` is `False`, `data` is the error message
|
||||
4. **Result Routing**:
|
||||
- On success (`True`), the result is automatically passed to the next task
|
||||
- On failure (`False`), the error is sent back to the agent to generate a new answer
|
||||
|
||||
### Common Use Cases
|
||||
|
||||
#### Data Format Validation
|
||||
```python Code
|
||||
def validate_email_format(result: str) -> Tuple[bool, Union[str, str]]:
|
||||
"""Ensure the output contains a valid email address."""
|
||||
import re
|
||||
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
|
||||
if re.match(email_pattern, result.strip()):
|
||||
return (True, result.strip())
|
||||
return (False, "Output must be a valid email address")
|
||||
```
|
||||
|
||||
#### Content Filtering
|
||||
```python Code
|
||||
def filter_sensitive_info(result: str) -> Tuple[bool, Union[str, str]]:
|
||||
"""Remove or validate sensitive information."""
|
||||
sensitive_patterns = ['SSN:', 'password:', 'secret:']
|
||||
for pattern in sensitive_patterns:
|
||||
if pattern.lower() in result.lower():
|
||||
return (False, f"Output contains sensitive information ({pattern})")
|
||||
return (True, result)
|
||||
```
|
||||
|
||||
#### Data Transformation
|
||||
```python Code
|
||||
def normalize_phone_number(result: str) -> Tuple[bool, Union[str, str]]:
|
||||
"""Ensure phone numbers are in a consistent format."""
|
||||
import re
|
||||
digits = re.sub(r'\D', '', result)
|
||||
if len(digits) == 10:
|
||||
formatted = f"({digits[:3]}) {digits[3:6]}-{digits[6:]}"
|
||||
return (True, formatted)
|
||||
return (False, "Output must be a 10-digit phone number")
|
||||
```
|
||||
|
||||
### Advanced Features
|
||||
|
||||
#### Chaining Multiple Validations
|
||||
```python Code
|
||||
def chain_validations(*validators):
|
||||
"""Chain multiple validators together."""
|
||||
def combined_validator(result):
|
||||
for validator in validators:
|
||||
success, data = validator(result)
|
||||
if not success:
|
||||
return (False, data)
|
||||
result = data
|
||||
return (True, result)
|
||||
return combined_validator
|
||||
|
||||
# Usage
|
||||
task = Task(
|
||||
description="Get user contact info",
|
||||
expected_output="Email and phone",
|
||||
guardrail=chain_validations(
|
||||
validate_email_format,
|
||||
filter_sensitive_info
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
#### Custom Retry Logic
|
||||
```python Code
|
||||
task = Task(
|
||||
description="Generate data",
|
||||
expected_output="Valid data",
|
||||
guardrail=validate_data,
|
||||
max_retries=5 # Override default retry limit
|
||||
)
|
||||
```
|
||||
|
||||
## Creating Directories when Saving Files
|
||||
|
||||
You can now specify if a task should create directories when saving its output to a file. This is particularly useful for organizing outputs and ensuring that file paths are correctly structured.
|
||||
The `create_directory` parameter controls whether CrewAI should automatically create directories when saving task outputs to files. This feature is particularly useful for organizing outputs and ensuring that file paths are correctly structured, especially when working with complex project hierarchies.
|
||||
|
||||
### Default Behavior
|
||||
|
||||
By default, `create_directory=True`, which means CrewAI will automatically create any missing directories in the output file path:
|
||||
|
||||
```python Code
|
||||
# ...
|
||||
|
||||
save_output_task = Task(
|
||||
description='Save the summarized AI news to a file',
|
||||
expected_output='File saved successfully',
|
||||
agent=research_agent,
|
||||
tools=[file_save_tool],
|
||||
output_file='outputs/ai_news_summary.txt',
|
||||
create_directory=True
|
||||
# Default behavior - directories are created automatically
|
||||
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', # Creates 'reports/2025/' if it doesn't exist
|
||||
markdown=True
|
||||
)
|
||||
```
|
||||
|
||||
#...
|
||||
### Disabling Directory Creation
|
||||
|
||||
If you want to prevent automatic directory creation and ensure that the directory already exists, set `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 Configuration
|
||||
|
||||
You can also configure this behavior in your YAML task definitions:
|
||||
|
||||
```yaml tasks.yaml
|
||||
analysis_task:
|
||||
description: >
|
||||
Generate quarterly financial analysis
|
||||
expected_output: >
|
||||
A comprehensive financial report with quarterly insights
|
||||
agent: financial_analyst
|
||||
output_file: reports/quarterly/q4_2024_analysis.pdf
|
||||
create_directory: true # Automatically create 'reports/quarterly/' directory
|
||||
|
||||
audit_task:
|
||||
description: >
|
||||
Perform compliance audit and save to existing audit directory
|
||||
expected_output: >
|
||||
A compliance audit report
|
||||
agent: auditor
|
||||
output_file: audit/compliance_report.md
|
||||
create_directory: false # Directory must already exist
|
||||
```
|
||||
|
||||
### Use Cases
|
||||
|
||||
**Automatic Directory Creation (`create_directory=True`):**
|
||||
- Development and prototyping environments
|
||||
- Dynamic report generation with date-based folders
|
||||
- Automated workflows where directory structure may vary
|
||||
- Multi-tenant applications with user-specific folders
|
||||
|
||||
**Manual Directory Management (`create_directory=False`):**
|
||||
- Production environments with strict file system controls
|
||||
- Security-sensitive applications where directories must be pre-configured
|
||||
- Systems with specific permission requirements
|
||||
- Compliance environments where directory creation is audited
|
||||
|
||||
### Error Handling
|
||||
|
||||
When `create_directory=False` and the directory doesn't exist, CrewAI will raise a `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
|
||||
```
|
||||
|
||||
Check out the video below to see how to use structured outputs in CrewAI:
|
||||
|
||||
@@ -21,13 +21,17 @@ To use the training feature, follow these steps:
|
||||
3. Run the following command:
|
||||
|
||||
```shell
|
||||
crewai train -n <n_iterations> <filename> (optional)
|
||||
crewai train -n <n_iterations> -f <filename.pkl>
|
||||
```
|
||||
<Tip>
|
||||
Replace `<n_iterations>` with the desired number of training iterations and `<filename>` with the appropriate filename ending with `.pkl`.
|
||||
</Tip>
|
||||
|
||||
### Training Your Crew Programmatically
|
||||
<Note>
|
||||
If you omit `-f`, the output defaults to `trained_agents_data.pkl` in the current working directory. You can pass an absolute path to control where the file is written.
|
||||
</Note>
|
||||
|
||||
### Training your Crew programmatically
|
||||
|
||||
To train your crew programmatically, use the following steps:
|
||||
|
||||
@@ -51,19 +55,65 @@ except Exception as e:
|
||||
raise Exception(f"An error occurred while training the crew: {e}")
|
||||
```
|
||||
|
||||
### Key Points to Note
|
||||
## How trained data is used by agents
|
||||
|
||||
- **Positive Integer Requirement:** Ensure that the number of iterations (`n_iterations`) is a positive integer. The code will raise a `ValueError` if this condition is not met.
|
||||
- **Filename Requirement:** Ensure that the filename ends with `.pkl`. The code will raise a `ValueError` if this condition is not met.
|
||||
- **Error Handling:** The code handles subprocess errors and unexpected exceptions, providing error messages to the user.
|
||||
CrewAI uses the training artifacts in two ways: during training to incorporate your human feedback, and after training to guide agents with consolidated suggestions.
|
||||
|
||||
It is important to note that the training process may take some time, depending on the complexity of your agents and will also require your feedback on each iteration.
|
||||
### Training data flow
|
||||
|
||||
Once the training is complete, your agents will be equipped with enhanced capabilities and knowledge, ready to tackle complex tasks and provide more consistent and valuable insights.
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Start training<br/>CLI: crewai train -n -f<br/>or Python: crew.train(...)"] --> B["Setup training mode<br/>- task.human_input = true<br/>- disable delegation<br/>- init training_data.pkl + trained file"]
|
||||
|
||||
Remember to regularly update and retrain your agents to ensure they stay up-to-date with the latest information and advancements in the field.
|
||||
subgraph "Iterations"
|
||||
direction LR
|
||||
C["Iteration i<br/>initial_output"] --> D["User human_feedback"]
|
||||
D --> E["improved_output"]
|
||||
E --> F["Append to training_data.pkl<br/>by agent_id and iteration"]
|
||||
end
|
||||
|
||||
Happy training with CrewAI! 🚀
|
||||
B --> C
|
||||
F --> G{"More iterations?"}
|
||||
G -- "Yes" --> C
|
||||
G -- "No" --> H["Evaluate per agent<br/>aggregate iterations"]
|
||||
|
||||
H --> I["Consolidate<br/>suggestions[] + quality + final_summary"]
|
||||
I --> J["Save by agent role to trained file<br/>(default: trained_agents_data.pkl)"]
|
||||
|
||||
J --> K["Normal (non-training) runs"]
|
||||
K --> L["Auto-load suggestions<br/>from trained_agents_data.pkl"]
|
||||
L --> M["Append to prompt<br/>for consistent improvements"]
|
||||
```
|
||||
|
||||
### During training runs
|
||||
|
||||
- On each iteration, the system records for every agent:
|
||||
- `initial_output`: the agent’s first answer
|
||||
- `human_feedback`: your inline feedback when prompted
|
||||
- `improved_output`: the agent’s follow-up answer after feedback
|
||||
- This data is stored in a working file named `training_data.pkl` keyed by the agent’s internal ID and iteration.
|
||||
- While training is active, the agent automatically appends your prior human feedback to its prompt to enforce those instructions on subsequent attempts within the training session.
|
||||
Training is interactive: tasks set `human_input = true`, so running in a non-interactive environment will block on user input.
|
||||
|
||||
### After training completes
|
||||
|
||||
- When `train(...)` finishes, CrewAI evaluates the collected training data per agent and produces a consolidated result containing:
|
||||
- `suggestions`: clear, actionable instructions distilled from your feedback and the difference between initial/improved outputs
|
||||
- `quality`: a 0–10 score capturing improvement
|
||||
- `final_summary`: a step-by-step set of action items for future tasks
|
||||
- These consolidated results are saved to the filename you pass to `train(...)` (default via CLI is `trained_agents_data.pkl`). Entries are keyed by the agent’s `role` so they can be applied across sessions.
|
||||
- During normal (non-training) execution, each agent automatically loads its consolidated `suggestions` and appends them to the task prompt as mandatory instructions. This gives you consistent improvements without changing your agent definitions.
|
||||
|
||||
### File summary
|
||||
|
||||
- `training_data.pkl` (ephemeral, per-session):
|
||||
- Structure: `agent_id -> { iteration_number: { initial_output, human_feedback, improved_output } }`
|
||||
- Purpose: capture raw data and human feedback during training
|
||||
- Location: saved in the current working directory (CWD)
|
||||
- `trained_agents_data.pkl` (or your custom filename):
|
||||
- Structure: `agent_role -> { suggestions: string[], quality: number, final_summary: string }`
|
||||
- Purpose: persist consolidated guidance for future runs
|
||||
- Location: written to the CWD by default; use `-f` to set a custom (including absolute) path
|
||||
|
||||
## Small Language Model Considerations
|
||||
|
||||
@@ -129,3 +179,18 @@ Happy training with CrewAI! 🚀
|
||||
</Warning>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Key Points to Note
|
||||
|
||||
- **Positive Integer Requirement:** Ensure that the number of iterations (`n_iterations`) is a positive integer. The code will raise a `ValueError` if this condition is not met.
|
||||
- **Filename Requirement:** Ensure that the filename ends with `.pkl`. The code will raise a `ValueError` if this condition is not met.
|
||||
- **Error Handling:** The code handles subprocess errors and unexpected exceptions, providing error messages to the user.
|
||||
- Trained guidance is applied at prompt time; it does not modify your Python/YAML agent configuration.
|
||||
- Agents automatically load trained suggestions from a file named `trained_agents_data.pkl` located in the current working directory. If you trained to a different filename, either rename it to `trained_agents_data.pkl` before running, or adjust the loader in code.
|
||||
- You can change the output filename when calling `crewai train` with `-f/--filename`. Absolute paths are supported if you want to save outside the CWD.
|
||||
|
||||
It is important to note that the training process may take some time, depending on the complexity of your agents and will also require your feedback on each iteration.
|
||||
|
||||
Once the training is complete, your agents will be equipped with enhanced capabilities and knowledge, ready to tackle complex tasks and provide more consistent and valuable insights.
|
||||
|
||||
Remember to regularly update and retrain your agents to ensure they stay up-to-date with the latest information and advancements in the field.
|
||||
|
||||
@@ -59,7 +59,7 @@ Before using Authentication Integrations, ensure you have:
|
||||
3. Click **Connect** on your desired service from the Authentication Integrations section
|
||||
4. Complete the OAuth authentication flow
|
||||
5. Grant necessary permissions for your use case
|
||||
6. Get your Enterprise Token from your [CrewAI Enterprise](https://app.crewai.com) account page - https://app.crewai.com/crewai_plus/settings/account
|
||||
6. All set! Get your Enterprise Token from your [CrewAI Enterprise](https://app.crewai.com) in **Integration** tab
|
||||
|
||||
<Frame>
|
||||

|
||||
|
||||
103
docs/en/enterprise/features/rbac.mdx
Normal file
@@ -0,0 +1,103 @@
|
||||
---
|
||||
title: "Role-Based Access Control (RBAC)"
|
||||
description: "Control access to crews, tools, and data with roles, scopes, and granular permissions."
|
||||
icon: "shield"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
RBAC in CrewAI Enterprise enables secure, scalable access management through a combination of organization‑level roles and automation‑level visibility controls.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/users_and_roles.png" alt="RBAC overview in CrewAI Enterprise" />
|
||||
|
||||
</Frame>
|
||||
|
||||
## Users and Roles
|
||||
|
||||
Each member in your CrewAI workspace is assigned a role, which determines their access across various features.
|
||||
|
||||
You can:
|
||||
|
||||
- Use predefined roles (Owner, Member)
|
||||
- Create custom roles tailored to specific permissions
|
||||
- Assign roles at any time through the settings panel
|
||||
|
||||
You can configure users and roles in Settings → Roles.
|
||||
|
||||
<Steps>
|
||||
<Step title="Open Roles settings">
|
||||
Go to <b>Settings → Roles</b> in CrewAI Enterprise.
|
||||
</Step>
|
||||
<Step title="Choose a role type">
|
||||
Use a predefined role (<b>Owner</b>, <b>Member</b>) or click <b>Create role</b> to define a custom one.
|
||||
</Step>
|
||||
<Step title="Assign to members">
|
||||
Select users and assign the role. You can change this anytime.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Configuration summary
|
||||
|
||||
| Area | Where to configure | Options |
|
||||
|:---|:---|:---|
|
||||
| Users & Roles | Settings → Roles | Predefined: Owner, Member; Custom roles |
|
||||
| Automation visibility | Automation → Settings → Visibility | Private; Whitelist users/roles |
|
||||
|
||||
## Automation‑level Access Control
|
||||
|
||||
In addition to organization‑wide roles, CrewAI Automations support fine‑grained visibility settings that let you restrict access to specific automations by user or role.
|
||||
|
||||
This is useful for:
|
||||
|
||||
- Keeping sensitive or experimental automations private
|
||||
- Managing visibility across large teams or external collaborators
|
||||
- Testing automations in isolated contexts
|
||||
|
||||
Deployments can be configured as private, meaning only whitelisted users and roles will be able to:
|
||||
|
||||
- View the deployment
|
||||
- Run it or interact with its API
|
||||
- Access its logs, metrics, and settings
|
||||
|
||||
The organization owner always has access, regardless of visibility settings.
|
||||
|
||||
You can configure automation‑level access control in Automation → Settings → Visibility tab.
|
||||
|
||||
<Steps>
|
||||
<Step title="Open Visibility tab">
|
||||
Navigate to <b>Automation → Settings → Visibility</b>.
|
||||
</Step>
|
||||
<Step title="Set visibility">
|
||||
Choose <b>Private</b> to restrict access. The organization owner always retains access.
|
||||
</Step>
|
||||
<Step title="Whitelist access">
|
||||
Add specific users and roles allowed to view, run, and access logs/metrics/settings.
|
||||
</Step>
|
||||
<Step title="Save and verify">
|
||||
Save changes, then confirm that non‑whitelisted users cannot view or run the automation.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Private visibility: access outcomes
|
||||
|
||||
| Action | Owner | Whitelisted user/role | Not whitelisted |
|
||||
|:---|:---|:---|:---|
|
||||
| View automation | ✓ | ✓ | ✗ |
|
||||
| Run automation/API | ✓ | ✓ | ✗ |
|
||||
| Access logs/metrics/settings | ✓ | ✓ | ✗ |
|
||||
|
||||
<Tip>
|
||||
The organization owner always has access. In private mode, only whitelisted users and roles can view, run, and access logs/metrics/settings.
|
||||
</Tip>
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/visibility.png" alt="Automation Visibility settings in CrewAI Enterprise" />
|
||||
|
||||
</Frame>
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with RBAC questions.
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -35,6 +35,22 @@ crewai tool install <tool-name>
|
||||
|
||||
This installs the tool and adds it to `pyproject.toml`.
|
||||
|
||||
You can use the tool by importing it and adding it to your agents:
|
||||
|
||||
```python
|
||||
from your_tool.tool import YourTool
|
||||
|
||||
custom_tool = YourTool()
|
||||
|
||||
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=[custom_tool],
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## Creating and Publishing Tools
|
||||
|
||||
To create a new tool project:
|
||||
|
||||
@@ -141,6 +141,16 @@ Traces are invaluable for troubleshooting issues with your crews:
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Performance and batching
|
||||
|
||||
CrewAI batches trace uploads to reduce overhead on high-volume runs:
|
||||
|
||||
- A TraceBatchManager buffers events and sends them in batches via the Plus API client
|
||||
- Reduces network chatter and improves reliability on flaky connections
|
||||
- Automatically enabled in the default trace listener; no configuration needed
|
||||
|
||||
This yields more stable tracing under load while preserving detailed task/agent telemetry.
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with trace analysis or any other CrewAI Enterprise features.
|
||||
</Card>
|
||||
178
docs/en/enterprise/guides/automation-triggers.mdx
Normal file
@@ -0,0 +1,178 @@
|
||||
---
|
||||
title: "Automation Triggers"
|
||||
description: "Automatically execute your CrewAI workflows when specific events occur in connected integrations"
|
||||
icon: "bolt"
|
||||
---
|
||||
|
||||
Automation triggers enable you to automatically run your CrewAI deployments when specific events occur in your connected integrations, creating powerful event-driven workflows that respond to real-time changes in your business systems.
|
||||
|
||||
## Overview
|
||||
|
||||
With automation triggers, you can:
|
||||
|
||||
- **Respond to real-time events** - Automatically execute workflows when specific conditions are met
|
||||
- **Integrate with external systems** - Connect with platforms like Gmail, Outlook, OneDrive, JIRA, Slack, Stripe and more
|
||||
- **Scale your automation** - Handle high-volume events without manual intervention
|
||||
- **Maintain context** - Access trigger data within your crews and flows
|
||||
|
||||
## Managing Automation Triggers
|
||||
|
||||
### Viewing Available Triggers
|
||||
|
||||
To access and manage your automation triggers:
|
||||
|
||||
1. Navigate to your deployment in the CrewAI dashboard
|
||||
2. Click on the **Triggers** tab to view all available trigger integrations
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/list-available-triggers.png" alt="List of available automation triggers" />
|
||||
</Frame>
|
||||
|
||||
This view shows all the trigger integrations available for your deployment, along with their current connection status.
|
||||
|
||||
### Enabling and Disabling Triggers
|
||||
|
||||
Each trigger can be easily enabled or disabled using the toggle switch:
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/trigger-selected.png" alt="Enable or disable triggers with toggle" />
|
||||
</Frame>
|
||||
|
||||
- **Enabled (blue toggle)**: The trigger is active and will automatically execute your deployment when the specified events occur
|
||||
- **Disabled (gray toggle)**: The trigger is inactive and will not respond to events
|
||||
|
||||
Simply click the toggle to change the trigger state. Changes take effect immediately.
|
||||
|
||||
### Monitoring Trigger Executions
|
||||
|
||||
Track the performance and history of your triggered executions:
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/list-executions.png" alt="List of executions triggered by automation" />
|
||||
</Frame>
|
||||
|
||||
## Building Automation
|
||||
|
||||
Before building your automation, it's helpful to understand the structure of trigger payloads that your crews and flows will receive.
|
||||
|
||||
### Payload Samples Repository
|
||||
|
||||
We maintain a comprehensive repository with sample payloads from various trigger sources to help you build and test your automations:
|
||||
|
||||
**🔗 [CrewAI Enterprise Trigger Payload Samples](https://github.com/crewAIInc/crewai-enterprise-trigger-payload-samples)**
|
||||
|
||||
This repository contains:
|
||||
|
||||
- **Real payload examples** from different trigger sources (Gmail, Google Drive, etc.)
|
||||
- **Payload structure documentation** showing the format and available fields
|
||||
|
||||
### Triggers with Crew
|
||||
|
||||
Your existing crew definitions work seamlessly with triggers, you just need to have a task to parse the received payload:
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class MyAutomatedCrew:
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'],
|
||||
)
|
||||
|
||||
@task
|
||||
def parse_trigger_payload(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['parse_trigger_payload'],
|
||||
agent=self.researcher(),
|
||||
)
|
||||
|
||||
@task
|
||||
def analyze_trigger_content(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['analyze_trigger_data'],
|
||||
agent=self.researcher(),
|
||||
)
|
||||
```
|
||||
|
||||
The crew will automatically receive and can access the trigger payload through the standard CrewAI context mechanisms.
|
||||
|
||||
<Note>
|
||||
Crew and Flow inputs can include `crewai_trigger_payload`. CrewAI automatically injects this payload:
|
||||
- Tasks: appended to the first task's description by default ("Trigger Payload: {crewai_trigger_payload}")
|
||||
- Control via `allow_crewai_trigger_context`: set `True` to always inject, `False` to never inject
|
||||
- Flows: any `@start()` method that accepts a `crewai_trigger_payload` parameter will receive it
|
||||
</Note>
|
||||
|
||||
### Integration with Flows
|
||||
|
||||
For flows, you have more control over how trigger data is handled:
|
||||
|
||||
#### Accessing Trigger Payload
|
||||
|
||||
All `@start()` methods in your flows will accept an additional parameter called `crewai_trigger_payload`:
|
||||
|
||||
```python
|
||||
from crewai.flow import Flow, start, listen
|
||||
|
||||
class MyAutomatedFlow(Flow):
|
||||
@start()
|
||||
def handle_trigger(self, crewai_trigger_payload: dict = None):
|
||||
"""
|
||||
This start method can receive trigger data
|
||||
"""
|
||||
if crewai_trigger_payload:
|
||||
# Process the trigger data
|
||||
trigger_id = crewai_trigger_payload.get('id')
|
||||
event_data = crewai_trigger_payload.get('payload', {})
|
||||
|
||||
# Store in flow state for use by other methods
|
||||
self.state.trigger_id = trigger_id
|
||||
self.state.trigger_type = event_data
|
||||
|
||||
return event_data
|
||||
|
||||
# Handle manual execution
|
||||
return None
|
||||
|
||||
@listen(handle_trigger)
|
||||
def process_data(self, trigger_data):
|
||||
"""
|
||||
Process the data from the trigger
|
||||
"""
|
||||
# ... process the trigger
|
||||
```
|
||||
|
||||
#### Triggering Crews from Flows
|
||||
|
||||
When kicking off a crew within a flow that was triggered, pass the trigger payload as it:
|
||||
|
||||
```python
|
||||
@start()
|
||||
def delegate_to_crew(self, crewai_trigger_payload: dict = None):
|
||||
"""
|
||||
Delegate processing to a specialized crew
|
||||
"""
|
||||
crew = MySpecializedCrew()
|
||||
|
||||
# Pass the trigger payload to the crew
|
||||
result = crew.crew().kickoff(
|
||||
inputs={
|
||||
'a_custom_parameter': "custom_value",
|
||||
'crewai_trigger_payload': crewai_trigger_payload
|
||||
},
|
||||
)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Trigger not firing:**
|
||||
- Verify the trigger is enabled
|
||||
- Check integration connection status
|
||||
|
||||
**Execution failures:**
|
||||
- Check the execution logs for error details
|
||||
- If you are developing, make sure the inputs include the `crewai_trigger_payload` parameter with the correct payload
|
||||
|
||||
Automation triggers transform your CrewAI deployments into responsive, event-driven systems that can seamlessly integrate with your existing business processes and tools.
|
||||
22
docs/en/examples/cookbooks.mdx
Normal file
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: CrewAI Cookbooks
|
||||
description: Feature-focused quickstarts and notebooks for learning patterns fast.
|
||||
icon: book
|
||||
---
|
||||
|
||||
## Quickstarts & Demos
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Task Guardrails" icon="shield-check" href="https://github.com/crewAIInc/crewAI-quickstarts/tree/main/Task%20Guardrails">
|
||||
Interactive notebooks for hands-on exploration.
|
||||
</Card>
|
||||
<Card title="Browse Quickstarts" icon="bolt" href="https://github.com/crewAIInc/crewAI-quickstarts">
|
||||
Feature demos and small projects showcasing specific CrewAI capabilities.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
Use Cookbooks to learn a pattern quickly, then jump to Full Examples for production‑grade implementations.
|
||||
</Tip>
|
||||
|
||||
|
||||
@@ -1,62 +1,85 @@
|
||||
---
|
||||
title: CrewAI Examples
|
||||
description: A collection of examples that show how to use CrewAI framework to automate workflows.
|
||||
description: Explore curated examples organized by Crews, Flows, Integrations, and Notebooks.
|
||||
icon: rocket-launch
|
||||
---
|
||||
|
||||
## Crews
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="Marketing Strategy"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/crewAIInc/crewAI-examples/tree/main/marketing_strategy"
|
||||
icon="bullhorn"
|
||||
iconType="solid"
|
||||
>
|
||||
Automate marketing strategy creation with CrewAI.
|
||||
<Card title="Marketing Strategy" icon="bullhorn" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews/marketing_strategy">
|
||||
Multi‑agent marketing campaign planning.
|
||||
</Card>
|
||||
<Card title="Surprise Trip" icon="plane" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews/surprise_trip">
|
||||
Personalized surprise travel planning.
|
||||
</Card>
|
||||
<Card title="Match Profile to Positions" icon="id-card" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews/match_profile_to_positions">
|
||||
CV‑to‑job matching with vector search.
|
||||
</Card>
|
||||
<Card title="Job Posting" icon="newspaper" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews/job-posting">
|
||||
Automated job description creation.
|
||||
</Card>
|
||||
<Card title="Game Builder Crew" icon="gamepad" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews/game-builder-crew">
|
||||
Multi‑agent team that designs and builds Python games.
|
||||
</Card>
|
||||
<Card title="Recruitment" icon="user-group" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews/recruitment">
|
||||
Candidate sourcing and evaluation.
|
||||
</Card>
|
||||
<Card title="Browse all Crews" icon="users" href="https://github.com/crewAIInc/crewAI-examples/tree/main/crews">
|
||||
See the full list of crew examples.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Flows
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Content Creator Flow" icon="pen" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows/content_creator_flow">
|
||||
Multi‑crew content generation with routing.
|
||||
</Card>
|
||||
<Card title="Email Auto Responder" icon="envelope" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows/email_auto_responder_flow">
|
||||
Automated email monitoring and replies.
|
||||
</Card>
|
||||
<Card title="Lead Score Flow" icon="chart-line" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows/lead_score_flow">
|
||||
Lead qualification with human‑in‑the‑loop.
|
||||
</Card>
|
||||
<Card title="Meeting Assistant Flow" icon="calendar" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows/meeting_assistant_flow">
|
||||
Notes processing with integrations.
|
||||
</Card>
|
||||
<Card title="Self Evaluation Loop" icon="rotate" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows/self_evaluation_loop_flow">
|
||||
Iterative self‑improvement workflows.
|
||||
</Card>
|
||||
<Card title="Write a Book (Flows)" icon="book" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows/write_a_book_with_flows">
|
||||
Parallel chapter generation.
|
||||
</Card>
|
||||
<Card title="Browse all Flows" icon="diagram-project" href="https://github.com/crewAIInc/crewAI-examples/tree/main/flows">
|
||||
See the full list of flow examples.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Integrations
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="CrewAI ↔ LangGraph" icon="link" href="https://github.com/crewAIInc/crewAI-examples/tree/main/integrations/crewai-langgraph">
|
||||
Integration with LangGraph framework.
|
||||
</Card>
|
||||
<Card title="Azure OpenAI" icon="cloud" href="https://github.com/crewAIInc/crewAI-examples/tree/main/integrations/azure_model">
|
||||
Using CrewAI with Azure OpenAI.
|
||||
</Card>
|
||||
<Card title="NVIDIA Models" icon="microchip" href="https://github.com/crewAIInc/crewAI-examples/tree/main/integrations/nvidia_models">
|
||||
NVIDIA ecosystem integrations.
|
||||
</Card>
|
||||
<Card title="Browse Integrations" icon="puzzle-piece" href="https://github.com/crewAIInc/crewAI-examples/tree/main/integrations">
|
||||
See all integration examples.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Notebooks
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Simple QA Crew + Flow" icon="book" href="https://github.com/crewAIInc/crewAI-examples/tree/main/Notebooks/Simple%20QA%20Crew%20%2B%20Flow">
|
||||
Simple QA Crew + Flow.
|
||||
</Card>
|
||||
<Card title="All Notebooks" icon="book" href="https://github.com/crewAIInc/crewAI-examples/tree/main/Notebooks">
|
||||
Interactive examples for learning and experimentation.
|
||||
</Card>
|
||||
<Card
|
||||
title="Surprise Trip"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/crewAIInc/crewAI-examples/tree/main/surprise_trip"
|
||||
icon="plane"
|
||||
iconType="duotone"
|
||||
>
|
||||
Create a surprise trip itinerary with CrewAI.
|
||||
</Card>
|
||||
<Card
|
||||
title="Match Profile to Positions"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/crewAIInc/crewAI-examples/tree/main/match_profile_to_positions"
|
||||
icon="linkedin"
|
||||
iconType="duotone"
|
||||
>
|
||||
Match a profile to jobpositions with CrewAI.
|
||||
</Card>
|
||||
<Card
|
||||
title="Create Job Posting"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/crewAIInc/crewAI-examples/tree/main/job-posting"
|
||||
icon="newspaper"
|
||||
iconType="duotone"
|
||||
>
|
||||
Create a job posting with CrewAI.
|
||||
</Card>
|
||||
<Card
|
||||
title="Game Generator"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/crewAIInc/crewAI-examples/tree/main/game-builder-crew"
|
||||
icon="gamepad"
|
||||
iconType="duotone"
|
||||
>
|
||||
Create a game with CrewAI.
|
||||
</Card>
|
||||
<Card
|
||||
title="Find Job Candidates"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/crewAIInc/crewAI-examples/tree/main/recruitment"
|
||||
icon="user-group"
|
||||
iconType="duotone"
|
||||
>
|
||||
Find job candidates with CrewAI.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -348,6 +348,31 @@ class SelectivePersistFlow(Flow):
|
||||
|
||||
## Advanced State Patterns
|
||||
|
||||
### Conditional starts and resumable execution
|
||||
|
||||
Flows support conditional `@start()` and resumable execution for HITL/cyclic scenarios:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, start, listen, and_, or_
|
||||
|
||||
class ResumableFlow(Flow):
|
||||
@start() # unconditional start
|
||||
def init(self):
|
||||
...
|
||||
|
||||
# Conditional start: run after "init" or external trigger name
|
||||
@start("init")
|
||||
def maybe_begin(self):
|
||||
...
|
||||
|
||||
@listen(and_(init, maybe_begin))
|
||||
def proceed(self):
|
||||
...
|
||||
```
|
||||
|
||||
- Conditional `@start()` accepts a method name, a router label, or a callable condition.
|
||||
- During resume, listeners continue from prior checkpoints; cycle/router branches honor resumption flags.
|
||||
|
||||
### State-Based Conditional Logic
|
||||
|
||||
You can use state to implement complex conditional logic in your flows:
|
||||
|
||||
@@ -30,6 +30,12 @@ Watch this video tutorial for a step-by-step demonstration of the installation p
|
||||
If you need to update Python, visit [python.org/downloads](https://python.org/downloads)
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
**OpenAI SDK Requirement**
|
||||
|
||||
CrewAI 0.175.0 requires `openai >= 1.13.3`. If you manage dependencies yourself, ensure your environment satisfies this constraint to avoid import/runtime issues.
|
||||
</Note>
|
||||
|
||||
CrewAI uses the `uv` as its dependency management and package handling tool. It simplifies project setup and execution, offering a seamless experience.
|
||||
|
||||
If you haven't installed `uv` yet, follow **step 1** to quickly get it set up on your system, else you can skip to **step 2**.
|
||||
|
||||
@@ -44,6 +44,19 @@ The `MCPServerAdapter` class from `crewai-tools` is the primary way to connect t
|
||||
|
||||
Using a Python context manager (`with` statement) is the **recommended approach** for `MCPServerAdapter`. It automatically handles starting and stopping the connection to the MCP server.
|
||||
|
||||
## Connection Configuration
|
||||
|
||||
The `MCPServerAdapter` supports several configuration options to customize the connection behavior:
|
||||
|
||||
- **`connect_timeout`** (optional): Maximum time in seconds to wait for establishing a connection to the MCP server. Defaults to 30 seconds if not specified. This is particularly useful for remote servers that may have variable response times.
|
||||
|
||||
```python
|
||||
# Example with custom connection timeout
|
||||
with MCPServerAdapter(server_params, connect_timeout=60) as tools:
|
||||
# Connection will timeout after 60 seconds if not established
|
||||
pass
|
||||
```
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai_tools import MCPServerAdapter
|
||||
@@ -70,7 +83,7 @@ server_params = {
|
||||
}
|
||||
|
||||
# Example usage (uncomment and adapt once server_params is set):
|
||||
with MCPServerAdapter(server_params) as mcp_tools:
|
||||
with MCPServerAdapter(server_params, connect_timeout=60) as mcp_tools:
|
||||
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
|
||||
|
||||
my_agent = Agent(
|
||||
@@ -95,7 +108,7 @@ There are two ways to filter tools:
|
||||
### Accessing a specific tool using dictionary-style indexing.
|
||||
|
||||
```python
|
||||
with MCPServerAdapter(server_params) as mcp_tools:
|
||||
with MCPServerAdapter(server_params, connect_timeout=60) as mcp_tools:
|
||||
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
|
||||
|
||||
my_agent = Agent(
|
||||
@@ -112,7 +125,7 @@ with MCPServerAdapter(server_params) as mcp_tools:
|
||||
### Pass a list of tool names to the `MCPServerAdapter` constructor.
|
||||
|
||||
```python
|
||||
with MCPServerAdapter(server_params, "tool_name") as mcp_tools:
|
||||
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(
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
---
|
||||
title: AgentOps Integration
|
||||
description: Understanding and logging your agent performance with AgentOps.
|
||||
icon: paperclip
|
||||
---
|
||||
|
||||
# Introduction
|
||||
|
||||
Observability is a key aspect of developing and deploying conversational AI agents. It allows developers to understand how their agents are performing,
|
||||
how their agents are interacting with users, and how their agents use external tools and APIs.
|
||||
AgentOps is a product independent of CrewAI that provides a comprehensive observability solution for agents.
|
||||
|
||||
## AgentOps
|
||||
|
||||
[AgentOps](https://agentops.ai/?=crew) provides session replays, metrics, and monitoring for agents.
|
||||
|
||||
At a high level, AgentOps gives you the ability to monitor cost, token usage, latency, agent failures, session-wide statistics, and more.
|
||||
For more info, check out the [AgentOps Repo](https://github.com/AgentOps-AI/agentops).
|
||||
|
||||
### Overview
|
||||
|
||||
AgentOps provides monitoring for agents in development and production.
|
||||
It provides a dashboard for tracking agent performance, session replays, and custom reporting.
|
||||
|
||||
Additionally, AgentOps provides session drilldowns for viewing Crew agent interactions, LLM calls, and tool usage in real-time.
|
||||
This feature is useful for debugging and understanding how agents interact with users as well as other agents.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
### Features
|
||||
|
||||
- **LLM Cost Management and Tracking**: Track spend with foundation model providers.
|
||||
- **Replay Analytics**: Watch step-by-step agent execution graphs.
|
||||
- **Recursive Thought Detection**: Identify when agents fall into infinite loops.
|
||||
- **Custom Reporting**: Create custom analytics on agent performance.
|
||||
- **Analytics Dashboard**: Monitor high-level statistics about agents in development and production.
|
||||
- **Public Model Testing**: Test your agents against benchmarks and leaderboards.
|
||||
- **Custom Tests**: Run your agents against domain-specific tests.
|
||||
- **Time Travel Debugging**: Restart your sessions from checkpoints.
|
||||
- **Compliance and Security**: Create audit logs and detect potential threats such as profanity and PII leaks.
|
||||
- **Prompt Injection Detection**: Identify potential code injection and secret leaks.
|
||||
|
||||
### Using AgentOps
|
||||
|
||||
<Steps>
|
||||
<Step title="Create an API Key">
|
||||
Create a user API key here: [Create API Key](https://app.agentops.ai/account)
|
||||
</Step>
|
||||
<Step title="Configure Your Environment">
|
||||
Add your API key to your environment variables:
|
||||
```bash
|
||||
AGENTOPS_API_KEY=<YOUR_AGENTOPS_API_KEY>
|
||||
```
|
||||
</Step>
|
||||
<Step title="Install AgentOps">
|
||||
Install AgentOps with:
|
||||
```bash
|
||||
pip install 'crewai[agentops]'
|
||||
```
|
||||
or
|
||||
```bash
|
||||
pip install agentops
|
||||
```
|
||||
</Step>
|
||||
<Step title="Initialize AgentOps">
|
||||
Before using `Crew` in your script, include these lines:
|
||||
|
||||
```python
|
||||
import agentops
|
||||
agentops.init()
|
||||
```
|
||||
|
||||
This will initiate an AgentOps session as well as automatically track Crew agents. For further info on how to outfit more complex agentic systems,
|
||||
check out the [AgentOps documentation](https://docs.agentops.ai) or join the [Discord](https://discord.gg/j4f3KbeH).
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Crew + AgentOps Examples
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="Job Posting"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/joaomdmoura/crewAI-examples/tree/main/job-posting"
|
||||
icon="briefcase"
|
||||
iconType="solid"
|
||||
>
|
||||
Example of a Crew agent that generates job posts.
|
||||
</Card>
|
||||
<Card
|
||||
title="Markdown Validator"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/joaomdmoura/crewAI-examples/tree/main/markdown_validator"
|
||||
icon="markdown"
|
||||
iconType="solid"
|
||||
>
|
||||
Example of a Crew agent that validates Markdown files.
|
||||
</Card>
|
||||
<Card
|
||||
title="Instagram Post"
|
||||
color="#F3A78B"
|
||||
href="https://github.com/joaomdmoura/crewAI-examples/tree/main/instagram_post"
|
||||
icon="square-instagram"
|
||||
iconType="brands"
|
||||
>
|
||||
Example of a Crew agent that generates Instagram posts.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Further Information
|
||||
|
||||
To get started, create an [AgentOps account](https://agentops.ai/?=crew).
|
||||
|
||||
For feature requests or bug reports, please reach out to the AgentOps team on the [AgentOps Repo](https://github.com/AgentOps-AI/agentops).
|
||||
|
||||
#### Extra links
|
||||
|
||||
<a href="https://twitter.com/agentopsai/">🐦 Twitter</a>
|
||||
<span> • </span>
|
||||
<a href="https://discord.gg/JHPt4C7r">📢 Discord</a>
|
||||
<span> • </span>
|
||||
<a href="https://app.agentops.ai/?=crew">🖇️ AgentOps Dashboard</a>
|
||||
<span> • </span>
|
||||
<a href="https://docs.agentops.ai/introduction">📙 Documentation</a>
|
||||
286
docs/en/observability/langdb.mdx
Normal file
@@ -0,0 +1,286 @@
|
||||
---
|
||||
title: LangDB Integration
|
||||
description: Govern, secure, and optimize your CrewAI workflows with LangDB AI Gateway—access 350+ models, automatic routing, cost optimization, and full observability.
|
||||
icon: database
|
||||
---
|
||||
|
||||
# Introduction
|
||||
|
||||
[LangDB AI Gateway](https://langdb.ai) provides OpenAI-compatible APIs to connect with multiple Large Language Models and serves as an observability platform that makes it effortless to trace CrewAI workflows end-to-end while providing access to 350+ language models. With a single `init()` call, all agent interactions, task executions, and LLM calls are captured, providing comprehensive observability and production-ready AI infrastructure for your applications.
|
||||
|
||||
<Frame caption="LangDB CrewAI Trace Example">
|
||||
<img src="/images/langdb-1.png" alt="LangDB CrewAI trace example" />
|
||||
</Frame>
|
||||
|
||||
**Checkout:** [View the live trace example](https://app.langdb.ai/sharing/threads/3becbfed-a1be-ae84-ea3c-4942867a3e22)
|
||||
|
||||
## Features
|
||||
|
||||
### AI Gateway Capabilities
|
||||
- **Access to 350+ LLMs**: Connect to all major language models through a single integration
|
||||
- **Virtual Models**: Create custom model configurations with specific parameters and routing rules
|
||||
- **Virtual MCP**: Enable compatibility and integration with MCP (Model Context Protocol) systems for enhanced agent communication
|
||||
- **Guardrails**: Implement safety measures and compliance controls for agent behavior
|
||||
|
||||
### Observability & Tracing
|
||||
- **Automatic Tracing**: Single `init()` call captures all CrewAI interactions
|
||||
- **End-to-End Visibility**: Monitor agent workflows from start to finish
|
||||
- **Tool Usage Tracking**: Track which tools agents use and their outcomes
|
||||
- **Model Call Monitoring**: Detailed insights into LLM interactions
|
||||
- **Performance Analytics**: Monitor latency, token usage, and costs
|
||||
- **Debugging Support**: Step-through execution for troubleshooting
|
||||
- **Real-time Monitoring**: Live traces and metrics dashboard
|
||||
|
||||
## Setup Instructions
|
||||
|
||||
<Steps>
|
||||
<Step title="Install LangDB">
|
||||
Install the LangDB client with CrewAI feature flag:
|
||||
```bash
|
||||
pip install 'pylangdb[crewai]'
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set Environment Variables">
|
||||
Configure your LangDB credentials:
|
||||
```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="Initialize Tracing">
|
||||
Import and initialize LangDB before configuring your CrewAI code:
|
||||
```python
|
||||
from pylangdb.crewai import init
|
||||
# Initialize LangDB
|
||||
init()
|
||||
```
|
||||
</Step>
|
||||
<Step title="Configure CrewAI with LangDB">
|
||||
Set up your LLM with LangDB headers:
|
||||
```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>
|
||||
|
||||
## Quick Start Example
|
||||
|
||||
Here's a simple example to get you started with LangDB and 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)
|
||||
```
|
||||
|
||||
## Complete Example: Research and Planning Agent
|
||||
|
||||
This comprehensive example demonstrates a multi-agent workflow with research and planning capabilities.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
```bash
|
||||
pip install crewai 'pylangdb[crewai]' crewai_tools setuptools python-dotenv
|
||||
```
|
||||
|
||||
### Environment Setup
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### Complete Implementation
|
||||
|
||||
```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()
|
||||
```
|
||||
|
||||
### Running the Example
|
||||
|
||||
```bash
|
||||
python main.py "Sustainable Energy Solutions"
|
||||
```
|
||||
|
||||
## Viewing Traces in LangDB
|
||||
|
||||
After running your CrewAI application, you can view detailed traces in the LangDB dashboard:
|
||||
|
||||
<Frame caption="LangDB Trace Dashboard">
|
||||
<img src="/images/langdb-2.png" alt="LangDB trace dashboard showing CrewAI workflow" />
|
||||
</Frame>
|
||||
|
||||
### What You'll See
|
||||
|
||||
- **Agent Interactions**: Complete flow of agent conversations and task handoffs
|
||||
- **Tool Usage**: Which tools were called, their inputs, and outputs
|
||||
- **Model Calls**: Detailed LLM interactions with prompts image.pngand responses
|
||||
- **Performance Metrics**: Latency, token usage, and cost tracking
|
||||
- **Execution Timeline**: Step-by-step view of the entire workflow
|
||||
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
- **No traces appearing**: Ensure `init()` is called before any CrewAI imports
|
||||
- **Authentication errors**: Verify your LangDB API key and project ID
|
||||
|
||||
|
||||
## Resources
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="LangDB Documentation" icon="book" href="https://docs.langdb.ai">
|
||||
Official LangDB documentation and guides
|
||||
</Card>
|
||||
<Card title="LangDB Guides" icon="graduation-cap" href="https://docs.langdb.ai/guides">
|
||||
Step-by-step tutorials for building AI agents
|
||||
</Card>
|
||||
<Card title="GitHub Examples" icon="github" href="https://github.com/langdb/langdb-samples/tree/main/examples/crewai" >
|
||||
Complete CrewAI integration examples
|
||||
</Card>
|
||||
<Card title="LangDB Dashboard" icon="chart-line" href="https://app.langdb.ai">
|
||||
Access your traces and analytics
|
||||
</Card>
|
||||
<Card title="Model Catalog" icon="list" href="https://app.langdb.ai/models">
|
||||
Browse 350+ available language models
|
||||
</Card>
|
||||
<Card title="Enterprise Features" icon="building" href="https://docs.langdb.ai/enterprise">
|
||||
Self-hosted options and enterprise capabilities
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
This guide covered the basics of integrating LangDB AI Gateway with CrewAI. To further enhance your AI workflows, explore:
|
||||
|
||||
- **Virtual Models**: Create custom model configurations with routing strategies
|
||||
- **Guardrails & Safety**: Implement content filtering and compliance controls
|
||||
- **Production Deployment**: Configure fallbacks, retries, and load balancing
|
||||
|
||||
For more advanced features and use cases, visit the [LangDB Documentation](https://docs.langdb.ai) or explore the [Model Catalog](https://app.langdb.ai/models) to discover all available models.
|
||||
134
docs/en/observability/neatlogs.mdx
Normal file
@@ -0,0 +1,134 @@
|
||||
---
|
||||
title: Neatlogs Integration
|
||||
description: Understand, debug, and share your CrewAI agent runs
|
||||
icon: magnifying-glass-chart
|
||||
---
|
||||
|
||||
# Introduction
|
||||
|
||||
Neatlogs helps you **see what your agent did**, **why**, and **share it**.
|
||||
|
||||
It captures every step: thoughts, tool calls, responses, evaluations. No raw logs. Just clear, structured traces. Great for debugging and collaboration.
|
||||
|
||||
## Why use Neatlogs?
|
||||
|
||||
CrewAI agents use multiple tools and reasoning steps. When something goes wrong, you need context — not just errors.
|
||||
|
||||
Neatlogs lets you:
|
||||
|
||||
- Follow the full decision path
|
||||
- Add feedback directly on steps
|
||||
- Chat with the trace using AI assistant
|
||||
- Share runs publicly for feedback
|
||||
- Turn insights into tasks
|
||||
|
||||
All in one place.
|
||||
|
||||
Manage your traces effortlessly
|
||||
|
||||

|
||||

|
||||
|
||||
The best UX to view a CrewAI trace. Post comments anywhere you want. Use AI to debug.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## Core Features
|
||||
|
||||
- **Trace Viewer**: Track thoughts, tools, and decisions in sequence
|
||||
- **Inline Comments**: Tag teammates on any trace step
|
||||
- **Feedback & Evaluation**: Mark outputs as correct or incorrect
|
||||
- **Error Highlighting**: Automatic flagging of API/tool failures
|
||||
- **Task Conversion**: Convert comments into assigned tasks
|
||||
- **Ask the Trace (AI)**: Chat with your trace using Neatlogs AI bot
|
||||
- **Public Sharing**: Publish trace links to your community
|
||||
|
||||
## Quick Setup with CrewAI
|
||||
|
||||
<Steps>
|
||||
<Step title="Sign Up & Get API Key">
|
||||
Visit [neatlogs.com](https://neatlogs.com/?utm_source=crewAI-docs), create a project, copy the API key.
|
||||
</Step>
|
||||
<Step title="Install SDK">
|
||||
```bash
|
||||
pip install neatlogs
|
||||
```
|
||||
(Latest version 0.8.0, Python 3.8+; MIT license)
|
||||
</Step>
|
||||
<Step title="Initialize Neatlogs">
|
||||
Before starting Crew agents, add:
|
||||
|
||||
```python
|
||||
import neatlogs
|
||||
neatlogs.init("YOUR_PROJECT_API_KEY")
|
||||
```
|
||||
|
||||
Agents run as usual. Neatlogs captures everything automatically.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
|
||||
## Under the Hood
|
||||
|
||||
According to GitHub, Neatlogs:
|
||||
|
||||
- Captures thoughts, tool calls, responses, errors, and token stats
|
||||
- Supports AI-powered task generation and robust evaluation workflows
|
||||
|
||||
All with just two lines of code.
|
||||
|
||||
|
||||
|
||||
## Watch It Work
|
||||
|
||||
### 🔍 Full Demo (4 min)
|
||||
|
||||
<iframe
|
||||
width="100%"
|
||||
height="315"
|
||||
src="https://www.youtube.com/embed/8KDme9T2I7Q?si=b8oHteaBwFNs_Duk"
|
||||
title="YouTube video player"
|
||||
frameBorder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
|
||||
### ⚙️ CrewAI Integration (30 s)
|
||||
|
||||
<iframe
|
||||
className="w-full aspect-video rounded-xl"
|
||||
src="https://www.loom.com/embed/9c78b552af43452bb3e4783cb8d91230?sid=e9d7d370-a91a-49b0-809e-2f375d9e801d"
|
||||
title="Loom video player"
|
||||
frameBorder="0"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
|
||||
|
||||
|
||||
## Links & Support
|
||||
|
||||
- 📘 [Neatlogs Docs](https://docs.neatlogs.com/)
|
||||
- 🔐 [Dashboard & API Key](https://app.neatlogs.com/)
|
||||
- 🐦 [Follow on Twitter](https://twitter.com/neatlogs)
|
||||
- 📧 Contact: hello@neatlogs.com
|
||||
- 🛠 [GitHub SDK](https://github.com/NeatLogs/neatlogs)
|
||||
|
||||
|
||||
|
||||
## TL;DR
|
||||
|
||||
With just:
|
||||
|
||||
```bash
|
||||
pip install neatlogs
|
||||
|
||||
import neatlogs
|
||||
neatlogs.init("YOUR_API_KEY")
|
||||
|
||||
You can now capture, understand, share, and act on your CrewAI agent runs in seconds.
|
||||
No setup overhead. Full trace transparency. Full team collaboration.
|
||||
```
|
||||
@@ -21,8 +21,9 @@ Observability is crucial for understanding how your CrewAI agents perform, ident
|
||||
### Monitoring & Tracing Platforms
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AgentOps" icon="paperclip" href="/en/observability/agentops">
|
||||
Session replays, metrics, and monitoring for agent development and production.
|
||||
|
||||
<Card title="LangDB" icon="database" href="/en/observability/langdb">
|
||||
End-to-end tracing for CrewAI workflows with automatic agent interaction capture.
|
||||
</Card>
|
||||
|
||||
<Card title="OpenLIT" icon="magnifying-glass-chart" href="/en/observability/openlit">
|
||||
|
||||
146
docs/en/observability/truefoundry.mdx
Normal file
@@ -0,0 +1,146 @@
|
||||
---
|
||||
title: TrueFoundry Integration
|
||||
icon: chart-line
|
||||
---
|
||||
|
||||
TrueFoundry provides an enterprise-ready [AI Gateway](https://www.truefoundry.com/ai-gateway) which can integrate with agentic frameworks like CrewAI and provides governance and observability for your AI Applications. TrueFoundry AI Gateway serves as a unified interface for LLM access, providing:
|
||||
|
||||
- **Unified API Access**: Connect to 250+ LLMs (OpenAI, Claude, Gemini, Groq, Mistral) through one API
|
||||
- **Low Latency**: Sub-3ms internal latency with intelligent routing and load balancing
|
||||
- **Enterprise Security**: SOC 2, HIPAA, GDPR compliance with RBAC and audit logging
|
||||
- **Quota and cost management**: Token-based quotas, rate limiting, and comprehensive usage tracking
|
||||
- **Observability**: Full request/response logging, metrics, and traces with customizable retention
|
||||
|
||||
## How TrueFoundry Integrates with CrewAI
|
||||
|
||||
|
||||
### Installation & Setup
|
||||
|
||||
<Steps>
|
||||
<Step title="Install CrewAI">
|
||||
```bash
|
||||
pip install crewai
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Get TrueFoundry Access Token">
|
||||
1. Sign up for a [TrueFoundry account](https://www.truefoundry.com/register)
|
||||
2. Follow the steps here in [Quick start](https://docs.truefoundry.com/gateway/quick-start)
|
||||
</Step>
|
||||
|
||||
<Step title="Configure CrewAI with TrueFoundry">
|
||||

|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Create an LLM instance with TrueFoundry AI Gateway
|
||||
truefoundry_llm = LLM(
|
||||
model="openai-main/gpt-4o", # Similarly, you can call any model from any provider
|
||||
base_url="your_truefoundry_gateway_base_url",
|
||||
api_key="your_truefoundry_api_key"
|
||||
)
|
||||
|
||||
# Use in your CrewAI agents
|
||||
from crewai import Agent
|
||||
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'],
|
||||
llm=truefoundry_llm,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Complete CrewAI Example
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew, LLM
|
||||
|
||||
# Configure LLM with TrueFoundry
|
||||
llm = LLM(
|
||||
model="openai-main/gpt-4o",
|
||||
base_url="your_truefoundry_gateway_base_url",
|
||||
api_key="your_truefoundry_api_key"
|
||||
)
|
||||
|
||||
# Create agents
|
||||
researcher = Agent(
|
||||
role='Research Analyst',
|
||||
goal='Conduct detailed market research',
|
||||
backstory='Expert market analyst with attention to detail',
|
||||
llm=llm,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role='Content Writer',
|
||||
goal='Create comprehensive reports',
|
||||
backstory='Experienced technical writer',
|
||||
llm=llm,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create tasks
|
||||
research_task = Task(
|
||||
description='Research AI market trends for 2024',
|
||||
agent=researcher,
|
||||
expected_output='Comprehensive research summary'
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description='Create a market research report',
|
||||
agent=writer,
|
||||
expected_output='Well-structured report with insights',
|
||||
context=[research_task]
|
||||
)
|
||||
|
||||
# Create and execute crew
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, writing_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### Observability and Governance
|
||||
|
||||
Monitor your CrewAI agents through TrueFoundry's metrics tab:
|
||||

|
||||
|
||||
With Truefoundry's AI gateway, you can monitor and analyze:
|
||||
|
||||
- **Performance Metrics**: Track key latency metrics like Request Latency, Time to First Token (TTFS), and Inter-Token Latency (ITL) with P99, P90, and P50 percentiles
|
||||
- **Cost and Token Usage**: Gain visibility into your application's costs with detailed breakdowns of input/output tokens and the associated expenses for each model
|
||||
- **Usage Patterns**: Understand how your application is being used with detailed analytics on user activity, model distribution, and team-based usage
|
||||
- **Rate limit and Load balancing**: You can set up rate limiting, load balancing and fallback for your models
|
||||
|
||||
## Tracing
|
||||
|
||||
For a more detailed understanding on tracing, please see [getting-started-tracing](https://docs.truefoundry.com/docs/tracing/tracing-getting-started).For tracing, you can add the Traceloop SDK:
|
||||
For tracing, you can add the Traceloop SDK:
|
||||
|
||||
```bash
|
||||
pip install traceloop-sdk
|
||||
```
|
||||
|
||||
```python
|
||||
from traceloop.sdk import Traceloop
|
||||
|
||||
# Initialize enhanced tracing
|
||||
Traceloop.init(
|
||||
api_endpoint="https://your-truefoundry-endpoint/api/tracing",
|
||||
headers={
|
||||
"Authorization": f"Bearer {your_truefoundry_pat_token}",
|
||||
"TFY-Tracing-Project": "your_project_name",
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
This provides additional trace correlation across your entire CrewAI workflow.
|
||||

|
||||
@@ -35,7 +35,7 @@ os.environ['OTEL_SDK_DISABLED'] = 'true'
|
||||
|
||||
### Data Explanation:
|
||||
| Defaulted | Data | Reason and Specifics |
|
||||
|-----------|-------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|
|
||||
|:----------|:------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------|
|
||||
| Yes | CrewAI and Python Version | Tracks software versions. Example: CrewAI v1.2.3, Python 3.8.10. No personal data. |
|
||||
| Yes | Crew Metadata | Includes: randomly generated key and ID, process type (e.g., 'sequential', 'parallel'), boolean flag for memory usage (true/false), count of tasks, count of agents. All non-personal. |
|
||||
| Yes | Agent Data | Includes: randomly generated key and ID, role name (should not include personal info), boolean settings (verbose, delegation enabled, code execution allowed), max iterations, max RPM, max retry limit, LLM info (see LLM Attributes), list of tool names (should not include personal info). No personal data. |
|
||||
|
||||
@@ -20,6 +20,10 @@ These tools enable your agents to automate workflows, integrate with external pl
|
||||
<Card title="Multion Tool" icon="window-restore" href="/en/tools/automation/multiontool">
|
||||
Automate browser interactions and web-based workflows.
|
||||
</Card>
|
||||
|
||||
<Card title="Zapier Actions Adapter" icon="bolt" href="/en/tools/automation/zapieractionstool">
|
||||
Expose Zapier Actions as CrewAI tools for automation across thousands of apps.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## **Common Use Cases**
|
||||
|
||||
58
docs/en/tools/automation/zapieractionstool.mdx
Normal file
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Zapier Actions Tool
|
||||
description: The `ZapierActionsAdapter` exposes Zapier actions as CrewAI tools for automation.
|
||||
icon: bolt
|
||||
---
|
||||
|
||||
# `ZapierActionsAdapter`
|
||||
|
||||
## Description
|
||||
|
||||
Use the Zapier adapter to list and call Zapier actions as CrewAI tools. This enables agents to trigger automations across thousands of apps.
|
||||
|
||||
## Installation
|
||||
|
||||
This adapter is included with `crewai-tools`. No extra install required.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `ZAPIER_API_KEY` (required): Zapier API key. Get one from the Zapier Actions dashboard at https://actions.zapier.com/ (create an account, then generate an API key). You can also pass `zapier_api_key` directly when constructing the adapter.
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools.adapters.zapier_adapter import ZapierActionsAdapter
|
||||
|
||||
adapter = ZapierActionsAdapter(api_key="your_zapier_api_key")
|
||||
tools = adapter.tools()
|
||||
|
||||
agent = Agent(
|
||||
role="Automator",
|
||||
goal="Execute Zapier actions",
|
||||
backstory="Automation specialist",
|
||||
tools=tools,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Create a new Google Sheet and add a row using Zapier actions",
|
||||
expected_output="Confirmation with created resource IDs",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Notes & limits
|
||||
|
||||
- The adapter lists available actions for your key and creates `BaseTool` wrappers dynamically.
|
||||
- Handle action‑specific required fields in your task instructions or tool call.
|
||||
- Rate limits depend on your Zapier plan; see the Zapier Actions docs.
|
||||
|
||||
## Notes
|
||||
|
||||
- The adapter fetches available actions and generates `BaseTool` wrappers dynamically.
|
||||
|
||||
|
||||
168
docs/en/tools/database-data/mongodbvectorsearchtool.mdx
Normal file
@@ -0,0 +1,168 @@
|
||||
---
|
||||
title: MongoDB Vector Search Tool
|
||||
description: The `MongoDBVectorSearchTool` performs vector search on MongoDB Atlas with optional indexing helpers.
|
||||
icon: "leaf"
|
||||
---
|
||||
|
||||
# `MongoDBVectorSearchTool`
|
||||
|
||||
## Description
|
||||
|
||||
Perform vector similarity queries on MongoDB Atlas collections. Supports index creation helpers and bulk insert of embedded texts.
|
||||
|
||||
MongoDB Atlas supports native vector search. Learn more:
|
||||
https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-overview/
|
||||
|
||||
## Installation
|
||||
|
||||
Install with the MongoDB extra:
|
||||
|
||||
```shell
|
||||
pip install crewai-tools[mongodb]
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```shell
|
||||
uv add crewai-tools --extra mongodb
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
### Initialization
|
||||
|
||||
- `connection_string` (str, required)
|
||||
- `database_name` (str, required)
|
||||
- `collection_name` (str, required)
|
||||
- `vector_index_name` (str, default `vector_index`)
|
||||
- `text_key` (str, default `text`)
|
||||
- `embedding_key` (str, default `embedding`)
|
||||
- `dimensions` (int, default `1536`)
|
||||
|
||||
### Run Parameters
|
||||
|
||||
- `query` (str, required): Natural language query to embed and search.
|
||||
|
||||
## Quick start
|
||||
|
||||
```python Code
|
||||
from crewai_tools import MongoDBVectorSearchTool
|
||||
|
||||
tool = MongoDBVectorSearchTool(
|
||||
connection_string="mongodb+srv://...",
|
||||
database_name="mydb",
|
||||
collection_name="docs",
|
||||
)
|
||||
|
||||
print(tool.run(query="how to create vector index"))
|
||||
```
|
||||
|
||||
## Index creation helpers
|
||||
|
||||
Use `create_vector_search_index(...)` to provision an Atlas Vector Search index with the correct dimensions and similarity.
|
||||
|
||||
## Common issues
|
||||
|
||||
- Authentication failures: ensure your Atlas IP Access List allows your runner and the connection string includes credentials.
|
||||
- Index not found: create the vector index first; name must match `vector_index_name`.
|
||||
- Dimensions mismatch: align embedding model dimensions with `dimensions`.
|
||||
|
||||
## More examples
|
||||
|
||||
### Basic initialization
|
||||
|
||||
```python Code
|
||||
from crewai_tools import MongoDBVectorSearchTool
|
||||
|
||||
tool = MongoDBVectorSearchTool(
|
||||
database_name="example_database",
|
||||
collection_name="example_collection",
|
||||
connection_string="<your_mongodb_connection_string>",
|
||||
)
|
||||
```
|
||||
|
||||
### Custom query configuration
|
||||
|
||||
```python Code
|
||||
from crewai_tools import MongoDBVectorSearchConfig, MongoDBVectorSearchTool
|
||||
|
||||
query_config = MongoDBVectorSearchConfig(limit=10, oversampling_factor=2)
|
||||
tool = MongoDBVectorSearchTool(
|
||||
database_name="example_database",
|
||||
collection_name="example_collection",
|
||||
connection_string="<your_mongodb_connection_string>",
|
||||
query_config=query_config,
|
||||
vector_index_name="my_vector_index",
|
||||
)
|
||||
|
||||
rag_agent = Agent(
|
||||
name="rag_agent",
|
||||
role="You are a helpful assistant that can answer questions with the help of the MongoDBVectorSearchTool.",
|
||||
goal="...",
|
||||
backstory="...",
|
||||
tools=[tool],
|
||||
)
|
||||
```
|
||||
|
||||
### Preloading the database and creating the index
|
||||
|
||||
```python Code
|
||||
import os
|
||||
from crewai_tools import MongoDBVectorSearchTool
|
||||
|
||||
tool = MongoDBVectorSearchTool(
|
||||
database_name="example_database",
|
||||
collection_name="example_collection",
|
||||
connection_string="<your_mongodb_connection_string>",
|
||||
)
|
||||
|
||||
# Load text content from a local folder and add to MongoDB
|
||||
texts = []
|
||||
for fname in os.listdir("knowledge"):
|
||||
path = os.path.join("knowledge", fname)
|
||||
if os.path.isfile(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
texts.append(f.read())
|
||||
|
||||
tool.add_texts(texts)
|
||||
|
||||
# Create the Atlas Vector Search index (e.g., 3072 dims for text-embedding-3-large)
|
||||
tool.create_vector_search_index(dimensions=3072)
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import MongoDBVectorSearchTool
|
||||
|
||||
tool = MongoDBVectorSearchTool(
|
||||
connection_string="mongodb+srv://...",
|
||||
database_name="mydb",
|
||||
collection_name="docs",
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role="RAG Agent",
|
||||
goal="Answer using MongoDB vector search",
|
||||
backstory="Knowledge retrieval specialist",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Find relevant content for 'indexing guidance'",
|
||||
expected_output="A concise answer citing the most relevant matches",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
|
||||
@@ -32,6 +32,14 @@ These tools enable your agents to interact with various database systems, from t
|
||||
<Card title="Weaviate Vector Search" icon="network-wired" href="/en/tools/database-data/weaviatevectorsearchtool">
|
||||
Perform semantic search with Weaviate vector database.
|
||||
</Card>
|
||||
|
||||
<Card title="MongoDB Vector Search" icon="leaf" href="/en/tools/database-data/mongodbvectorsearchtool">
|
||||
Vector similarity search on MongoDB Atlas with indexing helpers.
|
||||
</Card>
|
||||
|
||||
<Card title="SingleStore Search" icon="database" href="/en/tools/database-data/singlestoresearchtool">
|
||||
Safe SELECT/SHOW queries on SingleStore with pooling and validation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## **Common Use Cases**
|
||||
|
||||
61
docs/en/tools/database-data/singlestoresearchtool.mdx
Normal file
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: SingleStore Search Tool
|
||||
description: The `SingleStoreSearchTool` safely executes SELECT/SHOW queries on SingleStore with pooling.
|
||||
icon: circle
|
||||
---
|
||||
|
||||
# `SingleStoreSearchTool`
|
||||
|
||||
## Description
|
||||
|
||||
Execute read‑only queries (`SELECT`/`SHOW`) against SingleStore with connection pooling and input validation.
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
uv add crewai-tools[singlestore]
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Variables like `SINGLESTOREDB_HOST`, `SINGLESTOREDB_USER`, `SINGLESTOREDB_PASSWORD`, etc., can be used, or `SINGLESTOREDB_URL` as a single DSN.
|
||||
|
||||
Generate the API key from the SingleStore dashboard, [docs here](https://docs.singlestore.com/cloud/reference/management-api/#generate-an-api-key).
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import SingleStoreSearchTool
|
||||
|
||||
tool = SingleStoreSearchTool(
|
||||
tables=["products"],
|
||||
host="host",
|
||||
user="user",
|
||||
password="pass",
|
||||
database="db",
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role="Analyst",
|
||||
goal="Query SingleStore",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="List 5 products",
|
||||
expected_output="5 rows as JSON/text",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
title: Weaviate Vector Search
|
||||
description: The `WeaviateVectorSearchTool` is designed to search a Weaviate vector database for semantically similar documents.
|
||||
description: The `WeaviateVectorSearchTool` is designed to search a Weaviate vector database for semantically similar documents using hybrid search.
|
||||
icon: network-wired
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
|
||||
The `WeaviateVectorSearchTool` is specifically crafted for conducting semantic searches within documents stored in a Weaviate vector database. This tool allows you to find semantically similar documents to a given query, leveraging the power of vector embeddings for more accurate and contextually relevant search results.
|
||||
The `WeaviateVectorSearchTool` is specifically crafted for conducting semantic searches within documents stored in a Weaviate vector database. This tool allows you to find semantically similar documents to a given query, leveraging the power of vector and keyword search for more accurate and contextually relevant search results.
|
||||
|
||||
[Weaviate](https://weaviate.io/) is a vector database that stores and queries vector embeddings, enabling semantic search capabilities.
|
||||
|
||||
@@ -39,6 +39,7 @@ from crewai_tools import WeaviateVectorSearchTool
|
||||
tool = WeaviateVectorSearchTool(
|
||||
collection_name='example_collections',
|
||||
limit=3,
|
||||
alpha=0.75,
|
||||
weaviate_cluster_url="https://your-weaviate-cluster-url.com",
|
||||
weaviate_api_key="your-weaviate-api-key",
|
||||
)
|
||||
@@ -63,6 +64,7 @@ The `WeaviateVectorSearchTool` accepts the following parameters:
|
||||
- **weaviate_cluster_url**: Required. The URL of the Weaviate cluster.
|
||||
- **weaviate_api_key**: Required. The API key for the Weaviate cluster.
|
||||
- **limit**: Optional. The number of results to return. Default is `3`.
|
||||
- **alpha**: Optional. Controls the weighting between vector and keyword (BM25) search. alpha = 0 -> BM25 only, alpha = 1 -> vector search only. Default is `0.75`.
|
||||
- **vectorizer**: Optional. The vectorizer to use. If not provided, it will use `text2vec_openai` with the `nomic-embed-text` model.
|
||||
- **generative_model**: Optional. The generative model to use. If not provided, it will use OpenAI's `gpt-4o`.
|
||||
|
||||
@@ -78,6 +80,7 @@ from weaviate.classes.config import Configure
|
||||
tool = WeaviateVectorSearchTool(
|
||||
collection_name='example_collections',
|
||||
limit=3,
|
||||
alpha=0.75,
|
||||
vectorizer=Configure.Vectorizer.text2vec_openai(model="nomic-embed-text"),
|
||||
generative_model=Configure.Generative.openai(model="gpt-4o-mini"),
|
||||
weaviate_cluster_url="https://your-weaviate-cluster-url.com",
|
||||
@@ -128,6 +131,7 @@ with test_docs.batch.dynamic() as batch:
|
||||
tool = WeaviateVectorSearchTool(
|
||||
collection_name='example_collections',
|
||||
limit=3,
|
||||
alpha=0.75,
|
||||
weaviate_cluster_url="https://your-weaviate-cluster-url.com",
|
||||
weaviate_api_key="your-weaviate-api-key",
|
||||
)
|
||||
@@ -145,6 +149,7 @@ from crewai_tools import WeaviateVectorSearchTool
|
||||
weaviate_tool = WeaviateVectorSearchTool(
|
||||
collection_name='example_collections',
|
||||
limit=3,
|
||||
alpha=0.75,
|
||||
weaviate_cluster_url="https://your-weaviate-cluster-url.com",
|
||||
weaviate_api_key="your-weaviate-api-key",
|
||||
)
|
||||
|
||||
89
docs/en/tools/file-document/ocrtool.mdx
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
title: OCR Tool
|
||||
description: The `OCRTool` extracts text from local images or image URLs using an LLM with vision.
|
||||
icon: image
|
||||
---
|
||||
|
||||
# `OCRTool`
|
||||
|
||||
## Description
|
||||
|
||||
Extract text from images (local path or URL). Uses a vision‑capable LLM via CrewAI’s LLM interface.
|
||||
|
||||
## Installation
|
||||
|
||||
No extra install beyond `crewai-tools`. Ensure your selected LLM supports vision.
|
||||
|
||||
## Parameters
|
||||
|
||||
### Run Parameters
|
||||
|
||||
- `image_path_url` (str, required): Local image path or HTTP(S) URL.
|
||||
|
||||
## Examples
|
||||
|
||||
### Direct usage
|
||||
|
||||
```python Code
|
||||
from crewai_tools import OCRTool
|
||||
|
||||
print(OCRTool().run(image_path_url="/tmp/receipt.png"))
|
||||
```
|
||||
|
||||
### With an agent
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import OCRTool
|
||||
|
||||
ocr = OCRTool()
|
||||
|
||||
agent = Agent(
|
||||
role="OCR",
|
||||
goal="Extract text",
|
||||
tools=[ocr],
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Extract text from https://example.com/invoice.jpg",
|
||||
expected_output="All detected text in plain text",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Ensure the selected LLM supports image inputs.
|
||||
- For large images, consider downscaling to reduce token usage.
|
||||
- You can pass a specific LLM instance to the tool (e.g., `LLM(model="gpt-4o")`) if needed, matching the README guidance.
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import OCRTool
|
||||
|
||||
tool = OCRTool()
|
||||
|
||||
agent = Agent(
|
||||
role="OCR Specialist",
|
||||
goal="Extract text from images",
|
||||
backstory="Vision‑enabled analyst",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Extract text from https://example.com/receipt.png",
|
||||
expected_output="All detected text in plain text",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
|
||||
@@ -52,6 +52,14 @@ These tools enable your agents to work with various file formats and document ty
|
||||
<Card title="Directory Read Tool" icon="folder" href="/en/tools/file-document/directoryreadtool">
|
||||
Read and list directory contents, file structures, and metadata.
|
||||
</Card>
|
||||
|
||||
<Card title="OCR Tool" icon="image" href="/en/tools/file-document/ocrtool">
|
||||
Extract text from images (local files or URLs) using a vision‑capable LLM.
|
||||
</Card>
|
||||
|
||||
<Card title="PDF Text Writing Tool" icon="file-pdf" href="/en/tools/file-document/pdf-text-writing-tool">
|
||||
Write text at specific coordinates in PDFs, with optional custom fonts.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## **Common Use Cases**
|
||||
|
||||
76
docs/en/tools/file-document/pdf-text-writing-tool.mdx
Normal file
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: PDF Text Writing Tool
|
||||
description: The `PDFTextWritingTool` writes text to specific positions in a PDF, supporting custom fonts.
|
||||
icon: file-pdf
|
||||
---
|
||||
|
||||
# `PDFTextWritingTool`
|
||||
|
||||
## Description
|
||||
|
||||
Write text at precise coordinates on a PDF page, optionally embedding a custom TrueType font.
|
||||
|
||||
## Parameters
|
||||
|
||||
### Run Parameters
|
||||
|
||||
- `pdf_path` (str, required): Path to the input PDF.
|
||||
- `text` (str, required): Text to add.
|
||||
- `position` (tuple[int, int], required): `(x, y)` coordinates.
|
||||
- `font_size` (int, default `12`)
|
||||
- `font_color` (str, default `"0 0 0 rg"`)
|
||||
- `font_name` (str, default `"F1"`)
|
||||
- `font_file` (str, optional): Path to `.ttf` file.
|
||||
- `page_number` (int, default `0`)
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import PDFTextWritingTool
|
||||
|
||||
tool = PDFTextWritingTool()
|
||||
|
||||
agent = Agent(
|
||||
role="PDF Editor",
|
||||
goal="Annotate PDFs",
|
||||
backstory="Documentation specialist",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Write 'CONFIDENTIAL' at (72, 720) on page 1 of ./sample.pdf",
|
||||
expected_output="Confirmation message",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### Direct usage
|
||||
|
||||
```python Code
|
||||
from crewai_tools import PDFTextWritingTool
|
||||
|
||||
PDFTextWritingTool().run(
|
||||
pdf_path="./input.pdf",
|
||||
text="CONFIDENTIAL",
|
||||
position=(72, 720),
|
||||
font_size=18,
|
||||
page_number=0,
|
||||
)
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
- Coordinate origin is the bottom‑left corner.
|
||||
- If using a custom font (`font_file`), ensure it is a valid `.ttf`.
|
||||
|
||||
|
||||
@@ -117,4 +117,19 @@ agent = Agent(
|
||||
)
|
||||
```
|
||||
|
||||
## **Max Usage Count**
|
||||
|
||||
You can set a maximum usage count for a tool to prevent it from being used more than a certain number of times.
|
||||
By default, the max usage count is unlimited.
|
||||
|
||||
|
||||
|
||||
```python
|
||||
from crewai_tools import FileReadTool
|
||||
|
||||
tool = FileReadTool(max_usage_count=5, ...)
|
||||
```
|
||||
|
||||
|
||||
|
||||
Ready to explore? Pick a category above to discover tools that fit your use case!
|
||||
|
||||
112
docs/en/tools/search-research/arxivpapertool.mdx
Normal file
@@ -0,0 +1,112 @@
|
||||
---
|
||||
title: Arxiv Paper Tool
|
||||
description: The `ArxivPaperTool` searches arXiv for papers matching a query and optionally downloads PDFs.
|
||||
icon: box-archive
|
||||
---
|
||||
|
||||
# `ArxivPaperTool`
|
||||
|
||||
## Description
|
||||
|
||||
The `ArxivPaperTool` queries the arXiv API for academic papers and returns compact, readable results. It can also optionally download PDFs to disk.
|
||||
|
||||
## Installation
|
||||
|
||||
This tool has no special installation beyond `crewai-tools`.
|
||||
|
||||
```shell
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
No API key is required. This tool uses the public arXiv Atom API.
|
||||
|
||||
## Steps to Get Started
|
||||
|
||||
1. Initialize the tool.
|
||||
2. Provide a `search_query` (e.g., "transformer neural network").
|
||||
3. Optionally set `max_results` (1–100) and enable PDF downloads in the constructor.
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import ArxivPaperTool
|
||||
|
||||
tool = ArxivPaperTool(
|
||||
download_pdfs=False,
|
||||
save_dir="./arxiv_pdfs",
|
||||
use_title_as_filename=True,
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Find relevant arXiv papers",
|
||||
backstory="Expert at literature discovery",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Search arXiv for 'transformer neural network' and list top 5 results.",
|
||||
expected_output="A concise list of 5 relevant papers with titles, links, and summaries.",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### Direct usage (without Agent)
|
||||
|
||||
```python Code
|
||||
from crewai_tools import ArxivPaperTool
|
||||
|
||||
tool = ArxivPaperTool(
|
||||
download_pdfs=True,
|
||||
save_dir="./arxiv_pdfs",
|
||||
)
|
||||
print(tool.run(search_query="mixture of experts", max_results=3))
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
### Initialization Parameters
|
||||
|
||||
- `download_pdfs` (bool, default `False`): Whether to download PDFs.
|
||||
- `save_dir` (str, default `./arxiv_pdfs`): Directory to save PDFs.
|
||||
- `use_title_as_filename` (bool, default `False`): Use paper titles for filenames.
|
||||
|
||||
### Run Parameters
|
||||
|
||||
- `search_query` (str, required): The arXiv search query.
|
||||
- `max_results` (int, default `5`, range 1–100): Number of results.
|
||||
|
||||
## Output format
|
||||
|
||||
The tool returns a human‑readable list of papers with:
|
||||
- Title
|
||||
- Link (abs page)
|
||||
- Snippet/summary (truncated)
|
||||
|
||||
When `download_pdfs=True`, PDFs are saved to disk and the summary mentions saved files.
|
||||
|
||||
## Usage Notes
|
||||
|
||||
- The tool returns formatted text with key metadata and links.
|
||||
- When `download_pdfs=True`, PDFs will be stored in `save_dir`.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- If you receive a network timeout, re‑try or reduce `max_results`.
|
||||
- Invalid XML errors indicate an arXiv response parse issue; try a simpler query.
|
||||
- File system errors (e.g., permission denied) may occur when saving PDFs; ensure `save_dir` is writable.
|
||||
|
||||
## Related links
|
||||
|
||||
- arXiv API docs: https://info.arxiv.org/help/api/index.html
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Network issues, invalid XML, and OS errors are handled with informative messages.
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ pip install 'crewai[tools]'
|
||||
To effectively use the `BraveSearchTool`, follow these steps:
|
||||
|
||||
1. **Package Installation**: Confirm that the `crewai[tools]` package is installed in your Python environment.
|
||||
2. **API Key Acquisition**: Acquire a Brave Search API key by registering at [Brave Search API](https://api.search.brave.com/app/keys).
|
||||
2. **API Key Acquisition**: Acquire a Brave Search API key at https://api.search.brave.com/app/keys (sign in to generate a key).
|
||||
3. **Environment Configuration**: Store your obtained API key in an environment variable named `BRAVE_API_KEY` to facilitate its use by the tool.
|
||||
|
||||
## Example
|
||||
|
||||
80
docs/en/tools/search-research/databricks-query-tool.mdx
Normal file
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Databricks SQL Query Tool
|
||||
description: The `DatabricksQueryTool` executes SQL queries against Databricks workspace tables.
|
||||
icon: trowel-bricks
|
||||
---
|
||||
|
||||
# `DatabricksQueryTool`
|
||||
|
||||
## Description
|
||||
|
||||
Run SQL against Databricks workspace tables with either CLI profile or direct host/token authentication.
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
uv add crewai-tools[databricks-sdk]
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `DATABRICKS_CONFIG_PROFILE` or (`DATABRICKS_HOST` + `DATABRICKS_TOKEN`)
|
||||
|
||||
Create a personal access token and find host details in the Databricks workspace under User Settings → Developer.
|
||||
Docs: https://docs.databricks.com/en/dev-tools/auth/pat.html
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import DatabricksQueryTool
|
||||
|
||||
tool = DatabricksQueryTool(
|
||||
default_catalog="main",
|
||||
default_schema="default",
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Query Databricks",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="SELECT * FROM my_table LIMIT 10",
|
||||
expected_output="10 rows",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True,
|
||||
)
|
||||
result = crew.kickoff()
|
||||
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
- `query` (required): SQL query to execute
|
||||
- `catalog` (optional): Override default catalog
|
||||
- `db_schema` (optional): Override default schema
|
||||
- `warehouse_id` (optional): Override default SQL warehouse
|
||||
- `row_limit` (optional): Maximum rows to return (default: 1000)
|
||||
|
||||
## Defaults on initialization
|
||||
|
||||
- `default_catalog`
|
||||
- `default_schema`
|
||||
- `default_warehouse_id`
|
||||
|
||||
### Error handling & tips
|
||||
|
||||
- Authentication errors: verify `DATABRICKS_HOST` begins with `https://` and token is valid.
|
||||
- Permissions: ensure your SQL warehouse and schema are accessible by your token.
|
||||
- Limits: long‑running queries should be avoided in agent loops; add filters/limits.
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ pip install 'crewai[tools]'
|
||||
|
||||
This command installs the necessary package to run the GithubSearchTool along with any other tools included in the crewai_tools package.
|
||||
|
||||
Get a GitHub Personal Access Token at https://github.com/settings/tokens (Developer settings → Fine‑grained tokens or classic tokens).
|
||||
|
||||
## Example
|
||||
|
||||
Here’s how you can use the GithubSearchTool to perform semantic searches within a GitHub repository:
|
||||
|
||||
@@ -44,6 +44,26 @@ These tools enable your agents to search the web, research topics, and find info
|
||||
<Card title="YouTube Video Search" icon="play" href="/en/tools/search-research/youtubevideosearchtool">
|
||||
Find and analyze YouTube videos by topic, keyword, or criteria.
|
||||
</Card>
|
||||
|
||||
<Card title="Tavily Search Tool" icon="magnifying-glass" href="/en/tools/search-research/tavilysearchtool">
|
||||
Comprehensive web search using Tavily's AI-powered search API.
|
||||
</Card>
|
||||
|
||||
<Card title="Tavily Extractor Tool" icon="file-text" href="/en/tools/search-research/tavilyextractortool">
|
||||
Extract structured content from web pages using the Tavily API.
|
||||
</Card>
|
||||
|
||||
<Card title="Arxiv Paper Tool" icon="box-archive" href="/en/tools/search-research/arxivpapertool">
|
||||
Search arXiv and optionally download PDFs.
|
||||
</Card>
|
||||
|
||||
<Card title="SerpApi Google Search" icon="search" href="/en/tools/search-research/serpapi-googlesearchtool">
|
||||
Google search via SerpApi with structured results.
|
||||
</Card>
|
||||
|
||||
<Card title="SerpApi Google Shopping" icon="cart-shopping" href="/en/tools/search-research/serpapi-googleshoppingtool">
|
||||
Google Shopping queries via SerpApi.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## **Common Use Cases**
|
||||
@@ -55,17 +75,19 @@ These tools enable your agents to search the web, research topics, and find info
|
||||
- **Academic Research**: Find scholarly articles and technical papers
|
||||
|
||||
```python
|
||||
from crewai_tools import SerperDevTool, GitHubSearchTool, YoutubeVideoSearchTool
|
||||
from crewai_tools import SerperDevTool, GitHubSearchTool, YoutubeVideoSearchTool, TavilySearchTool, TavilyExtractorTool
|
||||
|
||||
# Create research tools
|
||||
web_search = SerperDevTool()
|
||||
code_search = GitHubSearchTool()
|
||||
video_research = YoutubeVideoSearchTool()
|
||||
tavily_search = TavilySearchTool()
|
||||
content_extractor = TavilyExtractorTool()
|
||||
|
||||
# Add to your agent
|
||||
agent = Agent(
|
||||
role="Research Analyst",
|
||||
tools=[web_search, code_search, video_research],
|
||||
tools=[web_search, code_search, video_research, tavily_search, content_extractor],
|
||||
goal="Gather comprehensive information on any topic"
|
||||
)
|
||||
```
|
||||
|
||||
65
docs/en/tools/search-research/serpapi-googlesearchtool.mdx
Normal file
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: SerpApi Google Search Tool
|
||||
description: The `SerpApiGoogleSearchTool` performs Google searches using the SerpApi service.
|
||||
icon: google
|
||||
---
|
||||
|
||||
# `SerpApiGoogleSearchTool`
|
||||
|
||||
## Description
|
||||
|
||||
Use the `SerpApiGoogleSearchTool` to run Google searches with SerpApi and retrieve structured results. Requires a SerpApi API key.
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
uv add crewai-tools[serpapi]
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `SERPAPI_API_KEY` (required): API key for SerpApi. Create one at https://serpapi.com/ (free tier available).
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import SerpApiGoogleSearchTool
|
||||
|
||||
tool = SerpApiGoogleSearchTool()
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Answer questions using Google search",
|
||||
backstory="Search specialist",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Search for the latest CrewAI releases",
|
||||
expected_output="A concise list of relevant results with titles and links",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Set `SERPAPI_API_KEY` in the environment. Create a key at https://serpapi.com/
|
||||
- See also Google Shopping via SerpApi: `/en/tools/search-research/serpapi-googleshoppingtool`
|
||||
|
||||
## Parameters
|
||||
|
||||
### Run Parameters
|
||||
|
||||
- `search_query` (str, required): The Google query.
|
||||
- `location` (str, optional): Geographic location parameter.
|
||||
|
||||
## Notes
|
||||
|
||||
- This tool wraps SerpApi and returns structured search results.
|
||||
|
||||
|
||||
61
docs/en/tools/search-research/serpapi-googleshoppingtool.mdx
Normal file
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: SerpApi Google Shopping Tool
|
||||
description: The `SerpApiGoogleShoppingTool` searches Google Shopping results using SerpApi.
|
||||
icon: cart-shopping
|
||||
---
|
||||
|
||||
# `SerpApiGoogleShoppingTool`
|
||||
|
||||
## Description
|
||||
|
||||
Leverage `SerpApiGoogleShoppingTool` to query Google Shopping via SerpApi and retrieve product-oriented results.
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
uv add crewai-tools[serpapi]
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `SERPAPI_API_KEY` (required): API key for SerpApi. Create one at https://serpapi.com/ (free tier available).
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import SerpApiGoogleShoppingTool
|
||||
|
||||
tool = SerpApiGoogleShoppingTool()
|
||||
|
||||
agent = Agent(
|
||||
role="Shopping Researcher",
|
||||
goal="Find relevant products",
|
||||
backstory="Expert in product search",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Search Google Shopping for 'wireless noise-canceling headphones'",
|
||||
expected_output="Top relevant products with titles and links",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Set `SERPAPI_API_KEY` in the environment. Create a key at https://serpapi.com/
|
||||
- See also Google Web Search via SerpApi: `/en/tools/search-research/serpapi-googlesearchtool`
|
||||
|
||||
## Parameters
|
||||
|
||||
### Run Parameters
|
||||
|
||||
- `search_query` (str, required): Product search query.
|
||||
- `location` (str, optional): Geographic location parameter.
|
||||
|
||||
|
||||
@@ -6,10 +6,6 @@ icon: google
|
||||
|
||||
# `SerperDevTool`
|
||||
|
||||
<Note>
|
||||
We are still working on improving tools, so there might be unexpected behavior or changes in the future.
|
||||
</Note>
|
||||
|
||||
## Description
|
||||
|
||||
This tool is designed to perform a semantic search for a specified query from a text's content across the internet. It utilizes the [serper.dev](https://serper.dev) API
|
||||
@@ -17,6 +13,12 @@ to fetch and display the most relevant search results based on the query provide
|
||||
|
||||
## Installation
|
||||
|
||||
To effectively use the `SerperDevTool`, follow these steps:
|
||||
|
||||
1. **Package Installation**: Confirm that the `crewai[tools]` package is installed in your Python environment.
|
||||
2. **API Key Acquisition**: Acquire a `serper.dev` API key at https://serper.dev/ (free tier available).
|
||||
3. **Environment Configuration**: Store your obtained API key in an environment variable named `SERPER_API_KEY` to facilitate its use by the tool.
|
||||
|
||||
To incorporate this tool into your project, follow the installation instructions below:
|
||||
|
||||
```shell
|
||||
@@ -34,14 +36,6 @@ from crewai_tools import SerperDevTool
|
||||
tool = SerperDevTool()
|
||||
```
|
||||
|
||||
## Steps to Get Started
|
||||
|
||||
To effectively use the `SerperDevTool`, follow these steps:
|
||||
|
||||
1. **Package Installation**: Confirm that the `crewai[tools]` package is installed in your Python environment.
|
||||
2. **API Key Acquisition**: Acquire a `serper.dev` API key by registering for a free account at `serper.dev`.
|
||||
3. **Environment Configuration**: Store your obtained API key in an environment variable named `SERPER_API_KEY` to facilitate its use by the tool.
|
||||
|
||||
## Parameters
|
||||
|
||||
The `SerperDevTool` comes with several parameters that will be passed to the API :
|
||||
|
||||
139
docs/en/tools/search-research/tavilyextractortool.mdx
Normal file
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: "Tavily Extractor Tool"
|
||||
description: "Extract structured content from web pages using the Tavily API"
|
||||
icon: square-poll-horizontal
|
||||
---
|
||||
|
||||
The `TavilyExtractorTool` allows CrewAI agents to extract structured content from web pages using the Tavily API. It can process single URLs or lists of URLs and provides options for controlling the extraction depth and including images.
|
||||
|
||||
## Installation
|
||||
|
||||
To use the `TavilyExtractorTool`, you need to install the `tavily-python` library:
|
||||
|
||||
```shell
|
||||
pip install 'crewai[tools]' tavily-python
|
||||
```
|
||||
|
||||
You also need to set your Tavily API key as an environment variable:
|
||||
|
||||
```bash
|
||||
export TAVILY_API_KEY='your-tavily-api-key'
|
||||
```
|
||||
|
||||
## Example Usage
|
||||
|
||||
Here's how to initialize and use the `TavilyExtractorTool` within a CrewAI agent:
|
||||
|
||||
```python
|
||||
import os
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import TavilyExtractorTool
|
||||
|
||||
# Ensure TAVILY_API_KEY is set in your environment
|
||||
# os.environ["TAVILY_API_KEY"] = "YOUR_API_KEY"
|
||||
|
||||
# Initialize the tool
|
||||
tavily_tool = TavilyExtractorTool()
|
||||
|
||||
# Create an agent that uses the tool
|
||||
extractor_agent = Agent(
|
||||
role='Web Content Extractor',
|
||||
goal='Extract key information from specified web pages',
|
||||
backstory='You are an expert at extracting relevant content from websites using the Tavily API.',
|
||||
tools=[tavily_tool],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Define a task for the agent
|
||||
extract_task = Task(
|
||||
description='Extract the main content from the URL https://example.com using basic extraction depth.',
|
||||
expected_output='A JSON string containing the extracted content from the URL.',
|
||||
agent=extractor_agent
|
||||
)
|
||||
|
||||
# Create and run the crew
|
||||
crew = Crew(
|
||||
agents=[extractor_agent],
|
||||
tasks=[extract_task],
|
||||
verbose=2
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
The `TavilyExtractorTool` accepts the following arguments:
|
||||
|
||||
- `urls` (Union[List[str], str]): **Required**. A single URL string or a list of URL strings to extract data from.
|
||||
- `include_images` (Optional[bool]): Whether to include images in the extraction results. Defaults to `False`.
|
||||
- `extract_depth` (Literal["basic", "advanced"]): The depth of extraction. Use `"basic"` for faster, surface-level extraction or `"advanced"` for more comprehensive extraction. Defaults to `"basic"`.
|
||||
- `timeout` (int): The maximum time in seconds to wait for the extraction request to complete. Defaults to `60`.
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Multiple URLs with Advanced Extraction
|
||||
|
||||
```python
|
||||
# Example with multiple URLs and advanced extraction
|
||||
multi_extract_task = Task(
|
||||
description='Extract content from https://example.com and https://anotherexample.org using advanced extraction.',
|
||||
expected_output='A JSON string containing the extracted content from both URLs.',
|
||||
agent=extractor_agent
|
||||
)
|
||||
|
||||
# Configure the tool with custom parameters
|
||||
custom_extractor = TavilyExtractorTool(
|
||||
extract_depth='advanced',
|
||||
include_images=True,
|
||||
timeout=120
|
||||
)
|
||||
|
||||
agent_with_custom_tool = Agent(
|
||||
role="Advanced Content Extractor",
|
||||
goal="Extract comprehensive content with images",
|
||||
tools=[custom_extractor]
|
||||
)
|
||||
```
|
||||
|
||||
### Tool Parameters
|
||||
|
||||
You can customize the tool's behavior by setting parameters during initialization:
|
||||
|
||||
```python
|
||||
# Initialize with custom configuration
|
||||
extractor_tool = TavilyExtractorTool(
|
||||
extract_depth='advanced', # More comprehensive extraction
|
||||
include_images=True, # Include image results
|
||||
timeout=90 # Custom timeout
|
||||
)
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Single or Multiple URLs**: Extract content from one URL or process multiple URLs in a single request
|
||||
- **Configurable Depth**: Choose between basic (fast) and advanced (comprehensive) extraction modes
|
||||
- **Image Support**: Optionally include images in the extraction results
|
||||
- **Structured Output**: Returns well-formatted JSON containing the extracted content
|
||||
- **Error Handling**: Robust handling of network timeouts and extraction errors
|
||||
|
||||
## Response Format
|
||||
|
||||
The tool returns a JSON string representing the structured data extracted from the provided URL(s). The exact structure depends on the content of the pages and the `extract_depth` used.
|
||||
|
||||
Common response elements include:
|
||||
- **Title**: The page title
|
||||
- **Content**: Main text content of the page
|
||||
- **Images**: Image URLs and metadata (when `include_images=True`)
|
||||
- **Metadata**: Additional page information like author, description, etc.
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Content Analysis**: Extract and analyze content from competitor websites
|
||||
- **Research**: Gather structured data from multiple sources for analysis
|
||||
- **Content Migration**: Extract content from existing websites for migration
|
||||
- **Monitoring**: Regular extraction of content for change detection
|
||||
- **Data Collection**: Systematic extraction of information from web sources
|
||||
|
||||
Refer to the [Tavily API documentation](https://docs.tavily.com/docs/tavily-api/python-sdk#extract) for detailed information about the response structure and available options.
|
||||
124
docs/en/tools/search-research/tavilysearchtool.mdx
Normal file
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: "Tavily Search Tool"
|
||||
description: "Perform comprehensive web searches using the Tavily Search API"
|
||||
icon: "magnifying-glass"
|
||||
---
|
||||
|
||||
The `TavilySearchTool` provides an interface to the Tavily Search API, enabling CrewAI agents to perform comprehensive web searches. It allows for specifying search depth, topics, time ranges, included/excluded domains, and whether to include direct answers, raw content, or images in the results.
|
||||
|
||||
## Installation
|
||||
|
||||
To use the `TavilySearchTool`, you need to install the `tavily-python` library:
|
||||
|
||||
```shell
|
||||
pip install 'crewai[tools]' tavily-python
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Ensure your Tavily API key is set as an environment variable:
|
||||
|
||||
```bash
|
||||
export TAVILY_API_KEY='your_tavily_api_key'
|
||||
```
|
||||
|
||||
Get an API key at https://app.tavily.com/ (sign up, then create a key).
|
||||
|
||||
## Example Usage
|
||||
|
||||
Here's how to initialize and use the `TavilySearchTool` within a CrewAI agent:
|
||||
|
||||
```python
|
||||
import os
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import TavilySearchTool
|
||||
|
||||
# Ensure the TAVILY_API_KEY environment variable is set
|
||||
# os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
|
||||
|
||||
# Initialize the tool
|
||||
tavily_tool = TavilySearchTool()
|
||||
|
||||
# Create an agent that uses the tool
|
||||
researcher = Agent(
|
||||
role='Market Researcher',
|
||||
goal='Find information about the latest AI trends',
|
||||
backstory='An expert market researcher specializing in technology.',
|
||||
tools=[tavily_tool],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create a task for the agent
|
||||
research_task = Task(
|
||||
description='Search for the top 3 AI trends in 2024.',
|
||||
expected_output='A JSON report summarizing the top 3 AI trends found.',
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Form the crew and kick it off
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[research_task],
|
||||
verbose=2
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
The `TavilySearchTool` accepts the following arguments during initialization or when calling the `run` method:
|
||||
|
||||
- `query` (str): **Required**. The search query string.
|
||||
- `search_depth` (Literal["basic", "advanced"], optional): The depth of the search. Defaults to `"basic"`.
|
||||
- `topic` (Literal["general", "news", "finance"], optional): The topic to focus the search on. Defaults to `"general"`.
|
||||
- `time_range` (Literal["day", "week", "month", "year"], optional): The time range for the search. Defaults to `None`.
|
||||
- `days` (int, optional): The number of days to search back. Relevant if `time_range` is not set. Defaults to `7`.
|
||||
- `max_results` (int, optional): The maximum number of search results to return. Defaults to `5`.
|
||||
- `include_domains` (Sequence[str], optional): A list of domains to prioritize in the search. Defaults to `None`.
|
||||
- `exclude_domains` (Sequence[str], optional): A list of domains to exclude from the search. Defaults to `None`.
|
||||
- `include_answer` (Union[bool, Literal["basic", "advanced"]], optional): Whether to include a direct answer synthesized from the search results. Defaults to `False`.
|
||||
- `include_raw_content` (bool, optional): Whether to include the raw HTML content of the searched pages. Defaults to `False`.
|
||||
- `include_images` (bool, optional): Whether to include image results. Defaults to `False`.
|
||||
- `timeout` (int, optional): The request timeout in seconds. Defaults to `60`.
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
You can configure the tool with custom parameters:
|
||||
|
||||
```python
|
||||
# Example: Initialize with specific parameters
|
||||
custom_tavily_tool = TavilySearchTool(
|
||||
search_depth='advanced',
|
||||
max_results=10,
|
||||
include_answer=True
|
||||
)
|
||||
|
||||
# The agent will use these defaults
|
||||
agent_with_custom_tool = Agent(
|
||||
role="Advanced Researcher",
|
||||
goal="Conduct detailed research with comprehensive results",
|
||||
tools=[custom_tavily_tool]
|
||||
)
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Comprehensive Search**: Access to Tavily's powerful search index
|
||||
- **Configurable Depth**: Choose between basic and advanced search modes
|
||||
- **Topic Filtering**: Focus searches on general, news, or finance topics
|
||||
- **Time Range Control**: Limit results to specific time periods
|
||||
- **Domain Control**: Include or exclude specific domains
|
||||
- **Direct Answers**: Get synthesized answers from search results
|
||||
- **Content Filtering**: Prevent context window issues with automatic content truncation
|
||||
|
||||
## Response Format
|
||||
|
||||
The tool returns search results as a JSON string containing:
|
||||
- Search results with titles, URLs, and content snippets
|
||||
- Optional direct answers to queries
|
||||
- Optional image results
|
||||
- Optional raw HTML content (when enabled)
|
||||
|
||||
Content for each result is automatically truncated to prevent context window issues while maintaining the most relevant information.
|
||||
111
docs/en/tools/web-scraping/brightdata-tools.mdx
Normal file
@@ -0,0 +1,111 @@
|
||||
---
|
||||
title: Bright Data Tools
|
||||
description: Bright Data integrations for SERP search, Web Unlocker scraping, and Dataset API.
|
||||
icon: spider
|
||||
---
|
||||
|
||||
# Bright Data Tools
|
||||
|
||||
This set of tools integrates Bright Data services for web extraction.
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
uv add crewai-tools requests aiohttp
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `BRIGHT_DATA_API_KEY` (required)
|
||||
- `BRIGHT_DATA_ZONE` (for SERP/Web Unlocker)
|
||||
|
||||
Create credentials at https://brightdata.com/ (sign up, then create an API token and zone).
|
||||
See their docs: https://developers.brightdata.com/
|
||||
|
||||
## Included Tools
|
||||
|
||||
- `BrightDataSearchTool`: SERP search (Google/Bing/Yandex) with geo/language/device options.
|
||||
- `BrightDataWebUnlockerTool`: Scrape pages with anti-bot bypass and rendering.
|
||||
- `BrightDataDatasetTool`: Run Dataset API jobs and fetch results.
|
||||
|
||||
## Examples
|
||||
|
||||
### SERP Search
|
||||
|
||||
```python Code
|
||||
from crewai_tools import BrightDataSearchTool
|
||||
|
||||
tool = BrightDataSearchTool(
|
||||
query="CrewAI",
|
||||
country="us",
|
||||
)
|
||||
|
||||
print(tool.run())
|
||||
```
|
||||
|
||||
### Web Unlocker
|
||||
|
||||
```python Code
|
||||
from crewai_tools import BrightDataWebUnlockerTool
|
||||
|
||||
tool = BrightDataWebUnlockerTool(
|
||||
url="https://example.com",
|
||||
format="markdown",
|
||||
)
|
||||
|
||||
print(tool.run(url="https://example.com"))
|
||||
```
|
||||
|
||||
### Dataset API
|
||||
|
||||
```python Code
|
||||
from crewai_tools import BrightDataDatasetTool
|
||||
|
||||
tool = BrightDataDatasetTool(
|
||||
dataset_type="ecommerce",
|
||||
url="https://example.com/product",
|
||||
)
|
||||
|
||||
print(tool.run())
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- 401/403: verify `BRIGHT_DATA_API_KEY` and `BRIGHT_DATA_ZONE`.
|
||||
- Empty/blocked content: enable rendering or try a different zone.
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import BrightDataSearchTool
|
||||
|
||||
tool = BrightDataSearchTool(
|
||||
query="CrewAI",
|
||||
country="us",
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role="Web Researcher",
|
||||
goal="Search with Bright Data",
|
||||
backstory="Finds reliable results",
|
||||
tools=[tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Search for CrewAI and summarize top results",
|
||||
expected_output="Short summary with links",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
|
||||
@@ -60,6 +60,10 @@ These tools enable your agents to interact with the web, extract data from websi
|
||||
<Card title="Oxylabs Scraper Tool" icon="globe" href="/en/tools/web-scraping/oxylabsscraperstool">
|
||||
Access web data at scale with Oxylabs.
|
||||
</Card>
|
||||
|
||||
<Card title="Bright Data Tools" icon="spider" href="/en/tools/web-scraping/brightdata-tools">
|
||||
SERP search, Web Unlocker, and Dataset API integrations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## **Common Use Cases**
|
||||
|
||||
100
docs/en/tools/web-scraping/serperscrapewebsitetool.mdx
Normal file
@@ -0,0 +1,100 @@
|
||||
---
|
||||
title: Serper Scrape Website
|
||||
description: The `SerperScrapeWebsiteTool` is designed to scrape websites and extract clean, readable content using Serper's scraping API.
|
||||
icon: globe
|
||||
---
|
||||
|
||||
# `SerperScrapeWebsiteTool`
|
||||
|
||||
## Description
|
||||
|
||||
This tool is designed to scrape website content and extract clean, readable text from any website URL. It utilizes the [serper.dev](https://serper.dev) scraping API to fetch and process web pages, optionally including markdown formatting for better structure and readability.
|
||||
|
||||
## Installation
|
||||
|
||||
To effectively use the `SerperScrapeWebsiteTool`, follow these steps:
|
||||
|
||||
1. **Package Installation**: Confirm that the `crewai[tools]` package is installed in your Python environment.
|
||||
2. **API Key Acquisition**: Acquire a `serper.dev` API key by registering for an account at `serper.dev`.
|
||||
3. **Environment Configuration**: Store your obtained API key in an environment variable named `SERPER_API_KEY` to facilitate its use by the tool.
|
||||
|
||||
To incorporate this tool into your project, follow the installation instructions below:
|
||||
|
||||
```shell
|
||||
pip install 'crewai[tools]'
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
The following example demonstrates how to initialize the tool and scrape a website:
|
||||
|
||||
```python Code
|
||||
from crewai_tools import SerperScrapeWebsiteTool
|
||||
|
||||
# Initialize the tool for website scraping capabilities
|
||||
tool = SerperScrapeWebsiteTool()
|
||||
|
||||
# Scrape a website with markdown formatting
|
||||
result = tool.run(url="https://example.com", include_markdown=True)
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
The `SerperScrapeWebsiteTool` accepts the following arguments:
|
||||
|
||||
- **url**: Required. The URL of the website to scrape.
|
||||
- **include_markdown**: Optional. Whether to include markdown formatting in the scraped content. Defaults to `True`.
|
||||
|
||||
## Example with Parameters
|
||||
|
||||
Here is an example demonstrating how to use the tool with different parameters:
|
||||
|
||||
```python Code
|
||||
from crewai_tools import SerperScrapeWebsiteTool
|
||||
|
||||
tool = SerperScrapeWebsiteTool()
|
||||
|
||||
# Scrape with markdown formatting (default)
|
||||
markdown_result = tool.run(
|
||||
url="https://docs.crewai.com",
|
||||
include_markdown=True
|
||||
)
|
||||
|
||||
# Scrape without markdown formatting for plain text
|
||||
plain_result = tool.run(
|
||||
url="https://docs.crewai.com",
|
||||
include_markdown=False
|
||||
)
|
||||
|
||||
print("Markdown formatted content:")
|
||||
print(markdown_result)
|
||||
|
||||
print("\nPlain text content:")
|
||||
print(plain_result)
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
The `SerperScrapeWebsiteTool` is particularly useful for:
|
||||
|
||||
- **Content Analysis**: Extract and analyze website content for research purposes
|
||||
- **Data Collection**: Gather structured information from web pages
|
||||
- **Documentation Processing**: Convert web-based documentation into readable formats
|
||||
- **Competitive Analysis**: Scrape competitor websites for market research
|
||||
- **Content Migration**: Extract content from existing websites for migration purposes
|
||||
|
||||
## Error Handling
|
||||
|
||||
The tool includes comprehensive error handling for:
|
||||
|
||||
- **Network Issues**: Handles connection timeouts and network errors gracefully
|
||||
- **API Errors**: Provides detailed error messages for API-related issues
|
||||
- **Invalid URLs**: Validates and reports issues with malformed URLs
|
||||
- **Authentication**: Clear error messages for missing or invalid API keys
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- Always store your `SERPER_API_KEY` in environment variables, never hardcode it in your source code
|
||||
- Be mindful of rate limits imposed by the Serper API
|
||||
- Respect robots.txt and website terms of service when scraping content
|
||||
- Consider implementing delays between requests for large-scale scraping operations
|
||||
435
docs/enterprise-api.en.yaml
Normal file
@@ -0,0 +1,435 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: CrewAI Enterprise API
|
||||
description: |
|
||||
REST API for interacting with your deployed CrewAI crews on CrewAI Enterprise.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. **Find your crew URL**: Get your unique crew URL from the CrewAI Enterprise dashboard
|
||||
2. **Copy examples**: Use the code examples from each endpoint page as templates
|
||||
3. **Replace placeholders**: Update URLs and tokens with your actual values
|
||||
4. **Test with your tools**: Use cURL, Postman, or your preferred API client
|
||||
|
||||
## Authentication
|
||||
|
||||
All API requests require a bearer token for authentication. There are two types of tokens:
|
||||
|
||||
- **Bearer Token**: Organization-level token for full crew operations
|
||||
- **User Bearer Token**: User-scoped token for individual access with limited permissions
|
||||
|
||||
You can find your bearer tokens in the Status tab of your crew's detail page in the CrewAI Enterprise dashboard.
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
This documentation provides comprehensive examples for each endpoint:
|
||||
|
||||
- **Request formats** with all required and optional parameters
|
||||
- **Response examples** for success and error scenarios
|
||||
- **Code samples** in multiple programming languages
|
||||
- **Authentication patterns** with proper Bearer token usage
|
||||
|
||||
Copy the examples and customize them with your actual crew URL and authentication tokens.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Discover inputs** using `GET /inputs`
|
||||
2. **Start execution** using `POST /kickoff`
|
||||
3. **Monitor progress** using `GET /status/{kickoff_id}`
|
||||
version: 1.0.0
|
||||
contact:
|
||||
name: CrewAI Support
|
||||
email: support@crewai.com
|
||||
url: https://crewai.com
|
||||
servers:
|
||||
- url: https://your-actual-crew-name.crewai.com
|
||||
description: Replace with your actual deployed crew URL from the CrewAI Enterprise dashboard
|
||||
- url: https://my-travel-crew.crewai.com
|
||||
description: Example travel planning crew (replace with your URL)
|
||||
- url: https://content-creation-crew.crewai.com
|
||||
description: Example content creation crew (replace with your URL)
|
||||
- url: https://research-assistant-crew.crewai.com
|
||||
description: Example research assistant crew (replace with your URL)
|
||||
security:
|
||||
- BearerAuth: []
|
||||
paths:
|
||||
/inputs:
|
||||
get:
|
||||
summary: Get Required Inputs
|
||||
description: |
|
||||
**📋 Reference Example Only** - *This shows the request format. To test with your actual crew, copy the cURL example and replace the URL + token with your real values.*
|
||||
|
||||
Retrieves the list of all required input parameters that your crew expects for execution.
|
||||
Use this endpoint to discover what inputs you need to provide when starting a crew execution.
|
||||
operationId: getRequiredInputs
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully retrieved required inputs
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
inputs:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Array of required input parameter names
|
||||
example: ["budget", "interests", "duration", "age"]
|
||||
examples:
|
||||
travel_crew:
|
||||
summary: Travel planning crew inputs
|
||||
value:
|
||||
inputs: ["budget", "interests", "duration", "age"]
|
||||
outreach_crew:
|
||||
summary: Outreach crew inputs
|
||||
value:
|
||||
inputs: ["name", "title", "company", "industry", "our_product", "linkedin_url"]
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFoundError'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
/kickoff:
|
||||
post:
|
||||
summary: Start Crew Execution
|
||||
description: |
|
||||
**📋 Reference Example Only** - *This shows the request format. To test with your actual crew, copy the cURL example and replace the URL + token with your real values.*
|
||||
|
||||
Initiates a new crew execution with the provided inputs. Returns a kickoff ID that can be used
|
||||
to track the execution progress and retrieve results.
|
||||
|
||||
Crew executions can take anywhere from seconds to minutes depending on their complexity.
|
||||
Consider using webhooks for real-time notifications or implement polling with the status endpoint.
|
||||
operationId: startCrewExecution
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- inputs
|
||||
properties:
|
||||
inputs:
|
||||
type: object
|
||||
description: Key-value pairs of all required inputs for your crew
|
||||
additionalProperties:
|
||||
type: string
|
||||
example:
|
||||
budget: "1000 USD"
|
||||
interests: "games, tech, ai, relaxing hikes, amazing food"
|
||||
duration: "7 days"
|
||||
age: "35"
|
||||
meta:
|
||||
type: object
|
||||
description: Additional metadata to pass to the crew
|
||||
additionalProperties: true
|
||||
example:
|
||||
requestId: "user-request-12345"
|
||||
source: "mobile-app"
|
||||
taskWebhookUrl:
|
||||
type: string
|
||||
format: uri
|
||||
description: Callback URL executed after each task completion
|
||||
example: "https://your-server.com/webhooks/task"
|
||||
stepWebhookUrl:
|
||||
type: string
|
||||
format: uri
|
||||
description: Callback URL executed after each agent thought/action
|
||||
example: "https://your-server.com/webhooks/step"
|
||||
crewWebhookUrl:
|
||||
type: string
|
||||
format: uri
|
||||
description: Callback URL executed when the crew execution completes
|
||||
example: "https://your-server.com/webhooks/crew"
|
||||
examples:
|
||||
travel_planning:
|
||||
summary: Travel planning crew
|
||||
value:
|
||||
inputs:
|
||||
budget: "1000 USD"
|
||||
interests: "games, tech, ai, relaxing hikes, amazing food"
|
||||
duration: "7 days"
|
||||
age: "35"
|
||||
meta:
|
||||
requestId: "travel-req-123"
|
||||
source: "web-app"
|
||||
outreach_campaign:
|
||||
summary: Outreach crew with webhooks
|
||||
value:
|
||||
inputs:
|
||||
name: "John Smith"
|
||||
title: "CTO"
|
||||
company: "TechCorp"
|
||||
industry: "Software"
|
||||
our_product: "AI Development Platform"
|
||||
linkedin_url: "https://linkedin.com/in/johnsmith"
|
||||
taskWebhookUrl: "https://api.example.com/webhooks/task"
|
||||
crewWebhookUrl: "https://api.example.com/webhooks/crew"
|
||||
responses:
|
||||
'200':
|
||||
description: Crew execution started successfully
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
kickoff_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Unique identifier for tracking this execution
|
||||
example: "abcd1234-5678-90ef-ghij-klmnopqrstuv"
|
||||
'400':
|
||||
description: Invalid request body or missing required inputs
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'422':
|
||||
description: Validation error - ensure all required inputs are provided
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ValidationError'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
/status/{kickoff_id}:
|
||||
get:
|
||||
summary: Get Execution Status
|
||||
description: |
|
||||
**📋 Reference Example Only** - *This shows the request format. To test with your actual crew, copy the cURL example and replace the URL + token with your real values.*
|
||||
|
||||
Retrieves the current status and results of a crew execution using its kickoff ID.
|
||||
|
||||
The response structure varies depending on the execution state:
|
||||
- **running**: Execution in progress with current task info
|
||||
- **completed**: Execution finished with full results
|
||||
- **error**: Execution failed with error details
|
||||
operationId: getExecutionStatus
|
||||
parameters:
|
||||
- name: kickoff_id
|
||||
in: path
|
||||
required: true
|
||||
description: The kickoff ID returned from the /kickoff endpoint
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "abcd1234-5678-90ef-ghij-klmnopqrstuv"
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully retrieved execution status
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/ExecutionRunning'
|
||||
- $ref: '#/components/schemas/ExecutionCompleted'
|
||||
- $ref: '#/components/schemas/ExecutionError'
|
||||
examples:
|
||||
running:
|
||||
summary: Execution in progress
|
||||
value:
|
||||
status: "running"
|
||||
current_task: "research_task"
|
||||
progress:
|
||||
completed_tasks: 1
|
||||
total_tasks: 3
|
||||
completed:
|
||||
summary: Execution completed successfully
|
||||
value:
|
||||
status: "completed"
|
||||
result:
|
||||
output: "Comprehensive travel itinerary for 7 days in Japan focusing on tech culture..."
|
||||
tasks:
|
||||
- task_id: "research_task"
|
||||
output: "Research findings on tech destinations in Japan..."
|
||||
agent: "Travel Researcher"
|
||||
execution_time: 45.2
|
||||
- task_id: "planning_task"
|
||||
output: "7-day detailed itinerary with activities and recommendations..."
|
||||
agent: "Trip Planner"
|
||||
execution_time: 62.8
|
||||
execution_time: 108.5
|
||||
error:
|
||||
summary: Execution failed
|
||||
value:
|
||||
status: "error"
|
||||
error: "Task execution failed: Invalid API key for external service"
|
||||
execution_time: 23.1
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'404':
|
||||
description: Kickoff ID not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
example:
|
||||
error: "Execution not found"
|
||||
message: "No execution found with ID: abcd1234-5678-90ef-ghij-klmnopqrstuv"
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
description: |
|
||||
**📋 Reference Documentation** - *The tokens shown in examples are placeholders for reference only.*
|
||||
|
||||
Use your actual Bearer Token or User Bearer Token from the CrewAI Enterprise dashboard for real API calls.
|
||||
|
||||
**Bearer Token**: Organization-level access for full crew operations
|
||||
**User Bearer Token**: User-scoped access with limited permissions
|
||||
|
||||
schemas:
|
||||
ExecutionRunning:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["running"]
|
||||
example: "running"
|
||||
current_task:
|
||||
type: string
|
||||
description: Name of the currently executing task
|
||||
example: "research_task"
|
||||
progress:
|
||||
type: object
|
||||
properties:
|
||||
completed_tasks:
|
||||
type: integer
|
||||
description: Number of completed tasks
|
||||
example: 1
|
||||
total_tasks:
|
||||
type: integer
|
||||
description: Total number of tasks in the crew
|
||||
example: 3
|
||||
|
||||
ExecutionCompleted:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["completed"]
|
||||
example: "completed"
|
||||
result:
|
||||
type: object
|
||||
properties:
|
||||
output:
|
||||
type: string
|
||||
description: Final output from the crew execution
|
||||
example: "Comprehensive travel itinerary..."
|
||||
tasks:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/TaskResult'
|
||||
execution_time:
|
||||
type: number
|
||||
description: Total execution time in seconds
|
||||
example: 108.5
|
||||
|
||||
ExecutionError:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["error"]
|
||||
example: "error"
|
||||
error:
|
||||
type: string
|
||||
description: Error message describing what went wrong
|
||||
example: "Task execution failed: Invalid API key"
|
||||
execution_time:
|
||||
type: number
|
||||
description: Time until error occurred in seconds
|
||||
example: 23.1
|
||||
|
||||
TaskResult:
|
||||
type: object
|
||||
properties:
|
||||
task_id:
|
||||
type: string
|
||||
description: Unique identifier for the task
|
||||
example: "research_task"
|
||||
output:
|
||||
type: string
|
||||
description: Output generated by this task
|
||||
example: "Research findings..."
|
||||
agent:
|
||||
type: string
|
||||
description: Name of the agent that executed this task
|
||||
example: "Travel Researcher"
|
||||
execution_time:
|
||||
type: number
|
||||
description: Time taken to execute this task in seconds
|
||||
example: 45.2
|
||||
|
||||
Error:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Error type or title
|
||||
example: "Authentication Error"
|
||||
message:
|
||||
type: string
|
||||
description: Detailed error message
|
||||
example: "Invalid bearer token provided"
|
||||
|
||||
ValidationError:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Validation Error"
|
||||
message:
|
||||
type: string
|
||||
example: "Missing required inputs"
|
||||
details:
|
||||
type: object
|
||||
properties:
|
||||
missing_inputs:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
example: ["budget", "interests"]
|
||||
|
||||
responses:
|
||||
UnauthorizedError:
|
||||
description: Authentication failed - check your bearer token
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
example:
|
||||
error: "Unauthorized"
|
||||
message: "Invalid or missing bearer token"
|
||||
|
||||
NotFoundError:
|
||||
description: Resource not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
example:
|
||||
error: "Not Found"
|
||||
message: "The requested resource was not found"
|
||||
|
||||
ServerError:
|
||||
description: Internal server error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
example:
|
||||
error: "Internal Server Error"
|
||||
message: "An unexpected error occurred"
|
||||
|
||||
231
docs/enterprise-api.ko.yaml
Normal file
@@ -0,0 +1,231 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: CrewAI 엔터프라이즈 API
|
||||
description: |
|
||||
CrewAI Enterprise에 배포된 crew와 상호작용하기 위한 REST API입니다.
|
||||
|
||||
## 시작하기
|
||||
1. **Crew URL 확인**: 대시보드에서 고유한 crew URL을 확인하세요
|
||||
2. **예제 복사**: 각 엔드포인트의 예제를 템플릿으로 사용하세요
|
||||
3. **플레이스홀더 교체**: 실제 URL과 토큰으로 바꾸세요
|
||||
4. **도구로 테스트**: cURL, Postman 등 선호하는 도구로 테스트하세요
|
||||
version: 1.0.0
|
||||
contact:
|
||||
name: CrewAI 지원
|
||||
email: support@crewai.com
|
||||
url: https://crewai.com
|
||||
servers:
|
||||
- url: https://your-actual-crew-name.crewai.com
|
||||
description: 대시보드의 실제 crew URL로 교체하세요
|
||||
security:
|
||||
- BearerAuth: []
|
||||
paths:
|
||||
/inputs:
|
||||
get:
|
||||
summary: 필요 입력값 조회
|
||||
description: |
|
||||
**📋 참조 예제만 제공** - *요청 형식을 보여줍니다. 실제 호출은 cURL 예제를 복사해 URL과 토큰을 교체하세요.*
|
||||
|
||||
실행에 필요한 입력 파라미터 목록을 반환합니다.
|
||||
operationId: getRequiredInputs
|
||||
responses:
|
||||
'200':
|
||||
description: 입력값을 성공적으로 조회
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
inputs:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFoundError'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
/kickoff:
|
||||
post:
|
||||
summary: Crew 실행 시작
|
||||
description: |
|
||||
**📋 참조 예제만 제공** - *요청 형식을 보여줍니다. 실제 호출은 cURL 예제를 복사해 URL과 토큰을 교체하세요.*
|
||||
|
||||
제공된 입력으로 새로운 실행을 시작하고 kickoff ID를 반환합니다.
|
||||
operationId: startCrewExecution
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- inputs
|
||||
properties:
|
||||
inputs:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: 실행이 성공적으로 시작됨
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
kickoff_id:
|
||||
type: string
|
||||
format: uuid
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
/status/{kickoff_id}:
|
||||
get:
|
||||
summary: 실행 상태 조회
|
||||
description: |
|
||||
**📋 참조 예제만 제공** - *요청 형식을 보여줍니다. 실제 호출은 cURL 예제를 복사해 URL과 토큰을 교체하세요.*
|
||||
|
||||
kickoff ID로 실행 상태와 결과를 조회합니다.
|
||||
operationId: getExecutionStatus
|
||||
parameters:
|
||||
- name: kickoff_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
responses:
|
||||
'200':
|
||||
description: 상태를 성공적으로 조회
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/ExecutionRunning'
|
||||
- $ref: '#/components/schemas/ExecutionCompleted'
|
||||
- $ref: '#/components/schemas/ExecutionError'
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'404':
|
||||
description: Kickoff ID를 찾을 수 없음
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
description: |
|
||||
**📋 참고** - *예시의 토큰은 자리 표시자입니다.* 실제 토큰을 사용하세요.
|
||||
|
||||
schemas:
|
||||
ExecutionRunning:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["running"]
|
||||
current_task:
|
||||
type: string
|
||||
progress:
|
||||
type: object
|
||||
properties:
|
||||
completed_tasks:
|
||||
type: integer
|
||||
total_tasks:
|
||||
type: integer
|
||||
|
||||
ExecutionCompleted:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["completed"]
|
||||
result:
|
||||
type: object
|
||||
properties:
|
||||
output:
|
||||
type: string
|
||||
tasks:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/TaskResult'
|
||||
execution_time:
|
||||
type: number
|
||||
|
||||
ExecutionError:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["error"]
|
||||
error:
|
||||
type: string
|
||||
execution_time:
|
||||
type: number
|
||||
|
||||
TaskResult:
|
||||
type: object
|
||||
properties:
|
||||
task_id:
|
||||
type: string
|
||||
output:
|
||||
type: string
|
||||
agent:
|
||||
type: string
|
||||
execution_time:
|
||||
type: number
|
||||
|
||||
Error:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
|
||||
ValidationError:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
details:
|
||||
type: object
|
||||
properties:
|
||||
missing_inputs:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
|
||||
responses:
|
||||
UnauthorizedError:
|
||||
description: 인증 실패
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
NotFoundError:
|
||||
description: 리소스를 찾을 수 없음
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
ServerError:
|
||||
description: 서버 내부 오류
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
268
docs/enterprise-api.pt-BR.yaml
Normal file
@@ -0,0 +1,268 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: CrewAI Enterprise API
|
||||
description: |
|
||||
REST API para interagir com suas crews implantadas no CrewAI Enterprise.
|
||||
|
||||
## Introdução
|
||||
|
||||
1. **Encontre a URL da sua crew**: Obtenha sua URL única no painel do CrewAI Enterprise
|
||||
2. **Copie os exemplos**: Use os exemplos de cada endpoint como modelo
|
||||
3. **Substitua os placeholders**: Atualize URLs e tokens com seus valores reais
|
||||
4. **Teste com suas ferramentas**: Use cURL, Postman ou seu cliente preferido
|
||||
|
||||
## Autenticação
|
||||
|
||||
Todas as requisições exigem um token bearer. Existem dois tipos:
|
||||
|
||||
- **Bearer Token**: Token em nível de organização para operações completas
|
||||
- **User Bearer Token**: Token com escopo de usuário com permissões limitadas
|
||||
|
||||
Você encontra os tokens na aba Status da sua crew no painel do CrewAI Enterprise.
|
||||
|
||||
## Documentação de Referência
|
||||
|
||||
Este documento fornece exemplos completos para cada endpoint:
|
||||
|
||||
- **Formatos de requisição** com parâmetros obrigatórios e opcionais
|
||||
- **Exemplos de resposta** para sucesso e erro
|
||||
- **Amostras de código** em várias linguagens
|
||||
- **Padrões de autenticação** com uso correto de Bearer token
|
||||
|
||||
Copie os exemplos e personalize com sua URL e tokens reais.
|
||||
|
||||
## Fluxo
|
||||
|
||||
1. **Descubra os inputs** usando `GET /inputs`
|
||||
2. **Inicie a execução** usando `POST /kickoff`
|
||||
3. **Monitore o progresso** usando `GET /status/{kickoff_id}`
|
||||
version: 1.0.0
|
||||
contact:
|
||||
name: CrewAI Suporte
|
||||
email: support@crewai.com
|
||||
url: https://crewai.com
|
||||
servers:
|
||||
- url: https://your-actual-crew-name.crewai.com
|
||||
description: Substitua pela URL real da sua crew no painel do CrewAI Enterprise
|
||||
security:
|
||||
- BearerAuth: []
|
||||
paths:
|
||||
/inputs:
|
||||
get:
|
||||
summary: Obter Inputs Requeridos
|
||||
description: |
|
||||
**📋 Exemplo de Referência** - *Mostra o formato da requisição. Para testar com sua crew real, copie o cURL e substitua URL + token.*
|
||||
|
||||
Retorna a lista de parâmetros de entrada que sua crew espera.
|
||||
operationId: getRequiredInputs
|
||||
responses:
|
||||
'200':
|
||||
description: Inputs requeridos obtidos com sucesso
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
inputs:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Nomes dos parâmetros de entrada
|
||||
example: ["budget", "interests", "duration", "age"]
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFoundError'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
/kickoff:
|
||||
post:
|
||||
summary: Iniciar Execução da Crew
|
||||
description: |
|
||||
**📋 Exemplo de Referência** - *Mostra o formato da requisição. Para testar com sua crew real, copie o cURL e substitua URL + token.*
|
||||
|
||||
Inicia uma nova execução da crew com os inputs fornecidos e retorna um kickoff ID.
|
||||
operationId: startCrewExecution
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- inputs
|
||||
properties:
|
||||
inputs:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: string
|
||||
example:
|
||||
budget: "1000 USD"
|
||||
interests: "games, tech, ai, relaxing hikes, amazing food"
|
||||
duration: "7 days"
|
||||
age: "35"
|
||||
|
||||
responses:
|
||||
'200':
|
||||
description: Execução iniciada com sucesso
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
kickoff_id:
|
||||
type: string
|
||||
format: uuid
|
||||
example: "abcd1234-5678-90ef-ghij-klmnopqrstuv"
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
/status/{kickoff_id}:
|
||||
get:
|
||||
summary: Obter Status da Execução
|
||||
description: |
|
||||
**📋 Exemplo de Referência** - *Mostra o formato da requisição. Para testar com sua crew real, copie o cURL e substitua URL + token.*
|
||||
|
||||
Retorna o status atual e os resultados de uma execução usando o kickoff ID.
|
||||
operationId: getExecutionStatus
|
||||
parameters:
|
||||
- name: kickoff_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
responses:
|
||||
'200':
|
||||
description: Status recuperado com sucesso
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/ExecutionRunning'
|
||||
- $ref: '#/components/schemas/ExecutionCompleted'
|
||||
- $ref: '#/components/schemas/ExecutionError'
|
||||
'401':
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
'404':
|
||||
description: Kickoff ID não encontrado
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
'500':
|
||||
$ref: '#/components/responses/ServerError'
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
description: |
|
||||
**📋 Referência** - *Os tokens mostrados são apenas exemplos.*
|
||||
Use seus tokens reais do painel do CrewAI Enterprise.
|
||||
|
||||
schemas:
|
||||
ExecutionRunning:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["running"]
|
||||
current_task:
|
||||
type: string
|
||||
progress:
|
||||
type: object
|
||||
properties:
|
||||
completed_tasks:
|
||||
type: integer
|
||||
total_tasks:
|
||||
type: integer
|
||||
|
||||
ExecutionCompleted:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["completed"]
|
||||
result:
|
||||
type: object
|
||||
properties:
|
||||
output:
|
||||
type: string
|
||||
tasks:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/TaskResult'
|
||||
execution_time:
|
||||
type: number
|
||||
|
||||
ExecutionError:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["error"]
|
||||
error:
|
||||
type: string
|
||||
execution_time:
|
||||
type: number
|
||||
|
||||
TaskResult:
|
||||
type: object
|
||||
properties:
|
||||
task_id:
|
||||
type: string
|
||||
output:
|
||||
type: string
|
||||
agent:
|
||||
type: string
|
||||
execution_time:
|
||||
type: number
|
||||
|
||||
Error:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
|
||||
ValidationError:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
details:
|
||||
type: object
|
||||
properties:
|
||||
missing_inputs:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
|
||||
responses:
|
||||
UnauthorizedError:
|
||||
description: Autenticação falhou
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
NotFoundError:
|
||||
description: Recurso não encontrado
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
ServerError:
|
||||
description: Erro interno do servidor
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Error'
|
||||
|
||||
|
Before Width: | Height: | Size: 288 KiB |
|
Before Width: | Height: | Size: 419 KiB |
|
Before Width: | Height: | Size: 263 KiB |
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 72 KiB |
BIN
docs/images/enterprise/list-available-triggers.png
Normal file
|
After Width: | Height: | Size: 142 KiB |
BIN
docs/images/enterprise/list-executions.png
Normal file
|
After Width: | Height: | Size: 330 KiB |
BIN
docs/images/enterprise/trigger-selected.png
Normal file
|
After Width: | Height: | Size: 133 KiB |
BIN
docs/images/enterprise/users_and_roles.png
Normal file
|
After Width: | Height: | Size: 248 KiB |
BIN
docs/images/enterprise/visibility.png
Normal file
|
After Width: | Height: | Size: 472 KiB |
BIN
docs/images/gateway-metrics.png
Normal file
|
After Width: | Height: | Size: 530 KiB |
BIN
docs/images/langdb-1.png
Normal file
|
After Width: | Height: | Size: 127 KiB |
BIN
docs/images/langdb-2.png
Normal file
|
After Width: | Height: | Size: 117 KiB |
BIN
docs/images/neatlogs-1.png
Normal file
|
After Width: | Height: | Size: 222 KiB |
BIN
docs/images/neatlogs-2.png
Normal file
|
After Width: | Height: | Size: 329 KiB |
BIN
docs/images/neatlogs-3.png
Normal file
|
After Width: | Height: | Size: 590 KiB |
BIN
docs/images/neatlogs-4.png
Normal file
|
After Width: | Height: | Size: 216 KiB |
BIN
docs/images/neatlogs-5.png
Normal file
|
After Width: | Height: | Size: 277 KiB |
BIN
docs/images/new-code-snippet.png
Normal file
|
After Width: | Height: | Size: 554 KiB |
BIN
docs/images/tracing_crewai.png
Normal file
|
After Width: | Height: | Size: 128 KiB |
7
docs/ko/api-reference/inputs.mdx
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
title: "GET /inputs"
|
||||
description: "크루가 필요로 하는 입력 확인"
|
||||
openapi: "/enterprise-api.ko.yaml GET /inputs"
|
||||
---
|
||||
|
||||
|
||||
119
docs/ko/api-reference/introduction.mdx
Normal 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>
|
||||
7
docs/ko/api-reference/kickoff.mdx
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
title: "POST /kickoff"
|
||||
description: "크루 실행 시작"
|
||||
openapi: "/enterprise-api.ko.yaml POST /kickoff"
|
||||
---
|
||||
|
||||
|
||||
7
docs/ko/api-reference/status.mdx
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
title: "GET /status/{kickoff_id}"
|
||||
description: "실행 상태 조회"
|
||||
openapi: "/enterprise-api.ko.yaml GET /status/{kickoff_id}"
|
||||
---
|
||||
|
||||
|
||||
690
docs/ko/concepts/agents.mdx
Normal file
@@ -0,0 +1,690 @@
|
||||
---
|
||||
title: 에이전트
|
||||
description: CrewAI 프레임워크 내에서 에이전트를 생성하고 관리하는 자세한 가이드입니다.
|
||||
icon: robot
|
||||
---
|
||||
|
||||
## 에이전트 개요
|
||||
|
||||
CrewAI 프레임워크에서 `Agent`는 다음과 같은 역할을 수행하는 자율적 단위입니다:
|
||||
- 특정 작업 수행
|
||||
- 자신의 역할과 목표에 기반한 의사결정
|
||||
- 도구를 활용하여 목표 달성
|
||||
- 다른 에이전트와의 소통 및 협업
|
||||
- 상호작용에 대한 기억 유지
|
||||
- 허용될 경우 작업 위임
|
||||
|
||||
<Tip>
|
||||
에이전트는 특정한 기술, 전문성, 책임을 가진 전문 팀원이라고 생각하시면 됩니다. 예를 들어, `Researcher` 에이전트는 정보 수집 및 분석에 뛰어날 수 있고, `Writer` 에이전트는 콘텐츠 작성에 더 강점을 가질 수 있습니다.
|
||||
</Tip>
|
||||
|
||||
<Note type="info" title="엔터프라이즈 확장: 시각적 에이전트 빌더">
|
||||
CrewAI Enterprise에는 코드를 작성하지 않고도 에이전트 생성 및 구성을 간편하게 할 수 있는 시각적 에이전트 빌더가 포함되어 있습니다. 에이전트를 시각적으로 설계하고 실시간으로 테스트하세요.
|
||||
|
||||

|
||||
|
||||
시각적 에이전트 빌더를 통해 다음과 같은 기능을 사용할 수 있습니다:
|
||||
- 폼 기반 인터페이스를 통한 직관적 에이전트 구성
|
||||
- 실시간 테스트 및 검증
|
||||
- 사전 구성된 에이전트 유형 템플릿 라이브러리
|
||||
- 에이전트 속성 및 행동의 손쉬운 커스터마이즈
|
||||
</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
@@ -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>
|
||||
362
docs/ko/concepts/collaboration.mdx
Normal 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
@@ -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 작업부터 다시 실행할 수 있습니다.
|
||||
312
docs/ko/concepts/event-listener.mdx
Normal file
@@ -0,0 +1,312 @@
|
||||
---
|
||||
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을 통해 다음과 같은 작업이 가능합니다:
|
||||
- LLM에 전송된 모든 prompt의 전체 기록 보기
|
||||
- token 사용량 및 비용 추적
|
||||
- agent reasoning 실패 디버깅
|
||||
- 팀 내에서 prompt 시퀀스 공유
|
||||
- 다양한 prompt 전략 비교
|
||||
- 컴플라이언스 및 감사를 위한 trace 내보내기
|
||||
</Note>
|
||||
|
||||
## 커스텀 이벤트 리스너 생성하기
|
||||
|
||||
커스텀 이벤트 리스너를 생성하려면 다음 단계를 따라야 합니다:
|
||||
|
||||
1. `BaseEventListener`를 상속하는 클래스를 생성합니다.
|
||||
2. `setup_listeners` 메서드를 구현합니다.
|
||||
3. 원하는 이벤트에 대한 핸들러를 등록합니다.
|
||||
4. 해당 파일에서 리스너의 인스턴스를 생성합니다.
|
||||
|
||||
아래는 커스텀 이벤트 리스너 클래스의 간단한 예시입니다:
|
||||
|
||||
```python
|
||||
from crewai.events import (
|
||||
CrewKickoffStartedEvent,
|
||||
CrewKickoffCompletedEvent,
|
||||
AgentExecutionCompletedEvent,
|
||||
)
|
||||
from crewai.events 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.events 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 코드베이스에서 서드파티 이벤트 리스너가 등록되는 방식입니다.
|
||||
|
||||
## 사용 가능한 이벤트 유형
|
||||
|
||||
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` 필드가 포함됩니다.
|
||||
|
||||
|
||||
## 고급 사용법: Scoped Handlers
|
||||
|
||||
임시 이벤트 처리가 필요한 경우(테스트 또는 특정 작업에 유용함), `scoped_handlers` 컨텍스트 관리자를 사용할 수 있습니다:
|
||||
|
||||
```python
|
||||
from crewai.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
@@ -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}")
|
||||
```
|
||||

|
||||
위 예제에서는 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>
|
||||

|
||||
|
||||
이 예제에서 `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>
|
||||
|
||||

|
||||
|
||||
이 예시에서 상태는 `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()
|
||||
```
|
||||
|
||||

|
||||
|
||||
**참고:** `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()
|
||||
```
|
||||
|
||||

|
||||
|
||||
**핵심 포인트:**
|
||||
|
||||
- **정의된 스키마:** `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를 실행하면, `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를 실행하면, `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>
|
||||
|
||||

|
||||
|
||||
위 예제에서 `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())
|
||||
```
|
||||
|
||||

|
||||
|
||||
이 예시는 플로우에서 에이전트를 사용할 때의 몇 가지 주요 기능을 보여줍니다:
|
||||
|
||||
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이 생성됩니다.
|
||||
|
||||

|
||||
|
||||
### 플로우 실행하기
|
||||
|
||||
(선택 사항) 플로우를 실행하기 전에, 다음 명령어를 실행하여 의존성을 설치할 수 있습니다:
|
||||
|
||||
```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 모두에 작동하므로 더욱 선호되는 방법입니다.
|
||||
961
docs/ko/concepts/knowledge.mdx
Normal 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.events import (
|
||||
KnowledgeRetrievalStartedEvent,
|
||||
KnowledgeRetrievalCompletedEvent,
|
||||
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
@@ -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.events import (
|
||||
LLMStreamChunkEvent
|
||||
)
|
||||
from crewai.events 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.events import LLMStreamChunkEvent
|
||||
from crewai.events 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
152
docs/ko/concepts/planning.mdx
Normal 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>
|
||||
66
docs/ko/concepts/processes.mdx
Normal 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 통합을 반영하도록 업데이트되었으며, 사용자가 가장 최신이고 포괄적인 정보를 이용할 수 있도록 보장합니다.
|
||||
147
docs/ko/concepts/reasoning.mdx
Normal 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가 작업에 접근하는 방식을 체계적으로 구성하고, 발생할 수 있는 잠재적 문제를 고려하며, 기대되는 결과를 제공하도록 돕습니다.
|
||||
903
docs/ko/concepts/tasks.mdx
Normal file
@@ -0,0 +1,903 @@
|
||||
---
|
||||
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 빌더의 주요 기능:
|
||||
- 드래그 앤 드롭 방식의 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]` | 다음 태스크로 진행하기 전에 태스크 출력을 검증하는 함수입니다. |
|
||||
| **가드레일 최대 재시도** _(선택 사항)_ | `guardrail_max_retries` | `Optional[int]` | 가드레일 검증 실패 시 최대 재시도 횟수입니다. 기본값은 3입니다. |
|
||||
|
||||
## 작업 생성하기
|
||||
|
||||
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,
|
||||
guardrail_max_retries=3 # 재시도 횟수 제한
|
||||
)
|
||||
```
|
||||
|
||||
## 작업에서 구조화된 일관된 출력 얻기
|
||||
|
||||
<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의 잠재력을 극대화하는 데 필수적입니다.
|
||||
이를 통해 에이전트가 할당된 작업에 효과적으로 준비되고, 작업이 의도대로 수행될 수 있습니다.
|
||||