mirror of
https://github.com/crewAIInc/crewAI.git
synced 2025-12-16 12:28:30 +00:00
Compare commits
487 Commits
tony-docs
...
devin/1753
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ab236a68e | ||
|
|
dce11df0b7 | ||
|
|
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 | ||
|
|
bf8fa3232b | ||
|
|
a6e60a5d42 | ||
|
|
7b0f3aabd9 | ||
|
|
f071966951 | ||
|
|
318310bb7a | ||
|
|
34a03f882c | ||
|
|
a0fcc0c8d1 | ||
|
|
748c25451c | ||
|
|
a77dcdd419 | ||
|
|
68f5bdf0d9 | ||
|
|
7f83947020 | ||
|
|
ceb310bcde | ||
|
|
ae57e5723c | ||
|
|
ab39753a75 | ||
|
|
640e1a7bc2 | ||
|
|
e544ff8ba3 | ||
|
|
49c0144154 | ||
|
|
2ab002a5bf | ||
|
|
b7bf15681e | ||
|
|
af9c01f5d3 | ||
|
|
5a12b51ba2 | ||
|
|
576b8ff836 | ||
|
|
b35c3e8024 | ||
|
|
b09796cd3f | ||
|
|
e0b46492fa | ||
|
|
ece13fbda0 | ||
|
|
94a62d84e1 | ||
|
|
cdf8388b18 | ||
|
|
0f861338ef | ||
|
|
4d1aabf620 | ||
|
|
a50fae3a4b | ||
|
|
f6dfec61d6 | ||
|
|
060c486948 | ||
|
|
8b176d0598 | ||
|
|
c96d4a6823 | ||
|
|
59032817c7 | ||
|
|
e9d8a853ea | ||
|
|
463ea2b97f | ||
|
|
ec2903e5ee | ||
|
|
4364585ebc | ||
|
|
0a6b7c655b | ||
|
|
db1e9e9b9a | ||
|
|
d92382b6cf | ||
|
|
7c8f2a1325 | ||
|
|
a40447df29 | ||
|
|
5d6b467042 | ||
|
|
e0ff30c212 | ||
|
|
a5b5c8ab37 | ||
|
|
7f12e98de5 | ||
|
|
99133104dd | ||
|
|
970a63c13c | ||
|
|
06c991d8c3 | ||
|
|
739eb72fd0 | ||
|
|
b0d2e9fe31 | ||
|
|
5c51349a85 | ||
|
|
5b740467cb | ||
|
|
e9d9dd2a79 | ||
|
|
3e74cb4832 | ||
|
|
db3c8a49bd | ||
|
|
8a37b535ed | ||
|
|
e6ac1311e7 | ||
|
|
b0d89698fd | ||
|
|
21d063a46c | ||
|
|
02912a653e | ||
|
|
f1cfba7527 | ||
|
|
3e075cd48d | ||
|
|
e03ec4d60f | ||
|
|
ba740c6157 | ||
|
|
34c813ed79 | ||
|
|
545cc2ffe4 | ||
|
|
47b97d9b7f | ||
|
|
bf8fbb0a44 | ||
|
|
552921cf83 | ||
|
|
372874fb3a | ||
|
|
2bd6b72aae | ||
|
|
f02e0060fa | ||
|
|
66b7628972 | ||
|
|
c045399d6b | ||
|
|
1da2fd2a5c | ||
|
|
e07e11fbe7 | ||
|
|
55ed91e313 | ||
|
|
e676c83d7f | ||
|
|
844d142f2e | ||
|
|
bcc694348e | ||
|
|
dfc4255f2f | ||
|
|
4e0ce9adfe | ||
|
|
42dacb2862 | ||
|
|
22db4aae81 | ||
|
|
7fe193866d | ||
|
|
921423679a | ||
|
|
2460f61d3e | ||
|
|
be24559630 | ||
|
|
2b4a6b2e3d | ||
|
|
beddc72189 | ||
|
|
2d6deee753 | ||
|
|
222912d14b | ||
|
|
d131d4ef96 | ||
|
|
e59627adf2 | ||
|
|
d0855987f8 | ||
|
|
c1672613bc | ||
|
|
9945da7dbe | ||
|
|
31ffa90075 | ||
|
|
169d3233e8 | ||
|
|
b3484c1d0e | ||
|
|
910ed716d9 | ||
|
|
eb6364284f | ||
|
|
e21d54654c | ||
|
|
50b8f83428 | ||
|
|
8d2928e49a | ||
|
|
1ef22131e6 | ||
|
|
227b521f9e | ||
|
|
bef5971598 | ||
|
|
aa6e5b703e | ||
|
|
0b35e40a24 | ||
|
|
49bbf3f234 | ||
|
|
c566747d4a | ||
|
|
3a114463f9 | ||
|
|
b4dfb19a3a | ||
|
|
30ef8ed70b | ||
|
|
e1541b2619 | ||
|
|
7c4889f5c9 | ||
|
|
c403497cf4 | ||
|
|
fed397f745 | ||
|
|
d55e596800 | ||
|
|
f700e014c9 | ||
|
|
4e496d7a20 | ||
|
|
8663c7e1c2 | ||
|
|
cb1a98cabf | ||
|
|
369e6d109c | ||
|
|
2c011631f9 | ||
|
|
d3fc2b4477 | ||
|
|
516d45deaa | ||
|
|
7ad51d9d05 | ||
|
|
e3887ae36e | ||
|
|
e23bc2aaa7 | ||
|
|
7fc405408e | ||
|
|
cac06adc6c | ||
|
|
c8ec03424a | ||
|
|
bfea85d22c | ||
|
|
836e9fc545 | ||
|
|
c3726092fd | ||
|
|
dabf02a90d | ||
|
|
2912c93d77 | ||
|
|
17474a3a0c | ||
|
|
f89c2bfb7e | ||
|
|
2902201bfa | ||
|
|
378dcc79bb | ||
|
|
d348d5f20e | ||
|
|
bc24bc64cd | ||
|
|
015e1a41b2 | ||
|
|
94b1a6cfb8 | ||
|
|
1c2976c4d1 | ||
|
|
25c8155609 | ||
|
|
55b07506c2 | ||
|
|
59f34d900a | ||
|
|
4f6054d439 | ||
|
|
a86a1213c7 | ||
|
|
566935fb94 | ||
|
|
3a66746a99 | ||
|
|
337a6d5719 | ||
|
|
51eb5e9998 | ||
|
|
b2969e9441 | ||
|
|
5b9606e8b6 | ||
|
|
685d20f46c | ||
|
|
9ebf3aa043 | ||
|
|
2e4c97661a | ||
|
|
16eb4df556 | ||
|
|
3d9000495c | ||
|
|
6d0039b117 | ||
|
|
311a078ca6 | ||
|
|
371f19f3cd | ||
|
|
870dffbb89 | ||
|
|
ced3c8f0e0 | ||
|
|
8e555149f7 | ||
|
|
a96a27f064 | ||
|
|
a2f3566cd9 | ||
|
|
e655412aca | ||
|
|
1d91ab5d1b | ||
|
|
37359a34f0 | ||
|
|
6eb4045339 | ||
|
|
aebbc75dea | ||
|
|
bc91e94f03 | ||
|
|
d659151dca | ||
|
|
9dffd42e6d | ||
|
|
88455cd52c | ||
|
|
6a1eb10830 | ||
|
|
10edde100e | ||
|
|
40a441f30e | ||
|
|
ea5ae9086a | ||
|
|
0cd524af86 | ||
|
|
4bff5408d8 | ||
|
|
d2caf11191 | ||
|
|
37979a0ca1 | ||
|
|
c9f47e6a37 | ||
|
|
5780c3147a | ||
|
|
98ccbeb4bd | ||
|
|
fbb156b9de | ||
|
|
b73960cebe | ||
|
|
10328f3db4 | ||
|
|
da42ec7eb9 | ||
|
|
97d4439872 | ||
|
|
c3bb221fb3 | ||
|
|
e68cad380e | ||
|
|
96a78a97f0 | ||
|
|
337d2b634b | ||
|
|
475b704f95 | ||
|
|
b992ee9d6b | ||
|
|
d7fa8464c7 | ||
|
|
918c0589eb | ||
|
|
c9d3eb7ccf | ||
|
|
d216edb022 | ||
|
|
afa8783750 | ||
|
|
a661050464 | ||
|
|
c14f990098 | ||
|
|
26ccaf78ec | ||
|
|
12e98e1f3c | ||
|
|
efe27bd570 | ||
|
|
403ea385d7 | ||
|
|
9b51e1174c | ||
|
|
a3b5413f16 | ||
|
|
bce4bb5c4e | ||
|
|
3f92e217f9 | ||
|
|
b0f9637662 | ||
|
|
63ef3918dd | ||
|
|
3c24350306 | ||
|
|
356d4d9729 | ||
|
|
e290064ecc | ||
|
|
77fa1b18c7 | ||
|
|
08a6a82071 | ||
|
|
625748e462 | ||
|
|
6e209d5d77 | ||
|
|
f845fac4da | ||
|
|
b6c32b014c | ||
|
|
06950921e9 | ||
|
|
fc9da22c38 | ||
|
|
02f790ffcb | ||
|
|
af7983be43 | ||
|
|
a83661fd6e | ||
|
|
e1a73e0c44 | ||
|
|
48983773f5 | ||
|
|
73701fda1e | ||
|
|
3deeba4cab | ||
|
|
e3dde17af0 | ||
|
|
49b8cc95ae | ||
|
|
6145331ee4 | ||
|
|
f1839bc6db | ||
|
|
0b58911153 | ||
|
|
ee78446cc5 | ||
|
|
50fe5080e6 | ||
|
|
e1b8394265 | ||
|
|
c23e8fbb02 | ||
|
|
65aeb85e88 | ||
|
|
6c003e0382 | ||
|
|
6b14ffcffb | ||
|
|
df25703cc2 | ||
|
|
12a815e5db | ||
|
|
102836a2c2 | ||
|
|
d38be25d33 | ||
|
|
ac848f9ff4 | ||
|
|
a25a27c3d3 | ||
|
|
22c8e5f433 | ||
|
|
8df8255f18 | ||
|
|
66124d9afb | ||
|
|
7def3a8acc | ||
|
|
5b7fed2cb6 | ||
|
|
838b3bc09d | ||
|
|
ebb585e494 | ||
|
|
7c67c2c6af | ||
|
|
e4f5c7cdf2 | ||
|
|
f09238e512 | ||
|
|
da5f60e7f3 | ||
|
|
807c13e144 | ||
|
|
3dea3d0183 | ||
|
|
35cb7fcf4d | ||
|
|
d2a9a4a4e4 | ||
|
|
e62e9c7401 | ||
|
|
3c5031e711 | ||
|
|
82e84c0f88 | ||
|
|
2c550dc175 | ||
|
|
bdc92deade | ||
|
|
448d31cad9 | ||
|
|
ed1f009c64 | ||
|
|
bb3829a9ed | ||
|
|
0a116202f0 | ||
|
|
4daa88fa59 | ||
|
|
53067f8b92 | ||
|
|
d3a09c3180 | ||
|
|
4d7aacb5f2 | ||
|
|
6b1cf78e41 | ||
|
|
80f1a88b63 | ||
|
|
32da76a2ca | ||
|
|
b3667a8c09 | ||
|
|
3aa48dcd58 | ||
|
|
03f1d57463 | ||
|
|
4725d0de0d | ||
|
|
b766af75f2 | ||
|
|
b2c8779f4c | ||
|
|
df266bda01 | ||
|
|
eed7919d72 | ||
|
|
1e49d1b592 | ||
|
|
ded7197fcb | ||
|
|
2155acb3a3 | ||
|
|
794574957e | ||
|
|
66b19311a7 | ||
|
|
9fc84fc1ac | ||
|
|
f8f9df6d1d | ||
|
|
6e94edb777 | ||
|
|
5f2ac8c33e | ||
|
|
bbe896d48c | ||
|
|
9298054436 | ||
|
|
90b7937796 | ||
|
|
520933b4c5 | ||
|
|
9ea4fb8c82 | ||
|
|
fe0813e831 | ||
|
|
33cebea15b | ||
|
|
e723e5ca3f | ||
|
|
24f1a19310 | ||
|
|
d0959573dc | ||
|
|
939afd5f82 | ||
|
|
d42e58e199 | ||
|
|
000bab4cf5 | ||
|
|
8df1042180 | ||
|
|
313038882c | ||
|
|
41a670166a | ||
|
|
a77496a217 | ||
|
|
430260c985 | ||
|
|
334b0959b0 | ||
|
|
2b31e26ba5 | ||
|
|
7122a29a20 | ||
|
|
f3ddb430a7 | ||
|
|
435bfca186 | ||
|
|
2ef896bdd5 | ||
|
|
59c6c29706 | ||
|
|
a1f35e768f | ||
|
|
00eede0d5d | ||
|
|
cf1864ce0f | ||
|
|
a3d5c86218 | ||
|
|
60d13bf7e8 | ||
|
|
52e0a84829 | ||
|
|
86825e1769 | ||
|
|
7afc531fbb | ||
|
|
ed0490112b | ||
|
|
66c66e3d84 | ||
|
|
b9b625a70d | ||
|
|
b58253cacc | ||
|
|
fbf8732784 | ||
|
|
8fedbe49cb | ||
|
|
1e8ee247ca | ||
|
|
34d2993456 | ||
|
|
e3c5c174ee | ||
|
|
b4e2db0306 | ||
|
|
9cc759ba32 | ||
|
|
ac9f8b9d5a | ||
|
|
3d4a1e4b18 | ||
|
|
123f302744 | ||
|
|
5bae78639e | ||
|
|
5235442a5b | ||
|
|
c62fb615b1 | ||
|
|
78797c64b0 | ||
|
|
8a7584798b | ||
|
|
b50772a38b | ||
|
|
96a7e8038f | ||
|
|
ec050e5d33 | ||
|
|
e2ce65fc5b | ||
|
|
14503bc43b | ||
|
|
00c2f5043e | ||
|
|
bcd90e26b0 | ||
|
|
4eaa8755eb | ||
|
|
ba66910fbd | ||
|
|
90f1bee602 | ||
|
|
1cb5f57864 | ||
|
|
7dc47adb5c | ||
|
|
ac819bcb6e | ||
|
|
b6d668fc66 | ||
|
|
1b488b6da7 | ||
|
|
d3b398ed52 | ||
|
|
d52fd09602 | ||
|
|
d6800d8957 | ||
|
|
2fd7506ed9 | ||
|
|
161084aff2 | ||
|
|
b145cb3247 | ||
|
|
1adbcf697d | ||
|
|
e51355200a | ||
|
|
47818f4f41 | ||
|
|
9b10fd47b0 | ||
|
|
c408368267 | ||
|
|
90b3145e92 | ||
|
|
fbd0e015d5 | ||
|
|
17e25fb842 | ||
|
|
d6d98ee969 | ||
|
|
e0600e3bb9 | ||
|
|
a79d77dfd7 | ||
|
|
56ec9bc224 | ||
|
|
8eef02739a | ||
|
|
6f4ad532e6 | ||
|
|
74a1de8550 | ||
|
|
e529766391 | ||
|
|
a7f5d574dc | ||
|
|
0cc02d9492 | ||
|
|
fa26f6ebae | ||
|
|
f6c2982619 | ||
|
|
5a8649a97f | ||
|
|
e6100debac | ||
|
|
abee94d056 | ||
|
|
92731544ae | ||
|
|
77c7b7dfa1 | ||
|
|
ea64c29fee | ||
|
|
f4bb040ad8 | ||
|
|
515478473a | ||
|
|
9cf3fadd0f | ||
|
|
89c4b3fe88 | ||
|
|
9e5c599f58 | ||
|
|
a950e67c7d | ||
|
|
de6933b2d2 | ||
|
|
748383d74c | ||
|
|
23b9e10323 | ||
|
|
ddb7958da7 | ||
|
|
477cce321f | ||
|
|
7bed63a693 | ||
|
|
2709a9205a | ||
|
|
d19d7b01ec | ||
|
|
a3ad2c1957 | ||
|
|
c3e7a3ec19 | ||
|
|
cba8c9faec | ||
|
|
bcb7fb27d0 | ||
|
|
c310044bec | ||
|
|
5263df24b6 | ||
|
|
dea6ed7ef0 | ||
|
|
d3a0dad323 | ||
|
|
67bf4aea56 | ||
|
|
8c76bad50f | ||
|
|
e27a15023c | ||
|
|
a836f466f4 | ||
|
|
67f0de1f90 | ||
|
|
c642ebf97e | ||
|
|
a21e310d78 | ||
|
|
aba68da542 | ||
|
|
e254f11933 | ||
|
|
ab2274caf0 | ||
|
|
3e4f112f39 | ||
|
|
cc018bf128 | ||
|
|
46d3e4d4d9 | ||
|
|
627bb3f5f6 | ||
|
|
4a44245de9 | ||
|
|
30d027158a | ||
|
|
3fecde49b6 | ||
|
|
cc129a0bce | ||
|
|
b5779dca12 | ||
|
|
42311d9c7a | ||
|
|
294f2cc3a9 | ||
|
|
3dc442801f |
1429
.cursorrules
Normal file
1429
.cursorrules
Normal file
File diff suppressed because it is too large
Load Diff
38
.github/security.md
vendored
38
.github/security.md
vendored
@@ -1,19 +1,27 @@
|
||||
CrewAI takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organization.
|
||||
If you believe you have found a security vulnerability in any CrewAI product or service, please report it to us as described below.
|
||||
## CrewAI Security Vulnerability Reporting Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
Please do not report security vulnerabilities through public GitHub issues.
|
||||
To report a vulnerability, please email us at security@crewai.com.
|
||||
Please include the requested information listed below so that we can triage your report more quickly
|
||||
CrewAI prioritizes the security of our software products, services, and GitHub repositories. To promptly address vulnerabilities, follow these steps for reporting security issues:
|
||||
|
||||
- Type of issue (e.g. SQL injection, cross-site scripting, etc.)
|
||||
- Full paths of source file(s) related to the manifestation of the issue
|
||||
- The location of the affected source code (tag/branch/commit or direct URL)
|
||||
- Any special configuration required to reproduce the issue
|
||||
- Step-by-step instructions to reproduce the issue (please include screenshots if needed)
|
||||
- Proof-of-concept or exploit code (if possible)
|
||||
- Impact of the issue, including how an attacker might exploit the issue
|
||||
### Reporting Process
|
||||
Do **not** report vulnerabilities via public GitHub issues.
|
||||
|
||||
Once we have received your report, we will respond to you at the email address you provide. If the issue is confirmed, we will release a patch as soon as possible depending on the complexity of the issue.
|
||||
Email all vulnerability reports directly to:
|
||||
**security@crewai.com**
|
||||
|
||||
At this time, we are not offering a bug bounty program. Any rewards will be at our discretion.
|
||||
### Required Information
|
||||
To help us quickly validate and remediate the issue, your report must include:
|
||||
|
||||
- **Vulnerability Type:** Clearly state the vulnerability type (e.g., SQL injection, XSS, privilege escalation).
|
||||
- **Affected Source Code:** Provide full file paths and direct URLs (branch, tag, or commit).
|
||||
- **Reproduction Steps:** Include detailed, step-by-step instructions. Screenshots are recommended.
|
||||
- **Special Configuration:** Document any special settings or configurations required to reproduce.
|
||||
- **Proof-of-Concept (PoC):** Provide exploit or PoC code (if available).
|
||||
- **Impact Assessment:** Clearly explain the severity and potential exploitation scenarios.
|
||||
|
||||
### Our Response
|
||||
- We will acknowledge receipt of your report promptly via your provided email.
|
||||
- Confirmed vulnerabilities will receive priority remediation based on severity.
|
||||
- Patches will be released as swiftly as possible following verification.
|
||||
|
||||
### Reward Notice
|
||||
Currently, we do not offer a bug bounty program. Rewards, if issued, are discretionary.
|
||||
|
||||
28
.github/workflows/linter.yml
vendored
28
.github/workflows/linter.yml
vendored
@@ -5,12 +5,32 @@ on: [pull_request]
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TARGET_BRANCH: ${{ github.event.pull_request.base.ref }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install Requirements
|
||||
- name: Fetch Target Branch
|
||||
run: git fetch origin $TARGET_BRANCH --depth=1
|
||||
|
||||
- name: Install Ruff
|
||||
run: pip install ruff
|
||||
|
||||
- name: Get Changed Python Files
|
||||
id: changed-files
|
||||
run: |
|
||||
pip install ruff
|
||||
merge_base=$(git merge-base origin/"$TARGET_BRANCH" HEAD)
|
||||
changed_files=$(git diff --name-only --diff-filter=ACMRTUB "$merge_base" | grep '\.py$' || true)
|
||||
echo "files<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$changed_files" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Ruff Linter
|
||||
run: ruff check
|
||||
- name: Run Ruff on Changed Files
|
||||
if: ${{ steps.changed-files.outputs.files != '' }}
|
||||
run: |
|
||||
echo "${{ steps.changed-files.outputs.files }}" \
|
||||
| tr ' ' '\n' \
|
||||
| grep -v 'src/crewai/cli/templates/' \
|
||||
| xargs -I{} ruff check "{}"
|
||||
|
||||
45
.github/workflows/mkdocs.yml
vendored
45
.github/workflows/mkdocs.yml
vendored
@@ -1,45 +0,0 @@
|
||||
name: Deploy MkDocs
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
|
||||
- name: Calculate requirements hash
|
||||
id: req-hash
|
||||
run: echo "::set-output name=hash::$(sha256sum requirements-doc.txt | awk '{print $1}')"
|
||||
|
||||
- name: Setup cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
key: mkdocs-material-${{ steps.req-hash.outputs.hash }}
|
||||
path: .cache
|
||||
restore-keys: |
|
||||
mkdocs-material-
|
||||
|
||||
- name: Install Requirements
|
||||
run: |
|
||||
sudo apt-get update &&
|
||||
sudo apt-get install pngquant &&
|
||||
pip install mkdocs-material mkdocs-material-extensions pillow cairosvg
|
||||
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Build and deploy MkDocs
|
||||
run: mkdocs gh-deploy --force
|
||||
33
.github/workflows/notify-downstream.yml
vendored
Normal file
33
.github/workflows/notify-downstream.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
name: Notify Downstream
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
notify-downstream:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
uses: tibdex/github-app-token@v2
|
||||
with:
|
||||
app_id: ${{ secrets.OSS_SYNC_APP_ID }}
|
||||
private_key: ${{ secrets.OSS_SYNC_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Notify Repo B
|
||||
uses: peter-evans/repository-dispatch@v3
|
||||
with:
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
repository: ${{ secrets.OSS_SYNC_DOWNSTREAM_REPO }}
|
||||
event-type: upstream-commit
|
||||
client-payload: |
|
||||
{
|
||||
"commit_sha": "${{ github.sha }}"
|
||||
}
|
||||
|
||||
28
.github/workflows/tests.yml
vendored
28
.github/workflows/tests.yml
vendored
@@ -7,11 +7,18 @@ permissions:
|
||||
|
||||
env:
|
||||
OPENAI_API_KEY: fake-api-key
|
||||
PYTHONUNBUFFERED: 1
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: tests (${{ matrix.python-version }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
python-version: ['3.10', '3.11', '3.12', '3.13']
|
||||
group: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -20,13 +27,24 @@ jobs:
|
||||
uses: astral-sh/setup-uv@v3
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
**/pyproject.toml
|
||||
**/uv.lock
|
||||
|
||||
|
||||
- name: Set up Python
|
||||
run: uv python install 3.12.8
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
run: uv python install ${{ matrix.python-version }}
|
||||
|
||||
- name: Install the project
|
||||
run: uv sync --dev --all-extras
|
||||
|
||||
- name: Run tests
|
||||
run: uv run pytest tests -vv
|
||||
- name: Run tests (group ${{ matrix.group }} of 8)
|
||||
run: |
|
||||
uv run pytest \
|
||||
--block-network \
|
||||
--timeout=30 \
|
||||
-vv \
|
||||
--splits 8 \
|
||||
--group ${{ matrix.group }} \
|
||||
--durations=10 \
|
||||
-n auto \
|
||||
--maxfail=3
|
||||
|
||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -21,4 +21,10 @@ crew_tasks_output.json
|
||||
.mypy_cache
|
||||
.ruff_cache
|
||||
.venv
|
||||
agentops.log
|
||||
agentops.log
|
||||
test_flow.html
|
||||
crewairules.mdc
|
||||
plan.md
|
||||
conceptual_plan.md
|
||||
build_image
|
||||
chromadb-*.lock
|
||||
|
||||
@@ -2,8 +2,3 @@ exclude = [
|
||||
"templates",
|
||||
"__init__.py",
|
||||
]
|
||||
|
||||
[lint]
|
||||
select = [
|
||||
"I", # isort rules
|
||||
]
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2018 The Python Packaging Authority
|
||||
Copyright (c) 2025 crewAI, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
286
README.md
286
README.md
@@ -1,21 +1,85 @@
|
||||
<div align="center">
|
||||
<p align="center">
|
||||
<a href="https://github.com/crewAIInc/crewAI">
|
||||
<img src="docs/images/crewai_logo.png" width="600px" alt="Open source Multi-AI Agent orchestration framework">
|
||||
</a>
|
||||
</p>
|
||||
<p align="center" style="display: flex; justify-content: center; gap: 20px; align-items: center;">
|
||||
<a href="https://trendshift.io/repositories/11239" target="_blank">
|
||||
<img src="https://trendshift.io/api/badge/repositories/11239" alt="crewAIInc%2FcrewAI | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||

|
||||
<p align="center">
|
||||
<a href="https://crewai.com">Homepage</a>
|
||||
·
|
||||
<a href="https://docs.crewai.com">Docs</a>
|
||||
·
|
||||
<a href="https://app.crewai.com">Start Cloud Trial</a>
|
||||
·
|
||||
<a href="https://blog.crewai.com">Blog</a>
|
||||
·
|
||||
<a href="https://community.crewai.com">Forum</a>
|
||||
</p>
|
||||
|
||||
# **CrewAI**
|
||||
<p align="center">
|
||||
<a href="https://github.com/crewAIInc/crewAI">
|
||||
<img src="https://img.shields.io/github/stars/crewAIInc/crewAI" alt="GitHub Repo stars">
|
||||
</a>
|
||||
<a href="https://github.com/crewAIInc/crewAI/network/members">
|
||||
<img src="https://img.shields.io/github/forks/crewAIInc/crewAI" alt="GitHub forks">
|
||||
</a>
|
||||
<a href="https://github.com/crewAIInc/crewAI/issues">
|
||||
<img src="https://img.shields.io/github/issues/crewAIInc/crewAI" alt="GitHub issues">
|
||||
</a>
|
||||
<a href="https://github.com/crewAIInc/crewAI/pulls">
|
||||
<img src="https://img.shields.io/github/issues-pr/crewAIInc/crewAI" alt="GitHub pull requests">
|
||||
</a>
|
||||
<a href="https://opensource.org/licenses/MIT">
|
||||
<img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License: MIT">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
🤖 **CrewAI**: Production-grade framework for orchestrating sophisticated AI agent systems. From simple automations to complex real-world applications, CrewAI provides precise control and deep customization. By fostering collaborative intelligence through flexible, production-ready architecture, CrewAI empowers agents to work together seamlessly, tackling complex business challenges with predictable, consistent results.
|
||||
<p align="center">
|
||||
<a href="https://pypi.org/project/crewai/">
|
||||
<img src="https://img.shields.io/pypi/v/crewai" alt="PyPI version">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/crewai/">
|
||||
<img src="https://img.shields.io/pypi/dm/crewai" alt="PyPI downloads">
|
||||
</a>
|
||||
<a href="https://twitter.com/crewAIInc">
|
||||
<img src="https://img.shields.io/twitter/follow/crewAIInc?style=social" alt="Twitter Follow">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h3>
|
||||
### Fast and Flexible Multi-Agent Automation Framework
|
||||
|
||||
[Homepage](https://www.crewai.com/) | [Documentation](https://docs.crewai.com/) | [Chat with Docs](https://chatg.pt/DWjSBZn) | [Examples](https://github.com/crewAIInc/crewAI-examples) | [Discourse](https://community.crewai.com)
|
||||
> CrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely **independent of LangChain or other agent frameworks**.
|
||||
> It empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario.
|
||||
|
||||
</h3>
|
||||
- **CrewAI Crews**: Optimize for autonomy and collaborative intelligence.
|
||||
- **CrewAI Flows**: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively
|
||||
|
||||
[](https://github.com/crewAIInc/crewAI)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
With over 100,000 developers certified through our community courses at [learn.crewai.com](https://learn.crewai.com), CrewAI is rapidly becoming the
|
||||
standard for enterprise-ready AI automation.
|
||||
|
||||
</div>
|
||||
# CrewAI Enterprise Suite
|
||||
|
||||
CrewAI Enterprise Suite is a comprehensive bundle tailored for organizations that require secure, scalable, and easy-to-manage agent-driven automation.
|
||||
|
||||
You can try one part of the suite the [Crew Control Plane for free](https://app.crewai.com)
|
||||
|
||||
## Crew Control Plane Key Features:
|
||||
|
||||
- **Tracing & Observability**: Monitor and track your AI agents and workflows in real-time, including metrics, logs, and traces.
|
||||
- **Unified Control Plane**: A centralized platform for managing, monitoring, and scaling your AI agents and workflows.
|
||||
- **Seamless Integrations**: Easily connect with existing enterprise systems, data sources, and cloud infrastructure.
|
||||
- **Advanced Security**: Built-in robust security and compliance measures ensuring safe deployment and management.
|
||||
- **Actionable Insights**: Real-time analytics and reporting to optimize performance and decision-making.
|
||||
- **24/7 Support**: Dedicated enterprise support to ensure uninterrupted operation and quick resolution of issues.
|
||||
- **On-premise and Cloud Deployment Options**: Deploy CrewAI Enterprise on-premise or in the cloud, depending on your security and compliance requirements.
|
||||
|
||||
CrewAI Enterprise is designed for enterprises seeking a powerful, reliable solution to transform complex business processes into efficient,
|
||||
intelligent automations.
|
||||
|
||||
## Table of contents
|
||||
|
||||
@@ -39,14 +103,31 @@
|
||||
|
||||
## Why CrewAI?
|
||||
|
||||
The power of AI collaboration has too much to offer.
|
||||
CrewAI is a standalone framework, built from the ground up without dependencies on Langchain or other agent frameworks. It's designed to enable AI agents to assume roles, share goals, and operate in a cohesive unit - much like a well-oiled crew. Whether you're building a smart assistant platform, an automated customer service ensemble, or a multi-agent research team, CrewAI provides the backbone for sophisticated multi-agent interactions.
|
||||
<div align="center" style="margin-bottom: 30px;">
|
||||
<img src="docs/images/asset.png" alt="CrewAI Logo" width="100%">
|
||||
</div>
|
||||
|
||||
CrewAI unlocks the true potential of multi-agent automation, delivering the best-in-class combination of speed, flexibility, and control with either Crews of AI Agents or Flows of Events:
|
||||
|
||||
- **Standalone Framework**: Built from scratch, independent of LangChain or any other agent framework.
|
||||
- **High Performance**: Optimized for speed and minimal resource usage, enabling faster execution.
|
||||
- **Flexible Low Level Customization**: Complete freedom to customize at both high and low levels - from overall workflows and system architecture to granular agent behaviors, internal prompts, and execution logic.
|
||||
- **Ideal for Every Use Case**: Proven effective for both simple tasks and highly complex, real-world, enterprise-grade scenarios.
|
||||
- **Robust Community**: Backed by a rapidly growing community of over **100,000 certified** developers offering comprehensive support and resources.
|
||||
|
||||
CrewAI empowers developers and enterprises to confidently build intelligent automations, bridging the gap between simplicity, flexibility, and performance.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Learning Resources
|
||||
Setup and run your first CrewAI agents by following this tutorial.
|
||||
|
||||
[](https://www.youtube.com/watch?v=-kSOTtYzgEw "CrewAI Getting Started Tutorial")
|
||||
|
||||
###
|
||||
Learning Resources
|
||||
|
||||
Learn CrewAI through our comprehensive courses:
|
||||
|
||||
- [Multi AI Agent Systems with CrewAI](https://www.deeplearning.ai/short-courses/multi-ai-agent-systems-with-crewai/) - Master the fundamentals of multi-agent systems
|
||||
- [Practical Multi AI Agents and Advanced Use Cases](https://www.deeplearning.ai/short-courses/practical-multi-ai-agents-and-advanced-use-cases-with-crewai/) - Deep dive into advanced implementations
|
||||
|
||||
@@ -55,18 +136,20 @@ Learn CrewAI through our comprehensive courses:
|
||||
CrewAI offers two powerful, complementary approaches that work seamlessly together to build sophisticated AI applications:
|
||||
|
||||
1. **Crews**: Teams of AI agents with true autonomy and agency, working together to accomplish complex tasks through role-based collaboration. Crews enable:
|
||||
|
||||
- Natural, autonomous decision-making between agents
|
||||
- Dynamic task delegation and collaboration
|
||||
- Specialized roles with defined goals and expertise
|
||||
- Flexible problem-solving approaches
|
||||
|
||||
2. **Flows**: Production-ready, event-driven workflows that deliver precise control over complex automations. Flows provide:
|
||||
|
||||
- Fine-grained control over execution paths for real-world scenarios
|
||||
- Secure, consistent state management between tasks
|
||||
- Clean integration of AI agents with production Python code
|
||||
- Conditional branching for complex business logic
|
||||
|
||||
The true power of CrewAI emerges when combining Crews and Flows. This synergy allows you to:
|
||||
|
||||
- Build complex, production-grade applications
|
||||
- Balance autonomy with precise control
|
||||
- Handle sophisticated real-world scenarios
|
||||
@@ -78,18 +161,20 @@ To get started with CrewAI, follow these simple steps:
|
||||
|
||||
### 1. Installation
|
||||
|
||||
Ensure you have Python >=3.10 <3.13 installed on your system. CrewAI uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
|
||||
Ensure you have Python >=3.10 <3.14 installed on your system. CrewAI uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
|
||||
|
||||
First, install CrewAI:
|
||||
|
||||
```shell
|
||||
pip install crewai
|
||||
```
|
||||
|
||||
If you want to install the 'crewai' package along with its optional features that include additional tools for agents, you can do so by using the following command:
|
||||
|
||||
```shell
|
||||
pip install 'crewai[tools]'
|
||||
```
|
||||
|
||||
The command above installs the basic package and also adds extra components which require more dependencies to function.
|
||||
|
||||
### Troubleshooting Dependencies
|
||||
@@ -99,10 +184,11 @@ If you encounter issues during installation or usage, here are some common solut
|
||||
#### Common Issues
|
||||
|
||||
1. **ModuleNotFoundError: No module named 'tiktoken'**
|
||||
|
||||
- Install tiktoken explicitly: `pip install 'crewai[embeddings]'`
|
||||
- If using embedchain or other tools: `pip install 'crewai[tools]'`
|
||||
|
||||
2. **Failed building wheel for tiktoken**
|
||||
|
||||
- Ensure Rust compiler is installed (see installation steps above)
|
||||
- For Windows: Verify Visual C++ Build Tools are installed
|
||||
- Try upgrading pip: `pip install --upgrade pip`
|
||||
@@ -190,7 +276,7 @@ research_task:
|
||||
description: >
|
||||
Conduct a thorough research about {topic}
|
||||
Make sure you find any interesting and relevant information given
|
||||
the current year is 2024.
|
||||
the current year is 2025.
|
||||
expected_output: >
|
||||
A list with 10 bullet points of the most relevant information about {topic}
|
||||
agent: researcher
|
||||
@@ -213,10 +299,14 @@ reporting_task:
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from crewai.project import CrewBase, agent, crew, task
|
||||
from crewai_tools import SerperDevTool
|
||||
from crewai.agents.agent_builder.base_agent import BaseAgent
|
||||
from typing import List
|
||||
|
||||
@CrewBase
|
||||
class LatestAiDevelopmentCrew():
|
||||
"""LatestAiDevelopment crew"""
|
||||
agents: List[BaseAgent]
|
||||
tasks: List[Task]
|
||||
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
@@ -313,18 +403,16 @@ In addition to the sequential process, you can use the hierarchical process, whi
|
||||
|
||||
## Key Features
|
||||
|
||||
**Note**: CrewAI is a standalone framework built from the ground up, without dependencies on Langchain or other agent frameworks.
|
||||
CrewAI stands apart as a lean, standalone, high-performance multi-AI Agent framework delivering simplicity, flexibility, and precise control—free from the complexity and limitations found in other agent frameworks.
|
||||
|
||||
- **Deep Customization**: Build sophisticated agents with full control over the system - from overriding inner prompts to accessing low-level APIs. Customize roles, goals, tools, and behaviors while maintaining clean abstractions.
|
||||
- **Autonomous Inter-Agent Delegation**: Agents can autonomously delegate tasks and inquire amongst themselves, enabling complex problem-solving in real-world scenarios.
|
||||
- **Flexible Task Management**: Define and customize tasks with granular control, from simple operations to complex multi-step processes.
|
||||
- **Production-Grade Architecture**: Support for both high-level abstractions and low-level customization, with robust error handling and state management.
|
||||
- **Predictable Results**: Ensure consistent, accurate outputs through programmatic guardrails, agent training capabilities, and flow-based execution control. See our [documentation on guardrails](https://docs.crewai.com/how-to/guardrails/) for implementation details.
|
||||
- **Model Flexibility**: Run your crew using OpenAI or open source models with production-ready integrations. See [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-Connections/) for detailed configuration options.
|
||||
- **Event-Driven Flows**: Build complex, real-world workflows with precise control over execution paths, state management, and conditional logic.
|
||||
- **Process Orchestration**: Achieve any workflow pattern through flows - from simple sequential and hierarchical processes to complex, custom orchestration patterns with conditional branching and parallel execution.
|
||||
- **Standalone & Lean**: Completely independent from other frameworks like LangChain, offering faster execution and lighter resource demands.
|
||||
- **Flexible & Precise**: Easily orchestrate autonomous agents through intuitive [Crews](https://docs.crewai.com/concepts/crews) or precise [Flows](https://docs.crewai.com/concepts/flows), achieving perfect balance for your needs.
|
||||
- **Seamless Integration**: Effortlessly combine Crews (autonomy) and Flows (precision) to create complex, real-world automations.
|
||||
- **Deep Customization**: Tailor every aspect—from high-level workflows down to low-level internal prompts and agent behaviors.
|
||||
- **Reliable Performance**: Consistent results across simple tasks and complex, enterprise-level automations.
|
||||
- **Thriving Community**: Backed by robust documentation and over 100,000 certified developers, providing exceptional support and guidance.
|
||||
|
||||

|
||||
Choose CrewAI to easily build powerful, adaptable, and production-ready AI automations.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -359,11 +447,17 @@ You can test different real life examples of AI crews in the [CrewAI-examples re
|
||||
|
||||
### Using Crews and Flows Together
|
||||
|
||||
CrewAI's power truly shines when combining Crews with Flows to create sophisticated automation pipelines. Here's how you can orchestrate multiple Crews within a Flow:
|
||||
CrewAI's power truly shines when combining Crews with Flows to create sophisticated automation pipelines.
|
||||
CrewAI flows support logical operators like `or_` and `and_` to combine multiple conditions. This can be used with `@start`, `@listen`, or `@router` decorators to create complex triggering conditions.
|
||||
|
||||
- `or_`: Triggers when any of the specified conditions are met.
|
||||
- `and_`Triggers when all of the specified conditions are met.
|
||||
|
||||
Here's how you can orchestrate multiple Crews within a Flow:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start, router
|
||||
from crewai import Crew, Agent, Task
|
||||
from crewai.flow.flow import Flow, listen, start, router, or_
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Define structured state for precise control
|
||||
@@ -392,7 +486,7 @@ class AdvancedAnalysisFlow(Flow[MarketState]):
|
||||
goal="Gather and validate supporting market data",
|
||||
backstory="You excel at finding and correlating multiple data sources"
|
||||
)
|
||||
|
||||
|
||||
analysis_task = Task(
|
||||
description="Analyze {sector} sector data for the past {timeframe}",
|
||||
expected_output="Detailed market analysis with confidence score",
|
||||
@@ -403,7 +497,7 @@ class AdvancedAnalysisFlow(Flow[MarketState]):
|
||||
expected_output="Corroborating evidence and potential contradictions",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
|
||||
# Demonstrate crew autonomy
|
||||
analysis_crew = Crew(
|
||||
agents=[analyst, researcher],
|
||||
@@ -437,13 +531,14 @@ class AdvancedAnalysisFlow(Flow[MarketState]):
|
||||
)
|
||||
return strategy_crew.kickoff()
|
||||
|
||||
@listen("medium_confidence", "low_confidence")
|
||||
@listen(or_("medium_confidence", "low_confidence"))
|
||||
def request_additional_analysis(self):
|
||||
self.state.recommendations.append("Gather more data")
|
||||
return "Additional analysis required"
|
||||
```
|
||||
|
||||
This example demonstrates how to:
|
||||
|
||||
1. Use Python code for basic data operations
|
||||
2. Create and execute Crews as steps in your workflow
|
||||
3. Use Flow decorators to manage the sequence of operations
|
||||
@@ -453,7 +548,7 @@ This example demonstrates how to:
|
||||
|
||||
CrewAI supports using various LLMs through a variety of connection options. By default your agents will use the OpenAI API when querying the model. However, there are several other ways to allow your agents to connect to models. For example, you can configure your agents to use a local model via the Ollama tool.
|
||||
|
||||
Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-Connections/) page for details on configuring you agents' connections to models.
|
||||
Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-Connections/) page for details on configuring your agents' connections to models.
|
||||
|
||||
## How CrewAI Compares
|
||||
|
||||
@@ -464,7 +559,6 @@ Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-
|
||||
*P.S. CrewAI demonstrates significant performance advantages over LangGraph, executing 5.76x faster in certain cases like this QA task example ([see comparison](https://github.com/crewAIInc/crewAI-examples/tree/main/Notebooks/CrewAI%20Flows%20%26%20Langgraph/QA%20Agent)) while achieving higher evaluation scores with faster completion times in certain coding tasks, like in this example ([detailed analysis](https://github.com/crewAIInc/crewAI-examples/blob/main/Notebooks/CrewAI%20Flows%20%26%20Langgraph/Coding%20Assistant/coding_assistant_eval.ipynb)).*
|
||||
|
||||
- **Autogen**: While Autogen excels at creating conversational agents capable of working together, it lacks an inherent concept of process. In Autogen, orchestrating agents' interactions requires additional programming, which can become complex and cumbersome as the scale of tasks grows.
|
||||
|
||||
- **ChatDev**: ChatDev introduced the idea of processes into the realm of AI agents, but its implementation is quite rigid. Customizations in ChatDev are limited and not geared towards production environments, which can hinder scalability and flexibility in real-world applications.
|
||||
|
||||
## Contribution
|
||||
@@ -557,39 +651,127 @@ CrewAI is released under the [MIT License](https://github.com/crewAIInc/crewAI/b
|
||||
|
||||
## Frequently Asked Questions (FAQ)
|
||||
|
||||
### Q: What is CrewAI?
|
||||
A: CrewAI is a cutting-edge framework for orchestrating role-playing, autonomous AI agents. It enables agents to work together seamlessly, tackling complex tasks through collaborative intelligence.
|
||||
### General
|
||||
|
||||
- [What exactly is CrewAI?](#q-what-exactly-is-crewai)
|
||||
- [How do I install CrewAI?](#q-how-do-i-install-crewai)
|
||||
- [Does CrewAI depend on LangChain?](#q-does-crewai-depend-on-langchain)
|
||||
- [Is CrewAI open-source?](#q-is-crewai-open-source)
|
||||
- [Does CrewAI collect data from users?](#q-does-crewai-collect-data-from-users)
|
||||
|
||||
### Features and Capabilities
|
||||
|
||||
- [Can CrewAI handle complex use cases?](#q-can-crewai-handle-complex-use-cases)
|
||||
- [Can I use CrewAI with local AI models?](#q-can-i-use-crewai-with-local-ai-models)
|
||||
- [What makes Crews different from Flows?](#q-what-makes-crews-different-from-flows)
|
||||
- [How is CrewAI better than LangChain?](#q-how-is-crewai-better-than-langchain)
|
||||
- [Does CrewAI support fine-tuning or training custom models?](#q-does-crewai-support-fine-tuning-or-training-custom-models)
|
||||
|
||||
### Resources and Community
|
||||
|
||||
- [Where can I find real-world CrewAI examples?](#q-where-can-i-find-real-world-crewai-examples)
|
||||
- [How can I contribute to CrewAI?](#q-how-can-i-contribute-to-crewai)
|
||||
|
||||
### Enterprise Features
|
||||
|
||||
- [What additional features does CrewAI Enterprise offer?](#q-what-additional-features-does-crewai-enterprise-offer)
|
||||
- [Is CrewAI Enterprise available for cloud and on-premise deployments?](#q-is-crewai-enterprise-available-for-cloud-and-on-premise-deployments)
|
||||
- [Can I try CrewAI Enterprise for free?](#q-can-i-try-crewai-enterprise-for-free)
|
||||
|
||||
### Q: What exactly is CrewAI?
|
||||
|
||||
A: CrewAI is a standalone, lean, and fast Python framework built specifically for orchestrating autonomous AI agents. Unlike frameworks like LangChain, CrewAI does not rely on external dependencies, making it leaner, faster, and simpler.
|
||||
|
||||
### Q: How do I install CrewAI?
|
||||
A: You can install CrewAI using pip:
|
||||
|
||||
A: Install CrewAI using pip:
|
||||
|
||||
```shell
|
||||
pip install crewai
|
||||
```
|
||||
|
||||
For additional tools, use:
|
||||
|
||||
```shell
|
||||
pip install 'crewai[tools]'
|
||||
```
|
||||
|
||||
### Q: Can I use CrewAI with local models?
|
||||
A: Yes, CrewAI supports various LLMs, including local models. You can configure your agents to use local models via tools like Ollama & LM Studio. Check the [LLM Connections documentation](https://docs.crewai.com/how-to/LLM-Connections/) for more details.
|
||||
### Q: Does CrewAI depend on LangChain?
|
||||
|
||||
### Q: What are the key features of CrewAI?
|
||||
A: Key features include role-based agent design, autonomous inter-agent delegation, flexible task management, process-driven execution, output saving as files, and compatibility with both open-source and proprietary models.
|
||||
A: No. CrewAI is built entirely from the ground up, with no dependencies on LangChain or other agent frameworks. This ensures a lean, fast, and flexible experience.
|
||||
|
||||
### Q: How does CrewAI compare to other AI orchestration tools?
|
||||
A: CrewAI is designed with production in mind, offering flexibility similar to Autogen's conversational agents and structured processes like ChatDev, but with more adaptability for real-world applications.
|
||||
### Q: Can CrewAI handle complex use cases?
|
||||
|
||||
A: Yes. CrewAI excels at both simple and highly complex real-world scenarios, offering deep customization options at both high and low levels, from internal prompts to sophisticated workflow orchestration.
|
||||
|
||||
### Q: Can I use CrewAI with local AI models?
|
||||
|
||||
A: Absolutely! CrewAI supports various language models, including local ones. Tools like Ollama and LM Studio allow seamless integration. Check the [LLM Connections documentation](https://docs.crewai.com/how-to/LLM-Connections/) for more details.
|
||||
|
||||
### Q: What makes Crews different from Flows?
|
||||
|
||||
A: Crews provide autonomous agent collaboration, ideal for tasks requiring flexible decision-making and dynamic interaction. Flows offer precise, event-driven control, ideal for managing detailed execution paths and secure state management. You can seamlessly combine both for maximum effectiveness.
|
||||
|
||||
### Q: How is CrewAI better than LangChain?
|
||||
|
||||
A: CrewAI provides simpler, more intuitive APIs, faster execution speeds, more reliable and consistent results, robust documentation, and an active community—addressing common criticisms and limitations associated with LangChain.
|
||||
|
||||
### Q: Is CrewAI open-source?
|
||||
A: Yes, CrewAI is open-source and welcomes contributions from the community.
|
||||
|
||||
### Q: Does CrewAI collect any data?
|
||||
A: CrewAI uses anonymous telemetry to collect usage data for improvement purposes. No sensitive data (like prompts, task descriptions, or API calls) is collected. Users can opt-in to share more detailed data by setting `share_crew=True` on their Crews.
|
||||
A: Yes, CrewAI is open-source and actively encourages community contributions and collaboration.
|
||||
|
||||
### Q: Where can I find examples of CrewAI in action?
|
||||
A: You can find various real-life examples in the [CrewAI-examples repository](https://github.com/crewAIInc/crewAI-examples), including trip planners, stock analysis tools, and more.
|
||||
### Q: Does CrewAI collect data from users?
|
||||
|
||||
### Q: What is the difference between Crews and Flows?
|
||||
A: Crews and Flows serve different but complementary purposes in CrewAI. Crews are teams of AI agents working together to accomplish specific tasks through role-based collaboration, delivering accurate and predictable results. Flows, on the other hand, are event-driven workflows that can orchestrate both Crews and regular Python code, allowing you to build complex automation pipelines with secure state management and conditional execution paths.
|
||||
A: CrewAI collects anonymous telemetry data strictly for improvement purposes. Sensitive data such as prompts, tasks, or API responses are never collected unless explicitly enabled by the user.
|
||||
|
||||
### Q: Where can I find real-world CrewAI examples?
|
||||
|
||||
A: Check out practical examples in the [CrewAI-examples repository](https://github.com/crewAIInc/crewAI-examples), covering use cases like trip planners, stock analysis, and job postings.
|
||||
|
||||
### Q: How can I contribute to CrewAI?
|
||||
A: Contributions are welcome! You can fork the repository, create a new branch for your feature, add your improvement, and send a pull request. Check the Contribution section in the README for more details.
|
||||
|
||||
A: Contributions are warmly welcomed! Fork the repository, create your branch, implement your changes, and submit a pull request. See the Contribution section of the README for detailed guidelines.
|
||||
|
||||
### Q: What additional features does CrewAI Enterprise offer?
|
||||
|
||||
A: CrewAI Enterprise provides advanced features such as a unified control plane, real-time observability, secure integrations, advanced security, actionable insights, and dedicated 24/7 enterprise support.
|
||||
|
||||
### Q: Is CrewAI Enterprise available for cloud and on-premise deployments?
|
||||
|
||||
A: Yes, CrewAI Enterprise supports both cloud-based and on-premise deployment options, allowing enterprises to meet their specific security and compliance requirements.
|
||||
|
||||
### Q: Can I try CrewAI Enterprise for free?
|
||||
|
||||
A: Yes, you can explore part of the CrewAI Enterprise Suite by accessing the [Crew Control Plane](https://app.crewai.com) for free.
|
||||
|
||||
### Q: Does CrewAI support fine-tuning or training custom models?
|
||||
|
||||
A: Yes, CrewAI can integrate with custom-trained or fine-tuned models, allowing you to enhance your agents with domain-specific knowledge and accuracy.
|
||||
|
||||
### Q: Can CrewAI agents interact with external tools and APIs?
|
||||
|
||||
A: Absolutely! CrewAI agents can easily integrate with external tools, APIs, and databases, empowering them to leverage real-world data and resources.
|
||||
|
||||
### Q: Is CrewAI suitable for production environments?
|
||||
|
||||
A: Yes, CrewAI is explicitly designed with production-grade standards, ensuring reliability, stability, and scalability for enterprise deployments.
|
||||
|
||||
### Q: How scalable is CrewAI?
|
||||
|
||||
A: CrewAI is highly scalable, supporting simple automations and large-scale enterprise workflows involving numerous agents and complex tasks simultaneously.
|
||||
|
||||
### Q: Does CrewAI offer debugging and monitoring tools?
|
||||
|
||||
A: Yes, CrewAI Enterprise includes advanced debugging, tracing, and real-time observability features, simplifying the management and troubleshooting of your automations.
|
||||
|
||||
### Q: What programming languages does CrewAI support?
|
||||
|
||||
A: CrewAI is primarily Python-based but easily integrates with services and APIs written in any programming language through its flexible API integration capabilities.
|
||||
|
||||
### Q: Does CrewAI offer educational resources for beginners?
|
||||
|
||||
A: Yes, CrewAI provides extensive beginner-friendly tutorials, courses, and documentation through learn.crewai.com, supporting developers at all skill levels.
|
||||
|
||||
### Q: Can CrewAI automate human-in-the-loop workflows?
|
||||
|
||||
A: Yes, CrewAI fully supports human-in-the-loop workflows, allowing seamless collaboration between human experts and AI agents for enhanced decision-making.
|
||||
|
||||
18
docs/common-room-tracking.js
Normal file
18
docs/common-room-tracking.js
Normal file
@@ -0,0 +1,18 @@
|
||||
(function() {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (typeof window.signals !== 'undefined') return;
|
||||
var script = document.createElement('script');
|
||||
script.src = 'https://cdn.cr-relay.com/v1/site/883520f4-c431-44be-80e7-e123a1ee7a2b/signals.js';
|
||||
script.async = true;
|
||||
window.signals = Object.assign(
|
||||
[],
|
||||
['page', 'identify', 'form'].reduce(function (acc, method){
|
||||
acc[method] = function () {
|
||||
signals.push([method, arguments]);
|
||||
return signals;
|
||||
};
|
||||
return acc;
|
||||
}, {})
|
||||
);
|
||||
document.head.appendChild(script);
|
||||
})();
|
||||
@@ -1,179 +0,0 @@
|
||||
---
|
||||
title: CLI
|
||||
description: Learn how to use the CrewAI CLI to interact with CrewAI.
|
||||
icon: terminal
|
||||
---
|
||||
|
||||
# CrewAI CLI Documentation
|
||||
|
||||
The CrewAI CLI provides a set of commands to interact with CrewAI, allowing you to create, train, run, and manage crews & flows.
|
||||
|
||||
## Installation
|
||||
|
||||
To use the CrewAI CLI, make sure you have CrewAI installed:
|
||||
|
||||
```shell
|
||||
pip install crewai
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
The basic structure of a CrewAI CLI command is:
|
||||
|
||||
```shell
|
||||
crewai [COMMAND] [OPTIONS] [ARGUMENTS]
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
### 1. Create
|
||||
|
||||
Create a new crew or flow.
|
||||
|
||||
```shell
|
||||
crewai create [OPTIONS] TYPE NAME
|
||||
```
|
||||
|
||||
- `TYPE`: Choose between "crew" or "flow"
|
||||
- `NAME`: Name of the crew or flow
|
||||
|
||||
Example:
|
||||
```shell
|
||||
crewai create crew my_new_crew
|
||||
crewai create flow my_new_flow
|
||||
```
|
||||
|
||||
### 2. Version
|
||||
|
||||
Show the installed version of CrewAI.
|
||||
|
||||
```shell
|
||||
crewai version [OPTIONS]
|
||||
```
|
||||
|
||||
- `--tools`: (Optional) Show the installed version of CrewAI tools
|
||||
|
||||
Example:
|
||||
```shell
|
||||
crewai version
|
||||
crewai version --tools
|
||||
```
|
||||
|
||||
### 3. Train
|
||||
|
||||
Train the crew for a specified number of iterations.
|
||||
|
||||
```shell
|
||||
crewai train [OPTIONS]
|
||||
```
|
||||
|
||||
- `-n, --n_iterations INTEGER`: Number of iterations to train the crew (default: 5)
|
||||
- `-f, --filename TEXT`: Path to a custom file for training (default: "trained_agents_data.pkl")
|
||||
|
||||
Example:
|
||||
```shell
|
||||
crewai train -n 10 -f my_training_data.pkl
|
||||
```
|
||||
|
||||
### 4. Replay
|
||||
|
||||
Replay the crew execution from a specific task.
|
||||
|
||||
```shell
|
||||
crewai replay [OPTIONS]
|
||||
```
|
||||
|
||||
- `-t, --task_id TEXT`: Replay the crew from this task ID, including all subsequent tasks
|
||||
|
||||
Example:
|
||||
```shell
|
||||
crewai replay -t task_123456
|
||||
```
|
||||
|
||||
### 5. Log-tasks-outputs
|
||||
|
||||
Retrieve your latest crew.kickoff() task outputs.
|
||||
|
||||
```shell
|
||||
crewai log-tasks-outputs
|
||||
```
|
||||
|
||||
### 6. Reset-memories
|
||||
|
||||
Reset the crew memories (long, short, entity, latest_crew_kickoff_outputs).
|
||||
|
||||
```shell
|
||||
crewai reset-memories [OPTIONS]
|
||||
```
|
||||
|
||||
- `-l, --long`: Reset LONG TERM memory
|
||||
- `-s, --short`: Reset SHORT TERM memory
|
||||
- `-e, --entities`: Reset ENTITIES memory
|
||||
- `-k, --kickoff-outputs`: Reset LATEST KICKOFF TASK OUTPUTS
|
||||
- `-a, --all`: Reset ALL memories
|
||||
|
||||
Example:
|
||||
```shell
|
||||
crewai reset-memories --long --short
|
||||
crewai reset-memories --all
|
||||
```
|
||||
|
||||
### 7. Test
|
||||
|
||||
Test the crew and evaluate the results.
|
||||
|
||||
```shell
|
||||
crewai test [OPTIONS]
|
||||
```
|
||||
|
||||
- `-n, --n_iterations INTEGER`: Number of iterations to test the crew (default: 3)
|
||||
- `-m, --model TEXT`: LLM Model to run the tests on the Crew (default: "gpt-4o-mini")
|
||||
|
||||
Example:
|
||||
```shell
|
||||
crewai test -n 5 -m gpt-3.5-turbo
|
||||
```
|
||||
|
||||
### 8. Run
|
||||
|
||||
Run the crew.
|
||||
|
||||
```shell
|
||||
crewai run
|
||||
```
|
||||
<Note>
|
||||
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>
|
||||
|
||||
|
||||
### 9. API Keys
|
||||
|
||||
When running ```crewai create crew``` command, the CLI will first show you the top 5 most common LLM providers and ask you to select one.
|
||||
|
||||
Once you've selected an LLM provider, you will be prompted for API keys.
|
||||
|
||||
#### Initial API key providers
|
||||
|
||||
The CLI will initially prompt for API keys for the following services:
|
||||
|
||||
* OpenAI
|
||||
* Groq
|
||||
* Anthropic
|
||||
* Google Gemini
|
||||
* SambaNova
|
||||
|
||||
When you select a provider, the CLI will prompt you to enter your API key.
|
||||
|
||||
#### Other Options
|
||||
|
||||
If you select option 6, you will be able to select from a list of LiteLLM supported providers.
|
||||
|
||||
When you select a provider, the CLI will prompt you to enter the Key name and the API key.
|
||||
|
||||
See the following link for each provider's key name:
|
||||
|
||||
* [LiteLLM Providers](https://docs.litellm.ai/docs/providers)
|
||||
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
---
|
||||
title: Collaboration
|
||||
description: Exploring the dynamics of agent collaboration within the CrewAI framework, focusing on the newly integrated features for enhanced functionality.
|
||||
icon: screen-users
|
||||
---
|
||||
|
||||
## Collaboration Fundamentals
|
||||
|
||||
Collaboration in CrewAI is fundamental, enabling agents to combine their skills, share information, and assist each other in task execution, embodying a truly cooperative ecosystem.
|
||||
|
||||
- **Information Sharing**: Ensures all agents are well-informed and can contribute effectively by sharing data and findings.
|
||||
- **Task Assistance**: Allows agents to seek help from peers with the required expertise for specific tasks.
|
||||
- **Resource Allocation**: Optimizes task execution through the efficient distribution and sharing of resources among agents.
|
||||
|
||||
## Enhanced Attributes for Improved Collaboration
|
||||
|
||||
The `Crew` class has been enriched with several attributes to support advanced functionalities:
|
||||
|
||||
| Feature | Description |
|
||||
|:-------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| **Language Model Management** (`manager_llm`, `function_calling_llm`) | Manages language models for executing tasks and tools. `manager_llm` is required for hierarchical processes, while `function_calling_llm` is optional with a default value for streamlined interactions. |
|
||||
| **Custom Manager Agent** (`manager_agent`) | Specifies a custom agent as the manager, replacing the default CrewAI manager. |
|
||||
| **Process Flow** (`process`) | Defines execution logic (e.g., sequential, hierarchical) for task distribution. |
|
||||
| **Verbose Logging** (`verbose`) | Provides detailed logging for monitoring and debugging. Accepts integer and boolean values to control verbosity level. |
|
||||
| **Rate Limiting** (`max_rpm`) | Limits requests per minute to optimize resource usage. Setting guidelines depend on task complexity and load. |
|
||||
| **Internationalization / Customization** (`language`, `prompt_file`) | Supports prompt customization for global usability. [Example of file](https://github.com/joaomdmoura/crewAI/blob/main/src/crewai/translations/en.json) |
|
||||
| **Execution and Output Handling** (`full_output`) | Controls output granularity, distinguishing between full and final outputs. |
|
||||
| **Callback and Telemetry** (`step_callback`, `task_callback`) | Enables step-wise and task-level execution monitoring and telemetry for performance analytics. |
|
||||
| **Crew Sharing** (`share_crew`) | Allows sharing crew data with CrewAI for model improvement. Privacy implications and benefits should be considered. |
|
||||
| **Usage Metrics** (`usage_metrics`) | Logs all LLM usage metrics during task execution for performance insights. |
|
||||
| **Memory Usage** (`memory`) | Enables memory for storing execution history, aiding in agent learning and task efficiency. |
|
||||
| **Embedder Configuration** (`embedder`) | Configures the embedder for language understanding and generation, with support for provider customization. |
|
||||
| **Cache Management** (`cache`) | Specifies whether to cache tool execution results, enhancing performance. |
|
||||
| **Output Logging** (`output_log_file`) | Defines the file path for logging crew execution output. |
|
||||
| **Planning Mode** (`planning`) | Enables action planning before task execution. Set `planning=True` to activate. |
|
||||
| **Replay Feature** (`replay`) | Provides CLI for listing tasks from the last run and replaying from specific tasks, aiding in task management and troubleshooting. |
|
||||
|
||||
## Delegation (Dividing to Conquer)
|
||||
|
||||
Delegation enhances functionality by allowing agents to intelligently assign tasks or seek help, thereby amplifying the crew's overall capability.
|
||||
|
||||
## Implementing Collaboration and Delegation
|
||||
|
||||
Setting up a crew involves defining the roles and capabilities of each agent. CrewAI seamlessly manages their interactions, ensuring efficient collaboration and delegation, with enhanced customization and monitoring features to adapt to various operational needs.
|
||||
|
||||
## Example Scenario
|
||||
|
||||
Consider a crew with a researcher agent tasked with data gathering and a writer agent responsible for compiling reports. The integration of advanced language model management and process flow attributes allows for more sophisticated interactions, such as the writer delegating complex research tasks to the researcher or querying specific information, thereby facilitating a seamless workflow.
|
||||
|
||||
## Conclusion
|
||||
|
||||
The integration of advanced attributes and functionalities into the CrewAI framework significantly enriches the agent collaboration ecosystem. These enhancements not only simplify interactions but also offer unprecedented flexibility and control, paving the way for sophisticated AI-driven solutions capable of tackling complex tasks through intelligent collaboration and delegation.
|
||||
@@ -1,610 +0,0 @@
|
||||
---
|
||||
title: Knowledge
|
||||
description: What is knowledge in CrewAI and how to use it.
|
||||
icon: book
|
||||
---
|
||||
|
||||
## What is Knowledge?
|
||||
|
||||
Knowledge in CrewAI is a powerful system that allows AI agents to access and utilize external information sources during their tasks.
|
||||
Think of it as giving your agents a reference library they can consult while working.
|
||||
|
||||
<Info>
|
||||
Key benefits of using Knowledge:
|
||||
- Enhance agents with domain-specific information
|
||||
- Support decisions with real-world data
|
||||
- Maintain context across conversations
|
||||
- Ground responses in factual information
|
||||
</Info>
|
||||
|
||||
## Supported Knowledge Sources
|
||||
|
||||
CrewAI supports various types of knowledge sources out of the box:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Text Sources" icon="text">
|
||||
- Raw strings
|
||||
- Text files (.txt)
|
||||
- PDF documents
|
||||
</Card>
|
||||
<Card title="Structured Data" icon="table">
|
||||
- CSV files
|
||||
- Excel spreadsheets
|
||||
- JSON documents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Supported Knowledge Parameters
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| :--------------------------- | :---------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `sources` | **List[BaseKnowledgeSource]** | Yes | List of knowledge sources that provide content to be stored and queried. Can include PDF, CSV, Excel, JSON, text files, or string content. |
|
||||
| `collection_name` | **str** | No | Name of the collection where the knowledge will be stored. Used to identify different sets of knowledge. Defaults to "knowledge" if not provided. |
|
||||
| `storage` | **Optional[KnowledgeStorage]** | No | Custom storage configuration for managing how the knowledge is stored and retrieved. If not provided, a default storage will be created. |
|
||||
|
||||
## Quickstart Example
|
||||
|
||||
<Tip>
|
||||
For file-Based Knowledge Sources, make sure to place your files in a `knowledge` directory at the root of your project.
|
||||
Also, use relative paths from the `knowledge` directory when creating the source.
|
||||
</Tip>
|
||||
|
||||
Here's an example using string-based knowledge:
|
||||
|
||||
```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. You can also add more sources to the sources list.
|
||||
)
|
||||
|
||||
result = crew.kickoff(inputs={"question": "What city does John live in and how old is he?"})
|
||||
```
|
||||
|
||||
|
||||
Here's another example with the `CrewDoclingSource`. The CrewDoclingSource is actually quite versatile and can handle multiple file formats including TXT, PDF, DOCX, HTML, and more.
|
||||
|
||||
```python Code
|
||||
from crewai import LLM, Agent, Crew, Process, Task
|
||||
from crewai.knowledge.source.crew_docling_source import CrewDoclingSource
|
||||
|
||||
# Create a knowledge source
|
||||
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
|
||||
], # Enable knowledge by adding the sources here. You can also add more sources to the sources list.
|
||||
)
|
||||
|
||||
result = crew.kickoff(
|
||||
inputs={
|
||||
"question": "What is the reward hacking paper about? Be sure to provide sources."
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## More Examples
|
||||
|
||||
Here are examples of how to use different types of knowledge sources:
|
||||
|
||||
### Text File Knowledge Source
|
||||
```python
|
||||
from crewai.knowledge.source.crew_docling_source import CrewDoclingSource
|
||||
|
||||
# Create a text file knowledge source
|
||||
text_source = CrewDoclingSource(
|
||||
file_paths=["document.txt", "another.txt"]
|
||||
)
|
||||
|
||||
# Create crew with text file source on agents or crew level
|
||||
agent = Agent(
|
||||
...
|
||||
knowledge_sources=[text_source]
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
...
|
||||
knowledge_sources=[text_source]
|
||||
)
|
||||
```
|
||||
|
||||
### PDF Knowledge Source
|
||||
```python
|
||||
from crewai.knowledge.source.pdf_knowledge_source import PDFKnowledgeSource
|
||||
|
||||
# Create a PDF knowledge source
|
||||
pdf_source = PDFKnowledgeSource(
|
||||
file_paths=["document.pdf", "another.pdf"]
|
||||
)
|
||||
|
||||
# Create crew with PDF knowledge source on agents or crew level
|
||||
agent = Agent(
|
||||
...
|
||||
knowledge_sources=[pdf_source]
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
...
|
||||
knowledge_sources=[pdf_source]
|
||||
)
|
||||
```
|
||||
|
||||
### CSV Knowledge Source
|
||||
```python
|
||||
from crewai.knowledge.source.csv_knowledge_source import CSVKnowledgeSource
|
||||
|
||||
# Create a CSV knowledge source
|
||||
csv_source = CSVKnowledgeSource(
|
||||
file_paths=["data.csv"]
|
||||
)
|
||||
|
||||
# Create crew with CSV knowledge source or on agent level
|
||||
agent = Agent(
|
||||
...
|
||||
knowledge_sources=[csv_source]
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
...
|
||||
knowledge_sources=[csv_source]
|
||||
)
|
||||
```
|
||||
|
||||
### Excel Knowledge Source
|
||||
```python
|
||||
from crewai.knowledge.source.excel_knowledge_source import ExcelKnowledgeSource
|
||||
|
||||
# Create an Excel knowledge source
|
||||
excel_source = ExcelKnowledgeSource(
|
||||
file_paths=["spreadsheet.xlsx"]
|
||||
)
|
||||
|
||||
# Create crew with Excel knowledge source on agents or crew level
|
||||
agent = Agent(
|
||||
...
|
||||
knowledge_sources=[excel_source]
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
...
|
||||
knowledge_sources=[excel_source]
|
||||
)
|
||||
```
|
||||
|
||||
### JSON Knowledge Source
|
||||
```python
|
||||
from crewai.knowledge.source.json_knowledge_source import JSONKnowledgeSource
|
||||
|
||||
# Create a JSON knowledge source
|
||||
json_source = JSONKnowledgeSource(
|
||||
file_paths=["data.json"]
|
||||
)
|
||||
|
||||
# Create crew with JSON knowledge source on agents or crew level
|
||||
agent = Agent(
|
||||
...
|
||||
knowledge_sources=[json_source]
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
...
|
||||
knowledge_sources=[json_source]
|
||||
)
|
||||
```
|
||||
|
||||
## Knowledge Configuration
|
||||
|
||||
### Chunking Configuration
|
||||
|
||||
Knowledge sources automatically chunk content for better processing.
|
||||
You can configure chunking behavior in your knowledge sources:
|
||||
|
||||
```python
|
||||
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
|
||||
|
||||
source = StringKnowledgeSource(
|
||||
content="Your content here",
|
||||
chunk_size=4000, # Maximum size of each chunk (default: 4000)
|
||||
chunk_overlap=200 # Overlap between chunks (default: 200)
|
||||
)
|
||||
```
|
||||
|
||||
The chunking configuration helps in:
|
||||
- Breaking down large documents into manageable pieces
|
||||
- Maintaining context through chunk overlap
|
||||
- Optimizing retrieval accuracy
|
||||
|
||||
### Embeddings Configuration
|
||||
|
||||
You can also configure the embedder for the knowledge store.
|
||||
This is useful if you want to use a different embedder for the knowledge store than the one used for the agents.
|
||||
The `embedder` parameter supports various embedding model providers that include:
|
||||
- `openai`: OpenAI's embedding models
|
||||
- `google`: Google's text embedding models
|
||||
- `azure`: Azure OpenAI embeddings
|
||||
- `ollama`: Local embeddings with Ollama
|
||||
- `vertexai`: Google Cloud VertexAI embeddings
|
||||
- `cohere`: Cohere's embedding models
|
||||
- `bedrock`: AWS Bedrock embeddings
|
||||
- `huggingface`: Hugging Face models
|
||||
- `watson`: IBM Watson embeddings
|
||||
|
||||
Here's an example of how to configure the embedder for the knowledge store using Google's `text-embedding-004` model:
|
||||
<CodeGroup>
|
||||
```python Example
|
||||
from crewai import Agent, Task, Crew, Process, LLM
|
||||
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
|
||||
import os
|
||||
|
||||
# Get the GEMINI API key
|
||||
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
||||
|
||||
# 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
|
||||
gemini_llm = LLM(
|
||||
model="gemini/gemini-1.5-pro-002",
|
||||
api_key=GEMINI_API_KEY,
|
||||
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=gemini_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],
|
||||
embedder={
|
||||
"provider": "google",
|
||||
"config": {
|
||||
"model": "models/text-embedding-004",
|
||||
"api_key": GEMINI_API_KEY,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
result = crew.kickoff(inputs={"question": "What city does John live in and how old is he?"})
|
||||
```
|
||||
```text Output
|
||||
# Agent: About User
|
||||
## Task: Answer the following questions about the user: What city does John live in and how old is he?
|
||||
|
||||
# Agent: About User
|
||||
## Final Answer:
|
||||
John is 30 years old and lives in San Francisco.
|
||||
```
|
||||
</CodeGroup>
|
||||
## Clearing Knowledge
|
||||
|
||||
If you need to clear the knowledge stored in CrewAI, you can use the `crewai reset-memories` command with the `--knowledge` option.
|
||||
|
||||
```bash Command
|
||||
crewai reset-memories --knowledge
|
||||
```
|
||||
|
||||
This is useful when you've updated your knowledge sources and want to ensure that the agents are using the most recent information.
|
||||
|
||||
## Agent-Specific Knowledge
|
||||
|
||||
While knowledge can be provided at the crew level using `crew.knowledge_sources`, individual agents can also have their own knowledge sources using the `knowledge_sources` parameter:
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
|
||||
|
||||
# Create agent-specific knowledge about a product
|
||||
product_specs = StringKnowledgeSource(
|
||||
content="""The XPS 13 laptop features:
|
||||
- 13.4-inch 4K display
|
||||
- Intel Core i7 processor
|
||||
- 16GB RAM
|
||||
- 512GB SSD storage
|
||||
- 12-hour battery life""",
|
||||
metadata={"category": "product_specs"}
|
||||
)
|
||||
|
||||
# Create a support agent with product knowledge
|
||||
support_agent = Agent(
|
||||
role="Technical Support Specialist",
|
||||
goal="Provide accurate product information and support.",
|
||||
backstory="You are an expert on our laptop products and specifications.",
|
||||
knowledge_sources=[product_specs] # Agent-specific knowledge
|
||||
)
|
||||
|
||||
# Create a task that requires product knowledge
|
||||
support_task = Task(
|
||||
description="Answer this customer question: {question}",
|
||||
agent=support_agent
|
||||
)
|
||||
|
||||
# Create and run the crew
|
||||
crew = Crew(
|
||||
agents=[support_agent],
|
||||
tasks=[support_task]
|
||||
)
|
||||
|
||||
# Get answer about the laptop's specifications
|
||||
result = crew.kickoff(
|
||||
inputs={"question": "What is the storage capacity of the XPS 13?"}
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Benefits of agent-specific knowledge:
|
||||
- Give agents specialized information for their roles
|
||||
- Maintain separation of concerns between agents
|
||||
- Combine with crew-level knowledge for layered information access
|
||||
</Info>
|
||||
|
||||
## Custom Knowledge Sources
|
||||
|
||||
CrewAI allows you to create custom knowledge sources for any type of data by extending the `BaseKnowledgeSource` class. Let's create a practical example that fetches and processes space news articles.
|
||||
|
||||
#### Space News Knowledge Source Example
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew, Process, LLM
|
||||
from crewai.knowledge.source.base_knowledge_source import BaseKnowledgeSource
|
||||
import requests
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class SpaceNewsKnowledgeSource(BaseKnowledgeSource):
|
||||
"""Knowledge source that fetches data from Space News API."""
|
||||
|
||||
api_endpoint: str = Field(description="API endpoint URL")
|
||||
limit: int = Field(default=10, description="Number of articles to fetch")
|
||||
|
||||
def load_content(self) -> Dict[Any, str]:
|
||||
"""Fetch and format space news articles."""
|
||||
try:
|
||||
response = requests.get(
|
||||
f"{self.api_endpoint}?limit={self.limit}"
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
articles = data.get('results', [])
|
||||
|
||||
formatted_data = self._format_articles(articles)
|
||||
return {self.api_endpoint: formatted_data}
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to fetch space news: {str(e)}")
|
||||
|
||||
def _format_articles(self, articles: list) -> str:
|
||||
"""Format articles into readable text."""
|
||||
formatted = "Space News Articles:\n\n"
|
||||
for article in articles:
|
||||
formatted += f"""
|
||||
Title: {article['title']}
|
||||
Published: {article['published_at']}
|
||||
Summary: {article['summary']}
|
||||
News Site: {article['news_site']}
|
||||
URL: {article['url']}
|
||||
-------------------"""
|
||||
return formatted
|
||||
|
||||
def add(self) -> None:
|
||||
"""Process and store the articles."""
|
||||
content = self.load_content()
|
||||
for _, text in content.items():
|
||||
chunks = self._chunk_text(text)
|
||||
self.chunks.extend(chunks)
|
||||
|
||||
self._save_documents()
|
||||
|
||||
# Create knowledge source
|
||||
recent_news = SpaceNewsKnowledgeSource(
|
||||
api_endpoint="https://api.spaceflightnewsapi.net/v4/articles",
|
||||
limit=10,
|
||||
)
|
||||
|
||||
# Create specialized agent
|
||||
space_analyst = Agent(
|
||||
role="Space News Analyst",
|
||||
goal="Answer questions about space news accurately and comprehensively",
|
||||
backstory="""You are a space industry analyst with expertise in space exploration,
|
||||
satellite technology, and space industry trends. You excel at answering questions
|
||||
about space news and providing detailed, accurate information.""",
|
||||
knowledge_sources=[recent_news],
|
||||
llm=LLM(model="gpt-4", temperature=0.0)
|
||||
)
|
||||
|
||||
# Create task that handles user questions
|
||||
analysis_task = Task(
|
||||
description="Answer this question about space news: {user_question}",
|
||||
expected_output="A detailed answer based on the recent space news articles",
|
||||
agent=space_analyst
|
||||
)
|
||||
|
||||
# Create and run the crew
|
||||
crew = Crew(
|
||||
agents=[space_analyst],
|
||||
tasks=[analysis_task],
|
||||
verbose=True,
|
||||
process=Process.sequential
|
||||
)
|
||||
|
||||
# Example usage
|
||||
result = crew.kickoff(
|
||||
inputs={"user_question": "What are the latest developments in space exploration?"}
|
||||
)
|
||||
```
|
||||
|
||||
```output Output
|
||||
# Agent: Space News Analyst
|
||||
## Task: Answer this question about space news: What are the latest developments in space exploration?
|
||||
|
||||
|
||||
# Agent: Space News Analyst
|
||||
## Final Answer:
|
||||
The latest developments in space exploration, based on recent space news articles, include the following:
|
||||
|
||||
1. SpaceX has received the final regulatory approvals to proceed with the second integrated Starship/Super Heavy launch, scheduled for as soon as the morning of Nov. 17, 2023. This is a significant step in SpaceX's ambitious plans for space exploration and colonization. [Source: SpaceNews](https://spacenews.com/starship-cleared-for-nov-17-launch/)
|
||||
|
||||
2. SpaceX has also informed the US Federal Communications Commission (FCC) that it plans to begin launching its first next-generation Starlink Gen2 satellites. This represents a major upgrade to the Starlink satellite internet service, which aims to provide high-speed internet access worldwide. [Source: Teslarati](https://www.teslarati.com/spacex-first-starlink-gen2-satellite-launch-2022/)
|
||||
|
||||
3. AI startup Synthetaic has raised $15 million in Series B funding. The company uses artificial intelligence to analyze data from space and air sensors, which could have significant applications in space exploration and satellite technology. [Source: SpaceNews](https://spacenews.com/ai-startup-synthetaic-raises-15-million-in-series-b-funding/)
|
||||
|
||||
4. The Space Force has formally established a unit within the U.S. Indo-Pacific Command, marking a permanent presence in the Indo-Pacific region. This could have significant implications for space security and geopolitics. [Source: SpaceNews](https://spacenews.com/space-force-establishes-permanent-presence-in-indo-pacific-region/)
|
||||
|
||||
5. Slingshot Aerospace, a space tracking and data analytics company, is expanding its network of ground-based optical telescopes to increase coverage of low Earth orbit. This could improve our ability to track and analyze objects in low Earth orbit, including satellites and space debris. [Source: SpaceNews](https://spacenews.com/slingshots-space-tracking-network-to-extend-coverage-of-low-earth-orbit/)
|
||||
|
||||
6. The National Natural Science Foundation of China has outlined a five-year project for researchers to study the assembly of ultra-large spacecraft. This could lead to significant advancements in spacecraft technology and space exploration capabilities. [Source: SpaceNews](https://spacenews.com/china-researching-challenges-of-kilometer-scale-ultra-large-spacecraft/)
|
||||
|
||||
7. The Center for AEroSpace Autonomy Research (CAESAR) at Stanford University is focusing on spacecraft autonomy. The center held a kickoff event on May 22, 2024, to highlight the industry, academia, and government collaboration it seeks to foster. This could lead to significant advancements in autonomous spacecraft technology. [Source: SpaceNews](https://spacenews.com/stanford-center-focuses-on-spacecraft-autonomy/)
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
#### Key Components Explained
|
||||
|
||||
1. **Custom Knowledge Source (`SpaceNewsKnowledgeSource`)**:
|
||||
|
||||
- Extends `BaseKnowledgeSource` for integration with CrewAI
|
||||
- Configurable API endpoint and article limit
|
||||
- Implements three key methods:
|
||||
- `load_content()`: Fetches articles from the API
|
||||
- `_format_articles()`: Structures the articles into readable text
|
||||
- `add()`: Processes and stores the content
|
||||
|
||||
2. **Agent Configuration**:
|
||||
|
||||
- Specialized role as a Space News Analyst
|
||||
- Uses the knowledge source to access space news
|
||||
|
||||
3. **Task Setup**:
|
||||
|
||||
- Takes a user question as input through `{user_question}`
|
||||
- Designed to provide detailed answers based on the knowledge source
|
||||
|
||||
4. **Crew Orchestration**:
|
||||
- Manages the workflow between agent and task
|
||||
- Handles input/output through the kickoff method
|
||||
|
||||
This example demonstrates how to:
|
||||
|
||||
- Create a custom knowledge source that fetches real-time data
|
||||
- Process and format external data for AI consumption
|
||||
- Use the knowledge source to answer specific user questions
|
||||
- Integrate everything seamlessly with CrewAI's agent system
|
||||
|
||||
#### About the Spaceflight News API
|
||||
|
||||
The example uses the [Spaceflight News API](https://api.spaceflightnewsapi.net/v4/docs/), which:
|
||||
|
||||
- Provides free access to space-related news articles
|
||||
- Requires no authentication
|
||||
- Returns structured data about space news
|
||||
- Supports pagination and filtering
|
||||
|
||||
You can customize the API query by modifying the endpoint URL:
|
||||
|
||||
```python
|
||||
# Fetch more articles
|
||||
recent_news = SpaceNewsKnowledgeSource(
|
||||
api_endpoint="https://api.spaceflightnewsapi.net/v4/articles",
|
||||
limit=20, # Increase the number of articles
|
||||
)
|
||||
|
||||
# Add search parameters
|
||||
recent_news = SpaceNewsKnowledgeSource(
|
||||
api_endpoint="https://api.spaceflightnewsapi.net/v4/articles?search=NASA", # Search for NASA news
|
||||
limit=10,
|
||||
)
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Content Organization">
|
||||
- Keep chunk sizes appropriate for your content type
|
||||
- Consider content overlap for context preservation
|
||||
- Organize related information into separate knowledge sources
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Performance Tips">
|
||||
- Adjust chunk sizes based on content complexity
|
||||
- Configure appropriate embedding models
|
||||
- Consider using local embedding providers for faster processing
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
@@ -1,71 +0,0 @@
|
||||
---
|
||||
title: Using LlamaIndex Tools
|
||||
description: Learn how to integrate LlamaIndex tools with CrewAI agents to enhance search-based queries and more.
|
||||
icon: toolbox
|
||||
---
|
||||
|
||||
## Using LlamaIndex Tools
|
||||
|
||||
<Info>
|
||||
CrewAI seamlessly integrates with LlamaIndex’s comprehensive toolkit for RAG (Retrieval-Augmented Generation) and agentic pipelines, enabling advanced search-based queries and more.
|
||||
</Info>
|
||||
|
||||
Here are the available built-in tools offered by LlamaIndex.
|
||||
|
||||
```python Code
|
||||
from crewai import Agent
|
||||
from crewai_tools import LlamaIndexTool
|
||||
|
||||
# Example 1: Initialize from FunctionTool
|
||||
from llama_index.core.tools import FunctionTool
|
||||
|
||||
your_python_function = lambda ...: ...
|
||||
og_tool = FunctionTool.from_defaults(
|
||||
your_python_function,
|
||||
name="<name>",
|
||||
description='<description>'
|
||||
)
|
||||
tool = LlamaIndexTool.from_tool(og_tool)
|
||||
|
||||
# Example 2: Initialize from LlamaHub Tools
|
||||
from llama_index.tools.wolfram_alpha import WolframAlphaToolSpec
|
||||
wolfram_spec = WolframAlphaToolSpec(app_id="<app_id>")
|
||||
wolfram_tools = wolfram_spec.to_tool_list()
|
||||
tools = [LlamaIndexTool.from_tool(t) for t in wolfram_tools]
|
||||
|
||||
# Example 3: Initialize Tool from a LlamaIndex Query Engine
|
||||
query_engine = index.as_query_engine()
|
||||
query_tool = LlamaIndexTool.from_query_engine(
|
||||
query_engine,
|
||||
name="Uber 2019 10K Query Tool",
|
||||
description="Use this tool to lookup the 2019 Uber 10K Annual Report"
|
||||
)
|
||||
|
||||
# Create and assign the tools to an agent
|
||||
agent = Agent(
|
||||
role='Research Analyst',
|
||||
goal='Provide up-to-date market analysis',
|
||||
backstory='An expert analyst with a keen eye for market trends.',
|
||||
tools=[tool, *tools, query_tool]
|
||||
)
|
||||
|
||||
# rest of the code ...
|
||||
```
|
||||
|
||||
## Steps to Get Started
|
||||
|
||||
To effectively use the LlamaIndexTool, follow these steps:
|
||||
|
||||
<Steps>
|
||||
<Step title="Package Installation">
|
||||
Make sure that `crewai[tools]` package is installed in your Python environment:
|
||||
<CodeGroup>
|
||||
```shell Terminal
|
||||
pip install 'crewai[tools]'
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Install and Use LlamaIndex">
|
||||
Follow the LlamaIndex documentation [LlamaIndex Documentation](https://docs.llamaindex.ai/) to set up a RAG/agent pipeline.
|
||||
</Step>
|
||||
</Steps>
|
||||
@@ -1,743 +0,0 @@
|
||||
---
|
||||
title: 'LLMs'
|
||||
description: 'A comprehensive guide to configuring and using Large Language Models (LLMs) in your CrewAI projects'
|
||||
icon: 'microchip-ai'
|
||||
---
|
||||
|
||||
<Note>
|
||||
CrewAI integrates with multiple LLM providers through LiteLLM, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.
|
||||
</Note>
|
||||
|
||||
## What are LLMs?
|
||||
|
||||
Large Language Models (LLMs) are the core intelligence behind CrewAI agents. They enable agents to understand context, make decisions, and generate human-like responses. Here's what you need to know:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="LLM Basics" icon="brain">
|
||||
Large Language Models are AI systems trained on vast amounts of text data. They power the intelligence of your CrewAI agents, enabling them to understand and generate human-like text.
|
||||
</Card>
|
||||
<Card title="Context Window" icon="window">
|
||||
The context window determines how much text an LLM can process at once. Larger windows (e.g., 128K tokens) allow for more context but may be more expensive and slower.
|
||||
</Card>
|
||||
<Card title="Temperature" icon="temperature-three-quarters">
|
||||
Temperature (0.0 to 1.0) controls response randomness. Lower values (e.g., 0.2) produce more focused, deterministic outputs, while higher values (e.g., 0.8) increase creativity and variability.
|
||||
</Card>
|
||||
<Card title="Provider Selection" icon="server">
|
||||
Each LLM provider (e.g., OpenAI, Anthropic, Google) offers different models with varying capabilities, pricing, and features. Choose based on your needs for accuracy, speed, and cost.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Models and Their Capabilities
|
||||
|
||||
Here's a detailed breakdown of supported models and their capabilities, you can compare performance at [lmarena.ai](https://lmarena.ai/?leaderboard) and [artificialanalysis.ai](https://artificialanalysis.ai/):
|
||||
|
||||
<Tabs>
|
||||
<Tab title="OpenAI">
|
||||
| Model | Context Window | Best For |
|
||||
|-------|---------------|-----------|
|
||||
| GPT-4 | 8,192 tokens | High-accuracy tasks, complex reasoning |
|
||||
| GPT-4 Turbo | 128,000 tokens | Long-form content, document analysis |
|
||||
| GPT-4o & GPT-4o-mini | 128,000 tokens | Cost-effective large context processing |
|
||||
|
||||
<Note>
|
||||
1 token ≈ 4 characters in English. For example, 8,192 tokens ≈ 32,768 characters or about 6,000 words.
|
||||
</Note>
|
||||
</Tab>
|
||||
<Tab title="Nvidia NIM">
|
||||
| Model | Context Window | Best For |
|
||||
|-------|---------------|-----------|
|
||||
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8,192 tokens | State-of-the-art small language model delivering superior accuracy for chatbot, virtual assistants, and content generation. |
|
||||
| nvidia/nemotron-4-mini-hindi-4b-instruct| 4,096 tokens | A bilingual Hindi-English SLM for on-device inference, tailored specifically for Hindi Language. |
|
||||
| "nvidia/llama-3.1-nemotron-70b-instruct | 128k tokens | Llama-3.1-Nemotron-70B-Instruct is a large language model customized by NVIDIA in order to improve the helpfulness of LLM generated responses. |
|
||||
| nvidia/llama3-chatqa-1.5-8b | 128k tokens | Advanced LLM to generate high-quality, context-aware responses for chatbots and search engines. |
|
||||
| nvidia/llama3-chatqa-1.5-70b | 128k tokens | Advanced LLM to generate high-quality, context-aware responses for chatbots and search engines. |
|
||||
| nvidia/vila | 128k tokens | Multi-modal vision-language model that understands text/img/video and creates informative responses |
|
||||
| nvidia/neva-22| 4,096 tokens | Multi-modal vision-language model that understands text/images and generates informative responses |
|
||||
| nvidia/nemotron-mini-4b-instruct | 8,192 tokens | General-purpose tasks |
|
||||
| nvidia/usdcode-llama3-70b-instruct | 128k tokens | State-of-the-art LLM that answers OpenUSD knowledge queries and generates USD-Python code. |
|
||||
| nvidia/nemotron-4-340b-instruct | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| meta/codellama-70b | 100k tokens | LLM capable of generating code from natural language and vice versa. |
|
||||
| meta/llama2-70b | 4,096 tokens | Cutting-edge large language AI model capable of generating text and code in response to prompts. |
|
||||
| meta/llama3-8b-instruct | 8,192 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama3-70b-instruct | 8,192 tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| meta/llama-3.1-8b-instruct | 128k tokens | Advanced state-of-the-art model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.1-70b-instruct | 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| meta/llama-3.1-405b-instruct | 128k tokens | Advanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks. |
|
||||
| meta/llama-3.2-1b-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-3b-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-11b-vision-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-90b-vision-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.1-70b-instruct | 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| google/gemma-7b | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2b | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/codegemma-7b | 8,192 tokens | Cutting-edge model built on Google's Gemma-7B specialized for code generation and code completion. |
|
||||
| google/codegemma-1.1-7b | 8,192 tokens | Advanced programming model for code generation, completion, reasoning, and instruction following. |
|
||||
| google/recurrentgemma-2b | 8,192 tokens | Novel recurrent architecture based language model for faster inference when generating long sequences. |
|
||||
| google/gemma-2-9b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2-27b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2-2b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/deplot | 512 tokens | One-shot visual language understanding model that translates images of plots into tables. |
|
||||
| google/paligemma | 8,192 tokens | Vision language model adept at comprehending text and visual inputs to produce informative responses. |
|
||||
| mistralai/mistral-7b-instruct-v0.2 | 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| mistralai/mixtral-8x7b-instruct-v0.1 | 8,192 tokens | An MOE LLM that follows instructions, completes requests, and generates creative text. |
|
||||
| mistralai/mistral-large | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| mistralai/mixtral-8x22b-instruct-v0.1 | 8,192 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| mistralai/mistral-7b-instruct-v0.3 | 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| nv-mistralai/mistral-nemo-12b-instruct | 128k tokens | Most advanced language model for reasoning, code, multilingual tasks; runs on a single GPU. |
|
||||
| mistralai/mamba-codestral-7b-v0.1 | 256k tokens | Model for writing and interacting with code across a wide range of programming languages and tasks. |
|
||||
| microsoft/phi-3-mini-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-mini-4k-instruct | 4,096 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-small-8k-instruct | 8,192 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-small-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-medium-4k-instruct | 4,096 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-medium-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3.5-mini-instruct | 128K tokens | Lightweight multilingual LLM powering AI applications in latency bound, memory/compute constrained environments |
|
||||
| microsoft/phi-3.5-moe-instruct | 128K tokens | Advanced LLM based on Mixture of Experts architecure to deliver compute efficient content generation |
|
||||
| microsoft/kosmos-2 | 1,024 tokens | Groundbreaking multimodal model designed to understand and reason about visual elements in images. |
|
||||
| microsoft/phi-3-vision-128k-instruct | 128k tokens | Cutting-edge open multimodal model exceling in high-quality reasoning from images. |
|
||||
| microsoft/phi-3.5-vision-instruct | 128k tokens | Cutting-edge open multimodal model exceling in high-quality reasoning from images. |
|
||||
| databricks/dbrx-instruct | 12k tokens | A general-purpose LLM with state-of-the-art performance in language understanding, coding, and RAG. |
|
||||
| snowflake/arctic | 1,024 tokens | Delivers high efficiency inference for enterprise applications focused on SQL generation and coding. |
|
||||
| aisingapore/sea-lion-7b-instruct | 4,096 tokens | LLM to represent and serve the linguistic and cultural diversity of Southeast Asia |
|
||||
| ibm/granite-8b-code-instruct | 4,096 tokens | Software programming LLM for code generation, completion, explanation, and multi-turn conversion. |
|
||||
| ibm/granite-34b-code-instruct | 8,192 tokens | Software programming LLM for code generation, completion, explanation, and multi-turn conversion. |
|
||||
| ibm/granite-3.0-8b-instruct | 4,096 tokens | Advanced Small Language Model supporting RAG, summarization, classification, code, and agentic AI |
|
||||
| ibm/granite-3.0-3b-a800m-instruct | 4,096 tokens | Highly efficient Mixture of Experts model for RAG, summarization, entity extraction, and classification |
|
||||
| mediatek/breeze-7b-instruct | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| upstage/solar-10.7b-instruct | 4,096 tokens | Excels in NLP tasks, particularly in instruction-following, reasoning, and mathematics. |
|
||||
| writer/palmyra-med-70b-32k | 32k tokens | Leading LLM for accurate, contextually relevant responses in the medical domain. |
|
||||
| writer/palmyra-med-70b | 32k tokens | Leading LLM for accurate, contextually relevant responses in the medical domain. |
|
||||
| writer/palmyra-fin-70b-32k | 32k tokens | Specialized LLM for financial analysis, reporting, and data processing |
|
||||
| 01-ai/yi-large | 32k tokens | Powerful model trained on English and Chinese for diverse tasks including chatbot and creative writing. |
|
||||
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k tokens | Powerful coding model offering advanced capabilities in code generation, completion, and infilling |
|
||||
| rakuten/rakutenai-7b-instruct | 1,024 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| rakuten/rakutenai-7b-chat | 1,024 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| baichuan-inc/baichuan2-13b-chat | 4,096 tokens | Support Chinese and English chat, coding, math, instruction following, solving quizzes |
|
||||
|
||||
<Note>
|
||||
NVIDIA's NIM support for models is expanding continuously! For the most up-to-date list of available models, please visit build.nvidia.com.
|
||||
</Note>
|
||||
</Tab>
|
||||
<Tab title="Gemini">
|
||||
| Model | Context Window | Best For |
|
||||
|-------|---------------|-----------|
|
||||
| gemini-2.0-flash-exp | 1M tokens | Higher quality at faster speed, multimodal model, good for most tasks |
|
||||
| gemini-1.5-flash | 1M tokens | Balanced multimodal model, good for most tasks |
|
||||
| gemini-1.5-flash-8B | 1M tokens | Fastest, most cost-efficient, good for high-frequency tasks |
|
||||
| gemini-1.5-pro | 2M tokens | Best performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration |
|
||||
|
||||
<Tip>
|
||||
Google's Gemini models are all multimodal, supporting audio, images, video and text, supporting context caching, json schema, function calling, etc.
|
||||
|
||||
These models are available via API_KEY from
|
||||
[The Gemini API](https://ai.google.dev/gemini-api/docs) and also from
|
||||
[Google Cloud Vertex](https://cloud.google.com/vertex-ai/generative-ai/docs/migrate/migrate-google-ai) as part of the
|
||||
[Model Garden](https://cloud.google.com/vertex-ai/generative-ai/docs/model-garden/explore-models).
|
||||
</Tip>
|
||||
</Tab>
|
||||
<Tab title="Groq">
|
||||
| Model | Context Window | Best For |
|
||||
|-------|---------------|-----------|
|
||||
| Llama 3.1 70B/8B | 131,072 tokens | High-performance, large context tasks |
|
||||
| Llama 3.2 Series | 8,192 tokens | General-purpose tasks |
|
||||
| Mixtral 8x7B | 32,768 tokens | Balanced performance and context |
|
||||
|
||||
<Tip>
|
||||
Groq is known for its fast inference speeds, making it suitable for real-time applications.
|
||||
</Tip>
|
||||
</Tab>
|
||||
<Tab title="SambaNova">
|
||||
| Model | Context Window | Best For |
|
||||
|-------|---------------|-----------|
|
||||
| Llama 3.1 70B/8B | Up to 131,072 tokens | High-performance, large context tasks |
|
||||
| Llama 3.1 405B | 8,192 tokens | High-performance and output quality |
|
||||
| Llama 3.2 Series | 8,192 tokens | General-purpose tasks, multimodal |
|
||||
| Llama 3.3 70B | Up to 131,072 tokens | High-performance and output quality|
|
||||
| Qwen2 familly | 8,192 tokens | High-performance and output quality |
|
||||
|
||||
<Tip>
|
||||
[SambaNova](https://cloud.sambanova.ai/) has several models with fast inference speed at full precision.
|
||||
</Tip>
|
||||
</Tab>
|
||||
<Tab title="Others">
|
||||
| Provider | Context Window | Key Features |
|
||||
|----------|---------------|--------------|
|
||||
| Deepseek Chat | 128,000 tokens | Specialized in technical discussions |
|
||||
| Claude 3 | Up to 200K tokens | Strong reasoning, code understanding |
|
||||
| Gemma Series | 8,192 tokens | Efficient, smaller-scale tasks |
|
||||
|
||||
<Info>
|
||||
Provider selection should consider factors like:
|
||||
- API availability in your region
|
||||
- Pricing structure
|
||||
- Required features (e.g., streaming, function calling)
|
||||
- Performance requirements
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Setting Up Your LLM
|
||||
|
||||
There are three ways to configure LLMs in CrewAI. Choose the method that best fits your workflow:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="1. Environment Variables">
|
||||
The simplest way to get started. Set these variables in your environment:
|
||||
|
||||
```bash
|
||||
# Required: Your API key for authentication
|
||||
OPENAI_API_KEY=<your-api-key>
|
||||
|
||||
# Optional: Default model selection
|
||||
OPENAI_MODEL_NAME=gpt-4o-mini # Default if not set
|
||||
|
||||
# Optional: Organization ID (if applicable)
|
||||
OPENAI_ORGANIZATION_ID=<your-org-id>
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Never commit API keys to version control. Use environment files (.env) or your system's secret management.
|
||||
</Warning>
|
||||
</Tab>
|
||||
<Tab title="2. YAML Configuration">
|
||||
Create a YAML file to define your agent configurations. This method is great for version control and team collaboration:
|
||||
|
||||
```yaml
|
||||
researcher:
|
||||
# Agent Definition
|
||||
role: Research Specialist
|
||||
goal: Conduct comprehensive research and analysis
|
||||
backstory: A dedicated research professional with years of experience
|
||||
verbose: true
|
||||
|
||||
# Model Selection (uncomment your choice)
|
||||
|
||||
# OpenAI Models - Known for reliability and performance
|
||||
llm: openai/gpt-4o-mini
|
||||
# llm: openai/gpt-4 # More accurate but expensive
|
||||
# llm: openai/gpt-4-turbo # Fast with large context
|
||||
# llm: openai/gpt-4o # Optimized for longer texts
|
||||
# llm: openai/o1-preview # Latest features
|
||||
# llm: openai/o1-mini # Cost-effective
|
||||
|
||||
# Azure Models - For enterprise deployments
|
||||
# llm: azure/gpt-4o-mini
|
||||
# llm: azure/gpt-4
|
||||
# llm: azure/gpt-35-turbo
|
||||
|
||||
# Anthropic Models - Strong reasoning capabilities
|
||||
# llm: anthropic/claude-3-opus-20240229-v1:0
|
||||
# llm: anthropic/claude-3-sonnet-20240229-v1:0
|
||||
# llm: anthropic/claude-3-haiku-20240307-v1:0
|
||||
# llm: anthropic/claude-2.1
|
||||
# llm: anthropic/claude-2.0
|
||||
|
||||
# Google Models - Strong reasoning, large cachable context window, multimodal
|
||||
# llm: gemini/gemini-1.5-pro-latest
|
||||
# llm: gemini/gemini-1.5-flash-latest
|
||||
# llm: gemini/gemini-1.5-flash-8b-latest
|
||||
|
||||
# AWS Bedrock Models - Enterprise-grade
|
||||
# llm: bedrock/anthropic.claude-3-sonnet-20240229-v1:0
|
||||
# llm: bedrock/anthropic.claude-v2:1
|
||||
# llm: bedrock/amazon.titan-text-express-v1
|
||||
# llm: bedrock/meta.llama2-70b-chat-v1
|
||||
|
||||
# Mistral Models - Open source alternative
|
||||
# llm: mistral/mistral-large-latest
|
||||
# llm: mistral/mistral-medium-latest
|
||||
# llm: mistral/mistral-small-latest
|
||||
|
||||
# Groq Models - Fast inference
|
||||
# llm: groq/mixtral-8x7b-32768
|
||||
# llm: groq/llama-3.1-70b-versatile
|
||||
# llm: groq/llama-3.2-90b-text-preview
|
||||
# llm: groq/gemma2-9b-it
|
||||
# llm: groq/gemma-7b-it
|
||||
|
||||
# IBM watsonx.ai Models - Enterprise features
|
||||
# llm: watsonx/ibm/granite-13b-chat-v2
|
||||
# llm: watsonx/meta-llama/llama-3-1-70b-instruct
|
||||
# llm: watsonx/bigcode/starcoder2-15b
|
||||
|
||||
# Ollama Models - Local deployment
|
||||
# llm: ollama/llama3:70b
|
||||
# llm: ollama/codellama
|
||||
# llm: ollama/mistral
|
||||
# llm: ollama/mixtral
|
||||
# llm: ollama/phi
|
||||
|
||||
# Fireworks AI Models - Specialized tasks
|
||||
# llm: fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct
|
||||
# llm: fireworks_ai/accounts/fireworks/models/mixtral-8x7b
|
||||
# llm: fireworks_ai/accounts/fireworks/models/zephyr-7b-beta
|
||||
|
||||
# Perplexity AI Models - Research focused
|
||||
# llm: pplx/llama-3.1-sonar-large-128k-online
|
||||
# llm: pplx/mistral-7b-instruct
|
||||
# llm: pplx/codellama-34b-instruct
|
||||
# llm: pplx/mixtral-8x7b-instruct
|
||||
|
||||
# Hugging Face Models - Community models
|
||||
# llm: huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct
|
||||
# llm: huggingface/mistralai/Mixtral-8x7B-Instruct-v0.1
|
||||
# llm: huggingface/tiiuae/falcon-180B-chat
|
||||
# llm: huggingface/google/gemma-7b-it
|
||||
|
||||
# Nvidia NIM Models - GPU-optimized
|
||||
# llm: nvidia_nim/meta/llama3-70b-instruct
|
||||
# llm: nvidia_nim/mistral/mixtral-8x7b
|
||||
# llm: nvidia_nim/google/gemma-7b
|
||||
|
||||
# SambaNova Models - Enterprise AI
|
||||
# llm: sambanova/Meta-Llama-3.1-8B-Instruct
|
||||
# llm: sambanova/BioMistral-7B
|
||||
# llm: sambanova/Falcon-180B
|
||||
```
|
||||
|
||||
<Info>
|
||||
The YAML configuration allows you to:
|
||||
- Version control your agent settings
|
||||
- Easily switch between different models
|
||||
- Share configurations across team members
|
||||
- Document model choices and their purposes
|
||||
</Info>
|
||||
</Tab>
|
||||
<Tab title="3. Direct Code">
|
||||
For maximum flexibility, configure LLMs directly in your Python code:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Basic configuration
|
||||
llm = LLM(model="gpt-4")
|
||||
|
||||
# Advanced configuration with detailed parameters
|
||||
llm = LLM(
|
||||
model="gpt-4o-mini",
|
||||
temperature=0.7, # Higher for more creative outputs
|
||||
timeout=120, # Seconds to wait for response
|
||||
max_tokens=4000, # Maximum length of response
|
||||
top_p=0.9, # Nucleus sampling parameter
|
||||
frequency_penalty=0.1, # Reduce repetition
|
||||
presence_penalty=0.1, # Encourage topic diversity
|
||||
response_format={"type": "json"}, # For structured outputs
|
||||
seed=42 # For reproducible results
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Parameter explanations:
|
||||
- `temperature`: Controls randomness (0.0-1.0)
|
||||
- `timeout`: Maximum wait time for response
|
||||
- `max_tokens`: Limits response length
|
||||
- `top_p`: Alternative to temperature for sampling
|
||||
- `frequency_penalty`: Reduces word repetition
|
||||
- `presence_penalty`: Encourages new topics
|
||||
- `response_format`: Specifies output structure
|
||||
- `seed`: Ensures consistent outputs
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Advanced Features and Optimization
|
||||
|
||||
Learn how to get the most out of your LLM configuration:
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Context Window Management">
|
||||
CrewAI includes smart context management features:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# CrewAI automatically handles:
|
||||
# 1. Token counting and tracking
|
||||
# 2. Content summarization when needed
|
||||
# 3. Task splitting for large contexts
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
max_tokens=4000, # Limit response length
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Best practices for context management:
|
||||
1. Choose models with appropriate context windows
|
||||
2. Pre-process long inputs when possible
|
||||
3. Use chunking for large documents
|
||||
4. Monitor token usage to optimize costs
|
||||
</Info>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Performance Optimization">
|
||||
<Steps>
|
||||
<Step title="Token Usage Optimization">
|
||||
Choose the right context window for your task:
|
||||
- Small tasks (up to 4K tokens): Standard models
|
||||
- Medium tasks (between 4K-32K): Enhanced models
|
||||
- Large tasks (over 32K): Large context models
|
||||
|
||||
```python
|
||||
# Configure model with appropriate settings
|
||||
llm = LLM(
|
||||
model="openai/gpt-4-turbo-preview",
|
||||
temperature=0.7, # Adjust based on task
|
||||
max_tokens=4096, # Set based on output needs
|
||||
timeout=300 # Longer timeout for complex tasks
|
||||
)
|
||||
```
|
||||
<Tip>
|
||||
- Lower temperature (0.1 to 0.3) for factual responses
|
||||
- Higher temperature (0.7 to 0.9) for creative tasks
|
||||
</Tip>
|
||||
</Step>
|
||||
|
||||
<Step title="Best Practices">
|
||||
1. Monitor token usage
|
||||
2. Implement rate limiting
|
||||
3. Use caching when possible
|
||||
4. Set appropriate max_tokens limits
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Info>
|
||||
Remember to regularly monitor your token usage and adjust your configuration as needed to optimize costs and performance.
|
||||
</Info>
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Provider Configuration Examples
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI">
|
||||
```python Code
|
||||
# Required
|
||||
OPENAI_API_KEY=sk-...
|
||||
|
||||
# Optional
|
||||
OPENAI_API_BASE=<custom-base-url>
|
||||
OPENAI_ORGANIZATION=<your-org-id>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
temperature=0.8,
|
||||
max_tokens=150,
|
||||
top_p=0.9,
|
||||
frequency_penalty=0.1,
|
||||
presence_penalty=0.1,
|
||||
stop=["END"],
|
||||
seed=42
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Anthropic">
|
||||
```python Code
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-sonnet-20240229-v1:0",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google">
|
||||
```python Code
|
||||
# Option 1. Gemini accessed with an API key.
|
||||
# https://ai.google.dev/gemini-api/docs/api-key
|
||||
GEMINI_API_KEY=<your-api-key>
|
||||
|
||||
# Option 2. Vertex AI IAM credentials for Gemini, Anthropic, and anything in the Model Garden.
|
||||
# https://cloud.google.com/vertex-ai/generative-ai/docs/overview
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="gemini/gemini-1.5-pro-latest",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Azure">
|
||||
```python 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>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="azure/gpt-4",
|
||||
api_version="2023-05-15"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="AWS Bedrock">
|
||||
```python Code
|
||||
AWS_ACCESS_KEY_ID=<your-access-key>
|
||||
AWS_SECRET_ACCESS_KEY=<your-secret-key>
|
||||
AWS_DEFAULT_REGION=<your-region>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Mistral">
|
||||
```python Code
|
||||
MISTRAL_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="mistral/mistral-large-latest",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Nvidia NIM">
|
||||
```python Code
|
||||
NVIDIA_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nvidia_nim/meta/llama3-70b-instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Groq">
|
||||
```python Code
|
||||
GROQ_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="groq/llama-3.2-90b-text-preview",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="IBM watsonx.ai">
|
||||
```python 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>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```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. Install Ollama: [ollama.ai](https://ollama.ai/)
|
||||
2. Run a model: `ollama run llama2`
|
||||
3. Configure:
|
||||
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="ollama/llama3:70b",
|
||||
base_url="http://localhost:11434"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Fireworks AI">
|
||||
```python Code
|
||||
FIREWORKS_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Perplexity AI">
|
||||
```python Code
|
||||
PERPLEXITY_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="llama-3.1-sonar-large-128k-online",
|
||||
base_url="https://api.perplexity.ai/"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Hugging Face">
|
||||
```python Code
|
||||
HUGGINGFACE_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct",
|
||||
base_url="your_api_endpoint"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SambaNova">
|
||||
```python Code
|
||||
SAMBANOVA_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sambanova/Meta-Llama-3.1-8B-Instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Cerebras">
|
||||
```python Code
|
||||
# Required
|
||||
CEREBRAS_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="cerebras/llama3.1-70b",
|
||||
temperature=0.7,
|
||||
max_tokens=8192
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Cerebras features:
|
||||
- Fast inference speeds
|
||||
- Competitive pricing
|
||||
- Good balance of speed and quality
|
||||
- Support for long context windows
|
||||
</Info>
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Common Issues and Solutions
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Authentication">
|
||||
<Warning>
|
||||
Most authentication issues can be resolved by checking API key format and environment variable names.
|
||||
</Warning>
|
||||
|
||||
```bash
|
||||
# OpenAI
|
||||
OPENAI_API_KEY=sk-...
|
||||
|
||||
# Anthropic
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Model Names">
|
||||
<Check>
|
||||
Always include the provider prefix in model names
|
||||
</Check>
|
||||
|
||||
```python
|
||||
# Correct
|
||||
llm = LLM(model="openai/gpt-4")
|
||||
|
||||
# Incorrect
|
||||
llm = LLM(model="gpt-4")
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Context Length">
|
||||
<Tip>
|
||||
Use larger context models for extensive tasks
|
||||
</Tip>
|
||||
|
||||
```python
|
||||
# Large context model
|
||||
llm = LLM(model="openai/gpt-4o") # 128K tokens
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you need assistance, these resources are available:
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="LiteLLM Documentation"
|
||||
href="https://docs.litellm.ai/docs/"
|
||||
icon="book"
|
||||
>
|
||||
Comprehensive documentation for LiteLLM integration and troubleshooting common issues.
|
||||
</Card>
|
||||
<Card
|
||||
title="GitHub Issues"
|
||||
href="https://github.com/joaomdmoura/crewAI/issues"
|
||||
icon="bug"
|
||||
>
|
||||
Report bugs, request features, or browse existing issues for solutions.
|
||||
</Card>
|
||||
<Card
|
||||
title="Community Forum"
|
||||
href="https://community.crewai.com"
|
||||
icon="comment-question"
|
||||
>
|
||||
Connect with other CrewAI users, share experiences, and get help from the community.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
Best Practices for API Key Security:
|
||||
- Use environment variables or secure vaults
|
||||
- Never commit keys to version control
|
||||
- Rotate keys regularly
|
||||
- Use separate keys for development and production
|
||||
- Monitor key usage for unusual patterns
|
||||
</Note>
|
||||
@@ -1,367 +0,0 @@
|
||||
---
|
||||
title: Memory
|
||||
description: Leveraging memory systems in the CrewAI framework to enhance agent capabilities.
|
||||
icon: database
|
||||
---
|
||||
|
||||
## Introduction to Memory Systems in CrewAI
|
||||
|
||||
The crewAI framework introduces a sophisticated memory system designed to significantly enhance the capabilities of AI agents.
|
||||
This system comprises `short-term memory`, `long-term memory`, `entity memory`, and `contextual memory`, each serving a unique purpose in aiding agents to remember,
|
||||
reason, and learn from past interactions.
|
||||
|
||||
## Memory System Components
|
||||
|
||||
| Component | Description |
|
||||
| :------------------- | :---------------------------------------------------------------------------------------------------------------------- |
|
||||
| **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. |
|
||||
| **User Memory** | Stores user-specific information and preferences, enhancing personalization and user experience. |
|
||||
|
||||
## How Memory Systems Empower Agents
|
||||
|
||||
1. **Contextual Awareness**: With short-term and contextual memory, agents gain the ability to maintain context over a conversation or task sequence, leading to more coherent and relevant responses.
|
||||
|
||||
2. **Experience Accumulation**: Long-term memory allows agents to accumulate experiences, learning from past actions to improve future decision-making and problem-solving.
|
||||
|
||||
3. **Entity Understanding**: By maintaining entity memory, agents can recognize and remember key entities, enhancing their ability to process and interact with complex information.
|
||||
|
||||
## Implementing Memory in Your Crew
|
||||
|
||||
When configuring a crew, you can enable and customize each memory component to suit the crew's objectives and the nature of tasks it will perform.
|
||||
By default, the memory system is disabled, and you can ensure it is active by setting `memory=True` in the crew configuration.
|
||||
The memory will use OpenAI embeddings by default, but you can change it by setting `embedder` to a different model.
|
||||
It's also possible to initialize the memory instance with your own instance.
|
||||
|
||||
The 'embedder' only applies to **Short-Term Memory** which uses Chroma for RAG.
|
||||
The **Long-Term Memory** uses SQLite3 to store task results. Currently, there is no way to override these storage implementations.
|
||||
The data storage files are saved into a platform-specific location found using the appdirs package,
|
||||
and the name of the project can be overridden using the **CREWAI_STORAGE_DIR** environment variable.
|
||||
|
||||
### Example: Configuring Memory for a Crew
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
# Assemble your crew with memory capabilities
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
### Example: Use Custom Memory Instances e.g FAISS as the VectorDB
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
# Assemble your crew with memory capabilities
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process="Process.sequential",
|
||||
memory=True,
|
||||
long_term_memory=EnhanceLongTermMemory(
|
||||
storage=LTMSQLiteStorage(
|
||||
db_path="/my_data_dir/my_crew1/long_term_memory_storage.db"
|
||||
)
|
||||
),
|
||||
short_term_memory=EnhanceShortTermMemory(
|
||||
storage=CustomRAGStorage(
|
||||
crew_name="my_crew",
|
||||
storage_type="short_term",
|
||||
data_dir="//my_data_dir",
|
||||
model=embedder["model"],
|
||||
dimension=embedder["dimension"],
|
||||
),
|
||||
),
|
||||
entity_memory=EnhanceEntityMemory(
|
||||
storage=CustomRAGStorage(
|
||||
crew_name="my_crew",
|
||||
storage_type="entities",
|
||||
data_dir="//my_data_dir",
|
||||
model=embedder["model"],
|
||||
dimension=embedder["dimension"],
|
||||
),
|
||||
),
|
||||
verbose=True,
|
||||
)
|
||||
```
|
||||
|
||||
## Integrating Mem0 for Enhanced User Memory
|
||||
|
||||
[Mem0](https://mem0.ai/) is a self-improving memory layer for LLM applications, enabling personalized AI experiences.
|
||||
|
||||
To include user-specific memory you can get your API key [here](https://app.mem0.ai/dashboard/api-keys) and refer the [docs](https://docs.mem0.ai/platform/quickstart#4-1-create-memories) for adding user preferences.
|
||||
|
||||
|
||||
```python Code
|
||||
import os
|
||||
from crewai import Crew, Process
|
||||
from mem0 import MemoryClient
|
||||
|
||||
# Set environment variables for Mem0
|
||||
os.environ["MEM0_API_KEY"] = "m0-xx"
|
||||
|
||||
# Step 1: Record preferences based on past conversation or user input
|
||||
client = MemoryClient()
|
||||
messages = [
|
||||
{"role": "user", "content": "Hi there! I'm planning a vacation and could use some advice."},
|
||||
{"role": "assistant", "content": "Hello! I'd be happy to help with your vacation planning. What kind of destination do you prefer?"},
|
||||
{"role": "user", "content": "I am more of a beach person than a mountain person."},
|
||||
{"role": "assistant", "content": "That's interesting. Do you like hotels or Airbnb?"},
|
||||
{"role": "user", "content": "I like Airbnb more."},
|
||||
]
|
||||
client.add(messages, user_id="john")
|
||||
|
||||
# Step 2: Create a Crew with User Memory
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
verbose=True,
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
memory_config={
|
||||
"provider": "mem0",
|
||||
"config": {"user_id": "john"},
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
## Memory Configuration Options
|
||||
If you want to access a specific organization and project, you can set the `org_id` and `project_id` parameters in the memory configuration.
|
||||
|
||||
```python Code
|
||||
from crewai import Crew
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
verbose=True,
|
||||
memory=True,
|
||||
memory_config={
|
||||
"provider": "mem0",
|
||||
"config": {"user_id": "john", "org_id": "my_org_id", "project_id": "my_project_id"},
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
## Additional Embedding Providers
|
||||
|
||||
### Using OpenAI embeddings (already default)
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder={
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": 'text-embedding-3-small'
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
Alternatively, you can directly pass the OpenAIEmbeddingFunction to the embedder parameter.
|
||||
|
||||
Example:
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder=OpenAIEmbeddingFunction(api_key=os.getenv("OPENAI_API_KEY"), model_name="text-embedding-3-small"),
|
||||
)
|
||||
```
|
||||
|
||||
### Using Ollama embeddings
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder={
|
||||
"provider": "ollama",
|
||||
"config": {
|
||||
"model": "mxbai-embed-large"
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Using Google AI embeddings
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder={
|
||||
"provider": "google",
|
||||
"config": {
|
||||
"api_key": "<YOUR_API_KEY>",
|
||||
"model_name": "<model_name>"
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Using Azure OpenAI embeddings
|
||||
|
||||
```python Code
|
||||
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder=OpenAIEmbeddingFunction(
|
||||
api_key="YOUR_API_KEY",
|
||||
api_base="YOUR_API_BASE_PATH",
|
||||
api_type="azure",
|
||||
api_version="YOUR_API_VERSION",
|
||||
model_name="text-embedding-3-small"
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### Using Vertex AI embeddings
|
||||
|
||||
```python Code
|
||||
from chromadb.utils.embedding_functions import GoogleVertexEmbeddingFunction
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder=GoogleVertexEmbeddingFunction(
|
||||
project_id="YOUR_PROJECT_ID",
|
||||
region="YOUR_REGION",
|
||||
api_key="YOUR_API_KEY",
|
||||
model_name="textembedding-gecko"
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### Using Cohere embeddings
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder={
|
||||
"provider": "cohere",
|
||||
"config": {
|
||||
"api_key": "YOUR_API_KEY",
|
||||
"model_name": "<model_name>"
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
### Using HuggingFace embeddings
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder={
|
||||
"provider": "huggingface",
|
||||
"config": {
|
||||
"api_url": "<api_url>",
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Using Watson embeddings
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
# Note: Ensure you have installed and imported `ibm_watsonx_ai` for Watson embeddings to work.
|
||||
|
||||
my_crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
embedder={
|
||||
"provider": "watson",
|
||||
"config": {
|
||||
"model": "<model_name>",
|
||||
"api_url": "<api_url>",
|
||||
"api_key": "<YOUR_API_KEY>",
|
||||
"project_id": "<YOUR_PROJECT_ID>",
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Resetting Memory
|
||||
|
||||
```shell
|
||||
crewai reset-memories [OPTIONS]
|
||||
```
|
||||
|
||||
#### Resetting Memory Options
|
||||
|
||||
| Option | Description | Type | Default |
|
||||
| :----------------- | :------------------------------- | :------------- | :------ |
|
||||
| `-l`, `--long` | Reset LONG TERM memory. | Flag (boolean) | False |
|
||||
| `-s`, `--short` | Reset SHORT TERM memory. | Flag (boolean) | False |
|
||||
| `-e`, `--entities` | Reset ENTITIES memory. | Flag (boolean) | False |
|
||||
| `-k`, `--kickoff-outputs` | Reset LATEST KICKOFF TASK OUTPUTS. | Flag (boolean) | False |
|
||||
| `-a`, `--all` | Reset ALL memories. | Flag (boolean) | False |
|
||||
|
||||
|
||||
## Benefits of Using CrewAI's Memory System
|
||||
|
||||
- 🦾 **Adaptive Learning:** Crews become more efficient over time, adapting to new information and refining their approach to tasks.
|
||||
- 🫡 **Enhanced Personalization:** Memory enables agents to remember user preferences and historical interactions, leading to personalized experiences.
|
||||
- 🧠 **Improved Problem Solving:** Access to a rich memory store aids agents in making more informed decisions, drawing on past learnings and contextual insights.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Integrating CrewAI's memory system into your projects is straightforward. By leveraging the provided memory components and configurations,
|
||||
you can quickly empower your agents with the ability to remember, reason, and learn from their interactions, unlocking new levels of intelligence and capability.
|
||||
@@ -1,67 +0,0 @@
|
||||
---
|
||||
title: Training
|
||||
description: Learn how to train your CrewAI agents by giving them feedback early on and get consistent results.
|
||||
icon: dumbbell
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
The training feature in CrewAI allows you to train your AI agents using the command-line interface (CLI).
|
||||
By running the command `crewai train -n <n_iterations>`, you can specify the number of iterations for the training process.
|
||||
|
||||
During training, CrewAI utilizes techniques to optimize the performance of your agents along with human feedback.
|
||||
This helps the agents improve their understanding, decision-making, and problem-solving abilities.
|
||||
|
||||
### Training Your Crew Using the CLI
|
||||
|
||||
To use the training feature, follow these steps:
|
||||
|
||||
1. Open your terminal or command prompt.
|
||||
2. Navigate to the directory where your CrewAI project is located.
|
||||
3. Run the following command:
|
||||
|
||||
```shell
|
||||
crewai train -n <n_iterations> <filename> (optional)
|
||||
```
|
||||
<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
|
||||
|
||||
To train your crew programmatically, use the following steps:
|
||||
|
||||
1. Define the number of iterations for training.
|
||||
2. Specify the input parameters for the training process.
|
||||
3. Execute the training command within a try-except block to handle potential errors.
|
||||
|
||||
```python Code
|
||||
n_iterations = 2
|
||||
inputs = {"topic": "CrewAI Training"}
|
||||
filename = "your_model.pkl"
|
||||
|
||||
try:
|
||||
YourCrewName_Crew().crew().train(
|
||||
n_iterations=n_iterations,
|
||||
inputs=inputs,
|
||||
filename=filename
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"An error occurred while training the crew: {e}")
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
Happy training with CrewAI! 🚀
|
||||
|
||||
796
docs/docs.json
Normal file
796
docs/docs.json
Normal file
@@ -0,0 +1,796 @@
|
||||
{
|
||||
"$schema": "https://mintlify.com/docs.json",
|
||||
"theme": "mint",
|
||||
"name": "CrewAI",
|
||||
"colors": {
|
||||
"primary": "#EB6658",
|
||||
"light": "#F3A78B",
|
||||
"dark": "#C94C3C"
|
||||
},
|
||||
"favicon": "/images/favicon.svg",
|
||||
"contextual": {
|
||||
"options": ["copy", "view", "chatgpt", "claude"]
|
||||
},
|
||||
"navigation": {
|
||||
"languages": [
|
||||
{
|
||||
"language": "en",
|
||||
"global": {
|
||||
"anchors": [
|
||||
{
|
||||
"anchor": "Website",
|
||||
"href": "https://crewai.com",
|
||||
"icon": "globe"
|
||||
},
|
||||
{
|
||||
"anchor": "Forum",
|
||||
"href": "https://community.crewai.com",
|
||||
"icon": "discourse"
|
||||
},
|
||||
{
|
||||
"anchor": "Crew GPT",
|
||||
"href": "https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant",
|
||||
"icon": "robot"
|
||||
},
|
||||
{
|
||||
"anchor": "Releases",
|
||||
"href": "https://github.com/crewAIInc/crewAI/releases",
|
||||
"icon": "tag"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tabs": [
|
||||
{
|
||||
"tab": "Documentation",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Get Started",
|
||||
"pages": ["en/introduction", "en/installation", "en/quickstart"]
|
||||
},
|
||||
{
|
||||
"group": "Guides",
|
||||
"pages": [
|
||||
{
|
||||
"group": "Strategy",
|
||||
"pages": ["en/guides/concepts/evaluating-use-cases"]
|
||||
},
|
||||
{
|
||||
"group": "Agents",
|
||||
"pages": ["en/guides/agents/crafting-effective-agents"]
|
||||
},
|
||||
{
|
||||
"group": "Crews",
|
||||
"pages": ["en/guides/crews/first-crew"]
|
||||
},
|
||||
{
|
||||
"group": "Flows",
|
||||
"pages": [
|
||||
"en/guides/flows/first-flow",
|
||||
"en/guides/flows/mastering-flow-state"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Advanced",
|
||||
"pages": [
|
||||
"en/guides/advanced/customizing-prompts",
|
||||
"en/guides/advanced/fingerprinting"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Core Concepts",
|
||||
"pages": [
|
||||
"en/concepts/agents",
|
||||
"en/concepts/tasks",
|
||||
"en/concepts/crews",
|
||||
"en/concepts/flows",
|
||||
"en/concepts/knowledge",
|
||||
"en/concepts/llms",
|
||||
"en/concepts/processes",
|
||||
"en/concepts/collaboration",
|
||||
"en/concepts/training",
|
||||
"en/concepts/memory",
|
||||
"en/concepts/reasoning",
|
||||
"en/concepts/planning",
|
||||
"en/concepts/testing",
|
||||
"en/concepts/cli",
|
||||
"en/concepts/tools",
|
||||
"en/concepts/event-listener"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "MCP Integration",
|
||||
"pages": [
|
||||
"en/mcp/overview",
|
||||
"en/mcp/stdio",
|
||||
"en/mcp/sse",
|
||||
"en/mcp/streamable-http",
|
||||
"en/mcp/multiple-servers",
|
||||
"en/mcp/security"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Tools",
|
||||
"pages": [
|
||||
"en/tools/overview",
|
||||
{
|
||||
"group": "File & Document",
|
||||
"pages": [
|
||||
"en/tools/file-document/overview",
|
||||
"en/tools/file-document/filereadtool",
|
||||
"en/tools/file-document/filewritetool",
|
||||
"en/tools/file-document/pdfsearchtool",
|
||||
"en/tools/file-document/docxsearchtool",
|
||||
"en/tools/file-document/mdxsearchtool",
|
||||
"en/tools/file-document/xmlsearchtool",
|
||||
"en/tools/file-document/txtsearchtool",
|
||||
"en/tools/file-document/jsonsearchtool",
|
||||
"en/tools/file-document/csvsearchtool",
|
||||
"en/tools/file-document/directorysearchtool",
|
||||
"en/tools/file-document/directoryreadtool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Web Scraping & Browsing",
|
||||
"pages": [
|
||||
"en/tools/web-scraping/overview",
|
||||
"en/tools/web-scraping/scrapewebsitetool",
|
||||
"en/tools/web-scraping/scrapeelementfromwebsitetool",
|
||||
"en/tools/web-scraping/scrapflyscrapetool",
|
||||
"en/tools/web-scraping/seleniumscrapingtool",
|
||||
"en/tools/web-scraping/scrapegraphscrapetool",
|
||||
"en/tools/web-scraping/spidertool",
|
||||
"en/tools/web-scraping/browserbaseloadtool",
|
||||
"en/tools/web-scraping/hyperbrowserloadtool",
|
||||
"en/tools/web-scraping/stagehandtool",
|
||||
"en/tools/web-scraping/firecrawlcrawlwebsitetool",
|
||||
"en/tools/web-scraping/firecrawlscrapewebsitetool",
|
||||
"en/tools/web-scraping/oxylabsscraperstool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Search & Research",
|
||||
"pages": [
|
||||
"en/tools/search-research/overview",
|
||||
"en/tools/search-research/serperdevtool",
|
||||
"en/tools/search-research/bravesearchtool",
|
||||
"en/tools/search-research/exasearchtool",
|
||||
"en/tools/search-research/linkupsearchtool",
|
||||
"en/tools/search-research/githubsearchtool",
|
||||
"en/tools/search-research/websitesearchtool",
|
||||
"en/tools/search-research/codedocssearchtool",
|
||||
"en/tools/search-research/youtubechannelsearchtool",
|
||||
"en/tools/search-research/youtubevideosearchtool",
|
||||
"en/tools/search-research/tavilysearchtool",
|
||||
"en/tools/search-research/tavilyextractortool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Database & Data",
|
||||
"pages": [
|
||||
"en/tools/database-data/overview",
|
||||
"en/tools/database-data/mysqltool",
|
||||
"en/tools/database-data/pgsearchtool",
|
||||
"en/tools/database-data/snowflakesearchtool",
|
||||
"en/tools/database-data/nl2sqltool",
|
||||
"en/tools/database-data/qdrantvectorsearchtool",
|
||||
"en/tools/database-data/weaviatevectorsearchtool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "AI & Machine Learning",
|
||||
"pages": [
|
||||
"en/tools/ai-ml/overview",
|
||||
"en/tools/ai-ml/dalletool",
|
||||
"en/tools/ai-ml/visiontool",
|
||||
"en/tools/ai-ml/aimindtool",
|
||||
"en/tools/ai-ml/llamaindextool",
|
||||
"en/tools/ai-ml/langchaintool",
|
||||
"en/tools/ai-ml/ragtool",
|
||||
"en/tools/ai-ml/codeinterpretertool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Cloud & Storage",
|
||||
"pages": [
|
||||
"en/tools/cloud-storage/overview",
|
||||
"en/tools/cloud-storage/s3readertool",
|
||||
"en/tools/cloud-storage/s3writertool",
|
||||
"en/tools/cloud-storage/bedrockinvokeagenttool",
|
||||
"en/tools/cloud-storage/bedrockkbretriever"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Automation & Integration",
|
||||
"pages": [
|
||||
"en/tools/automation/overview",
|
||||
"en/tools/automation/apifyactorstool",
|
||||
"en/tools/automation/composiotool",
|
||||
"en/tools/automation/multiontool"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Observability",
|
||||
"pages": [
|
||||
"en/observability/overview",
|
||||
"en/observability/agentops",
|
||||
"en/observability/arize-phoenix",
|
||||
"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"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Learn",
|
||||
"pages": [
|
||||
"en/learn/overview",
|
||||
"en/learn/llm-selection-guide",
|
||||
"en/learn/conditional-tasks",
|
||||
"en/learn/coding-agents",
|
||||
"en/learn/create-custom-tools",
|
||||
"en/learn/custom-llm",
|
||||
"en/learn/custom-manager-agent",
|
||||
"en/learn/customizing-agents",
|
||||
"en/learn/dalle-image-generation",
|
||||
"en/learn/force-tool-output-as-result",
|
||||
"en/learn/hierarchical-process",
|
||||
"en/learn/human-input-on-execution",
|
||||
"en/learn/kickoff-async",
|
||||
"en/learn/kickoff-for-each",
|
||||
"en/learn/llm-connections",
|
||||
"en/learn/multimodal-agents",
|
||||
"en/learn/replay-tasks-from-latest-crew-kickoff",
|
||||
"en/learn/sequential-process",
|
||||
"en/learn/using-annotations"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Telemetry",
|
||||
"pages": ["en/telemetry"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Enterprise",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Getting Started",
|
||||
"pages": ["en/enterprise/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "Features",
|
||||
"pages": [
|
||||
"en/enterprise/features/tool-repository",
|
||||
"en/enterprise/features/webhook-streaming",
|
||||
"en/enterprise/features/traces",
|
||||
"en/enterprise/features/hallucination-guardrail",
|
||||
"en/enterprise/features/integrations",
|
||||
"en/enterprise/features/agent-repositories"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Integration Docs",
|
||||
"pages": [
|
||||
"en/enterprise/integrations/asana",
|
||||
"en/enterprise/integrations/box",
|
||||
"en/enterprise/integrations/clickup",
|
||||
"en/enterprise/integrations/github",
|
||||
"en/enterprise/integrations/gmail",
|
||||
"en/enterprise/integrations/google_calendar",
|
||||
"en/enterprise/integrations/google_sheets",
|
||||
"en/enterprise/integrations/hubspot",
|
||||
"en/enterprise/integrations/jira",
|
||||
"en/enterprise/integrations/linear",
|
||||
"en/enterprise/integrations/notion",
|
||||
"en/enterprise/integrations/salesforce",
|
||||
"en/enterprise/integrations/shopify",
|
||||
"en/enterprise/integrations/slack",
|
||||
"en/enterprise/integrations/stripe",
|
||||
"en/enterprise/integrations/zendesk"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "How-To Guides",
|
||||
"pages": [
|
||||
"en/enterprise/guides/build-crew",
|
||||
"en/enterprise/guides/deploy-crew",
|
||||
"en/enterprise/guides/kickoff-crew",
|
||||
"en/enterprise/guides/update-crew",
|
||||
"en/enterprise/guides/enable-crew-studio",
|
||||
"en/enterprise/guides/azure-openai-setup",
|
||||
"en/enterprise/guides/hubspot-trigger",
|
||||
"en/enterprise/guides/react-component-export",
|
||||
"en/enterprise/guides/salesforce-trigger",
|
||||
"en/enterprise/guides/slack-trigger",
|
||||
"en/enterprise/guides/team-management",
|
||||
"en/enterprise/guides/webhook-automation",
|
||||
"en/enterprise/guides/human-in-the-loop",
|
||||
"en/enterprise/guides/zapier-trigger"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Resources",
|
||||
"pages": ["en/enterprise/resources/frequently-asked-questions"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "API Reference",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Getting Started",
|
||||
"pages": ["en/api-reference/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "Endpoints",
|
||||
"openapi": "enterprise-api.yaml"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Examples",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Examples",
|
||||
"pages": ["en/examples/example"]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"language": "pt-BR",
|
||||
"global": {
|
||||
"anchors": [
|
||||
{
|
||||
"anchor": "Website",
|
||||
"href": "https://crewai.com",
|
||||
"icon": "globe"
|
||||
},
|
||||
{
|
||||
"anchor": "Fórum",
|
||||
"href": "https://community.crewai.com",
|
||||
"icon": "discourse"
|
||||
},
|
||||
{
|
||||
"anchor": "Crew GPT",
|
||||
"href": "https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant",
|
||||
"icon": "robot"
|
||||
},
|
||||
{
|
||||
"anchor": "Lançamentos",
|
||||
"href": "https://github.com/crewAIInc/crewAI/releases",
|
||||
"icon": "tag"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tabs": [
|
||||
{
|
||||
"tab": "Documentação",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Começando",
|
||||
"pages": [
|
||||
"pt-BR/introduction",
|
||||
"pt-BR/installation",
|
||||
"pt-BR/quickstart"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Guias",
|
||||
"pages": [
|
||||
{
|
||||
"group": "Estratégia",
|
||||
"pages": ["pt-BR/guides/concepts/evaluating-use-cases"]
|
||||
},
|
||||
{
|
||||
"group": "Agentes",
|
||||
"pages": ["pt-BR/guides/agents/crafting-effective-agents"]
|
||||
},
|
||||
{
|
||||
"group": "Crews",
|
||||
"pages": ["pt-BR/guides/crews/first-crew"]
|
||||
},
|
||||
{
|
||||
"group": "Flows",
|
||||
"pages": [
|
||||
"pt-BR/guides/flows/first-flow",
|
||||
"pt-BR/guides/flows/mastering-flow-state"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Avançado",
|
||||
"pages": [
|
||||
"pt-BR/guides/advanced/customizing-prompts",
|
||||
"pt-BR/guides/advanced/fingerprinting"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Conceitos-Chave",
|
||||
"pages": [
|
||||
"pt-BR/concepts/agents",
|
||||
"pt-BR/concepts/tasks",
|
||||
"pt-BR/concepts/crews",
|
||||
"pt-BR/concepts/flows",
|
||||
"pt-BR/concepts/knowledge",
|
||||
"pt-BR/concepts/llms",
|
||||
"pt-BR/concepts/processes",
|
||||
"pt-BR/concepts/collaboration",
|
||||
"pt-BR/concepts/training",
|
||||
"pt-BR/concepts/memory",
|
||||
"pt-BR/concepts/reasoning",
|
||||
"pt-BR/concepts/planning",
|
||||
"pt-BR/concepts/testing",
|
||||
"pt-BR/concepts/cli",
|
||||
"pt-BR/concepts/tools",
|
||||
"pt-BR/concepts/event-listener"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Integração MCP",
|
||||
"pages": [
|
||||
"pt-BR/mcp/overview",
|
||||
"pt-BR/mcp/stdio",
|
||||
"pt-BR/mcp/sse",
|
||||
"pt-BR/mcp/streamable-http",
|
||||
"pt-BR/mcp/multiple-servers",
|
||||
"pt-BR/mcp/security"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Ferramentas",
|
||||
"pages": [
|
||||
"pt-BR/tools/overview",
|
||||
{
|
||||
"group": "Arquivo & Documento",
|
||||
"pages": [
|
||||
"pt-BR/tools/file-document/overview",
|
||||
"pt-BR/tools/file-document/filereadtool",
|
||||
"pt-BR/tools/file-document/filewritetool",
|
||||
"pt-BR/tools/file-document/pdfsearchtool",
|
||||
"pt-BR/tools/file-document/docxsearchtool",
|
||||
"pt-BR/tools/file-document/mdxsearchtool",
|
||||
"pt-BR/tools/file-document/xmlsearchtool",
|
||||
"pt-BR/tools/file-document/txtsearchtool",
|
||||
"pt-BR/tools/file-document/jsonsearchtool",
|
||||
"pt-BR/tools/file-document/csvsearchtool",
|
||||
"pt-BR/tools/file-document/directorysearchtool",
|
||||
"pt-BR/tools/file-document/directoryreadtool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Web Scraping & Navegação",
|
||||
"pages": [
|
||||
"pt-BR/tools/web-scraping/overview",
|
||||
"pt-BR/tools/web-scraping/scrapewebsitetool",
|
||||
"pt-BR/tools/web-scraping/scrapeelementfromwebsitetool",
|
||||
"pt-BR/tools/web-scraping/scrapflyscrapetool",
|
||||
"pt-BR/tools/web-scraping/seleniumscrapingtool",
|
||||
"pt-BR/tools/web-scraping/scrapegraphscrapetool",
|
||||
"pt-BR/tools/web-scraping/spidertool",
|
||||
"pt-BR/tools/web-scraping/browserbaseloadtool",
|
||||
"pt-BR/tools/web-scraping/hyperbrowserloadtool",
|
||||
"pt-BR/tools/web-scraping/stagehandtool",
|
||||
"pt-BR/tools/web-scraping/firecrawlcrawlwebsitetool",
|
||||
"pt-BR/tools/web-scraping/firecrawlscrapewebsitetool",
|
||||
"pt-BR/tools/web-scraping/oxylabsscraperstool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Pesquisa",
|
||||
"pages": [
|
||||
"pt-BR/tools/search-research/overview",
|
||||
"pt-BR/tools/search-research/serperdevtool",
|
||||
"pt-BR/tools/search-research/bravesearchtool",
|
||||
"pt-BR/tools/search-research/exasearchtool",
|
||||
"pt-BR/tools/search-research/linkupsearchtool",
|
||||
"pt-BR/tools/search-research/githubsearchtool",
|
||||
"pt-BR/tools/search-research/websitesearchtool",
|
||||
"pt-BR/tools/search-research/codedocssearchtool",
|
||||
"pt-BR/tools/search-research/youtubechannelsearchtool",
|
||||
"pt-BR/tools/search-research/youtubevideosearchtool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Dados",
|
||||
"pages": [
|
||||
"pt-BR/tools/database-data/overview",
|
||||
"pt-BR/tools/database-data/mysqltool",
|
||||
"pt-BR/tools/database-data/pgsearchtool",
|
||||
"pt-BR/tools/database-data/snowflakesearchtool",
|
||||
"pt-BR/tools/database-data/nl2sqltool",
|
||||
"pt-BR/tools/database-data/qdrantvectorsearchtool",
|
||||
"pt-BR/tools/database-data/weaviatevectorsearchtool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "IA & Machine Learning",
|
||||
"pages": [
|
||||
"pt-BR/tools/ai-ml/overview",
|
||||
"pt-BR/tools/ai-ml/dalletool",
|
||||
"pt-BR/tools/ai-ml/visiontool",
|
||||
"pt-BR/tools/ai-ml/aimindtool",
|
||||
"pt-BR/tools/ai-ml/llamaindextool",
|
||||
"pt-BR/tools/ai-ml/langchaintool",
|
||||
"pt-BR/tools/ai-ml/ragtool",
|
||||
"pt-BR/tools/ai-ml/codeinterpretertool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Cloud & Armazenamento",
|
||||
"pages": [
|
||||
"pt-BR/tools/cloud-storage/overview",
|
||||
"pt-BR/tools/cloud-storage/s3readertool",
|
||||
"pt-BR/tools/cloud-storage/s3writertool",
|
||||
"pt-BR/tools/cloud-storage/bedrockinvokeagenttool",
|
||||
"pt-BR/tools/cloud-storage/bedrockkbretriever"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Automação & Integração",
|
||||
"pages": [
|
||||
"pt-BR/tools/automation/overview",
|
||||
"pt-BR/tools/automation/apifyactorstool",
|
||||
"pt-BR/tools/automation/composiotool",
|
||||
"pt-BR/tools/automation/multiontool"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Observabilidade",
|
||||
"pages": [
|
||||
"pt-BR/observability/overview",
|
||||
"pt-BR/observability/agentops",
|
||||
"pt-BR/observability/arize-phoenix",
|
||||
"pt-BR/observability/langfuse",
|
||||
"pt-BR/observability/langtrace",
|
||||
"pt-BR/observability/maxim",
|
||||
"pt-BR/observability/mlflow",
|
||||
"pt-BR/observability/openlit",
|
||||
"pt-BR/observability/opik",
|
||||
"pt-BR/observability/patronus-evaluation",
|
||||
"pt-BR/observability/portkey",
|
||||
"pt-BR/observability/weave"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Aprenda",
|
||||
"pages": [
|
||||
"pt-BR/learn/overview",
|
||||
"pt-BR/learn/llm-selection-guide",
|
||||
"pt-BR/learn/conditional-tasks",
|
||||
"pt-BR/learn/coding-agents",
|
||||
"pt-BR/learn/create-custom-tools",
|
||||
"pt-BR/learn/custom-llm",
|
||||
"pt-BR/learn/custom-manager-agent",
|
||||
"pt-BR/learn/customizing-agents",
|
||||
"pt-BR/learn/dalle-image-generation",
|
||||
"pt-BR/learn/force-tool-output-as-result",
|
||||
"pt-BR/learn/hierarchical-process",
|
||||
"pt-BR/learn/human-input-on-execution",
|
||||
"pt-BR/learn/kickoff-async",
|
||||
"pt-BR/learn/kickoff-for-each",
|
||||
"pt-BR/learn/llm-connections",
|
||||
"pt-BR/learn/multimodal-agents",
|
||||
"pt-BR/learn/replay-tasks-from-latest-crew-kickoff",
|
||||
"pt-BR/learn/sequential-process",
|
||||
"pt-BR/learn/using-annotations"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Telemetria",
|
||||
"pages": ["pt-BR/telemetry"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Enterprise",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Começando",
|
||||
"pages": ["pt-BR/enterprise/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "Funcionalidades",
|
||||
"pages": [
|
||||
"pt-BR/enterprise/features/tool-repository",
|
||||
"pt-BR/enterprise/features/webhook-streaming",
|
||||
"pt-BR/enterprise/features/traces",
|
||||
"pt-BR/enterprise/features/hallucination-guardrail",
|
||||
"pt-BR/enterprise/features/integrations"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Documentação de Integração",
|
||||
"pages": [
|
||||
"pt-BR/enterprise/integrations/asana",
|
||||
"pt-BR/enterprise/integrations/box",
|
||||
"pt-BR/enterprise/integrations/clickup",
|
||||
"pt-BR/enterprise/integrations/github",
|
||||
"pt-BR/enterprise/integrations/gmail",
|
||||
"pt-BR/enterprise/integrations/google_calendar",
|
||||
"pt-BR/enterprise/integrations/google_sheets",
|
||||
"pt-BR/enterprise/integrations/hubspot",
|
||||
"pt-BR/enterprise/integrations/jira",
|
||||
"pt-BR/enterprise/integrations/linear",
|
||||
"pt-BR/enterprise/integrations/notion",
|
||||
"pt-BR/enterprise/integrations/salesforce",
|
||||
"pt-BR/enterprise/integrations/shopify",
|
||||
"pt-BR/enterprise/integrations/slack",
|
||||
"pt-BR/enterprise/integrations/stripe",
|
||||
"pt-BR/enterprise/integrations/zendesk"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Guias",
|
||||
"pages": [
|
||||
"pt-BR/enterprise/guides/build-crew",
|
||||
"pt-BR/enterprise/guides/deploy-crew",
|
||||
"pt-BR/enterprise/guides/kickoff-crew",
|
||||
"pt-BR/enterprise/guides/update-crew",
|
||||
"pt-BR/enterprise/guides/enable-crew-studio",
|
||||
"pt-BR/enterprise/guides/azure-openai-setup",
|
||||
"pt-BR/enterprise/guides/hubspot-trigger",
|
||||
"pt-BR/enterprise/guides/react-component-export",
|
||||
"pt-BR/enterprise/guides/salesforce-trigger",
|
||||
"pt-BR/enterprise/guides/slack-trigger",
|
||||
"pt-BR/enterprise/guides/team-management",
|
||||
"pt-BR/enterprise/guides/webhook-automation",
|
||||
"pt-BR/enterprise/guides/human-in-the-loop",
|
||||
"pt-BR/enterprise/guides/zapier-trigger"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Recursos",
|
||||
"pages": [
|
||||
"pt-BR/enterprise/resources/frequently-asked-questions"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Referência da API",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Começando",
|
||||
"pages": ["pt-BR/api-reference/introduction"]
|
||||
},
|
||||
{
|
||||
"group": "Endpoints",
|
||||
"openapi": "enterprise-api.yaml"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Exemplos",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Exemplos",
|
||||
"pages": ["pt-BR/examples/example"]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"logo": {
|
||||
"light": "/images/crew_only_logo.png",
|
||||
"dark": "/images/crew_only_logo.png"
|
||||
},
|
||||
"appearance": {
|
||||
"default": "dark",
|
||||
"strict": false
|
||||
},
|
||||
"navbar": {
|
||||
"links": [
|
||||
{
|
||||
"label": "Start Cloud Trial",
|
||||
"href": "https://app.crewai.com"
|
||||
}
|
||||
],
|
||||
"primary": {
|
||||
"type": "github",
|
||||
"href": "https://github.com/crewAIInc/crewAI"
|
||||
}
|
||||
},
|
||||
"api": {
|
||||
"baseUrl": "https://your-actual-crew-name.crewai.com",
|
||||
"auth": {
|
||||
"method": "bearer",
|
||||
"name": "Authorization"
|
||||
},
|
||||
"playground": {
|
||||
"mode": "simple"
|
||||
}
|
||||
},
|
||||
"seo": {
|
||||
"indexing": "all"
|
||||
},
|
||||
"redirects": [
|
||||
{
|
||||
"source": "/introduction",
|
||||
"destination": "/en/introduction"
|
||||
},
|
||||
{
|
||||
"source": "/installation",
|
||||
"destination": "/en/installation"
|
||||
},
|
||||
{
|
||||
"source": "/quickstart",
|
||||
"destination": "/en/quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/changelog",
|
||||
"destination": "https://github.com/crewAIInc/crewAI/releases"
|
||||
},
|
||||
{
|
||||
"source": "/telemetry",
|
||||
"destination": "/en/telemetry"
|
||||
},
|
||||
{
|
||||
"source": "/concepts/:path*",
|
||||
"destination": "/en/concepts/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/guides/:path*",
|
||||
"destination": "/en/guides/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/tools/:path*",
|
||||
"destination": "/en/tools/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/learn/:path*",
|
||||
"destination": "/en/learn/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/mcp/:path*",
|
||||
"destination": "/en/mcp/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/observability/:path*",
|
||||
"destination": "/en/observability/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/enterprise/:path*",
|
||||
"destination": "/en/enterprise/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/:path*",
|
||||
"destination": "/en/api-reference/:path*"
|
||||
},
|
||||
{
|
||||
"source": "/examples/:path*",
|
||||
"destination": "/en/examples/:path*"
|
||||
}
|
||||
],
|
||||
"errors": {
|
||||
"404": {
|
||||
"redirect": true
|
||||
}
|
||||
},
|
||||
"footer": {
|
||||
"socials": {
|
||||
"website": "https://crewai.com",
|
||||
"x": "https://x.com/crewAIInc",
|
||||
"github": "https://github.com/crewAIInc/crewAI",
|
||||
"linkedin": "https://www.linkedin.com/company/crewai-inc",
|
||||
"youtube": "https://youtube.com/@crewAIInc",
|
||||
"reddit": "https://www.reddit.com/r/crewAIInc/"
|
||||
}
|
||||
}
|
||||
}
|
||||
119
docs/en/api-reference/introduction.mdx
Normal file
119
docs/en/api-reference/introduction.mdx
Normal file
@@ -0,0 +1,119 @@
|
||||
---
|
||||
title: "Introduction"
|
||||
description: "Complete reference for the CrewAI Enterprise REST API"
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
# CrewAI Enterprise API
|
||||
|
||||
Welcome to the CrewAI Enterprise API reference. This API allows you to programmatically interact with your deployed crews, enabling integration with your applications, workflows, and services.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Get Your API Credentials">
|
||||
Navigate to your crew's detail page in the CrewAI Enterprise dashboard and copy your Bearer Token from the Status tab.
|
||||
</Step>
|
||||
|
||||
<Step title="Discover Required Inputs">
|
||||
Use the `GET /inputs` endpoint to see what parameters your crew expects.
|
||||
</Step>
|
||||
|
||||
<Step title="Start a Crew Execution">
|
||||
Call `POST /kickoff` with your inputs to start the crew execution and receive a `kickoff_id`.
|
||||
</Step>
|
||||
|
||||
<Step title="Monitor Progress">
|
||||
Use `GET /status/{kickoff_id}` to check execution status and retrieve results.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Authentication
|
||||
|
||||
All API requests require authentication using a Bearer token. Include your token in the `Authorization` header:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" \
|
||||
https://your-crew-url.crewai.com/inputs
|
||||
```
|
||||
|
||||
### Token Types
|
||||
|
||||
| Token Type | Scope | Use Case |
|
||||
|:-----------|:--------|:----------|
|
||||
| **Bearer Token** | Organization-level access | Full crew operations, ideal for server-to-server integration |
|
||||
| **User Bearer Token** | User-scoped access | Limited permissions, suitable for user-specific operations |
|
||||
|
||||
<Tip>
|
||||
You can find both token types in the Status tab of your crew's detail page in the CrewAI Enterprise dashboard.
|
||||
</Tip>
|
||||
|
||||
## Base URL
|
||||
|
||||
Each deployed crew has its own unique API endpoint:
|
||||
|
||||
```
|
||||
https://your-crew-name.crewai.com
|
||||
```
|
||||
|
||||
Replace `your-crew-name` with your actual crew's URL from the dashboard.
|
||||
|
||||
## Typical Workflow
|
||||
|
||||
1. **Discovery**: Call `GET /inputs` to understand what your crew needs
|
||||
2. **Execution**: Submit inputs via `POST /kickoff` to start processing
|
||||
3. **Monitoring**: Poll `GET /status/{kickoff_id}` until completion
|
||||
4. **Results**: Extract the final output from the completed response
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes:
|
||||
|
||||
| Code | Meaning |
|
||||
|------|:--------|
|
||||
| `200` | Success |
|
||||
| `400` | Bad Request - Invalid input format |
|
||||
| `401` | Unauthorized - Invalid bearer token |
|
||||
| `404` | Not Found - Resource doesn't exist |
|
||||
| `422` | Validation Error - Missing required inputs |
|
||||
| `500` | Server Error - Contact support |
|
||||
|
||||
## Interactive Testing
|
||||
|
||||
<Info>
|
||||
**Why no "Send" button?** Since each CrewAI Enterprise user has their own unique crew URL, we use **reference mode** instead of an interactive playground to avoid confusion. This shows you exactly what the requests should look like without non-functional send buttons.
|
||||
</Info>
|
||||
|
||||
Each endpoint page shows you:
|
||||
- ✅ **Exact request format** with all parameters
|
||||
- ✅ **Response examples** for success and error cases
|
||||
- ✅ **Code samples** in multiple languages (cURL, Python, JavaScript, etc.)
|
||||
- ✅ **Authentication examples** with proper Bearer token format
|
||||
|
||||
### **To Test Your Actual API:**
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Copy cURL Examples" icon="terminal">
|
||||
Copy the cURL examples and replace the URL + token with your real values
|
||||
</Card>
|
||||
<Card title="Use Postman/Insomnia" icon="play">
|
||||
Import the examples into your preferred API testing tool
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Example workflow:**
|
||||
1. **Copy this cURL example** from any endpoint page
|
||||
2. **Replace `your-actual-crew-name.crewai.com`** with your real crew URL
|
||||
3. **Replace the Bearer token** with your real token from the dashboard
|
||||
4. **Run the request** in your terminal or API client
|
||||
|
||||
## Need Help?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Enterprise Support" icon="headset" href="mailto:support@crewai.com">
|
||||
Get help with API integration and troubleshooting
|
||||
</Card>
|
||||
<Card title="Enterprise Dashboard" icon="chart-line" href="https://app.crewai.com">
|
||||
Manage your crews and view execution logs
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -18,6 +18,18 @@ In the CrewAI framework, an `Agent` is an autonomous unit that can:
|
||||
Think of an agent as a specialized team member with specific skills, expertise, and responsibilities. For example, a `Researcher` agent might excel at gathering and analyzing information, while a `Writer` agent might be better at creating content.
|
||||
</Tip>
|
||||
|
||||
<Note type="info" title="Enterprise Enhancement: Visual Agent Builder">
|
||||
CrewAI Enterprise includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time.
|
||||
|
||||

|
||||
|
||||
The Visual Agent Builder enables:
|
||||
- Intuitive agent configuration with form-based interfaces
|
||||
- Real-time testing and validation
|
||||
- Template library with pre-configured agent types
|
||||
- Easy customization of agent attributes and behaviors
|
||||
</Note>
|
||||
|
||||
## Agent Attributes
|
||||
|
||||
| Attribute | Parameter | Type | Description |
|
||||
@@ -31,7 +43,6 @@ Think of an agent as a specialized team member with specific skills, expertise,
|
||||
| **Max Iterations** _(optional)_ | `max_iter` | `int` | Maximum iterations before the agent must provide its best answer. Default is 20. |
|
||||
| **Max RPM** _(optional)_ | `max_rpm` | `Optional[int]` | Maximum requests per minute to avoid rate limits. |
|
||||
| **Max Execution Time** _(optional)_ | `max_execution_time` | `Optional[int]` | Maximum time (in seconds) for task execution. |
|
||||
| **Memory** _(optional)_ | `memory` | `bool` | Whether the agent should maintain memory of interactions. Default is True. |
|
||||
| **Verbose** _(optional)_ | `verbose` | `bool` | Enable detailed execution logs for debugging. Default is False. |
|
||||
| **Allow Delegation** _(optional)_ | `allow_delegation` | `bool` | Allow the agent to delegate tasks to other agents. Default is False. |
|
||||
| **Step Callback** _(optional)_ | `step_callback` | `Optional[Any]` | Function called after each agent step, overrides crew callback. |
|
||||
@@ -43,7 +54,12 @@ Think of an agent as a specialized team member with specific skills, expertise,
|
||||
| **Max Retry Limit** _(optional)_ | `max_retry_limit` | `int` | Maximum number of retries when an error occurs. Default is 2. |
|
||||
| **Respect Context Window** _(optional)_ | `respect_context_window` | `bool` | Keep messages under context window size by summarizing. Default is True. |
|
||||
| **Code Execution Mode** _(optional)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | Mode for code execution: 'safe' (using Docker) or 'unsafe' (direct). Default is 'safe'. |
|
||||
| **Embedder Config** _(optional)_ | `embedder_config` | `Optional[Dict[str, Any]]` | Configuration for the embedder used by the agent. |
|
||||
| **Multimodal** _(optional)_ | `multimodal` | `bool` | Whether the agent supports multimodal capabilities. Default is False. |
|
||||
| **Inject Date** _(optional)_ | `inject_date` | `bool` | Whether to automatically inject the current date into tasks. Default is False. |
|
||||
| **Date Format** _(optional)_ | `date_format` | `str` | Format string for date when inject_date is enabled. Default is "%Y-%m-%d" (ISO format). |
|
||||
| **Reasoning** _(optional)_ | `reasoning` | `bool` | Whether the agent should reflect and create a plan before executing a task. Default is False. |
|
||||
| **Max Reasoning Attempts** _(optional)_ | `max_reasoning_attempts` | `Optional[int]` | Maximum number of reasoning attempts before executing the task. If None, will try until ready. |
|
||||
| **Embedder** _(optional)_ | `embedder` | `Optional[Dict[str, Any]]` | Configuration for the embedder used by the agent. |
|
||||
| **Knowledge Sources** _(optional)_ | `knowledge_sources` | `Optional[List[BaseKnowledgeSource]]` | Knowledge sources available to the agent. |
|
||||
| **Use System Prompt** _(optional)_ | `use_system_prompt` | `Optional[bool]` | Whether to use system prompt (for o1 model support). Default is True. |
|
||||
|
||||
@@ -55,7 +71,7 @@ There are two ways to create agents in CrewAI: using **YAML configuration (recom
|
||||
|
||||
Using YAML configuration provides a cleaner, more maintainable way to define agents. We strongly recommend using this approach in your CrewAI projects.
|
||||
|
||||
After creating your CrewAI project as outlined in the [Installation](/installation) section, navigate to the `src/latest_ai_development/config/agents.yaml` file and modify the template to match your requirements.
|
||||
After creating your CrewAI project as outlined in the [Installation](/en/installation) section, navigate to the `src/latest_ai_development/config/agents.yaml` file and modify the template to match your requirements.
|
||||
|
||||
<Note>
|
||||
Variables in your YAML files (like `{topic}`) will be replaced with values from your inputs when running the crew:
|
||||
@@ -106,7 +122,7 @@ class LatestAiDevelopmentCrew():
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'],
|
||||
config=self.agents_config['researcher'], # type: ignore[index]
|
||||
verbose=True,
|
||||
tools=[SerperDevTool()]
|
||||
)
|
||||
@@ -114,7 +130,7 @@ class LatestAiDevelopmentCrew():
|
||||
@agent
|
||||
def reporting_analyst(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['reporting_analyst'],
|
||||
config=self.agents_config['reporting_analyst'], # type: ignore[index]
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
@@ -139,7 +155,6 @@ agent = Agent(
|
||||
"you excel at finding patterns in complex datasets.",
|
||||
llm="gpt-4", # Default: OPENAI_MODEL_NAME or "gpt-4"
|
||||
function_calling_llm=None, # Optional: Separate LLM for tool calling
|
||||
memory=True, # Default: True
|
||||
verbose=False, # Default: False
|
||||
allow_delegation=False, # Default: False
|
||||
max_iter=20, # Default: 20 iterations
|
||||
@@ -150,9 +165,14 @@ agent = Agent(
|
||||
code_execution_mode="safe", # Default: "safe" (options: "safe", "unsafe")
|
||||
respect_context_window=True, # Default: True
|
||||
use_system_prompt=True, # Default: True
|
||||
multimodal=False, # Default: False
|
||||
inject_date=False, # Default: False
|
||||
date_format="%Y-%m-%d", # Default: ISO format
|
||||
reasoning=False, # Default: False
|
||||
max_reasoning_attempts=None, # Default: None
|
||||
tools=[SerperDevTool()], # Optional: List of tools
|
||||
knowledge_sources=None, # Optional: List of knowledge sources
|
||||
embedder_config=None, # Optional: Custom embedder configuration
|
||||
embedder=None, # Optional: Custom embedder configuration
|
||||
system_template=None, # Optional: Custom system prompt template
|
||||
prompt_template=None, # Optional: Custom prompt template
|
||||
response_template=None, # Optional: Custom response template
|
||||
@@ -214,6 +234,44 @@ custom_agent = Agent(
|
||||
)
|
||||
```
|
||||
|
||||
#### Date-Aware Agent with Reasoning
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
#### Multimodal Agent
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
### Parameter Details
|
||||
|
||||
#### Critical Parameters
|
||||
@@ -233,17 +291,31 @@ custom_agent = Agent(
|
||||
|
||||
#### Code Execution
|
||||
- `allow_code_execution`: Must be True to run code
|
||||
- `code_execution_mode`:
|
||||
- `code_execution_mode`:
|
||||
- `"safe"`: Uses Docker (recommended for production)
|
||||
- `"unsafe"`: Direct execution (use only in trusted environments)
|
||||
|
||||
<Note>
|
||||
This runs a default Docker image. If you want to configure the docker image, the checkout the Code Interpreter Tool in the tools section.
|
||||
Add the code interpreter tool as a tool in the agent as a tool parameter.
|
||||
</Note>
|
||||
|
||||
#### Advanced Features
|
||||
- `multimodal`: Enable multimodal capabilities for processing text and visual content
|
||||
- `reasoning`: Enable agent to reflect and create plans before executing tasks
|
||||
- `inject_date`: Automatically inject current date into task descriptions
|
||||
|
||||
#### Templates
|
||||
- `system_template`: Defines agent's core behavior
|
||||
- `prompt_template`: Structures input format
|
||||
- `response_template`: Formats agent responses
|
||||
|
||||
<Note>
|
||||
When using custom templates, you can use variables like `{role}`, `{goal}`, and `{input}` in your templates. These will be automatically populated during execution.
|
||||
When using custom templates, ensure that both `system_template` and `prompt_template` are defined. The `response_template` is optional but recommended for consistent output formatting.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
When using custom templates, you can use variables like `{role}`, `{goal}`, and `{backstory}` in your templates. These will be automatically populated during execution.
|
||||
</Note>
|
||||
|
||||
## Agent Tools
|
||||
@@ -290,6 +362,267 @@ analyst = Agent(
|
||||
When `memory` is enabled, the agent will maintain context across multiple interactions, improving its ability to handle complex, multi-step tasks.
|
||||
</Note>
|
||||
|
||||
## Context Window Management
|
||||
|
||||
CrewAI includes sophisticated automatic context window management to handle situations where conversations exceed the language model's token limits. This powerful feature is controlled by the `respect_context_window` parameter.
|
||||
|
||||
### How Context Window Management Works
|
||||
|
||||
When an agent's conversation history grows too large for the LLM's context window, CrewAI automatically detects this situation and can either:
|
||||
|
||||
1. **Automatically summarize content** (when `respect_context_window=True`)
|
||||
2. **Stop execution with an error** (when `respect_context_window=False`)
|
||||
|
||||
### Automatic Context Handling (`respect_context_window=True`)
|
||||
|
||||
This is the **default and recommended setting** for most use cases. When enabled, CrewAI will:
|
||||
|
||||
```python Code
|
||||
# Agent with automatic context management (default)
|
||||
smart_agent = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Analyze large documents and datasets",
|
||||
backstory="Expert at processing extensive information",
|
||||
respect_context_window=True, # 🔑 Default: auto-handle context limits
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
**What happens when context limits are exceeded:**
|
||||
- ⚠️ **Warning message**: `"Context length exceeded. Summarizing content to fit the model context window."`
|
||||
- 🔄 **Automatic summarization**: CrewAI intelligently summarizes the conversation history
|
||||
- ✅ **Continued execution**: Task execution continues seamlessly with the summarized context
|
||||
- 📝 **Preserved information**: Key information is retained while reducing token count
|
||||
|
||||
### Strict Context Limits (`respect_context_window=False`)
|
||||
|
||||
When you need precise control and prefer execution to stop rather than lose any information:
|
||||
|
||||
```python Code
|
||||
# Agent with strict context limits
|
||||
strict_agent = Agent(
|
||||
role="Legal Document Reviewer",
|
||||
goal="Provide precise legal analysis without information loss",
|
||||
backstory="Legal expert requiring complete context for accurate analysis",
|
||||
respect_context_window=False, # ❌ Stop execution on context limit
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
**What happens when context limits are exceeded:**
|
||||
- ❌ **Error message**: `"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."`
|
||||
- 🛑 **Execution stops**: Task execution halts immediately
|
||||
- 🔧 **Manual intervention required**: You need to modify your approach
|
||||
|
||||
### Choosing the Right Setting
|
||||
|
||||
#### Use `respect_context_window=True` (Default) when:
|
||||
- **Processing large documents** that might exceed context limits
|
||||
- **Long-running conversations** where some summarization is acceptable
|
||||
- **Research tasks** where general context is more important than exact details
|
||||
- **Prototyping and development** where you want robust execution
|
||||
|
||||
```python Code
|
||||
# Perfect for document processing
|
||||
document_processor = Agent(
|
||||
role="Document Analyst",
|
||||
goal="Extract insights from large research papers",
|
||||
backstory="Expert at analyzing extensive documentation",
|
||||
respect_context_window=True, # Handle large documents gracefully
|
||||
max_iter=50, # Allow more iterations for complex analysis
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
#### Use `respect_context_window=False` when:
|
||||
- **Precision is critical** and information loss is unacceptable
|
||||
- **Legal or medical tasks** requiring complete context
|
||||
- **Code review** where missing details could introduce bugs
|
||||
- **Financial analysis** where accuracy is paramount
|
||||
|
||||
```python Code
|
||||
# Perfect for precision tasks
|
||||
precision_agent = Agent(
|
||||
role="Code Security Auditor",
|
||||
goal="Identify security vulnerabilities in code",
|
||||
backstory="Security expert requiring complete code context",
|
||||
respect_context_window=False, # Prefer failure over incomplete analysis
|
||||
max_retry_limit=1, # Fail fast on context issues
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
### Alternative Approaches for Large Data
|
||||
|
||||
When dealing with very large datasets, consider these strategies:
|
||||
|
||||
#### 1. Use RAG Tools
|
||||
```python Code
|
||||
from crewai_tools import RagTool
|
||||
|
||||
# Create RAG tool for large document processing
|
||||
rag_tool = RagTool()
|
||||
|
||||
rag_agent = Agent(
|
||||
role="Research Assistant",
|
||||
goal="Query large knowledge bases efficiently",
|
||||
backstory="Expert at using RAG tools for information retrieval",
|
||||
tools=[rag_tool], # Use RAG instead of large context windows
|
||||
respect_context_window=True,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
#### 2. Use Knowledge Sources
|
||||
```python Code
|
||||
# Use knowledge sources instead of large prompts
|
||||
knowledge_agent = Agent(
|
||||
role="Knowledge Expert",
|
||||
goal="Answer questions using curated knowledge",
|
||||
backstory="Expert at leveraging structured knowledge sources",
|
||||
knowledge_sources=[your_knowledge_sources], # Pre-processed knowledge
|
||||
respect_context_window=True,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
### Context Window Best Practices
|
||||
|
||||
1. **Monitor Context Usage**: Enable `verbose=True` to see context management in action
|
||||
2. **Design for Efficiency**: Structure tasks to minimize context accumulation
|
||||
3. **Use Appropriate Models**: Choose LLMs with context windows suitable for your tasks
|
||||
4. **Test Both Settings**: Try both `True` and `False` to see which works better for your use case
|
||||
5. **Combine with RAG**: Use RAG tools for very large datasets instead of relying solely on context windows
|
||||
|
||||
### Troubleshooting Context Issues
|
||||
|
||||
**If you're getting context limit errors:**
|
||||
```python Code
|
||||
# Quick fix: Enable automatic handling
|
||||
agent.respect_context_window = True
|
||||
|
||||
# Better solution: Use RAG tools for large data
|
||||
from crewai_tools import RagTool
|
||||
agent.tools = [RagTool()]
|
||||
|
||||
# Alternative: Break tasks into smaller pieces
|
||||
# Or use knowledge sources instead of large prompts
|
||||
```
|
||||
|
||||
**If automatic summarization loses important information:**
|
||||
```python Code
|
||||
# Disable auto-summarization and use RAG instead
|
||||
agent = Agent(
|
||||
role="Detailed Analyst",
|
||||
goal="Maintain complete information accuracy",
|
||||
backstory="Expert requiring full context",
|
||||
respect_context_window=False, # No summarization
|
||||
tools=[RagTool()], # Use RAG for large data
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
<Note>
|
||||
The context window management feature works automatically in the background. You don't need to call any special functions - just set `respect_context_window` to your preferred behavior and CrewAI handles the rest!
|
||||
</Note>
|
||||
|
||||
## Direct Agent Interaction with `kickoff()`
|
||||
|
||||
Agents can be used directly without going through a task or crew workflow using the `kickoff()` method. This provides a simpler way to interact with an agent when you don't need the full crew orchestration capabilities.
|
||||
|
||||
### How `kickoff()` Works
|
||||
|
||||
The `kickoff()` method allows you to send messages directly to an agent and get a response, similar to how you would interact with an LLM but with all the agent's capabilities (tools, reasoning, etc.).
|
||||
|
||||
```python Code
|
||||
from crewai import Agent
|
||||
from crewai_tools import SerperDevTool
|
||||
|
||||
# Create an agent
|
||||
researcher = Agent(
|
||||
role="AI Technology Researcher",
|
||||
goal="Research the latest AI developments",
|
||||
tools=[SerperDevTool()],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Use kickoff() to interact directly with the agent
|
||||
result = researcher.kickoff("What are the latest developments in language models?")
|
||||
|
||||
# Access the raw response
|
||||
print(result.raw)
|
||||
```
|
||||
|
||||
### Parameters and Return Values
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| :---------------- | :---------------------------------- | :------------------------------------------------------------------------ |
|
||||
| `messages` | `Union[str, List[Dict[str, str]]]` | Either a string query or a list of message dictionaries with role/content |
|
||||
| `response_format` | `Optional[Type[Any]]` | Optional Pydantic model for structured output |
|
||||
|
||||
The method returns a `LiteAgentOutput` object with the following properties:
|
||||
|
||||
- `raw`: String containing the raw output text
|
||||
- `pydantic`: Parsed Pydantic model (if a `response_format` was provided)
|
||||
- `agent_role`: Role of the agent that produced the output
|
||||
- `usage_metrics`: Token usage metrics for the execution
|
||||
|
||||
### Structured Output
|
||||
|
||||
You can get structured output by providing a Pydantic model as the `response_format`:
|
||||
|
||||
```python Code
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
|
||||
class ResearchFindings(BaseModel):
|
||||
main_points: List[str]
|
||||
key_technologies: List[str]
|
||||
future_predictions: str
|
||||
|
||||
# Get structured output
|
||||
result = researcher.kickoff(
|
||||
"Summarize the latest developments in AI for 2025",
|
||||
response_format=ResearchFindings
|
||||
)
|
||||
|
||||
# Access structured data
|
||||
print(result.pydantic.main_points)
|
||||
print(result.pydantic.future_predictions)
|
||||
```
|
||||
|
||||
### Multiple Messages
|
||||
|
||||
You can also provide a conversation history as a list of message dictionaries:
|
||||
|
||||
```python Code
|
||||
messages = [
|
||||
{"role": "user", "content": "I need information about large language models"},
|
||||
{"role": "assistant", "content": "I'd be happy to help with that! What specifically would you like to know?"},
|
||||
{"role": "user", "content": "What are the latest developments in 2025?"}
|
||||
]
|
||||
|
||||
result = researcher.kickoff(messages)
|
||||
```
|
||||
|
||||
### Async Support
|
||||
|
||||
An asynchronous version is available via `kickoff_async()` with the same parameters:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
async def main():
|
||||
result = await researcher.kickoff_async("What are the latest developments in AI?")
|
||||
print(result.raw)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
<Note>
|
||||
The `kickoff()` method uses a `LiteAgent` internally, which provides a simpler execution flow while preserving all of the agent's configuration (role, goal, backstory, tools, etc.).
|
||||
</Note>
|
||||
|
||||
## Important Considerations and Best Practices
|
||||
|
||||
### Security and Code Execution
|
||||
@@ -304,11 +637,17 @@ When `memory` is enabled, the agent will maintain context across multiple intera
|
||||
- Adjust `max_iter` and `max_retry_limit` based on task complexity
|
||||
|
||||
### Memory and Context Management
|
||||
- Use `memory: true` for tasks requiring historical context
|
||||
- Leverage `knowledge_sources` for domain-specific information
|
||||
- Configure `embedder_config` when using custom embedding models
|
||||
- Configure `embedder` when using custom embedding models
|
||||
- Use custom templates (`system_template`, `prompt_template`, `response_template`) for fine-grained control over agent behavior
|
||||
|
||||
### Advanced Features
|
||||
- Enable `reasoning: true` for agents that need to plan and reflect before executing complex tasks
|
||||
- Set appropriate `max_reasoning_attempts` to control planning iterations (None for unlimited attempts)
|
||||
- Use `inject_date: true` to provide agents with current date awareness for time-sensitive tasks
|
||||
- Customize the date format with `date_format` using standard Python datetime format codes
|
||||
- Enable `multimodal: true` for agents that need to process both text and visual content
|
||||
|
||||
### Agent Collaboration
|
||||
- Enable `allow_delegation: true` when agents need to work together
|
||||
- Use `step_callback` to monitor and log agent interactions
|
||||
@@ -316,6 +655,13 @@ When `memory` is enabled, the agent will maintain context across multiple intera
|
||||
- Main `llm` for complex reasoning
|
||||
- `function_calling_llm` for efficient tool usage
|
||||
|
||||
### Date Awareness and Reasoning
|
||||
- Use `inject_date: true` to provide agents with current date awareness for time-sensitive tasks
|
||||
- Customize the date format with `date_format` using standard Python datetime format codes
|
||||
- Valid format codes include: %Y (year), %m (month), %d (day), %B (full month name), etc.
|
||||
- Invalid date formats will be logged as warnings and will not modify the task description
|
||||
- Enable `reasoning: true` for complex tasks that benefit from upfront planning and reflection
|
||||
|
||||
### Model Compatibility
|
||||
- Set `use_system_prompt: false` for older models that don't support system messages
|
||||
- Ensure your chosen `llm` supports the features you need (like function calling)
|
||||
@@ -338,7 +684,6 @@ When `memory` is enabled, the agent will maintain context across multiple intera
|
||||
- Review code sandbox settings
|
||||
|
||||
4. **Memory Issues**: If agent responses seem inconsistent:
|
||||
- Verify memory is enabled
|
||||
- Check knowledge source configuration
|
||||
- Review conversation history management
|
||||
|
||||
311
docs/en/concepts/cli.mdx
Normal file
311
docs/en/concepts/cli.mdx
Normal file
@@ -0,0 +1,311 @@
|
||||
---
|
||||
title: CLI
|
||||
description: Learn how to use the CrewAI CLI to interact with CrewAI.
|
||||
icon: terminal
|
||||
---
|
||||
|
||||
<Warning>Since release 0.140.0, CrewAI Enterprise started a process of migrating their login provider. As such, the authentication flow via CLI was updated. Users that use Google to login, or that created their account after July 3rd, 2025 will be unable to log in with older versions of the `crewai` library.</Warning>
|
||||
|
||||
## Overview
|
||||
|
||||
The CrewAI CLI provides a set of commands to interact with CrewAI, allowing you to create, train, run, and manage crews & flows.
|
||||
|
||||
## Installation
|
||||
|
||||
To use the CrewAI CLI, make sure you have CrewAI installed:
|
||||
|
||||
```shell Terminal
|
||||
pip install crewai
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
The basic structure of a CrewAI CLI command is:
|
||||
|
||||
```shell Terminal
|
||||
crewai [COMMAND] [OPTIONS] [ARGUMENTS]
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
### 1. Create
|
||||
|
||||
Create a new crew or flow.
|
||||
|
||||
```shell Terminal
|
||||
crewai create [OPTIONS] TYPE NAME
|
||||
```
|
||||
|
||||
- `TYPE`: Choose between "crew" or "flow"
|
||||
- `NAME`: Name of the crew or flow
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
crewai create crew my_new_crew
|
||||
crewai create flow my_new_flow
|
||||
```
|
||||
|
||||
### 2. Version
|
||||
|
||||
Show the installed version of CrewAI.
|
||||
|
||||
```shell Terminal
|
||||
crewai version [OPTIONS]
|
||||
```
|
||||
|
||||
- `--tools`: (Optional) Show the installed version of CrewAI tools
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
crewai version
|
||||
crewai version --tools
|
||||
```
|
||||
|
||||
### 3. Train
|
||||
|
||||
Train the crew for a specified number of iterations.
|
||||
|
||||
```shell Terminal
|
||||
crewai train [OPTIONS]
|
||||
```
|
||||
|
||||
- `-n, --n_iterations INTEGER`: Number of iterations to train the crew (default: 5)
|
||||
- `-f, --filename TEXT`: Path to a custom file for training (default: "trained_agents_data.pkl")
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
crewai train -n 10 -f my_training_data.pkl
|
||||
```
|
||||
|
||||
### 4. Replay
|
||||
|
||||
Replay the crew execution from a specific task.
|
||||
|
||||
```shell Terminal
|
||||
crewai replay [OPTIONS]
|
||||
```
|
||||
|
||||
- `-t, --task_id TEXT`: Replay the crew from this task ID, including all subsequent tasks
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
crewai replay -t task_123456
|
||||
```
|
||||
|
||||
### 5. Log-tasks-outputs
|
||||
|
||||
Retrieve your latest crew.kickoff() task outputs.
|
||||
|
||||
```shell Terminal
|
||||
crewai log-tasks-outputs
|
||||
```
|
||||
|
||||
### 6. Reset-memories
|
||||
|
||||
Reset the crew memories (long, short, entity, latest_crew_kickoff_outputs).
|
||||
|
||||
```shell Terminal
|
||||
crewai reset-memories [OPTIONS]
|
||||
```
|
||||
|
||||
- `-l, --long`: Reset LONG TERM memory
|
||||
- `-s, --short`: Reset SHORT TERM memory
|
||||
- `-e, --entities`: Reset ENTITIES memory
|
||||
- `-k, --kickoff-outputs`: Reset LATEST KICKOFF TASK OUTPUTS
|
||||
- `-kn, --knowledge`: Reset KNOWLEDGE storage
|
||||
- `-akn, --agent-knowledge`: Reset AGENT KNOWLEDGE storage
|
||||
- `-a, --all`: Reset ALL memories
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
crewai reset-memories --long --short
|
||||
crewai reset-memories --all
|
||||
```
|
||||
|
||||
### 7. Test
|
||||
|
||||
Test the crew and evaluate the results.
|
||||
|
||||
```shell Terminal
|
||||
crewai test [OPTIONS]
|
||||
```
|
||||
|
||||
- `-n, --n_iterations INTEGER`: Number of iterations to test the crew (default: 3)
|
||||
- `-m, --model TEXT`: LLM Model to run the tests on the Crew (default: "gpt-4o-mini")
|
||||
|
||||
Example:
|
||||
```shell Terminal
|
||||
crewai test -n 5 -m gpt-3.5-turbo
|
||||
```
|
||||
|
||||
### 8. Run
|
||||
|
||||
Run the crew or flow.
|
||||
|
||||
```shell Terminal
|
||||
crewai run
|
||||
```
|
||||
|
||||
<Note>
|
||||
Starting from version 0.103.0, the `crewai run` command can be used to run both standard crews and flows. For flows, it automatically detects the type from pyproject.toml and runs the appropriate command. This is now the recommended way to run both crews and flows.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
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>
|
||||
|
||||
### 9. Chat
|
||||
|
||||
Starting in version `0.98.0`, when you run the `crewai chat` command, you start an interactive session with your crew. The AI assistant will guide you by asking for necessary inputs to execute the crew. Once all inputs are provided, the crew will execute its tasks.
|
||||
|
||||
After receiving the results, you can continue interacting with the assistant for further instructions or questions.
|
||||
|
||||
```shell Terminal
|
||||
crewai chat
|
||||
```
|
||||
<Note>
|
||||
Ensure you execute these commands from your CrewAI project's root directory.
|
||||
</Note>
|
||||
<Note>
|
||||
IMPORTANT: Set the `chat_llm` property in your `crew.py` file to enable this command.
|
||||
|
||||
```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. Deploy
|
||||
|
||||
Deploy the crew or flow to [CrewAI Enterprise](https://app.crewai.com).
|
||||
|
||||
- **Authentication**: You need to be authenticated to deploy to CrewAI Enterprise.
|
||||
You can login or create an account with:
|
||||
```shell Terminal
|
||||
crewai login
|
||||
```
|
||||
|
||||
- **Create a deployment**: Once you are authenticated, you can create a deployment for your crew or flow from the root of your localproject.
|
||||
```shell Terminal
|
||||
crewai deploy create
|
||||
```
|
||||
- Reads your local project configuration.
|
||||
- Prompts you to confirm the environment variables (like `OPENAI_API_KEY`, `SERPER_API_KEY`) found locally. These will be securely stored with the deployment on the Enterprise platform. Ensure your sensitive keys are correctly configured locally (e.g., in a `.env` file) before running this.
|
||||
|
||||
### 11. Organization Management
|
||||
|
||||
Manage your CrewAI Enterprise organizations.
|
||||
|
||||
```shell Terminal
|
||||
crewai org [COMMAND] [OPTIONS]
|
||||
```
|
||||
|
||||
#### Commands:
|
||||
|
||||
- `list`: List all organizations you belong to
|
||||
```shell Terminal
|
||||
crewai org list
|
||||
```
|
||||
|
||||
- `current`: Display your currently active organization
|
||||
```shell Terminal
|
||||
crewai org current
|
||||
```
|
||||
|
||||
- `switch`: Switch to a specific organization
|
||||
```shell Terminal
|
||||
crewai org switch <organization_id>
|
||||
```
|
||||
|
||||
<Note>
|
||||
You must be authenticated to CrewAI Enterprise to use these organization management commands.
|
||||
</Note>
|
||||
|
||||
- **Create a deployment** (continued):
|
||||
- Links the deployment to the corresponding remote GitHub repository (it usually detects this automatically).
|
||||
|
||||
- **Deploy the Crew**: Once you are authenticated, you can deploy your crew or flow to CrewAI 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).
|
||||
|
||||
- **Deployment Status**: You can check the status of your deployment with:
|
||||
```shell Terminal
|
||||
crewai deploy status
|
||||
```
|
||||
This fetches the latest deployment status of your most recent deployment attempt (e.g., `Building Images for Crew`, `Deploy Enqueued`, `Online`).
|
||||
|
||||
- **Deployment Logs**: You can check the logs of your deployment with:
|
||||
```shell Terminal
|
||||
crewai deploy logs
|
||||
```
|
||||
This streams the deployment logs to your terminal.
|
||||
|
||||
- **List deployments**: You can list all your deployments with:
|
||||
```shell Terminal
|
||||
crewai deploy list
|
||||
```
|
||||
This lists all your deployments.
|
||||
|
||||
- **Delete a deployment**: You can delete a deployment with:
|
||||
```shell Terminal
|
||||
crewai deploy remove
|
||||
```
|
||||
This deletes the deployment from the CrewAI Enterprise platform.
|
||||
|
||||
- **Help Command**: You can get help with the CLI with:
|
||||
```shell Terminal
|
||||
crewai deploy --help
|
||||
```
|
||||
This shows the help message for the CrewAI Deploy CLI.
|
||||
|
||||
Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI Enterprise](http://app.crewai.com) using the CLI.
|
||||
|
||||
<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 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.
|
||||
|
||||
Once you've selected an LLM provider and model, you will be prompted for API keys.
|
||||
|
||||
#### Available LLM Providers
|
||||
|
||||
Here's a list of the most popular LLM providers suggested by the CLI:
|
||||
|
||||
* OpenAI
|
||||
* Groq
|
||||
* Anthropic
|
||||
* Google Gemini
|
||||
* SambaNova
|
||||
|
||||
When you select a provider, the CLI will then show you available models for that provider and prompt you to enter your API key.
|
||||
|
||||
#### Other Options
|
||||
|
||||
If you select "other", you will be able to select from a list of LiteLLM supported providers.
|
||||
|
||||
When you select a provider, the CLI will prompt you to enter the Key name and the API key.
|
||||
|
||||
See the following link for each provider's key name:
|
||||
|
||||
* [LiteLLM Providers](https://docs.litellm.ai/docs/providers)
|
||||
362
docs/en/concepts/collaboration.mdx
Normal file
362
docs/en/concepts/collaboration.mdx
Normal file
@@ -0,0 +1,362 @@
|
||||
---
|
||||
title: Collaboration
|
||||
description: How to enable agents to work together, delegate tasks, and communicate effectively within CrewAI teams.
|
||||
icon: screen-users
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Collaboration in CrewAI enables agents to work together as a team by delegating tasks and asking questions to leverage each other's expertise. When `allow_delegation=True`, agents automatically gain access to powerful collaboration tools.
|
||||
|
||||
## Quick Start: Enable Collaboration
|
||||
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
## How Agent Collaboration Works
|
||||
|
||||
When `allow_delegation=True`, CrewAI automatically provides agents with two powerful tools:
|
||||
|
||||
### 1. **Delegate Work Tool**
|
||||
Allows agents to assign tasks to teammates with specific expertise.
|
||||
|
||||
```python
|
||||
# Agent automatically gets this tool:
|
||||
# Delegate work to coworker(task: str, context: str, coworker: str)
|
||||
```
|
||||
|
||||
### 2. **Ask Question Tool**
|
||||
Enables agents to ask specific questions to gather information from colleagues.
|
||||
|
||||
```python
|
||||
# Agent automatically gets this tool:
|
||||
# Ask question to coworker(question: str, context: str, coworker: str)
|
||||
```
|
||||
|
||||
## Collaboration in Action
|
||||
|
||||
Here's a complete example showing agents collaborating on a content creation task:
|
||||
|
||||
```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()
|
||||
```
|
||||
|
||||
## Collaboration Patterns
|
||||
|
||||
### Pattern 1: Research → Write → Edit
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
### Pattern 2: Collaborative Single Task
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
## Hierarchical Collaboration
|
||||
|
||||
For complex projects, use a hierarchical process with a manager agent:
|
||||
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
## Best Practices for Collaboration
|
||||
|
||||
### 1. **Clear Role Definition**
|
||||
```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. **Strategic Delegation Enabling**
|
||||
```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. **Context Sharing**
|
||||
```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. **Clear Task Descriptions**
|
||||
```python
|
||||
# ✅ Specific, actionable descriptions
|
||||
Task(
|
||||
description="""Research competitors in the AI chatbot space.
|
||||
Focus on: pricing models, key features, target markets.
|
||||
Provide data in a structured format.""",
|
||||
...
|
||||
)
|
||||
|
||||
# ❌ Vague descriptions that don't guide collaboration
|
||||
Task(description="Do some research about chatbots", ...)
|
||||
```
|
||||
|
||||
## Troubleshooting Collaboration
|
||||
|
||||
### Issue: Agents Not Collaborating
|
||||
**Symptoms:** Agents work in isolation, no delegation occurs
|
||||
```python
|
||||
# ✅ Solution: Ensure delegation is enabled
|
||||
agent = Agent(
|
||||
role="...",
|
||||
allow_delegation=True, # This is required!
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### Issue: Too Much Back-and-Forth
|
||||
**Symptoms:** Agents ask excessive questions, slow progress
|
||||
```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.""",
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### Issue: Delegation Loops
|
||||
**Symptoms:** Agents delegate back and forth indefinitely
|
||||
```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)
|
||||
```
|
||||
|
||||
## Advanced Collaboration Features
|
||||
|
||||
### Custom Collaboration Rules
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
### Monitoring Collaboration
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
## Memory and Learning
|
||||
|
||||
Enable agents to remember past collaborations:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Content Lead",
|
||||
memory=True, # Remembers past interactions
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
With memory enabled, agents learn from previous collaborations and improve their delegation decisions over time.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **Try the examples**: Start with the basic collaboration example
|
||||
- **Experiment with roles**: Test different agent role combinations
|
||||
- **Monitor interactions**: Use `verbose=True` to see collaboration in action
|
||||
- **Optimize task descriptions**: Clear tasks lead to better collaboration
|
||||
- **Scale up**: Try hierarchical processes for complex projects
|
||||
|
||||
Collaboration transforms individual AI agents into powerful teams that can tackle complex, multi-faceted challenges together.
|
||||
@@ -4,7 +4,7 @@ description: Understanding and utilizing crews in the crewAI framework with comp
|
||||
icon: people-group
|
||||
---
|
||||
|
||||
## What is a Crew?
|
||||
## Overview
|
||||
|
||||
A crew in crewAI represents a collaborative group of agents working together to achieve a set of tasks. Each crew defines the strategy for task execution, agent collaboration, and the overall workflow.
|
||||
|
||||
@@ -20,21 +20,19 @@ 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`. |
|
||||
| **Language** _(optional)_ | `language` | Language used for the crew, defaults to English. |
|
||||
| **Language File** _(optional)_ | `language_file` | Path to the language file to be used for the crew. |
|
||||
| **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. |
|
||||
| **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"}`. |
|
||||
| **Full Output** _(optional)_ | `full_output` | Whether the crew should return the full output with all tasks outputs or just the final output. Defaults to `False`. |
|
||||
| **Memory Config** _(optional)_ | `memory_config` | Configuration for the memory provider to be used by the crew. |
|
||||
| **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`. |
|
||||
| **Task Callback** _(optional)_ | `task_callback` | A function that is called after the completion of each task. Useful for monitoring or additional operations post-task execution. |
|
||||
| **Share Crew** _(optional)_ | `share_crew` | Whether you want to share the complete crew information and execution with the crewAI team to make the library better, and allow us to train models. |
|
||||
| **Output Log File** _(optional)_ | `output_log_file` | Whether you want to have a file with the complete crew output and execution. You can set it using True and it will default to the folder you are currently in and it will be called logs.txt or passing a string with the full path and name of the file. |
|
||||
| **Output Log File** _(optional)_ | `output_log_file` | Set to True to save logs as logs.txt in the current directory or provide a file path. Logs will be in JSON format if the filename ends in .json, otherwise .txt. Defaults to `None`. |
|
||||
| **Manager Agent** _(optional)_ | `manager_agent` | `manager` sets a custom agent that will be used as a manager. |
|
||||
| **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.
|
||||
@@ -48,25 +46,29 @@ There are two ways to create crews in CrewAI: using **YAML configuration (recomm
|
||||
|
||||
Using YAML configuration provides a cleaner, more maintainable way to define crews and is consistent with how agents and tasks are defined in CrewAI projects.
|
||||
|
||||
After creating your CrewAI project as outlined in the [Installation](/installation) section, you can define your crew in a class that inherits from `CrewBase` and uses decorators to define agents, tasks, and the crew itself.
|
||||
After creating your CrewAI project as outlined in the [Installation](/en/installation) section, you can define your crew in a class that inherits from `CrewBase` and uses decorators to define agents, tasks, and the crew itself.
|
||||
|
||||
#### Example Crew Class with Decorators
|
||||
|
||||
```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]
|
||||
|
||||
# Paths to your YAML configuration files
|
||||
# To see an example agent and task defined in YAML, checkout the following:
|
||||
# - 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'
|
||||
agents_config = 'config/agents.yaml'
|
||||
tasks_config = 'config/tasks.yaml'
|
||||
|
||||
@before_kickoff
|
||||
def prepare_inputs(self, inputs):
|
||||
@@ -83,39 +85,45 @@ class YourCrewName:
|
||||
@agent
|
||||
def agent_one(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['agent_one'],
|
||||
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'],
|
||||
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']
|
||||
config=self.tasks_config['task_one'] # type: ignore[index]
|
||||
)
|
||||
|
||||
@task
|
||||
def task_two(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['task_two']
|
||||
config=self.tasks_config['task_two'] # type: ignore[index]
|
||||
)
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents, # Automatically collected by the @agent decorator
|
||||
tasks=self.tasks, # Automatically collected by the @task decorator.
|
||||
tasks=self.tasks, # Automatically collected by the @task decorator.
|
||||
process=Process.sequential,
|
||||
verbose=True,
|
||||
)
|
||||
```
|
||||
|
||||
How to run the above code:
|
||||
|
||||
```python code
|
||||
YourCrewName().crew().kickoff(inputs={"any": "input here"})
|
||||
```
|
||||
|
||||
<Note>
|
||||
Tasks will be executed in the order they are defined.
|
||||
</Note>
|
||||
@@ -183,6 +191,11 @@ class YourCrewName:
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
How to run the above code:
|
||||
|
||||
```python code
|
||||
YourCrewName().crew().kickoff(inputs={})
|
||||
```
|
||||
|
||||
In this example:
|
||||
|
||||
@@ -240,6 +253,23 @@ print(f"Tasks Output: {crew_output.tasks_output}")
|
||||
print(f"Token Usage: {crew_output.token_usage}")
|
||||
```
|
||||
|
||||
## Accessing Crew Logs
|
||||
|
||||
You can see real time log of the crew execution, by setting `output_log_file` as a `True(Boolean)` or a `file_name(str)`. Supports logging of events as both `file_name.txt` and `file_name.json`.
|
||||
In case of `True(Boolean)` will save as `logs.txt`.
|
||||
|
||||
In case of `output_log_file` is set as `False(Boolean)` or `None`, the logs will not be populated.
|
||||
|
||||
```python Code
|
||||
# Save crew logs
|
||||
crew = Crew(output_log_file = True) # Logs will be saved as logs.txt
|
||||
crew = Crew(output_log_file = file_name) # Logs will be saved as file_name.txt
|
||||
crew = Crew(output_log_file = file_name.txt) # Logs will be saved as file_name.txt
|
||||
crew = Crew(output_log_file = file_name.json) # Logs will be saved as file_name.json
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Memory Utilization
|
||||
|
||||
Crews can utilize memory (short-term, long-term, and entity memory) to enhance their execution and learning over time. This feature allows crews to store and recall execution memories, aiding in decision-making and task execution strategies.
|
||||
@@ -279,9 +309,9 @@ print(result)
|
||||
Once your crew is assembled, initiate the workflow with the appropriate kickoff method. CrewAI provides several methods for better control over the kickoff process: `kickoff()`, `kickoff_for_each()`, `kickoff_async()`, and `kickoff_for_each_async()`.
|
||||
|
||||
- `kickoff()`: Starts the execution process according to the defined process flow.
|
||||
- `kickoff_for_each()`: Executes tasks for each agent individually.
|
||||
- `kickoff_for_each()`: Executes tasks sequentially for each provided input event or item in the collection.
|
||||
- `kickoff_async()`: Initiates the workflow asynchronously.
|
||||
- `kickoff_for_each_async()`: Executes tasks for each agent individually in an asynchronous manner.
|
||||
- `kickoff_for_each_async()`: Executes tasks concurrently for each provided input event or item, leveraging asynchronous processing.
|
||||
|
||||
```python Code
|
||||
# Start the crew's task execution
|
||||
@@ -296,12 +326,12 @@ for result in results:
|
||||
|
||||
# Example of using kickoff_async
|
||||
inputs = {'topic': 'AI in healthcare'}
|
||||
async_result = my_crew.kickoff_async(inputs=inputs)
|
||||
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 = my_crew.kickoff_for_each_async(inputs=inputs_array)
|
||||
async_results = await my_crew.kickoff_for_each_async(inputs=inputs_array)
|
||||
for async_result in async_results:
|
||||
print(async_result)
|
||||
```
|
||||
390
docs/en/concepts/event-listener.mdx
Normal file
390
docs/en/concepts/event-listener.mdx
Normal file
@@ -0,0 +1,390 @@
|
||||
---
|
||||
title: 'Event Listeners'
|
||||
description: 'Tap into CrewAI events to build custom integrations and monitoring'
|
||||
icon: spinner
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CrewAI provides a powerful event system that allows you to listen for and react to various events that occur during the execution of your Crew. This feature enables you to build custom integrations, monitoring solutions, logging systems, or any other functionality that needs to be triggered based on CrewAI's internal events.
|
||||
|
||||
## How It Works
|
||||
|
||||
CrewAI uses an event bus architecture to emit events throughout the execution lifecycle. The event system is built on the following components:
|
||||
|
||||
1. **CrewAIEventsBus**: A singleton event bus that manages event registration and emission
|
||||
2. **BaseEvent**: Base class for all events in the system
|
||||
3. **BaseEventListener**: Abstract base class for creating custom event listeners
|
||||
|
||||
When specific actions occur in CrewAI (like a Crew starting execution, an Agent completing a task, or a tool being used), the system emits corresponding events. You can register handlers for these events to execute custom code when they occur.
|
||||
|
||||
<Note type="info" title="Enterprise Enhancement: Prompt Tracing">
|
||||
CrewAI Enterprise provides a built-in Prompt Tracing feature that leverages the event system to track, store, and visualize all prompts, completions, and associated metadata. This provides powerful debugging capabilities and transparency into your agent operations.
|
||||
|
||||

|
||||
|
||||
With Prompt Tracing you can:
|
||||
- View the complete history of all prompts sent to your LLM
|
||||
- Track token usage and costs
|
||||
- Debug agent reasoning failures
|
||||
- Share prompt sequences with your team
|
||||
- Compare different prompt strategies
|
||||
- Export traces for compliance and auditing
|
||||
</Note>
|
||||
|
||||
## Creating a Custom Event Listener
|
||||
|
||||
To create a custom event listener, you need to:
|
||||
|
||||
1. Create a class that inherits from `BaseEventListener`
|
||||
2. Implement the `setup_listeners` method
|
||||
3. Register handlers for the events you're interested in
|
||||
4. Create an instance of your listener in the appropriate file
|
||||
|
||||
Here's a simple example of a custom event listener class:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events import (
|
||||
CrewKickoffStartedEvent,
|
||||
CrewKickoffCompletedEvent,
|
||||
AgentExecutionCompletedEvent,
|
||||
)
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
||||
def on_crew_started(source, event):
|
||||
print(f"Crew '{event.crew_name}' has started execution!")
|
||||
|
||||
@crewai_event_bus.on(CrewKickoffCompletedEvent)
|
||||
def on_crew_completed(source, event):
|
||||
print(f"Crew '{event.crew_name}' has completed execution!")
|
||||
print(f"Output: {event.output}")
|
||||
|
||||
@crewai_event_bus.on(AgentExecutionCompletedEvent)
|
||||
def on_agent_execution_completed(source, event):
|
||||
print(f"Agent '{event.agent.role}' completed task")
|
||||
print(f"Output: {event.output}")
|
||||
```
|
||||
|
||||
## Properly Registering Your Listener
|
||||
|
||||
Simply defining your listener class isn't enough. You need to create an instance of it and ensure it's imported in your application. This ensures that:
|
||||
|
||||
1. The event handlers are registered with the event bus
|
||||
2. The listener instance remains in memory (not garbage collected)
|
||||
3. The listener is active when events are emitted
|
||||
|
||||
### Option 1: Import and Instantiate in Your Crew or Flow Implementation
|
||||
|
||||
The most important thing is to create an instance of your listener in the file where your Crew or Flow is defined and executed:
|
||||
|
||||
#### For Crew-based Applications
|
||||
|
||||
Create and import your listener at the top of your Crew implementation file:
|
||||
|
||||
```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=[...],
|
||||
# ...
|
||||
)
|
||||
```
|
||||
|
||||
#### For Flow-based Applications
|
||||
|
||||
Create and import your listener at the top of your Flow implementation file:
|
||||
|
||||
```python
|
||||
# In your main.py or flow.py file
|
||||
from crewai.flow import Flow, listen, start
|
||||
from my_listeners import MyCustomListener
|
||||
|
||||
# Create an instance of your listener
|
||||
my_listener = MyCustomListener()
|
||||
|
||||
class MyCustomFlow(Flow):
|
||||
# Your flow implementation...
|
||||
|
||||
@start()
|
||||
def first_step(self):
|
||||
# ...
|
||||
```
|
||||
|
||||
This ensures that your listener is loaded and active when your Crew or Flow is executed.
|
||||
|
||||
### Option 2: Create a Package for Your Listeners
|
||||
|
||||
For a more structured approach, especially if you have multiple listeners:
|
||||
|
||||
1. Create a package for your listeners:
|
||||
|
||||
```
|
||||
my_project/
|
||||
├── listeners/
|
||||
│ ├── __init__.py
|
||||
│ ├── my_custom_listener.py
|
||||
│ └── another_listener.py
|
||||
```
|
||||
|
||||
2. In `my_custom_listener.py`, define your listener class and create an instance:
|
||||
|
||||
```python
|
||||
# my_custom_listener.py
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
# ... import events ...
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
# ... implementation ...
|
||||
|
||||
# Create an instance of your listener
|
||||
my_custom_listener = MyCustomListener()
|
||||
```
|
||||
|
||||
3. In `__init__.py`, import the listener instances to ensure they're loaded:
|
||||
|
||||
```python
|
||||
# __init__.py
|
||||
from .my_custom_listener import my_custom_listener
|
||||
from .another_listener import another_listener
|
||||
|
||||
# Optionally export them if you need to access them elsewhere
|
||||
__all__ = ['my_custom_listener', 'another_listener']
|
||||
```
|
||||
|
||||
4. Import your listeners package in your Crew or Flow file:
|
||||
|
||||
```python
|
||||
# In your crew.py or flow.py file
|
||||
import my_project.listeners # This loads all your listeners
|
||||
|
||||
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.
|
||||
|
||||
## Available Event Types
|
||||
|
||||
CrewAI provides a wide range of events that you can listen for:
|
||||
|
||||
### Crew Events
|
||||
|
||||
- **CrewKickoffStartedEvent**: Emitted when a Crew starts execution
|
||||
- **CrewKickoffCompletedEvent**: Emitted when a Crew completes execution
|
||||
- **CrewKickoffFailedEvent**: Emitted when a Crew fails to complete execution
|
||||
- **CrewTestStartedEvent**: Emitted when a Crew starts testing
|
||||
- **CrewTestCompletedEvent**: Emitted when a Crew completes testing
|
||||
- **CrewTestFailedEvent**: Emitted when a Crew fails to complete testing
|
||||
- **CrewTrainStartedEvent**: Emitted when a Crew starts training
|
||||
- **CrewTrainCompletedEvent**: Emitted when a Crew completes training
|
||||
- **CrewTrainFailedEvent**: Emitted when a Crew fails to complete training
|
||||
|
||||
### Agent Events
|
||||
|
||||
- **AgentExecutionStartedEvent**: Emitted when an Agent starts executing a task
|
||||
- **AgentExecutionCompletedEvent**: Emitted when an Agent completes executing a task
|
||||
- **AgentExecutionErrorEvent**: Emitted when an Agent encounters an error during execution
|
||||
|
||||
### Task Events
|
||||
|
||||
- **TaskStartedEvent**: Emitted when a Task starts execution
|
||||
- **TaskCompletedEvent**: Emitted when a Task completes execution
|
||||
- **TaskFailedEvent**: Emitted when a Task fails to complete execution
|
||||
- **TaskEvaluationEvent**: Emitted when a Task is evaluated
|
||||
|
||||
### Tool Usage Events
|
||||
|
||||
- **ToolUsageStartedEvent**: Emitted when a tool execution is started
|
||||
- **ToolUsageFinishedEvent**: Emitted when a tool execution is completed
|
||||
- **ToolUsageErrorEvent**: Emitted when a tool execution encounters an error
|
||||
- **ToolValidateInputErrorEvent**: Emitted when a tool input validation encounters an error
|
||||
- **ToolExecutionErrorEvent**: Emitted when a tool execution encounters an error
|
||||
- **ToolSelectionErrorEvent**: Emitted when there's an error selecting a tool
|
||||
|
||||
### Knowledge Events
|
||||
|
||||
- **KnowledgeRetrievalStartedEvent**: Emitted when a knowledge retrieval is started
|
||||
- **KnowledgeRetrievalCompletedEvent**: Emitted when a knowledge retrieval is completed
|
||||
- **KnowledgeQueryStartedEvent**: Emitted when a knowledge query is started
|
||||
- **KnowledgeQueryCompletedEvent**: Emitted when a knowledge query is completed
|
||||
- **KnowledgeQueryFailedEvent**: Emitted when a knowledge query fails
|
||||
- **KnowledgeSearchQueryFailedEvent**: Emitted when a knowledge search query fails
|
||||
|
||||
### LLM Guardrail Events
|
||||
|
||||
- **LLMGuardrailStartedEvent**: Emitted when a guardrail validation starts. Contains details about the guardrail being applied and retry count.
|
||||
- **LLMGuardrailCompletedEvent**: Emitted when a guardrail validation completes. Contains details about validation success/failure, results, and error messages if any.
|
||||
|
||||
### Flow Events
|
||||
|
||||
- **FlowCreatedEvent**: Emitted when a Flow is created
|
||||
- **FlowStartedEvent**: Emitted when a Flow starts execution
|
||||
- **FlowFinishedEvent**: Emitted when a Flow completes execution
|
||||
- **FlowPlotEvent**: Emitted when a Flow is plotted
|
||||
- **MethodExecutionStartedEvent**: Emitted when a Flow method starts execution
|
||||
- **MethodExecutionFinishedEvent**: Emitted when a Flow method completes execution
|
||||
- **MethodExecutionFailedEvent**: Emitted when a Flow method fails to complete execution
|
||||
|
||||
### LLM Events
|
||||
|
||||
- **LLMCallStartedEvent**: Emitted when an LLM call starts
|
||||
- **LLMCallCompletedEvent**: Emitted when an LLM call completes
|
||||
- **LLMCallFailedEvent**: Emitted when an LLM call fails
|
||||
- **LLMStreamChunkEvent**: Emitted for each chunk received during streaming LLM responses
|
||||
|
||||
### Memory Events
|
||||
|
||||
- **MemoryQueryStartedEvent**: Emitted when a memory query is started. Contains the query, limit, and optional score threshold.
|
||||
- **MemoryQueryCompletedEvent**: Emitted when a memory query is completed successfully. Contains the query, results, limit, score threshold, and query execution time.
|
||||
- **MemoryQueryFailedEvent**: Emitted when a memory query fails. Contains the query, limit, score threshold, and error message.
|
||||
- **MemorySaveStartedEvent**: Emitted when a memory save operation is started. Contains the value to be saved, metadata, and optional agent role.
|
||||
- **MemorySaveCompletedEvent**: Emitted when a memory save operation is completed successfully. Contains the saved value, metadata, agent role, and save execution time.
|
||||
- **MemorySaveFailedEvent**: Emitted when a memory save operation fails. Contains the value, metadata, agent role, and error message.
|
||||
- **MemoryRetrievalStartedEvent**: Emitted when memory retrieval for a task prompt starts. Contains the optional task ID.
|
||||
- **MemoryRetrievalCompletedEvent**: Emitted when memory retrieval for a task prompt completes successfully. Contains the task ID, memory content, and retrieval execution time.
|
||||
|
||||
## Event Handler Structure
|
||||
|
||||
Each event handler receives two parameters:
|
||||
|
||||
1. **source**: The object that emitted the event
|
||||
2. **event**: The event instance, containing event-specific data
|
||||
|
||||
The structure of the event object depends on the event type, but all events inherit from `BaseEvent` and include:
|
||||
|
||||
- **timestamp**: The time when the event was emitted
|
||||
- **type**: A string identifier for the event type
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
# Outside the context, the temporary handler is removed
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
Event listeners can be used for a variety of purposes:
|
||||
|
||||
1. **Logging and Monitoring**: Track the execution of your Crew and log important events
|
||||
2. **Analytics**: Collect data about your Crew's performance and behavior
|
||||
3. **Debugging**: Set up temporary listeners to debug specific issues
|
||||
4. **Integration**: Connect CrewAI with external systems like monitoring platforms, databases, or notification services
|
||||
5. **Custom Behavior**: Trigger custom actions based on specific events
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep Handlers Light**: Event handlers should be lightweight and avoid blocking operations
|
||||
2. **Error Handling**: Include proper error handling in your event handlers to prevent exceptions from affecting the main execution
|
||||
3. **Cleanup**: If your listener allocates resources, ensure they're properly cleaned up
|
||||
4. **Selective Listening**: Only listen for events you actually need to handle
|
||||
5. **Testing**: Test your event listeners in isolation to ensure they behave as expected
|
||||
|
||||
By leveraging CrewAI's event system, you can extend its functionality and integrate it seamlessly with your existing infrastructure.
|
||||
@@ -4,7 +4,7 @@ description: Learn how to create and manage AI workflows using CrewAI Flows.
|
||||
icon: arrow-progress
|
||||
---
|
||||
|
||||
## Introduction
|
||||
## Overview
|
||||
|
||||
CrewAI Flows is a powerful feature designed to streamline the creation and management of AI workflows. Flows allow developers to combine and coordinate coding tasks and Crews efficiently, providing a robust framework for building sophisticated AI automations.
|
||||
|
||||
@@ -75,11 +75,12 @@ class ExampleFlow(Flow):
|
||||
|
||||
|
||||
flow = ExampleFlow()
|
||||
flow.plot()
|
||||
result = flow.kickoff()
|
||||
|
||||
print(f"Generated fun fact: {result}")
|
||||
```
|
||||
|
||||

|
||||
In the above example, we have created a simple Flow that generates a random city using OpenAI and then generates a fun fact about that city. The Flow consists of two tasks: `generate_city` and `generate_fun_fact`. The `generate_city` task is the starting point of the Flow, and the `generate_fun_fact` task listens for the output of the `generate_city` task.
|
||||
|
||||
Each Flow instance automatically receives a unique identifier (UUID) in its state, which helps track and manage flow executions. The state can also store additional data (like the generated city and fun fact) that persists throughout the flow's execution.
|
||||
@@ -146,21 +147,23 @@ class OutputExampleFlow(Flow):
|
||||
|
||||
|
||||
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>
|
||||

|
||||
|
||||
In this example, the `second_method` is the last method to complete, so its output will be the final output of the Flow.
|
||||
The `kickoff()` method will return the final output, which is then printed to the console.
|
||||
The `kickoff()` method will return the final output, which is then printed to the console. The `plot()` method will generate the HTML file, which will help you understand the flow.
|
||||
|
||||
#### Accessing and Updating State
|
||||
|
||||
@@ -192,6 +195,7 @@ class StateExampleFlow(Flow[ExampleState]):
|
||||
return self.state.message
|
||||
|
||||
flow = StateExampleFlow()
|
||||
flow.plot("my_flow_plot")
|
||||
final_output = flow.kickoff()
|
||||
print(f"Final Output: {final_output}")
|
||||
print("Final State:")
|
||||
@@ -206,6 +210,8 @@ counter=2 message='Hello from first_method - updated by second_method'
|
||||
|
||||
</CodeGroup>
|
||||
|
||||

|
||||
|
||||
In this example, the state is updated by both `first_method` and `second_method`.
|
||||
After the Flow has run, you can access the final state to see the updates made by these methods.
|
||||
|
||||
@@ -232,26 +238,29 @@ class UnstructuredExampleFlow(Flow):
|
||||
def first_method(self):
|
||||
# The state automatically includes an 'id' field
|
||||
print(f"State ID: {self.state['id']}")
|
||||
self.state.message = "Hello from structured flow"
|
||||
self.state.counter = 0
|
||||
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"
|
||||
self.state['counter'] += 1
|
||||
self.state['message'] += " - updated"
|
||||
|
||||
@listen(second_method)
|
||||
def third_method(self):
|
||||
self.state.counter += 1
|
||||
self.state.message += " - updated again"
|
||||
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()
|
||||
```
|
||||
|
||||

|
||||
|
||||
**Note:** The `id` field is automatically generated and preserved throughout the flow's execution. You don't need to manage or set it manually, and it will be maintained even when updating the state with new data.
|
||||
|
||||
**Key Points:**
|
||||
@@ -302,6 +311,8 @@ flow = StructuredExampleFlow()
|
||||
flow.kickoff()
|
||||
```
|
||||
|
||||

|
||||
|
||||
**Key Points:**
|
||||
|
||||
- **Defined Schema:** `ExampleState` clearly outlines the state structure, enhancing code readability and maintainability.
|
||||
@@ -323,6 +334,91 @@ flow.kickoff()
|
||||
|
||||
By providing both unstructured and structured state management options, CrewAI Flows empowers developers to build AI workflows that are both flexible and robust, catering to a wide range of application requirements.
|
||||
|
||||
## Flow Persistence
|
||||
|
||||
The @persist decorator enables automatic state persistence in CrewAI Flows, allowing you to maintain flow state across restarts or different workflow executions. This decorator can be applied at either the class level or method level, providing flexibility in how you manage state persistence.
|
||||
|
||||
### Class-Level Persistence
|
||||
|
||||
When applied at the class level, the @persist decorator automatically persists all flow method states:
|
||||
|
||||
```python
|
||||
@persist # Using SQLiteFlowPersistence by default
|
||||
class MyFlow(Flow[MyState]):
|
||||
@start()
|
||||
def initialize_flow(self):
|
||||
# This method will automatically have its state persisted
|
||||
self.state.counter = 1
|
||||
print("Initialized flow. State ID:", self.state.id)
|
||||
|
||||
@listen(initialize_flow)
|
||||
def next_step(self):
|
||||
# The state (including self.state.id) is automatically reloaded
|
||||
self.state.counter += 1
|
||||
print("Flow state is persisted. Counter:", self.state.counter)
|
||||
```
|
||||
|
||||
### Method-Level Persistence
|
||||
|
||||
For more granular control, you can apply @persist to specific methods:
|
||||
|
||||
```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"])
|
||||
```
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Unique State Identification**
|
||||
- Each flow state automatically receives a unique UUID
|
||||
- The ID is preserved across state updates and method calls
|
||||
- Supports both structured (Pydantic BaseModel) and unstructured (dictionary) states
|
||||
|
||||
2. **Default SQLite Backend**
|
||||
- SQLiteFlowPersistence is the default storage backend
|
||||
- States are automatically saved to a local SQLite database
|
||||
- Robust error handling ensures clear messages if database operations fail
|
||||
|
||||
3. **Error Handling**
|
||||
- Comprehensive error messages for database operations
|
||||
- Automatic state validation during save and load
|
||||
- Clear feedback when persistence operations encounter issues
|
||||
|
||||
### Important Considerations
|
||||
|
||||
- **State Types**: Both structured (Pydantic BaseModel) and unstructured (dictionary) states are supported
|
||||
- **Automatic ID**: The `id` field is automatically added if not present
|
||||
- **State Recovery**: Failed or restarted flows can automatically reload their previous state
|
||||
- **Custom Implementation**: You can provide your own FlowPersistence implementation for specialized storage needs
|
||||
|
||||
### Technical Advantages
|
||||
|
||||
1. **Precise Control Through Low-Level Access**
|
||||
- Direct access to persistence operations for advanced use cases
|
||||
- Fine-grained control via method-level persistence decorators
|
||||
- Built-in state inspection and debugging capabilities
|
||||
- Full visibility into state changes and persistence operations
|
||||
|
||||
2. **Enhanced Reliability**
|
||||
- Automatic state recovery after system failures or restarts
|
||||
- Transaction-based state updates for data integrity
|
||||
- Comprehensive error handling with clear error messages
|
||||
- Robust validation during state save and load operations
|
||||
|
||||
3. **Extensible Architecture**
|
||||
- Customizable persistence backend through FlowPersistence interface
|
||||
- Support for specialized storage solutions beyond SQLite
|
||||
- Compatible with both structured (Pydantic) and unstructured (dict) states
|
||||
- Seamless integration with existing CrewAI flow patterns
|
||||
|
||||
The persistence system's architecture emphasizes technical precision and customization options, allowing developers to maintain full control over state management while benefiting from built-in reliability features.
|
||||
|
||||
## Flow Control
|
||||
|
||||
### Conditional Logic: `or`
|
||||
@@ -351,6 +447,7 @@ class OrExampleFlow(Flow):
|
||||
|
||||
|
||||
flow = OrExampleFlow()
|
||||
flow.plot("my_flow_plot")
|
||||
flow.kickoff()
|
||||
```
|
||||
|
||||
@@ -361,6 +458,8 @@ Logger: Hello from the second method
|
||||
|
||||
</CodeGroup>
|
||||
|
||||

|
||||
|
||||
When you run this Flow, the `logger` method will be triggered by the output of either the `start_method` or the `second_method`.
|
||||
The `or_` function is used to listen to multiple methods and trigger the listener method when any of the specified methods emit an output.
|
||||
|
||||
@@ -389,6 +488,7 @@ class AndExampleFlow(Flow):
|
||||
print(self.state)
|
||||
|
||||
flow = AndExampleFlow()
|
||||
flow.plot()
|
||||
flow.kickoff()
|
||||
```
|
||||
|
||||
@@ -399,6 +499,8 @@ flow.kickoff()
|
||||
|
||||
</CodeGroup>
|
||||
|
||||

|
||||
|
||||
When you run this Flow, the `logger` method will be triggered only when both the `start_method` and the `second_method` emit an output.
|
||||
The `and_` function is used to listen to multiple methods and trigger the listener method only when all the specified methods emit an output.
|
||||
|
||||
@@ -442,6 +544,7 @@ class RouterFlow(Flow[ExampleState]):
|
||||
|
||||
|
||||
flow = RouterFlow()
|
||||
flow.plot("my_flow_plot")
|
||||
flow.kickoff()
|
||||
```
|
||||
|
||||
@@ -453,6 +556,8 @@ Fourth method running
|
||||
|
||||
</CodeGroup>
|
||||
|
||||

|
||||
|
||||
In the above example, the `start_method` generates a random boolean value and sets it in the state.
|
||||
The `second_method` uses the `@router()` decorator to define conditional routing logic based on the value of the boolean.
|
||||
If the boolean is `True`, the method returns `"success"`, and if it is `False`, the method returns `"failed"`.
|
||||
@@ -460,6 +565,122 @@ The `third_method` and `fourth_method` listen to the output of the `second_metho
|
||||
|
||||
When you run this Flow, the output will change based on the random boolean value generated by the `start_method`.
|
||||
|
||||
## Adding Agents to Flows
|
||||
|
||||
Agents can be seamlessly integrated into your flows, providing a lightweight alternative to full Crews when you need simpler, focused task execution. Here's an example of how to use an Agent within a flow to perform market research:
|
||||
|
||||
```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())
|
||||
```
|
||||
|
||||

|
||||
|
||||
This example demonstrates several key features of using Agents in flows:
|
||||
|
||||
1. **Structured Output**: Using Pydantic models to define the expected output format (`MarketAnalysis`) ensures type safety and structured data throughout the flow.
|
||||
|
||||
2. **State Management**: The flow state (`MarketResearchState`) maintains context between steps and stores both inputs and outputs.
|
||||
|
||||
3. **Tool Integration**: Agents can use tools (like `WebsiteSearchTool`) to enhance their capabilities.
|
||||
|
||||
## Adding Crews to Flows
|
||||
|
||||
Creating a flow with multiple crews in CrewAI is straightforward.
|
||||
@@ -548,13 +769,16 @@ def kickoff():
|
||||
|
||||
def plot():
|
||||
poem_flow = PoemFlow()
|
||||
poem_flow.plot()
|
||||
poem_flow.plot("PoemFlowPlot")
|
||||
|
||||
if __name__ == "__main__":
|
||||
kickoff()
|
||||
plot()
|
||||
```
|
||||
|
||||
In this example, the `PoemFlow` class defines a flow that generates a sentence count, uses the `PoemCrew` to generate a poem, and then saves the poem to a file. The flow is kicked off by calling the `kickoff()` method.
|
||||
In this example, the `PoemFlow` class defines a flow that generates a sentence count, uses the `PoemCrew` to generate a poem, and then saves the poem to a file. The flow is kicked off by calling the `kickoff()` method. The PoemFlowPlot will be generated by `plot()` method.
|
||||
|
||||

|
||||
|
||||
### Running the Flow
|
||||
|
||||
@@ -653,3 +877,34 @@ Also, check out our YouTube video on how to use flows in CrewAI below!
|
||||
referrerpolicy="strict-origin-when-cross-origin"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
|
||||
## Running Flows
|
||||
|
||||
There are two ways to run a flow:
|
||||
|
||||
### Using the Flow API
|
||||
|
||||
You can run a flow programmatically by creating an instance of your flow class and calling the `kickoff()` method:
|
||||
|
||||
```python
|
||||
flow = ExampleFlow()
|
||||
result = flow.kickoff()
|
||||
```
|
||||
|
||||
### Using the CLI
|
||||
|
||||
Starting from version 0.103.0, you can run flows using the `crewai run` command:
|
||||
|
||||
```shell
|
||||
crewai run
|
||||
```
|
||||
|
||||
This command automatically detects if your project is a flow (based on the `type = "flow"` setting in your pyproject.toml) and runs it accordingly. This is the recommended way to run flows from the command line.
|
||||
|
||||
For backward compatibility, you can also use:
|
||||
|
||||
```shell
|
||||
crewai flow kickoff
|
||||
```
|
||||
|
||||
However, the `crewai run` command is now the preferred method as it works for both crews and flows.
|
||||
1061
docs/en/concepts/knowledge.mdx
Normal file
1061
docs/en/concepts/knowledge.mdx
Normal file
File diff suppressed because it is too large
Load Diff
958
docs/en/concepts/llms.mdx
Normal file
958
docs/en/concepts/llms.mdx
Normal file
@@ -0,0 +1,958 @@
|
||||
---
|
||||
title: 'LLMs'
|
||||
description: 'A comprehensive guide to configuring and using Large Language Models (LLMs) in your CrewAI projects'
|
||||
icon: 'microchip-ai'
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CrewAI integrates with multiple LLM providers through LiteLLM, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.
|
||||
|
||||
|
||||
## What are LLMs?
|
||||
|
||||
Large Language Models (LLMs) are the core intelligence behind CrewAI agents. They enable agents to understand context, make decisions, and generate human-like responses. Here's what you need to know:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="LLM Basics" icon="brain">
|
||||
Large Language Models are AI systems trained on vast amounts of text data. They power the intelligence of your CrewAI agents, enabling them to understand and generate human-like text.
|
||||
</Card>
|
||||
<Card title="Context Window" icon="window">
|
||||
The context window determines how much text an LLM can process at once. Larger windows (e.g., 128K tokens) allow for more context but may be more expensive and slower.
|
||||
</Card>
|
||||
<Card title="Temperature" icon="temperature-three-quarters">
|
||||
Temperature (0.0 to 1.0) controls response randomness. Lower values (e.g., 0.2) produce more focused, deterministic outputs, while higher values (e.g., 0.8) increase creativity and variability.
|
||||
</Card>
|
||||
<Card title="Provider Selection" icon="server">
|
||||
Each LLM provider (e.g., OpenAI, Anthropic, Google) offers different models with varying capabilities, pricing, and features. Choose based on your needs for accuracy, speed, and cost.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Setting up your LLM
|
||||
|
||||
There are different places in CrewAI code where you can specify the model to use. Once you specify the model you are using, you will need to provide the configuration (like an API key) for each of the model providers you use. See the [provider configuration examples](#provider-configuration-examples) section for your provider.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="1. Environment Variables">
|
||||
The simplest way to get started. Set the model in your environment directly, through an `.env` file or in your app code. If you used `crewai create` to bootstrap your project, it will be set already.
|
||||
|
||||
```bash .env
|
||||
MODEL=model-id # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...
|
||||
|
||||
# Be sure to set your API keys here too. See the Provider
|
||||
# section below.
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Never commit API keys to version control. Use environment files (.env) or your system's secret management.
|
||||
</Warning>
|
||||
</Tab>
|
||||
<Tab title="2. YAML Configuration">
|
||||
Create a YAML file to define your agent configurations. This method is great for version control and team collaboration:
|
||||
|
||||
```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...
|
||||
# (see provider configuration examples below for more)
|
||||
```
|
||||
|
||||
<Info>
|
||||
The YAML configuration allows you to:
|
||||
- Version control your agent settings
|
||||
- Easily switch between different models
|
||||
- Share configurations across team members
|
||||
- Document model choices and their purposes
|
||||
</Info>
|
||||
</Tab>
|
||||
<Tab title="3. Direct Code">
|
||||
For maximum flexibility, configure LLMs directly in your Python code:
|
||||
|
||||
```python {4,8}
|
||||
from crewai import LLM
|
||||
|
||||
# Basic configuration
|
||||
llm = LLM(model="model-id-here") # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
|
||||
# Advanced configuration with detailed parameters
|
||||
llm = LLM(
|
||||
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
temperature=0.7, # Higher for more creative outputs
|
||||
timeout=120, # Seconds to wait for response
|
||||
max_tokens=4000, # Maximum length of response
|
||||
top_p=0.9, # Nucleus sampling parameter
|
||||
frequency_penalty=0.1 , # Reduce repetition
|
||||
presence_penalty=0.1, # Encourage topic diversity
|
||||
response_format={"type": "json"}, # For structured outputs
|
||||
seed=42 # For reproducible results
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Parameter explanations:
|
||||
- `temperature`: Controls randomness (0.0-1.0)
|
||||
- `timeout`: Maximum wait time for response
|
||||
- `max_tokens`: Limits response length
|
||||
- `top_p`: Alternative to temperature for sampling
|
||||
- `frequency_penalty`: Reduces word repetition
|
||||
- `presence_penalty`: Encourages new topics
|
||||
- `response_format`: Specifies output structure
|
||||
- `seed`: Ensures consistent outputs
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Provider Configuration Examples
|
||||
|
||||
CrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.
|
||||
In this section, you'll find detailed examples that help you select, configure, and optimize the LLM that best fits your project's needs.
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI">
|
||||
Set the following environment variables in your `.env` file:
|
||||
|
||||
```toml Code
|
||||
# Required
|
||||
OPENAI_API_KEY=sk-...
|
||||
|
||||
# Optional
|
||||
OPENAI_API_BASE=<custom-base-url>
|
||||
OPENAI_ORGANIZATION=<your-org-id>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```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 is one of the leading providers of LLMs with a wide range of models and features.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|---------------------|------------------|-----------------------------------------------|
|
||||
| GPT-4 | 8,192 tokens | High-accuracy tasks, complex reasoning |
|
||||
| GPT-4 Turbo | 128,000 tokens | Long-form content, document analysis |
|
||||
| GPT-4o & GPT-4o-mini | 128,000 tokens | Cost-effective large context processing |
|
||||
| o3-mini | 200,000 tokens | Fast reasoning, complex reasoning |
|
||||
| o1-mini | 128,000 tokens | Fast reasoning, complex reasoning |
|
||||
| o1-preview | 128,000 tokens | Fast reasoning, complex reasoning |
|
||||
| o1 | 200,000 tokens | Fast reasoning, complex reasoning |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Meta-Llama">
|
||||
Meta's Llama API provides access to Meta's family of large language models.
|
||||
The API is available through the [Meta Llama API](https://llama.developer.meta.com?utm_source=partner-crewai&utm_medium=website).
|
||||
Set the following environment variables in your `.env` file:
|
||||
|
||||
```toml Code
|
||||
# Meta Llama API Key Configuration
|
||||
LLAMA_API_KEY=LLM|your_api_key_here
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
# Initialize Meta Llama LLM
|
||||
llm = LLM(
|
||||
model="meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8",
|
||||
temperature=0.8,
|
||||
stop=["END"],
|
||||
seed=42
|
||||
)
|
||||
```
|
||||
|
||||
All models listed here https://llama.developer.meta.com/docs/models/ are supported.
|
||||
|
||||
| Model ID | Input context length | Output context length | Input Modalities | Output Modalities |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8` | 128k | 4028 | Text, Image | Text |
|
||||
| `meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 128k | 4028 | Text, Image | Text |
|
||||
| `meta_llama/Llama-3.3-70B-Instruct` | 128k | 4028 | Text | Text |
|
||||
| `meta_llama/Llama-3.3-8B-Instruct` | 128k | 4028 | Text | Text |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Anthropic">
|
||||
```toml Code
|
||||
# Required
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
|
||||
# Optional
|
||||
ANTHROPIC_API_BASE=<custom-base-url>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-sonnet-20240229-v1:0",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google (Gemini API)">
|
||||
Set your API key in your `.env` file. If you need a key, or need to find an
|
||||
existing key, check [AI Studio](https://aistudio.google.com/apikey).
|
||||
|
||||
```toml .env
|
||||
# https://ai.google.dev/gemini-api/docs/api-key
|
||||
GEMINI_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7,
|
||||
)
|
||||
```
|
||||
|
||||
### Gemini models
|
||||
|
||||
Google offers a range of powerful models optimized for different use cases.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|--------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M tokens | Adaptive thinking, cost efficiency |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M tokens | Enhanced thinking and reasoning, multimodal understanding, advanced coding, and more |
|
||||
| gemini-2.0-flash | 1M tokens | Next generation features, speed, thinking, and realtime streaming |
|
||||
| gemini-2.0-flash-lite | 1M tokens | Cost efficiency and low latency |
|
||||
| gemini-1.5-flash | 1M tokens | Balanced multimodal model, good for most tasks |
|
||||
| gemini-1.5-flash-8B | 1M tokens | Fastest, most cost-efficient, good for high-frequency tasks |
|
||||
| gemini-1.5-pro | 2M tokens | Best performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration |
|
||||
|
||||
The full list of models is available in the [Gemini model docs](https://ai.google.dev/gemini-api/docs/models).
|
||||
|
||||
### Gemma
|
||||
|
||||
The Gemini API also allows you to use your API key to access [Gemma models](https://ai.google.dev/gemma/docs) hosted on Google infrastructure.
|
||||
|
||||
| Model | Context Window |
|
||||
|----------------|----------------|
|
||||
| gemma-3-1b-it | 32k tokens |
|
||||
| gemma-3-4b-it | 32k tokens |
|
||||
| gemma-3-12b-it | 32k tokens |
|
||||
| gemma-3-27b-it | 128k tokens |
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Google (Vertex AI)">
|
||||
Get credentials from your Google Cloud Console and save it to a JSON file, then load it with the following code:
|
||||
```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)
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```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 offers a range of powerful models optimized for different use cases:
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|--------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M tokens | Adaptive thinking, cost efficiency |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M tokens | Enhanced thinking and reasoning, multimodal understanding, advanced coding, and more |
|
||||
| gemini-2.0-flash | 1M tokens | Next generation features, speed, thinking, and realtime streaming |
|
||||
| gemini-2.0-flash-lite | 1M tokens | Cost efficiency and low latency |
|
||||
| gemini-1.5-flash | 1M tokens | Balanced multimodal model, good for most tasks |
|
||||
| gemini-1.5-flash-8B | 1M tokens | Fastest, most cost-efficient, good for high-frequency tasks |
|
||||
| gemini-1.5-pro | 2M tokens | Best performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration |
|
||||
</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>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```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>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
|
||||
)
|
||||
```
|
||||
|
||||
Before using Amazon Bedrock, make sure you have boto3 installed in your environment
|
||||
|
||||
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) is a managed service that provides access to multiple foundation models from top AI companies through a unified API, enabling secure and responsible AI application development.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|-------------------------|----------------------|-------------------------------------------------------------------|
|
||||
| Amazon Nova Pro | Up to 300k tokens | High-performance, model balancing accuracy, speed, and cost-effectiveness across diverse tasks. |
|
||||
| Amazon Nova Micro | Up to 128k tokens | High-performance, cost-effective text-only model optimized for lowest latency responses. |
|
||||
| Amazon Nova Lite | Up to 300k tokens | High-performance, affordable multimodal processing for images, video, and text with real-time capabilities. |
|
||||
| Claude 3.7 Sonnet | Up to 128k tokens | High-performance, best for complex reasoning, coding & AI agents |
|
||||
| Claude 3.5 Sonnet v2 | Up to 200k tokens | State-of-the-art model specialized in software engineering, agentic capabilities, and computer interaction at optimized cost. |
|
||||
| Claude 3.5 Sonnet | Up to 200k tokens | High-performance model delivering superior intelligence and reasoning across diverse tasks with optimal speed-cost balance. |
|
||||
| Claude 3.5 Haiku | Up to 200k tokens | Fast, compact multimodal model optimized for quick responses and seamless human-like interactions |
|
||||
| Claude 3 Sonnet | Up to 200k tokens | Multimodal model balancing intelligence and speed for high-volume deployments. |
|
||||
| Claude 3 Haiku | Up to 200k tokens | Compact, high-speed multimodal model optimized for quick responses and natural conversational interactions |
|
||||
| Claude 3 Opus | Up to 200k tokens | Most advanced multimodal model exceling at complex tasks with human-like reasoning and superior contextual understanding. |
|
||||
| Claude 2.1 | Up to 200k tokens | Enhanced version with expanded context window, improved reliability, and reduced hallucinations for long-form and RAG applications |
|
||||
| Claude | Up to 100k tokens | Versatile model excelling in sophisticated dialogue, creative content, and precise instruction following. |
|
||||
| Claude Instant | Up to 100k tokens | Fast, cost-effective model for everyday tasks like dialogue, analysis, summarization, and document Q&A |
|
||||
| Llama 3.1 405B Instruct | Up to 128k tokens | Advanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks. |
|
||||
| Llama 3.1 70B Instruct | Up to 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| Llama 3.1 8B Instruct | Up to 128k tokens | Advanced state-of-the-art model with language understanding, superior reasoning, and text generation. |
|
||||
| Llama 3 70B Instruct | Up to 8k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| Llama 3 8B Instruct | Up to 8k tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| Titan Text G1 - Lite | Up to 4k tokens | Lightweight, cost-effective model optimized for English tasks and fine-tuning with focus on summarization and content generation. |
|
||||
| Titan Text G1 - Express | Up to 8k tokens | Versatile model for general language tasks, chat, and RAG applications with support for English and 100+ languages. |
|
||||
| Cohere Command | Up to 4k tokens | Model specialized in following user commands and delivering practical enterprise solutions. |
|
||||
| Jurassic-2 Mid | Up to 8,191 tokens | Cost-effective model balancing quality and affordability for diverse language tasks like Q&A, summarization, and content generation. |
|
||||
| Jurassic-2 Ultra | Up to 8,191 tokens | Model for advanced text generation and comprehension, excelling in complex tasks like analysis and content creation. |
|
||||
| Jamba-Instruct | Up to 256k tokens | Model with extended context window optimized for cost-effective text generation, summarization, and Q&A. |
|
||||
| Mistral 7B Instruct | Up to 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| Mistral 8x7B Instruct | Up to 32k tokens | An MOE LLM that follows instructions, completes requests, and generates creative text. |
|
||||
|
||||
</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>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sagemaker/<my-endpoint>"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Mistral">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
MISTRAL_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="mistral/mistral-large-latest",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Nvidia NIM">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
NVIDIA_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nvidia_nim/meta/llama3-70b-instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
Nvidia NIM provides a comprehensive suite of models for various use cases, from general-purpose tasks to specialized applications.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|-------------------------------------------------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8,192 tokens | State-of-the-art small language model delivering superior accuracy for chatbot, virtual assistants, and content generation. |
|
||||
| nvidia/nemotron-4-mini-hindi-4b-instruct | 4,096 tokens | A bilingual Hindi-English SLM for on-device inference, tailored specifically for Hindi Language. |
|
||||
| nvidia/llama-3.1-nemotron-70b-instruct | 128k tokens | Customized for enhanced helpfulness in responses |
|
||||
| nvidia/llama3-chatqa-1.5-8b | 128k tokens | Advanced LLM to generate high-quality, context-aware responses for chatbots and search engines. |
|
||||
| nvidia/llama3-chatqa-1.5-70b | 128k tokens | Advanced LLM to generate high-quality, context-aware responses for chatbots and search engines. |
|
||||
| nvidia/vila | 128k tokens | Multi-modal vision-language model that understands text/img/video and creates informative responses |
|
||||
| nvidia/neva-22 | 4,096 tokens | Multi-modal vision-language model that understands text/images and generates informative responses |
|
||||
| nvidia/nemotron-mini-4b-instruct | 8,192 tokens | General-purpose tasks |
|
||||
| nvidia/usdcode-llama3-70b-instruct | 128k tokens | State-of-the-art LLM that answers OpenUSD knowledge queries and generates USD-Python code. |
|
||||
| nvidia/nemotron-4-340b-instruct | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| meta/codellama-70b | 100k tokens | LLM capable of generating code from natural language and vice versa. |
|
||||
| meta/llama2-70b | 4,096 tokens | Cutting-edge large language AI model capable of generating text and code in response to prompts. |
|
||||
| meta/llama3-8b-instruct | 8,192 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama3-70b-instruct | 8,192 tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| meta/llama-3.1-8b-instruct | 128k tokens | Advanced state-of-the-art model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.1-70b-instruct | 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| meta/llama-3.1-405b-instruct | 128k tokens | Advanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks. |
|
||||
| meta/llama-3.2-1b-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-3b-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-11b-vision-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-90b-vision-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| google/gemma-7b | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2b | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/codegemma-7b | 8,192 tokens | Cutting-edge model built on Google's Gemma-7B specialized for code generation and code completion. |
|
||||
| google/codegemma-1.1-7b | 8,192 tokens | Advanced programming model for code generation, completion, reasoning, and instruction following. |
|
||||
| google/recurrentgemma-2b | 8,192 tokens | Novel recurrent architecture based language model for faster inference when generating long sequences. |
|
||||
| google/gemma-2-9b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2-27b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2-2b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/deplot | 512 tokens | One-shot visual language understanding model that translates images of plots into tables. |
|
||||
| google/paligemma | 8,192 tokens | Vision language model adept at comprehending text and visual inputs to produce informative responses. |
|
||||
| mistralai/mistral-7b-instruct-v0.2 | 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| mistralai/mixtral-8x7b-instruct-v0.1 | 8,192 tokens | An MOE LLM that follows instructions, completes requests, and generates creative text. |
|
||||
| mistralai/mistral-large | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| mistralai/mixtral-8x22b-instruct-v0.1 | 8,192 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| mistralai/mistral-7b-instruct-v0.3 | 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| nv-mistralai/mistral-nemo-12b-instruct | 128k tokens | Most advanced language model for reasoning, code, multilingual tasks; runs on a single GPU. |
|
||||
| mistralai/mamba-codestral-7b-v0.1 | 256k tokens | Model for writing and interacting with code across a wide range of programming languages and tasks. |
|
||||
| microsoft/phi-3-mini-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-mini-4k-instruct | 4,096 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-small-8k-instruct | 8,192 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-small-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-medium-4k-instruct | 4,096 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-medium-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3.5-mini-instruct | 128K tokens | Lightweight multilingual LLM powering AI applications in latency bound, memory/compute constrained environments |
|
||||
| microsoft/phi-3.5-moe-instruct | 128K tokens | Advanced LLM based on Mixture of Experts architecture to deliver compute efficient content generation |
|
||||
| microsoft/kosmos-2 | 1,024 tokens | Groundbreaking multimodal model designed to understand and reason about visual elements in images. |
|
||||
| microsoft/phi-3-vision-128k-instruct | 128k tokens | Cutting-edge open multimodal model exceling in high-quality reasoning from images. |
|
||||
| microsoft/phi-3.5-vision-instruct | 128k tokens | Cutting-edge open multimodal model exceling in high-quality reasoning from images. |
|
||||
| databricks/dbrx-instruct | 12k tokens | A general-purpose LLM with state-of-the-art performance in language understanding, coding, and RAG. |
|
||||
| snowflake/arctic | 1,024 tokens | Delivers high efficiency inference for enterprise applications focused on SQL generation and coding. |
|
||||
| aisingapore/sea-lion-7b-instruct | 4,096 tokens | LLM to represent and serve the linguistic and cultural diversity of Southeast Asia |
|
||||
| ibm/granite-8b-code-instruct | 4,096 tokens | Software programming LLM for code generation, completion, explanation, and multi-turn conversion. |
|
||||
| ibm/granite-34b-code-instruct | 8,192 tokens | Software programming LLM for code generation, completion, explanation, and multi-turn conversion. |
|
||||
| ibm/granite-3.0-8b-instruct | 4,096 tokens | Advanced Small Language Model supporting RAG, summarization, classification, code, and agentic AI |
|
||||
| ibm/granite-3.0-3b-a800m-instruct | 4,096 tokens | Highly efficient Mixture of Experts model for RAG, summarization, entity extraction, and classification |
|
||||
| mediatek/breeze-7b-instruct | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| upstage/solar-10.7b-instruct | 4,096 tokens | Excels in NLP tasks, particularly in instruction-following, reasoning, and mathematics. |
|
||||
| writer/palmyra-med-70b-32k | 32k tokens | Leading LLM for accurate, contextually relevant responses in the medical domain. |
|
||||
| writer/palmyra-med-70b | 32k tokens | Leading LLM for accurate, contextually relevant responses in the medical domain. |
|
||||
| writer/palmyra-fin-70b-32k | 32k tokens | Specialized LLM for financial analysis, reporting, and data processing |
|
||||
| 01-ai/yi-large | 32k tokens | Powerful model trained on English and Chinese for diverse tasks including chatbot and creative writing. |
|
||||
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k tokens | Powerful coding model offering advanced capabilities in code generation, completion, and infilling |
|
||||
| rakuten/rakutenai-7b-instruct | 1,024 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| rakuten/rakutenai-7b-chat | 1,024 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| baichuan-inc/baichuan2-13b-chat | 4,096 tokens | Support Chinese and English chat, coding, math, instruction following, solving quizzes |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Local NVIDIA NIM Deployed using WSL2">
|
||||
|
||||
NVIDIA NIM enables you to run powerful LLMs locally on your Windows machine using WSL2 (Windows Subsystem for Linux).
|
||||
This approach allows you to leverage your NVIDIA GPU for private, secure, and cost-effective AI inference without relying on cloud services.
|
||||
Perfect for development, testing, or production scenarios where data privacy or offline capabilities are required.
|
||||
|
||||
Here is a step-by-step guide to setting up a local NVIDIA NIM model:
|
||||
|
||||
1. Follow installation instructions from [NVIDIA Website](https://docs.nvidia.com/nim/wsl2/latest/getting-started.html)
|
||||
|
||||
2. Install the local model. For Llama 3.1-8b follow [instructions](https://build.nvidia.com/meta/llama-3_1-8b-instruct/deploy)
|
||||
|
||||
3. Configure your crewai local models:
|
||||
|
||||
```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
|
||||
)
|
||||
|
||||
# Then you can use it in your 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">
|
||||
Set the following environment variables in your `.env` file:
|
||||
|
||||
```toml Code
|
||||
GROQ_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="groq/llama-3.2-90b-text-preview",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| Model | Context Window | Best For |
|
||||
|-------------------|------------------|--------------------------------------------|
|
||||
| Llama 3.1 70B/8B | 131,072 tokens | High-performance, large context tasks |
|
||||
| Llama 3.2 Series | 8,192 tokens | General-purpose tasks |
|
||||
| Mixtral 8x7B | 32,768 tokens | Balanced performance and context |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="IBM watsonx.ai">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```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>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```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. Install Ollama: [ollama.ai](https://ollama.ai/)
|
||||
2. Run a model: `ollama run llama3`
|
||||
3. Configure:
|
||||
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="ollama/llama3:70b",
|
||||
base_url="http://localhost:11434"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Fireworks AI">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
FIREWORKS_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Perplexity AI">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
PERPLEXITY_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="llama-3.1-sonar-large-128k-online",
|
||||
base_url="https://api.perplexity.ai/"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Hugging Face">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
HF_TOKEN=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SambaNova">
|
||||
Set the following environment variables in your `.env` file:
|
||||
|
||||
```toml Code
|
||||
SAMBANOVA_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sambanova/Meta-Llama-3.1-8B-Instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| Model | Context Window | Best For |
|
||||
|--------------------|------------------------|----------------------------------------------|
|
||||
| Llama 3.1 70B/8B | Up to 131,072 tokens | High-performance, large context tasks |
|
||||
| Llama 3.1 405B | 8,192 tokens | High-performance and output quality |
|
||||
| Llama 3.2 Series | 8,192 tokens | General-purpose, multimodal tasks |
|
||||
| Llama 3.3 70B | Up to 131,072 tokens | High-performance and output quality |
|
||||
| Qwen2 familly | 8,192 tokens | High-performance and output quality |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Cerebras">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
# Required
|
||||
CEREBRAS_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="cerebras/llama3.1-70b",
|
||||
temperature=0.7,
|
||||
max_tokens=8192
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Cerebras features:
|
||||
- Fast inference speeds
|
||||
- Competitive pricing
|
||||
- Good balance of speed and quality
|
||||
- Support for long context windows
|
||||
</Info>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Open Router">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
OPENROUTER_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="openrouter/deepseek/deepseek-r1",
|
||||
base_url="https://openrouter.ai/api/v1",
|
||||
api_key=OPENROUTER_API_KEY
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Open Router models:
|
||||
- openrouter/deepseek/deepseek-r1
|
||||
- openrouter/deepseek/deepseek-chat
|
||||
</Info>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Nebius AI Studio">
|
||||
Set the following environment variables in your `.env` file:
|
||||
```toml Code
|
||||
NEBIUS_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nebius/Qwen/Qwen3-30B-A3B"
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Nebius AI Studio features:
|
||||
- Large collection of open source models
|
||||
- Higher rate limits
|
||||
- Competitive pricing
|
||||
- Good balance of speed and quality
|
||||
</Info>
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Streaming Responses
|
||||
|
||||
CrewAI supports streaming responses from LLMs, allowing your application to receive and process outputs in real-time as they're generated.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Basic Setup">
|
||||
Enable streaming by setting the `stream` parameter to `True` when initializing your LLM:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Create an LLM with streaming enabled
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
stream=True # Enable streaming
|
||||
)
|
||||
```
|
||||
|
||||
When streaming is enabled, responses are delivered in chunks as they're generated, creating a more responsive user experience.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Event Handling">
|
||||
CrewAI emits events for each chunk received during streaming:
|
||||
|
||||
```python
|
||||
from crewai.utilities.events import (
|
||||
LLMStreamChunkEvent
|
||||
)
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
@crewai_event_bus.on(LLMStreamChunkEvent)
|
||||
def on_llm_stream_chunk(self, event: LLMStreamChunkEvent):
|
||||
# Process each chunk as it arrives
|
||||
print(f"Received chunk: {event.chunk}")
|
||||
|
||||
my_listener = MyCustomListener()
|
||||
```
|
||||
|
||||
<Tip>
|
||||
[Click here](https://docs.crewai.com/concepts/event-listener#event-listeners) for more details
|
||||
</Tip>
|
||||
</Tab>
|
||||
|
||||
<Tab title="Agent & Task Tracking">
|
||||
All LLM events in CrewAI include agent and task information, allowing you to track and filter LLM interactions by specific agents or tasks:
|
||||
|
||||
```python
|
||||
from crewai import LLM, Agent, Task, Crew
|
||||
from crewai.utilities.events import LLMStreamChunkEvent
|
||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
@crewai_event_bus.on(LLMStreamChunkEvent)
|
||||
def on_llm_stream_chunk(source, event):
|
||||
if researcher.id == event.agent_id:
|
||||
print("\n==============\n Got event:", event, "\n==============\n")
|
||||
|
||||
|
||||
my_listener = MyCustomListener()
|
||||
|
||||
llm = LLM(model="gpt-4o-mini", temperature=0, stream=True)
|
||||
|
||||
researcher = Agent(
|
||||
role="About User",
|
||||
goal="You know everything about the user.",
|
||||
backstory="""You are a master at understanding people and their preferences.""",
|
||||
llm=llm,
|
||||
)
|
||||
|
||||
search = Task(
|
||||
description="Answer the following questions about the user: {question}",
|
||||
expected_output="An answer to the question.",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[researcher], tasks=[search])
|
||||
|
||||
result = crew.kickoff(
|
||||
inputs={"question": "..."}
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
This feature is particularly useful for:
|
||||
- Debugging specific agent behaviors
|
||||
- Logging LLM usage by task type
|
||||
- Auditing which agents are making what types of LLM calls
|
||||
- Performance monitoring of specific tasks
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Structured LLM Calls
|
||||
|
||||
CrewAI supports structured responses from LLM calls by allowing you to define a `response_format` using a Pydantic model. This enables the framework to automatically parse and validate the output, making it easier to integrate the response into your application without manual post-processing.
|
||||
|
||||
For example, you can define a Pydantic model to represent the expected response structure and pass it as the `response_format` when instantiating the LLM. The model will then be used to convert the LLM output into a structured Python object.
|
||||
|
||||
```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')
|
||||
```
|
||||
|
||||
## Advanced Features and Optimization
|
||||
|
||||
Learn how to get the most out of your LLM configuration:
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Context Window Management">
|
||||
CrewAI includes smart context management features:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# CrewAI automatically handles:
|
||||
# 1. Token counting and tracking
|
||||
# 2. Content summarization when needed
|
||||
# 3. Task splitting for large contexts
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
max_tokens=4000, # Limit response length
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Best practices for context management:
|
||||
1. Choose models with appropriate context windows
|
||||
2. Pre-process long inputs when possible
|
||||
3. Use chunking for large documents
|
||||
4. Monitor token usage to optimize costs
|
||||
</Info>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Performance Optimization">
|
||||
<Steps>
|
||||
<Step title="Token Usage Optimization">
|
||||
Choose the right context window for your task:
|
||||
- Small tasks (up to 4K tokens): Standard models
|
||||
- Medium tasks (between 4K-32K): Enhanced models
|
||||
- Large tasks (over 32K): Large context models
|
||||
|
||||
```python
|
||||
# Configure model with appropriate settings
|
||||
llm = LLM(
|
||||
model="openai/gpt-4-turbo-preview",
|
||||
temperature=0.7, # Adjust based on task
|
||||
max_tokens=4096, # Set based on output needs
|
||||
timeout=300 # Longer timeout for complex tasks
|
||||
)
|
||||
```
|
||||
<Tip>
|
||||
- Lower temperature (0.1 to 0.3) for factual responses
|
||||
- Higher temperature (0.7 to 0.9) for creative tasks
|
||||
</Tip>
|
||||
</Step>
|
||||
|
||||
<Step title="Best Practices">
|
||||
1. Monitor token usage
|
||||
2. Implement rate limiting
|
||||
3. Use caching when possible
|
||||
4. Set appropriate max_tokens limits
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Info>
|
||||
Remember to regularly monitor your token usage and adjust your configuration as needed to optimize costs and performance.
|
||||
</Info>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Drop Additional Parameters">
|
||||
CrewAI internally uses Litellm for LLM calls, which allows you to drop additional parameters that are not needed for your specific use case. This can help simplify your code and reduce the complexity of your LLM configuration.
|
||||
For example, if you don't need to send the <code>stop</code> parameter, you can simply omit it from your LLM call:
|
||||
|
||||
```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>
|
||||
|
||||
## Common Issues and Solutions
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Authentication">
|
||||
<Warning>
|
||||
Most authentication issues can be resolved by checking API key format and environment variable names.
|
||||
</Warning>
|
||||
|
||||
```bash
|
||||
# OpenAI
|
||||
OPENAI_API_KEY=sk-...
|
||||
|
||||
# Anthropic
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Model Names">
|
||||
<Check>
|
||||
Always include the provider prefix in model names
|
||||
</Check>
|
||||
|
||||
```python
|
||||
# Correct
|
||||
llm = LLM(model="openai/gpt-4")
|
||||
|
||||
# Incorrect
|
||||
llm = LLM(model="gpt-4")
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Context Length">
|
||||
<Tip>
|
||||
Use larger context models for extensive tasks
|
||||
</Tip>
|
||||
|
||||
```python
|
||||
# Large context model
|
||||
llm = LLM(model="openai/gpt-4o") # 128K tokens
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
1201
docs/en/concepts/memory.mdx
Normal file
1201
docs/en/concepts/memory.mdx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,10 @@
|
||||
---
|
||||
title: Planning
|
||||
description: Learn how to add planning to your CrewAI Crew and improve their performance.
|
||||
icon: brain
|
||||
icon: ruler-combined
|
||||
---
|
||||
|
||||
## Introduction
|
||||
## Overview
|
||||
|
||||
The planning feature in CrewAI allows you to add planning capability to your crew. When enabled, before each Crew iteration,
|
||||
all Crew information is sent to an AgentPlanner that will plan the tasks step by step, and this plan will be added to each task description.
|
||||
@@ -29,6 +29,10 @@ my_crew = Crew(
|
||||
|
||||
From this point on, your crew will have planning enabled, and the tasks will be planned before each iteration.
|
||||
|
||||
<Warning>
|
||||
When planning is enabled, crewAI will use `gpt-4o-mini` as the default LLM for planning, which requires a valid OpenAI API key. Since your agents might be using different LLMs, this could cause confusion if you don't have an OpenAI API key configured or if you're experiencing unexpected behavior related to LLM API calls.
|
||||
</Warning>
|
||||
|
||||
#### Planning LLM
|
||||
|
||||
Now you can define the LLM that will be used to plan the tasks.
|
||||
@@ -81,8 +85,8 @@ my_crew.kickoff()
|
||||
|
||||
3. **Collect Data:**
|
||||
|
||||
- Search for the latest papers, articles, and reports published in 2023 and early 2024.
|
||||
- Use keywords like "Large Language Models 2024", "AI LLM advancements", "AI ethics 2024", etc.
|
||||
- Search for the latest papers, articles, and reports published in 2024 and early 2025.
|
||||
- Use keywords like "Large Language Models 2025", "AI LLM advancements", "AI ethics 2025", etc.
|
||||
|
||||
4. **Analyze Findings:**
|
||||
|
||||
@@ -4,7 +4,8 @@ description: Detailed guide on workflow management through processes in CrewAI,
|
||||
icon: bars-staggered
|
||||
---
|
||||
|
||||
## Understanding Processes
|
||||
## Overview
|
||||
|
||||
<Tip>
|
||||
Processes orchestrate the execution of tasks by agents, akin to project management in human teams.
|
||||
These processes ensure tasks are distributed and executed efficiently, in alignment with a predefined strategy.
|
||||
147
docs/en/concepts/reasoning.mdx
Normal file
147
docs/en/concepts/reasoning.mdx
Normal file
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: Reasoning
|
||||
description: "Learn how to enable and use agent reasoning to improve task execution."
|
||||
icon: brain
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Agent reasoning is a feature that allows agents to reflect on a task and create a plan before execution. This helps agents approach tasks more methodically and ensures they're ready to perform the assigned work.
|
||||
|
||||
## Usage
|
||||
|
||||
To enable reasoning for an agent, simply set `reasoning=True` when creating the agent:
|
||||
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
When reasoning is enabled, before executing a task, the agent will:
|
||||
|
||||
1. Reflect on the task and create a detailed plan
|
||||
2. Evaluate whether it's ready to execute the task
|
||||
3. Refine the plan as necessary until it's ready or max_reasoning_attempts is reached
|
||||
4. Inject the reasoning plan into the task description before execution
|
||||
|
||||
This process helps the agent break down complex tasks into manageable steps and identify potential challenges before starting.
|
||||
|
||||
## Configuration Options
|
||||
|
||||
<ParamField body="reasoning" type="bool" default="False">
|
||||
Enable or disable reasoning
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="max_reasoning_attempts" type="int" default="None">
|
||||
Maximum number of attempts to refine the plan before proceeding with execution. If None (default), the agent will continue refining until it's ready.
|
||||
</ParamField>
|
||||
|
||||
## Example
|
||||
|
||||
Here's a complete example:
|
||||
|
||||
```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)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The reasoning process is designed to be robust, with error handling built in. If an error occurs during reasoning, the agent will proceed with executing the task without the reasoning plan. This ensures that tasks can still be executed even if the reasoning process fails.
|
||||
|
||||
Here's how to handle potential errors in your code:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task
|
||||
import logging
|
||||
|
||||
# Set up logging to capture any reasoning errors
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
# Create an agent with reasoning enabled
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze data and provide insights",
|
||||
reasoning=True,
|
||||
max_reasoning_attempts=3
|
||||
)
|
||||
|
||||
# Create a task
|
||||
task = Task(
|
||||
description="Analyze the provided sales data and identify key trends.",
|
||||
expected_output="A report highlighting the top 3 sales trends.",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Execute the task
|
||||
# If an error occurs during reasoning, it will be logged and execution will continue
|
||||
result = agent.execute_task(task)
|
||||
```
|
||||
|
||||
## Example Reasoning Output
|
||||
|
||||
Here's an example of what a reasoning plan might look like for a data analysis task:
|
||||
|
||||
```
|
||||
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.
|
||||
```
|
||||
|
||||
This reasoning plan helps the agent organize its approach to the task, consider potential challenges, and ensure it delivers the expected output.
|
||||
@@ -4,7 +4,7 @@ description: Detailed guide on managing and creating tasks within the CrewAI fra
|
||||
icon: list-check
|
||||
---
|
||||
|
||||
## Overview of a Task
|
||||
## Overview
|
||||
|
||||
In the CrewAI framework, a `Task` is a specific assignment completed by an `Agent`.
|
||||
|
||||
@@ -12,6 +12,18 @@ Tasks provide all necessary details for execution, such as a description, the ag
|
||||
|
||||
Tasks within CrewAI can be collaborative, requiring multiple agents to work together. This is managed through the task properties and orchestrated by the Crew's process, enhancing teamwork and efficiency.
|
||||
|
||||
<Note type="info" title="Enterprise Enhancement: Visual Task Builder">
|
||||
CrewAI Enterprise includes a Visual Task Builder in Crew Studio that simplifies complex task creation and chaining. Design your task flows visually and test them in real-time without writing code.
|
||||
|
||||

|
||||
|
||||
The Visual Task Builder enables:
|
||||
- Drag-and-drop task creation
|
||||
- Visual task dependencies and flow
|
||||
- Real-time testing and validation
|
||||
- Easy sharing and collaboration
|
||||
</Note>
|
||||
|
||||
### Task Execution Flow
|
||||
|
||||
Tasks can be executed in two ways:
|
||||
@@ -33,16 +45,20 @@ crew = Crew(
|
||||
| :------------------------------- | :---------------- | :---------------------------- | :------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Description** | `description` | `str` | A clear, concise statement of what the task entails. |
|
||||
| **Expected Output** | `expected_output` | `str` | A detailed description of what the task's completion looks like. |
|
||||
| **Name** _(optional)_ | `name` | `Optional[str]` | A name identifier for the task. |
|
||||
| **Agent** _(optional)_ | `agent` | `Optional[BaseAgent]` | The agent responsible for executing the task. |
|
||||
| **Tools** _(optional)_ | `tools` | `List[BaseTool]` | The tools/resources the agent is limited to use for this task. |
|
||||
| **Name** _(optional)_ | `name` | `Optional[str]` | A name identifier for the task. |
|
||||
| **Agent** _(optional)_ | `agent` | `Optional[BaseAgent]` | The agent responsible for executing the task. |
|
||||
| **Tools** _(optional)_ | `tools` | `List[BaseTool]` | The tools/resources the agent is limited to use for this task. |
|
||||
| **Context** _(optional)_ | `context` | `Optional[List["Task"]]` | Other tasks whose outputs will be used as context for this task. |
|
||||
| **Async Execution** _(optional)_ | `async_execution` | `Optional[bool]` | Whether the task should be executed asynchronously. Defaults to False. |
|
||||
| **Human Input** _(optional)_ | `human_input` | `Optional[bool]` | Whether the task should have a human review the final answer of the agent. Defaults to False. |
|
||||
| **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. |
|
||||
|
||||
## Creating Tasks
|
||||
|
||||
@@ -52,7 +68,7 @@ There are two ways to create tasks in CrewAI: using **YAML configuration (recomm
|
||||
|
||||
Using YAML configuration provides a cleaner, more maintainable way to define tasks. We strongly recommend using this approach to define tasks in your CrewAI projects.
|
||||
|
||||
After creating your CrewAI project as outlined in the [Installation](/installation) section, navigate to the `src/latest_ai_development/config/tasks.yaml` file and modify the template to match your specific task requirements.
|
||||
After creating your CrewAI project as outlined in the [Installation](/en/installation) section, navigate to the `src/latest_ai_development/config/tasks.yaml` file and modify the template to match your specific task requirements.
|
||||
|
||||
<Note>
|
||||
Variables in your YAML files (like `{topic}`) will be replaced with values from your inputs when running the crew:
|
||||
@@ -68,7 +84,7 @@ research_task:
|
||||
description: >
|
||||
Conduct a thorough research about {topic}
|
||||
Make sure you find any interesting and relevant information given
|
||||
the current year is 2024.
|
||||
the current year is 2025.
|
||||
expected_output: >
|
||||
A list with 10 bullet points of the most relevant information about {topic}
|
||||
agent: researcher
|
||||
@@ -81,6 +97,7 @@ reporting_task:
|
||||
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
|
||||
```
|
||||
|
||||
@@ -100,7 +117,7 @@ class LatestAiDevelopmentCrew():
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'],
|
||||
config=self.agents_config['researcher'], # type: ignore[index]
|
||||
verbose=True,
|
||||
tools=[SerperDevTool()]
|
||||
)
|
||||
@@ -108,20 +125,20 @@ class LatestAiDevelopmentCrew():
|
||||
@agent
|
||||
def reporting_analyst(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['reporting_analyst'],
|
||||
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']
|
||||
config=self.tasks_config['research_task'] # type: ignore[index]
|
||||
)
|
||||
|
||||
@task
|
||||
def reporting_task(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['reporting_task']
|
||||
config=self.tasks_config['reporting_task'] # type: ignore[index]
|
||||
)
|
||||
|
||||
@crew
|
||||
@@ -154,7 +171,7 @@ 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 2024.
|
||||
the current year is 2025.
|
||||
""",
|
||||
expected_output="""
|
||||
A list with 10 bullet points of the most relevant information about AI Agents
|
||||
@@ -169,9 +186,9 @@ reporting_task = Task(
|
||||
""",
|
||||
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, # Enable markdown formatting for the final output
|
||||
output_file="report.md"
|
||||
)
|
||||
```
|
||||
@@ -244,6 +261,54 @@ if task_output.pydantic:
|
||||
print(f"Pydantic Output: {task_output.pydantic}")
|
||||
```
|
||||
|
||||
## Markdown Output Formatting
|
||||
|
||||
The `markdown` parameter enables automatic markdown formatting for task outputs. When set to `True`, the task will instruct the agent to format the final answer using proper Markdown syntax.
|
||||
|
||||
### Using Markdown Formatting
|
||||
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
When `markdown=True`, the agent will receive additional instructions to format the output using:
|
||||
- `#` for headers
|
||||
- `**text**` for bold text
|
||||
- `*text*` for italic text
|
||||
- `-` or `*` for bullet points
|
||||
- `` `code` `` for inline code
|
||||
- ``` ```language ``` for code blocks
|
||||
|
||||
### YAML Configuration with Markdown
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### Benefits of Markdown Output
|
||||
|
||||
- **Consistent Formatting**: Ensures all outputs follow proper markdown conventions
|
||||
- **Better Readability**: Structured content with headers, lists, and emphasis
|
||||
- **Documentation Ready**: Output can be directly used in documentation systems
|
||||
- **Cross-Platform Compatibility**: Markdown is universally supported
|
||||
|
||||
<Note>
|
||||
The markdown formatting instructions are automatically added to the task prompt when `markdown=True`, so you don't need to specify formatting requirements in your task description.
|
||||
</Note>
|
||||
|
||||
## Task Dependencies and Context
|
||||
|
||||
Tasks can depend on the output of other tasks using the `context` attribute. For example:
|
||||
@@ -267,34 +332,30 @@ analysis_task = Task(
|
||||
|
||||
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
|
||||
efeedback to agents when their output doesn't meet specific criteria.
|
||||
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
|
||||
from crewai import TaskOutput
|
||||
|
||||
def validate_blog_content(result: str) -> Tuple[bool, Union[Dict[str, Any], str]]:
|
||||
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, {
|
||||
"error": "Blog content exceeds 200 words",
|
||||
"code": "WORD_COUNT_ERROR",
|
||||
"context": {"word_count": word_count}
|
||||
})
|
||||
return (False, "Blog content exceeds 200 words")
|
||||
|
||||
# Additional validation logic here
|
||||
return (True, result.strip())
|
||||
except Exception as e:
|
||||
return (False, {
|
||||
"error": "Unexpected error during validation",
|
||||
"code": "SYSTEM_ERROR"
|
||||
})
|
||||
return (False, "Unexpected error during validation")
|
||||
|
||||
blog_task = Task(
|
||||
description="Write a blog post about AI",
|
||||
@@ -312,29 +373,26 @@ blog_task = Task(
|
||||
- Type hints are recommended but optional
|
||||
|
||||
2. **Return Values**:
|
||||
- Success: Return `(True, validated_result)`
|
||||
- Failure: Return `(False, error_details)`
|
||||
- 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")`
|
||||
|
||||
|
||||
|
||||
### Error Handling Best Practices
|
||||
|
||||
1. **Structured Error Responses**:
|
||||
```python Code
|
||||
def validate_with_context(result: str) -> Tuple[bool, Union[Dict[str, Any], str]]:
|
||||
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, {
|
||||
"error": str(e),
|
||||
"code": "VALIDATION_ERROR",
|
||||
"context": {"input": result}
|
||||
})
|
||||
return (False, f"VALIDATION_ERROR: {str(e)}")
|
||||
except Exception as e:
|
||||
return (False, {
|
||||
"error": "Unexpected error",
|
||||
"code": "SYSTEM_ERROR"
|
||||
})
|
||||
return (False, str(e))
|
||||
```
|
||||
|
||||
2. **Error Categories**:
|
||||
@@ -345,28 +403,25 @@ def validate_with_context(result: str) -> Tuple[bool, Union[Dict[str, Any], str]
|
||||
3. **Validation Chain**:
|
||||
```python Code
|
||||
from typing import Any, Dict, List, Tuple, Union
|
||||
from crewai import TaskOutput
|
||||
|
||||
def complex_validation(result: str) -> Tuple[bool, Union[str, Dict[str, Any]]]:
|
||||
def complex_validation(result: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""Chain multiple validation steps."""
|
||||
# Step 1: Basic validation
|
||||
if not result:
|
||||
return (False, {"error": "Empty result", "code": "EMPTY_INPUT"})
|
||||
return (False, "Empty result")
|
||||
|
||||
# Step 2: Content validation
|
||||
try:
|
||||
validated = validate_content(result)
|
||||
if not validated:
|
||||
return (False, {"error": "Invalid content", "code": "CONTENT_ERROR"})
|
||||
return (False, "Invalid content")
|
||||
|
||||
# Step 3: Format validation
|
||||
formatted = format_output(validated)
|
||||
return (True, formatted)
|
||||
except Exception as e:
|
||||
return (False, {
|
||||
"error": str(e),
|
||||
"code": "VALIDATION_ERROR",
|
||||
"context": {"step": "content_validation"}
|
||||
})
|
||||
return (False, str(e))
|
||||
```
|
||||
|
||||
### Handling Guardrail Results
|
||||
@@ -381,19 +436,16 @@ When a guardrail returns `(False, error)`:
|
||||
Example with retry handling:
|
||||
```python Code
|
||||
from typing import Optional, Tuple, Union
|
||||
from crewai import TaskOutput, Task
|
||||
|
||||
def validate_json_output(result: str) -> Tuple[bool, Union[Dict[str, Any], str]]:
|
||||
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, {
|
||||
"error": "Invalid JSON format",
|
||||
"code": "JSON_ERROR",
|
||||
"context": {"line": e.lineno, "column": e.colno}
|
||||
})
|
||||
return (False, "Invalid JSON format")
|
||||
|
||||
task = Task(
|
||||
description="Generate a JSON report",
|
||||
@@ -413,7 +465,7 @@ It's also important to note that the output of the final task of a crew becomes
|
||||
### Using `output_pydantic`
|
||||
The `output_pydantic` property allows you to define a Pydantic model that the task output should conform to. This ensures that the output is not only structured but also validated according to the Pydantic model.
|
||||
|
||||
Here’s an example demonstrating how to use output_pydantic:
|
||||
Here's an example demonstrating how to use output_pydantic:
|
||||
|
||||
```python Code
|
||||
import json
|
||||
@@ -494,7 +546,7 @@ In this example:
|
||||
### Using `output_json`
|
||||
The `output_json` property allows you to define the expected output in JSON format. This ensures that the task's output is a valid JSON structure that can be easily parsed and used in your application.
|
||||
|
||||
Here’s an example demonstrating how to use `output_json`:
|
||||
Here's an example demonstrating how to use `output_json`:
|
||||
|
||||
```python Code
|
||||
import json
|
||||
@@ -748,133 +800,106 @@ 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
|
||||
|
||||
```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
|
||||
)
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
<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>
|
||||
|
||||
## Conclusion
|
||||
|
||||
Tasks are the driving force behind the actions of agents in CrewAI.
|
||||
@@ -4,7 +4,7 @@ description: Learn how to test your CrewAI Crew and evaluate their performance.
|
||||
icon: vial
|
||||
---
|
||||
|
||||
## Introduction
|
||||
## Overview
|
||||
|
||||
Testing is a crucial part of the development process, and it is essential to ensure that your crew is performing as expected. With crewAI, you can easily test your crew and evaluate its performance using the built-in testing capabilities.
|
||||
|
||||
@@ -4,7 +4,7 @@ description: Understanding and leveraging tools within the CrewAI framework for
|
||||
icon: screwdriver-wrench
|
||||
---
|
||||
|
||||
## Introduction
|
||||
## Overview
|
||||
|
||||
CrewAI tools empower agents with capabilities ranging from web searching and data analysis to collaboration and delegating tasks among coworkers.
|
||||
This documentation outlines how to create, integrate, and leverage these tools within the CrewAI framework, including a new focus on collaboration tools.
|
||||
@@ -15,6 +15,16 @@ A tool in CrewAI is a skill or function that agents can utilize to perform vario
|
||||
This includes tools from the [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) and [LangChain Tools](https://python.langchain.com/docs/integrations/tools),
|
||||
enabling everything from simple searches to complex interactions and effective teamwork among agents.
|
||||
|
||||
<Note type="info" title="Enterprise Enhancement: Tools Repository">
|
||||
CrewAI Enterprise provides a comprehensive Tools Repository with pre-built integrations for common business systems and APIs. Deploy agents with enterprise tools in minutes instead of days.
|
||||
|
||||
The Enterprise Tools Repository includes:
|
||||
- Pre-built connectors for popular enterprise systems
|
||||
- Custom tool creation interface
|
||||
- Version control and sharing capabilities
|
||||
- Security and compliance features
|
||||
</Note>
|
||||
|
||||
## Key Characteristics of Tools
|
||||
|
||||
- **Utility**: Crafted for tasks such as web searching, data analysis, content generation, and agent collaboration.
|
||||
@@ -22,6 +32,7 @@ enabling everything from simple searches to complex interactions and effective t
|
||||
- **Customizability**: Provides the flexibility to develop custom tools or utilize existing ones, catering to the specific needs of agents.
|
||||
- **Error Handling**: Incorporates robust error handling mechanisms to ensure smooth operation.
|
||||
- **Caching Mechanism**: Features intelligent caching to optimize performance and reduce redundant operations.
|
||||
- **Asynchronous Support**: Handles both synchronous and asynchronous tools, enabling non-blocking operations.
|
||||
|
||||
## Using CrewAI Tools
|
||||
|
||||
@@ -79,7 +90,7 @@ research = Task(
|
||||
)
|
||||
|
||||
write = Task(
|
||||
description='Write an engaging blog post about the AI industry, based on the research analyst’s summary. Draw inspiration from the latest blog posts in the directory.',
|
||||
description='Write an engaging blog post about the AI industry, based on the research analyst's summary. Draw inspiration from the latest blog posts in the directory.',
|
||||
expected_output='A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.',
|
||||
agent=writer,
|
||||
output_file='blog-posts/new_post.md' # The final blog post will be saved here
|
||||
@@ -106,6 +117,7 @@ Here is a list of the available tools and their descriptions:
|
||||
|
||||
| Tool | Description |
|
||||
| :------------------------------- | :--------------------------------------------------------------------------------------------- |
|
||||
| **ApifyActorsTool** | A tool that integrates Apify Actors with your workflows for web scraping and automation tasks. |
|
||||
| **BrowserbaseLoadTool** | A tool for interacting with and extracting data from web browsers. |
|
||||
| **CodeDocsSearchTool** | A RAG tool optimized for searching through code documentation and related technical documents. |
|
||||
| **CodeInterpreterTool** | A tool for interpreting python code. |
|
||||
@@ -140,7 +152,7 @@ Here is a list of the available tools and their descriptions:
|
||||
## Creating your own Tools
|
||||
|
||||
<Tip>
|
||||
Developers can craft `custom tools` tailored for their agent’s needs or
|
||||
Developers can craft `custom tools` tailored for their agent's needs or
|
||||
utilize pre-built options.
|
||||
</Tip>
|
||||
|
||||
@@ -166,6 +178,62 @@ class MyCustomTool(BaseTool):
|
||||
return "Tool's result"
|
||||
```
|
||||
|
||||
## Asynchronous Tool Support
|
||||
|
||||
CrewAI supports asynchronous tools, allowing you to implement tools that perform non-blocking operations like network requests, file I/O, or other async operations without blocking the main execution thread.
|
||||
|
||||
### Creating Async Tools
|
||||
|
||||
You can create async tools in two ways:
|
||||
|
||||
#### 1. Using the `tool` Decorator with Async Functions
|
||||
|
||||
```python Code
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("fetch_data_async")
|
||||
async def fetch_data_async(query: str) -> str:
|
||||
"""Asynchronously fetch data based on the query."""
|
||||
# Simulate async operation
|
||||
await asyncio.sleep(1)
|
||||
return f"Data retrieved for {query}"
|
||||
```
|
||||
|
||||
#### 2. Implementing Async Methods in Custom Tool Classes
|
||||
|
||||
```python Code
|
||||
from crewai.tools import BaseTool
|
||||
|
||||
class AsyncCustomTool(BaseTool):
|
||||
name: str = "async_custom_tool"
|
||||
description: str = "An asynchronous custom tool"
|
||||
|
||||
async def _run(self, query: str = "") -> str:
|
||||
"""Asynchronously run the tool"""
|
||||
# Your async implementation here
|
||||
await asyncio.sleep(1)
|
||||
return f"Processed {query} asynchronously"
|
||||
```
|
||||
|
||||
### Using Async Tools
|
||||
|
||||
Async tools work seamlessly in both standard Crew workflows and Flow-based workflows:
|
||||
|
||||
```python Code
|
||||
# In standard Crew
|
||||
agent = Agent(role="researcher", tools=[async_custom_tool])
|
||||
|
||||
# In Flow
|
||||
class MyFlow(Flow):
|
||||
@start()
|
||||
async def begin(self):
|
||||
crew = Crew(agents=[agent])
|
||||
result = await crew.kickoff_async()
|
||||
return result
|
||||
```
|
||||
|
||||
The CrewAI framework automatically handles the execution of both synchronous and asynchronous tools, so you don't need to worry about how to call them differently.
|
||||
|
||||
### Utilizing the `tool` Decorator
|
||||
|
||||
```python Code
|
||||
@@ -177,48 +245,6 @@ def my_tool(question: str) -> str:
|
||||
return "Result from your custom tool"
|
||||
```
|
||||
|
||||
### Structured Tools
|
||||
|
||||
The `StructuredTool` class wraps functions as tools, providing flexibility and validation while reducing boilerplate. It supports custom schemas and dynamic logic for seamless integration of complex functionalities.
|
||||
|
||||
#### Example:
|
||||
Using `StructuredTool.from_function`, you can wrap a function that interacts with an external API or system, providing a structured interface. This enables robust validation and consistent execution, making it easier to integrate complex functionalities into your applications as demonstrated in the following example:
|
||||
|
||||
```python
|
||||
from crewai.tools.structured_tool import CrewStructuredTool
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Define the schema for the tool's input using Pydantic
|
||||
class APICallInput(BaseModel):
|
||||
endpoint: str
|
||||
parameters: dict
|
||||
|
||||
# Wrapper function to execute the API call
|
||||
def tool_wrapper(*args, **kwargs):
|
||||
# Here, you would typically call the API using the parameters
|
||||
# For demonstration, we'll return a placeholder string
|
||||
return f"Call the API at {kwargs['endpoint']} with parameters {kwargs['parameters']}"
|
||||
|
||||
# Create and return the structured tool
|
||||
def create_structured_tool():
|
||||
return CrewStructuredTool.from_function(
|
||||
name='Wrapper API',
|
||||
description="A tool to wrap API calls with structured input.",
|
||||
args_schema=APICallInput,
|
||||
func=tool_wrapper,
|
||||
)
|
||||
|
||||
# Example usage
|
||||
structured_tool = create_structured_tool()
|
||||
|
||||
# Execute the tool with structured input
|
||||
result = structured_tool._run(**{
|
||||
"endpoint": "https://example.com/api",
|
||||
"parameters": {"key1": "value1", "key2": "value2"}
|
||||
})
|
||||
print(result) # Output: Call the API at https://example.com/api with parameters {'key1': 'value1', 'key2': 'value2'}
|
||||
```
|
||||
|
||||
### Custom Caching Mechanism
|
||||
|
||||
<Tip>
|
||||
131
docs/en/concepts/training.mdx
Normal file
131
docs/en/concepts/training.mdx
Normal file
@@ -0,0 +1,131 @@
|
||||
---
|
||||
title: Training
|
||||
description: Learn how to train your CrewAI agents by giving them feedback early on and get consistent results.
|
||||
icon: dumbbell
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The training feature in CrewAI allows you to train your AI agents using the command-line interface (CLI).
|
||||
By running the command `crewai train -n <n_iterations>`, you can specify the number of iterations for the training process.
|
||||
|
||||
During training, CrewAI utilizes techniques to optimize the performance of your agents along with human feedback.
|
||||
This helps the agents improve their understanding, decision-making, and problem-solving abilities.
|
||||
|
||||
### Training Your Crew Using the CLI
|
||||
|
||||
To use the training feature, follow these steps:
|
||||
|
||||
1. Open your terminal or command prompt.
|
||||
2. Navigate to the directory where your CrewAI project is located.
|
||||
3. Run the following command:
|
||||
|
||||
```shell
|
||||
crewai train -n <n_iterations> <filename> (optional)
|
||||
```
|
||||
<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
|
||||
|
||||
To train your crew programmatically, use the following steps:
|
||||
|
||||
1. Define the number of iterations for training.
|
||||
2. Specify the input parameters for the training process.
|
||||
3. Execute the training command within a try-except block to handle potential errors.
|
||||
|
||||
```python Code
|
||||
n_iterations = 2
|
||||
inputs = {"topic": "CrewAI Training"}
|
||||
filename = "your_model.pkl"
|
||||
|
||||
try:
|
||||
YourCrewName_Crew().crew().train(
|
||||
n_iterations=n_iterations,
|
||||
inputs=inputs,
|
||||
filename=filename
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"An error occurred while training the crew: {e}")
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
Happy training with CrewAI! 🚀
|
||||
|
||||
## Small Language Model Considerations
|
||||
|
||||
<Warning>
|
||||
When using smaller language models (≤7B parameters) for training data evaluation, be aware that they may face challenges with generating structured outputs and following complex instructions.
|
||||
</Warning>
|
||||
|
||||
### Limitations of Small Models in Training Evaluation
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="JSON Output Accuracy" icon="triangle-exclamation">
|
||||
Smaller models often struggle with producing valid JSON responses needed for structured training evaluations, leading to parsing errors and incomplete data.
|
||||
</Card>
|
||||
<Card title="Evaluation Quality" icon="chart-line">
|
||||
Models under 7B parameters may provide less nuanced evaluations with limited reasoning depth compared to larger models.
|
||||
</Card>
|
||||
<Card title="Instruction Following" icon="list-check">
|
||||
Complex training evaluation criteria may not be fully followed or considered by smaller models.
|
||||
</Card>
|
||||
<Card title="Consistency" icon="rotate">
|
||||
Evaluations across multiple training iterations may lack consistency with smaller models.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Recommendations for Training
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Best Practice">
|
||||
For optimal training quality and reliable evaluations, we strongly recommend using models with at least 7B parameters or larger:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task, LLM
|
||||
|
||||
# Recommended minimum for training evaluation
|
||||
llm = LLM(model="mistral/open-mistral-7b")
|
||||
|
||||
# Better options for reliable training evaluation
|
||||
llm = LLM(model="anthropic/claude-3-sonnet-20240229-v1:0")
|
||||
llm = LLM(model="gpt-4o")
|
||||
|
||||
# Use this LLM with your agents
|
||||
agent = Agent(
|
||||
role="Training Evaluator",
|
||||
goal="Provide accurate training feedback",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
More powerful models provide higher quality feedback with better reasoning, leading to more effective training iterations.
|
||||
</Tip>
|
||||
</Tab>
|
||||
<Tab title="Small Model Usage">
|
||||
If you must use smaller models for training evaluation, be aware of these constraints:
|
||||
|
||||
```python
|
||||
# Using a smaller model (expect some limitations)
|
||||
llm = LLM(model="huggingface/microsoft/Phi-3-mini-4k-instruct")
|
||||
```
|
||||
|
||||
<Warning>
|
||||
While CrewAI includes optimizations for small models, expect less reliable and less nuanced evaluation results that may require more human intervention during training.
|
||||
</Warning>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
155
docs/en/enterprise/features/agent-repositories.mdx
Normal file
155
docs/en/enterprise/features/agent-repositories.mdx
Normal file
@@ -0,0 +1,155 @@
|
||||
---
|
||||
title: 'Agent Repositories'
|
||||
description: 'Learn how to use Agent Repositories to share and reuse your agents across teams and projects'
|
||||
icon: 'database'
|
||||
---
|
||||
|
||||
Agent Repositories allow enterprise users to store, share, and reuse agent definitions across teams and projects. This feature enables organizations to maintain a centralized library of standardized agents, promoting consistency and reducing duplication of effort.
|
||||
|
||||
## Benefits of Agent Repositories
|
||||
|
||||
- **Standardization**: Maintain consistent agent definitions across your organization
|
||||
- **Reusability**: Create an agent once and use it in multiple crews and projects
|
||||
- **Governance**: Implement organization-wide policies for agent configurations
|
||||
- **Collaboration**: Enable teams to share and build upon each other's work
|
||||
|
||||
## Using Agent Repositories
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. You must have an account at CrewAI, try the [free plan](https://app.crewai.com).
|
||||
2. You need to be authenticated using the CrewAI CLI.
|
||||
3. If you have more than one organization, make sure you are switched to the correct organization using the CLI command:
|
||||
|
||||
```bash
|
||||
crewai org switch <org_id>
|
||||
```
|
||||
|
||||
### Creating and Managing Agents in Repositories
|
||||
|
||||
To create and manage agents in repositories,Enterprise Dashboard.
|
||||
|
||||
### Loading Agents from Repositories
|
||||
|
||||
You can load agents from repositories in your code using the `from_repository` parameter:
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
# Create an agent by loading it from a repository
|
||||
# The agent is loaded with all its predefined configurations
|
||||
researcher = Agent(
|
||||
from_repository="market-research-agent"
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
### Overriding Repository Settings
|
||||
|
||||
You can override specific settings from the repository by providing them in the configuration:
|
||||
|
||||
```python
|
||||
researcher = Agent(
|
||||
from_repository="market-research-agent",
|
||||
goal="Research the latest trends in AI development", # Override the repository goal
|
||||
verbose=True # Add a setting not in the repository
|
||||
)
|
||||
```
|
||||
|
||||
### Example: Creating a Crew with Repository Agents
|
||||
|
||||
```python
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
# Load agents from repositories
|
||||
researcher = Agent(
|
||||
from_repository="market-research-agent"
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
from_repository="content-writer-agent"
|
||||
)
|
||||
|
||||
# Create tasks
|
||||
research_task = Task(
|
||||
description="Research the latest trends in AI",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description="Write a comprehensive report based on the research",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Create the crew
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, writing_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run the crew
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### Example: Using `kickoff()` with Repository Agents
|
||||
|
||||
You can also use repository agents directly with the `kickoff()` method for simpler interactions:
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
|
||||
# Define a structured output format
|
||||
class MarketAnalysis(BaseModel):
|
||||
key_trends: List[str]
|
||||
opportunities: List[str]
|
||||
recommendation: str
|
||||
|
||||
# Load an agent from repository
|
||||
analyst = Agent(
|
||||
from_repository="market-analyst-agent",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Get a free-form response
|
||||
result = analyst.kickoff("Analyze the AI market in 2025")
|
||||
print(result.raw) # Access the raw response
|
||||
|
||||
# Get structured output
|
||||
structured_result = analyst.kickoff(
|
||||
"Provide a structured analysis of the AI market in 2025",
|
||||
response_format=MarketAnalysis
|
||||
)
|
||||
|
||||
# Access structured data
|
||||
print(f"Key Trends: {structured_result.pydantic.key_trends}")
|
||||
print(f"Recommendation: {structured_result.pydantic.recommendation}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Naming Convention**: Use clear, descriptive names for your repository agents
|
||||
2. **Documentation**: Include comprehensive descriptions for each agent
|
||||
3. **Tool Management**: Ensure that tools referenced by repository agents are available in your environment
|
||||
4. **Access Control**: Manage permissions to ensure only authorized team members can modify repository agents
|
||||
|
||||
## Organization Management
|
||||
|
||||
To switch between organizations or see your current organization, use the CrewAI CLI:
|
||||
|
||||
```bash
|
||||
# View current organization
|
||||
crewai org current
|
||||
|
||||
# Switch to a different organization
|
||||
crewai org switch <org_id>
|
||||
|
||||
# List all available organizations
|
||||
crewai org list
|
||||
```
|
||||
|
||||
<Note>
|
||||
When loading agents from repositories, you must be authenticated and switched to the correct organization. If you receive errors, check your authentication status and organization settings using the CLI commands above.
|
||||
</Note>
|
||||
250
docs/en/enterprise/features/hallucination-guardrail.mdx
Normal file
250
docs/en/enterprise/features/hallucination-guardrail.mdx
Normal file
@@ -0,0 +1,250 @@
|
||||
---
|
||||
title: Hallucination Guardrail
|
||||
description: "Prevent and detect AI hallucinations in your CrewAI tasks"
|
||||
icon: "shield-check"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Hallucination Guardrail is an enterprise feature that validates AI-generated content to ensure it's grounded in facts and doesn't contain hallucinations. It analyzes task outputs against reference context and provides detailed feedback when potentially hallucinated content is detected.
|
||||
|
||||
## What are Hallucinations?
|
||||
|
||||
AI hallucinations occur when language models generate content that appears plausible but is factually incorrect or not supported by the provided context. The Hallucination Guardrail helps prevent these issues by:
|
||||
|
||||
- Comparing outputs against reference context
|
||||
- Evaluating faithfulness to source material
|
||||
- Providing detailed feedback on problematic content
|
||||
- Supporting custom thresholds for validation strictness
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Setting Up the Guardrail
|
||||
|
||||
```python
|
||||
from crewai.tasks.hallucination_guardrail import HallucinationGuardrail
|
||||
from crewai import LLM
|
||||
|
||||
# Basic usage - will use task's expected_output as context
|
||||
guardrail = HallucinationGuardrail(
|
||||
llm=LLM(model="gpt-4o-mini")
|
||||
)
|
||||
|
||||
# With explicit reference context
|
||||
context_guardrail = HallucinationGuardrail(
|
||||
context="AI helps with various tasks including analysis and generation.",
|
||||
llm=LLM(model="gpt-4o-mini")
|
||||
)
|
||||
```
|
||||
|
||||
### Adding to Tasks
|
||||
|
||||
```python
|
||||
from crewai import Task
|
||||
|
||||
# Create your task with the guardrail
|
||||
task = Task(
|
||||
description="Write a summary about AI capabilities",
|
||||
expected_output="A factual summary based on the provided context",
|
||||
agent=my_agent,
|
||||
guardrail=guardrail # Add the guardrail to validate output
|
||||
)
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Custom Threshold Validation
|
||||
|
||||
For stricter validation, you can set a custom faithfulness threshold (0-10 scale):
|
||||
|
||||
```python
|
||||
# Strict guardrail requiring high faithfulness score
|
||||
strict_guardrail = HallucinationGuardrail(
|
||||
context="Quantum computing uses qubits that exist in superposition states.",
|
||||
llm=LLM(model="gpt-4o-mini"),
|
||||
threshold=8.0 # Requires score >= 8 to pass validation
|
||||
)
|
||||
```
|
||||
|
||||
### Including Tool Response Context
|
||||
|
||||
When your task uses tools, you can include tool responses for more accurate validation:
|
||||
|
||||
```python
|
||||
# Guardrail with tool response context
|
||||
weather_guardrail = HallucinationGuardrail(
|
||||
context="Current weather information for the requested location",
|
||||
llm=LLM(model="gpt-4o-mini"),
|
||||
tool_response="Weather API returned: Temperature 22°C, Humidity 65%, Clear skies"
|
||||
)
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### Validation Process
|
||||
|
||||
1. **Context Analysis**: The guardrail compares task output against the provided reference context
|
||||
2. **Faithfulness Scoring**: Uses an internal evaluator to assign a faithfulness score (0-10)
|
||||
3. **Verdict Determination**: Determines if content is faithful or contains hallucinations
|
||||
4. **Threshold Checking**: If a custom threshold is set, validates against that score
|
||||
5. **Feedback Generation**: Provides detailed reasons when validation fails
|
||||
|
||||
### Validation Logic
|
||||
|
||||
- **Default Mode**: Uses verdict-based validation (FAITHFUL vs HALLUCINATED)
|
||||
- **Threshold Mode**: Requires faithfulness score to meet or exceed the specified threshold
|
||||
- **Error Handling**: Gracefully handles evaluation errors and provides informative feedback
|
||||
|
||||
## Guardrail Results
|
||||
|
||||
The guardrail returns structured results indicating validation status:
|
||||
|
||||
```python
|
||||
# Example of guardrail result structure
|
||||
{
|
||||
"valid": False,
|
||||
"feedback": "Content appears to be hallucinated (score: 4.2/10, verdict: HALLUCINATED). The output contains information not supported by the provided context."
|
||||
}
|
||||
```
|
||||
|
||||
### Result Properties
|
||||
|
||||
- **valid**: Boolean indicating whether the output passed validation
|
||||
- **feedback**: Detailed explanation when validation fails, including:
|
||||
- Faithfulness score
|
||||
- Verdict classification
|
||||
- Specific reasons for failure
|
||||
|
||||
## Integration with Task System
|
||||
|
||||
### Automatic Validation
|
||||
|
||||
When a guardrail is added to a task, it automatically validates the output before the task is marked as complete:
|
||||
|
||||
```python
|
||||
# Task output validation flow
|
||||
task_output = agent.execute_task(task)
|
||||
validation_result = guardrail(task_output)
|
||||
|
||||
if validation_result.valid:
|
||||
# Task completes successfully
|
||||
return task_output
|
||||
else:
|
||||
# Task fails with validation feedback
|
||||
raise ValidationError(validation_result.feedback)
|
||||
```
|
||||
|
||||
### Event Tracking
|
||||
|
||||
The guardrail integrates with CrewAI's event system to provide observability:
|
||||
|
||||
- **Validation Started**: When guardrail evaluation begins
|
||||
- **Validation Completed**: When evaluation finishes with results
|
||||
- **Validation Failed**: When technical errors occur during evaluation
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Context Guidelines
|
||||
|
||||
<Steps>
|
||||
<Step title="Provide Comprehensive Context">
|
||||
Include all relevant factual information that the AI should base its output on:
|
||||
|
||||
```python
|
||||
context = """
|
||||
Company XYZ was founded in 2020 and specializes in renewable energy solutions.
|
||||
They have 150 employees and generated $50M revenue in 2023.
|
||||
Their main products include solar panels and wind turbines.
|
||||
"""
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Keep Context Relevant">
|
||||
Only include information directly related to the task to avoid confusion:
|
||||
|
||||
```python
|
||||
# Good: Focused context
|
||||
context = "The current weather in New York is 18°C with light rain."
|
||||
|
||||
# Avoid: Unrelated information
|
||||
context = "The weather is 18°C. The city has 8 million people. Traffic is heavy."
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Update Context Regularly">
|
||||
Ensure your reference context reflects current, accurate information.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Threshold Selection
|
||||
|
||||
<Steps>
|
||||
<Step title="Start with Default Validation">
|
||||
Begin without custom thresholds to understand baseline performance.
|
||||
</Step>
|
||||
|
||||
<Step title="Adjust Based on Requirements">
|
||||
- **High-stakes content**: Use threshold 8-10 for maximum accuracy
|
||||
- **General content**: Use threshold 6-7 for balanced validation
|
||||
- **Creative content**: Use threshold 4-5 or default verdict-based validation
|
||||
</Step>
|
||||
|
||||
<Step title="Monitor and Iterate">
|
||||
Track validation results and adjust thresholds based on false positives/negatives.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Impact on Execution Time
|
||||
|
||||
- **Validation Overhead**: Each guardrail adds ~1-3 seconds per task
|
||||
- **LLM Efficiency**: Choose efficient models for evaluation (e.g., gpt-4o-mini)
|
||||
|
||||
### Cost Optimization
|
||||
|
||||
- **Model Selection**: Use smaller, efficient models for guardrail evaluation
|
||||
- **Context Size**: Keep reference context concise but comprehensive
|
||||
- **Caching**: Consider caching validation results for repeated content
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<Accordion title="Validation Always Fails">
|
||||
**Possible Causes:**
|
||||
- Context is too restrictive or unrelated to task output
|
||||
- Threshold is set too high for the content type
|
||||
- Reference context contains outdated information
|
||||
|
||||
**Solutions:**
|
||||
- Review and update context to match task requirements
|
||||
- Lower threshold or use default verdict-based validation
|
||||
- Ensure context is current and accurate
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="False Positives (Valid Content Marked Invalid)">
|
||||
**Possible Causes:**
|
||||
- Threshold too high for creative or interpretive tasks
|
||||
- Context doesn't cover all valid aspects of the output
|
||||
- Evaluation model being overly conservative
|
||||
|
||||
**Solutions:**
|
||||
- Lower threshold or use default validation
|
||||
- Expand context to include broader acceptable content
|
||||
- Test with different evaluation models
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Evaluation Errors">
|
||||
**Possible Causes:**
|
||||
- Network connectivity issues
|
||||
- LLM model unavailable or rate limited
|
||||
- Malformed task output or context
|
||||
|
||||
**Solutions:**
|
||||
- Check network connectivity and LLM service status
|
||||
- Implement retry logic for transient failures
|
||||
- Validate task output format before guardrail evaluation
|
||||
</Accordion>
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with hallucination guardrail configuration or troubleshooting.
|
||||
</Card>
|
||||
185
docs/en/enterprise/features/integrations.mdx
Normal file
185
docs/en/enterprise/features/integrations.mdx
Normal file
@@ -0,0 +1,185 @@
|
||||
---
|
||||
title: Integrations
|
||||
description: "Connected applications for your agents to take actions."
|
||||
icon: "plug"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to authenticate with any OAuth enabled provider and take actions. From Salesforce and HubSpot to Google and GitHub, we've got you covered with 16+ integrated services.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## Supported Integrations
|
||||
|
||||
### **Communication & Collaboration**
|
||||
- **Gmail** - Manage emails and drafts
|
||||
- **Slack** - Workspace notifications and alerts
|
||||
- **Microsoft** - Office 365 and Teams integration
|
||||
|
||||
### **Project Management**
|
||||
- **Jira** - Issue tracking and project management
|
||||
- **ClickUp** - Task and productivity management
|
||||
- **Asana** - Team task and project coordination
|
||||
- **Notion** - Page and database management
|
||||
- **Linear** - Software project and bug tracking
|
||||
- **GitHub** - Repository and issue management
|
||||
|
||||
### **Customer Relationship Management**
|
||||
- **Salesforce** - CRM account and opportunity management
|
||||
- **HubSpot** - Sales pipeline and contact management
|
||||
- **Zendesk** - Customer support ticket management
|
||||
|
||||
### **Business & Finance**
|
||||
- **Stripe** - Payment processing and customer management
|
||||
- **Shopify** - E-commerce store and product management
|
||||
|
||||
### **Productivity & Storage**
|
||||
- **Google Sheets** - Spreadsheet data synchronization
|
||||
- **Google Calendar** - Event and schedule management
|
||||
- **Box** - File storage and document management
|
||||
|
||||
and more to come!
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using Authentication Integrations, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account. You can get started with a free trial.
|
||||
|
||||
|
||||
## Setting Up Integrations
|
||||
|
||||
### 1. Connect Your Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise](https://app.crewai.com)
|
||||
2. Go to **Integrations** tab - https://app.crewai.com/crewai_plus/connectors
|
||||
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
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### 2. Install Integration Tools
|
||||
|
||||
All you need is the latest version of `crewai-tools` package.
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Usage
|
||||
<Tip>
|
||||
All the services you are authenticated into will be available as tools. So all you need to do is add the `CrewaiEnterpriseTools` to your agent and you are good to go.
|
||||
</Tip>
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Gmail tool will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
# print the tools
|
||||
print(enterprise_tools)
|
||||
|
||||
# Create an agent with Gmail capabilities
|
||||
email_agent = Agent(
|
||||
role="Email Manager",
|
||||
goal="Manage and organize email communications",
|
||||
backstory="An AI assistant specialized in email management and communication.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to send an email
|
||||
email_task = Task(
|
||||
description="Draft and send a follow-up email to john@example.com about the project update",
|
||||
agent=email_agent,
|
||||
expected_output="Confirmation that email was sent successfully"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[email_agent],
|
||||
tasks=[email_task]
|
||||
)
|
||||
|
||||
# Run the crew
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
actions_list=["gmail_find_email"] # only gmail_find_email tool will be available
|
||||
)
|
||||
gmail_tool = enterprise_tools["gmail_find_email"]
|
||||
|
||||
gmail_agent = Agent(
|
||||
role="Gmail Manager",
|
||||
goal="Manage gmail communications and notifications",
|
||||
backstory="An AI assistant that helps coordinate gmail communications.",
|
||||
tools=[gmail_tool]
|
||||
)
|
||||
|
||||
notification_task = Task(
|
||||
description="Find the email from john@example.com",
|
||||
agent=gmail_agent,
|
||||
expected_output="Email found from john@example.com"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[slack_agent],
|
||||
tasks=[notification_task]
|
||||
)
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Security
|
||||
- **Principle of Least Privilege**: Only grant the minimum permissions required for your agents' tasks
|
||||
- **Regular Audits**: Periodically review connected integrations and their permissions
|
||||
- **Secure Credentials**: Never hardcode credentials; use CrewAI's secure authentication flow
|
||||
|
||||
|
||||
### Filtering Tools
|
||||
On a deployed crew, you can specify which actions are avialbel for each integration from the settings page of the service you connected to.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
|
||||
### Scoped Deployments for multi user organizations
|
||||
You can deploy your crew and scope each integration to a specific user. For example, a crew that connects to google can use a specific user's gmail account.
|
||||
|
||||
<Tip>
|
||||
This is useful for multi user organizations where you want to scope the integration to a specific user.
|
||||
</Tip>
|
||||
|
||||
|
||||
Use the `user_bearer_token` to scope the integration to a specific user so that when the crew is kicked off, it will use the user's bearer token to authenticate with the integration. If user is not logged in, then the crew will not use any connected integrations. Use the default bearer token to authenticate with the integrations thats deployed with the crew.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with integration setup or troubleshooting.
|
||||
</Card>
|
||||
107
docs/en/enterprise/features/tool-repository.mdx
Normal file
107
docs/en/enterprise/features/tool-repository.mdx
Normal file
@@ -0,0 +1,107 @@
|
||||
---
|
||||
title: Tool Repository
|
||||
description: "Using the Tool Repository to manage your tools"
|
||||
icon: "toolbox"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Tool Repository is a package manager for CrewAI tools. It allows users to publish, install, and manage tools that integrate with CrewAI crews and flows.
|
||||
|
||||
Tools can be:
|
||||
|
||||
- **Private**: accessible only within your organization (default)
|
||||
- **Public**: accessible to all CrewAI users if published with the `--public` flag
|
||||
|
||||
The repository is not a version control system. Use Git to track code changes and enable collaboration.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Tool Repository, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account
|
||||
- [CrewAI CLI](https://docs.crewai.com/concepts/cli#cli) installed
|
||||
- uv>=0.5.0 installed. Check out [how to upgrade](https://docs.astral.sh/uv/getting-started/installation/#upgrading-uv)
|
||||
- [Git](https://git-scm.com) installed and configured
|
||||
- Access permissions to publish or install tools in your CrewAI Enterprise organization
|
||||
|
||||
## Installing Tools
|
||||
|
||||
To install a tool:
|
||||
|
||||
```bash
|
||||
crewai tool install <tool-name>
|
||||
```
|
||||
|
||||
This installs the tool and adds it to `pyproject.toml`.
|
||||
|
||||
## Creating and Publishing Tools
|
||||
|
||||
To create a new tool project:
|
||||
|
||||
```bash
|
||||
crewai tool create <tool-name>
|
||||
```
|
||||
|
||||
This generates a scaffolded tool project locally.
|
||||
|
||||
After making changes, initialize a Git repository and commit the code:
|
||||
|
||||
```bash
|
||||
git init
|
||||
git add .
|
||||
git commit -m "Initial version"
|
||||
```
|
||||
|
||||
To publish the tool:
|
||||
|
||||
```bash
|
||||
crewai tool publish
|
||||
```
|
||||
|
||||
By default, tools are published as private. To make a tool public:
|
||||
|
||||
```bash
|
||||
crewai tool publish --public
|
||||
```
|
||||
|
||||
For more details on how to build tools, see [Creating your own tools](https://docs.crewai.com/concepts/tools#creating-your-own-tools).
|
||||
|
||||
## Updating Tools
|
||||
|
||||
To update a published tool:
|
||||
|
||||
1. Modify the tool locally
|
||||
2. Update the version in `pyproject.toml` (e.g., from `0.1.0` to `0.1.1`)
|
||||
3. Commit the changes and publish
|
||||
|
||||
```bash
|
||||
git commit -m "Update version to 0.1.1"
|
||||
crewai tool publish
|
||||
```
|
||||
|
||||
## Deleting Tools
|
||||
|
||||
To delete a tool:
|
||||
|
||||
1. Go to [CrewAI Enterprise](https://app.crewai.com)
|
||||
2. Navigate to **Tools**
|
||||
3. Select the tool
|
||||
4. Click **Delete**
|
||||
|
||||
<Warning>
|
||||
Deletion is permanent. Deleted tools cannot be restored or re-installed.
|
||||
</Warning>
|
||||
|
||||
## Security Checks
|
||||
|
||||
Every published version undergoes automated security checks, and are only available to install after they pass.
|
||||
|
||||
You can check the security check status of a tool at:
|
||||
|
||||
`CrewAI Enterprise > Tools > Your Tool > Versions`
|
||||
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with API integration or troubleshooting.
|
||||
</Card>
|
||||
146
docs/en/enterprise/features/traces.mdx
Normal file
146
docs/en/enterprise/features/traces.mdx
Normal file
@@ -0,0 +1,146 @@
|
||||
---
|
||||
title: Traces
|
||||
description: "Using Traces to monitor your Crews"
|
||||
icon: "timeline"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Traces provide comprehensive visibility into your crew executions, helping you monitor performance, debug issues, and optimize your AI agent workflows.
|
||||
|
||||
## What are Traces?
|
||||
|
||||
Traces in CrewAI Enterprise are detailed execution records that capture every aspect of your crew's operation, from initial inputs to final outputs. They record:
|
||||
|
||||
- Agent thoughts and reasoning
|
||||
- Task execution details
|
||||
- Tool usage and outputs
|
||||
- Token consumption metrics
|
||||
- Execution times
|
||||
- Cost estimates
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## Accessing Traces
|
||||
|
||||
<Steps>
|
||||
<Step title="Navigate to the Traces Tab">
|
||||
Once in your CrewAI Enterprise dashboard, click on the **Traces** to view all execution records.
|
||||
</Step>
|
||||
|
||||
<Step title="Select an Execution">
|
||||
You'll see a list of all crew executions, sorted by date. Click on any execution to view its detailed trace.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding the Trace Interface
|
||||
|
||||
The trace interface is divided into several sections, each providing different insights into your crew's execution:
|
||||
|
||||
### 1. Execution Summary
|
||||
|
||||
The top section displays high-level metrics about the execution:
|
||||
|
||||
- **Total Tokens**: Number of tokens consumed across all tasks
|
||||
- **Prompt Tokens**: Tokens used in prompts to the LLM
|
||||
- **Completion Tokens**: Tokens generated in LLM responses
|
||||
- **Requests**: Number of API calls made
|
||||
- **Execution Time**: Total duration of the crew run
|
||||
- **Estimated Cost**: Approximate cost based on token usage
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### 2. Tasks & Agents
|
||||
|
||||
This section shows all tasks and agents that were part of the crew execution:
|
||||
|
||||
- Task name and agent assignment
|
||||
- Agents and LLMs used for each task
|
||||
- Status (completed/failed)
|
||||
- Individual execution time of the task
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### 3. Final Output
|
||||
|
||||
Displays the final result produced by the crew after all tasks are completed.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### 4. Execution Timeline
|
||||
|
||||
A visual representation of when each task started and ended, helping you identify bottlenecks or parallel execution patterns.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### 5. Detailed Task View
|
||||
|
||||
When you click on a specific task in the timeline or task list, you'll see:
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
- **Task Key**: Unique identifier for the task
|
||||
- **Task ID**: Technical identifier in the system
|
||||
- **Status**: Current state (completed/running/failed)
|
||||
- **Agent**: Which agent performed the task
|
||||
- **LLM**: Language model used for this task
|
||||
- **Start/End Time**: When the task began and completed
|
||||
- **Execution Time**: Duration of this specific task
|
||||
- **Task Description**: What the agent was instructed to do
|
||||
- **Expected Output**: What output format was requested
|
||||
- **Input**: Any input provided to this task from previous tasks
|
||||
- **Output**: The actual result produced by the agent
|
||||
|
||||
|
||||
## Using Traces for Debugging
|
||||
|
||||
Traces are invaluable for troubleshooting issues with your crews:
|
||||
|
||||
<Steps>
|
||||
<Step title="Identify Failure Points">
|
||||
When a crew execution doesn't produce the expected results, examine the trace to find where things went wrong. Look for:
|
||||
|
||||
- Failed tasks
|
||||
- Unexpected agent decisions
|
||||
- Tool usage errors
|
||||
- Misinterpreted instructions
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Optimize Performance">
|
||||
Use execution metrics to identify performance bottlenecks:
|
||||
|
||||
- Tasks that took longer than expected
|
||||
- Excessive token usage
|
||||
- Redundant tool operations
|
||||
- Unnecessary API calls
|
||||
</Step>
|
||||
|
||||
<Step title="Improve Cost Efficiency">
|
||||
Analyze token usage and cost estimates to optimize your crew's efficiency:
|
||||
|
||||
- Consider using smaller models for simpler tasks
|
||||
- Refine prompts to be more concise
|
||||
- Cache frequently accessed information
|
||||
- Structure tasks to minimize redundant operations
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<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>
|
||||
82
docs/en/enterprise/features/webhook-streaming.mdx
Normal file
82
docs/en/enterprise/features/webhook-streaming.mdx
Normal file
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Webhook Streaming
|
||||
description: "Using Webhook Streaming to stream events to your webhook"
|
||||
icon: "webhook"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enterprise Event Streaming lets you receive real-time webhook updates about your crews and flows deployed to
|
||||
CrewAI Enterprise, such as model calls, tool usage, and flow steps.
|
||||
|
||||
## Usage
|
||||
|
||||
When using the Kickoff API, include a `webhooks` object to your request, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"inputs": {"foo": "bar"},
|
||||
"webhooks": {
|
||||
"events": ["crew_kickoff_started", "llm_call_started"],
|
||||
"url": "https://your.endpoint/webhook",
|
||||
"realtime": false,
|
||||
"authentication": {
|
||||
"strategy": "bearer",
|
||||
"token": "my-secret-token"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If `realtime` is set to `true`, each event is delivered individually and immediately, at the cost of crew/flow performance.
|
||||
|
||||
## Webhook Format
|
||||
|
||||
Each webhook sends a list of events:
|
||||
|
||||
```json
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"id": "event-id",
|
||||
"execution_id": "crew-run-id",
|
||||
"timestamp": "2025-02-16T10:58:44.965Z",
|
||||
"type": "llm_call_started",
|
||||
"data": {
|
||||
"model": "gpt-4",
|
||||
"messages": [
|
||||
{"role": "system", "content": "You are an assistant."},
|
||||
{"role": "user", "content": "Summarize this article."}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The `data` object structure varies by event type. Refer to the [event list](https://github.com/crewAIInc/crewAI/tree/main/src/crewai/utilities/events) on GitHub.
|
||||
|
||||
As requests are sent over HTTP, the order of events can't be guaranteed. If you need ordering, use the `timestamp` field.
|
||||
|
||||
## Supported Events
|
||||
|
||||
CrewAI supports both system events and custom events in Enterprise Event Streaming. These events are sent to your configured webhook endpoint during crew and flow execution.
|
||||
|
||||
- `crew_kickoff_started`
|
||||
- `crew_step_started`
|
||||
- `crew_step_completed`
|
||||
- `crew_execution_completed`
|
||||
- `llm_call_started`
|
||||
- `llm_call_completed`
|
||||
- `tool_usage_started`
|
||||
- `tool_usage_completed`
|
||||
- `crew_test_failed`
|
||||
- *...and others*
|
||||
|
||||
Event names match the internal event bus. See [GitHub source](https://github.com/crewAIInc/crewAI/tree/main/src/crewai/utilities/events) for the full list.
|
||||
|
||||
You can emit your own custom events, and they will be delivered through the webhook stream alongside system events.
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with webhook integration or troubleshooting.
|
||||
</Card>
|
||||
51
docs/en/enterprise/guides/azure-openai-setup.mdx
Normal file
51
docs/en/enterprise/guides/azure-openai-setup.mdx
Normal file
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: "Azure OpenAI Setup"
|
||||
description: "Configure Azure OpenAI with Crew Studio for enterprise LLM connections"
|
||||
icon: "microsoft"
|
||||
---
|
||||
|
||||
This guide walks you through connecting Azure OpenAI with Crew Studio for seamless enterprise AI operations.
|
||||
|
||||
## Setup Process
|
||||
|
||||
<Steps>
|
||||
<Step title="Access Azure OpenAI Studio">
|
||||
1. In Azure, go to `Azure AI Services > select your deployment > open Azure OpenAI Studio`.
|
||||
2. On the left menu, click `Deployments`. If you don't have one, create a deployment with your desired model.
|
||||
3. Once created, select your deployment and locate the `Target URI` and `Key` on the right side of the page. Keep this page open, as you'll need this information.
|
||||
<Frame>
|
||||
<img src="/images/enterprise/azure-openai-studio.png" alt="Azure OpenAI Studio" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Configure CrewAI Enterprise Connection">
|
||||
4. In another tab, open `CrewAI Enterprise > LLM Connections`. Name your LLM Connection, select Azure as the provider, and choose the same model you selected in Azure.
|
||||
5. On the same page, add environment variables from step 3:
|
||||
- One named `AZURE_DEPLOYMENT_TARGET_URL` (using the Target URI). The URL should look like this: https://your-deployment.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview
|
||||
- Another named `AZURE_API_KEY` (using the Key).
|
||||
6. Click `Add Connection` to save your LLM Connection.
|
||||
</Step>
|
||||
|
||||
<Step title="Set Default Configuration">
|
||||
7. In `CrewAI Enterprise > Settings > Defaults > Crew Studio LLM Settings`, set the new LLM Connection and model as defaults.
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Network Access">
|
||||
8. Ensure network access settings:
|
||||
- In Azure, go to `Azure OpenAI > select your deployment`.
|
||||
- Navigate to `Resource Management > Networking`.
|
||||
- Ensure that `Allow access from all networks` is enabled. If this setting is restricted, CrewAI may be blocked from accessing your Azure OpenAI endpoint.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Verification
|
||||
|
||||
You're all set! Crew Studio will now use your Azure OpenAI connection. Test the connection by creating a simple crew or task to ensure everything is working properly.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If you encounter issues:
|
||||
- Verify the Target URI format matches the expected pattern
|
||||
- Check that the API key is correct and has proper permissions
|
||||
- Ensure network access is configured to allow CrewAI connections
|
||||
- Confirm the deployment model matches what you've configured in CrewAI
|
||||
43
docs/en/enterprise/guides/build-crew.mdx
Normal file
43
docs/en/enterprise/guides/build-crew.mdx
Normal file
@@ -0,0 +1,43 @@
|
||||
---
|
||||
title: "Build Crew"
|
||||
description: "A Crew is a group of agents that work together to complete a task."
|
||||
icon: "people-arrows"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
[CrewAI Enterprise](https://app.crewai.com) streamlines the process of **creating**, **deploying**, and **managing** your AI agents in production environments.
|
||||
|
||||
## Getting Started
|
||||
|
||||
<iframe
|
||||
width="100%"
|
||||
height="400"
|
||||
src="https://www.youtube.com/embed/-kSOTtYzgEw"
|
||||
title="Building Crews with CrewAI CLI"
|
||||
frameborder="0"
|
||||
style={{ borderRadius: '10px' }}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
|
||||
### Installation and Setup
|
||||
|
||||
<Card title="Follow Standard Installation" icon="wrench" href="/en/installation">
|
||||
Follow our standard installation guide to set up CrewAI CLI and create your first project.
|
||||
</Card>
|
||||
|
||||
### Building Your Crew
|
||||
|
||||
<Card title="Quickstart Tutorial" icon="rocket" href="/en/quickstart">
|
||||
Follow our quickstart guide to create your first agent crew using YAML configuration.
|
||||
</Card>
|
||||
|
||||
## Support and Resources
|
||||
|
||||
For Enterprise-specific support or questions, contact our dedicated support team at [support@crewai.com](mailto:support@crewai.com).
|
||||
|
||||
|
||||
<Card title="Schedule a Demo" icon="calendar" href="mailto:support@crewai.com">
|
||||
Book time with our team to learn more about Enterprise features and how they can benefit your organization.
|
||||
</Card>
|
||||
290
docs/en/enterprise/guides/deploy-crew.mdx
Normal file
290
docs/en/enterprise/guides/deploy-crew.mdx
Normal file
@@ -0,0 +1,290 @@
|
||||
---
|
||||
title: "Deploy Crew"
|
||||
description: "Deploying a Crew on CrewAI Enterprise"
|
||||
icon: "rocket"
|
||||
---
|
||||
|
||||
<Note>
|
||||
After creating a crew locally or through Crew Studio, the next step is deploying it to the CrewAI Enterprise platform. This guide covers multiple deployment methods to help you choose the best approach for your workflow.
|
||||
</Note>
|
||||
|
||||
## Prerequisites
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Crew Ready for Deployment" icon="users">
|
||||
You should have a working crew either built locally or created through Crew Studio
|
||||
</Card>
|
||||
<Card title="GitHub Repository" icon="github">
|
||||
Your crew code should be in a GitHub repository (for GitHub integration method)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Option 1: Deploy Using CrewAI CLI
|
||||
|
||||
The CLI provides the fastest way to deploy locally developed crews to the Enterprise platform.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install CrewAI CLI">
|
||||
If you haven't already, install the CrewAI CLI:
|
||||
|
||||
```bash
|
||||
pip install crewai[tools]
|
||||
```
|
||||
|
||||
<Tip>
|
||||
The CLI comes with the main CrewAI package, but the `[tools]` extra ensures you have all deployment dependencies.
|
||||
</Tip>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Authenticate with the Enterprise Platform">
|
||||
First, you need to authenticate your CLI with the CrewAI Enterprise platform:
|
||||
|
||||
```bash
|
||||
# If you already have a CrewAI Enterprise account, or want to create one:
|
||||
crewai login
|
||||
```
|
||||
|
||||
When you run either command, the CLI will:
|
||||
1. Display a URL and a unique device code
|
||||
2. Open your browser to the authentication page
|
||||
3. Prompt you to confirm the device
|
||||
4. Complete the authentication process
|
||||
|
||||
Upon successful authentication, you'll see a confirmation message in your terminal!
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Create a Deployment">
|
||||
|
||||
From your project directory, run:
|
||||
|
||||
```bash
|
||||
crewai deploy create
|
||||
```
|
||||
|
||||
This command will:
|
||||
1. Detect your GitHub repository information
|
||||
2. Identify environment variables in your local `.env` file
|
||||
3. Securely transfer these variables to the Enterprise platform
|
||||
4. Create a new deployment with a unique identifier
|
||||
|
||||
On successful creation, you'll see a message like:
|
||||
```shell
|
||||
Deployment created successfully!
|
||||
Name: your_project_name
|
||||
Deployment ID: 01234567-89ab-cdef-0123-456789abcdef
|
||||
Current Status: Deploy Enqueued
|
||||
```
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Monitor Deployment Progress">
|
||||
|
||||
Track the deployment status with:
|
||||
|
||||
```bash
|
||||
crewai deploy status
|
||||
```
|
||||
|
||||
For detailed logs of the build process:
|
||||
|
||||
```bash
|
||||
crewai deploy logs
|
||||
```
|
||||
|
||||
<Tip>
|
||||
The first deployment typically takes 10-15 minutes as it builds the container images. Subsequent deployments are much faster.
|
||||
</Tip>
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Additional CLI Commands
|
||||
|
||||
The CrewAI CLI offers several commands to manage your deployments:
|
||||
|
||||
```bash
|
||||
# List all your deployments
|
||||
crewai deploy list
|
||||
|
||||
# Get the status of your deployment
|
||||
crewai deploy status
|
||||
|
||||
# View the logs of your deployment
|
||||
crewai deploy logs
|
||||
|
||||
# Push updates after code changes
|
||||
crewai deploy push
|
||||
|
||||
# Remove a deployment
|
||||
crewai deploy remove <deployment_id>
|
||||
```
|
||||
|
||||
## Option 2: Deploy Directly via Web Interface
|
||||
|
||||
You can also deploy your crews directly through the CrewAI Enterprise web interface by connecting your GitHub account. This approach doesn't require using the CLI on your local machine.
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step title="Pushing to GitHub">
|
||||
|
||||
You need to push your crew to a GitHub repository. If you haven't created a crew yet, you can [follow this tutorial](/en/quickstart).
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Connecting GitHub to CrewAI Enterprise">
|
||||
|
||||
1. Log in to [CrewAI Enterprise](https://app.crewai.com)
|
||||
2. Click on the button "Connect GitHub"
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Select the Repository">
|
||||
|
||||
After connecting your GitHub account, you'll be able to select which repository to deploy:
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Set Environment Variables">
|
||||
|
||||
Before deploying, you'll need to set up your environment variables to connect to your LLM provider or other services:
|
||||
|
||||
1. You can add variables individually or in bulk
|
||||
2. Enter your environment variables in `KEY=VALUE` format (one per line)
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Deploy Your Crew">
|
||||
|
||||
1. Click the "Deploy" button to start the deployment process
|
||||
2. You can monitor the progress through the progress bar
|
||||
3. The first deployment typically takes around 10-15 minutes; subsequent deployments will be faster
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Once deployment is complete, you'll see:
|
||||
- Your crew's unique URL
|
||||
- A Bearer token to protect your crew API
|
||||
- A "Delete" button if you need to remove the deployment
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## ⚠️ Environment Variable Security Requirements
|
||||
|
||||
<Warning>
|
||||
**Important**: CrewAI Enterprise has security restrictions on environment variable names that can cause deployment failures if not followed.
|
||||
</Warning>
|
||||
|
||||
### Blocked Environment Variable Patterns
|
||||
|
||||
For security reasons, the following environment variable naming patterns are **automatically filtered** and will cause deployment issues:
|
||||
|
||||
**Blocked Patterns:**
|
||||
- Variables ending with `_TOKEN` (e.g., `MY_API_TOKEN`)
|
||||
- Variables ending with `_PASSWORD` (e.g., `DB_PASSWORD`)
|
||||
- Variables ending with `_SECRET` (e.g., `API_SECRET`)
|
||||
- Variables ending with `_KEY` in certain contexts
|
||||
|
||||
**Specific Blocked Variables:**
|
||||
- `GITHUB_USER`, `GITHUB_TOKEN`
|
||||
- `AWS_REGION`, `AWS_DEFAULT_REGION`
|
||||
- Various internal CrewAI system variables
|
||||
|
||||
### Allowed Exceptions
|
||||
|
||||
Some variables are explicitly allowed despite matching blocked patterns:
|
||||
- `AZURE_AD_TOKEN`
|
||||
- `AZURE_OPENAI_AD_TOKEN`
|
||||
- `ENTERPRISE_ACTION_TOKEN`
|
||||
- `CREWAI_ENTEPRISE_TOOLS_TOKEN`
|
||||
|
||||
### How to Fix Naming Issues
|
||||
|
||||
If your deployment fails due to environment variable restrictions:
|
||||
|
||||
```bash
|
||||
# ❌ These will cause deployment failures
|
||||
OPENAI_TOKEN=sk-...
|
||||
DATABASE_PASSWORD=mypassword
|
||||
API_SECRET=secret123
|
||||
|
||||
# ✅ Use these naming patterns instead
|
||||
OPENAI_API_KEY=sk-...
|
||||
DATABASE_CREDENTIALS=mypassword
|
||||
API_CONFIG=secret123
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
1. **Use standard naming conventions**: `PROVIDER_API_KEY` instead of `PROVIDER_TOKEN`
|
||||
2. **Test locally first**: Ensure your crew works with the renamed variables
|
||||
3. **Update your code**: Change any references to the old variable names
|
||||
4. **Document changes**: Keep track of renamed variables for your team
|
||||
|
||||
<Tip>
|
||||
If you encounter deployment failures with cryptic environment variable errors, check your variable names against these patterns first.
|
||||
</Tip>
|
||||
|
||||
### Interact with Your Deployed Crew
|
||||
|
||||
Once deployment is complete, you can access your crew through:
|
||||
|
||||
1. **REST API**: The platform generates a unique HTTPS endpoint with these key routes:
|
||||
- `/inputs`: Lists the required input parameters
|
||||
- `/kickoff`: Initiates an execution with provided inputs
|
||||
- `/status/{kickoff_id}`: Checks the execution status
|
||||
|
||||
2. **Web Interface**: Visit [app.crewai.com](https://app.crewai.com) to access:
|
||||
- **Status tab**: View deployment information, API endpoint details, and authentication token
|
||||
- **Run tab**: Visual representation of your crew's structure
|
||||
- **Executions tab**: History of all executions
|
||||
- **Metrics tab**: Performance analytics
|
||||
- **Traces tab**: Detailed execution insights
|
||||
|
||||
### Trigger an Execution
|
||||
|
||||
From the Enterprise dashboard, you can:
|
||||
|
||||
1. Click on your crew's name to open its details
|
||||
2. Select "Trigger Crew" from the management interface
|
||||
3. Enter the required inputs in the modal that appears
|
||||
4. Monitor progress as the execution moves through the pipeline
|
||||
|
||||
### Monitoring and Analytics
|
||||
|
||||
The Enterprise platform provides comprehensive observability features:
|
||||
|
||||
- **Execution Management**: Track active and completed runs
|
||||
- **Traces**: Detailed breakdowns of each execution
|
||||
- **Metrics**: Token usage, execution times, and costs
|
||||
- **Timeline View**: Visual representation of task sequences
|
||||
|
||||
### Advanced Features
|
||||
|
||||
The Enterprise platform also offers:
|
||||
|
||||
- **Environment Variables Management**: Securely store and manage API keys
|
||||
- **LLM Connections**: Configure integrations with various LLM providers
|
||||
- **Custom Tools Repository**: Create, share, and install tools
|
||||
- **Crew Studio**: Build crews through a chat interface without writing code
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with deployment issues or questions about the Enterprise platform.
|
||||
</Card>
|
||||
166
docs/en/enterprise/guides/enable-crew-studio.mdx
Normal file
166
docs/en/enterprise/guides/enable-crew-studio.mdx
Normal file
@@ -0,0 +1,166 @@
|
||||
---
|
||||
title: "Enable Crew Studio"
|
||||
description: "Enabling Crew Studio on CrewAI Enterprise"
|
||||
icon: "comments"
|
||||
---
|
||||
|
||||
<Tip>
|
||||
Crew Studio is a powerful **no-code/low-code** tool that allows you to quickly scaffold or build Crews through a conversational interface.
|
||||
</Tip>
|
||||
|
||||
## What is Crew Studio?
|
||||
|
||||
Crew Studio is an innovative way to create AI agent crews without writing code.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
With Crew Studio, you can:
|
||||
|
||||
- Chat with the Crew Assistant to describe your problem
|
||||
- Automatically generate agents and tasks
|
||||
- Select appropriate tools
|
||||
- Configure necessary inputs
|
||||
- Generate downloadable code for customization
|
||||
- Deploy directly to the CrewAI Enterprise platform
|
||||
|
||||
## Configuration Steps
|
||||
|
||||
Before you can start using Crew Studio, you need to configure your LLM connections:
|
||||
|
||||
<Steps>
|
||||
<Step title="Set Up LLM Connection">
|
||||
Go to the **LLM Connections** tab in your CrewAI Enterprise dashboard and create a new LLM connection.
|
||||
|
||||
<Note>
|
||||
Feel free to use any LLM provider you want that is supported by CrewAI.
|
||||
</Note>
|
||||
|
||||
Configure your LLM connection:
|
||||
|
||||
- Enter a `Connection Name` (e.g., `OpenAI`)
|
||||
- Select your model provider: `openai` or `azure`
|
||||
- Select models you'd like to use in your Studio-generated Crews
|
||||
- We recommend at least `gpt-4o`, `o1-mini`, and `gpt-4o-mini`
|
||||
- Add your API key as an environment variable:
|
||||
- For OpenAI: Add `OPENAI_API_KEY` with your API key
|
||||
- For Azure OpenAI: Refer to [this article](https://blog.crewai.com/configuring-azure-openai-with-crewai-a-comprehensive-guide/) for configuration details
|
||||
- Click `Add Connection` to save your configuration
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Verify Connection Added">
|
||||
Once you complete the setup, you'll see your new connection added to the list of available connections.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Configure LLM Defaults">
|
||||
In the main menu, go to **Settings → Defaults** and configure the LLM Defaults settings:
|
||||
|
||||
- Select default models for agents and other components
|
||||
- Set default configurations for Crew Studio
|
||||
|
||||
Click `Save Settings` to apply your changes.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Using Crew Studio
|
||||
|
||||
Now that you've configured your LLM connection and default settings, you're ready to start using Crew Studio!
|
||||
|
||||
<Steps>
|
||||
<Step title="Access Studio">
|
||||
Navigate to the **Studio** section in your CrewAI Enterprise dashboard.
|
||||
</Step>
|
||||
|
||||
<Step title="Start a Conversation">
|
||||
Start a conversation with the Crew Assistant by describing the problem you want to solve:
|
||||
|
||||
```md
|
||||
I need a crew that can research the latest AI developments and create a summary report.
|
||||
```
|
||||
|
||||
The Crew Assistant will ask clarifying questions to better understand your requirements.
|
||||
</Step>
|
||||
|
||||
<Step title="Review Generated Crew">
|
||||
Review the generated crew configuration, including:
|
||||
|
||||
- Agents and their roles
|
||||
- Tasks to be performed
|
||||
- Required inputs
|
||||
- Tools to be used
|
||||
|
||||
This is your opportunity to refine the configuration before proceeding.
|
||||
</Step>
|
||||
|
||||
<Step title="Deploy or Download">
|
||||
Once you're satisfied with the configuration, you can:
|
||||
|
||||
- Download the generated code for local customization
|
||||
- Deploy the crew directly to the CrewAI Enterprise platform
|
||||
- Modify the configuration and regenerate the crew
|
||||
</Step>
|
||||
|
||||
<Step title="Test Your Crew">
|
||||
After deployment, test your crew with sample inputs to ensure it performs as expected.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Tip>
|
||||
For best results, provide clear, detailed descriptions of what you want your crew to accomplish. Include specific inputs and expected outputs in your description.
|
||||
</Tip>
|
||||
|
||||
## Example Workflow
|
||||
|
||||
Here's a typical workflow for creating a crew with Crew Studio:
|
||||
|
||||
<Steps>
|
||||
<Step title="Describe Your Problem">
|
||||
Start by describing your problem:
|
||||
|
||||
```md
|
||||
I need a crew that can analyze financial news and provide investment recommendations
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Answer Questions">
|
||||
Respond to clarifying questions from the Crew Assistant to refine your requirements.
|
||||
</Step>
|
||||
|
||||
<Step title="Review the Plan">
|
||||
Review the generated crew plan, which might include:
|
||||
|
||||
- A Research Agent to gather financial news
|
||||
- An Analysis Agent to interpret the data
|
||||
- A Recommendations Agent to provide investment advice
|
||||
</Step>
|
||||
|
||||
<Step title="Approve or Modify">
|
||||
Approve the plan or request changes if necessary.
|
||||
</Step>
|
||||
|
||||
<Step title="Download or Deploy">
|
||||
Download the code for customization or deploy directly to the platform.
|
||||
</Step>
|
||||
|
||||
<Step title="Test and Refine">
|
||||
Test your crew with sample inputs and refine as needed.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Crew Studio or any other CrewAI Enterprise features.
|
||||
</Card>
|
||||
|
||||
53
docs/en/enterprise/guides/hubspot-trigger.mdx
Normal file
53
docs/en/enterprise/guides/hubspot-trigger.mdx
Normal file
@@ -0,0 +1,53 @@
|
||||
---
|
||||
title: "HubSpot Trigger"
|
||||
description: "Trigger CrewAI crews directly from HubSpot Workflows"
|
||||
icon: "hubspot"
|
||||
---
|
||||
|
||||
This guide provides a step-by-step process to set up HubSpot triggers for CrewAI Enterprise, enabling you to initiate crews directly from HubSpot Workflows.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A CrewAI Enterprise account
|
||||
- A HubSpot account with the [HubSpot Workflows](https://knowledge.hubspot.com/workflows/create-workflows) feature
|
||||
|
||||
## Setup Steps
|
||||
|
||||
<Steps>
|
||||
<Step title="Connect your HubSpot account with CrewAI Enterprise">
|
||||
- Log in to your `CrewAI Enterprise account > Triggers`
|
||||
- Select `HubSpot` from the list of available triggers
|
||||
- Choose the HubSpot account you want to connect with CrewAI Enterprise
|
||||
- Follow the on-screen prompts to authorize CrewAI Enterprise access to your HubSpot account
|
||||
- A confirmation message will appear once HubSpot is successfully connected with CrewAI Enterprise
|
||||
</Step>
|
||||
<Step title="Create a HubSpot Workflow">
|
||||
- Log in to your `HubSpot account > Automations > Workflows > New workflow`
|
||||
- Select the workflow type that fits your needs (e.g., Start from scratch)
|
||||
- In the workflow builder, click the Plus (+) icon to add a new action.
|
||||
- Choose `Integrated apps > CrewAI > Kickoff a Crew`.
|
||||
- Select the Crew you want to initiate.
|
||||
- Click `Save` to add the action to your workflow
|
||||
<Frame>
|
||||
<img src="/images/enterprise/hubspot-workflow-1.png" alt="HubSpot Workflow 1" />
|
||||
</Frame>
|
||||
</Step>
|
||||
<Step title="Use Crew results with other actions">
|
||||
- After the Kickoff a Crew step, click the Plus (+) icon to add a new action.
|
||||
- For example, to send an internal email notification, choose `Communications > Send internal email notification`
|
||||
- In the Body field, click `Insert data`, select `View properties or action outputs from > Action outputs > Crew Result` to include Crew data in the email
|
||||
<Frame>
|
||||
<img src="/images/enterprise/hubspot-workflow-2.png" alt="HubSpot Workflow 2" />
|
||||
</Frame>
|
||||
- Configure any additional actions as needed
|
||||
- Review your workflow steps to ensure everything is set up correctly
|
||||
- Activate the workflow
|
||||
<Frame>
|
||||
<img src="/images/enterprise/hubspot-workflow-3.png" alt="HubSpot Workflow 3" />
|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Additional Resources
|
||||
|
||||
For more detailed information on available actions and customization options, refer to the [HubSpot Workflows Documentation](https://knowledge.hubspot.com/workflows/create-workflows).
|
||||
78
docs/en/enterprise/guides/human-in-the-loop.mdx
Normal file
78
docs/en/enterprise/guides/human-in-the-loop.mdx
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
title: "HITL Workflows"
|
||||
description: "Learn how to implement Human-In-The-Loop workflows in CrewAI for enhanced decision-making"
|
||||
icon: "user-check"
|
||||
---
|
||||
|
||||
Human-In-The-Loop (HITL) is a powerful approach that combines artificial intelligence with human expertise to enhance decision-making and improve task outcomes. This guide shows you how to implement HITL within CrewAI.
|
||||
|
||||
## Setting Up HITL Workflows
|
||||
|
||||
<Steps>
|
||||
<Step title="Configure Your Task">
|
||||
Set up your task with human input enabled:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crew-human-input.png" alt="Crew Human Input" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Provide Webhook URL">
|
||||
When kicking off your crew, include a webhook URL for human input:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crew-webhook-url.png" alt="Crew Webhook URL" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Receive Webhook Notification">
|
||||
Once the crew completes the task requiring human input, you'll receive a webhook notification containing:
|
||||
- **Execution ID**
|
||||
- **Task ID**
|
||||
- **Task output**
|
||||
</Step>
|
||||
|
||||
<Step title="Review Task Output">
|
||||
The system will pause in the `Pending Human Input` state. Review the task output carefully.
|
||||
</Step>
|
||||
|
||||
<Step title="Submit Human Feedback">
|
||||
Call the resume endpoint of your crew with the following information:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crew-resume-endpoint.png" alt="Crew Resume Endpoint" />
|
||||
</Frame>
|
||||
<Warning>
|
||||
**Feedback Impact on Task Execution**:
|
||||
It's crucial to exercise care when providing feedback, as the entire feedback content will be incorporated as additional context for further task executions.
|
||||
</Warning>
|
||||
This means:
|
||||
- All information in your feedback becomes part of the task's context.
|
||||
- Irrelevant details may negatively influence it.
|
||||
- Concise, relevant feedback helps maintain task focus and efficiency.
|
||||
- Always review your feedback carefully before submission to ensure it contains only pertinent information that will positively guide the task's execution.
|
||||
</Step>
|
||||
<Step title="Handle Negative Feedback">
|
||||
If you provide negative feedback:
|
||||
- The crew will retry the task with added context from your feedback.
|
||||
- You'll receive another webhook notification for further review.
|
||||
- Repeat steps 4-6 until satisfied.
|
||||
</Step>
|
||||
|
||||
<Step title="Execution Continuation">
|
||||
When you submit positive feedback, the execution will proceed to the next steps.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Be Specific**: Provide clear, actionable feedback that directly addresses the task at hand
|
||||
- **Stay Relevant**: Only include information that will help improve the task execution
|
||||
- **Be Timely**: Respond to HITL prompts promptly to avoid workflow delays
|
||||
- **Review Carefully**: Double-check your feedback before submitting to ensure accuracy
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
HITL workflows are particularly valuable for:
|
||||
- Quality assurance and validation
|
||||
- Complex decision-making scenarios
|
||||
- Sensitive or high-stakes operations
|
||||
- Creative tasks requiring human judgment
|
||||
- Compliance and regulatory reviews
|
||||
186
docs/en/enterprise/guides/kickoff-crew.mdx
Normal file
186
docs/en/enterprise/guides/kickoff-crew.mdx
Normal file
@@ -0,0 +1,186 @@
|
||||
---
|
||||
title: "Kickoff Crew"
|
||||
description: "Kickoff a Crew on CrewAI Enterprise"
|
||||
icon: "flag-checkered"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Once you've deployed your crew to the CrewAI Enterprise platform, you can kickoff executions through the web interface or the API. This guide covers both approaches.
|
||||
|
||||
## Method 1: Using the Web Interface
|
||||
|
||||
### Step 1: Navigate to Your Deployed Crew
|
||||
|
||||
1. Log in to [CrewAI Enterprise](https://app.crewai.com)
|
||||
2. Click on the crew name from your projects list
|
||||
3. You'll be taken to the crew's detail page
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### Step 2: Initiate Execution
|
||||
|
||||
From your crew's detail page, you have two options to kickoff an execution:
|
||||
|
||||
#### Option A: Quick Kickoff
|
||||
|
||||
1. Click the `Kickoff` link in the Test Endpoints section
|
||||
2. Enter the required input parameters for your crew in the JSON editor
|
||||
3. Click the `Send Request` button
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
#### Option B: Using the Visual Interface
|
||||
|
||||
1. Click the `Run` tab in the crew detail page
|
||||
2. Enter the required inputs in the form fields
|
||||
3. Click the `Run Crew` button
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### Step 3: Monitor Execution Progress
|
||||
|
||||
After initiating the execution:
|
||||
|
||||
1. You'll receive a response containing a `kickoff_id` - **copy this ID**
|
||||
2. This ID is essential for tracking your execution
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### Step 4: Check Execution Status
|
||||
|
||||
To monitor the progress of your execution:
|
||||
|
||||
1. Click the "Status" endpoint in the Test Endpoints section
|
||||
2. Paste the `kickoff_id` into the designated field
|
||||
3. Click the "Get Status" button
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
The status response will show:
|
||||
- Current execution state (`running`, `completed`, etc.)
|
||||
- Details about which tasks are in progress
|
||||
- Any outputs produced so far
|
||||
|
||||
### Step 5: View Final Results
|
||||
|
||||
Once execution is complete:
|
||||
|
||||
1. The status will change to `completed`
|
||||
2. You can view the full execution results and outputs
|
||||
3. For a more detailed view, check the `Executions` tab in the crew detail page
|
||||
|
||||
## Method 2: Using the API
|
||||
|
||||
You can also kickoff crews programmatically using the CrewAI Enterprise REST API.
|
||||
|
||||
### Authentication
|
||||
|
||||
All API requests require a bearer token for authentication:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" https://your-crew-url.crewai.com
|
||||
```
|
||||
|
||||
Your bearer token is available on the Status tab of your crew's detail page.
|
||||
|
||||
### Checking Crew Health
|
||||
|
||||
Before executing operations, you can verify that your crew is running properly:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" https://your-crew-url.crewai.com
|
||||
```
|
||||
|
||||
A successful response will return a message indicating the crew is operational:
|
||||
|
||||
```
|
||||
Healthy%
|
||||
```
|
||||
|
||||
### Step 1: Retrieve Required Inputs
|
||||
|
||||
First, determine what inputs your crew requires:
|
||||
|
||||
```bash
|
||||
curl -X GET \
|
||||
-H "Authorization: Bearer YOUR_CREW_TOKEN" \
|
||||
https://your-crew-url.crewai.com/inputs
|
||||
```
|
||||
|
||||
The response will be a JSON object containing an array of required input parameters, for example:
|
||||
|
||||
```json
|
||||
{"inputs":["topic","current_year"]}
|
||||
```
|
||||
|
||||
This example shows that this particular crew requires two inputs: `topic` and `current_year`.
|
||||
|
||||
### Step 2: Kickoff Execution
|
||||
|
||||
Initiate execution by providing the required inputs:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer YOUR_CREW_TOKEN" \
|
||||
-d '{"inputs": {"topic": "AI Agent Frameworks", "current_year": "2025"}}' \
|
||||
https://your-crew-url.crewai.com/kickoff
|
||||
```
|
||||
|
||||
The response will include a `kickoff_id` that you'll need for tracking:
|
||||
|
||||
```json
|
||||
{"kickoff_id":"abcd1234-5678-90ef-ghij-klmnopqrstuv"}
|
||||
```
|
||||
|
||||
### Step 3: Check Execution Status
|
||||
|
||||
Monitor the execution progress using the kickoff_id:
|
||||
|
||||
```bash
|
||||
curl -X GET \
|
||||
-H "Authorization: Bearer YOUR_CREW_TOKEN" \
|
||||
https://your-crew-url.crewai.com/status/abcd1234-5678-90ef-ghij-klmnopqrstuv
|
||||
```
|
||||
|
||||
## Handling Executions
|
||||
|
||||
### Long-Running Executions
|
||||
|
||||
For executions that may take a long time:
|
||||
|
||||
1. Consider implementing a polling mechanism to check status periodically
|
||||
2. Use webhooks (if available) for notification when execution completes
|
||||
3. Implement error handling for potential timeouts
|
||||
|
||||
### Execution Context
|
||||
|
||||
The execution context includes:
|
||||
|
||||
- Inputs provided at kickoff
|
||||
- Environment variables configured during deployment
|
||||
- Any state maintained between tasks
|
||||
|
||||
### Debugging Failed Executions
|
||||
|
||||
If an execution fails:
|
||||
|
||||
1. Check the "Executions" tab for detailed logs
|
||||
2. Review the "Traces" tab for step-by-step execution details
|
||||
3. Look for LLM responses and tool usage in the trace details
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with execution issues or questions about the Enterprise platform.
|
||||
</Card>
|
||||
|
||||
103
docs/en/enterprise/guides/react-component-export.mdx
Normal file
103
docs/en/enterprise/guides/react-component-export.mdx
Normal file
@@ -0,0 +1,103 @@
|
||||
---
|
||||
title: "React Component Export"
|
||||
description: "Learn how to export and integrate CrewAI Enterprise React components into your applications"
|
||||
icon: "react"
|
||||
---
|
||||
|
||||
This guide explains how to export CrewAI Enterprise crews as React components and integrate them into your own applications.
|
||||
|
||||
## Exporting a React Component
|
||||
|
||||
<Steps>
|
||||
<Step title="Export the Component">
|
||||
Click on the ellipsis (three dots on the right of your deployed crew) and select the export option and save the file locally. We will be using `CrewLead.jsx` for our example.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/export-react-component.png" alt="Export React Component" />
|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Setting Up Your React Environment
|
||||
|
||||
To run this React component locally, you'll need to set up a React development environment and integrate this component into a React project.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Node.js">
|
||||
- Download and install Node.js from the official website: https://nodejs.org/
|
||||
- Choose the LTS (Long Term Support) version for stability.
|
||||
</Step>
|
||||
|
||||
<Step title="Create a new React project">
|
||||
- Open Command Prompt or PowerShell
|
||||
- Navigate to the directory where you want to create your project
|
||||
- Run the following command to create a new React project:
|
||||
|
||||
```bash
|
||||
npx create-react-app my-crew-app
|
||||
```
|
||||
- Change into the project directory:
|
||||
|
||||
```bash
|
||||
cd my-crew-app
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Install necessary dependencies">
|
||||
```bash
|
||||
npm install react-dom
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create the CrewLead component">
|
||||
- Move the downloaded file `CrewLead.jsx` into the `src` folder of your project,
|
||||
</Step>
|
||||
|
||||
<Step title="Modify your App.js to use the CrewLead component">
|
||||
- Open `src/App.js`
|
||||
- Replace its contents with something like this:
|
||||
|
||||
```jsx
|
||||
import React from 'react';
|
||||
import CrewLead from './CrewLead';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="App">
|
||||
<CrewLead baseUrl="YOUR_API_BASE_URL" bearerToken="YOUR_BEARER_TOKEN" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
```
|
||||
- Replace `YOUR_API_BASE_URL` and `YOUR_BEARER_TOKEN` with the actual values for your API.
|
||||
</Step>
|
||||
|
||||
<Step title="Start the development server">
|
||||
- In your project directory, run:
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
- This will start the development server, and your default web browser should open automatically to http://localhost:3000, where you'll see your React app running.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Customization
|
||||
|
||||
You can then customise the `CrewLead.jsx` to add color, title etc
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/customise-react-component.png" alt="Customise React Component" />
|
||||
</Frame>
|
||||
<Frame>
|
||||
<img src="/images/enterprise/customise-react-component-2.png" alt="Customise React Component" />
|
||||
</Frame>
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Customize the component styling to match your application's design
|
||||
- Add additional props for configuration
|
||||
- Integrate with your application's state management
|
||||
- Add error handling and loading states
|
||||
44
docs/en/enterprise/guides/salesforce-trigger.mdx
Normal file
44
docs/en/enterprise/guides/salesforce-trigger.mdx
Normal file
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: "Salesforce Trigger"
|
||||
description: "Trigger CrewAI crews from Salesforce workflows for CRM automation"
|
||||
icon: "salesforce"
|
||||
---
|
||||
|
||||
CrewAI Enterprise can be triggered from Salesforce to automate customer relationship management workflows and enhance your sales operations.
|
||||
|
||||
## Overview
|
||||
|
||||
Salesforce is a leading customer relationship management (CRM) platform that helps businesses streamline their sales, service, and marketing operations. By setting up CrewAI triggers from Salesforce, you can:
|
||||
|
||||
- Automate lead scoring and qualification
|
||||
- Generate personalized sales materials
|
||||
- Enhance customer service with AI-powered responses
|
||||
- Streamline data analysis and reporting
|
||||
|
||||
## Demo
|
||||
|
||||
<Frame>
|
||||
<iframe width="100%" height="400" src="https://www.youtube.com/embed/oJunVqjjfu4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
</Frame>
|
||||
|
||||
## Getting Started
|
||||
|
||||
To set up Salesforce triggers:
|
||||
|
||||
1. **Contact Support**: Reach out to CrewAI Enterprise support for assistance with Salesforce trigger setup
|
||||
2. **Review Requirements**: Ensure you have the necessary Salesforce permissions and API access
|
||||
3. **Configure Connection**: Work with the support team to establish the connection between CrewAI and your Salesforce instance
|
||||
4. **Test Triggers**: Verify the triggers work correctly with your specific use cases
|
||||
|
||||
## Use Cases
|
||||
|
||||
Common Salesforce + CrewAI trigger scenarios include:
|
||||
|
||||
- **Lead Processing**: Automatically analyze and score incoming leads
|
||||
- **Proposal Generation**: Create customized proposals based on opportunity data
|
||||
- **Customer Insights**: Generate analysis reports from customer interaction history
|
||||
- **Follow-up Automation**: Create personalized follow-up messages and recommendations
|
||||
|
||||
## Next Steps
|
||||
|
||||
For detailed setup instructions and advanced configuration options, please contact CrewAI Enterprise support who can provide tailored guidance for your specific Salesforce environment and business needs.
|
||||
61
docs/en/enterprise/guides/slack-trigger.mdx
Normal file
61
docs/en/enterprise/guides/slack-trigger.mdx
Normal file
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: "Slack Trigger"
|
||||
description: "Trigger CrewAI crews directly from Slack using slash commands"
|
||||
icon: "slack"
|
||||
---
|
||||
|
||||
This guide explains how to start a crew directly from Slack using CrewAI triggers.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- CrewAI Slack trigger installed and connected to your Slack workspace
|
||||
- At least one crew configured in CrewAI
|
||||
|
||||
## Setup Steps
|
||||
|
||||
<Steps>
|
||||
<Step title="Ensure the CrewAI Slack trigger is set up">
|
||||
In the CrewAI dashboard, navigate to the **Triggers** section.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/slack-integration.png" alt="CrewAI Slack Integration" />
|
||||
</Frame>
|
||||
|
||||
Verify that Slack is listed and is connected.
|
||||
</Step>
|
||||
<Step title="Open your Slack channel">
|
||||
- Navigate to the channel where you want to kickoff the crew.
|
||||
- Type the slash command "**/kickoff**" to initiate the crew kickoff process.
|
||||
- You should see a "**Kickoff crew**" appear as you type:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/kickoff-slack-crew.png" alt="Kickoff crew" />
|
||||
</Frame>
|
||||
- Press Enter or select the "**Kickoff crew**" option. A dialog box titled "**Kickoff an AI Crew**" will appear.
|
||||
</Step>
|
||||
<Step title="Select the crew you want to start">
|
||||
- In the dropdown menu labeled "**Select of the crews online:**", choose the crew you want to start.
|
||||
- In the example below, "**prep-for-meeting**" is selected:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/kickoff-slack-crew-dropdown.png" alt="Kickoff crew dropdown" />
|
||||
</Frame>
|
||||
- If your crew requires any inputs, click the "**Add Inputs**" button to provide them.
|
||||
<Note>
|
||||
The "**Add Inputs**" button is shown in the example above but is not yet clicked.
|
||||
</Note>
|
||||
</Step>
|
||||
<Step title="Click Kickoff and wait for the crew to complete">
|
||||
- Once you've selected the crew and added any necessary inputs, click "**Kickoff**" to start the crew.
|
||||
<Frame>
|
||||
<img src="/images/enterprise/kickoff-slack-crew-kickoff.png" alt="Kickoff crew" />
|
||||
</Frame>
|
||||
- The crew will start executing and you will see the results in the Slack channel.
|
||||
<Frame>
|
||||
<img src="/images/enterprise/kickoff-slack-crew-results.png" alt="Kickoff crew results" />
|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Tips
|
||||
|
||||
- Make sure you have the necessary permissions to use the `/kickoff` command in your Slack workspace.
|
||||
- If you don't see your desired crew in the dropdown, ensure it's properly configured and online in CrewAI.
|
||||
87
docs/en/enterprise/guides/team-management.mdx
Normal file
87
docs/en/enterprise/guides/team-management.mdx
Normal file
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: "Team Management"
|
||||
description: "Learn how to invite and manage team members in your CrewAI Enterprise organization"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
As an administrator of a CrewAI Enterprise account, you can easily invite new team members to join your organization. This guide will walk you through the process step-by-step.
|
||||
|
||||
## Inviting Team Members
|
||||
|
||||
<Steps>
|
||||
<Step title="Access the Settings Page">
|
||||
- Log in to your CrewAI Enterprise account
|
||||
- Look for the gear icon (⚙️) in the top right corner of the dashboard
|
||||
- Click on the gear icon to access the **Settings** page:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/settings-page.png" alt="Settings Page" />
|
||||
</Frame>
|
||||
</Step>
|
||||
<Step title="Navigate to the Members Section">
|
||||
- On the Settings page, you'll see a `Members` tab
|
||||
- Click on the `Members` tab to access the **Members** page:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/members-tab.png" alt="Members Tab" />
|
||||
</Frame>
|
||||
</Step>
|
||||
<Step title="Invite New Members">
|
||||
- In the Members section, you'll see a list of current members (including yourself)
|
||||
- Locate the `Email` input field
|
||||
- Enter the email address of the person you want to invite
|
||||
- Click the `Invite` button to send the invitation
|
||||
</Step>
|
||||
<Step title="Repeat as Needed">
|
||||
- You can repeat this process to invite multiple team members
|
||||
- Each invited member will receive an email invitation to join your organization
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Adding Roles
|
||||
|
||||
You can add roles to your team members to control their access to different parts of the platform.
|
||||
|
||||
<Steps>
|
||||
<Step title="Access the Settings Page">
|
||||
- Log in to your CrewAI Enterprise account
|
||||
- Look for the gear icon (⚙️) in the top right corner of the dashboard
|
||||
- Click on the gear icon to access the **Settings** page:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/settings-page.png" alt="Settings Page" />
|
||||
</Frame>
|
||||
</Step>
|
||||
<Step title="Navigate to the Members Section">
|
||||
- On the Settings page, you'll see a `Roles` tab
|
||||
- Click on the `Roles` tab to access the **Roles** page.
|
||||
<Frame>
|
||||
<img src="/images/enterprise/roles-tab.png" alt="Roles Tab" />
|
||||
</Frame>
|
||||
- Click on the `Add Role` button to add a new role.
|
||||
- Enter the details and permissions of the role and click the `Create Role` button to create the role.
|
||||
<Frame>
|
||||
<img src="/images/enterprise/add-role-modal.png" alt="Add Role Modal" />
|
||||
</Frame>
|
||||
</Step>
|
||||
<Step title="Add Roles to Members">
|
||||
- In the Members section, you'll see a list of current members (including yourself)
|
||||
<Frame>
|
||||
<img src="/images/enterprise/member-accepted-invitation.png" alt="Member Accepted Invitation" />
|
||||
</Frame>
|
||||
- Once the member has accepted the invitation, you can add a role to them.
|
||||
- Navigate back to `Roles` tab
|
||||
- Go to the member you want to add a role to and under the `Role` column, click on the dropdown
|
||||
- Select the role you want to add to the member
|
||||
- Click the `Update` button to save the role
|
||||
<Frame>
|
||||
<img src="/images/enterprise/assign-role.png" alt="Add Role to Member" />
|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Admin Privileges**: Only users with administrative privileges can invite new members
|
||||
- **Email Accuracy**: Ensure you have the correct email addresses for your team members
|
||||
- **Invitation Acceptance**: Invited members will need to accept the invitation to join your organization
|
||||
- **Email Notifications**: You may want to inform your team members to check their email (including spam folders) for the invitation
|
||||
|
||||
By following these steps, you can easily expand your team and collaborate more effectively within your CrewAI Enterprise organization.
|
||||
89
docs/en/enterprise/guides/update-crew.mdx
Normal file
89
docs/en/enterprise/guides/update-crew.mdx
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
title: "Update Crew"
|
||||
description: "Updating a Crew on CrewAI Enterprise"
|
||||
icon: "pencil"
|
||||
---
|
||||
|
||||
<Note>
|
||||
After deploying your crew to CrewAI Enterprise, you may need to make updates to the code, security settings, or configuration.
|
||||
This guide explains how to perform these common update operations.
|
||||
</Note>
|
||||
|
||||
## Why Update Your Crew?
|
||||
|
||||
CrewAI won't automatically pick up GitHub updates by default, so you'll need to manually trigger updates, unless you checked the `Auto-update` option when deploying your crew.
|
||||
|
||||
There are several reasons you might want to update your crew deployment:
|
||||
- You want to update the code with a latest commit you pushed to GitHub
|
||||
- You want to reset the bearer token for security reasons
|
||||
- You want to update environment variables
|
||||
|
||||
## 1. Updating Your Crew Code for a Latest Commit
|
||||
|
||||
When you've pushed new commits to your GitHub repository and want to update your deployment:
|
||||
|
||||
1. Navigate to your crew in the CrewAI Enterprise platform
|
||||
2. Click on the `Re-deploy` button on your crew details page
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
This will trigger an update that you can track using the progress bar. The system will pull the latest code from your repository and rebuild your deployment.
|
||||
|
||||
## 2. Resetting Bearer Token
|
||||
|
||||
If you need to generate a new bearer token (for example, if you suspect the current token might have been compromised):
|
||||
|
||||
1. Navigate to your crew in the CrewAI Enterprise platform
|
||||
2. Find the `Bearer Token` section
|
||||
3. Click the `Reset` button next to your current token
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
<Warning>
|
||||
Resetting your bearer token will invalidate the previous token immediately. Make sure to update any applications or scripts that are using the old token.
|
||||
</Warning>
|
||||
|
||||
## 3. Updating Environment Variables
|
||||
|
||||
To update the environment variables for your crew:
|
||||
|
||||
1. First access the deployment page by clicking on your crew's name
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
2. Locate the `Environment Variables` section (you will need to click the `Settings` icon to access it)
|
||||
3. Edit the existing variables or add new ones in the fields provided
|
||||
4. Click the `Update` button next to each variable you modify
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
5. Finally, click the `Update Deployment` button at the bottom of the page to apply the changes
|
||||
|
||||
<Note>
|
||||
Updating environment variables will trigger a new deployment, but this will only update the environment configuration and not the code itself.
|
||||
</Note>
|
||||
|
||||
## After Updating
|
||||
|
||||
After performing any update:
|
||||
|
||||
1. The system will rebuild and redeploy your crew
|
||||
2. You can monitor the deployment progress in real-time
|
||||
3. Once complete, test your crew to ensure the changes are working as expected
|
||||
|
||||
<Tip>
|
||||
If you encounter any issues after updating, you can view deployment logs in the platform or contact support for assistance.
|
||||
</Tip>
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with updating your crew or troubleshooting deployment issues.
|
||||
</Card>
|
||||
|
||||
121
docs/en/enterprise/guides/webhook-automation.mdx
Normal file
121
docs/en/enterprise/guides/webhook-automation.mdx
Normal file
@@ -0,0 +1,121 @@
|
||||
---
|
||||
title: "Webhook Automation"
|
||||
description: "Automate CrewAI Enterprise workflows using webhooks with platforms like ActivePieces, Zapier, and Make.com"
|
||||
icon: "webhook"
|
||||
---
|
||||
|
||||
CrewAI Enterprise allows you to automate your workflow using webhooks. This article will guide you through the process of setting up and using webhooks to kickoff your crew execution, with a focus on integration with ActivePieces, a workflow automation platform similar to Zapier and Make.com.
|
||||
|
||||
## Setting Up Webhooks
|
||||
|
||||
<Steps>
|
||||
<Step title="Accessing the Kickoff Interface">
|
||||
- Navigate to the CrewAI Enterprise dashboard
|
||||
- Look for the `/kickoff` section, which is used to start the crew execution
|
||||
<Frame>
|
||||
<img src="/images/enterprise/kickoff-interface.png" alt="Kickoff Interface" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Configuring the JSON Content">
|
||||
In the JSON Content section, you'll need to provide the following information:
|
||||
|
||||
- **inputs**: A JSON object containing:
|
||||
- `company`: The name of the company (e.g., "tesla")
|
||||
- `product_name`: The name of the product (e.g., "crewai")
|
||||
- `form_response`: The type of response (e.g., "financial")
|
||||
- `icp_description`: A brief description of the Ideal Customer Profile
|
||||
- `product_description`: A short description of the product
|
||||
- `taskWebhookUrl`, `stepWebhookUrl`, `crewWebhookUrl`: URLs for various webhook endpoints (ActivePieces, Zapier, Make.com or another compatible platform)
|
||||
</Step>
|
||||
|
||||
<Step title="Integrating with ActivePieces">
|
||||
In this example we will be using ActivePieces. You can use other platforms such as Zapier and Make.com
|
||||
|
||||
To integrate with ActivePieces:
|
||||
|
||||
1. Set up a new flow in ActivePieces
|
||||
2. Add a trigger (e.g., `Every Day` schedule)
|
||||
<Frame>
|
||||
<img src="/images/enterprise/activepieces-trigger.png" alt="ActivePieces Trigger" />
|
||||
</Frame>
|
||||
|
||||
3. Add an HTTP action step
|
||||
- Set the action to `Send HTTP request`
|
||||
- Use `POST` as the method
|
||||
- Set the URL to your CrewAI Enterprise kickoff endpoint
|
||||
- Add necessary headers (e.g., `Bearer Token`)
|
||||
<Frame>
|
||||
<img src="/images/enterprise/activepieces-headers.png" alt="ActivePieces Headers" />
|
||||
</Frame>
|
||||
|
||||
- In the body, include the JSON content as configured in step 2
|
||||
<Frame>
|
||||
<img src="/images/enterprise/activepieces-body.png" alt="ActivePieces Body" />
|
||||
</Frame>
|
||||
|
||||
- The crew will then kickoff at the pre-defined time.
|
||||
</Step>
|
||||
|
||||
<Step title="Setting Up the Webhook">
|
||||
1. Create a new flow in ActivePieces and name it
|
||||
<Frame>
|
||||
<img src="/images/enterprise/activepieces-flow.png" alt="ActivePieces Flow" />
|
||||
</Frame>
|
||||
|
||||
2. Add a webhook step as the trigger:
|
||||
- Select `Catch Webhook` as the trigger type
|
||||
- This will generate a unique URL that will receive HTTP requests and trigger your flow
|
||||
<Frame>
|
||||
<img src="/images/enterprise/activepieces-webhook.png" alt="ActivePieces Webhook" />
|
||||
</Frame>
|
||||
|
||||
- Configure the email to use crew webhook body text
|
||||
<Frame>
|
||||
<img src="/images/enterprise/activepieces-email.png" alt="ActivePieces Email" />
|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Webhook Output Examples
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Step Webhook">
|
||||
`stepWebhookUrl` - Callback that will be executed upon each agent inner thought
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "**Preliminary Research Report on the Financial Industry for crewai Enterprise Solution**\n1. Industry Overview and Trends\nThe financial industry in ....\nConclusion:\nThe financial industry presents a fertile ground for implementing AI solutions like crewai, particularly in areas such as digital customer engagement, risk management, and regulatory compliance. Further engagement with the lead is recommended to better tailor the crewai solution to their specific needs and scale.",
|
||||
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0"
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Task Webhook">
|
||||
`taskWebhookUrl` - Callback that will be executed upon the end of each task
|
||||
|
||||
```json
|
||||
{
|
||||
"description": "Using the information gathered from the lead's data, conduct preliminary research on the lead's industry, company background, and potential use cases for crewai. Focus on finding relevant data that can aid in scoring the lead and planning a strategy to pitch them crewai.The financial industry presents a fertile ground for implementing AI solutions like crewai, particularly in areas such as digital customer engagement, risk management, and regulatory compliance. Further engagement with the lead is recommended to better tailor the crewai solution to their specific needs and scale.",
|
||||
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0"
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Crew Webhook">
|
||||
`crewWebhookUrl` - Callback that will be executed upon the end of the crew execution
|
||||
|
||||
```json
|
||||
{
|
||||
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0",
|
||||
"result": {
|
||||
"lead_score": "Customer service enhancement, and compliance are particularly relevant.",
|
||||
"talking_points": [
|
||||
"Highlight how crewai's AI solutions can transform customer service with automated, personalized experiences and 24/7 support, improving both customer satisfaction and operational efficiency.",
|
||||
"Discuss crewai's potential to help the institution achieve its sustainability goals through better data analysis and decision-making, contributing to responsible investing and green initiatives.",
|
||||
"Emphasize crewai's ability to enhance compliance with evolving regulations through efficient data processing and reporting, reducing the risk of non-compliance penalties.",
|
||||
"Stress the adaptability of crewai to support both extensive multinational operations and smaller, targeted projects, ensuring the solution grows with the institution's needs."
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
103
docs/en/enterprise/guides/zapier-trigger.mdx
Normal file
103
docs/en/enterprise/guides/zapier-trigger.mdx
Normal file
@@ -0,0 +1,103 @@
|
||||
---
|
||||
title: "Zapier Trigger"
|
||||
description: "Trigger CrewAI crews from Zapier workflows to automate cross-app workflows"
|
||||
icon: "bolt"
|
||||
---
|
||||
|
||||
This guide will walk you through the process of setting up Zapier triggers for CrewAI Enterprise, allowing you to automate workflows between CrewAI Enterprise and other applications.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A CrewAI Enterprise account
|
||||
- A Zapier account
|
||||
- A Slack account (for this specific example)
|
||||
|
||||
## Step-by-Step Setup
|
||||
|
||||
<Steps>
|
||||
<Step title="Set Up the Slack Trigger">
|
||||
- In Zapier, create a new Zap.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-1.png" alt="Zapier 1" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Choose Slack as your trigger app">
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-2.png" alt="Zapier 2" />
|
||||
</Frame>
|
||||
- Select `New Pushed Message` as the Trigger Event.
|
||||
- Connect your Slack account if you haven't already.
|
||||
</Step>
|
||||
|
||||
<Step title="Configure the CrewAI Enterprise Action">
|
||||
- Add a new action step to your Zap.
|
||||
- Choose CrewAI+ as your action app and Kickoff as the Action Event
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-3.png" alt="Zapier 5" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Connect your CrewAI Enterprise account">
|
||||
- Connect your CrewAI Enterprise account.
|
||||
- Select the appropriate Crew for your workflow.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-4.png" alt="Zapier 6" />
|
||||
</Frame>
|
||||
- Configure the inputs for the Crew using the data from the Slack message.
|
||||
</Step>
|
||||
|
||||
<Step title="Format the CrewAI Enterprise Output">
|
||||
- Add another action step to format the text output from CrewAI Enterprise.
|
||||
- Use Zapier's formatting tools to convert the Markdown output to HTML.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-5.png" alt="Zapier 8" />
|
||||
</Frame>
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-6.png" alt="Zapier 9" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Send the Output via Email">
|
||||
- Add a final action step to send the formatted output via email.
|
||||
- Choose your preferred email service (e.g., Gmail, Outlook).
|
||||
- Configure the email details, including recipient, subject, and body.
|
||||
- Insert the formatted CrewAI Enterprise output into the email body.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-7.png" alt="Zapier 7" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Kick Off the crew from Slack">
|
||||
- Enter the text in your Slack channel
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-7b.png" alt="Zapier 10" />
|
||||
</Frame>
|
||||
|
||||
- Select the 3 ellipsis button and then chose Push to Zapier
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-8.png" alt="Zapier 11" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Select the crew and then Push to Kick Off">
|
||||
<Frame>
|
||||
<img src="/images/enterprise/zapier-9.png" alt="Zapier 12" />
|
||||
</Frame>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Tips for Success
|
||||
|
||||
- Ensure that your CrewAI Enterprise inputs are correctly mapped from the Slack message.
|
||||
- Test your Zap thoroughly before turning it on to catch any potential issues.
|
||||
- Consider adding error handling steps to manage potential failures in the workflow.
|
||||
|
||||
By following these steps, you'll have successfully set up Zapier triggers for CrewAI Enterprise, allowing for automated workflows triggered by Slack messages and resulting in email notifications with CrewAI Enterprise output.
|
||||
253
docs/en/enterprise/integrations/asana.mdx
Normal file
253
docs/en/enterprise/integrations/asana.mdx
Normal file
@@ -0,0 +1,253 @@
|
||||
---
|
||||
title: Asana Integration
|
||||
description: "Team task and project coordination with Asana integration for CrewAI."
|
||||
icon: "circle"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage tasks, projects, and team coordination through Asana. Create tasks, update project status, manage assignments, and streamline your team's workflow with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Asana integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- An Asana account with appropriate permissions
|
||||
- Connected your Asana account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Asana Integration
|
||||
|
||||
### 1. Connect Your Asana Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Asana** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for task and project management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="ASANA_CREATE_COMMENT">
|
||||
**Description:** Create a comment in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `task` (string, required): Task ID - The ID of the Task the comment will be added to. The comment will be authored by the currently authenticated user.
|
||||
- `text` (string, required): Text (example: "This is a comment.").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_CREATE_PROJECT">
|
||||
**Description:** Create a project in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string, required): Name (example: "Stuff to buy").
|
||||
- `workspace` (string, required): Workspace - Use Connect Portal Workflow Settings to allow users to select which Workspace to create Projects in. Defaults to the user's first Workspace if left blank.
|
||||
- `team` (string, optional): Team - Use Connect Portal Workflow Settings to allow users to select which Team to share this Project with. Defaults to the user's first Team if left blank.
|
||||
- `notes` (string, optional): Notes (example: "These are things we need to purchase.").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_PROJECTS">
|
||||
**Description:** Get a list of projects in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `archived` (string, optional): Archived - Choose "true" to show archived projects, "false" to display only active projects, or "default" to show both archived and active projects.
|
||||
- Options: `default`, `true`, `false`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_PROJECT_BY_ID">
|
||||
**Description:** Get a project by ID in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `projectFilterId` (string, required): Project ID.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_CREATE_TASK">
|
||||
**Description:** Create a task in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string, required): Name (example: "Task Name").
|
||||
- `workspace` (string, optional): Workspace - Use Connect Portal Workflow Settings to allow users to select which Workspace to create Tasks in. Defaults to the user's first Workspace if left blank..
|
||||
- `project` (string, optional): Project - Use Connect Portal Workflow Settings to allow users to select which Project to create this Task in.
|
||||
- `notes` (string, optional): Notes.
|
||||
- `dueOnDate` (string, optional): Due On - The date on which this task is due. Cannot be used together with Due At. (example: "YYYY-MM-DD").
|
||||
- `dueAtDate` (string, optional): Due At - The date and time (ISO timestamp) at which this task is due. Cannot be used together with Due On. (example: "2019-09-15T02:06:58.147Z").
|
||||
- `assignee` (string, optional): Assignee - The ID of the Asana user this task will be assigned to. Use Connect Portal Workflow Settings to allow users to select an Assignee.
|
||||
- `gid` (string, optional): External ID - An ID from your application to associate this task with. You can use this ID to sync updates to this task later.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_UPDATE_TASK">
|
||||
**Description:** Update a task in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `taskId` (string, required): Task ID - The ID of the Task that will be updated.
|
||||
- `completeStatus` (string, optional): Completed Status.
|
||||
- Options: `true`, `false`
|
||||
- `name` (string, optional): Name (example: "Task Name").
|
||||
- `notes` (string, optional): Notes.
|
||||
- `dueOnDate` (string, optional): Due On - The date on which this task is due. Cannot be used together with Due At. (example: "YYYY-MM-DD").
|
||||
- `dueAtDate` (string, optional): Due At - The date and time (ISO timestamp) at which this task is due. Cannot be used together with Due On. (example: "2019-09-15T02:06:58.147Z").
|
||||
- `assignee` (string, optional): Assignee - The ID of the Asana user this task will be assigned to. Use Connect Portal Workflow Settings to allow users to select an Assignee.
|
||||
- `gid` (string, optional): External ID - An ID from your application to associate this task with. You can use this ID to sync updates to this task later.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_TASKS">
|
||||
**Description:** Get a list of tasks in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `workspace` (string, optional): Workspace - The ID of the Workspace to filter tasks on. Use Connect Portal Workflow Settings to allow users to select a Workspace.
|
||||
- `project` (string, optional): Project - The ID of the Project to filter tasks on. Use Connect Portal Workflow Settings to allow users to select a Project.
|
||||
- `assignee` (string, optional): Assignee - The ID of the assignee to filter tasks on. Use Connect Portal Workflow Settings to allow users to select an Assignee.
|
||||
- `completedSince` (string, optional): Completed since - Only return tasks that are either incomplete or that have been completed since this time (ISO or Unix timestamp). (example: "2014-04-25T16:15:47-04:00").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_TASKS_BY_ID">
|
||||
**Description:** Get a list of tasks by ID in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `taskId` (string, required): Task ID.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_TASK_BY_EXTERNAL_ID">
|
||||
**Description:** Get a task by external ID in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `gid` (string, required): External ID - The ID that this task is associated or synced with, from your application.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_ADD_TASK_TO_SECTION">
|
||||
**Description:** Add a task to a section in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `sectionId` (string, required): Section ID - The ID of the section to add this task to.
|
||||
- `taskId` (string, required): Task ID - The ID of the task. (example: "1204619611402340").
|
||||
- `beforeTaskId` (string, optional): Before Task ID - The ID of a task in this section that this task will be inserted before. Cannot be used with After Task ID. (example: "1204619611402340").
|
||||
- `afterTaskId` (string, optional): After Task ID - The ID of a task in this section that this task will be inserted after. Cannot be used with Before Task ID. (example: "1204619611402340").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_TEAMS">
|
||||
**Description:** Get a list of teams in Asana.
|
||||
|
||||
**Parameters:**
|
||||
- `workspace` (string, required): Workspace - Returns the teams in this workspace visible to the authorized user.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ASANA_GET_WORKSPACES">
|
||||
**Description:** Get a list of workspaces in Asana.
|
||||
|
||||
**Parameters:** None required.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Asana Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Asana tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Asana capabilities
|
||||
asana_agent = Agent(
|
||||
role="Project Manager",
|
||||
goal="Manage tasks and projects in Asana efficiently",
|
||||
backstory="An AI assistant specialized in project management and task coordination.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new project
|
||||
create_project_task = Task(
|
||||
description="Create a new project called 'Q1 Marketing Campaign' in the Marketing workspace",
|
||||
agent=asana_agent,
|
||||
expected_output="Confirmation that the project was created successfully with project ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[asana_agent],
|
||||
tasks=[create_project_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Asana Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Asana tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["asana_create_task", "asana_update_task", "asana_get_tasks"]
|
||||
)
|
||||
|
||||
task_manager_agent = Agent(
|
||||
role="Task Manager",
|
||||
goal="Create and manage tasks efficiently",
|
||||
backstory="An AI assistant that focuses on task creation and management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to create and assign a task
|
||||
task_management = Task(
|
||||
description="Create a task called 'Review quarterly reports' and assign it to the appropriate team member",
|
||||
agent=task_manager_agent,
|
||||
expected_output="Task created and assigned successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[task_manager_agent],
|
||||
tasks=[task_management]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced Project Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
project_coordinator = Agent(
|
||||
role="Project Coordinator",
|
||||
goal="Coordinate project activities and track progress",
|
||||
backstory="An experienced project coordinator who ensures projects run smoothly.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving multiple Asana operations
|
||||
coordination_task = Task(
|
||||
description="""
|
||||
1. Get all active projects in the workspace
|
||||
2. For each project, get the list of incomplete tasks
|
||||
3. Create a summary report task in the 'Management Reports' project
|
||||
4. Add comments to overdue tasks to request status updates
|
||||
""",
|
||||
agent=project_coordinator,
|
||||
expected_output="Summary report created and status update requests sent for overdue tasks"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[project_coordinator],
|
||||
tasks=[coordination_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
268
docs/en/enterprise/integrations/box.mdx
Normal file
268
docs/en/enterprise/integrations/box.mdx
Normal file
@@ -0,0 +1,268 @@
|
||||
---
|
||||
title: Box Integration
|
||||
description: "File storage and document management with Box integration for CrewAI."
|
||||
icon: "box"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage files, folders, and documents through Box. Upload files, organize folder structures, search content, and streamline your team's document management with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Box integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Box account with appropriate permissions
|
||||
- Connected your Box account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Box Integration
|
||||
|
||||
### 1. Connect Your Box Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Box** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for file and folder management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="BOX_SAVE_FILE">
|
||||
**Description:** Save a file from URL in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `fileAttributes` (object, required): Attributes - File metadata including name, parent folder, and timestamps.
|
||||
```json
|
||||
{
|
||||
"content_created_at": "2012-12-12T10:53:43-08:00",
|
||||
"content_modified_at": "2012-12-12T10:53:43-08:00",
|
||||
"name": "qwerty.png",
|
||||
"parent": { "id": "1234567" }
|
||||
}
|
||||
```
|
||||
- `file` (string, required): File URL - Files must be smaller than 50MB in size. (example: "https://picsum.photos/200/300").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_SAVE_FILE_FROM_OBJECT">
|
||||
**Description:** Save a file in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `file` (string, required): File - Accepts a File Object containing file data. Files must be smaller than 50MB in size.
|
||||
- `fileName` (string, required): File Name (example: "qwerty.png").
|
||||
- `folder` (string, optional): Folder - Use Connect Portal Workflow Settings to allow users to select the File's Folder destination. Defaults to the user's root folder if left blank.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_GET_FILE_BY_ID">
|
||||
**Description:** Get a file by ID in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `fileId` (string, required): File ID - The unique identifier that represents a file. (example: "12345").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_LIST_FILES">
|
||||
**Description:** List files in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `folderId` (string, required): Folder ID - The unique identifier that represents a folder. (example: "0").
|
||||
- `filterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "direction",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "ASC"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_CREATE_FOLDER">
|
||||
**Description:** Create a folder in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `folderName` (string, required): Name - The name for the new folder. (example: "New Folder").
|
||||
- `folderParent` (object, required): Parent Folder - The parent folder where the new folder will be created.
|
||||
```json
|
||||
{
|
||||
"id": "123456"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_MOVE_FOLDER">
|
||||
**Description:** Move a folder in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `folderId` (string, required): Folder ID - The unique identifier that represents a folder. (example: "0").
|
||||
- `folderName` (string, required): Name - The name for the folder. (example: "New Folder").
|
||||
- `folderParent` (object, required): Parent Folder - The new parent folder destination.
|
||||
```json
|
||||
{
|
||||
"id": "123456"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_GET_FOLDER_BY_ID">
|
||||
**Description:** Get a folder by ID in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `folderId` (string, required): Folder ID - The unique identifier that represents a folder. (example: "0").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_SEARCH_FOLDERS">
|
||||
**Description:** Search folders in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `folderId` (string, required): Folder ID - The folder to search within.
|
||||
- `filterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "sort",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "name"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="BOX_DELETE_FOLDER">
|
||||
**Description:** Delete a folder in Box.
|
||||
|
||||
**Parameters:**
|
||||
- `folderId` (string, required): Folder ID - The unique identifier that represents a folder. (example: "0").
|
||||
- `recursive` (boolean, optional): Recursive - Delete a folder that is not empty by recursively deleting the folder and all of its content.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Box Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Box tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Box capabilities
|
||||
box_agent = Agent(
|
||||
role="Document Manager",
|
||||
goal="Manage files and folders in Box efficiently",
|
||||
backstory="An AI assistant specialized in document management and file organization.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a folder structure
|
||||
create_structure_task = Task(
|
||||
description="Create a folder called 'Project Files' in the root directory and upload a document from URL",
|
||||
agent=box_agent,
|
||||
expected_output="Folder created and file uploaded successfully"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[box_agent],
|
||||
tasks=[create_structure_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Box Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Box tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["box_create_folder", "box_save_file", "box_list_files"]
|
||||
)
|
||||
|
||||
file_organizer_agent = Agent(
|
||||
role="File Organizer",
|
||||
goal="Organize and manage file storage efficiently",
|
||||
backstory="An AI assistant that focuses on file organization and storage management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to organize files
|
||||
organization_task = Task(
|
||||
description="Create a folder structure for the marketing team and organize existing files",
|
||||
agent=file_organizer_agent,
|
||||
expected_output="Folder structure created and files organized"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[file_organizer_agent],
|
||||
tasks=[organization_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced File Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
file_manager = Agent(
|
||||
role="File Manager",
|
||||
goal="Maintain organized file structure and manage document lifecycle",
|
||||
backstory="An experienced file manager who ensures documents are properly organized and accessible.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving multiple Box operations
|
||||
management_task = Task(
|
||||
description="""
|
||||
1. List all files in the root folder
|
||||
2. Create monthly archive folders for the current year
|
||||
3. Move old files to appropriate archive folders
|
||||
4. Generate a summary report of the file organization
|
||||
""",
|
||||
agent=file_manager,
|
||||
expected_output="Files organized into archive structure with summary report"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[file_manager],
|
||||
tasks=[management_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
293
docs/en/enterprise/integrations/clickup.mdx
Normal file
293
docs/en/enterprise/integrations/clickup.mdx
Normal file
@@ -0,0 +1,293 @@
|
||||
---
|
||||
title: ClickUp Integration
|
||||
description: "Task and productivity management with ClickUp integration for CrewAI."
|
||||
icon: "list-check"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage tasks, projects, and productivity workflows through ClickUp. Create and update tasks, organize projects, manage team assignments, and streamline your productivity management with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the ClickUp integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A ClickUp account with appropriate permissions
|
||||
- Connected your ClickUp account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up ClickUp Integration
|
||||
|
||||
### 1. Connect Your ClickUp Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **ClickUp** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for task and project management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="CLICKUP_SEARCH_TASKS">
|
||||
**Description:** Search for tasks in ClickUp using advanced filters.
|
||||
|
||||
**Parameters:**
|
||||
- `taskFilterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "statuses%5B%5D",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "open"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available fields: `space_ids%5B%5D`, `project_ids%5B%5D`, `list_ids%5B%5D`, `statuses%5B%5D`, `include_closed`, `assignees%5B%5D`, `tags%5B%5D`, `due_date_gt`, `due_date_lt`, `date_created_gt`, `date_created_lt`, `date_updated_gt`, `date_updated_lt`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_TASK_IN_LIST">
|
||||
**Description:** Get tasks in a specific list in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `listId` (string, required): List - Select a List to get tasks from. Use Connect Portal User Settings to allow users to select a ClickUp List.
|
||||
- `taskFilterFormula` (string, optional): Search for tasks that match specified filters. For example: name=task1.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_CREATE_TASK">
|
||||
**Description:** Create a task in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `listId` (string, required): List - Select a List to create this task in. Use Connect Portal User Settings to allow users to select a ClickUp List.
|
||||
- `name` (string, required): Name - The task name.
|
||||
- `description` (string, optional): Description - Task description.
|
||||
- `status` (string, optional): Status - Select a Status for this task. Use Connect Portal User Settings to allow users to select a ClickUp Status.
|
||||
- `assignees` (string, optional): Assignees - Select a Member (or an array of member IDs) to be assigned to this task. Use Connect Portal User Settings to allow users to select a ClickUp Member.
|
||||
- `dueDate` (string, optional): Due Date - Specify a date for this task to be due on.
|
||||
- `additionalFields` (string, optional): Additional Fields - Specify additional fields to include on this task as JSON.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_UPDATE_TASK">
|
||||
**Description:** Update a task in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `taskId` (string, required): Task ID - The ID of the task to update.
|
||||
- `listId` (string, required): List - Select a List to create this task in. Use Connect Portal User Settings to allow users to select a ClickUp List.
|
||||
- `name` (string, optional): Name - The task name.
|
||||
- `description` (string, optional): Description - Task description.
|
||||
- `status` (string, optional): Status - Select a Status for this task. Use Connect Portal User Settings to allow users to select a ClickUp Status.
|
||||
- `assignees` (string, optional): Assignees - Select a Member (or an array of member IDs) to be assigned to this task. Use Connect Portal User Settings to allow users to select a ClickUp Member.
|
||||
- `dueDate` (string, optional): Due Date - Specify a date for this task to be due on.
|
||||
- `additionalFields` (string, optional): Additional Fields - Specify additional fields to include on this task as JSON.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_DELETE_TASK">
|
||||
**Description:** Delete a task in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `taskId` (string, required): Task ID - The ID of the task to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_LIST">
|
||||
**Description:** Get List information in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `spaceId` (string, required): Space ID - The ID of the space containing the lists.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_CUSTOM_FIELDS_IN_LIST">
|
||||
**Description:** Get Custom Fields in a List in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `listId` (string, required): List ID - The ID of the list to get custom fields from.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_ALL_FIELDS_IN_LIST">
|
||||
**Description:** Get All Fields in a List in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `listId` (string, required): List ID - The ID of the list to get all fields from.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_SPACE">
|
||||
**Description:** Get Space information in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `spaceId` (string, optional): Space ID - The ID of the space to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_FOLDERS">
|
||||
**Description:** Get Folders in ClickUp.
|
||||
|
||||
**Parameters:**
|
||||
- `spaceId` (string, required): Space ID - The ID of the space containing the folders.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CLICKUP_GET_MEMBER">
|
||||
**Description:** Get Member information in ClickUp.
|
||||
|
||||
**Parameters:** None required.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic ClickUp Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (ClickUp tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with ClickUp capabilities
|
||||
clickup_agent = Agent(
|
||||
role="Task Manager",
|
||||
goal="Manage tasks and projects in ClickUp efficiently",
|
||||
backstory="An AI assistant specialized in task management and productivity coordination.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new task
|
||||
create_task = Task(
|
||||
description="Create a task called 'Review Q1 Reports' in the Marketing list with high priority",
|
||||
agent=clickup_agent,
|
||||
expected_output="Task created successfully with task ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[clickup_agent],
|
||||
tasks=[create_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific ClickUp Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific ClickUp tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["clickup_create_task", "clickup_update_task", "clickup_search_tasks"]
|
||||
)
|
||||
|
||||
task_coordinator = Agent(
|
||||
role="Task Coordinator",
|
||||
goal="Create and manage tasks efficiently",
|
||||
backstory="An AI assistant that focuses on task creation and status management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage task workflow
|
||||
task_workflow = Task(
|
||||
description="Create a task for project planning and assign it to the development team",
|
||||
agent=task_coordinator,
|
||||
expected_output="Task created and assigned successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[task_coordinator],
|
||||
tasks=[task_workflow]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced Project Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
project_manager = Agent(
|
||||
role="Project Manager",
|
||||
goal="Coordinate project activities and track team productivity",
|
||||
backstory="An experienced project manager who ensures projects are delivered on time.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving multiple ClickUp operations
|
||||
project_coordination = Task(
|
||||
description="""
|
||||
1. Get all open tasks in the current space
|
||||
2. Identify overdue tasks and update their status
|
||||
3. Create a weekly report task summarizing project progress
|
||||
4. Assign the report task to the team lead
|
||||
""",
|
||||
agent=project_manager,
|
||||
expected_output="Project status updated and weekly report task created and assigned"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[project_manager],
|
||||
tasks=[project_coordination]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Task Search and Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
task_analyst = Agent(
|
||||
role="Task Analyst",
|
||||
goal="Analyze task patterns and optimize team productivity",
|
||||
backstory="An AI assistant that analyzes task data to improve team efficiency.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to analyze and optimize task distribution
|
||||
task_analysis = Task(
|
||||
description="""
|
||||
Search for all tasks assigned to team members in the last 30 days,
|
||||
analyze completion patterns, and create optimization recommendations
|
||||
""",
|
||||
agent=task_analyst,
|
||||
expected_output="Task analysis report with optimization recommendations"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[task_analyst],
|
||||
tasks=[task_analysis]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with ClickUp integration setup or troubleshooting.
|
||||
</Card>
|
||||
323
docs/en/enterprise/integrations/github.mdx
Normal file
323
docs/en/enterprise/integrations/github.mdx
Normal file
@@ -0,0 +1,323 @@
|
||||
---
|
||||
title: GitHub Integration
|
||||
description: "Repository and issue management with GitHub integration for CrewAI."
|
||||
icon: "github"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage repositories, issues, and releases through GitHub. Create and update issues, manage releases, track project development, and streamline your software development workflow with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the GitHub integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A GitHub account with appropriate repository permissions
|
||||
- Connected your GitHub account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up GitHub Integration
|
||||
|
||||
### 1. Connect Your GitHub Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **GitHub** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for repository and issue management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="GITHUB_CREATE_ISSUE">
|
||||
**Description:** Create an issue in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Issue. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Issue.
|
||||
- `title` (string, required): Issue Title - Specify the title of the issue to create.
|
||||
- `body` (string, optional): Issue Body - Specify the body contents of the issue to create.
|
||||
- `assignees` (string, optional): Assignees - Specify the assignee(s)' GitHub login as an array of strings for this issue. (example: `["octocat"]`).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_UPDATE_ISSUE">
|
||||
**Description:** Update an issue in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Issue. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Issue.
|
||||
- `issue_number` (string, required): Issue Number - Specify the number of the issue to update.
|
||||
- `title` (string, required): Issue Title - Specify the title of the issue to update.
|
||||
- `body` (string, optional): Issue Body - Specify the body contents of the issue to update.
|
||||
- `assignees` (string, optional): Assignees - Specify the assignee(s)' GitHub login as an array of strings for this issue. (example: `["octocat"]`).
|
||||
- `state` (string, optional): State - Specify the updated state of the issue.
|
||||
- Options: `open`, `closed`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_GET_ISSUE_BY_NUMBER">
|
||||
**Description:** Get an issue by number in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Issue. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Issue.
|
||||
- `issue_number` (string, required): Issue Number - Specify the number of the issue to fetch.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_LOCK_ISSUE">
|
||||
**Description:** Lock an issue in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Issue. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Issue.
|
||||
- `issue_number` (string, required): Issue Number - Specify the number of the issue to lock.
|
||||
- `lock_reason` (string, required): Lock Reason - Specify a reason for locking the issue or pull request conversation.
|
||||
- Options: `off-topic`, `too heated`, `resolved`, `spam`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_SEARCH_ISSUE">
|
||||
**Description:** Search for issues in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Issue. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Issue.
|
||||
- `filter` (object, required): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "assignee",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "octocat"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available fields: `assignee`, `creator`, `mentioned`, `labels`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_CREATE_RELEASE">
|
||||
**Description:** Create a release in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Release. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Release.
|
||||
- `tag_name` (string, required): Name - Specify the name of the release tag to be created. (example: "v1.0.0").
|
||||
- `target_commitish` (string, optional): Target - Specify the target of the release. This can either be a branch name or a commit SHA. Defaults to the main branch. (example: "master").
|
||||
- `body` (string, optional): Body - Specify a description for this release.
|
||||
- `draft` (string, optional): Draft - Specify whether the created release should be a draft (unpublished) release.
|
||||
- Options: `true`, `false`
|
||||
- `prerelease` (string, optional): Prerelease - Specify whether the created release should be a prerelease.
|
||||
- Options: `true`, `false`
|
||||
- `discussion_category_name` (string, optional): Discussion Category Name - If specified, a discussion of the specified category is created and linked to the release. The value must be a category that already exists in the repository.
|
||||
- `generate_release_notes` (string, optional): Release Notes - Specify whether the created release should automatically create release notes using the provided name and body specified.
|
||||
- Options: `true`, `false`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_UPDATE_RELEASE">
|
||||
**Description:** Update a release in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Release. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Release.
|
||||
- `id` (string, required): Release ID - Specify the ID of the release to update.
|
||||
- `tag_name` (string, optional): Name - Specify the name of the release tag to be updated. (example: "v1.0.0").
|
||||
- `target_commitish` (string, optional): Target - Specify the target of the release. This can either be a branch name or a commit SHA. Defaults to the main branch. (example: "master").
|
||||
- `body` (string, optional): Body - Specify a description for this release.
|
||||
- `draft` (string, optional): Draft - Specify whether the created release should be a draft (unpublished) release.
|
||||
- Options: `true`, `false`
|
||||
- `prerelease` (string, optional): Prerelease - Specify whether the created release should be a prerelease.
|
||||
- Options: `true`, `false`
|
||||
- `discussion_category_name` (string, optional): Discussion Category Name - If specified, a discussion of the specified category is created and linked to the release. The value must be a category that already exists in the repository.
|
||||
- `generate_release_notes` (string, optional): Release Notes - Specify whether the created release should automatically create release notes using the provided name and body specified.
|
||||
- Options: `true`, `false`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_GET_RELEASE_BY_ID">
|
||||
**Description:** Get a release by ID in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Release. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Release.
|
||||
- `id` (string, required): Release ID - Specify the release ID of the release to fetch.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_GET_RELEASE_BY_TAG_NAME">
|
||||
**Description:** Get a release by tag name in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Release. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Release.
|
||||
- `tag_name` (string, required): Name - Specify the tag of the release to fetch. (example: "v1.0.0").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GITHUB_DELETE_RELEASE">
|
||||
**Description:** Delete a release in GitHub.
|
||||
|
||||
**Parameters:**
|
||||
- `owner` (string, required): Owner - Specify the name of the account owner of the associated repository for this Release. (example: "abc").
|
||||
- `repo` (string, required): Repository - Specify the name of the associated repository for this Release.
|
||||
- `id` (string, required): Release ID - Specify the ID of the release to delete.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic GitHub Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (GitHub tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with GitHub capabilities
|
||||
github_agent = Agent(
|
||||
role="Repository Manager",
|
||||
goal="Manage GitHub repositories, issues, and releases efficiently",
|
||||
backstory="An AI assistant specialized in repository management and issue tracking.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new issue
|
||||
create_issue_task = Task(
|
||||
description="Create a bug report issue for the login functionality in the main repository",
|
||||
agent=github_agent,
|
||||
expected_output="Issue created successfully with issue number"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[github_agent],
|
||||
tasks=[create_issue_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific GitHub Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific GitHub tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["github_create_issue", "github_update_issue", "github_search_issue"]
|
||||
)
|
||||
|
||||
issue_manager = Agent(
|
||||
role="Issue Manager",
|
||||
goal="Create and manage GitHub issues efficiently",
|
||||
backstory="An AI assistant that focuses on issue tracking and management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage issue workflow
|
||||
issue_workflow = Task(
|
||||
description="Create a feature request issue and assign it to the development team",
|
||||
agent=issue_manager,
|
||||
expected_output="Feature request issue created and assigned successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[issue_manager],
|
||||
tasks=[issue_workflow]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Release Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
release_manager = Agent(
|
||||
role="Release Manager",
|
||||
goal="Manage software releases and versioning",
|
||||
backstory="An experienced release manager who handles version control and release processes.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new release
|
||||
release_task = Task(
|
||||
description="""
|
||||
Create a new release v2.1.0 for the project with:
|
||||
- Auto-generated release notes
|
||||
- Target the main branch
|
||||
- Include a description of new features and bug fixes
|
||||
""",
|
||||
agent=release_manager,
|
||||
expected_output="Release v2.1.0 created successfully with release notes"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[release_manager],
|
||||
tasks=[release_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Issue Tracking and Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
project_coordinator = Agent(
|
||||
role="Project Coordinator",
|
||||
goal="Track and coordinate project issues and development progress",
|
||||
backstory="An AI assistant that helps coordinate development work and track project progress.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving multiple GitHub operations
|
||||
coordination_task = Task(
|
||||
description="""
|
||||
1. Search for all open issues assigned to the current milestone
|
||||
2. Identify overdue issues and update their priority labels
|
||||
3. Create a weekly progress report issue
|
||||
4. Lock resolved issues that have been inactive for 30 days
|
||||
""",
|
||||
agent=project_coordinator,
|
||||
expected_output="Project coordination completed with progress report and issue management"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[project_coordinator],
|
||||
tasks=[coordination_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with GitHub integration setup or troubleshooting.
|
||||
</Card>
|
||||
356
docs/en/enterprise/integrations/gmail.mdx
Normal file
356
docs/en/enterprise/integrations/gmail.mdx
Normal file
@@ -0,0 +1,356 @@
|
||||
---
|
||||
title: Gmail Integration
|
||||
description: "Email and contact management with Gmail integration for CrewAI."
|
||||
icon: "envelope"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage emails, contacts, and drafts through Gmail. Send emails, search messages, manage contacts, create drafts, and streamline your email communications with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Gmail integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Gmail account with appropriate permissions
|
||||
- Connected your Gmail account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Gmail Integration
|
||||
|
||||
### 1. Connect Your Gmail Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Gmail** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for email and contact management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="GMAIL_SEND_EMAIL">
|
||||
**Description:** Send an email in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `toRecipients` (array, required): To - Specify the recipients as either a single string or a JSON array.
|
||||
```json
|
||||
[
|
||||
"recipient1@domain.com",
|
||||
"recipient2@domain.com"
|
||||
]
|
||||
```
|
||||
- `from` (string, required): From - Specify the email of the sender.
|
||||
- `subject` (string, required): Subject - Specify the subject of the message.
|
||||
- `messageContent` (string, required): Message Content - Specify the content of the email message as plain text or HTML.
|
||||
- `attachments` (string, optional): Attachments - Accepts either a single file object or a JSON array of file objects.
|
||||
- `additionalHeaders` (object, optional): Additional Headers - Specify any additional header fields here.
|
||||
```json
|
||||
{
|
||||
"reply-to": "Sender Name <sender@domain.com>"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_GET_EMAIL_BY_ID">
|
||||
**Description:** Get an email by ID in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `userId` (string, required): User ID - Specify the user's email address. (example: "user@domain.com").
|
||||
- `messageId` (string, required): Message ID - Specify the ID of the message to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_SEARCH_FOR_EMAIL">
|
||||
**Description:** Search for emails in Gmail using advanced filters.
|
||||
|
||||
**Parameters:**
|
||||
- `emailFilterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "from",
|
||||
"operator": "$stringContains",
|
||||
"value": "example@domain.com"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available fields: `from`, `to`, `date`, `label`, `subject`, `cc`, `bcc`, `category`, `deliveredto:`, `size`, `filename`, `older_than`, `newer_than`, `list`, `is:important`, `is:unread`, `is:snoozed`, `is:starred`, `is:read`, `has:drive`, `has:document`, `has:spreadsheet`, `has:presentation`, `has:attachment`, `has:youtube`, `has:userlabels`
|
||||
- `paginationParameters` (object, optional): Pagination Parameters.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "page_cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_DELETE_EMAIL">
|
||||
**Description:** Delete an email in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `userId` (string, required): User ID - Specify the user's email address. (example: "user@domain.com").
|
||||
- `messageId` (string, required): Message ID - Specify the ID of the message to trash.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_CREATE_A_CONTACT">
|
||||
**Description:** Create a contact in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `givenName` (string, required): Given Name - Specify the Given Name of the Contact to create. (example: "John").
|
||||
- `familyName` (string, required): Family Name - Specify the Family Name of the Contact to create. (example: "Doe").
|
||||
- `email` (string, required): Email - Specify the Email Address of the Contact to create.
|
||||
- `additionalFields` (object, optional): Additional Fields - Additional contact information.
|
||||
```json
|
||||
{
|
||||
"addresses": [
|
||||
{
|
||||
"streetAddress": "1000 North St.",
|
||||
"city": "Los Angeles"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_GET_CONTACT_BY_RESOURCE_NAME">
|
||||
**Description:** Get a contact by resource name in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `resourceName` (string, required): Resource Name - Specify the resource name of the contact to fetch.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_SEARCH_FOR_CONTACT">
|
||||
**Description:** Search for a contact in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `searchTerm` (string, required): Term - Specify a search term to search for near or exact matches on the names, nickNames, emailAddresses, phoneNumbers, or organizations Contact properties.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_DELETE_CONTACT">
|
||||
**Description:** Delete a contact in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `resourceName` (string, required): Resource Name - Specify the resource name of the contact to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GMAIL_CREATE_DRAFT">
|
||||
**Description:** Create a draft in Gmail.
|
||||
|
||||
**Parameters:**
|
||||
- `toRecipients` (array, optional): To - Specify the recipients as either a single string or a JSON array.
|
||||
```json
|
||||
[
|
||||
"recipient1@domain.com",
|
||||
"recipient2@domain.com"
|
||||
]
|
||||
```
|
||||
- `from` (string, optional): From - Specify the email of the sender.
|
||||
- `subject` (string, optional): Subject - Specify the subject of the message.
|
||||
- `messageContent` (string, optional): Message Content - Specify the content of the email message as plain text or HTML.
|
||||
- `attachments` (string, optional): Attachments - Accepts either a single file object or a JSON array of file objects.
|
||||
- `additionalHeaders` (object, optional): Additional Headers - Specify any additional header fields here.
|
||||
```json
|
||||
{
|
||||
"reply-to": "Sender Name <sender@domain.com>"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Gmail Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Gmail tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Gmail capabilities
|
||||
gmail_agent = Agent(
|
||||
role="Email Manager",
|
||||
goal="Manage email communications and contacts efficiently",
|
||||
backstory="An AI assistant specialized in email management and communication.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to send a follow-up email
|
||||
send_email_task = Task(
|
||||
description="Send a follow-up email to john@example.com about the project update meeting",
|
||||
agent=gmail_agent,
|
||||
expected_output="Email sent successfully with confirmation"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[gmail_agent],
|
||||
tasks=[send_email_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Gmail Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Gmail tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["gmail_send_email", "gmail_search_for_email", "gmail_create_draft"]
|
||||
)
|
||||
|
||||
email_coordinator = Agent(
|
||||
role="Email Coordinator",
|
||||
goal="Coordinate email communications and manage drafts",
|
||||
backstory="An AI assistant that focuses on email coordination and draft management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to prepare and send emails
|
||||
email_coordination = Task(
|
||||
description="Search for emails from the marketing team, create a summary draft, and send it to stakeholders",
|
||||
agent=email_coordinator,
|
||||
expected_output="Summary email sent to stakeholders"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[email_coordinator],
|
||||
tasks=[email_coordination]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Contact Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
contact_manager = Agent(
|
||||
role="Contact Manager",
|
||||
goal="Manage and organize email contacts efficiently",
|
||||
backstory="An experienced contact manager who maintains organized contact databases.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage contacts
|
||||
contact_task = Task(
|
||||
description="""
|
||||
1. Search for contacts from the 'example.com' domain
|
||||
2. Create new contacts for recent email senders not in the contact list
|
||||
3. Update contact information with recent interaction data
|
||||
""",
|
||||
agent=contact_manager,
|
||||
expected_output="Contact database updated with new contacts and recent interactions"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[contact_manager],
|
||||
tasks=[contact_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Email Search and Analysis
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
email_analyst = Agent(
|
||||
role="Email Analyst",
|
||||
goal="Analyze email patterns and provide insights",
|
||||
backstory="An AI assistant that analyzes email data to provide actionable insights.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to analyze email patterns
|
||||
analysis_task = Task(
|
||||
description="""
|
||||
Search for all unread emails from the last 7 days,
|
||||
categorize them by sender domain,
|
||||
and create a summary report of communication patterns
|
||||
""",
|
||||
agent=email_analyst,
|
||||
expected_output="Email analysis report with communication patterns and recommendations"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[email_analyst],
|
||||
tasks=[analysis_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Automated Email Workflows
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
workflow_manager = Agent(
|
||||
role="Email Workflow Manager",
|
||||
goal="Automate email workflows and responses",
|
||||
backstory="An AI assistant that manages automated email workflows and responses.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving multiple Gmail operations
|
||||
workflow_task = Task(
|
||||
description="""
|
||||
1. Search for emails with 'urgent' in the subject from the last 24 hours
|
||||
2. Create draft responses for each urgent email
|
||||
3. Send automated acknowledgment emails to senders
|
||||
4. Create a summary report of urgent items requiring attention
|
||||
""",
|
||||
agent=workflow_manager,
|
||||
expected_output="Urgent emails processed with automated responses and summary report"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[workflow_manager],
|
||||
tasks=[workflow_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Gmail integration setup or troubleshooting.
|
||||
</Card>
|
||||
391
docs/en/enterprise/integrations/google_calendar.mdx
Normal file
391
docs/en/enterprise/integrations/google_calendar.mdx
Normal file
@@ -0,0 +1,391 @@
|
||||
---
|
||||
title: Google Calendar Integration
|
||||
description: "Event and schedule management with Google Calendar integration for CrewAI."
|
||||
icon: "calendar"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage calendar events, schedules, and availability through Google Calendar. Create and update events, manage attendees, check availability, and streamline your scheduling workflows with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Google Calendar integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Google account with Google Calendar access
|
||||
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Google Calendar Integration
|
||||
|
||||
### 1. Connect Your Google Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Google Calendar** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for calendar and contact access
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="GOOGLE_CALENDAR_CREATE_EVENT">
|
||||
**Description:** Create an event in Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `eventName` (string, required): Event name.
|
||||
- `startTime` (string, required): Start time - Accepts Unix timestamp or ISO8601 date formats.
|
||||
- `endTime` (string, optional): End time - Defaults to one hour after the start time if left blank.
|
||||
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
|
||||
- `attendees` (string, optional): Attendees - Accepts an array of email addresses or email addresses separated by commas.
|
||||
- `eventLocation` (string, optional): Event location.
|
||||
- `eventDescription` (string, optional): Event description.
|
||||
- `eventId` (string, optional): Event ID - An ID from your application to associate this event with. You can use this ID to sync updates to this event later.
|
||||
- `includeMeetLink` (boolean, optional): Include Google Meet link? - Automatically creates Google Meet conference link for this event.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_UPDATE_EVENT">
|
||||
**Description:** Update an existing event in Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `eventId` (string, required): Event ID - The ID of the event to update.
|
||||
- `eventName` (string, optional): Event name.
|
||||
- `startTime` (string, optional): Start time - Accepts Unix timestamp or ISO8601 date formats.
|
||||
- `endTime` (string, optional): End time - Defaults to one hour after the start time if left blank.
|
||||
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
|
||||
- `attendees` (string, optional): Attendees - Accepts an array of email addresses or email addresses separated by commas.
|
||||
- `eventLocation` (string, optional): Event location.
|
||||
- `eventDescription` (string, optional): Event description.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_LIST_EVENTS">
|
||||
**Description:** List events from Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
|
||||
- `after` (string, optional): After - Filters events that start after the provided date (Unix in milliseconds or ISO timestamp). (example: "2025-04-12T10:00:00Z or 1712908800000").
|
||||
- `before` (string, optional): Before - Filters events that end before the provided date (Unix in milliseconds or ISO timestamp). (example: "2025-04-12T10:00:00Z or 1712908800000").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_GET_EVENT_BY_ID">
|
||||
**Description:** Get a specific event by ID from Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `eventId` (string, required): Event ID.
|
||||
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_DELETE_EVENT">
|
||||
**Description:** Delete an event from Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `eventId` (string, required): Event ID - The ID of the calendar event to be deleted.
|
||||
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_GET_CONTACTS">
|
||||
**Description:** Get contacts from Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Pagination Parameters.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "page_cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_SEARCH_CONTACTS">
|
||||
**Description:** Search for contacts in Google Calendar.
|
||||
|
||||
**Parameters:**
|
||||
- `query` (string, optional): Search query to search contacts.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_LIST_DIRECTORY_PEOPLE">
|
||||
**Description:** List directory people.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Pagination Parameters.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "page_cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_SEARCH_DIRECTORY_PEOPLE">
|
||||
**Description:** Search directory people.
|
||||
|
||||
**Parameters:**
|
||||
- `query` (string, required): Search query to search contacts.
|
||||
- `paginationParameters` (object, optional): Pagination Parameters.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "page_cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_LIST_OTHER_CONTACTS">
|
||||
**Description:** List other contacts.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Pagination Parameters.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "page_cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_SEARCH_OTHER_CONTACTS">
|
||||
**Description:** Search other contacts.
|
||||
|
||||
**Parameters:**
|
||||
- `query` (string, optional): Search query to search contacts.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_CALENDAR_GET_AVAILABILITY">
|
||||
**Description:** Get availability information for calendars.
|
||||
|
||||
**Parameters:**
|
||||
- `timeMin` (string, required): The start of the interval. In ISO format.
|
||||
- `timeMax` (string, required): The end of the interval. In ISO format.
|
||||
- `timeZone` (string, optional): Time zone used in the response. Optional. The default is UTC.
|
||||
- `items` (array, optional): List of calendars and/or groups to query. Defaults to the user default calendar.
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": "calendar_id_1"
|
||||
},
|
||||
{
|
||||
"id": "calendar_id_2"
|
||||
}
|
||||
]
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Calendar Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Google Calendar tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Google Calendar capabilities
|
||||
calendar_agent = Agent(
|
||||
role="Schedule Manager",
|
||||
goal="Manage calendar events and scheduling efficiently",
|
||||
backstory="An AI assistant specialized in calendar management and scheduling coordination.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a meeting
|
||||
create_meeting_task = Task(
|
||||
description="Create a team standup meeting for tomorrow at 9 AM with the development team",
|
||||
agent=calendar_agent,
|
||||
expected_output="Meeting created successfully with Google Meet link"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[calendar_agent],
|
||||
tasks=[create_meeting_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Calendar Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Google Calendar tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["google_calendar_create_event", "google_calendar_list_events", "google_calendar_get_availability"]
|
||||
)
|
||||
|
||||
meeting_coordinator = Agent(
|
||||
role="Meeting Coordinator",
|
||||
goal="Coordinate meetings and check availability",
|
||||
backstory="An AI assistant that focuses on meeting scheduling and availability management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to schedule a meeting with availability check
|
||||
schedule_meeting = Task(
|
||||
description="Check availability for next week and schedule a project review meeting with stakeholders",
|
||||
agent=meeting_coordinator,
|
||||
expected_output="Meeting scheduled after checking availability of all participants"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[meeting_coordinator],
|
||||
tasks=[schedule_meeting]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Event Management and Updates
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
event_manager = Agent(
|
||||
role="Event Manager",
|
||||
goal="Manage and update calendar events efficiently",
|
||||
backstory="An experienced event manager who handles event logistics and updates.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage event updates
|
||||
event_management = Task(
|
||||
description="""
|
||||
1. List all events for this week
|
||||
2. Update any events that need location changes to include video conference links
|
||||
3. Send calendar invitations to new team members for recurring meetings
|
||||
""",
|
||||
agent=event_manager,
|
||||
expected_output="Weekly events updated with proper locations and new attendees added"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[event_manager],
|
||||
tasks=[event_management]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Contact and Availability Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
availability_coordinator = Agent(
|
||||
role="Availability Coordinator",
|
||||
goal="Coordinate availability and manage contacts for scheduling",
|
||||
backstory="An AI assistant that specializes in availability management and contact coordination.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to coordinate availability
|
||||
availability_task = Task(
|
||||
description="""
|
||||
1. Search for contacts in the engineering department
|
||||
2. Check availability for all engineers next Friday afternoon
|
||||
3. Create a team meeting for the first available 2-hour slot
|
||||
4. Include Google Meet link and send invitations
|
||||
""",
|
||||
agent=availability_coordinator,
|
||||
expected_output="Team meeting scheduled based on availability with all engineers invited"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[availability_coordinator],
|
||||
tasks=[availability_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Automated Scheduling Workflows
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
scheduling_automator = Agent(
|
||||
role="Scheduling Automator",
|
||||
goal="Automate scheduling workflows and calendar management",
|
||||
backstory="An AI assistant that automates complex scheduling scenarios and calendar workflows.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex scheduling automation task
|
||||
automation_task = Task(
|
||||
description="""
|
||||
1. List all upcoming events for the next two weeks
|
||||
2. Identify any scheduling conflicts or back-to-back meetings
|
||||
3. Suggest optimal meeting times by checking availability
|
||||
4. Create buffer time between meetings where needed
|
||||
5. Update event descriptions with agenda items and meeting links
|
||||
""",
|
||||
agent=scheduling_automator,
|
||||
expected_output="Calendar optimized with resolved conflicts, buffer times, and updated meeting details"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[scheduling_automator],
|
||||
tasks=[automation_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Authentication Errors**
|
||||
- Ensure your Google account has the necessary permissions for calendar access
|
||||
- Verify that the OAuth connection includes all required scopes for Google Calendar API
|
||||
- Check if calendar sharing settings allow the required access level
|
||||
|
||||
**Event Creation Issues**
|
||||
- Verify that time formats are correct (ISO8601 or Unix timestamps)
|
||||
- Ensure attendee email addresses are properly formatted
|
||||
- Check that the target calendar exists and is accessible
|
||||
- Verify time zones are correctly specified
|
||||
|
||||
**Availability and Time Conflicts**
|
||||
- Use proper ISO format for time ranges when checking availability
|
||||
- Ensure time zones are consistent across all operations
|
||||
- Verify that calendar IDs are correct when checking multiple calendars
|
||||
|
||||
**Contact and People Search**
|
||||
- Ensure search queries are properly formatted
|
||||
- Check that directory access permissions are granted
|
||||
- Verify that contact information is up to date and accessible
|
||||
|
||||
**Event Updates and Deletions**
|
||||
- Verify that event IDs are correct and events exist
|
||||
- Ensure you have edit permissions for the events
|
||||
- Check that calendar ownership allows modifications
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Google Calendar integration setup or troubleshooting.
|
||||
</Card>
|
||||
321
docs/en/enterprise/integrations/google_sheets.mdx
Normal file
321
docs/en/enterprise/integrations/google_sheets.mdx
Normal file
@@ -0,0 +1,321 @@
|
||||
---
|
||||
title: Google Sheets Integration
|
||||
description: "Spreadsheet data synchronization with Google Sheets integration for CrewAI."
|
||||
icon: "google"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage spreadsheet data through Google Sheets. Read rows, create new entries, update existing data, and streamline your data management workflows with AI-powered automation. Perfect for data tracking, reporting, and collaborative data management.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Google Sheets integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Google account with Google Sheets access
|
||||
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
- Spreadsheets with proper column headers for data operations
|
||||
|
||||
## Setting Up Google Sheets Integration
|
||||
|
||||
### 1. Connect Your Google Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Google Sheets** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for spreadsheet access
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="GOOGLE_SHEETS_GET_ROW">
|
||||
**Description:** Get rows from a Google Sheets spreadsheet.
|
||||
|
||||
**Parameters:**
|
||||
- `spreadsheetId` (string, required): Spreadsheet - Use Connect Portal Workflow Settings to allow users to select a spreadsheet. Defaults to using the first worksheet in the selected spreadsheet.
|
||||
- `limit` (string, optional): Limit rows - Limit the maximum number of rows to return.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_SHEETS_CREATE_ROW">
|
||||
**Description:** Create a new row in a Google Sheets spreadsheet.
|
||||
|
||||
**Parameters:**
|
||||
- `spreadsheetId` (string, required): Spreadsheet - Use Connect Portal Workflow Settings to allow users to select a spreadsheet. Defaults to using the first worksheet in the selected spreadsheet..
|
||||
- `worksheet` (string, required): Worksheet - Your worksheet must have column headers.
|
||||
- `additionalFields` (object, required): Fields - Include fields to create this row with, as an object with keys of Column Names. Use Connect Portal Workflow Settings to allow users to select a Column Mapping.
|
||||
```json
|
||||
{
|
||||
"columnName1": "columnValue1",
|
||||
"columnName2": "columnValue2",
|
||||
"columnName3": "columnValue3",
|
||||
"columnName4": "columnValue4"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="GOOGLE_SHEETS_UPDATE_ROW">
|
||||
**Description:** Update existing rows in a Google Sheets spreadsheet.
|
||||
|
||||
**Parameters:**
|
||||
- `spreadsheetId` (string, required): Spreadsheet - Use Connect Portal Workflow Settings to allow users to select a spreadsheet. Defaults to using the first worksheet in the selected spreadsheet.
|
||||
- `worksheet` (string, required): Worksheet - Your worksheet must have column headers.
|
||||
- `filterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions to identify which rows to update.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "status",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "pending"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available operators: `$stringContains`, `$stringDoesNotContain`, `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringStartsWith`, `$stringDoesNotStartWith`, `$stringEndsWith`, `$stringDoesNotEndWith`, `$numberGreaterThan`, `$numberLessThan`, `$numberEquals`, `$numberDoesNotEqual`, `$dateTimeAfter`, `$dateTimeBefore`, `$dateTimeEquals`, `$booleanTrue`, `$booleanFalse`, `$exists`, `$doesNotExist`
|
||||
- `additionalFields` (object, required): Fields - Include fields to update, as an object with keys of Column Names. Use Connect Portal Workflow Settings to allow users to select a Column Mapping.
|
||||
```json
|
||||
{
|
||||
"columnName1": "newValue1",
|
||||
"columnName2": "newValue2",
|
||||
"columnName3": "newValue3",
|
||||
"columnName4": "newValue4"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Google Sheets Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Google Sheets tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Google Sheets capabilities
|
||||
sheets_agent = Agent(
|
||||
role="Data Manager",
|
||||
goal="Manage spreadsheet data and track information efficiently",
|
||||
backstory="An AI assistant specialized in data management and spreadsheet operations.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to add new data to a spreadsheet
|
||||
data_entry_task = Task(
|
||||
description="Add a new customer record to the customer database spreadsheet with name, email, and signup date",
|
||||
agent=sheets_agent,
|
||||
expected_output="New customer record added successfully to the spreadsheet"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[sheets_agent],
|
||||
tasks=[data_entry_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Google Sheets Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Google Sheets tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["google_sheets_get_row", "google_sheets_create_row"]
|
||||
)
|
||||
|
||||
data_collector = Agent(
|
||||
role="Data Collector",
|
||||
goal="Collect and organize data in spreadsheets",
|
||||
backstory="An AI assistant that focuses on data collection and organization.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to collect and organize data
|
||||
data_collection = Task(
|
||||
description="Retrieve current inventory data and add new product entries to the inventory spreadsheet",
|
||||
agent=data_collector,
|
||||
expected_output="Inventory data retrieved and new products added successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[data_collector],
|
||||
tasks=[data_collection]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Data Analysis and Reporting
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
data_analyst = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze spreadsheet data and generate insights",
|
||||
backstory="An experienced data analyst who extracts insights from spreadsheet data.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to analyze data and create reports
|
||||
analysis_task = Task(
|
||||
description="""
|
||||
1. Retrieve all sales data from the current month's spreadsheet
|
||||
2. Analyze the data for trends and patterns
|
||||
3. Create a summary report in a new row with key metrics
|
||||
""",
|
||||
agent=data_analyst,
|
||||
expected_output="Sales data analyzed and summary report created with key insights"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[data_analyst],
|
||||
tasks=[analysis_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Automated Data Updates
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
data_updater = Agent(
|
||||
role="Data Updater",
|
||||
goal="Automatically update and maintain spreadsheet data",
|
||||
backstory="An AI assistant that maintains data accuracy and updates records automatically.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to update data based on conditions
|
||||
update_task = Task(
|
||||
description="""
|
||||
1. Find all pending orders in the orders spreadsheet
|
||||
2. Update their status to 'processing'
|
||||
3. Add a timestamp for when the status was updated
|
||||
4. Log the changes in a separate tracking sheet
|
||||
""",
|
||||
agent=data_updater,
|
||||
expected_output="All pending orders updated to processing status with timestamps logged"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[data_updater],
|
||||
tasks=[update_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Complex Data Management Workflow
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
workflow_manager = Agent(
|
||||
role="Data Workflow Manager",
|
||||
goal="Manage complex data workflows across multiple spreadsheets",
|
||||
backstory="An AI assistant that orchestrates complex data operations across multiple spreadsheets.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex workflow task
|
||||
workflow_task = Task(
|
||||
description="""
|
||||
1. Get all customer data from the main customer spreadsheet
|
||||
2. Create monthly summary entries for active customers
|
||||
3. Update customer status based on activity in the last 30 days
|
||||
4. Generate a monthly report with customer metrics
|
||||
5. Archive inactive customer records to a separate sheet
|
||||
""",
|
||||
agent=workflow_manager,
|
||||
expected_output="Monthly customer workflow completed with updated statuses and generated reports"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[workflow_manager],
|
||||
tasks=[workflow_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Permission Errors**
|
||||
- Ensure your Google account has edit access to the target spreadsheets
|
||||
- Verify that the OAuth connection includes required scopes for Google Sheets API
|
||||
- Check that spreadsheets are shared with the authenticated account
|
||||
|
||||
**Spreadsheet Structure Issues**
|
||||
- Ensure worksheets have proper column headers before creating or updating rows
|
||||
- Verify that column names in `additionalFields` match the actual column headers
|
||||
- Check that the specified worksheet exists in the spreadsheet
|
||||
|
||||
**Data Type and Format Issues**
|
||||
- Ensure data values match the expected format for each column
|
||||
- Use proper date formats for date columns (ISO format recommended)
|
||||
- Verify that numeric values are properly formatted for number columns
|
||||
|
||||
**Filter Formula Issues**
|
||||
- Ensure filter formulas follow the correct JSON structure for disjunctive normal form
|
||||
- Use valid field names that match actual column headers
|
||||
- Test simple filters before building complex multi-condition queries
|
||||
- Verify that operator types match the data types in the columns
|
||||
|
||||
**Row Limits and Performance**
|
||||
- Be mindful of row limits when using `GOOGLE_SHEETS_GET_ROW`
|
||||
- Consider pagination for large datasets
|
||||
- Use specific filters to reduce the amount of data processed
|
||||
|
||||
**Update Operations**
|
||||
- Ensure filter conditions properly identify the intended rows for updates
|
||||
- Test filter conditions with small datasets before large updates
|
||||
- Verify that all required fields are included in update operations
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Google Sheets integration setup or troubleshooting.
|
||||
</Card>
|
||||
579
docs/en/enterprise/integrations/hubspot.mdx
Normal file
579
docs/en/enterprise/integrations/hubspot.mdx
Normal file
@@ -0,0 +1,579 @@
|
||||
---
|
||||
title: "HubSpot Integration"
|
||||
description: "Manage companies and contacts in HubSpot with CrewAI."
|
||||
icon: "briefcase"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage companies and contacts within HubSpot. Create new records and streamline your CRM processes with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the HubSpot integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription.
|
||||
- A HubSpot account with appropriate permissions.
|
||||
- Connected your HubSpot account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors).
|
||||
|
||||
## Setting Up HubSpot Integration
|
||||
|
||||
### 1. Connect Your HubSpot Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors).
|
||||
2. Find **HubSpot** in the Authentication Integrations section.
|
||||
3. Click **Connect** and complete the OAuth flow.
|
||||
4. Grant the necessary permissions for company and contact management.
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account).
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="HUBSPOT_CREATE_RECORD_COMPANIES">
|
||||
**Description:** Create a new company record in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string, required): Name of the company.
|
||||
- `domain` (string, optional): Company Domain Name.
|
||||
- `industry` (string, optional): Industry. Must be one of the predefined values from HubSpot.
|
||||
- `phone` (string, optional): Phone Number.
|
||||
- `hubspot_owner_id` (string, optional): Company owner ID.
|
||||
- `type` (string, optional): Type of the company. Available values: `PROSPECT`, `PARTNER`, `RESELLER`, `VENDOR`, `OTHER`.
|
||||
- `city` (string, optional): City.
|
||||
- `state` (string, optional): State/Region.
|
||||
- `zip` (string, optional): Postal Code.
|
||||
- `numberofemployees` (number, optional): Number of Employees.
|
||||
- `annualrevenue` (number, optional): Annual Revenue.
|
||||
- `timezone` (string, optional): Time Zone.
|
||||
- `description` (string, optional): Description.
|
||||
- `linkedin_company_page` (string, optional): LinkedIn Company Page URL.
|
||||
- `company_email` (string, optional): Company Email.
|
||||
- `first_name` (string, optional): First Name of a contact at the company.
|
||||
- `last_name` (string, optional): Last Name of a contact at the company.
|
||||
- `about_us` (string, optional): About Us.
|
||||
- `hs_csm_sentiment` (string, optional): CSM Sentiment. Available values: `at_risk`, `neutral`, `healthy`.
|
||||
- `closedate` (string, optional): Close Date.
|
||||
- `hs_keywords` (string, optional): Company Keywords. Must be one of the predefined values.
|
||||
- `country` (string, optional): Country/Region.
|
||||
- `hs_country_code` (string, optional): Country/Region Code.
|
||||
- `hs_employee_range` (string, optional): Employee range.
|
||||
- `facebook_company_page` (string, optional): Facebook Company Page URL.
|
||||
- `facebookfans` (number, optional): Number of Facebook Fans.
|
||||
- `hs_gps_coordinates` (string, optional): GPS Coordinates.
|
||||
- `hs_gps_error` (string, optional): GPS Error.
|
||||
- `googleplus_page` (string, optional): Google Plus Page URL.
|
||||
- `owneremail` (string, optional): HubSpot Owner Email.
|
||||
- `ownername` (string, optional): HubSpot Owner Name.
|
||||
- `hs_ideal_customer_profile` (string, optional): Ideal Customer Profile Tier. Available values: `tier_1`, `tier_2`, `tier_3`.
|
||||
- `hs_industry_group` (string, optional): Industry group.
|
||||
- `is_public` (boolean, optional): Is Public.
|
||||
- `hs_last_metered_enrichment_timestamp` (string, optional): Last Metered Enrichment Timestamp.
|
||||
- `hs_lead_status` (string, optional): Lead Status. Available values: `NEW`, `OPEN`, `IN_PROGRESS`, `OPEN_DEAL`, `UNQUALIFIED`, `ATTEMPTED_TO_CONTACT`, `CONNECTED`, `BAD_TIMING`.
|
||||
- `lifecyclestage` (string, optional): Lifecycle Stage. Available values: `subscriber`, `lead`, `marketingqualifiedlead`, `salesqualifiedlead`, `opportunity`, `customer`, `evangelist`, `other`.
|
||||
- `linkedinbio` (string, optional): LinkedIn Bio.
|
||||
- `hs_linkedin_handle` (string, optional): LinkedIn handle.
|
||||
- `hs_live_enrichment_deadline` (string, optional): Live enrichment deadline.
|
||||
- `hs_logo_url` (string, optional): Logo URL.
|
||||
- `hs_analytics_source` (string, optional): Original Traffic Source.
|
||||
- `hs_pinned_engagement_id` (number, optional): Pinned Engagement ID.
|
||||
- `hs_quick_context` (string, optional): Quick context.
|
||||
- `hs_revenue_range` (string, optional): Revenue range.
|
||||
- `hs_state_code` (string, optional): State/Region Code.
|
||||
- `address` (string, optional): Street Address.
|
||||
- `address2` (string, optional): Street Address 2.
|
||||
- `hs_is_target_account` (boolean, optional): Target Account.
|
||||
- `hs_target_account` (string, optional): Target Account Tier. Available values: `tier_1`, `tier_2`, `tier_3`.
|
||||
- `hs_target_account_recommendation_snooze_time` (string, optional): Target Account Recommendation Snooze Time.
|
||||
- `hs_target_account_recommendation_state` (string, optional): Target Account Recommendation State. Available values: `DISMISSED`, `NONE`, `SNOOZED`.
|
||||
- `total_money_raised` (string, optional): Total Money Raised.
|
||||
- `twitterbio` (string, optional): Twitter Bio.
|
||||
- `twitterfollowers` (number, optional): Twitter Followers.
|
||||
- `twitterhandle` (string, optional): Twitter Handle.
|
||||
- `web_technologies` (string, optional): Web Technologies used. Must be one of the predefined values.
|
||||
- `website` (string, optional): Website URL.
|
||||
- `founded_year` (string, optional): Year Founded.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_CREATE_RECORD_CONTACTS">
|
||||
**Description:** Create a new contact record in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `email` (string, required): Email address of the contact.
|
||||
- `firstname` (string, optional): First Name.
|
||||
- `lastname` (string, optional): Last Name.
|
||||
- `phone` (string, optional): Phone Number.
|
||||
- `hubspot_owner_id` (string, optional): Contact owner.
|
||||
- `lifecyclestage` (string, optional): Lifecycle Stage. Available values: `subscriber`, `lead`, `marketingqualifiedlead`, `salesqualifiedlead`, `opportunity`, `customer`, `evangelist`, `other`.
|
||||
- `hs_lead_status` (string, optional): Lead Status. Available values: `NEW`, `OPEN`, `IN_PROGRESS`, `OPEN_DEAL`, `UNQUALIFIED`, `ATTEMPTED_TO_CONTACT`, `CONNECTED`, `BAD_TIMING`.
|
||||
- `annualrevenue` (string, optional): Annual Revenue.
|
||||
- `hs_buying_role` (string, optional): Buying Role.
|
||||
- `cc_emails` (string, optional): CC Emails.
|
||||
- `ch_customer_id` (string, optional): Chargify Customer ID.
|
||||
- `ch_customer_reference` (string, optional): Chargify Customer Reference.
|
||||
- `chargify_sites` (string, optional): Chargify Site(s).
|
||||
- `city` (string, optional): City.
|
||||
- `hs_facebook_ad_clicked` (boolean, optional): Clicked Facebook ad.
|
||||
- `hs_linkedin_ad_clicked` (string, optional): Clicked LinkedIn Ad.
|
||||
- `hs_clicked_linkedin_ad` (string, optional): Clicked on a LinkedIn Ad.
|
||||
- `closedate` (string, optional): Close Date.
|
||||
- `company` (string, optional): Company Name.
|
||||
- `company_size` (string, optional): Company size.
|
||||
- `country` (string, optional): Country/Region.
|
||||
- `hs_country_region_code` (string, optional): Country/Region Code.
|
||||
- `date_of_birth` (string, optional): Date of birth.
|
||||
- `degree` (string, optional): Degree.
|
||||
- `hs_email_customer_quarantined_reason` (string, optional): Email address quarantine reason.
|
||||
- `hs_role` (string, optional): Employment Role. Must be one of the predefined values.
|
||||
- `hs_seniority` (string, optional): Employment Seniority. Must be one of the predefined values.
|
||||
- `hs_sub_role` (string, optional): Employment Sub Role. Must be one of the predefined values.
|
||||
- `hs_employment_change_detected_date` (string, optional): Employment change detected date.
|
||||
- `hs_enriched_email_bounce_detected` (boolean, optional): Enriched Email Bounce Detected.
|
||||
- `hs_facebookid` (string, optional): Facebook ID.
|
||||
- `hs_facebook_click_id` (string, optional): Facebook click id.
|
||||
- `fax` (string, optional): Fax Number.
|
||||
- `field_of_study` (string, optional): Field of study.
|
||||
- `followercount` (number, optional): Follower Count.
|
||||
- `gender` (string, optional): Gender.
|
||||
- `hs_google_click_id` (string, optional): Google ad click id.
|
||||
- `graduation_date` (string, optional): Graduation date.
|
||||
- `owneremail` (string, optional): HubSpot Owner Email (legacy).
|
||||
- `ownername` (string, optional): HubSpot Owner Name (legacy).
|
||||
- `industry` (string, optional): Industry.
|
||||
- `hs_inferred_language_codes` (string, optional): Inferred Language Codes. Must be one of the predefined values.
|
||||
- `jobtitle` (string, optional): Job Title.
|
||||
- `hs_job_change_detected_date` (string, optional): Job change detected date.
|
||||
- `job_function` (string, optional): Job function.
|
||||
- `hs_journey_stage` (string, optional): Journey Stage. Must be one of the predefined values.
|
||||
- `kloutscoregeneral` (number, optional): Klout Score.
|
||||
- `hs_last_metered_enrichment_timestamp` (string, optional): Last Metered Enrichment Timestamp.
|
||||
- `hs_latest_source` (string, optional): Latest Traffic Source.
|
||||
- `hs_latest_source_timestamp` (string, optional): Latest Traffic Source Date.
|
||||
- `hs_legal_basis` (string, optional): Legal basis for processing contact's data.
|
||||
- `linkedinbio` (string, optional): LinkedIn Bio.
|
||||
- `linkedinconnections` (number, optional): LinkedIn Connections.
|
||||
- `hs_linkedin_url` (string, optional): LinkedIn URL.
|
||||
- `hs_linkedinid` (string, optional): Linkedin ID.
|
||||
- `hs_live_enrichment_deadline` (string, optional): Live enrichment deadline.
|
||||
- `marital_status` (string, optional): Marital Status.
|
||||
- `hs_content_membership_email` (string, optional): Member email.
|
||||
- `hs_content_membership_notes` (string, optional): Membership Notes.
|
||||
- `message` (string, optional): Message.
|
||||
- `military_status` (string, optional): Military status.
|
||||
- `mobilephone` (string, optional): Mobile Phone Number.
|
||||
- `numemployees` (string, optional): Number of Employees.
|
||||
- `hs_analytics_source` (string, optional): Original Traffic Source.
|
||||
- `photo` (string, optional): Photo.
|
||||
- `hs_pinned_engagement_id` (number, optional): Pinned engagement ID.
|
||||
- `zip` (string, optional): Postal Code.
|
||||
- `hs_language` (string, optional): Preferred language. Must be one of the predefined values.
|
||||
- `associatedcompanyid` (number, optional): Primary Associated Company ID.
|
||||
- `hs_email_optout_survey_reason` (string, optional): Reason for opting out of email.
|
||||
- `relationship_status` (string, optional): Relationship Status.
|
||||
- `hs_returning_to_office_detected_date` (string, optional): Returning to office detected date.
|
||||
- `salutation` (string, optional): Salutation.
|
||||
- `school` (string, optional): School.
|
||||
- `seniority` (string, optional): Seniority.
|
||||
- `hs_feedback_show_nps_web_survey` (boolean, optional): Should be shown an NPS web survey.
|
||||
- `start_date` (string, optional): Start date.
|
||||
- `state` (string, optional): State/Region.
|
||||
- `hs_state_code` (string, optional): State/Region Code.
|
||||
- `hs_content_membership_status` (string, optional): Status.
|
||||
- `address` (string, optional): Street Address.
|
||||
- `tax_exempt` (string, optional): Tax Exempt.
|
||||
- `hs_timezone` (string, optional): Time Zone. Must be one of the predefined values.
|
||||
- `twitterbio` (string, optional): Twitter Bio.
|
||||
- `hs_twitterid` (string, optional): Twitter ID.
|
||||
- `twitterprofilephoto` (string, optional): Twitter Profile Photo.
|
||||
- `twitterhandle` (string, optional): Twitter Username.
|
||||
- `vat_number` (string, optional): VAT Number.
|
||||
- `ch_verified` (string, optional): Verified for ACH/eCheck Payments.
|
||||
- `website` (string, optional): Website URL.
|
||||
- `hs_whatsapp_phone_number` (string, optional): WhatsApp Phone Number.
|
||||
- `work_email` (string, optional): Work email.
|
||||
- `hs_googleplusid` (string, optional): googleplus ID.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_CREATE_RECORD_DEALS">
|
||||
**Description:** Create a new deal record in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `dealname` (string, required): Name of the deal.
|
||||
- `amount` (number, optional): The value of the deal.
|
||||
- `dealstage` (string, optional): The pipeline stage of the deal.
|
||||
- `pipeline` (string, optional): The pipeline the deal belongs to.
|
||||
- `closedate` (string, optional): The date the deal is expected to close.
|
||||
- `hubspot_owner_id` (string, optional): The owner of the deal.
|
||||
- `dealtype` (string, optional): The type of deal. Available values: `newbusiness`, `existingbusiness`.
|
||||
- `description` (string, optional): A description of the deal.
|
||||
- `hs_priority` (string, optional): The priority of the deal. Available values: `low`, `medium`, `high`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_CREATE_RECORD_ENGAGEMENTS">
|
||||
**Description:** Create a new engagement (e.g., note, email, call, meeting, task) in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `engagementType` (string, required): The type of engagement. Available values: `NOTE`, `EMAIL`, `CALL`, `MEETING`, `TASK`.
|
||||
- `hubspot_owner_id` (string, optional): The user the activity is assigned to.
|
||||
- `hs_timestamp` (string, optional): The date and time of the activity.
|
||||
- `hs_note_body` (string, optional): The body of the note. (Used for `NOTE`)
|
||||
- `hs_task_subject` (string, optional): The title of the task. (Used for `TASK`)
|
||||
- `hs_task_body` (string, optional): The notes for the task. (Used for `TASK`)
|
||||
- `hs_task_status` (string, optional): The status of the task. (Used for `TASK`)
|
||||
- `hs_meeting_title` (string, optional): The title of the meeting. (Used for `MEETING`)
|
||||
- `hs_meeting_body` (string, optional): The description for the meeting. (Used for `MEETING`)
|
||||
- `hs_meeting_start_time` (string, optional): The start time of the meeting. (Used for `MEETING`)
|
||||
- `hs_meeting_end_time` (string, optional): The end time of the meeting. (Used for `MEETING`)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_UPDATE_RECORD_COMPANIES">
|
||||
**Description:** Update an existing company record in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the company to update.
|
||||
- `name` (string, optional): Name of the company.
|
||||
- `domain` (string, optional): Company Domain Name.
|
||||
- `industry` (string, optional): Industry.
|
||||
- `phone` (string, optional): Phone Number.
|
||||
- `city` (string, optional): City.
|
||||
- `state` (string, optional): State/Region.
|
||||
- `zip` (string, optional): Postal Code.
|
||||
- `numberofemployees` (number, optional): Number of Employees.
|
||||
- `annualrevenue` (number, optional): Annual Revenue.
|
||||
- `description` (string, optional): Description.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_CREATE_RECORD_ANY">
|
||||
**Description:** Create a record for a specified object type in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): The object type ID of the custom object.
|
||||
- Additional parameters depend on the custom object's schema.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_UPDATE_RECORD_CONTACTS">
|
||||
**Description:** Update an existing contact record in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the contact to update.
|
||||
- `firstname` (string, optional): First Name.
|
||||
- `lastname` (string, optional): Last Name.
|
||||
- `email` (string, optional): Email address.
|
||||
- `phone` (string, optional): Phone Number.
|
||||
- `company` (string, optional): Company Name.
|
||||
- `jobtitle` (string, optional): Job Title.
|
||||
- `lifecyclestage` (string, optional): Lifecycle Stage.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_UPDATE_RECORD_DEALS">
|
||||
**Description:** Update an existing deal record in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the deal to update.
|
||||
- `dealname` (string, optional): Name of the deal.
|
||||
- `amount` (number, optional): The value of the deal.
|
||||
- `dealstage` (string, optional): The pipeline stage of the deal.
|
||||
- `pipeline` (string, optional): The pipeline the deal belongs to.
|
||||
- `closedate` (string, optional): The date the deal is expected to close.
|
||||
- `dealtype` (string, optional): The type of deal.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_UPDATE_RECORD_ENGAGEMENTS">
|
||||
**Description:** Update an existing engagement in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the engagement to update.
|
||||
- `hs_note_body` (string, optional): The body of the note.
|
||||
- `hs_task_subject` (string, optional): The title of the task.
|
||||
- `hs_task_body` (string, optional): The notes for the task.
|
||||
- `hs_task_status` (string, optional): The status of the task.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_UPDATE_RECORD_ANY">
|
||||
**Description:** Update a record for a specified object type in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the record to update.
|
||||
- `recordType` (string, required): The object type ID of the custom object.
|
||||
- Additional parameters depend on the custom object's schema.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORDS_COMPANIES">
|
||||
**Description:** Get a list of company records from HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORDS_CONTACTS">
|
||||
**Description:** Get a list of contact records from HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORDS_DEALS">
|
||||
**Description:** Get a list of deal records from HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORDS_ENGAGEMENTS">
|
||||
**Description:** Get a list of engagement records from HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `objectName` (string, required): The type of engagement to fetch (e.g., "notes").
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORDS_ANY">
|
||||
**Description:** Get a list of records for any specified object type in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): The object type ID of the custom object.
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_COMPANIES">
|
||||
**Description:** Get a single company record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the company to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_CONTACTS">
|
||||
**Description:** Get a single contact record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the contact to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_DEALS">
|
||||
**Description:** Get a single deal record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the deal to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_ENGAGEMENTS">
|
||||
**Description:** Get a single engagement record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the engagement to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_ANY">
|
||||
**Description:** Get a single record of any specified object type by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): The object type ID of the custom object.
|
||||
- `recordId` (string, required): The ID of the record to retrieve.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_SEARCH_RECORDS_COMPANIES">
|
||||
**Description:** Search for company records in HubSpot using a filter formula.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): A filter in disjunctive normal form (OR of ANDs).
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_SEARCH_RECORDS_CONTACTS">
|
||||
**Description:** Search for contact records in HubSpot using a filter formula.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): A filter in disjunctive normal form (OR of ANDs).
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_SEARCH_RECORDS_DEALS">
|
||||
**Description:** Search for deal records in HubSpot using a filter formula.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): A filter in disjunctive normal form (OR of ANDs).
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_SEARCH_RECORDS_ENGAGEMENTS">
|
||||
**Description:** Search for engagement records in HubSpot using a filter formula.
|
||||
|
||||
**Parameters:**
|
||||
- `engagementFilterFormula` (object, optional): A filter for engagements.
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_SEARCH_RECORDS_ANY">
|
||||
**Description:** Search for records of any specified object type in HubSpot.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): The object type ID to search.
|
||||
- `filterFormula` (string, optional): The filter formula to apply.
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_DELETE_RECORD_COMPANIES">
|
||||
**Description:** Delete a company record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the company to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_DELETE_RECORD_CONTACTS">
|
||||
**Description:** Delete a contact record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the contact to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_DELETE_RECORD_DEALS">
|
||||
**Description:** Delete a deal record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the deal to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_DELETE_RECORD_ENGAGEMENTS">
|
||||
**Description:** Delete an engagement record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the engagement to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_DELETE_RECORD_ANY">
|
||||
**Description:** Delete a record of any specified object type by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): The object type ID of the custom object.
|
||||
- `recordId` (string, required): The ID of the record to delete.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_GET_CONTACTS_BY_LIST_ID">
|
||||
**Description:** Get contacts from a specific list by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `listId` (string, required): The ID of the list to get contacts from.
|
||||
- `paginationParameters` (object, optional): Use `pageCursor` for subsequent pages.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="HUBSPOT_DESCRIBE_ACTION_SCHEMA">
|
||||
**Description:** Get the expected schema for a given object type and operation.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): The object type ID (e.g., 'companies').
|
||||
- `operation` (string, required): The operation type (e.g., 'CREATE_RECORD').
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic HubSpot Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (HubSpot tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with HubSpot capabilities
|
||||
hubspot_agent = Agent(
|
||||
role="CRM Manager",
|
||||
goal="Manage company and contact records in HubSpot",
|
||||
backstory="An AI assistant specialized in CRM management.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new company
|
||||
create_company_task = Task(
|
||||
description="Create a new company in HubSpot with name 'Innovate Corp' and domain 'innovatecorp.com'.",
|
||||
agent=hubspot_agent,
|
||||
expected_output="Company created successfully with confirmation"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[hubspot_agent],
|
||||
tasks=[create_company_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific HubSpot Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only the tool to create contacts
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["hubspot_create_record_contacts"]
|
||||
)
|
||||
|
||||
contact_creator = Agent(
|
||||
role="Contact Creator",
|
||||
goal="Create new contacts in HubSpot",
|
||||
backstory="An AI assistant that focuses on creating new contact entries in the CRM.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a contact
|
||||
create_contact = Task(
|
||||
description="Create a new contact for 'John Doe' with email 'john.doe@example.com'.",
|
||||
agent=contact_creator,
|
||||
expected_output="Contact created successfully in HubSpot."
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[contact_creator],
|
||||
tasks=[create_contact]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Contact Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
crm_manager = Agent(
|
||||
role="CRM Manager",
|
||||
goal="Manage and organize HubSpot contacts efficiently.",
|
||||
backstory="An experienced CRM manager who maintains an organized contact database.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage contacts
|
||||
contact_task = Task(
|
||||
description="Create a new contact for 'Jane Smith' at 'Global Tech Inc.' with email 'jane.smith@globaltech.com'.",
|
||||
agent=crm_manager,
|
||||
expected_output="Contact database updated with the new contact."
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[crm_manager],
|
||||
tasks=[contact_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with HubSpot integration setup or troubleshooting.
|
||||
</Card>
|
||||
394
docs/en/enterprise/integrations/jira.mdx
Normal file
394
docs/en/enterprise/integrations/jira.mdx
Normal file
@@ -0,0 +1,394 @@
|
||||
---
|
||||
title: Jira Integration
|
||||
description: "Issue tracking and project management with Jira integration for CrewAI."
|
||||
icon: "bug"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage issues, projects, and workflows through Jira. Create and update issues, track project progress, manage assignments, and streamline your project management with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Jira integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Jira account with appropriate project permissions
|
||||
- Connected your Jira account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Jira Integration
|
||||
|
||||
### 1. Connect Your Jira Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Jira** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for issue and project management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="JIRA_CREATE_ISSUE">
|
||||
**Description:** Create an issue in Jira.
|
||||
|
||||
**Parameters:**
|
||||
- `summary` (string, required): Summary - A brief one-line summary of the issue. (example: "The printer stopped working").
|
||||
- `project` (string, optional): Project - The project which the issue belongs to. Defaults to the user's first project if not provided. Use Connect Portal Workflow Settings to allow users to select a Project.
|
||||
- `issueType` (string, optional): Issue type - Defaults to Task if not provided.
|
||||
- `jiraIssueStatus` (string, optional): Status - Defaults to the project's first status if not provided.
|
||||
- `assignee` (string, optional): Assignee - Defaults to the authenticated user if not provided.
|
||||
- `descriptionType` (string, optional): Description Type - Select the Description Type.
|
||||
- Options: `description`, `descriptionJSON`
|
||||
- `description` (string, optional): Description - A detailed description of the issue. This field appears only when 'descriptionType' = 'description'.
|
||||
- `additionalFields` (string, optional): Additional Fields - Specify any other fields that should be included in JSON format. Use Connect Portal Workflow Settings to allow users to select which Issue Fields to update.
|
||||
```json
|
||||
{
|
||||
"customfield_10001": "value"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_UPDATE_ISSUE">
|
||||
**Description:** Update an issue in Jira.
|
||||
|
||||
**Parameters:**
|
||||
- `issueKey` (string, required): Issue Key (example: "TEST-1234").
|
||||
- `summary` (string, optional): Summary - A brief one-line summary of the issue. (example: "The printer stopped working").
|
||||
- `issueType` (string, optional): Issue type - Use Connect Portal Workflow Settings to allow users to select an Issue Type.
|
||||
- `jiraIssueStatus` (string, optional): Status - Use Connect Portal Workflow Settings to allow users to select a Status.
|
||||
- `assignee` (string, optional): Assignee - Use Connect Portal Workflow Settings to allow users to select an Assignee.
|
||||
- `descriptionType` (string, optional): Description Type - Select the Description Type.
|
||||
- Options: `description`, `descriptionJSON`
|
||||
- `description` (string, optional): Description - A detailed description of the issue. This field appears only when 'descriptionType' = 'description'.
|
||||
- `additionalFields` (string, optional): Additional Fields - Specify any other fields that should be included in JSON format.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_GET_ISSUE_BY_KEY">
|
||||
**Description:** Get an issue by key in Jira.
|
||||
|
||||
**Parameters:**
|
||||
- `issueKey` (string, required): Issue Key (example: "TEST-1234").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_FILTER_ISSUES">
|
||||
**Description:** Search issues in Jira using filters.
|
||||
|
||||
**Parameters:**
|
||||
- `jqlQuery` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "status",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "Open"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available operators: `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringIsIn`, `$stringIsNotIn`, `$stringContains`, `$stringDoesNotContain`, `$stringGreaterThan`, `$stringLessThan`
|
||||
- `limit` (string, optional): Limit results - Limit the maximum number of issues to return. Defaults to 10 if left blank.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_SEARCH_BY_JQL">
|
||||
**Description:** Search issues by JQL in Jira.
|
||||
|
||||
**Parameters:**
|
||||
- `jqlQuery` (string, required): JQL Query (example: "project = PROJECT").
|
||||
- `paginationParameters` (object, optional): Pagination parameters for paginated results.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_UPDATE_ISSUE_ANY">
|
||||
**Description:** Update any issue in Jira. Use DESCRIBE_ACTION_SCHEMA to get properties schema for this function.
|
||||
|
||||
**Parameters:** No specific parameters - use JIRA_DESCRIBE_ACTION_SCHEMA first to get the expected schema.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_DESCRIBE_ACTION_SCHEMA">
|
||||
**Description:** Get the expected schema for an issue type. Use this function first if no other function matches the issue type you want to operate on.
|
||||
|
||||
**Parameters:**
|
||||
- `issueTypeId` (string, required): Issue Type ID.
|
||||
- `projectKey` (string, required): Project key.
|
||||
- `operation` (string, required): Operation Type value, for example CREATE_ISSUE or UPDATE_ISSUE.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_GET_PROJECTS">
|
||||
**Description:** Get Projects in Jira.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Pagination Parameters.
|
||||
```json
|
||||
{
|
||||
"pageCursor": "cursor_string"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_GET_ISSUE_TYPES_BY_PROJECT">
|
||||
**Description:** Get Issue Types by project in Jira.
|
||||
|
||||
**Parameters:**
|
||||
- `project` (string, required): Project key.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_GET_ISSUE_TYPES">
|
||||
**Description:** Get all Issue Types in Jira.
|
||||
|
||||
**Parameters:** None required.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_GET_ISSUE_STATUS_BY_PROJECT">
|
||||
**Description:** Get issue statuses for a given project.
|
||||
|
||||
**Parameters:**
|
||||
- `project` (string, required): Project key.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="JIRA_GET_ALL_ASSIGNEES_BY_PROJECT">
|
||||
**Description:** Get assignees for a given project.
|
||||
|
||||
**Parameters:**
|
||||
- `project` (string, required): Project key.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Jira Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Jira tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Jira capabilities
|
||||
jira_agent = Agent(
|
||||
role="Issue Manager",
|
||||
goal="Manage Jira issues and track project progress efficiently",
|
||||
backstory="An AI assistant specialized in issue tracking and project management.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a bug report
|
||||
create_bug_task = Task(
|
||||
description="Create a bug report for the login functionality with high priority and assign it to the development team",
|
||||
agent=jira_agent,
|
||||
expected_output="Bug report created successfully with issue key"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[jira_agent],
|
||||
tasks=[create_bug_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Jira Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Jira tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["jira_create_issue", "jira_update_issue", "jira_search_by_jql"]
|
||||
)
|
||||
|
||||
issue_coordinator = Agent(
|
||||
role="Issue Coordinator",
|
||||
goal="Create and manage Jira issues efficiently",
|
||||
backstory="An AI assistant that focuses on issue creation and management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage issue workflow
|
||||
issue_workflow = Task(
|
||||
description="Create a feature request issue and update the status of related issues",
|
||||
agent=issue_coordinator,
|
||||
expected_output="Feature request created and related issues updated"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[issue_coordinator],
|
||||
tasks=[issue_workflow]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Project Analysis and Reporting
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
project_analyst = Agent(
|
||||
role="Project Analyst",
|
||||
goal="Analyze project data and generate insights from Jira",
|
||||
backstory="An experienced project analyst who extracts insights from project management data.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to analyze project status
|
||||
analysis_task = Task(
|
||||
description="""
|
||||
1. Get all projects and their issue types
|
||||
2. Search for all open issues across projects
|
||||
3. Analyze issue distribution by status and assignee
|
||||
4. Create a summary report issue with findings
|
||||
""",
|
||||
agent=project_analyst,
|
||||
expected_output="Project analysis completed with summary report created"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[project_analyst],
|
||||
tasks=[analysis_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Automated Issue Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
automation_manager = Agent(
|
||||
role="Automation Manager",
|
||||
goal="Automate issue management and workflow processes",
|
||||
backstory="An AI assistant that automates repetitive issue management tasks.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to automate issue management
|
||||
automation_task = Task(
|
||||
description="""
|
||||
1. Search for all unassigned issues using JQL
|
||||
2. Get available assignees for each project
|
||||
3. Automatically assign issues based on workload and expertise
|
||||
4. Update issue priorities based on age and type
|
||||
5. Create weekly sprint planning issues
|
||||
""",
|
||||
agent=automation_manager,
|
||||
expected_output="Issues automatically assigned and sprint planning issues created"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[automation_manager],
|
||||
tasks=[automation_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced Schema-Based Operations
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
schema_specialist = Agent(
|
||||
role="Schema Specialist",
|
||||
goal="Handle complex Jira operations using dynamic schemas",
|
||||
backstory="An AI assistant that can work with dynamic Jira schemas and custom issue types.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task using schema-based operations
|
||||
schema_task = Task(
|
||||
description="""
|
||||
1. Get all projects and their custom issue types
|
||||
2. For each custom issue type, describe the action schema
|
||||
3. Create issues using the dynamic schema for complex custom fields
|
||||
4. Update issues with custom field values based on business rules
|
||||
""",
|
||||
agent=schema_specialist,
|
||||
expected_output="Custom issues created and updated using dynamic schemas"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[schema_specialist],
|
||||
tasks=[schema_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Permission Errors**
|
||||
- Ensure your Jira account has necessary permissions for the target projects
|
||||
- Verify that the OAuth connection includes required scopes for Jira API
|
||||
- Check if you have create/edit permissions for issues in the specified projects
|
||||
|
||||
**Invalid Project or Issue Keys**
|
||||
- Double-check project keys and issue keys for correct format (e.g., "PROJ-123")
|
||||
- Ensure projects exist and are accessible to your account
|
||||
- Verify that issue keys reference existing issues
|
||||
|
||||
**Issue Type and Status Issues**
|
||||
- Use JIRA_GET_ISSUE_TYPES_BY_PROJECT to get valid issue types for a project
|
||||
- Use JIRA_GET_ISSUE_STATUS_BY_PROJECT to get valid statuses
|
||||
- Ensure issue types and statuses are available in the target project
|
||||
|
||||
**JQL Query Problems**
|
||||
- Test JQL queries in Jira's issue search before using in API calls
|
||||
- Ensure field names in JQL are spelled correctly and exist in your Jira instance
|
||||
- Use proper JQL syntax for complex queries
|
||||
|
||||
**Custom Fields and Schema Issues**
|
||||
- Use JIRA_DESCRIBE_ACTION_SCHEMA to get the correct schema for complex issue types
|
||||
- Ensure custom field IDs are correct (e.g., "customfield_10001")
|
||||
- Verify that custom fields are available in the target project and issue type
|
||||
|
||||
**Filter Formula Issues**
|
||||
- Ensure filter formulas follow the correct JSON structure for disjunctive normal form
|
||||
- Use valid field names that exist in your Jira configuration
|
||||
- Test simple filters before building complex multi-condition queries
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Jira integration setup or troubleshooting.
|
||||
</Card>
|
||||
453
docs/en/enterprise/integrations/linear.mdx
Normal file
453
docs/en/enterprise/integrations/linear.mdx
Normal file
@@ -0,0 +1,453 @@
|
||||
---
|
||||
title: Linear Integration
|
||||
description: "Software project and bug tracking with Linear integration for CrewAI."
|
||||
icon: "list-check"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage issues, projects, and development workflows through Linear. Create and update issues, manage project timelines, organize teams, and streamline your software development process with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Linear integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Linear account with appropriate workspace permissions
|
||||
- Connected your Linear account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Linear Integration
|
||||
|
||||
### 1. Connect Your Linear Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Linear** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for issue and project management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="LINEAR_CREATE_ISSUE">
|
||||
**Description:** Create a new issue in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `teamId` (string, required): Team ID - Specify the Team ID of the parent for this new issue. Use Connect Portal Workflow Settings to allow users to select a Team ID. (example: "a70bdf0f-530a-4887-857d-46151b52b47c").
|
||||
- `title` (string, required): Title - Specify a title for this issue.
|
||||
- `description` (string, optional): Description - Specify a description for this issue.
|
||||
- `statusId` (string, optional): Status - Specify the state or status of this issue.
|
||||
- `priority` (string, optional): Priority - Specify the priority of this issue as an integer.
|
||||
- `dueDate` (string, optional): Due Date - Specify the due date of this issue in ISO 8601 format.
|
||||
- `cycleId` (string, optional): Cycle ID - Specify the cycle associated with this issue.
|
||||
- `additionalFields` (object, optional): Additional Fields.
|
||||
```json
|
||||
{
|
||||
"assigneeId": "a70bdf0f-530a-4887-857d-46151b52b47c",
|
||||
"labelIds": ["a70bdf0f-530a-4887-857d-46151b52b47c"]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_UPDATE_ISSUE">
|
||||
**Description:** Update an issue in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `issueId` (string, required): Issue ID - Specify the Issue ID of the issue to update. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
|
||||
- `title` (string, optional): Title - Specify a title for this issue.
|
||||
- `description` (string, optional): Description - Specify a description for this issue.
|
||||
- `statusId` (string, optional): Status - Specify the state or status of this issue.
|
||||
- `priority` (string, optional): Priority - Specify the priority of this issue as an integer.
|
||||
- `dueDate` (string, optional): Due Date - Specify the due date of this issue in ISO 8601 format.
|
||||
- `cycleId` (string, optional): Cycle ID - Specify the cycle associated with this issue.
|
||||
- `additionalFields` (object, optional): Additional Fields.
|
||||
```json
|
||||
{
|
||||
"assigneeId": "a70bdf0f-530a-4887-857d-46151b52b47c",
|
||||
"labelIds": ["a70bdf0f-530a-4887-857d-46151b52b47c"]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_GET_ISSUE_BY_ID">
|
||||
**Description:** Get an issue by ID in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `issueId` (string, required): Issue ID - Specify the record ID of the issue to fetch. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_GET_ISSUE_BY_ISSUE_IDENTIFIER">
|
||||
**Description:** Get an issue by issue identifier in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `externalId` (string, required): External ID - Specify the human-readable Issue identifier of the issue to fetch. (example: "ABC-1").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_SEARCH_ISSUE">
|
||||
**Description:** Search issues in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `queryTerm` (string, required): Query Term - The search term to look for.
|
||||
- `issueFilterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "title",
|
||||
"operator": "$stringContains",
|
||||
"value": "bug"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available fields: `title`, `number`, `project`, `createdAt`
|
||||
Available operators: `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringIsIn`, `$stringIsNotIn`, `$stringStartsWith`, `$stringDoesNotStartWith`, `$stringEndsWith`, `$stringDoesNotEndWith`, `$stringContains`, `$stringDoesNotContain`, `$stringGreaterThan`, `$stringLessThan`, `$numberGreaterThanOrEqualTo`, `$numberLessThanOrEqualTo`, `$numberGreaterThan`, `$numberLessThan`, `$dateTimeAfter`, `$dateTimeBefore`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_DELETE_ISSUE">
|
||||
**Description:** Delete an issue in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `issueId` (string, required): Issue ID - Specify the record ID of the issue to delete. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_ARCHIVE_ISSUE">
|
||||
**Description:** Archive an issue in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `issueId` (string, required): Issue ID - Specify the record ID of the issue to archive. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_CREATE_SUB_ISSUE">
|
||||
**Description:** Create a sub-issue in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `parentId` (string, required): Parent ID - Specify the Issue ID for the parent of this new issue.
|
||||
- `teamId` (string, required): Team ID - Specify the Team ID of the parent for this new sub-issue. Use Connect Portal Workflow Settings to allow users to select a Team ID. (example: "a70bdf0f-530a-4887-857d-46151b52b47c").
|
||||
- `title` (string, required): Title - Specify a title for this issue.
|
||||
- `description` (string, optional): Description - Specify a description for this issue.
|
||||
- `additionalFields` (object, optional): Additional Fields.
|
||||
```json
|
||||
{
|
||||
"lead": "linear_user_id"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_CREATE_PROJECT">
|
||||
**Description:** Create a new project in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `teamIds` (object, required): Team ID - Specify the team ID(s) this project is associated with as a string or a JSON array. Use Connect Portal User Settings to allow your user to select a Team ID.
|
||||
```json
|
||||
[
|
||||
"a70bdf0f-530a-4887-857d-46151b52b47c",
|
||||
"4ac7..."
|
||||
]
|
||||
```
|
||||
- `projectName` (string, required): Project Name - Specify the name of the project. (example: "My Linear Project").
|
||||
- `description` (string, optional): Project Description - Specify a description for this project.
|
||||
- `additionalFields` (object, optional): Additional Fields.
|
||||
```json
|
||||
{
|
||||
"state": "planned",
|
||||
"description": ""
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_UPDATE_PROJECT">
|
||||
**Description:** Update a project in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `projectId` (string, required): Project ID - Specify the ID of the project to update. (example: "a6634484-6061-4ac7-9739-7dc5e52c796b").
|
||||
- `projectName` (string, optional): Project Name - Specify the name of the project to update. (example: "My Linear Project").
|
||||
- `description` (string, optional): Project Description - Specify a description for this project.
|
||||
- `additionalFields` (object, optional): Additional Fields.
|
||||
```json
|
||||
{
|
||||
"state": "planned",
|
||||
"description": ""
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_GET_PROJECT_BY_ID">
|
||||
**Description:** Get a project by ID in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `projectId` (string, required): Project ID - Specify the Project ID of the project to fetch. (example: "a6634484-6061-4ac7-9739-7dc5e52c796b").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_DELETE_PROJECT">
|
||||
**Description:** Delete a project in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `projectId` (string, required): Project ID - Specify the Project ID of the project to delete. (example: "a6634484-6061-4ac7-9739-7dc5e52c796b").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="LINEAR_SEARCH_TEAMS">
|
||||
**Description:** Search teams in Linear.
|
||||
|
||||
**Parameters:**
|
||||
- `teamFilterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "name",
|
||||
"operator": "$stringContains",
|
||||
"value": "Engineering"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available fields: `id`, `name`
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Linear Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Linear tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Linear capabilities
|
||||
linear_agent = Agent(
|
||||
role="Development Manager",
|
||||
goal="Manage Linear issues and track development progress efficiently",
|
||||
backstory="An AI assistant specialized in software development project management.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a bug report
|
||||
create_bug_task = Task(
|
||||
description="Create a high-priority bug report for the authentication system and assign it to the backend team",
|
||||
agent=linear_agent,
|
||||
expected_output="Bug report created successfully with issue ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[linear_agent],
|
||||
tasks=[create_bug_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Linear Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Linear tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["linear_create_issue", "linear_update_issue", "linear_search_issue"]
|
||||
)
|
||||
|
||||
issue_manager = Agent(
|
||||
role="Issue Manager",
|
||||
goal="Create and manage Linear issues efficiently",
|
||||
backstory="An AI assistant that focuses on issue creation and lifecycle management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage issue workflow
|
||||
issue_workflow = Task(
|
||||
description="Create a feature request issue and update the status of related issues to reflect current progress",
|
||||
agent=issue_manager,
|
||||
expected_output="Feature request created and related issues updated"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[issue_manager],
|
||||
tasks=[issue_workflow]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Project and Team Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
project_coordinator = Agent(
|
||||
role="Project Coordinator",
|
||||
goal="Coordinate projects and teams in Linear efficiently",
|
||||
backstory="An experienced project coordinator who manages development cycles and team workflows.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to coordinate project setup
|
||||
project_coordination = Task(
|
||||
description="""
|
||||
1. Search for engineering teams in Linear
|
||||
2. Create a new project for Q2 feature development
|
||||
3. Associate the project with relevant teams
|
||||
4. Create initial project milestones as issues
|
||||
""",
|
||||
agent=project_coordinator,
|
||||
expected_output="Q2 project created with teams assigned and initial milestones established"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[project_coordinator],
|
||||
tasks=[project_coordination]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Issue Hierarchy and Sub-task Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
task_organizer = Agent(
|
||||
role="Task Organizer",
|
||||
goal="Organize complex issues into manageable sub-tasks",
|
||||
backstory="An AI assistant that breaks down complex development work into organized sub-tasks.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create issue hierarchy
|
||||
hierarchy_task = Task(
|
||||
description="""
|
||||
1. Search for large feature issues that need to be broken down
|
||||
2. For each complex issue, create sub-issues for different components
|
||||
3. Update the parent issues with proper descriptions and links to sub-issues
|
||||
4. Assign sub-issues to appropriate team members based on expertise
|
||||
""",
|
||||
agent=task_organizer,
|
||||
expected_output="Complex issues broken down into manageable sub-tasks with proper assignments"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[task_organizer],
|
||||
tasks=[hierarchy_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Automated Development Workflow
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
workflow_automator = Agent(
|
||||
role="Workflow Automator",
|
||||
goal="Automate development workflow processes in Linear",
|
||||
backstory="An AI assistant that automates repetitive development workflow tasks.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex workflow automation task
|
||||
automation_task = Task(
|
||||
description="""
|
||||
1. Search for issues that have been in progress for more than 7 days
|
||||
2. Update their priorities based on due dates and project importance
|
||||
3. Create weekly sprint planning issues for each team
|
||||
4. Archive completed issues from the previous cycle
|
||||
5. Generate project status reports as new issues
|
||||
""",
|
||||
agent=workflow_automator,
|
||||
expected_output="Development workflow automated with updated priorities, sprint planning, and status reports"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[workflow_automator],
|
||||
tasks=[automation_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Permission Errors**
|
||||
- Ensure your Linear account has necessary permissions for the target workspace
|
||||
- Verify that the OAuth connection includes required scopes for Linear API
|
||||
- Check if you have create/edit permissions for issues and projects in the workspace
|
||||
|
||||
**Invalid IDs and References**
|
||||
- Double-check team IDs, issue IDs, and project IDs for correct UUID format
|
||||
- Ensure referenced entities (teams, projects, cycles) exist and are accessible
|
||||
- Verify that issue identifiers follow the correct format (e.g., "ABC-1")
|
||||
|
||||
**Team and Project Association Issues**
|
||||
- Use LINEAR_SEARCH_TEAMS to get valid team IDs before creating issues or projects
|
||||
- Ensure teams exist and are active in your workspace
|
||||
- Verify that team IDs are properly formatted as UUIDs
|
||||
|
||||
**Issue Status and Priority Problems**
|
||||
- Check that status IDs reference valid workflow states for the team
|
||||
- Ensure priority values are within the valid range for your Linear configuration
|
||||
- Verify that custom fields and labels exist before referencing them
|
||||
|
||||
**Date and Time Format Issues**
|
||||
- Use ISO 8601 format for due dates and timestamps
|
||||
- Ensure time zones are handled correctly for due date calculations
|
||||
- Verify that date values are valid and in the future for due dates
|
||||
|
||||
**Search and Filter Issues**
|
||||
- Ensure search queries are properly formatted and not empty
|
||||
- Use valid field names in filter formulas: `title`, `number`, `project`, `createdAt`
|
||||
- Test simple filters before building complex multi-condition queries
|
||||
- Verify that operator types match the data types of the fields being filtered
|
||||
|
||||
**Sub-issue Creation Problems**
|
||||
- Ensure parent issue IDs are valid and accessible
|
||||
- Verify that the team ID for sub-issues matches or is compatible with the parent issue's team
|
||||
- Check that parent issues are not already archived or deleted
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Linear integration setup or troubleshooting.
|
||||
</Card>
|
||||
509
docs/en/enterprise/integrations/notion.mdx
Normal file
509
docs/en/enterprise/integrations/notion.mdx
Normal file
@@ -0,0 +1,509 @@
|
||||
---
|
||||
title: Notion Integration
|
||||
description: "Page and database management with Notion integration for CrewAI."
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage pages, databases, and content through Notion. Create and update pages, manage content blocks, organize knowledge bases, and streamline your documentation workflows with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Notion integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Notion account with appropriate workspace permissions
|
||||
- Connected your Notion account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
|
||||
|
||||
## Setting Up Notion Integration
|
||||
|
||||
### 1. Connect Your Notion Account
|
||||
|
||||
1. Navigate to [CrewAI Enterprise Integrations](https://app.crewai.com/crewai_plus/connectors)
|
||||
2. Find **Notion** in the Authentication Integrations section
|
||||
3. Click **Connect** and complete the OAuth flow
|
||||
4. Grant the necessary permissions for page and database management
|
||||
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
|
||||
|
||||
### 2. Install Required Package
|
||||
|
||||
```bash
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Available Actions
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="NOTION_CREATE_PAGE">
|
||||
**Description:** Create a page in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `parent` (object, required): Parent - The parent page or database where the new page is inserted, represented as a JSON object with a page_id or database_id key.
|
||||
```json
|
||||
{
|
||||
"database_id": "DATABASE_ID"
|
||||
}
|
||||
```
|
||||
- `properties` (object, required): Properties - The values of the page's properties. If the parent is a database, then the schema must match the parent database's properties.
|
||||
```json
|
||||
{
|
||||
"title": [
|
||||
{
|
||||
"text": {
|
||||
"content": "My Page"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
- `icon` (object, required): Icon - The page icon.
|
||||
```json
|
||||
{
|
||||
"emoji": "🥬"
|
||||
}
|
||||
```
|
||||
- `children` (object, optional): Children - Content blocks to add to the page.
|
||||
```json
|
||||
[
|
||||
{
|
||||
"object": "block",
|
||||
"type": "heading_2",
|
||||
"heading_2": {
|
||||
"rich_text": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": {
|
||||
"content": "Lacinato kale"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
- `cover` (object, optional): Cover - The page cover image.
|
||||
```json
|
||||
{
|
||||
"external": {
|
||||
"url": "https://upload.wikimedia.org/wikipedia/commons/6/62/Tuscankale.jpg"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_UPDATE_PAGE">
|
||||
**Description:** Update a page in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `pageId` (string, required): Page ID - Specify the ID of the Page to Update. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
|
||||
- `icon` (object, required): Icon - The page icon.
|
||||
```json
|
||||
{
|
||||
"emoji": "🥬"
|
||||
}
|
||||
```
|
||||
- `archived` (boolean, optional): Archived - Whether the page is archived (deleted). Set to true to archive a page. Set to false to un-archive (restore) a page.
|
||||
- `properties` (object, optional): Properties - The property values to update for the page.
|
||||
```json
|
||||
{
|
||||
"title": [
|
||||
{
|
||||
"text": {
|
||||
"content": "My Updated Page"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
- `cover` (object, optional): Cover - The page cover image.
|
||||
```json
|
||||
{
|
||||
"external": {
|
||||
"url": "https://upload.wikimedia.org/wikipedia/commons/6/62/Tuscankale.jpg"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_GET_PAGE_BY_ID">
|
||||
**Description:** Get a page by ID in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `pageId` (string, required): Page ID - Specify the ID of the Page to Get. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_ARCHIVE_PAGE">
|
||||
**Description:** Archive a page in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `pageId` (string, required): Page ID - Specify the ID of the Page to Archive. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_SEARCH_PAGES">
|
||||
**Description:** Search pages in Notion using filters.
|
||||
|
||||
**Parameters:**
|
||||
- `searchByTitleFilterSearch` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
|
||||
```json
|
||||
{
|
||||
"operator": "OR",
|
||||
"conditions": [
|
||||
{
|
||||
"operator": "AND",
|
||||
"conditions": [
|
||||
{
|
||||
"field": "query",
|
||||
"operator": "$stringExactlyMatches",
|
||||
"value": "meeting notes"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Available fields: `query`, `filter.value`, `direction`, `page_size`
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_GET_PAGE_CONTENT">
|
||||
**Description:** Get page content (blocks) in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `blockId` (string, required): Page ID - Specify a Block or Page ID to receive all of its block's children in order. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_UPDATE_BLOCK">
|
||||
**Description:** Update a block in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `blockId` (string, required): Block ID - Specify the ID of the Block to Update. (example: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
|
||||
- `archived` (boolean, optional): Archived - Set to true to archive (delete) a block. Set to false to un-archive (restore) a block.
|
||||
- `paragraph` (object, optional): Paragraph content.
|
||||
```json
|
||||
{
|
||||
"rich_text": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": {
|
||||
"content": "Lacinato kale",
|
||||
"link": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"color": "default"
|
||||
}
|
||||
```
|
||||
- `image` (object, optional): Image block.
|
||||
```json
|
||||
{
|
||||
"type": "external",
|
||||
"external": {
|
||||
"url": "https://website.domain/images/image.png"
|
||||
}
|
||||
}
|
||||
```
|
||||
- `bookmark` (object, optional): Bookmark block.
|
||||
```json
|
||||
{
|
||||
"caption": [],
|
||||
"url": "https://companywebsite.com"
|
||||
}
|
||||
```
|
||||
- `code` (object, optional): Code block.
|
||||
```json
|
||||
{
|
||||
"rich_text": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": {
|
||||
"content": "const a = 3"
|
||||
}
|
||||
}
|
||||
],
|
||||
"language": "javascript"
|
||||
}
|
||||
```
|
||||
- `pdf` (object, optional): PDF block.
|
||||
```json
|
||||
{
|
||||
"type": "external",
|
||||
"external": {
|
||||
"url": "https://website.domain/files/doc.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
- `table` (object, optional): Table block.
|
||||
```json
|
||||
{
|
||||
"table_width": 2,
|
||||
"has_column_header": false,
|
||||
"has_row_header": false
|
||||
}
|
||||
```
|
||||
- `tableOfContent` (object, optional): Table of Contents block.
|
||||
```json
|
||||
{
|
||||
"color": "default"
|
||||
}
|
||||
```
|
||||
- `additionalFields` (object, optional): Additional block types.
|
||||
```json
|
||||
{
|
||||
"child_page": {
|
||||
"title": "Lacinato kale"
|
||||
},
|
||||
"child_database": {
|
||||
"title": "My database"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_GET_BLOCK_BY_ID">
|
||||
**Description:** Get a block by ID in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `blockId` (string, required): Block ID - Specify the ID of the Block to Get. (example: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="NOTION_DELETE_BLOCK">
|
||||
**Description:** Delete a block in Notion.
|
||||
|
||||
**Parameters:**
|
||||
- `blockId` (string, required): Block ID - Specify the ID of the Block to Delete. (example: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Notion Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Notion tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Notion capabilities
|
||||
notion_agent = Agent(
|
||||
role="Documentation Manager",
|
||||
goal="Manage documentation and knowledge base in Notion efficiently",
|
||||
backstory="An AI assistant specialized in content management and documentation.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a meeting notes page
|
||||
create_notes_task = Task(
|
||||
description="Create a new meeting notes page in the team database with today's date and agenda items",
|
||||
agent=notion_agent,
|
||||
expected_output="Meeting notes page created successfully with structured content"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[notion_agent],
|
||||
tasks=[create_notes_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Notion Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Notion tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["notion_create_page", "notion_update_block", "notion_search_pages"]
|
||||
)
|
||||
|
||||
content_manager = Agent(
|
||||
role="Content Manager",
|
||||
goal="Create and manage content pages efficiently",
|
||||
backstory="An AI assistant that focuses on content creation and management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage content workflow
|
||||
content_workflow = Task(
|
||||
description="Create a new project documentation page and add structured content blocks for requirements and specifications",
|
||||
agent=content_manager,
|
||||
expected_output="Project documentation created with organized content sections"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[content_manager],
|
||||
tasks=[content_workflow]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Knowledge Base Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
knowledge_curator = Agent(
|
||||
role="Knowledge Curator",
|
||||
goal="Curate and organize knowledge base content in Notion",
|
||||
backstory="An experienced knowledge manager who organizes and maintains comprehensive documentation.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to curate knowledge base
|
||||
curation_task = Task(
|
||||
description="""
|
||||
1. Search for existing documentation pages related to our new product feature
|
||||
2. Create a comprehensive feature documentation page with proper structure
|
||||
3. Add code examples, images, and links to related resources
|
||||
4. Update existing pages with cross-references to the new documentation
|
||||
""",
|
||||
agent=knowledge_curator,
|
||||
expected_output="Feature documentation created and integrated with existing knowledge base"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[knowledge_curator],
|
||||
tasks=[curation_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Content Structure and Organization
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
content_organizer = Agent(
|
||||
role="Content Organizer",
|
||||
goal="Organize and structure content blocks for optimal readability",
|
||||
backstory="An AI assistant that specializes in content structure and user experience.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to organize content structure
|
||||
organization_task = Task(
|
||||
description="""
|
||||
1. Get content from existing project pages
|
||||
2. Analyze the structure and identify improvement opportunities
|
||||
3. Update content blocks to use proper headings, tables, and formatting
|
||||
4. Add table of contents and improve navigation between related pages
|
||||
5. Create templates for future documentation consistency
|
||||
""",
|
||||
agent=content_organizer,
|
||||
expected_output="Content reorganized with improved structure and navigation"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[content_organizer],
|
||||
tasks=[organization_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Automated Documentation Workflows
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
doc_automator = Agent(
|
||||
role="Documentation Automator",
|
||||
goal="Automate documentation workflows and maintenance",
|
||||
backstory="An AI assistant that automates repetitive documentation tasks.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex documentation automation task
|
||||
automation_task = Task(
|
||||
description="""
|
||||
1. Search for pages that haven't been updated in the last 30 days
|
||||
2. Review and update outdated content blocks
|
||||
3. Create weekly team update pages with consistent formatting
|
||||
4. Add status indicators and progress tracking to project pages
|
||||
5. Generate monthly documentation health reports
|
||||
6. Archive completed project pages and organize them in archive sections
|
||||
""",
|
||||
agent=doc_automator,
|
||||
expected_output="Documentation automated with updated content, weekly reports, and organized archives"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[doc_automator],
|
||||
tasks=[automation_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Permission Errors**
|
||||
- Ensure your Notion account has edit access to the target workspace
|
||||
- Verify that the OAuth connection includes required scopes for Notion API
|
||||
- Check that pages and databases are shared with the authenticated integration
|
||||
|
||||
**Invalid Page and Block IDs**
|
||||
- Double-check page IDs and block IDs for correct UUID format
|
||||
- Ensure referenced pages and blocks exist and are accessible
|
||||
- Verify that parent page or database IDs are valid when creating new pages
|
||||
|
||||
**Property Schema Issues**
|
||||
- Ensure page properties match the database schema when creating pages in databases
|
||||
- Verify that property names and types are correct for the target database
|
||||
- Check that required properties are included when creating or updating pages
|
||||
|
||||
**Content Block Structure**
|
||||
- Ensure block content follows Notion's rich text format specifications
|
||||
- Verify that nested block structures are properly formatted
|
||||
- Check that media URLs are accessible and properly formatted
|
||||
|
||||
**Search and Filter Issues**
|
||||
- Ensure search queries are properly formatted and not empty
|
||||
- Use valid field names in filter formulas: `query`, `filter.value`, `direction`, `page_size`
|
||||
- Test simple searches before building complex filter conditions
|
||||
|
||||
**Parent-Child Relationships**
|
||||
- Verify that parent page or database exists before creating child pages
|
||||
- Ensure proper permissions exist for the parent container
|
||||
- Check that database schemas allow the properties you're trying to set
|
||||
|
||||
**Rich Text and Media Content**
|
||||
- Ensure URLs for external images, PDFs, and bookmarks are accessible
|
||||
- Verify that rich text formatting follows Notion's API specifications
|
||||
- Check that code block language types are supported by Notion
|
||||
|
||||
**Archive and Deletion Operations**
|
||||
- Understand the difference between archiving (reversible) and deleting (permanent)
|
||||
- Verify that you have permissions to archive or delete the target content
|
||||
- Be cautious with bulk operations that might affect multiple pages or blocks
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Notion integration setup or troubleshooting.
|
||||
</Card>
|
||||
632
docs/en/enterprise/integrations/salesforce.mdx
Normal file
632
docs/en/enterprise/integrations/salesforce.mdx
Normal file
@@ -0,0 +1,632 @@
|
||||
---
|
||||
title: Salesforce Integration
|
||||
description: "CRM and sales automation with Salesforce integration for CrewAI."
|
||||
icon: "salesforce"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage customer relationships, sales processes, and data through Salesforce. Create and update records, manage leads and opportunities, execute SOQL queries, and streamline your CRM workflows with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Salesforce integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Salesforce account with appropriate permissions
|
||||
- Connected your Salesforce account through the [Integrations page](https://app.crewai.com/integrations)
|
||||
|
||||
## Available Tools
|
||||
|
||||
### **Record Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_CREATE_RECORD_CONTACT">
|
||||
**Description:** Create a new Contact record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `FirstName` (string, optional): First Name
|
||||
- `LastName` (string, required): Last Name - This field is required
|
||||
- `accountId` (string, optional): Account ID - The Account that the Contact belongs to
|
||||
- `Email` (string, optional): Email address
|
||||
- `Title` (string, optional): Title of the contact, such as CEO or Vice President
|
||||
- `Description` (string, optional): A description of the Contact
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Contact fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_RECORD_LEAD">
|
||||
**Description:** Create a new Lead record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `FirstName` (string, optional): First Name
|
||||
- `LastName` (string, required): Last Name - This field is required
|
||||
- `Company` (string, required): Company - This field is required
|
||||
- `Email` (string, optional): Email address
|
||||
- `Phone` (string, optional): Phone number
|
||||
- `Website` (string, optional): Website URL
|
||||
- `Title` (string, optional): Title of the contact, such as CEO or Vice President
|
||||
- `Status` (string, optional): Lead Status - Use Connect Portal Workflow Settings to select Lead Status
|
||||
- `Description` (string, optional): A description of the Lead
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Lead fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_RECORD_OPPORTUNITY">
|
||||
**Description:** Create a new Opportunity record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `Name` (string, required): The Opportunity name - This field is required
|
||||
- `StageName` (string, optional): Opportunity Stage - Use Connect Portal Workflow Settings to select stage
|
||||
- `CloseDate` (string, optional): Close Date in YYYY-MM-DD format - Defaults to 30 days from current date
|
||||
- `AccountId` (string, optional): The Account that the Opportunity belongs to
|
||||
- `Amount` (string, optional): Estimated total sale amount
|
||||
- `Description` (string, optional): A description of the Opportunity
|
||||
- `OwnerId` (string, optional): The Salesforce user assigned to work on this Opportunity
|
||||
- `NextStep` (string, optional): Description of next task in closing Opportunity
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Opportunity fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_RECORD_TASK">
|
||||
**Description:** Create a new Task record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `whatId` (string, optional): Related to ID - The ID of the Account or Opportunity this Task is related to
|
||||
- `whoId` (string, optional): Name ID - The ID of the Contact or Lead this Task is related to
|
||||
- `subject` (string, required): Subject of the task
|
||||
- `activityDate` (string, optional): Activity Date in YYYY-MM-DD format
|
||||
- `description` (string, optional): A description of the Task
|
||||
- `taskSubtype` (string, required): Task Subtype - Options: task, email, listEmail, call
|
||||
- `Status` (string, optional): Status - Options: Not Started, In Progress, Completed
|
||||
- `ownerId` (string, optional): Assigned To ID - The Salesforce user assigned to this Task
|
||||
- `callDurationInSeconds` (string, optional): Call Duration in seconds
|
||||
- `isReminderSet` (boolean, optional): Whether reminder is set
|
||||
- `reminderDateTime` (string, optional): Reminder Date/Time in ISO format
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Task fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_RECORD_ACCOUNT">
|
||||
**Description:** Create a new Account record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `Name` (string, required): The Account name - This field is required
|
||||
- `OwnerId` (string, optional): The Salesforce user assigned to this Account
|
||||
- `Website` (string, optional): Website URL
|
||||
- `Phone` (string, optional): Phone number
|
||||
- `Description` (string, optional): Account description
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Account fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_RECORD_ANY">
|
||||
**Description:** Create a record of any object type in Salesforce.
|
||||
|
||||
**Note:** This is a flexible tool for creating records of custom or unknown object types.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Record Updates**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_UPDATE_RECORD_CONTACT">
|
||||
**Description:** Update an existing Contact record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the record to update
|
||||
- `FirstName` (string, optional): First Name
|
||||
- `LastName` (string, optional): Last Name
|
||||
- `accountId` (string, optional): Account ID - The Account that the Contact belongs to
|
||||
- `Email` (string, optional): Email address
|
||||
- `Title` (string, optional): Title of the contact
|
||||
- `Description` (string, optional): A description of the Contact
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Contact fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_UPDATE_RECORD_LEAD">
|
||||
**Description:** Update an existing Lead record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the record to update
|
||||
- `FirstName` (string, optional): First Name
|
||||
- `LastName` (string, optional): Last Name
|
||||
- `Company` (string, optional): Company name
|
||||
- `Email` (string, optional): Email address
|
||||
- `Phone` (string, optional): Phone number
|
||||
- `Website` (string, optional): Website URL
|
||||
- `Title` (string, optional): Title of the contact
|
||||
- `Status` (string, optional): Lead Status
|
||||
- `Description` (string, optional): A description of the Lead
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Lead fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_UPDATE_RECORD_OPPORTUNITY">
|
||||
**Description:** Update an existing Opportunity record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the record to update
|
||||
- `Name` (string, optional): The Opportunity name
|
||||
- `StageName` (string, optional): Opportunity Stage
|
||||
- `CloseDate` (string, optional): Close Date in YYYY-MM-DD format
|
||||
- `AccountId` (string, optional): The Account that the Opportunity belongs to
|
||||
- `Amount` (string, optional): Estimated total sale amount
|
||||
- `Description` (string, optional): A description of the Opportunity
|
||||
- `OwnerId` (string, optional): The Salesforce user assigned to work on this Opportunity
|
||||
- `NextStep` (string, optional): Description of next task in closing Opportunity
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Opportunity fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_UPDATE_RECORD_TASK">
|
||||
**Description:** Update an existing Task record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the record to update
|
||||
- `whatId` (string, optional): Related to ID - The ID of the Account or Opportunity this Task is related to
|
||||
- `whoId` (string, optional): Name ID - The ID of the Contact or Lead this Task is related to
|
||||
- `subject` (string, optional): Subject of the task
|
||||
- `activityDate` (string, optional): Activity Date in YYYY-MM-DD format
|
||||
- `description` (string, optional): A description of the Task
|
||||
- `Status` (string, optional): Status - Options: Not Started, In Progress, Completed
|
||||
- `ownerId` (string, optional): Assigned To ID - The Salesforce user assigned to this Task
|
||||
- `callDurationInSeconds` (string, optional): Call Duration in seconds
|
||||
- `isReminderSet` (boolean, optional): Whether reminder is set
|
||||
- `reminderDateTime` (string, optional): Reminder Date/Time in ISO format
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Task fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_UPDATE_RECORD_ACCOUNT">
|
||||
**Description:** Update an existing Account record in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): The ID of the record to update
|
||||
- `Name` (string, optional): The Account name
|
||||
- `OwnerId` (string, optional): The Salesforce user assigned to this Account
|
||||
- `Website` (string, optional): Website URL
|
||||
- `Phone` (string, optional): Phone number
|
||||
- `Description` (string, optional): Account description
|
||||
- `additionalFields` (object, optional): Additional fields in JSON format for custom Account fields
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_UPDATE_RECORD_ANY">
|
||||
**Description:** Update a record of any object type in Salesforce.
|
||||
|
||||
**Note:** This is a flexible tool for updating records of custom or unknown object types.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Record Retrieval**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_CONTACT">
|
||||
**Description:** Get a Contact record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): Record ID of the Contact
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_LEAD">
|
||||
**Description:** Get a Lead record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): Record ID of the Lead
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_OPPORTUNITY">
|
||||
**Description:** Get an Opportunity record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): Record ID of the Opportunity
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_TASK">
|
||||
**Description:** Get a Task record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): Record ID of the Task
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_ACCOUNT">
|
||||
**Description:** Get an Account record by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordId` (string, required): Record ID of the Account
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_ANY">
|
||||
**Description:** Get a record of any object type by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): Record Type (e.g., "CustomObject__c")
|
||||
- `recordId` (string, required): Record ID
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Record Search**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_SEARCH_RECORDS_CONTACT">
|
||||
**Description:** Search for Contact records with advanced filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): Advanced filter in disjunctive normal form with field-specific operators
|
||||
- `sortBy` (string, optional): Sort field (e.g., "CreatedDate")
|
||||
- `sortDirection` (string, optional): Sort direction - Options: ASC, DESC
|
||||
- `includeAllFields` (boolean, optional): Include all fields in results
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_SEARCH_RECORDS_LEAD">
|
||||
**Description:** Search for Lead records with advanced filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): Advanced filter in disjunctive normal form with field-specific operators
|
||||
- `sortBy` (string, optional): Sort field (e.g., "CreatedDate")
|
||||
- `sortDirection` (string, optional): Sort direction - Options: ASC, DESC
|
||||
- `includeAllFields` (boolean, optional): Include all fields in results
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_SEARCH_RECORDS_OPPORTUNITY">
|
||||
**Description:** Search for Opportunity records with advanced filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): Advanced filter in disjunctive normal form with field-specific operators
|
||||
- `sortBy` (string, optional): Sort field (e.g., "CreatedDate")
|
||||
- `sortDirection` (string, optional): Sort direction - Options: ASC, DESC
|
||||
- `includeAllFields` (boolean, optional): Include all fields in results
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_SEARCH_RECORDS_TASK">
|
||||
**Description:** Search for Task records with advanced filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): Advanced filter in disjunctive normal form with field-specific operators
|
||||
- `sortBy` (string, optional): Sort field (e.g., "CreatedDate")
|
||||
- `sortDirection` (string, optional): Sort direction - Options: ASC, DESC
|
||||
- `includeAllFields` (boolean, optional): Include all fields in results
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_SEARCH_RECORDS_ACCOUNT">
|
||||
**Description:** Search for Account records with advanced filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): Advanced filter in disjunctive normal form with field-specific operators
|
||||
- `sortBy` (string, optional): Sort field (e.g., "CreatedDate")
|
||||
- `sortDirection` (string, optional): Sort direction - Options: ASC, DESC
|
||||
- `includeAllFields` (boolean, optional): Include all fields in results
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_SEARCH_RECORDS_ANY">
|
||||
**Description:** Search for records of any object type.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): Record Type to search
|
||||
- `filterFormula` (string, optional): Filter search criteria
|
||||
- `includeAllFields` (boolean, optional): Include all fields in results
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **List View Retrieval**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_CONTACT">
|
||||
**Description:** Get Contact records from a specific List View.
|
||||
|
||||
**Parameters:**
|
||||
- `listViewId` (string, required): List View ID
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_LEAD">
|
||||
**Description:** Get Lead records from a specific List View.
|
||||
|
||||
**Parameters:**
|
||||
- `listViewId` (string, required): List View ID
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_OPPORTUNITY">
|
||||
**Description:** Get Opportunity records from a specific List View.
|
||||
|
||||
**Parameters:**
|
||||
- `listViewId` (string, required): List View ID
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_TASK">
|
||||
**Description:** Get Task records from a specific List View.
|
||||
|
||||
**Parameters:**
|
||||
- `listViewId` (string, required): List View ID
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_ACCOUNT">
|
||||
**Description:** Get Account records from a specific List View.
|
||||
|
||||
**Parameters:**
|
||||
- `listViewId` (string, required): List View ID
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_ANY">
|
||||
**Description:** Get records of any object type from a specific List View.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): Record Type
|
||||
- `listViewId` (string, required): List View ID
|
||||
- `paginationParameters` (object, optional): Pagination settings with pageCursor
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Custom Fields**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_CONTACT">
|
||||
**Description:** Deploy custom fields for Contact objects.
|
||||
|
||||
**Parameters:**
|
||||
- `label` (string, required): Field Label for displays and internal reference
|
||||
- `type` (string, required): Field Type - Options: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
|
||||
- `defaultCheckboxValue` (boolean, optional): Default value for checkbox fields
|
||||
- `length` (string, required): Length for numeric/text fields
|
||||
- `decimalPlace` (string, required): Decimal places for numeric fields
|
||||
- `pickListValues` (string, required): Values for picklist fields (separated by new lines)
|
||||
- `visibleLines` (string, required): Visible lines for multiselect/text area fields
|
||||
- `description` (string, optional): Field description
|
||||
- `helperText` (string, optional): Helper text shown on hover
|
||||
- `defaultFieldValue` (string, optional): Default field value
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_LEAD">
|
||||
**Description:** Deploy custom fields for Lead objects.
|
||||
|
||||
**Parameters:**
|
||||
- `label` (string, required): Field Label for displays and internal reference
|
||||
- `type` (string, required): Field Type - Options: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
|
||||
- `defaultCheckboxValue` (boolean, optional): Default value for checkbox fields
|
||||
- `length` (string, required): Length for numeric/text fields
|
||||
- `decimalPlace` (string, required): Decimal places for numeric fields
|
||||
- `pickListValues` (string, required): Values for picklist fields (separated by new lines)
|
||||
- `visibleLines` (string, required): Visible lines for multiselect/text area fields
|
||||
- `description` (string, optional): Field description
|
||||
- `helperText` (string, optional): Helper text shown on hover
|
||||
- `defaultFieldValue` (string, optional): Default field value
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_OPPORTUNITY">
|
||||
**Description:** Deploy custom fields for Opportunity objects.
|
||||
|
||||
**Parameters:**
|
||||
- `label` (string, required): Field Label for displays and internal reference
|
||||
- `type` (string, required): Field Type - Options: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
|
||||
- `defaultCheckboxValue` (boolean, optional): Default value for checkbox fields
|
||||
- `length` (string, required): Length for numeric/text fields
|
||||
- `decimalPlace` (string, required): Decimal places for numeric fields
|
||||
- `pickListValues` (string, required): Values for picklist fields (separated by new lines)
|
||||
- `visibleLines` (string, required): Visible lines for multiselect/text area fields
|
||||
- `description` (string, optional): Field description
|
||||
- `helperText` (string, optional): Helper text shown on hover
|
||||
- `defaultFieldValue` (string, optional): Default field value
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_TASK">
|
||||
**Description:** Deploy custom fields for Task objects.
|
||||
|
||||
**Parameters:**
|
||||
- `label` (string, required): Field Label for displays and internal reference
|
||||
- `type` (string, required): Field Type - Options: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, Time, Url
|
||||
- `defaultCheckboxValue` (boolean, optional): Default value for checkbox fields
|
||||
- `length` (string, required): Length for numeric/text fields
|
||||
- `decimalPlace` (string, required): Decimal places for numeric fields
|
||||
- `pickListValues` (string, required): Values for picklist fields (separated by new lines)
|
||||
- `visibleLines` (string, required): Visible lines for multiselect fields
|
||||
- `description` (string, optional): Field description
|
||||
- `helperText` (string, optional): Helper text shown on hover
|
||||
- `defaultFieldValue` (string, optional): Default field value
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_ACCOUNT">
|
||||
**Description:** Deploy custom fields for Account objects.
|
||||
|
||||
**Parameters:**
|
||||
- `label` (string, required): Field Label for displays and internal reference
|
||||
- `type` (string, required): Field Type - Options: Checkbox, Currency, Date, Email, Number, Percent, Phone, Picklist, MultiselectPicklist, Text, TextArea, LongTextArea, Html, Time, Url
|
||||
- `defaultCheckboxValue` (boolean, optional): Default value for checkbox fields
|
||||
- `length` (string, required): Length for numeric/text fields
|
||||
- `decimalPlace` (string, required): Decimal places for numeric fields
|
||||
- `pickListValues` (string, required): Values for picklist fields (separated by new lines)
|
||||
- `visibleLines` (string, required): Visible lines for multiselect/text area fields
|
||||
- `description` (string, optional): Field description
|
||||
- `helperText` (string, optional): Helper text shown on hover
|
||||
- `defaultFieldValue` (string, optional): Default field value
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_ANY">
|
||||
**Description:** Deploy custom fields for any object type.
|
||||
|
||||
**Note:** This is a flexible tool for creating custom fields on custom or unknown object types.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Advanced Operations**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SALESFORCE_WRITE_SOQL_QUERY">
|
||||
**Description:** Execute custom SOQL queries against your Salesforce data.
|
||||
|
||||
**Parameters:**
|
||||
- `query` (string, required): SOQL Query (e.g., "SELECT Id, Name FROM Account WHERE Name = 'Example'")
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_CREATE_CUSTOM_OBJECT">
|
||||
**Description:** Deploy a new custom object in Salesforce.
|
||||
|
||||
**Parameters:**
|
||||
- `label` (string, required): Object Label for tabs, page layouts, and reports
|
||||
- `pluralLabel` (string, required): Plural Label (e.g., "Accounts")
|
||||
- `description` (string, optional): A description of the Custom Object
|
||||
- `recordName` (string, required): Record Name that appears in layouts and searches (e.g., "Account Name")
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SALESFORCE_DESCRIBE_ACTION_SCHEMA">
|
||||
**Description:** Get the expected schema for operations on specific object types.
|
||||
|
||||
**Parameters:**
|
||||
- `recordType` (string, required): Record Type to describe
|
||||
- `operation` (string, required): Operation Type (e.g., "CREATE_RECORD" or "UPDATE_RECORD")
|
||||
|
||||
**Note:** Use this function first when working with custom objects to understand their schema before performing operations.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Salesforce Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Salesforce tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Salesforce capabilities
|
||||
salesforce_agent = Agent(
|
||||
role="CRM Manager",
|
||||
goal="Manage customer relationships and sales processes efficiently",
|
||||
backstory="An AI assistant specialized in CRM operations and sales automation.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new lead
|
||||
create_lead_task = Task(
|
||||
description="Create a new lead for John Doe from Example Corp with email john.doe@example.com",
|
||||
agent=salesforce_agent,
|
||||
expected_output="Lead created successfully with lead ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[salesforce_agent],
|
||||
tasks=[create_lead_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Salesforce Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Salesforce tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["salesforce_create_record_lead", "salesforce_update_record_opportunity", "salesforce_search_records_contact"]
|
||||
)
|
||||
|
||||
sales_manager = Agent(
|
||||
role="Sales Manager",
|
||||
goal="Manage leads and opportunities in the sales pipeline",
|
||||
backstory="An experienced sales manager who handles lead qualification and opportunity management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage sales pipeline
|
||||
pipeline_task = Task(
|
||||
description="Create a qualified lead and convert it to an opportunity with $50,000 value",
|
||||
agent=sales_manager,
|
||||
expected_output="Lead created and opportunity established successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[sales_manager],
|
||||
tasks=[pipeline_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Contact and Account Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
account_manager = Agent(
|
||||
role="Account Manager",
|
||||
goal="Manage customer accounts and maintain strong relationships",
|
||||
backstory="An AI assistant that specializes in account management and customer relationship building.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage customer accounts
|
||||
account_task = Task(
|
||||
description="""
|
||||
1. Create a new account for TechCorp Inc.
|
||||
2. Add John Doe as the primary contact for this account
|
||||
3. Create a follow-up task for next week to check on their project status
|
||||
""",
|
||||
agent=account_manager,
|
||||
expected_output="Account, contact, and follow-up task created successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[account_manager],
|
||||
tasks=[account_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced SOQL Queries and Reporting
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
data_analyst = Agent(
|
||||
role="Sales Data Analyst",
|
||||
goal="Generate insights from Salesforce data using SOQL queries",
|
||||
backstory="An analytical AI that excels at extracting meaningful insights from CRM data.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving SOQL queries and data analysis
|
||||
analysis_task = Task(
|
||||
description="""
|
||||
1. Execute a SOQL query to find all opportunities closing this quarter
|
||||
2. Search for contacts at companies with opportunities over $100K
|
||||
3. Create a summary report of the sales pipeline status
|
||||
4. Update high-value opportunities with next steps
|
||||
""",
|
||||
agent=data_analyst,
|
||||
expected_output="Comprehensive sales pipeline analysis with actionable insights"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[data_analyst],
|
||||
tasks=[analysis_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
This comprehensive documentation covers all the Salesforce tools organized by functionality, making it easy for users to find the specific operations they need for their CRM automation tasks.
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Salesforce integration setup or troubleshooting.
|
||||
</Card>
|
||||
382
docs/en/enterprise/integrations/shopify.mdx
Normal file
382
docs/en/enterprise/integrations/shopify.mdx
Normal file
@@ -0,0 +1,382 @@
|
||||
---
|
||||
title: Shopify Integration
|
||||
description: "E-commerce and online store management with Shopify integration for CrewAI."
|
||||
icon: "shopify"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage e-commerce operations through Shopify. Handle customers, orders, products, inventory, and store analytics to streamline your online business with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Shopify integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Shopify store with appropriate admin permissions
|
||||
- Connected your Shopify store through the [Integrations page](https://app.crewai.com/integrations)
|
||||
|
||||
## Available Tools
|
||||
|
||||
### **Customer Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SHOPIFY_GET_CUSTOMERS">
|
||||
**Description:** Retrieve a list of customers from your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `customerIds` (string, optional): Comma-separated list of customer IDs to filter by (example: "207119551, 207119552")
|
||||
- `createdAtMin` (string, optional): Only return customers created after this date (ISO or Unix timestamp)
|
||||
- `createdAtMax` (string, optional): Only return customers created before this date (ISO or Unix timestamp)
|
||||
- `updatedAtMin` (string, optional): Only return customers updated after this date (ISO or Unix timestamp)
|
||||
- `updatedAtMax` (string, optional): Only return customers updated before this date (ISO or Unix timestamp)
|
||||
- `limit` (string, optional): Maximum number of customers to return (defaults to 250)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_SEARCH_CUSTOMERS">
|
||||
**Description:** Search for customers using advanced filtering criteria.
|
||||
|
||||
**Parameters:**
|
||||
- `filterFormula` (object, optional): Advanced filter in disjunctive normal form with field-specific operators
|
||||
- `limit` (string, optional): Maximum number of customers to return (defaults to 250)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_CREATE_CUSTOMER">
|
||||
**Description:** Create a new customer in your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `firstName` (string, required): Customer's first name
|
||||
- `lastName` (string, required): Customer's last name
|
||||
- `email` (string, required): Customer's email address
|
||||
- `company` (string, optional): Company name
|
||||
- `streetAddressLine1` (string, optional): Street address
|
||||
- `streetAddressLine2` (string, optional): Street address line 2
|
||||
- `city` (string, optional): City
|
||||
- `state` (string, optional): State or province code
|
||||
- `country` (string, optional): Country
|
||||
- `zipCode` (string, optional): Zip code
|
||||
- `phone` (string, optional): Phone number
|
||||
- `tags` (string, optional): Tags as array or comma-separated list
|
||||
- `note` (string, optional): Customer note
|
||||
- `sendEmailInvite` (boolean, optional): Whether to send email invitation
|
||||
- `metafields` (object, optional): Additional metafields in JSON format
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_UPDATE_CUSTOMER">
|
||||
**Description:** Update an existing customer in your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `customerId` (string, required): The ID of the customer to update
|
||||
- `firstName` (string, optional): Customer's first name
|
||||
- `lastName` (string, optional): Customer's last name
|
||||
- `email` (string, optional): Customer's email address
|
||||
- `company` (string, optional): Company name
|
||||
- `streetAddressLine1` (string, optional): Street address
|
||||
- `streetAddressLine2` (string, optional): Street address line 2
|
||||
- `city` (string, optional): City
|
||||
- `state` (string, optional): State or province code
|
||||
- `country` (string, optional): Country
|
||||
- `zipCode` (string, optional): Zip code
|
||||
- `phone` (string, optional): Phone number
|
||||
- `tags` (string, optional): Tags as array or comma-separated list
|
||||
- `note` (string, optional): Customer note
|
||||
- `sendEmailInvite` (boolean, optional): Whether to send email invitation
|
||||
- `metafields` (object, optional): Additional metafields in JSON format
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Order Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SHOPIFY_GET_ORDERS">
|
||||
**Description:** Retrieve a list of orders from your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `orderIds` (string, optional): Comma-separated list of order IDs to filter by (example: "450789469, 450789470")
|
||||
- `createdAtMin` (string, optional): Only return orders created after this date (ISO or Unix timestamp)
|
||||
- `createdAtMax` (string, optional): Only return orders created before this date (ISO or Unix timestamp)
|
||||
- `updatedAtMin` (string, optional): Only return orders updated after this date (ISO or Unix timestamp)
|
||||
- `updatedAtMax` (string, optional): Only return orders updated before this date (ISO or Unix timestamp)
|
||||
- `limit` (string, optional): Maximum number of orders to return (defaults to 250)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_CREATE_ORDER">
|
||||
**Description:** Create a new order in your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `email` (string, required): Customer email address
|
||||
- `lineItems` (object, required): Order line items in JSON format with title, price, quantity, and variant_id
|
||||
- `sendReceipt` (boolean, optional): Whether to send order receipt
|
||||
- `fulfillmentStatus` (string, optional): Fulfillment status - Options: fulfilled, null, partial, restocked
|
||||
- `financialStatus` (string, optional): Financial status - Options: pending, authorized, partially_paid, paid, partially_refunded, refunded, voided
|
||||
- `inventoryBehaviour` (string, optional): Inventory behavior - Options: bypass, decrement_ignoring_policy, decrement_obeying_policy
|
||||
- `note` (string, optional): Order note
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_UPDATE_ORDER">
|
||||
**Description:** Update an existing order in your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `orderId` (string, required): The ID of the order to update
|
||||
- `email` (string, optional): Customer email address
|
||||
- `lineItems` (object, optional): Updated order line items in JSON format
|
||||
- `sendReceipt` (boolean, optional): Whether to send order receipt
|
||||
- `fulfillmentStatus` (string, optional): Fulfillment status - Options: fulfilled, null, partial, restocked
|
||||
- `financialStatus` (string, optional): Financial status - Options: pending, authorized, partially_paid, paid, partially_refunded, refunded, voided
|
||||
- `inventoryBehaviour` (string, optional): Inventory behavior - Options: bypass, decrement_ignoring_policy, decrement_obeying_policy
|
||||
- `note` (string, optional): Order note
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_GET_ABANDONED_CARTS">
|
||||
**Description:** Retrieve abandoned carts from your Shopify store.
|
||||
|
||||
**Parameters:**
|
||||
- `createdWithInLast` (string, optional): Restrict results to checkouts created within specified time
|
||||
- `createdAfterId` (string, optional): Restrict results to after the specified ID
|
||||
- `status` (string, optional): Show checkouts with given status - Options: open, closed (defaults to open)
|
||||
- `createdAtMin` (string, optional): Only return carts created after this date (ISO or Unix timestamp)
|
||||
- `createdAtMax` (string, optional): Only return carts created before this date (ISO or Unix timestamp)
|
||||
- `limit` (string, optional): Maximum number of carts to return (defaults to 250)
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Product Management (REST API)**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SHOPIFY_GET_PRODUCTS">
|
||||
**Description:** Retrieve a list of products from your Shopify store using REST API.
|
||||
|
||||
**Parameters:**
|
||||
- `productIds` (string, optional): Comma-separated list of product IDs to filter by (example: "632910392, 632910393")
|
||||
- `title` (string, optional): Filter by product title
|
||||
- `productType` (string, optional): Filter by product type
|
||||
- `vendor` (string, optional): Filter by vendor
|
||||
- `status` (string, optional): Filter by status - Options: active, archived, draft
|
||||
- `createdAtMin` (string, optional): Only return products created after this date (ISO or Unix timestamp)
|
||||
- `createdAtMax` (string, optional): Only return products created before this date (ISO or Unix timestamp)
|
||||
- `updatedAtMin` (string, optional): Only return products updated after this date (ISO or Unix timestamp)
|
||||
- `updatedAtMax` (string, optional): Only return products updated before this date (ISO or Unix timestamp)
|
||||
- `limit` (string, optional): Maximum number of products to return (defaults to 250)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_CREATE_PRODUCT">
|
||||
**Description:** Create a new product in your Shopify store using REST API.
|
||||
|
||||
**Parameters:**
|
||||
- `title` (string, required): Product title
|
||||
- `productType` (string, required): Product type/category
|
||||
- `vendor` (string, required): Product vendor
|
||||
- `productDescription` (string, optional): Product description (accepts plain text or HTML)
|
||||
- `tags` (string, optional): Product tags as array or comma-separated list
|
||||
- `price` (string, optional): Product price
|
||||
- `inventoryPolicy` (string, optional): Inventory policy - Options: deny, continue
|
||||
- `imageUrl` (string, optional): Product image URL
|
||||
- `isPublished` (boolean, optional): Whether product is published
|
||||
- `publishToPointToSale` (boolean, optional): Whether to publish to point of sale
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_UPDATE_PRODUCT">
|
||||
**Description:** Update an existing product in your Shopify store using REST API.
|
||||
|
||||
**Parameters:**
|
||||
- `productId` (string, required): The ID of the product to update
|
||||
- `title` (string, optional): Product title
|
||||
- `productType` (string, optional): Product type/category
|
||||
- `vendor` (string, optional): Product vendor
|
||||
- `productDescription` (string, optional): Product description (accepts plain text or HTML)
|
||||
- `tags` (string, optional): Product tags as array or comma-separated list
|
||||
- `price` (string, optional): Product price
|
||||
- `inventoryPolicy` (string, optional): Inventory policy - Options: deny, continue
|
||||
- `imageUrl` (string, optional): Product image URL
|
||||
- `isPublished` (boolean, optional): Whether product is published
|
||||
- `publishToPointToSale` (boolean, optional): Whether to publish to point of sale
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Product Management (GraphQL)**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SHOPIFY_GET_PRODUCTS_GRAPHQL">
|
||||
**Description:** Retrieve products using advanced GraphQL filtering capabilities.
|
||||
|
||||
**Parameters:**
|
||||
- `productFilterFormula` (object, optional): Advanced filter in disjunctive normal form with support for fields like id, title, vendor, status, handle, tag, created_at, updated_at, published_at
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_CREATE_PRODUCT_GRAPHQL">
|
||||
**Description:** Create a new product using GraphQL API with enhanced media support.
|
||||
|
||||
**Parameters:**
|
||||
- `title` (string, required): Product title
|
||||
- `productType` (string, required): Product type/category
|
||||
- `vendor` (string, required): Product vendor
|
||||
- `productDescription` (string, optional): Product description (accepts plain text or HTML)
|
||||
- `tags` (string, optional): Product tags as array or comma-separated list
|
||||
- `media` (object, optional): Media objects with alt text, content type, and source URL
|
||||
- `additionalFields` (object, optional): Additional product fields like status, requiresSellingPlan, giftCard
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SHOPIFY_UPDATE_PRODUCT_GRAPHQL">
|
||||
**Description:** Update an existing product using GraphQL API with enhanced media support.
|
||||
|
||||
**Parameters:**
|
||||
- `productId` (string, required): The GraphQL ID of the product to update (e.g., "gid://shopify/Product/913144112")
|
||||
- `title` (string, optional): Product title
|
||||
- `productType` (string, optional): Product type/category
|
||||
- `vendor` (string, optional): Product vendor
|
||||
- `productDescription` (string, optional): Product description (accepts plain text or HTML)
|
||||
- `tags` (string, optional): Product tags as array or comma-separated list
|
||||
- `media` (object, optional): Updated media objects with alt text, content type, and source URL
|
||||
- `additionalFields` (object, optional): Additional product fields like status, requiresSellingPlan, giftCard
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Shopify Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Shopify tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Shopify capabilities
|
||||
shopify_agent = Agent(
|
||||
role="E-commerce Manager",
|
||||
goal="Manage online store operations and customer relationships efficiently",
|
||||
backstory="An AI assistant specialized in e-commerce operations and online store management.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new customer
|
||||
create_customer_task = Task(
|
||||
description="Create a new VIP customer Jane Smith with email jane.smith@example.com and phone +1-555-0123",
|
||||
agent=shopify_agent,
|
||||
expected_output="Customer created successfully with customer ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[shopify_agent],
|
||||
tasks=[create_customer_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Shopify Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Shopify tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["shopify_create_customer", "shopify_create_order", "shopify_get_products"]
|
||||
)
|
||||
|
||||
store_manager = Agent(
|
||||
role="Store Manager",
|
||||
goal="Manage customer orders and product catalog",
|
||||
backstory="An experienced store manager who handles customer relationships and inventory management.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage store operations
|
||||
store_task = Task(
|
||||
description="Create a new customer and process their order for 2 Premium Coffee Mugs",
|
||||
agent=store_manager,
|
||||
expected_output="Customer created and order processed successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[store_manager],
|
||||
tasks=[store_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Product Management with GraphQL
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
product_manager = Agent(
|
||||
role="Product Manager",
|
||||
goal="Manage product catalog and inventory with advanced GraphQL capabilities",
|
||||
backstory="An AI assistant that specializes in product management and catalog optimization.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage product catalog
|
||||
catalog_task = Task(
|
||||
description="""
|
||||
1. Create a new product "Premium Coffee Mug" from Coffee Co vendor
|
||||
2. Add high-quality product images and descriptions
|
||||
3. Search for similar products from the same vendor
|
||||
4. Update product tags and pricing strategy
|
||||
""",
|
||||
agent=product_manager,
|
||||
expected_output="Product created and catalog optimized successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[product_manager],
|
||||
tasks=[catalog_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Order and Customer Analytics
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
analytics_agent = Agent(
|
||||
role="E-commerce Analyst",
|
||||
goal="Analyze customer behavior and order patterns to optimize store performance",
|
||||
backstory="An analytical AI that excels at extracting insights from e-commerce data.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving multiple operations
|
||||
analytics_task = Task(
|
||||
description="""
|
||||
1. Retrieve recent customer data and order history
|
||||
2. Identify abandoned carts from the last 7 days
|
||||
3. Analyze product performance and inventory levels
|
||||
4. Generate recommendations for customer retention
|
||||
""",
|
||||
agent=analytics_agent,
|
||||
expected_output="Comprehensive e-commerce analytics report with actionable insights"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[analytics_agent],
|
||||
tasks=[analytics_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Shopify integration setup or troubleshooting.
|
||||
</Card>
|
||||
293
docs/en/enterprise/integrations/slack.mdx
Normal file
293
docs/en/enterprise/integrations/slack.mdx
Normal file
@@ -0,0 +1,293 @@
|
||||
---
|
||||
title: Slack Integration
|
||||
description: "Team communication and collaboration with Slack integration for CrewAI."
|
||||
icon: "slack"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage team communication through Slack. Send messages, search conversations, manage channels, and coordinate team activities to streamline your collaboration workflows with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Slack integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Slack workspace with appropriate permissions
|
||||
- Connected your Slack workspace through the [Integrations page](https://app.crewai.com/integrations)
|
||||
|
||||
## Available Tools
|
||||
|
||||
### **User Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SLACK_LIST_MEMBERS">
|
||||
**Description:** List all members in a Slack channel.
|
||||
|
||||
**Parameters:**
|
||||
- No parameters required - retrieves all channel members
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SLACK_GET_USER_BY_EMAIL">
|
||||
**Description:** Find a user in your Slack workspace by their email address.
|
||||
|
||||
**Parameters:**
|
||||
- `email` (string, required): The email address of a user in the workspace
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SLACK_GET_USERS_BY_NAME">
|
||||
**Description:** Search for users by their name or display name.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string, required): User's real name to search for
|
||||
- `displayName` (string, required): User's display name to search for
|
||||
- `paginationParameters` (object, optional): Pagination settings
|
||||
- `pageCursor` (string, optional): Page cursor for pagination
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Channel Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SLACK_LIST_CHANNELS">
|
||||
**Description:** List all channels in your Slack workspace.
|
||||
|
||||
**Parameters:**
|
||||
- No parameters required - retrieves all accessible channels
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Messaging**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SLACK_SEND_MESSAGE">
|
||||
**Description:** Send a message to a Slack channel.
|
||||
|
||||
**Parameters:**
|
||||
- `channel` (string, required): Channel name or ID - Use Connect Portal Workflow Settings to allow users to select a channel, or enter a channel name to create a new channel
|
||||
- `message` (string, required): The message text to send
|
||||
- `botName` (string, required): The name of the bot that sends this message
|
||||
- `botIcon` (string, required): Bot icon - Can be either an image URL or an emoji (e.g., ":dog:")
|
||||
- `blocks` (object, optional): Slack Block Kit JSON for rich message formatting with attachments and interactive elements
|
||||
- `authenticatedUser` (boolean, optional): If true, message appears to come from your authenticated Slack user instead of the application (defaults to false)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SLACK_SEND_DIRECT_MESSAGE">
|
||||
**Description:** Send a direct message to a specific user in Slack.
|
||||
|
||||
**Parameters:**
|
||||
- `memberId` (string, required): Recipient user ID - Use Connect Portal Workflow Settings to allow users to select a workspace member
|
||||
- `message` (string, required): The message text to send
|
||||
- `botName` (string, required): The name of the bot that sends this message
|
||||
- `botIcon` (string, required): Bot icon - Can be either an image URL or an emoji (e.g., ":dog:")
|
||||
- `blocks` (object, optional): Slack Block Kit JSON for rich message formatting with attachments and interactive elements
|
||||
- `authenticatedUser` (boolean, optional): If true, message appears to come from your authenticated Slack user instead of the application (defaults to false)
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Search & Discovery**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="SLACK_SEARCH_MESSAGES">
|
||||
**Description:** Search for messages across your Slack workspace.
|
||||
|
||||
**Parameters:**
|
||||
- `query` (string, required): Search query using Slack search syntax to find messages that match specified criteria
|
||||
|
||||
**Search Query Examples:**
|
||||
- `"project update"` - Search for messages containing "project update"
|
||||
- `from:@john in:#general` - Search for messages from John in the #general channel
|
||||
- `has:link after:2023-01-01` - Search for messages with links after January 1, 2023
|
||||
- `in:@channel before:yesterday` - Search for messages in a specific channel before yesterday
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Block Kit Integration
|
||||
|
||||
Slack's Block Kit allows you to create rich, interactive messages. Here are some examples of how to use the `blocks` parameter:
|
||||
|
||||
### Simple Text with Attachment
|
||||
```json
|
||||
[
|
||||
{
|
||||
"text": "I am a test message",
|
||||
"attachments": [
|
||||
{
|
||||
"text": "And here's an attachment!"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Rich Formatting with Sections
|
||||
```json
|
||||
[
|
||||
{
|
||||
"type": "section",
|
||||
"text": {
|
||||
"type": "mrkdwn",
|
||||
"text": "*Project Update*\nStatus: ✅ Complete"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "divider"
|
||||
},
|
||||
{
|
||||
"type": "section",
|
||||
"text": {
|
||||
"type": "plain_text",
|
||||
"text": "All tasks have been completed successfully."
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Slack Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Slack tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Slack capabilities
|
||||
slack_agent = Agent(
|
||||
role="Team Communication Manager",
|
||||
goal="Facilitate team communication and coordinate collaboration efficiently",
|
||||
backstory="An AI assistant specialized in team communication and workspace coordination.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to send project updates
|
||||
update_task = Task(
|
||||
description="Send a project status update to the #general channel with current progress",
|
||||
agent=slack_agent,
|
||||
expected_output="Project update message sent successfully to team channel"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[slack_agent],
|
||||
tasks=[update_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Slack Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Slack tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["slack_send_message", "slack_send_direct_message", "slack_search_messages"]
|
||||
)
|
||||
|
||||
communication_manager = Agent(
|
||||
role="Communication Coordinator",
|
||||
goal="Manage team communications and ensure important messages reach the right people",
|
||||
backstory="An experienced communication coordinator who handles team messaging and notifications.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to coordinate team communication
|
||||
coordination_task = Task(
|
||||
description="Send task completion notifications to team members and update project channels",
|
||||
agent=communication_manager,
|
||||
expected_output="Team notifications sent and project channels updated successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[communication_manager],
|
||||
tasks=[coordination_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced Messaging with Block Kit
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
notification_agent = Agent(
|
||||
role="Notification Manager",
|
||||
goal="Create rich, interactive notifications and manage workspace communication",
|
||||
backstory="An AI assistant that specializes in creating engaging team notifications and updates.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to send rich notifications
|
||||
notification_task = Task(
|
||||
description="""
|
||||
1. Send a formatted project completion message to #general with progress charts
|
||||
2. Send direct messages to team leads with task summaries
|
||||
3. Create interactive notification with action buttons for team feedback
|
||||
""",
|
||||
agent=notification_agent,
|
||||
expected_output="Rich notifications sent with interactive elements and formatted content"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[notification_agent],
|
||||
tasks=[notification_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Message Search and Analytics
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
analytics_agent = Agent(
|
||||
role="Communication Analyst",
|
||||
goal="Analyze team communication patterns and extract insights from conversations",
|
||||
backstory="An analytical AI that excels at understanding team dynamics through communication data.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving search and analysis
|
||||
analysis_task = Task(
|
||||
description="""
|
||||
1. Search for recent project-related messages across all channels
|
||||
2. Find users by email to identify team members
|
||||
3. Analyze communication patterns and response times
|
||||
4. Generate weekly team communication summary
|
||||
""",
|
||||
agent=analytics_agent,
|
||||
expected_output="Comprehensive communication analysis with team insights and recommendations"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[analytics_agent],
|
||||
tasks=[analysis_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Contact Support
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for assistance with Slack integration setup or troubleshooting.
|
||||
</Card>
|
||||
305
docs/en/enterprise/integrations/stripe.mdx
Normal file
305
docs/en/enterprise/integrations/stripe.mdx
Normal file
@@ -0,0 +1,305 @@
|
||||
---
|
||||
title: Stripe Integration
|
||||
description: "Payment processing and subscription management with Stripe integration for CrewAI."
|
||||
icon: "stripe"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage payments, subscriptions, and customer billing through Stripe. Handle customer data, process subscriptions, manage products, and track financial transactions to streamline your payment workflows with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Stripe integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Stripe account with appropriate API permissions
|
||||
- Connected your Stripe account through the [Integrations page](https://app.crewai.com/integrations)
|
||||
|
||||
## Available Tools
|
||||
|
||||
### **Customer Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="STRIPE_CREATE_CUSTOMER">
|
||||
**Description:** Create a new customer in your Stripe account.
|
||||
|
||||
**Parameters:**
|
||||
- `emailCreateCustomer` (string, required): Customer's email address
|
||||
- `name` (string, optional): Customer's full name
|
||||
- `description` (string, optional): Customer description for internal reference
|
||||
- `metadataCreateCustomer` (object, optional): Additional metadata as key-value pairs (e.g., `{"field1": 1, "field2": 2}`)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_GET_CUSTOMER_BY_ID">
|
||||
**Description:** Retrieve a specific customer by their Stripe customer ID.
|
||||
|
||||
**Parameters:**
|
||||
- `idGetCustomer` (string, required): The Stripe customer ID to retrieve
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_GET_CUSTOMERS">
|
||||
**Description:** Retrieve a list of customers with optional filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `emailGetCustomers` (string, optional): Filter customers by email address
|
||||
- `createdAfter` (string, optional): Filter customers created after this date (Unix timestamp)
|
||||
- `createdBefore` (string, optional): Filter customers created before this date (Unix timestamp)
|
||||
- `limitGetCustomers` (string, optional): Maximum number of customers to return (defaults to 10)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_UPDATE_CUSTOMER">
|
||||
**Description:** Update an existing customer's information.
|
||||
|
||||
**Parameters:**
|
||||
- `customerId` (string, required): The ID of the customer to update
|
||||
- `emailUpdateCustomer` (string, optional): Updated email address
|
||||
- `name` (string, optional): Updated customer name
|
||||
- `description` (string, optional): Updated customer description
|
||||
- `metadataUpdateCustomer` (object, optional): Updated metadata as key-value pairs
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Subscription Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="STRIPE_CREATE_SUBSCRIPTION">
|
||||
**Description:** Create a new subscription for a customer.
|
||||
|
||||
**Parameters:**
|
||||
- `customerIdCreateSubscription` (string, required): The customer ID for whom the subscription will be created
|
||||
- `plan` (string, required): The plan ID for the subscription - Use Connect Portal Workflow Settings to allow users to select a plan
|
||||
- `metadataCreateSubscription` (object, optional): Additional metadata for the subscription
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_GET_SUBSCRIPTIONS">
|
||||
**Description:** Retrieve subscriptions with optional filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `customerIdGetSubscriptions` (string, optional): Filter subscriptions by customer ID
|
||||
- `subscriptionStatus` (string, optional): Filter by subscription status - Options: incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid
|
||||
- `limitGetSubscriptions` (string, optional): Maximum number of subscriptions to return (defaults to 10)
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Product Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="STRIPE_CREATE_PRODUCT">
|
||||
**Description:** Create a new product in your Stripe catalog.
|
||||
|
||||
**Parameters:**
|
||||
- `productName` (string, required): The product name
|
||||
- `description` (string, optional): Product description
|
||||
- `metadataProduct` (object, optional): Additional product metadata as key-value pairs
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_GET_PRODUCT_BY_ID">
|
||||
**Description:** Retrieve a specific product by its Stripe product ID.
|
||||
|
||||
**Parameters:**
|
||||
- `productId` (string, required): The Stripe product ID to retrieve
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_GET_PRODUCTS">
|
||||
**Description:** Retrieve a list of products with optional filtering.
|
||||
|
||||
**Parameters:**
|
||||
- `createdAfter` (string, optional): Filter products created after this date (Unix timestamp)
|
||||
- `createdBefore` (string, optional): Filter products created before this date (Unix timestamp)
|
||||
- `limitGetProducts` (string, optional): Maximum number of products to return (defaults to 10)
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Financial Operations**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="STRIPE_GET_BALANCE_TRANSACTIONS">
|
||||
**Description:** Retrieve balance transactions from your Stripe account.
|
||||
|
||||
**Parameters:**
|
||||
- `balanceTransactionType` (string, optional): Filter by transaction type - Options: charge, refund, payment, payment_refund
|
||||
- `paginationParameters` (object, optional): Pagination settings
|
||||
- `pageCursor` (string, optional): Page cursor for pagination
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="STRIPE_GET_PLANS">
|
||||
**Description:** Retrieve subscription plans from your Stripe account.
|
||||
|
||||
**Parameters:**
|
||||
- `isPlanActive` (boolean, optional): Filter by plan status - true for active plans, false for inactive plans
|
||||
- `paginationParameters` (object, optional): Pagination settings
|
||||
- `pageCursor` (string, optional): Page cursor for pagination
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Stripe Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Stripe tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Stripe capabilities
|
||||
stripe_agent = Agent(
|
||||
role="Payment Manager",
|
||||
goal="Manage customer payments, subscriptions, and billing operations efficiently",
|
||||
backstory="An AI assistant specialized in payment processing and subscription management.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new customer
|
||||
create_customer_task = Task(
|
||||
description="Create a new premium customer John Doe with email john.doe@example.com",
|
||||
agent=stripe_agent,
|
||||
expected_output="Customer created successfully with customer ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[stripe_agent],
|
||||
tasks=[create_customer_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Stripe Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Stripe tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["stripe_create_customer", "stripe_create_subscription", "stripe_get_balance_transactions"]
|
||||
)
|
||||
|
||||
billing_manager = Agent(
|
||||
role="Billing Manager",
|
||||
goal="Handle customer billing, subscriptions, and payment processing",
|
||||
backstory="An experienced billing manager who handles subscription lifecycle and payment operations.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage billing operations
|
||||
billing_task = Task(
|
||||
description="Create a new customer and set up their premium subscription plan",
|
||||
agent=billing_manager,
|
||||
expected_output="Customer created and subscription activated successfully"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[billing_manager],
|
||||
tasks=[billing_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Subscription Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
subscription_manager = Agent(
|
||||
role="Subscription Manager",
|
||||
goal="Manage customer subscriptions and optimize recurring revenue",
|
||||
backstory="An AI assistant that specializes in subscription lifecycle management and customer retention.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage subscription operations
|
||||
subscription_task = Task(
|
||||
description="""
|
||||
1. Create a new product "Premium Service Plan" with advanced features
|
||||
2. Set up subscription plans with different tiers
|
||||
3. Create customers and assign them to appropriate plans
|
||||
4. Monitor subscription status and handle billing issues
|
||||
""",
|
||||
agent=subscription_manager,
|
||||
expected_output="Subscription management system configured with customers and active plans"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[subscription_manager],
|
||||
tasks=[subscription_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Financial Analytics and Reporting
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
financial_analyst = Agent(
|
||||
role="Financial Analyst",
|
||||
goal="Analyze payment data and generate financial insights",
|
||||
backstory="An analytical AI that excels at extracting insights from payment and subscription data.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving financial analysis
|
||||
analytics_task = Task(
|
||||
description="""
|
||||
1. Retrieve balance transactions for the current month
|
||||
2. Analyze customer payment patterns and subscription trends
|
||||
3. Identify high-value customers and subscription performance
|
||||
4. Generate monthly financial performance report
|
||||
""",
|
||||
agent=financial_analyst,
|
||||
expected_output="Comprehensive financial analysis with payment insights and recommendations"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[financial_analyst],
|
||||
tasks=[analytics_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## Subscription Status Reference
|
||||
|
||||
Understanding subscription statuses:
|
||||
|
||||
- **incomplete** - Subscription requires payment method or payment confirmation
|
||||
- **incomplete_expired** - Subscription expired before payment was confirmed
|
||||
- **trialing** - Subscription is in trial period
|
||||
- **active** - Subscription is active and current
|
||||
- **past_due** - Payment failed but subscription is still active
|
||||
- **canceled** - Subscription has been canceled
|
||||
- **unpaid** - Payment failed and subscription is no longer active
|
||||
|
||||
## Metadata Usage
|
||||
|
||||
Metadata allows you to store additional information about customers, subscriptions, and products:
|
||||
|
||||
```json
|
||||
{
|
||||
"customer_segment": "enterprise",
|
||||
"acquisition_source": "google_ads",
|
||||
"lifetime_value": "high",
|
||||
"custom_field_1": "value1"
|
||||
}
|
||||
```
|
||||
|
||||
This integration enables comprehensive payment and subscription management automation, allowing your AI agents to handle billing operations seamlessly within your Stripe ecosystem.
|
||||
343
docs/en/enterprise/integrations/zendesk.mdx
Normal file
343
docs/en/enterprise/integrations/zendesk.mdx
Normal file
@@ -0,0 +1,343 @@
|
||||
---
|
||||
title: Zendesk Integration
|
||||
description: "Customer support and helpdesk management with Zendesk integration for CrewAI."
|
||||
icon: "headset"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Enable your agents to manage customer support operations through Zendesk. Create and update tickets, manage users, track support metrics, and streamline your customer service workflows with AI-powered automation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the Zendesk integration, ensure you have:
|
||||
|
||||
- A [CrewAI Enterprise](https://app.crewai.com) account with an active subscription
|
||||
- A Zendesk account with appropriate API permissions
|
||||
- Connected your Zendesk account through the [Integrations page](https://app.crewai.com/integrations)
|
||||
|
||||
## Available Tools
|
||||
|
||||
### **Ticket Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="ZENDESK_CREATE_TICKET">
|
||||
**Description:** Create a new support ticket in Zendesk.
|
||||
|
||||
**Parameters:**
|
||||
- `ticketSubject` (string, required): Ticket subject line (e.g., "Help, my printer is on fire!")
|
||||
- `ticketDescription` (string, required): First comment that appears on the ticket (e.g., "The smoke is very colorful.")
|
||||
- `requesterName` (string, required): Name of the user requesting support (e.g., "Jane Customer")
|
||||
- `requesterEmail` (string, required): Email of the user requesting support (e.g., "jane@example.com")
|
||||
- `assigneeId` (string, optional): Zendesk Agent ID assigned to this ticket - Use Connect Portal Workflow Settings to allow users to select an assignee
|
||||
- `ticketType` (string, optional): Ticket type - Options: problem, incident, question, task
|
||||
- `ticketPriority` (string, optional): Priority level - Options: urgent, high, normal, low
|
||||
- `ticketStatus` (string, optional): Ticket status - Options: new, open, pending, hold, solved, closed
|
||||
- `ticketDueAt` (string, optional): Due date for task-type tickets (ISO 8601 timestamp)
|
||||
- `ticketTags` (string, optional): Array of tags to apply (e.g., `["enterprise", "other_tag"]`)
|
||||
- `ticketExternalId` (string, optional): External ID to link tickets to local records
|
||||
- `ticketCustomFields` (object, optional): Custom field values in JSON format
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_UPDATE_TICKET">
|
||||
**Description:** Update an existing support ticket in Zendesk.
|
||||
|
||||
**Parameters:**
|
||||
- `ticketId` (string, required): ID of the ticket to update (e.g., "35436")
|
||||
- `ticketSubject` (string, optional): Updated ticket subject
|
||||
- `requesterName` (string, required): Name of the user who requested this ticket
|
||||
- `requesterEmail` (string, required): Email of the user who requested this ticket
|
||||
- `assigneeId` (string, optional): Updated assignee ID - Use Connect Portal Workflow Settings
|
||||
- `ticketType` (string, optional): Updated ticket type - Options: problem, incident, question, task
|
||||
- `ticketPriority` (string, optional): Updated priority - Options: urgent, high, normal, low
|
||||
- `ticketStatus` (string, optional): Updated status - Options: new, open, pending, hold, solved, closed
|
||||
- `ticketDueAt` (string, optional): Updated due date (ISO 8601 timestamp)
|
||||
- `ticketTags` (string, optional): Updated tags array
|
||||
- `ticketExternalId` (string, optional): Updated external ID
|
||||
- `ticketCustomFields` (object, optional): Updated custom field values
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_GET_TICKET_BY_ID">
|
||||
**Description:** Retrieve a specific ticket by its ID.
|
||||
|
||||
**Parameters:**
|
||||
- `ticketId` (string, required): The ticket ID to retrieve (e.g., "35436")
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_ADD_COMMENT_TO_TICKET">
|
||||
**Description:** Add a comment or internal note to an existing ticket.
|
||||
|
||||
**Parameters:**
|
||||
- `ticketId` (string, required): ID of the ticket to add comment to (e.g., "35436")
|
||||
- `commentBody` (string, required): Comment message (accepts plain text or HTML, e.g., "Thanks for your help!")
|
||||
- `isInternalNote` (boolean, optional): Set to true for internal notes instead of public replies (defaults to false)
|
||||
- `isPublic` (boolean, optional): True for public comments, false for internal notes
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_SEARCH_TICKETS">
|
||||
**Description:** Search for tickets using various filters and criteria.
|
||||
|
||||
**Parameters:**
|
||||
- `ticketSubject` (string, optional): Filter by text in ticket subject
|
||||
- `ticketDescription` (string, optional): Filter by text in ticket description and comments
|
||||
- `ticketStatus` (string, optional): Filter by status - Options: new, open, pending, hold, solved, closed
|
||||
- `ticketType` (string, optional): Filter by type - Options: problem, incident, question, task, no_type
|
||||
- `ticketPriority` (string, optional): Filter by priority - Options: urgent, high, normal, low, no_priority
|
||||
- `requesterId` (string, optional): Filter by requester user ID
|
||||
- `assigneeId` (string, optional): Filter by assigned agent ID
|
||||
- `recipientEmail` (string, optional): Filter by original recipient email address
|
||||
- `ticketTags` (string, optional): Filter by ticket tags
|
||||
- `ticketExternalId` (string, optional): Filter by external ID
|
||||
- `createdDate` (object, optional): Filter by creation date with operator (EQUALS, LESS_THAN_EQUALS, GREATER_THAN_EQUALS) and value
|
||||
- `updatedDate` (object, optional): Filter by update date with operator and value
|
||||
- `dueDate` (object, optional): Filter by due date with operator and value
|
||||
- `sort_by` (string, optional): Sort field - Options: created_at, updated_at, priority, status, ticket_type
|
||||
- `sort_order` (string, optional): Sort direction - Options: asc, desc
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **User Management**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="ZENDESK_CREATE_USER">
|
||||
**Description:** Create a new user in Zendesk.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string, required): User's full name
|
||||
- `email` (string, optional): User's email address (e.g., "jane@example.com")
|
||||
- `phone` (string, optional): User's phone number
|
||||
- `role` (string, optional): User role - Options: admin, agent, end-user
|
||||
- `externalId` (string, optional): Unique identifier from another system
|
||||
- `details` (string, optional): Additional user details
|
||||
- `notes` (string, optional): Internal notes about the user
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_UPDATE_USER">
|
||||
**Description:** Update an existing user's information.
|
||||
|
||||
**Parameters:**
|
||||
- `userId` (string, required): ID of the user to update
|
||||
- `name` (string, optional): Updated user name
|
||||
- `email` (string, optional): Updated email (adds as secondary email on update)
|
||||
- `phone` (string, optional): Updated phone number
|
||||
- `role` (string, optional): Updated role - Options: admin, agent, end-user
|
||||
- `externalId` (string, optional): Updated external ID
|
||||
- `details` (string, optional): Updated user details
|
||||
- `notes` (string, optional): Updated internal notes
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_GET_USER_BY_ID">
|
||||
**Description:** Retrieve a specific user by their ID.
|
||||
|
||||
**Parameters:**
|
||||
- `userId` (string, required): The user ID to retrieve
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_SEARCH_USERS">
|
||||
**Description:** Search for users using various criteria.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string, optional): Filter by user name
|
||||
- `email` (string, optional): Filter by user email (e.g., "jane@example.com")
|
||||
- `role` (string, optional): Filter by role - Options: admin, agent, end-user
|
||||
- `externalId` (string, optional): Filter by external ID
|
||||
- `sort_by` (string, optional): Sort field - Options: created_at, updated_at
|
||||
- `sort_order` (string, optional): Sort direction - Options: asc, desc
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### **Administrative Tools**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="ZENDESK_GET_TICKET_FIELDS">
|
||||
**Description:** Retrieve all standard and custom fields available for tickets.
|
||||
|
||||
**Parameters:**
|
||||
- `paginationParameters` (object, optional): Pagination settings
|
||||
- `pageCursor` (string, optional): Page cursor for pagination
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ZENDESK_GET_TICKET_AUDITS">
|
||||
**Description:** Get audit records (read-only history) for tickets.
|
||||
|
||||
**Parameters:**
|
||||
- `ticketId` (string, optional): Get audits for specific ticket (if empty, retrieves audits for all non-archived tickets, e.g., "1234")
|
||||
- `paginationParameters` (object, optional): Pagination settings
|
||||
- `pageCursor` (string, optional): Page cursor for pagination
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Custom Fields
|
||||
|
||||
Custom fields allow you to store additional information specific to your organization:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "id": 27642, "value": "745" },
|
||||
{ "id": 27648, "value": "yes" }
|
||||
]
|
||||
```
|
||||
|
||||
## Ticket Priority Levels
|
||||
|
||||
Understanding priority levels:
|
||||
|
||||
- **urgent** - Critical issues requiring immediate attention
|
||||
- **high** - Important issues that should be addressed quickly
|
||||
- **normal** - Standard priority for most tickets
|
||||
- **low** - Minor issues that can be addressed when convenient
|
||||
|
||||
## Ticket Status Workflow
|
||||
|
||||
Standard ticket status progression:
|
||||
|
||||
- **new** - Recently created, not yet assigned
|
||||
- **open** - Actively being worked on
|
||||
- **pending** - Waiting for customer response or external action
|
||||
- **hold** - Temporarily paused
|
||||
- **solved** - Issue resolved, awaiting customer confirmation
|
||||
- **closed** - Ticket completed and closed
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Zendesk Agent Setup
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get enterprise tools (Zendesk tools will be included)
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
# Create an agent with Zendesk capabilities
|
||||
zendesk_agent = Agent(
|
||||
role="Support Manager",
|
||||
goal="Manage customer support tickets and provide excellent customer service",
|
||||
backstory="An AI assistant specialized in customer support operations and ticket management.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to create a new support ticket
|
||||
create_ticket_task = Task(
|
||||
description="Create a high-priority support ticket for John Smith who is unable to access his account after password reset",
|
||||
agent=zendesk_agent,
|
||||
expected_output="Support ticket created successfully with ticket ID"
|
||||
)
|
||||
|
||||
# Run the task
|
||||
crew = Crew(
|
||||
agents=[zendesk_agent],
|
||||
tasks=[create_ticket_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Filtering Specific Zendesk Tools
|
||||
|
||||
```python
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
# Get only specific Zendesk tools
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token",
|
||||
actions_list=["zendesk_create_ticket", "zendesk_update_ticket", "zendesk_add_comment_to_ticket"]
|
||||
)
|
||||
|
||||
support_agent = Agent(
|
||||
role="Customer Support Agent",
|
||||
goal="Handle customer inquiries and resolve support issues efficiently",
|
||||
backstory="An experienced support agent who specializes in ticket resolution and customer communication.",
|
||||
tools=enterprise_tools
|
||||
)
|
||||
|
||||
# Task to manage support workflow
|
||||
support_task = Task(
|
||||
description="Create a ticket for login issues, add troubleshooting comments, and update status to resolved",
|
||||
agent=support_agent,
|
||||
expected_output="Support ticket managed through complete resolution workflow"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[support_agent],
|
||||
tasks=[support_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Advanced Ticket Management
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
ticket_manager = Agent(
|
||||
role="Ticket Manager",
|
||||
goal="Manage support ticket workflows and ensure timely resolution",
|
||||
backstory="An AI assistant that specializes in support ticket triage and workflow optimization.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Task to manage ticket lifecycle
|
||||
ticket_workflow = Task(
|
||||
description="""
|
||||
1. Create a new support ticket for account access issues
|
||||
2. Add internal notes with troubleshooting steps
|
||||
3. Update ticket priority based on customer tier
|
||||
4. Add resolution comments and close the ticket
|
||||
""",
|
||||
agent=ticket_manager,
|
||||
expected_output="Complete ticket lifecycle managed from creation to resolution"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[ticket_manager],
|
||||
tasks=[ticket_workflow]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
### Support Analytics and Reporting
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import CrewaiEnterpriseTools
|
||||
|
||||
enterprise_tools = CrewaiEnterpriseTools(
|
||||
enterprise_token="your_enterprise_token"
|
||||
)
|
||||
|
||||
support_analyst = Agent(
|
||||
role="Support Analyst",
|
||||
goal="Analyze support metrics and generate insights for team performance",
|
||||
backstory="An analytical AI that excels at extracting insights from support data and ticket patterns.",
|
||||
tools=[enterprise_tools]
|
||||
)
|
||||
|
||||
# Complex task involving analytics and reporting
|
||||
analytics_task = Task(
|
||||
description="""
|
||||
1. Search for all open tickets from the last 30 days
|
||||
2. Analyze ticket resolution times and customer satisfaction
|
||||
3. Identify common issues and support patterns
|
||||
4. Generate weekly support performance report
|
||||
""",
|
||||
agent=support_analyst,
|
||||
expected_output="Comprehensive support analytics report with performance insights and recommendations"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[support_analyst],
|
||||
tasks=[analytics_task]
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
```
|
||||
99
docs/en/enterprise/introduction.mdx
Normal file
99
docs/en/enterprise/introduction.mdx
Normal file
@@ -0,0 +1,99 @@
|
||||
---
|
||||
title: "CrewAI Enterprise"
|
||||
description: "Deploy, monitor, and scale your AI agent workflows"
|
||||
icon: "globe"
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
CrewAI Enterprise provides a platform for deploying, monitoring, and scaling your crews and agents in a production environment.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crewai-enterprise-dashboard.png" alt="CrewAI Enterprise Dashboard" />
|
||||
</Frame>
|
||||
|
||||
CrewAI Enterprise extends the power of the open-source framework with features designed for production deployments, collaboration, and scalability. Deploy your crews to a managed infrastructure and monitor their execution in real-time.
|
||||
|
||||
## Key Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Crew Deployments" icon="rocket">
|
||||
Deploy your crews to a managed infrastructure with a few clicks
|
||||
</Card>
|
||||
<Card title="API Access" icon="code">
|
||||
Access your deployed crews via REST API for integration with existing systems
|
||||
</Card>
|
||||
<Card title="Observability" icon="chart-line">
|
||||
Monitor your crews with detailed execution traces and logs
|
||||
</Card>
|
||||
<Card title="Tool Repository" icon="toolbox">
|
||||
Publish and install tools to enhance your crews' capabilities
|
||||
</Card>
|
||||
<Card title="Webhook Streaming" icon="webhook">
|
||||
Stream real-time events and updates to your systems
|
||||
</Card>
|
||||
<Card title="Crew Studio" icon="paintbrush">
|
||||
Create and customize crews using a no-code/low-code interface
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Deployment Options
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="GitHub Integration" icon="github">
|
||||
Connect directly to your GitHub repositories to deploy code
|
||||
</Card>
|
||||
<Card title="Crew Studio" icon="palette">
|
||||
Deploy crews created through the no-code Crew Studio interface
|
||||
</Card>
|
||||
<Card title="CLI Deployment" icon="terminal">
|
||||
Use the CrewAI CLI for more advanced deployment workflows
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Getting Started
|
||||
|
||||
<Steps>
|
||||
<Step title="Sign up for an account">
|
||||
Create your account at [app.crewai.com](https://app.crewai.com)
|
||||
<Card
|
||||
title="Sign Up"
|
||||
icon="user"
|
||||
href="https://app.crewai.com/signup"
|
||||
>
|
||||
Sign Up
|
||||
</Card>
|
||||
</Step>
|
||||
<Step title="Build your first crew">
|
||||
Use code or Crew Studio to build your crew
|
||||
<Card
|
||||
title="Build Crew"
|
||||
icon="paintbrush"
|
||||
href="/en/enterprise/guides/build-crew"
|
||||
>
|
||||
Build Crew
|
||||
</Card>
|
||||
</Step>
|
||||
<Step title="Deploy your crew">
|
||||
Deploy your crew to the Enterprise platform
|
||||
<Card
|
||||
title="Deploy Crew"
|
||||
icon="rocket"
|
||||
href="/en/enterprise/guides/deploy-crew"
|
||||
>
|
||||
Deploy Crew
|
||||
</Card>
|
||||
</Step>
|
||||
<Step title="Access your crew">
|
||||
Integrate with your crew via the generated API endpoints
|
||||
<Card
|
||||
title="API Access"
|
||||
icon="code"
|
||||
href="/en/enterprise/guides/kickoff-crew"
|
||||
>
|
||||
Use the Crew API
|
||||
</Card>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
For detailed instructions, check out our [deployment guide](/en/enterprise/guides/deploy-crew) or click the button below to get started.
|
||||
151
docs/en/enterprise/resources/frequently-asked-questions.mdx
Normal file
151
docs/en/enterprise/resources/frequently-asked-questions.mdx
Normal file
@@ -0,0 +1,151 @@
|
||||
---
|
||||
title: FAQs
|
||||
description: "Frequently asked questions about CrewAI Enterprise"
|
||||
icon: "circle-question"
|
||||
---
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="How is task execution handled in the hierarchical process?">
|
||||
In the hierarchical process, a manager agent is automatically created and coordinates the workflow, delegating tasks and validating outcomes for streamlined and effective execution. The manager agent utilizes tools to facilitate task delegation and execution by agents under the manager's guidance. The manager LLM is crucial for the hierarchical process and must be set up correctly for proper function.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Where can I get the latest CrewAI documentation?">
|
||||
The most up-to-date documentation for CrewAI is available on our official documentation website: https://docs.crewai.com/
|
||||
<Card href="https://docs.crewai.com/" icon="books">CrewAI Docs</Card>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What are the key differences between Hierarchical and Sequential Processes in CrewAI?">
|
||||
#### Hierarchical Process:
|
||||
- Tasks are delegated and executed based on a structured chain of command
|
||||
- A manager language model (`manager_llm`) must be specified for the manager agent
|
||||
- Manager agent oversees task execution, planning, delegation, and validation
|
||||
- Tasks are not pre-assigned; the manager allocates tasks to agents based on their capabilities
|
||||
|
||||
#### Sequential Process:
|
||||
- Tasks are executed one after another, ensuring tasks are completed in an orderly progression
|
||||
- Output of one task serves as context for the next
|
||||
- Task execution follows the predefined order in the task list
|
||||
|
||||
#### Which Process is Better for Complex Projects?
|
||||
The hierarchical process is better suited for complex projects because it allows for:
|
||||
- **Dynamic task allocation and delegation**: Manager agent can assign tasks based on agent capabilities
|
||||
- **Structured validation and oversight**: Manager agent reviews task outputs and ensures completion
|
||||
- **Complex task management**: Precise control over tool availability at the agent level
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What are the benefits of using memory in the CrewAI framework?">
|
||||
- **Adaptive Learning**: Crews become more efficient over time, adapting to new information and refining their approach to tasks
|
||||
- **Enhanced Personalization**: Memory enables agents to remember user preferences and historical interactions, leading to personalized experiences
|
||||
- **Improved Problem Solving**: Access to a rich memory store aids agents in making more informed decisions, drawing on past learnings and contextual insights
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What is the purpose of setting a maximum RPM limit for an agent?">
|
||||
Setting a maximum RPM limit for an agent prevents the agent from making too many requests to external services, which can help to avoid rate limits and improve performance.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What role does human input play in the execution of tasks within a CrewAI crew?">
|
||||
Human input allows agents to request additional information or clarification when necessary. This feature is crucial in complex decision-making processes or when agents require more details to complete a task effectively.
|
||||
|
||||
To integrate human input into agent execution, set the `human_input` flag in the task definition. When enabled, the agent prompts the user for input before delivering its final answer. This input can provide extra context, clarify ambiguities, or validate the agent's output.
|
||||
|
||||
For detailed implementation guidance, see our [Human-in-the-Loop guide](/en/how-to/human-in-the-loop).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What advanced customization options are available for tailoring and enhancing agent behavior and capabilities in CrewAI?">
|
||||
CrewAI provides a range of advanced customization options:
|
||||
|
||||
- **Language Model Customization**: Agents can be customized with specific language models (`llm`) and function-calling language models (`function_calling_llm`)
|
||||
- **Performance and Debugging Settings**: Adjust an agent's performance and monitor its operations
|
||||
- **Verbose Mode**: Enables detailed logging of an agent's actions, useful for debugging and optimization
|
||||
- **RPM Limit**: Sets the maximum number of requests per minute (`max_rpm`)
|
||||
- **Maximum Iterations**: The `max_iter` attribute allows users to define the maximum number of iterations an agent can perform for a single task
|
||||
- **Delegation and Autonomy**: Control an agent's ability to delegate or ask questions with the `allow_delegation` attribute (default: True)
|
||||
- **Human Input Integration**: Agents can request additional information or clarification when necessary
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="In what scenarios is human input particularly useful in agent execution?">
|
||||
Human input is particularly useful when:
|
||||
- **Agents require additional information or clarification**: When agents encounter ambiguity or incomplete data
|
||||
- **Agents need to make complex or sensitive decisions**: Human input can assist in ethical or nuanced decision-making
|
||||
- **Oversight and validation of agent output**: Human input can help validate results and prevent errors
|
||||
- **Customizing agent behavior**: Human input can provide feedback to refine agent responses over time
|
||||
- **Identifying and resolving errors or limitations**: Human input helps address agent capability gaps
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What are the different types of memory that are available in crewAI?">
|
||||
The different types of memory available in CrewAI are:
|
||||
- **Short-term memory**: Temporary storage for immediate context
|
||||
- **Long-term memory**: Persistent storage for learned patterns and information
|
||||
- **Entity memory**: Focused storage for specific entities and their attributes
|
||||
- **Contextual memory**: Memory that maintains context across interactions
|
||||
|
||||
Learn more about the different types of memory:
|
||||
<Card href="https://docs.crewai.com/concepts/memory" icon="brain">CrewAI Memory</Card>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="How do I use Output Pydantic in a Task?">
|
||||
To use Output Pydantic in a task, you need to define the expected output of the task as a Pydantic model. Here's a quick example:
|
||||
|
||||
<Steps>
|
||||
<Step title="Define a Pydantic model">
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
|
||||
class User(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a task with Output Pydantic">
|
||||
```python
|
||||
from crewai import Task, Crew, Agent
|
||||
from my_models import User
|
||||
|
||||
task = Task(
|
||||
description="Create a user with the provided name and age",
|
||||
expected_output=User, # This is the Pydantic model
|
||||
agent=agent,
|
||||
tools=[tool1, tool2]
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set the output_pydantic attribute in your agent">
|
||||
```python
|
||||
from crewai import Agent
|
||||
from my_models import User
|
||||
|
||||
agent = Agent(
|
||||
role='User Creator',
|
||||
goal='Create users',
|
||||
backstory='I am skilled in creating user accounts',
|
||||
tools=[tool1, tool2],
|
||||
output_pydantic=User
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
Here's a tutorial on how to consistently get structured outputs from your agents:
|
||||
<Frame>
|
||||
<iframe
|
||||
height="400"
|
||||
width="100%"
|
||||
src="https://www.youtube.com/embed/dNpKQk5uxHw"
|
||||
title="YouTube video player" frameborder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowfullscreen></iframe>
|
||||
</Frame>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="How can I create custom tools for my CrewAI agents?">
|
||||
You can create custom tools by subclassing the `BaseTool` class provided by CrewAI or by using the tool decorator. Subclassing involves defining a new class that inherits from `BaseTool`, specifying the name, description, and the `_run` method for operational logic. The tool decorator allows you to create a `Tool` object directly with the required attributes and a functional logic.
|
||||
|
||||
<Card href="https://docs.crewai.com/how-to/create-custom-tools" icon="code">CrewAI Tools Guide</Card>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="How can you control the maximum number of requests per minute that the entire crew can perform?">
|
||||
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.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
316
docs/en/guides/advanced/customizing-prompts.mdx
Normal file
316
docs/en/guides/advanced/customizing-prompts.mdx
Normal file
@@ -0,0 +1,316 @@
|
||||
---
|
||||
title: Customizing Prompts
|
||||
description: Dive deeper into low-level prompt customization for CrewAI, enabling super custom and complex use cases for different models and languages.
|
||||
icon: message-pen
|
||||
---
|
||||
|
||||
## Why Customize Prompts?
|
||||
|
||||
Although CrewAI's default prompts work well for many scenarios, low-level customization opens the door to significantly more flexible and powerful agent behavior. Here's why you might want to take advantage of this deeper control:
|
||||
|
||||
1. **Optimize for specific LLMs** – Different models (such as GPT-4, Claude, or Llama) thrive with prompt formats tailored to their unique architectures.
|
||||
2. **Change the language** – Build agents that operate exclusively in languages beyond English, handling nuances with precision.
|
||||
3. **Specialize for complex domains** – Adapt prompts for highly specialized industries like healthcare, finance, or legal.
|
||||
4. **Adjust tone and style** – Make agents more formal, casual, creative, or analytical.
|
||||
5. **Support super custom use cases** – Utilize advanced prompt structures and formatting to meet intricate, project-specific requirements.
|
||||
|
||||
This guide explores how to tap into CrewAI's prompts at a lower level, giving you fine-grained control over how agents think and interact.
|
||||
|
||||
## Understanding CrewAI's Prompt System
|
||||
|
||||
Under the hood, CrewAI employs a modular prompt system that you can customize extensively:
|
||||
|
||||
- **Agent templates** – Govern each agent's approach to their assigned role.
|
||||
- **Prompt slices** – Control specialized behaviors such as tasks, tool usage, and output structure.
|
||||
- **Error handling** – Direct how agents respond to failures, exceptions, or timeouts.
|
||||
- **Tool-specific prompts** – Define detailed instructions for how tools are invoked or utilized.
|
||||
|
||||
Check out the [original prompt templates in CrewAI's repository](https://github.com/crewAIInc/crewAI/blob/main/src/crewai/translations/en.json) to see how these elements are organized. From there, you can override or adapt them as needed to unlock advanced behaviors.
|
||||
|
||||
## Understanding Default System Instructions
|
||||
|
||||
<Warning>
|
||||
**Production Transparency Issue**: CrewAI automatically injects default instructions into your prompts that you might not be aware of. This section explains what's happening under the hood and how to gain full control.
|
||||
</Warning>
|
||||
|
||||
When you define an agent with `role`, `goal`, and `backstory`, CrewAI automatically adds additional system instructions that control formatting and behavior. Understanding these default injections is crucial for production systems where you need full prompt transparency.
|
||||
|
||||
### What CrewAI Automatically Injects
|
||||
|
||||
Based on your agent configuration, CrewAI adds different default instructions:
|
||||
|
||||
#### For Agents Without Tools
|
||||
```text
|
||||
"I MUST use these formats, my job depends on it!"
|
||||
```
|
||||
|
||||
#### For Agents With Tools
|
||||
```text
|
||||
"IMPORTANT: Use the following format in your response:
|
||||
|
||||
Thought: you should always think about what to do
|
||||
Action: the action to take, only one name of [tool_names]
|
||||
Action Input: the input to the action, just a simple JSON object...
|
||||
```
|
||||
|
||||
#### For Structured Outputs (JSON/Pydantic)
|
||||
```text
|
||||
"Ensure your final answer contains only the content in the following format: {output_format}
|
||||
Ensure the final output does not include any code block markers like ```json or ```python."
|
||||
```
|
||||
|
||||
### Viewing the Complete System Prompt
|
||||
|
||||
To see exactly what prompt is being sent to your LLM, you can inspect the generated prompt:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.utilities.prompts import Prompts
|
||||
|
||||
# Create your agent
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze data and provide insights",
|
||||
backstory="You are an expert data analyst with 10 years of experience.",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create a sample task
|
||||
task = Task(
|
||||
description="Analyze the sales data and identify trends",
|
||||
expected_output="A detailed analysis with key insights and trends",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Create the prompt generator
|
||||
prompt_generator = Prompts(
|
||||
agent=agent,
|
||||
has_tools=len(agent.tools) > 0,
|
||||
use_system_prompt=agent.use_system_prompt
|
||||
)
|
||||
|
||||
# Generate and inspect the actual prompt
|
||||
generated_prompt = prompt_generator.task_execution()
|
||||
|
||||
# Print the complete system prompt that will be sent to the LLM
|
||||
if "system" in generated_prompt:
|
||||
print("=== SYSTEM PROMPT ===")
|
||||
print(generated_prompt["system"])
|
||||
print("\n=== USER PROMPT ===")
|
||||
print(generated_prompt["user"])
|
||||
else:
|
||||
print("=== COMPLETE PROMPT ===")
|
||||
print(generated_prompt["prompt"])
|
||||
|
||||
# You can also see how the task description gets formatted
|
||||
print("\n=== TASK CONTEXT ===")
|
||||
print(f"Task Description: {task.description}")
|
||||
print(f"Expected Output: {task.expected_output}")
|
||||
```
|
||||
|
||||
### Overriding Default Instructions
|
||||
|
||||
You have several options to gain full control over the prompts:
|
||||
|
||||
#### Option 1: Custom Templates (Recommended)
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
# Define your own system template without default instructions
|
||||
custom_system_template = """You are {role}. {backstory}
|
||||
Your goal is: {goal}
|
||||
|
||||
Respond naturally and conversationally. Focus on providing helpful, accurate information."""
|
||||
|
||||
custom_prompt_template = """Task: {input}
|
||||
|
||||
Please complete this task thoughtfully."""
|
||||
|
||||
agent = Agent(
|
||||
role="Research Assistant",
|
||||
goal="Help users find accurate information",
|
||||
backstory="You are a helpful research assistant.",
|
||||
system_template=custom_system_template,
|
||||
prompt_template=custom_prompt_template,
|
||||
use_system_prompt=True # Use separate system/user messages
|
||||
)
|
||||
```
|
||||
|
||||
#### Option 2: Custom Prompt File
|
||||
Create a `custom_prompts.json` file to override specific prompt slices:
|
||||
|
||||
```json
|
||||
{
|
||||
"slices": {
|
||||
"no_tools": "\nProvide your best answer in a natural, conversational way.",
|
||||
"tools": "\nYou have access to these tools: {tools}\n\nUse them when helpful, but respond naturally.",
|
||||
"formatted_task_instructions": "Format your response as: {output_format}"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then use it in your crew:
|
||||
|
||||
```python
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
prompt_file="custom_prompts.json",
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
#### Option 3: Disable System Prompts for o1 Models
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Analyst",
|
||||
goal="Analyze data",
|
||||
backstory="Expert analyst",
|
||||
use_system_prompt=False # Disables system prompt separation
|
||||
)
|
||||
```
|
||||
|
||||
### Debugging with Observability Tools
|
||||
|
||||
For production transparency, integrate with observability platforms to monitor all prompts and LLM interactions. This allows you to see exactly what prompts (including default instructions) are being sent to your LLMs.
|
||||
|
||||
See our [Observability documentation](/en/observability/overview) for detailed integration guides with various platforms including Langfuse, MLflow, Weights & Biases, and custom logging solutions.
|
||||
|
||||
### Best Practices for Production
|
||||
|
||||
1. **Always inspect generated prompts** before deploying to production
|
||||
2. **Use custom templates** when you need full control over prompt content
|
||||
3. **Integrate observability tools** for ongoing prompt monitoring (see [Observability docs](/en/observability/overview))
|
||||
4. **Test with different LLMs** as default instructions may work differently across models
|
||||
5. **Document your prompt customizations** for team transparency
|
||||
|
||||
<Tip>
|
||||
The default instructions exist to ensure consistent agent behavior, but they can interfere with domain-specific requirements. Use the customization options above to maintain full control over your agent's behavior in production systems.
|
||||
</Tip>
|
||||
|
||||
## Best Practices for Managing Prompt Files
|
||||
|
||||
When engaging in low-level prompt customization, follow these guidelines to keep things organized and maintainable:
|
||||
|
||||
1. **Keep files separate** – Store your customized prompts in dedicated JSON files outside your main codebase.
|
||||
2. **Version control** – Track changes within your repository, ensuring clear documentation of prompt adjustments over time.
|
||||
3. **Organize by model or language** – Use naming schemes like `prompts_llama.json` or `prompts_es.json` to quickly identify specialized configurations.
|
||||
4. **Document changes** – Provide comments or maintain a README detailing the purpose and scope of your customizations.
|
||||
5. **Minimize alterations** – Only override the specific slices you genuinely need to adjust, keeping default functionality intact for everything else.
|
||||
|
||||
## The Simplest Way to Customize Prompts
|
||||
|
||||
One straightforward approach is to create a JSON file for the prompts you want to override and then point your Crew at that file:
|
||||
|
||||
1. Craft a JSON file with your updated prompt slices.
|
||||
2. Reference that file via the `prompt_file` parameter in your Crew.
|
||||
|
||||
CrewAI then merges your customizations with the defaults, so you don't have to redefine every prompt. Here's how:
|
||||
|
||||
### Example: Basic Prompt Customization
|
||||
|
||||
Create a `custom_prompts.json` file with the prompts you want to modify. Ensure you list all top-level prompts it should contain, not just your changes:
|
||||
|
||||
```json
|
||||
{
|
||||
"slices": {
|
||||
"format": "When responding, follow this structure:\n\nTHOUGHTS: Your step-by-step thinking\nACTION: Any tool you're using\nRESULT: Your final answer or conclusion"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then integrate it like so:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task, Process
|
||||
|
||||
# Create agents and tasks as normal
|
||||
researcher = Agent(
|
||||
role="Research Specialist",
|
||||
goal="Find information on quantum computing",
|
||||
backstory="You are a quantum physics expert",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
research_task = Task(
|
||||
description="Research quantum computing applications",
|
||||
expected_output="A summary of practical applications",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Create a crew with your custom prompt file
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[research_task],
|
||||
prompt_file="path/to/custom_prompts.json",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run the crew
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
With these few edits, you gain low-level control over how your agents communicate and solve tasks.
|
||||
|
||||
## Optimizing for Specific Models
|
||||
|
||||
Different models thrive on differently structured prompts. Making deeper adjustments can significantly boost performance by aligning your prompts with a model's nuances.
|
||||
|
||||
### Example: Llama 3.3 Prompting Template
|
||||
|
||||
For instance, when dealing with Meta's Llama 3.3, deeper-level customization may reflect the recommended structure described at:
|
||||
https://www.llama.com/docs/model-cards-and-prompt-formats/llama3_1/#prompt-template
|
||||
|
||||
Here's an example to highlight how you might fine-tune an Agent to leverage Llama 3.3 in code:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task, Process
|
||||
from crewai_tools import DirectoryReadTool, FileReadTool
|
||||
|
||||
# Define templates for system, user (prompt), and assistant (response) messages
|
||||
system_template = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>{{ .System }}<|eot_id|>"""
|
||||
prompt_template = """<|start_header_id|>user<|end_header_id|>{{ .Prompt }}<|eot_id|>"""
|
||||
response_template = """<|start_header_id|>assistant<|end_header_id|>{{ .Response }}<|eot_id|>"""
|
||||
|
||||
# Create an Agent using Llama-specific layouts
|
||||
principal_engineer = Agent(
|
||||
role="Principal Engineer",
|
||||
goal="Oversee AI architecture and make high-level decisions",
|
||||
backstory="You are the lead engineer responsible for critical AI systems",
|
||||
verbose=True,
|
||||
llm="groq/llama-3.3-70b-versatile", # Using the Llama 3 model
|
||||
system_template=system_template,
|
||||
prompt_template=prompt_template,
|
||||
response_template=response_template,
|
||||
tools=[DirectoryReadTool(), FileReadTool()]
|
||||
)
|
||||
|
||||
# Define a sample task
|
||||
engineering_task = Task(
|
||||
description="Review AI implementation files for potential improvements",
|
||||
expected_output="A summary of key findings and recommendations",
|
||||
agent=principal_engineer
|
||||
)
|
||||
|
||||
# Create a Crew for the task
|
||||
llama_crew = Crew(
|
||||
agents=[principal_engineer],
|
||||
tasks=[engineering_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Execute the crew
|
||||
result = llama_crew.kickoff()
|
||||
print(result.raw)
|
||||
```
|
||||
|
||||
Through this deeper configuration, you can exercise comprehensive, low-level control over your Llama-based workflows without needing a separate JSON file.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Low-level prompt customization in CrewAI opens the door to super custom, complex use cases. By establishing well-organized prompt files (or direct inline templates), you can accommodate various models, languages, and specialized domains. This level of flexibility ensures you can craft precisely the AI behavior you need, all while knowing CrewAI still provides reliable defaults when you don't override them.
|
||||
|
||||
<Check>
|
||||
You now have the foundation for advanced prompt customizations in CrewAI. Whether you're adapting for model-specific structures or domain-specific constraints, this low-level approach lets you shape agent interactions in highly specialized ways.
|
||||
</Check>
|
||||
133
docs/en/guides/advanced/fingerprinting.mdx
Normal file
133
docs/en/guides/advanced/fingerprinting.mdx
Normal file
@@ -0,0 +1,133 @@
|
||||
---
|
||||
title: Fingerprinting
|
||||
description: Learn how to use CrewAI's fingerprinting system to uniquely identify and track components throughout their lifecycle.
|
||||
icon: fingerprint
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Fingerprints in CrewAI provide a way to uniquely identify and track components throughout their lifecycle. Each `Agent`, `Crew`, and `Task` automatically receives a unique fingerprint when created, which cannot be manually overridden.
|
||||
|
||||
These fingerprints can be used for:
|
||||
- Auditing and tracking component usage
|
||||
- Ensuring component identity integrity
|
||||
- Attaching metadata to components
|
||||
- Creating a traceable chain of operations
|
||||
|
||||
## How Fingerprints Work
|
||||
|
||||
A fingerprint is an instance of the `Fingerprint` class from the `crewai.security` module. Each fingerprint contains:
|
||||
|
||||
- A UUID string: A unique identifier for the component that is automatically generated and cannot be manually set
|
||||
- A creation timestamp: When the fingerprint was generated, automatically set and cannot be manually modified
|
||||
- Metadata: A dictionary of additional information that can be customized
|
||||
|
||||
Fingerprints are automatically generated and assigned when a component is created. Each component exposes its fingerprint through a read-only property.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Accessing Fingerprints
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task
|
||||
|
||||
# Create components - fingerprints are automatically generated
|
||||
agent = Agent(
|
||||
role="Data Scientist",
|
||||
goal="Analyze data",
|
||||
backstory="Expert in data analysis"
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[]
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Analyze customer data",
|
||||
expected_output="Insights from data analysis",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Access the fingerprints
|
||||
agent_fingerprint = agent.fingerprint
|
||||
crew_fingerprint = crew.fingerprint
|
||||
task_fingerprint = task.fingerprint
|
||||
|
||||
# Print the UUID strings
|
||||
print(f"Agent fingerprint: {agent_fingerprint.uuid_str}")
|
||||
print(f"Crew fingerprint: {crew_fingerprint.uuid_str}")
|
||||
print(f"Task fingerprint: {task_fingerprint.uuid_str}")
|
||||
```
|
||||
|
||||
### Working with Fingerprint Metadata
|
||||
|
||||
You can add metadata to fingerprints for additional context:
|
||||
|
||||
```python
|
||||
# Add metadata to the agent's fingerprint
|
||||
agent.security_config.fingerprint.metadata = {
|
||||
"version": "1.0",
|
||||
"department": "Data Science",
|
||||
"project": "Customer Analysis"
|
||||
}
|
||||
|
||||
# Access the metadata
|
||||
print(f"Agent metadata: {agent.fingerprint.metadata}")
|
||||
```
|
||||
|
||||
## Fingerprint Persistence
|
||||
|
||||
Fingerprints are designed to persist and remain unchanged throughout a component's lifecycle. If you modify a component, the fingerprint remains the same:
|
||||
|
||||
```python
|
||||
original_fingerprint = agent.fingerprint.uuid_str
|
||||
|
||||
# Modify the agent
|
||||
agent.goal = "New goal for analysis"
|
||||
|
||||
# The fingerprint remains unchanged
|
||||
assert agent.fingerprint.uuid_str == original_fingerprint
|
||||
```
|
||||
|
||||
## Deterministic Fingerprints
|
||||
|
||||
While you cannot directly set the UUID and creation timestamp, you can create deterministic fingerprints using the `generate` method with a seed:
|
||||
|
||||
```python
|
||||
from crewai.security import Fingerprint
|
||||
|
||||
# Create a deterministic fingerprint using a seed string
|
||||
deterministic_fingerprint = Fingerprint.generate(seed="my-agent-id")
|
||||
|
||||
# The same seed always produces the same fingerprint
|
||||
same_fingerprint = Fingerprint.generate(seed="my-agent-id")
|
||||
assert deterministic_fingerprint.uuid_str == same_fingerprint.uuid_str
|
||||
|
||||
# You can also set metadata
|
||||
custom_fingerprint = Fingerprint.generate(
|
||||
seed="my-agent-id",
|
||||
metadata={"version": "1.0"}
|
||||
)
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Fingerprint Structure
|
||||
|
||||
Each fingerprint has the following structure:
|
||||
|
||||
```python
|
||||
from crewai.security import Fingerprint
|
||||
|
||||
fingerprint = agent.fingerprint
|
||||
|
||||
# UUID string - the unique identifier (auto-generated)
|
||||
uuid_str = fingerprint.uuid_str # e.g., "123e4567-e89b-12d3-a456-426614174000"
|
||||
|
||||
# Creation timestamp (auto-generated)
|
||||
created_at = fingerprint.created_at # A datetime object
|
||||
|
||||
# Metadata - for additional information (can be customized)
|
||||
metadata = fingerprint.metadata # A dictionary, defaults to {}
|
||||
```
|
||||
452
docs/en/guides/agents/crafting-effective-agents.mdx
Normal file
452
docs/en/guides/agents/crafting-effective-agents.mdx
Normal file
@@ -0,0 +1,452 @@
|
||||
---
|
||||
title: Crafting Effective Agents
|
||||
description: Learn best practices for designing powerful, specialized AI agents that collaborate effectively to solve complex problems.
|
||||
icon: robot
|
||||
---
|
||||
|
||||
## The Art and Science of Agent Design
|
||||
|
||||
At the heart of CrewAI lies the agent - a specialized AI entity designed to perform specific roles within a collaborative framework. While creating basic agents is simple, crafting truly effective agents that produce exceptional results requires understanding key design principles and best practices.
|
||||
|
||||
This guide will help you master the art of agent design, enabling you to create specialized AI personas that collaborate effectively, think critically, and produce high-quality outputs tailored to your specific needs.
|
||||
|
||||
### Why Agent Design Matters
|
||||
|
||||
The way you define your agents significantly impacts:
|
||||
|
||||
1. **Output quality**: Well-designed agents produce more relevant, high-quality results
|
||||
2. **Collaboration effectiveness**: Agents with complementary skills work together more efficiently
|
||||
3. **Task performance**: Agents with clear roles and goals execute tasks more effectively
|
||||
4. **System scalability**: Thoughtfully designed agents can be reused across multiple crews and contexts
|
||||
|
||||
Let's explore best practices for creating agents that excel in these dimensions.
|
||||
|
||||
## The 80/20 Rule: Focus on Tasks Over Agents
|
||||
|
||||
When building effective AI systems, remember this crucial principle: **80% of your effort should go into designing tasks, and only 20% into defining agents**.
|
||||
|
||||
Why? Because even the most perfectly defined agent will fail with poorly designed tasks, but well-designed tasks can elevate even a simple agent. This means:
|
||||
|
||||
- Spend most of your time writing clear task instructions
|
||||
- Define detailed inputs and expected outputs
|
||||
- Add examples and context to guide execution
|
||||
- Dedicate the remaining time to agent role, goal, and backstory
|
||||
|
||||
This doesn't mean agent design isn't important - it absolutely is. But task design is where most execution failures occur, so prioritize accordingly.
|
||||
|
||||
## Core Principles of Effective Agent Design
|
||||
|
||||
### 1. The Role-Goal-Backstory Framework
|
||||
|
||||
The most powerful agents in CrewAI are built on a strong foundation of three key elements:
|
||||
|
||||
#### Role: The Agent's Specialized Function
|
||||
|
||||
The role defines what the agent does and their area of expertise. When crafting roles:
|
||||
|
||||
- **Be specific and specialized**: Instead of "Writer," use "Technical Documentation Specialist" or "Creative Storyteller"
|
||||
- **Align with real-world professions**: Base roles on recognizable professional archetypes
|
||||
- **Include domain expertise**: Specify the agent's field of knowledge (e.g., "Financial Analyst specializing in market trends")
|
||||
|
||||
**Examples of effective roles:**
|
||||
```yaml
|
||||
role: "Senior UX Researcher specializing in user interview analysis"
|
||||
role: "Full-Stack Software Architect with expertise in distributed systems"
|
||||
role: "Corporate Communications Director specializing in crisis management"
|
||||
```
|
||||
|
||||
#### Goal: The Agent's Purpose and Motivation
|
||||
|
||||
The goal directs the agent's efforts and shapes their decision-making process. Effective goals should:
|
||||
|
||||
- **Be clear and outcome-focused**: Define what the agent is trying to achieve
|
||||
- **Emphasize quality standards**: Include expectations about the quality of work
|
||||
- **Incorporate success criteria**: Help the agent understand what "good" looks like
|
||||
|
||||
**Examples of effective goals:**
|
||||
```yaml
|
||||
goal: "Uncover actionable user insights by analyzing interview data and identifying recurring patterns, unmet needs, and improvement opportunities"
|
||||
goal: "Design robust, scalable system architectures that balance performance, maintainability, and cost-effectiveness"
|
||||
goal: "Craft clear, empathetic crisis communications that address stakeholder concerns while protecting organizational reputation"
|
||||
```
|
||||
|
||||
#### Backstory: The Agent's Experience and Perspective
|
||||
|
||||
The backstory gives depth to the agent, influencing how they approach problems and interact with others. Good backstories:
|
||||
|
||||
- **Establish expertise and experience**: Explain how the agent gained their skills
|
||||
- **Define working style and values**: Describe how the agent approaches their work
|
||||
- **Create a cohesive persona**: Ensure all elements of the backstory align with the role and goal
|
||||
|
||||
**Examples of effective backstories:**
|
||||
```yaml
|
||||
backstory: "You have spent 15 years conducting and analyzing user research for top tech companies. You have a talent for reading between the lines and identifying patterns that others miss. You believe that good UX is invisible and that the best insights come from listening to what users don't say as much as what they do say."
|
||||
|
||||
backstory: "With 20+ years of experience building distributed systems at scale, you've developed a pragmatic approach to software architecture. You've seen both successful and failed systems and have learned valuable lessons from each. You balance theoretical best practices with practical constraints and always consider the maintenance and operational aspects of your designs."
|
||||
|
||||
backstory: "As a seasoned communications professional who has guided multiple organizations through high-profile crises, you understand the importance of transparency, speed, and empathy in crisis response. You have a methodical approach to crafting messages that address concerns while maintaining organizational credibility."
|
||||
```
|
||||
|
||||
### 2. Specialists Over Generalists
|
||||
|
||||
Agents perform significantly better when given specialized roles rather than general ones. A highly focused agent delivers more precise, relevant outputs:
|
||||
|
||||
**Generic (Less Effective):**
|
||||
```yaml
|
||||
role: "Writer"
|
||||
```
|
||||
|
||||
**Specialized (More Effective):**
|
||||
```yaml
|
||||
role: "Technical Blog Writer specializing in explaining complex AI concepts to non-technical audiences"
|
||||
```
|
||||
|
||||
**Specialist Benefits:**
|
||||
- Clearer understanding of expected output
|
||||
- More consistent performance
|
||||
- Better alignment with specific tasks
|
||||
- Improved ability to make domain-specific judgments
|
||||
|
||||
### 3. Balancing Specialization and Versatility
|
||||
|
||||
Effective agents strike the right balance between specialization (doing one thing extremely well) and versatility (being adaptable to various situations):
|
||||
|
||||
- **Specialize in role, versatile in application**: Create agents with specialized skills that can be applied across multiple contexts
|
||||
- **Avoid overly narrow definitions**: Ensure agents can handle variations within their domain of expertise
|
||||
- **Consider the collaborative context**: Design agents whose specializations complement the other agents they'll work with
|
||||
|
||||
### 4. Setting Appropriate Expertise Levels
|
||||
|
||||
The expertise level you assign to your agent shapes how they approach tasks:
|
||||
|
||||
- **Novice agents**: Good for straightforward tasks, brainstorming, or initial drafts
|
||||
- **Intermediate agents**: Suitable for most standard tasks with reliable execution
|
||||
- **Expert agents**: Best for complex, specialized tasks requiring depth and nuance
|
||||
- **World-class agents**: Reserved for critical tasks where exceptional quality is needed
|
||||
|
||||
Choose the appropriate expertise level based on task complexity and quality requirements. For most collaborative crews, a mix of expertise levels often works best, with higher expertise assigned to core specialized functions.
|
||||
|
||||
## Practical Examples: Before and After
|
||||
|
||||
Let's look at some examples of agent definitions before and after applying these best practices:
|
||||
|
||||
### Example 1: Content Creation Agent
|
||||
|
||||
**Before:**
|
||||
```yaml
|
||||
role: "Writer"
|
||||
goal: "Write good content"
|
||||
backstory: "You are a writer who creates content for websites."
|
||||
```
|
||||
|
||||
**After:**
|
||||
```yaml
|
||||
role: "B2B Technology Content Strategist"
|
||||
goal: "Create compelling, technically accurate content that explains complex topics in accessible language while driving reader engagement and supporting business objectives"
|
||||
backstory: "You have spent a decade creating content for leading technology companies, specializing in translating technical concepts for business audiences. You excel at research, interviewing subject matter experts, and structuring information for maximum clarity and impact. You believe that the best B2B content educates first and sells second, building trust through genuine expertise rather than marketing hype."
|
||||
```
|
||||
|
||||
### Example 2: Research Agent
|
||||
|
||||
**Before:**
|
||||
```yaml
|
||||
role: "Researcher"
|
||||
goal: "Find information"
|
||||
backstory: "You are good at finding information online."
|
||||
```
|
||||
|
||||
**After:**
|
||||
```yaml
|
||||
role: "Academic Research Specialist in Emerging Technologies"
|
||||
goal: "Discover and synthesize cutting-edge research, identifying key trends, methodologies, and findings while evaluating the quality and reliability of sources"
|
||||
backstory: "With a background in both computer science and library science, you've mastered the art of digital research. You've worked with research teams at prestigious universities and know how to navigate academic databases, evaluate research quality, and synthesize findings across disciplines. You're methodical in your approach, always cross-referencing information and tracing claims to primary sources before drawing conclusions."
|
||||
```
|
||||
|
||||
## Crafting Effective Tasks for Your Agents
|
||||
|
||||
While agent design is important, task design is critical for successful execution. Here are best practices for designing tasks that set your agents up for success:
|
||||
|
||||
### The Anatomy of an Effective Task
|
||||
|
||||
A well-designed task has two key components that serve different purposes:
|
||||
|
||||
#### Task Description: The Process
|
||||
The description should focus on what to do and how to do it, including:
|
||||
- Detailed instructions for execution
|
||||
- Context and background information
|
||||
- Scope and constraints
|
||||
- Process steps to follow
|
||||
|
||||
#### Expected Output: The Deliverable
|
||||
The expected output should define what the final result should look like:
|
||||
- Format specifications (markdown, JSON, etc.)
|
||||
- Structure requirements
|
||||
- Quality criteria
|
||||
- Examples of good outputs (when possible)
|
||||
|
||||
### Task Design Best Practices
|
||||
|
||||
#### 1. Single Purpose, Single Output
|
||||
Tasks perform best when focused on one clear objective:
|
||||
|
||||
**Bad Example (Too Broad):**
|
||||
```yaml
|
||||
task_description: "Research market trends, analyze the data, and create a visualization."
|
||||
```
|
||||
|
||||
**Good Example (Focused):**
|
||||
```yaml
|
||||
# Task 1
|
||||
research_task:
|
||||
description: "Research the top 5 market trends in the AI industry for 2024."
|
||||
expected_output: "A markdown list of the 5 trends with supporting evidence."
|
||||
|
||||
# Task 2
|
||||
analysis_task:
|
||||
description: "Analyze the identified trends to determine potential business impacts."
|
||||
expected_output: "A structured analysis with impact ratings (High/Medium/Low)."
|
||||
|
||||
# Task 3
|
||||
visualization_task:
|
||||
description: "Create a visual representation of the analyzed trends."
|
||||
expected_output: "A description of a chart showing trends and their impact ratings."
|
||||
```
|
||||
|
||||
#### 2. Be Explicit About Inputs and Outputs
|
||||
Always clearly specify what inputs the task will use and what the output should look like:
|
||||
|
||||
**Example:**
|
||||
```yaml
|
||||
analysis_task:
|
||||
description: >
|
||||
Analyze the customer feedback data from the CSV file.
|
||||
Focus on identifying recurring themes related to product usability.
|
||||
Consider sentiment and frequency when determining importance.
|
||||
expected_output: >
|
||||
A markdown report with the following sections:
|
||||
1. Executive summary (3-5 bullet points)
|
||||
2. Top 3 usability issues with supporting data
|
||||
3. Recommendations for improvement
|
||||
```
|
||||
|
||||
#### 3. Include Purpose and Context
|
||||
Explain why the task matters and how it fits into the larger workflow:
|
||||
|
||||
**Example:**
|
||||
```yaml
|
||||
competitor_analysis_task:
|
||||
description: >
|
||||
Analyze our three main competitors' pricing strategies.
|
||||
This analysis will inform our upcoming pricing model revision.
|
||||
Focus on identifying patterns in how they price premium features
|
||||
and how they structure their tiered offerings.
|
||||
```
|
||||
|
||||
#### 4. Use Structured Output Tools
|
||||
For machine-readable outputs, specify the format clearly:
|
||||
|
||||
**Example:**
|
||||
```yaml
|
||||
data_extraction_task:
|
||||
description: "Extract key metrics from the quarterly report."
|
||||
expected_output: "JSON object with the following keys: revenue, growth_rate, customer_acquisition_cost, and retention_rate."
|
||||
```
|
||||
|
||||
## Common Mistakes to Avoid
|
||||
|
||||
Based on lessons learned from real-world implementations, here are the most common pitfalls in agent and task design:
|
||||
|
||||
### 1. Unclear Task Instructions
|
||||
|
||||
**Problem:** Tasks lack sufficient detail, making it difficult for agents to execute effectively.
|
||||
|
||||
**Example of Poor Design:**
|
||||
```yaml
|
||||
research_task:
|
||||
description: "Research AI trends."
|
||||
expected_output: "A report on AI trends."
|
||||
```
|
||||
|
||||
**Improved Version:**
|
||||
```yaml
|
||||
research_task:
|
||||
description: >
|
||||
Research the top emerging AI trends for 2024 with a focus on:
|
||||
1. Enterprise adoption patterns
|
||||
2. Technical breakthroughs in the past 6 months
|
||||
3. Regulatory developments affecting implementation
|
||||
|
||||
For each trend, identify key companies, technologies, and potential business impacts.
|
||||
expected_output: >
|
||||
A comprehensive markdown report with:
|
||||
- Executive summary (5 bullet points)
|
||||
- 5-7 major trends with supporting evidence
|
||||
- For each trend: definition, examples, and business implications
|
||||
- References to authoritative sources
|
||||
```
|
||||
|
||||
### 2. "God Tasks" That Try to Do Too Much
|
||||
|
||||
**Problem:** Tasks that combine multiple complex operations into one instruction set.
|
||||
|
||||
**Example of Poor Design:**
|
||||
```yaml
|
||||
comprehensive_task:
|
||||
description: "Research market trends, analyze competitor strategies, create a marketing plan, and design a launch timeline."
|
||||
```
|
||||
|
||||
**Improved Version:**
|
||||
Break this into sequential, focused tasks:
|
||||
```yaml
|
||||
# Task 1: Research
|
||||
market_research_task:
|
||||
description: "Research current market trends in the SaaS project management space."
|
||||
expected_output: "A markdown summary of key market trends."
|
||||
|
||||
# Task 2: Competitive Analysis
|
||||
competitor_analysis_task:
|
||||
description: "Analyze strategies of the top 3 competitors based on the market research."
|
||||
expected_output: "A comparison table of competitor strategies."
|
||||
context: [market_research_task]
|
||||
|
||||
# Continue with additional focused tasks...
|
||||
```
|
||||
|
||||
### 3. Misaligned Description and Expected Output
|
||||
|
||||
**Problem:** The task description asks for one thing while the expected output specifies something different.
|
||||
|
||||
**Example of Poor Design:**
|
||||
```yaml
|
||||
analysis_task:
|
||||
description: "Analyze customer feedback to find areas of improvement."
|
||||
expected_output: "A marketing plan for the next quarter."
|
||||
```
|
||||
|
||||
**Improved Version:**
|
||||
```yaml
|
||||
analysis_task:
|
||||
description: "Analyze customer feedback to identify the top 3 areas for product improvement."
|
||||
expected_output: "A report listing the 3 priority improvement areas with supporting customer quotes and data points."
|
||||
```
|
||||
|
||||
### 4. Not Understanding the Process Yourself
|
||||
|
||||
**Problem:** Asking agents to execute tasks that you yourself don't fully understand.
|
||||
|
||||
**Solution:**
|
||||
1. Try to perform the task manually first
|
||||
2. Document your process, decision points, and information sources
|
||||
3. Use this documentation as the basis for your task description
|
||||
|
||||
### 5. Premature Use of Hierarchical Structures
|
||||
|
||||
**Problem:** Creating unnecessarily complex agent hierarchies where sequential processes would work better.
|
||||
|
||||
**Solution:** Start with sequential processes and only move to hierarchical models when the workflow complexity truly requires it.
|
||||
|
||||
### 6. Vague or Generic Agent Definitions
|
||||
|
||||
**Problem:** Generic agent definitions lead to generic outputs.
|
||||
|
||||
**Example of Poor Design:**
|
||||
```yaml
|
||||
agent:
|
||||
role: "Business Analyst"
|
||||
goal: "Analyze business data"
|
||||
backstory: "You are good at business analysis."
|
||||
```
|
||||
|
||||
**Improved Version:**
|
||||
```yaml
|
||||
agent:
|
||||
role: "SaaS Metrics Specialist focusing on growth-stage startups"
|
||||
goal: "Identify actionable insights from business data that can directly impact customer retention and revenue growth"
|
||||
backstory: "With 10+ years analyzing SaaS business models, you've developed a keen eye for the metrics that truly matter for sustainable growth. You've helped numerous companies identify the leverage points that turned around their business trajectory. You believe in connecting data to specific, actionable recommendations rather than general observations."
|
||||
```
|
||||
|
||||
## Advanced Agent Design Strategies
|
||||
|
||||
### Designing for Collaboration
|
||||
|
||||
When creating agents that will work together in a crew, consider:
|
||||
|
||||
- **Complementary skills**: Design agents with distinct but complementary abilities
|
||||
- **Handoff points**: Define clear interfaces for how work passes between agents
|
||||
- **Constructive tension**: Sometimes, creating agents with slightly different perspectives can lead to better outcomes through productive dialogue
|
||||
|
||||
For example, a content creation crew might include:
|
||||
|
||||
```yaml
|
||||
# Research Agent
|
||||
role: "Research Specialist for technical topics"
|
||||
goal: "Gather comprehensive, accurate information from authoritative sources"
|
||||
backstory: "You are a meticulous researcher with a background in library science..."
|
||||
|
||||
# Writer Agent
|
||||
role: "Technical Content Writer"
|
||||
goal: "Transform research into engaging, clear content that educates and informs"
|
||||
backstory: "You are an experienced writer who excels at explaining complex concepts..."
|
||||
|
||||
# Editor Agent
|
||||
role: "Content Quality Editor"
|
||||
goal: "Ensure content is accurate, well-structured, and polished while maintaining consistency"
|
||||
backstory: "With years of experience in publishing, you have a keen eye for detail..."
|
||||
```
|
||||
|
||||
### Creating Specialized Tool Users
|
||||
|
||||
Some agents can be designed specifically to leverage certain tools effectively:
|
||||
|
||||
```yaml
|
||||
role: "Data Analysis Specialist"
|
||||
goal: "Derive meaningful insights from complex datasets through statistical analysis"
|
||||
backstory: "With a background in data science, you excel at working with structured and unstructured data..."
|
||||
tools: [PythonREPLTool, DataVisualizationTool, CSVAnalysisTool]
|
||||
```
|
||||
|
||||
### Tailoring Agents to LLM Capabilities
|
||||
|
||||
Different LLMs have different strengths. Design your agents with these capabilities in mind:
|
||||
|
||||
```yaml
|
||||
# For complex reasoning tasks
|
||||
analyst:
|
||||
role: "Data Insights Analyst"
|
||||
goal: "..."
|
||||
backstory: "..."
|
||||
llm: openai/gpt-4o
|
||||
|
||||
# For creative content
|
||||
writer:
|
||||
role: "Creative Content Writer"
|
||||
goal: "..."
|
||||
backstory: "..."
|
||||
llm: anthropic/claude-3-opus
|
||||
```
|
||||
|
||||
## Testing and Iterating on Agent Design
|
||||
|
||||
Agent design is often an iterative process. Here's a practical approach:
|
||||
|
||||
1. **Start with a prototype**: Create an initial agent definition
|
||||
2. **Test with sample tasks**: Evaluate performance on representative tasks
|
||||
3. **Analyze outputs**: Identify strengths and weaknesses
|
||||
4. **Refine the definition**: Adjust role, goal, and backstory based on observations
|
||||
5. **Test in collaboration**: Evaluate how the agent performs in a crew setting
|
||||
|
||||
## Conclusion
|
||||
|
||||
Crafting effective agents is both an art and a science. By carefully defining roles, goals, and backstories that align with your specific needs, and combining them with well-designed tasks, you can create specialized AI collaborators that produce exceptional results.
|
||||
|
||||
Remember that agent and task design is an iterative process. Start with these best practices, observe your agents in action, and refine your approach based on what you learn. And always keep in mind the 80/20 rule - focus most of your effort on creating clear, focused tasks to get the best results from your agents.
|
||||
|
||||
<Check>
|
||||
Congratulations! You now understand the principles and practices of effective agent design. Apply these techniques to create powerful, specialized agents that work together seamlessly to accomplish complex tasks.
|
||||
</Check>
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Experiment with different agent configurations for your specific use case
|
||||
- Learn about [building your first crew](/en/guides/crews/first-crew) to see how agents work together
|
||||
- Explore [CrewAI Flows](/en/guides/flows/first-flow) for more advanced orchestration
|
||||
503
docs/en/guides/concepts/evaluating-use-cases.mdx
Normal file
503
docs/en/guides/concepts/evaluating-use-cases.mdx
Normal file
@@ -0,0 +1,503 @@
|
||||
---
|
||||
title: Evaluating Use Cases for CrewAI
|
||||
description: Learn how to assess your AI application needs and choose the right approach between Crews and Flows based on complexity and precision requirements.
|
||||
icon: scale-balanced
|
||||
---
|
||||
|
||||
## Understanding the Decision Framework
|
||||
|
||||
When building AI applications with CrewAI, one of the most important decisions you'll make is choosing the right approach for your specific use case. Should you use a Crew? A Flow? A combination of both? This guide will help you evaluate your requirements and make informed architectural decisions.
|
||||
|
||||
At the heart of this decision is understanding the relationship between **complexity** and **precision** in your application:
|
||||
|
||||
<Frame caption="Complexity vs. Precision Matrix for CrewAI Applications">
|
||||
<img src="/images/complexity_precision.png" alt="Complexity vs. Precision Matrix" />
|
||||
</Frame>
|
||||
|
||||
This matrix helps visualize how different approaches align with varying requirements for complexity and precision. Let's explore what each quadrant means and how it guides your architectural choices.
|
||||
|
||||
## The Complexity-Precision Matrix Explained
|
||||
|
||||
### What is Complexity?
|
||||
|
||||
In the context of CrewAI applications, **complexity** refers to:
|
||||
|
||||
- The number of distinct steps or operations required
|
||||
- The diversity of tasks that need to be performed
|
||||
- The interdependencies between different components
|
||||
- The need for conditional logic and branching
|
||||
- The sophistication of the overall workflow
|
||||
|
||||
### What is Precision?
|
||||
|
||||
**Precision** in this context refers to:
|
||||
|
||||
- The accuracy required in the final output
|
||||
- The need for structured, predictable results
|
||||
- The importance of reproducibility
|
||||
- The level of control needed over each step
|
||||
- The tolerance for variation in outputs
|
||||
|
||||
### The Four Quadrants
|
||||
|
||||
#### 1. Low Complexity, Low Precision
|
||||
|
||||
**Characteristics:**
|
||||
- Simple, straightforward tasks
|
||||
- Tolerance for some variation in outputs
|
||||
- Limited number of steps
|
||||
- Creative or exploratory applications
|
||||
|
||||
**Recommended Approach:** Simple Crews with minimal agents
|
||||
|
||||
**Example Use Cases:**
|
||||
- Basic content generation
|
||||
- Idea brainstorming
|
||||
- Simple summarization tasks
|
||||
- Creative writing assistance
|
||||
|
||||
#### 2. Low Complexity, High Precision
|
||||
|
||||
**Characteristics:**
|
||||
- Simple workflows that require exact, structured outputs
|
||||
- Need for reproducible results
|
||||
- Limited steps but high accuracy requirements
|
||||
- Often involves data processing or transformation
|
||||
|
||||
**Recommended Approach:** Flows with direct LLM calls or simple Crews with structured outputs
|
||||
|
||||
**Example Use Cases:**
|
||||
- Data extraction and transformation
|
||||
- Form filling and validation
|
||||
- Structured content generation (JSON, XML)
|
||||
- Simple classification tasks
|
||||
|
||||
#### 3. High Complexity, Low Precision
|
||||
|
||||
**Characteristics:**
|
||||
- Multi-stage processes with many steps
|
||||
- Creative or exploratory outputs
|
||||
- Complex interactions between components
|
||||
- Tolerance for variation in final results
|
||||
|
||||
**Recommended Approach:** Complex Crews with multiple specialized agents
|
||||
|
||||
**Example Use Cases:**
|
||||
- Research and analysis
|
||||
- Content creation pipelines
|
||||
- Exploratory data analysis
|
||||
- Creative problem-solving
|
||||
|
||||
#### 4. High Complexity, High Precision
|
||||
|
||||
**Characteristics:**
|
||||
- Complex workflows requiring structured outputs
|
||||
- Multiple interdependent steps with strict accuracy requirements
|
||||
- Need for both sophisticated processing and precise results
|
||||
- Often mission-critical applications
|
||||
|
||||
**Recommended Approach:** Flows orchestrating multiple Crews with validation steps
|
||||
|
||||
**Example Use Cases:**
|
||||
- Enterprise decision support systems
|
||||
- Complex data processing pipelines
|
||||
- Multi-stage document processing
|
||||
- Regulated industry applications
|
||||
|
||||
## Choosing Between Crews and Flows
|
||||
|
||||
### When to Choose Crews
|
||||
|
||||
Crews are ideal when:
|
||||
|
||||
1. **You need collaborative intelligence** - Multiple agents with different specializations need to work together
|
||||
2. **The problem requires emergent thinking** - The solution benefits from different perspectives and approaches
|
||||
3. **The task is primarily creative or analytical** - The work involves research, content creation, or analysis
|
||||
4. **You value adaptability over strict structure** - The workflow can benefit from agent autonomy
|
||||
5. **The output format can be somewhat flexible** - Some variation in output structure is acceptable
|
||||
|
||||
```python
|
||||
# Example: Research Crew for market analysis
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
|
||||
# Create specialized agents
|
||||
researcher = Agent(
|
||||
role="Market Research Specialist",
|
||||
goal="Find comprehensive market data on emerging technologies",
|
||||
backstory="You are an expert at discovering market trends and gathering data."
|
||||
)
|
||||
|
||||
analyst = Agent(
|
||||
role="Market Analyst",
|
||||
goal="Analyze market data and identify key opportunities",
|
||||
backstory="You excel at interpreting market data and spotting valuable insights."
|
||||
)
|
||||
|
||||
# Define their tasks
|
||||
research_task = Task(
|
||||
description="Research the current market landscape for AI-powered healthcare solutions",
|
||||
expected_output="Comprehensive market data including key players, market size, and growth trends",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
analysis_task = Task(
|
||||
description="Analyze the market data and identify the top 3 investment opportunities",
|
||||
expected_output="Analysis report with 3 recommended investment opportunities and rationale",
|
||||
agent=analyst,
|
||||
context=[research_task]
|
||||
)
|
||||
|
||||
# Create the crew
|
||||
market_analysis_crew = Crew(
|
||||
agents=[researcher, analyst],
|
||||
tasks=[research_task, analysis_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run the crew
|
||||
result = market_analysis_crew.kickoff()
|
||||
```
|
||||
|
||||
### When to Choose Flows
|
||||
|
||||
Flows are ideal when:
|
||||
|
||||
1. **You need precise control over execution** - The workflow requires exact sequencing and state management
|
||||
2. **The application has complex state requirements** - You need to maintain and transform state across multiple steps
|
||||
3. **You need structured, predictable outputs** - The application requires consistent, formatted results
|
||||
4. **The workflow involves conditional logic** - Different paths need to be taken based on intermediate results
|
||||
5. **You need to combine AI with procedural code** - The solution requires both AI capabilities and traditional programming
|
||||
|
||||
```python
|
||||
# Example: Customer Support Flow with structured processing
|
||||
from crewai.flow.flow import Flow, listen, router, start
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
|
||||
# Define structured state
|
||||
class SupportTicketState(BaseModel):
|
||||
ticket_id: str = ""
|
||||
customer_name: str = ""
|
||||
issue_description: str = ""
|
||||
category: str = ""
|
||||
priority: str = "medium"
|
||||
resolution: str = ""
|
||||
satisfaction_score: int = 0
|
||||
|
||||
class CustomerSupportFlow(Flow[SupportTicketState]):
|
||||
@start()
|
||||
def receive_ticket(self):
|
||||
# In a real app, this might come from an API
|
||||
self.state.ticket_id = "TKT-12345"
|
||||
self.state.customer_name = "Alex Johnson"
|
||||
self.state.issue_description = "Unable to access premium features after payment"
|
||||
return "Ticket received"
|
||||
|
||||
@listen(receive_ticket)
|
||||
def categorize_ticket(self, _):
|
||||
# Use a direct LLM call for categorization
|
||||
from crewai import LLM
|
||||
llm = LLM(model="openai/gpt-4o-mini")
|
||||
|
||||
prompt = f"""
|
||||
Categorize the following customer support issue into one of these categories:
|
||||
- Billing
|
||||
- Account Access
|
||||
- Technical Issue
|
||||
- Feature Request
|
||||
- Other
|
||||
|
||||
Issue: {self.state.issue_description}
|
||||
|
||||
Return only the category name.
|
||||
"""
|
||||
|
||||
self.state.category = llm.call(prompt).strip()
|
||||
return self.state.category
|
||||
|
||||
@router(categorize_ticket)
|
||||
def route_by_category(self, category):
|
||||
# Route to different handlers based on category
|
||||
return category.lower().replace(" ", "_")
|
||||
|
||||
@listen("billing")
|
||||
def handle_billing_issue(self):
|
||||
# Handle billing-specific logic
|
||||
self.state.priority = "high"
|
||||
# More billing-specific processing...
|
||||
return "Billing issue handled"
|
||||
|
||||
@listen("account_access")
|
||||
def handle_access_issue(self):
|
||||
# Handle access-specific logic
|
||||
self.state.priority = "high"
|
||||
# More access-specific processing...
|
||||
return "Access issue handled"
|
||||
|
||||
# Additional category handlers...
|
||||
|
||||
@listen("billing", "account_access", "technical_issue", "feature_request", "other")
|
||||
def resolve_ticket(self, resolution_info):
|
||||
# Final resolution step
|
||||
self.state.resolution = f"Issue resolved: {resolution_info}"
|
||||
return self.state.resolution
|
||||
|
||||
# Run the flow
|
||||
support_flow = CustomerSupportFlow()
|
||||
result = support_flow.kickoff()
|
||||
```
|
||||
|
||||
### When to Combine Crews and Flows
|
||||
|
||||
The most sophisticated applications often benefit from combining Crews and Flows:
|
||||
|
||||
1. **Complex multi-stage processes** - Use Flows to orchestrate the overall process and Crews for complex subtasks
|
||||
2. **Applications requiring both creativity and structure** - Use Crews for creative tasks and Flows for structured processing
|
||||
3. **Enterprise-grade AI applications** - Use Flows to manage state and process flow while leveraging Crews for specialized work
|
||||
|
||||
```python
|
||||
# Example: Content Production Pipeline combining Crews and Flows
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
|
||||
class ContentState(BaseModel):
|
||||
topic: str = ""
|
||||
target_audience: str = ""
|
||||
content_type: str = ""
|
||||
outline: Dict = {}
|
||||
draft_content: str = ""
|
||||
final_content: str = ""
|
||||
seo_score: int = 0
|
||||
|
||||
class ContentProductionFlow(Flow[ContentState]):
|
||||
@start()
|
||||
def initialize_project(self):
|
||||
# Set initial parameters
|
||||
self.state.topic = "Sustainable Investing"
|
||||
self.state.target_audience = "Millennial Investors"
|
||||
self.state.content_type = "Blog Post"
|
||||
return "Project initialized"
|
||||
|
||||
@listen(initialize_project)
|
||||
def create_outline(self, _):
|
||||
# Use a research crew to create an outline
|
||||
researcher = Agent(
|
||||
role="Content Researcher",
|
||||
goal=f"Research {self.state.topic} for {self.state.target_audience}",
|
||||
backstory="You are an expert researcher with deep knowledge of content creation."
|
||||
)
|
||||
|
||||
outliner = Agent(
|
||||
role="Content Strategist",
|
||||
goal=f"Create an engaging outline for a {self.state.content_type}",
|
||||
backstory="You excel at structuring content for maximum engagement."
|
||||
)
|
||||
|
||||
research_task = Task(
|
||||
description=f"Research {self.state.topic} focusing on what would interest {self.state.target_audience}",
|
||||
expected_output="Comprehensive research notes with key points and statistics",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
outline_task = Task(
|
||||
description=f"Create an outline for a {self.state.content_type} about {self.state.topic}",
|
||||
expected_output="Detailed content outline with sections and key points",
|
||||
agent=outliner,
|
||||
context=[research_task]
|
||||
)
|
||||
|
||||
outline_crew = Crew(
|
||||
agents=[researcher, outliner],
|
||||
tasks=[research_task, outline_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run the crew and store the result
|
||||
result = outline_crew.kickoff()
|
||||
|
||||
# Parse the outline (in a real app, you might use a more robust parsing approach)
|
||||
import json
|
||||
try:
|
||||
self.state.outline = json.loads(result.raw)
|
||||
except:
|
||||
# Fallback if not valid JSON
|
||||
self.state.outline = {"sections": result.raw}
|
||||
|
||||
return "Outline created"
|
||||
|
||||
@listen(create_outline)
|
||||
def write_content(self, _):
|
||||
# Use a writing crew to create the content
|
||||
writer = Agent(
|
||||
role="Content Writer",
|
||||
goal=f"Write engaging content for {self.state.target_audience}",
|
||||
backstory="You are a skilled writer who creates compelling content."
|
||||
)
|
||||
|
||||
editor = Agent(
|
||||
role="Content Editor",
|
||||
goal="Ensure content is polished, accurate, and engaging",
|
||||
backstory="You have a keen eye for detail and a talent for improving content."
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description=f"Write a {self.state.content_type} about {self.state.topic} following this outline: {self.state.outline}",
|
||||
expected_output="Complete draft content in markdown format",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
editing_task = Task(
|
||||
description="Edit and improve the draft content for clarity, engagement, and accuracy",
|
||||
expected_output="Polished final content in markdown format",
|
||||
agent=editor,
|
||||
context=[writing_task]
|
||||
)
|
||||
|
||||
writing_crew = Crew(
|
||||
agents=[writer, editor],
|
||||
tasks=[writing_task, editing_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run the crew and store the result
|
||||
result = writing_crew.kickoff()
|
||||
self.state.final_content = result.raw
|
||||
|
||||
return "Content created"
|
||||
|
||||
@listen(write_content)
|
||||
def optimize_for_seo(self, _):
|
||||
# Use a direct LLM call for SEO optimization
|
||||
from crewai import LLM
|
||||
llm = LLM(model="openai/gpt-4o-mini")
|
||||
|
||||
prompt = f"""
|
||||
Analyze this content for SEO effectiveness for the keyword "{self.state.topic}".
|
||||
Rate it on a scale of 1-100 and provide 3 specific recommendations for improvement.
|
||||
|
||||
Content: {self.state.final_content[:1000]}... (truncated for brevity)
|
||||
|
||||
Format your response as JSON with the following structure:
|
||||
{{
|
||||
"score": 85,
|
||||
"recommendations": [
|
||||
"Recommendation 1",
|
||||
"Recommendation 2",
|
||||
"Recommendation 3"
|
||||
]
|
||||
}}
|
||||
"""
|
||||
|
||||
seo_analysis = llm.call(prompt)
|
||||
|
||||
# Parse the SEO analysis
|
||||
import json
|
||||
try:
|
||||
analysis = json.loads(seo_analysis)
|
||||
self.state.seo_score = analysis.get("score", 0)
|
||||
return analysis
|
||||
except:
|
||||
self.state.seo_score = 50
|
||||
return {"score": 50, "recommendations": ["Unable to parse SEO analysis"]}
|
||||
|
||||
# Run the flow
|
||||
content_flow = ContentProductionFlow()
|
||||
result = content_flow.kickoff()
|
||||
```
|
||||
|
||||
## Practical Evaluation Framework
|
||||
|
||||
To determine the right approach for your specific use case, follow this step-by-step evaluation framework:
|
||||
|
||||
### Step 1: Assess Complexity
|
||||
|
||||
Rate your application's complexity on a scale of 1-10 by considering:
|
||||
|
||||
1. **Number of steps**: How many distinct operations are required?
|
||||
- 1-3 steps: Low complexity (1-3)
|
||||
- 4-7 steps: Medium complexity (4-7)
|
||||
- 8+ steps: High complexity (8-10)
|
||||
|
||||
2. **Interdependencies**: How interconnected are the different parts?
|
||||
- Few dependencies: Low complexity (1-3)
|
||||
- Some dependencies: Medium complexity (4-7)
|
||||
- Many complex dependencies: High complexity (8-10)
|
||||
|
||||
3. **Conditional logic**: How much branching and decision-making is needed?
|
||||
- Linear process: Low complexity (1-3)
|
||||
- Some branching: Medium complexity (4-7)
|
||||
- Complex decision trees: High complexity (8-10)
|
||||
|
||||
4. **Domain knowledge**: How specialized is the knowledge required?
|
||||
- General knowledge: Low complexity (1-3)
|
||||
- Some specialized knowledge: Medium complexity (4-7)
|
||||
- Deep expertise in multiple domains: High complexity (8-10)
|
||||
|
||||
Calculate your average score to determine overall complexity.
|
||||
|
||||
### Step 2: Assess Precision Requirements
|
||||
|
||||
Rate your precision requirements on a scale of 1-10 by considering:
|
||||
|
||||
1. **Output structure**: How structured must the output be?
|
||||
- Free-form text: Low precision (1-3)
|
||||
- Semi-structured: Medium precision (4-7)
|
||||
- Strictly formatted (JSON, XML): High precision (8-10)
|
||||
|
||||
2. **Accuracy needs**: How important is factual accuracy?
|
||||
- Creative content: Low precision (1-3)
|
||||
- Informational content: Medium precision (4-7)
|
||||
- Critical information: High precision (8-10)
|
||||
|
||||
3. **Reproducibility**: How consistent must results be across runs?
|
||||
- Variation acceptable: Low precision (1-3)
|
||||
- Some consistency needed: Medium precision (4-7)
|
||||
- Exact reproducibility required: High precision (8-10)
|
||||
|
||||
4. **Error tolerance**: What is the impact of errors?
|
||||
- Low impact: Low precision (1-3)
|
||||
- Moderate impact: Medium precision (4-7)
|
||||
- High impact: High precision (8-10)
|
||||
|
||||
Calculate your average score to determine overall precision requirements.
|
||||
|
||||
### Step 3: Map to the Matrix
|
||||
|
||||
Plot your complexity and precision scores on the matrix:
|
||||
|
||||
- **Low Complexity (1-4), Low Precision (1-4)**: Simple Crews
|
||||
- **Low Complexity (1-4), High Precision (5-10)**: Flows with direct LLM calls
|
||||
- **High Complexity (5-10), Low Precision (1-4)**: Complex Crews
|
||||
- **High Complexity (5-10), High Precision (5-10)**: Flows orchestrating Crews
|
||||
|
||||
### Step 4: Consider Additional Factors
|
||||
|
||||
Beyond complexity and precision, consider:
|
||||
|
||||
1. **Development time**: Crews are often faster to prototype
|
||||
2. **Maintenance needs**: Flows provide better long-term maintainability
|
||||
3. **Team expertise**: Consider your team's familiarity with different approaches
|
||||
4. **Scalability requirements**: Flows typically scale better for complex applications
|
||||
5. **Integration needs**: Consider how the solution will integrate with existing systems
|
||||
|
||||
## Conclusion
|
||||
|
||||
Choosing between Crews and Flows—or combining them—is a critical architectural decision that impacts the effectiveness, maintainability, and scalability of your CrewAI application. By evaluating your use case along the dimensions of complexity and precision, you can make informed decisions that align with your specific requirements.
|
||||
|
||||
Remember that the best approach often evolves as your application matures. Start with the simplest solution that meets your needs, and be prepared to refine your architecture as you gain experience and your requirements become clearer.
|
||||
|
||||
<Check>
|
||||
You now have a framework for evaluating CrewAI use cases and choosing the right approach based on complexity and precision requirements. This will help you build more effective, maintainable, and scalable AI applications.
|
||||
</Check>
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn more about [crafting effective agents](/en/guides/agents/crafting-effective-agents)
|
||||
- Explore [building your first crew](/en/guides/crews/first-crew)
|
||||
- Dive into [mastering flow state management](/en/guides/flows/mastering-flow-state)
|
||||
- Check out the [core concepts](/en/concepts/agents) for deeper understanding
|
||||
395
docs/en/guides/crews/first-crew.mdx
Normal file
395
docs/en/guides/crews/first-crew.mdx
Normal file
@@ -0,0 +1,395 @@
|
||||
---
|
||||
title: Build Your First Crew
|
||||
description: Step-by-step tutorial to create a collaborative AI team that works together to solve complex problems.
|
||||
icon: users-gear
|
||||
---
|
||||
|
||||
## Unleashing the Power of Collaborative AI
|
||||
|
||||
Imagine having a team of specialized AI agents working together seamlessly to solve complex problems, each contributing their unique skills to achieve a common goal. This is the power of CrewAI - a framework that enables you to create collaborative AI systems that can accomplish tasks far beyond what a single AI could achieve alone.
|
||||
|
||||
In this guide, we'll walk through creating a research crew that will help us research and analyze a topic, then create a comprehensive report. This practical example demonstrates how AI agents can collaborate to accomplish complex tasks, but it's just the beginning of what's possible with CrewAI.
|
||||
|
||||
### What You'll Build and Learn
|
||||
|
||||
By the end of this guide, you'll have:
|
||||
|
||||
1. **Created a specialized AI research team** with distinct roles and responsibilities
|
||||
2. **Orchestrated collaboration** between multiple AI agents
|
||||
3. **Automated a complex workflow** that involves gathering information, analysis, and report generation
|
||||
4. **Built foundational skills** that you can apply to more ambitious projects
|
||||
|
||||
While we're building a simple research crew in this guide, the same patterns and techniques can be applied to create much more sophisticated teams for tasks like:
|
||||
|
||||
- Multi-stage content creation with specialized writers, editors, and fact-checkers
|
||||
- Complex customer service systems with tiered support agents
|
||||
- Autonomous business analysts that gather data, create visualizations, and generate insights
|
||||
- Product development teams that ideate, design, and plan implementation
|
||||
|
||||
Let's get started building your first crew!
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before starting, make sure you have:
|
||||
|
||||
1. Installed CrewAI following the [installation guide](/en/installation)
|
||||
2. Set up your LLM API key in your environment, following the [LLM setup
|
||||
guide](/en/concepts/llms#setting-up-your-llm)
|
||||
3. Basic understanding of Python
|
||||
|
||||
## Step 1: Create a New CrewAI Project
|
||||
|
||||
First, let's create a new CrewAI project using the CLI. This command will set up a complete project structure with all the necessary files, allowing you to focus on defining your agents and their tasks rather than setting up boilerplate code.
|
||||
|
||||
```bash
|
||||
crewai create crew research_crew
|
||||
cd research_crew
|
||||
```
|
||||
|
||||
This will generate a project with the basic structure needed for your crew. The CLI automatically creates:
|
||||
|
||||
- A project directory with the necessary files
|
||||
- Configuration files for agents and tasks
|
||||
- A basic crew implementation
|
||||
- A main script to run the crew
|
||||
|
||||
<Frame caption="CrewAI Framework Overview">
|
||||
<img src="/images/crews.png" alt="CrewAI Framework Overview" />
|
||||
</Frame>
|
||||
|
||||
|
||||
## Step 2: Explore the Project Structure
|
||||
|
||||
Let's take a moment to understand the project structure created by the CLI. CrewAI follows best practices for Python projects, making it easy to maintain and extend your code as your crews become more complex.
|
||||
|
||||
```
|
||||
research_crew/
|
||||
├── .gitignore
|
||||
├── pyproject.toml
|
||||
├── README.md
|
||||
├── .env
|
||||
└── src/
|
||||
└── research_crew/
|
||||
├── __init__.py
|
||||
├── main.py
|
||||
├── crew.py
|
||||
├── tools/
|
||||
│ ├── custom_tool.py
|
||||
│ └── __init__.py
|
||||
└── config/
|
||||
├── agents.yaml
|
||||
└── tasks.yaml
|
||||
```
|
||||
|
||||
This structure follows best practices for Python projects and makes it easy to organize your code. The separation of configuration files (in YAML) from implementation code (in Python) makes it easy to modify your crew's behavior without changing the underlying code.
|
||||
|
||||
## Step 3: Configure Your Agents
|
||||
|
||||
Now comes the fun part - defining your AI agents! In CrewAI, agents are specialized entities with specific roles, goals, and backstories that shape their behavior. Think of them as characters in a play, each with their own personality and purpose.
|
||||
|
||||
For our research crew, we'll create two agents:
|
||||
1. A **researcher** who excels at finding and organizing information
|
||||
2. An **analyst** who can interpret research findings and create insightful reports
|
||||
|
||||
Let's modify the `agents.yaml` file to define these specialized agents. Be sure
|
||||
to set `llm` to the provider you are using.
|
||||
|
||||
```yaml
|
||||
# src/research_crew/config/agents.yaml
|
||||
researcher:
|
||||
role: >
|
||||
Senior Research Specialist for {topic}
|
||||
goal: >
|
||||
Find comprehensive and accurate information about {topic}
|
||||
with a focus on recent developments and key insights
|
||||
backstory: >
|
||||
You are an experienced research specialist with a talent for
|
||||
finding relevant information from various sources. You excel at
|
||||
organizing information in a clear and structured manner, making
|
||||
complex topics accessible to others.
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
|
||||
analyst:
|
||||
role: >
|
||||
Data Analyst and Report Writer for {topic}
|
||||
goal: >
|
||||
Analyze research findings and create a comprehensive, well-structured
|
||||
report that presents insights in a clear and engaging way
|
||||
backstory: >
|
||||
You are a skilled analyst with a background in data interpretation
|
||||
and technical writing. You have a talent for identifying patterns
|
||||
and extracting meaningful insights from research data, then
|
||||
communicating those insights effectively through well-crafted reports.
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
```
|
||||
|
||||
Notice how each agent has a distinct role, goal, and backstory. These elements aren't just descriptive - they actively shape how the agent approaches its tasks. By crafting these carefully, you can create agents with specialized skills and perspectives that complement each other.
|
||||
|
||||
## Step 4: Define Your Tasks
|
||||
|
||||
With our agents defined, we now need to give them specific tasks to perform. Tasks in CrewAI represent the concrete work that agents will perform, with detailed instructions and expected outputs.
|
||||
|
||||
For our research crew, we'll define two main tasks:
|
||||
1. A **research task** for gathering comprehensive information
|
||||
2. An **analysis task** for creating an insightful report
|
||||
|
||||
Let's modify the `tasks.yaml` file:
|
||||
|
||||
```yaml
|
||||
# src/research_crew/config/tasks.yaml
|
||||
research_task:
|
||||
description: >
|
||||
Conduct thorough research on {topic}. Focus on:
|
||||
1. Key concepts and definitions
|
||||
2. Historical development and recent trends
|
||||
3. Major challenges and opportunities
|
||||
4. Notable applications or case studies
|
||||
5. Future outlook and potential developments
|
||||
|
||||
Make sure to organize your findings in a structured format with clear sections.
|
||||
expected_output: >
|
||||
A comprehensive research document with well-organized sections covering
|
||||
all the requested aspects of {topic}. Include specific facts, figures,
|
||||
and examples where relevant.
|
||||
agent: researcher
|
||||
|
||||
analysis_task:
|
||||
description: >
|
||||
Analyze the research findings and create a comprehensive report on {topic}.
|
||||
Your report should:
|
||||
1. Begin with an executive summary
|
||||
2. Include all key information from the research
|
||||
3. Provide insightful analysis of trends and patterns
|
||||
4. Offer recommendations or future considerations
|
||||
5. Be formatted in a professional, easy-to-read style with clear headings
|
||||
expected_output: >
|
||||
A polished, professional report on {topic} that presents the research
|
||||
findings with added analysis and insights. The report should be well-structured
|
||||
with an executive summary, main sections, and conclusion.
|
||||
agent: analyst
|
||||
context:
|
||||
- research_task
|
||||
output_file: output/report.md
|
||||
```
|
||||
|
||||
Note the `context` field in the analysis task - this is a powerful feature that allows the analyst to access the output of the research task. This creates a workflow where information flows naturally between agents, just as it would in a human team.
|
||||
|
||||
## Step 5: Configure Your Crew
|
||||
|
||||
Now it's time to bring everything together by configuring our crew. The crew is the container that orchestrates how agents work together to complete tasks.
|
||||
|
||||
Let's modify the `crew.py` file:
|
||||
|
||||
```python
|
||||
# src/research_crew/crew.py
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from crewai.project import CrewBase, agent, crew, task
|
||||
from crewai_tools import SerperDevTool
|
||||
from crewai.agents.agent_builder.base_agent import BaseAgent
|
||||
from typing import List
|
||||
|
||||
@CrewBase
|
||||
class ResearchCrew():
|
||||
"""Research crew for comprehensive topic analysis and reporting"""
|
||||
|
||||
agents: List[BaseAgent]
|
||||
tasks: List[Task]
|
||||
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'], # type: ignore[index]
|
||||
verbose=True,
|
||||
tools=[SerperDevTool()]
|
||||
)
|
||||
|
||||
@agent
|
||||
def analyst(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['analyst'], # type: ignore[index]
|
||||
verbose=True
|
||||
)
|
||||
|
||||
@task
|
||||
def research_task(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['research_task'] # type: ignore[index]
|
||||
)
|
||||
|
||||
@task
|
||||
def analysis_task(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['analysis_task'], # type: ignore[index]
|
||||
output_file='output/report.md'
|
||||
)
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
"""Creates the research crew"""
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True,
|
||||
)
|
||||
```
|
||||
|
||||
In this code, we're:
|
||||
1. Creating the researcher agent and equipping it with the SerperDevTool to search the web
|
||||
2. Creating the analyst agent
|
||||
3. Setting up the research and analysis tasks
|
||||
4. Configuring the crew to run tasks sequentially (the analyst will wait for the researcher to finish)
|
||||
|
||||
This is where the magic happens - with just a few lines of code, we've defined a collaborative AI system where specialized agents work together in a coordinated process.
|
||||
|
||||
## Step 6: Set Up Your Main Script
|
||||
|
||||
Now, let's set up the main script that will run our crew. This is where we provide the specific topic we want our crew to research.
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python
|
||||
# src/research_crew/main.py
|
||||
import os
|
||||
from research_crew.crew import ResearchCrew
|
||||
|
||||
# Create output directory if it doesn't exist
|
||||
os.makedirs('output', exist_ok=True)
|
||||
|
||||
def run():
|
||||
"""
|
||||
Run the research crew.
|
||||
"""
|
||||
inputs = {
|
||||
'topic': 'Artificial Intelligence in Healthcare'
|
||||
}
|
||||
|
||||
# Create and run the crew
|
||||
result = ResearchCrew().crew().kickoff(inputs=inputs)
|
||||
|
||||
# Print the result
|
||||
print("\n\n=== FINAL REPORT ===\n\n")
|
||||
print(result.raw)
|
||||
|
||||
print("\n\nReport has been saved to output/report.md")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
```
|
||||
|
||||
This script prepares the environment, specifies our research topic, and kicks off the crew's work. The power of CrewAI is evident in how simple this code is - all the complexity of managing multiple AI agents is handled by the framework.
|
||||
|
||||
## Step 7: Set Up Your Environment Variables
|
||||
|
||||
Create a `.env` file in your project root with your API keys:
|
||||
|
||||
```sh
|
||||
SERPER_API_KEY=your_serper_api_key
|
||||
# Add your provider's API key here too.
|
||||
```
|
||||
|
||||
See the [LLM Setup guide](/en/concepts/llms#setting-up-your-llm) for details on configuring your provider of choice. You can get a Serper API key from [Serper.dev](https://serper.dev/).
|
||||
|
||||
## Step 8: Install Dependencies
|
||||
|
||||
Install the required dependencies using the CrewAI CLI:
|
||||
|
||||
```bash
|
||||
crewai install
|
||||
```
|
||||
|
||||
This command will:
|
||||
1. Read the dependencies from your project configuration
|
||||
2. Create a virtual environment if needed
|
||||
3. Install all required packages
|
||||
|
||||
## Step 9: Run Your Crew
|
||||
|
||||
Now for the exciting moment - it's time to run your crew and see AI collaboration in action!
|
||||
|
||||
```bash
|
||||
crewai run
|
||||
```
|
||||
|
||||
When you run this command, you'll see your crew spring to life. The researcher will gather information about the specified topic, and the analyst will then create a comprehensive report based on that research. You'll see the agents' thought processes, actions, and outputs in real-time as they work together to complete their tasks.
|
||||
|
||||
## Step 10: Review the Output
|
||||
|
||||
Once the crew completes its work, you'll find the final report in the `output/report.md` file. The report will include:
|
||||
|
||||
1. An executive summary
|
||||
2. Detailed information about the topic
|
||||
3. Analysis and insights
|
||||
4. Recommendations or future considerations
|
||||
|
||||
Take a moment to appreciate what you've accomplished - you've created a system where multiple AI agents collaborated on a complex task, each contributing their specialized skills to produce a result that's greater than what any single agent could achieve alone.
|
||||
|
||||
## Exploring Other CLI Commands
|
||||
|
||||
CrewAI offers several other useful CLI commands for working with crews:
|
||||
|
||||
```bash
|
||||
# View all available commands
|
||||
crewai --help
|
||||
|
||||
# Run the crew
|
||||
crewai run
|
||||
|
||||
# Test the crew
|
||||
crewai test
|
||||
|
||||
# Reset crew memories
|
||||
crewai reset-memories
|
||||
|
||||
# Replay from a specific task
|
||||
crewai replay -t <task_id>
|
||||
```
|
||||
|
||||
## The Art of the Possible: Beyond Your First Crew
|
||||
|
||||
What you've built in this guide is just the beginning. The skills and patterns you've learned can be applied to create increasingly sophisticated AI systems. Here are some ways you could extend this basic research crew:
|
||||
|
||||
### Expanding Your Crew
|
||||
|
||||
You could add more specialized agents to your crew:
|
||||
- A **fact-checker** to verify research findings
|
||||
- A **data visualizer** to create charts and graphs
|
||||
- A **domain expert** with specialized knowledge in a particular area
|
||||
- A **critic** to identify weaknesses in the analysis
|
||||
|
||||
### Adding Tools and Capabilities
|
||||
|
||||
You could enhance your agents with additional tools:
|
||||
- Web browsing tools for real-time research
|
||||
- CSV/database tools for data analysis
|
||||
- Code execution tools for data processing
|
||||
- API connections to external services
|
||||
|
||||
### Creating More Complex Workflows
|
||||
|
||||
You could implement more sophisticated processes:
|
||||
- Hierarchical processes where manager agents delegate to worker agents
|
||||
- Iterative processes with feedback loops for refinement
|
||||
- Parallel processes where multiple agents work simultaneously
|
||||
- Dynamic processes that adapt based on intermediate results
|
||||
|
||||
### Applying to Different Domains
|
||||
|
||||
The same patterns can be applied to create crews for:
|
||||
- **Content creation**: Writers, editors, fact-checkers, and designers working together
|
||||
- **Customer service**: Triage agents, specialists, and quality control working together
|
||||
- **Product development**: Researchers, designers, and planners collaborating
|
||||
- **Data analysis**: Data collectors, analysts, and visualization specialists
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you've built your first crew, you can:
|
||||
|
||||
1. Experiment with different agent configurations and personalities
|
||||
2. Try more complex task structures and workflows
|
||||
3. Implement custom tools to give your agents new capabilities
|
||||
4. Apply your crew to different topics or problem domains
|
||||
5. Explore [CrewAI Flows](/en/guides/flows/first-flow) for more advanced workflows with procedural programming
|
||||
|
||||
<Check>
|
||||
Congratulations! You've successfully built your first CrewAI crew that can research and analyze any topic you provide. This foundational experience has equipped you with the skills to create increasingly sophisticated AI systems that can tackle complex, multi-stage problems through collaborative intelligence.
|
||||
</Check>
|
||||
622
docs/en/guides/flows/first-flow.mdx
Normal file
622
docs/en/guides/flows/first-flow.mdx
Normal file
@@ -0,0 +1,622 @@
|
||||
---
|
||||
title: Build Your First Flow
|
||||
description: Learn how to create structured, event-driven workflows with precise control over execution.
|
||||
icon: diagram-project
|
||||
---
|
||||
|
||||
## Taking Control of AI Workflows with Flows
|
||||
|
||||
CrewAI Flows represent the next level in AI orchestration - combining the collaborative power of AI agent crews with the precision and flexibility of procedural programming. While crews excel at agent collaboration, flows give you fine-grained control over exactly how and when different components of your AI system interact.
|
||||
|
||||
In this guide, we'll walk through creating a powerful CrewAI Flow that generates a comprehensive learning guide on any topic. This tutorial will demonstrate how Flows provide structured, event-driven control over your AI workflows by combining regular code, direct LLM calls, and crew-based processing.
|
||||
|
||||
### What Makes Flows Powerful
|
||||
|
||||
Flows enable you to:
|
||||
|
||||
1. **Combine different AI interaction patterns** - Use crews for complex collaborative tasks, direct LLM calls for simpler operations, and regular code for procedural logic
|
||||
2. **Build event-driven systems** - Define how components respond to specific events and data changes
|
||||
3. **Maintain state across components** - Share and transform data between different parts of your application
|
||||
4. **Integrate with external systems** - Seamlessly connect your AI workflow with databases, APIs, and user interfaces
|
||||
5. **Create complex execution paths** - Design conditional branches, parallel processing, and dynamic workflows
|
||||
|
||||
### What You'll Build and Learn
|
||||
|
||||
By the end of this guide, you'll have:
|
||||
|
||||
1. **Created a sophisticated content generation system** that combines user input, AI planning, and multi-agent content creation
|
||||
2. **Orchestrated the flow of information** between different components of your system
|
||||
3. **Implemented event-driven architecture** where each step responds to the completion of previous steps
|
||||
4. **Built a foundation for more complex AI applications** that you can expand and customize
|
||||
|
||||
This guide creator flow demonstrates fundamental patterns that can be applied to create much more advanced applications, such as:
|
||||
|
||||
- Interactive AI assistants that combine multiple specialized subsystems
|
||||
- Complex data processing pipelines with AI-enhanced transformations
|
||||
- Autonomous agents that integrate with external services and APIs
|
||||
- Multi-stage decision-making systems with human-in-the-loop processes
|
||||
|
||||
Let's dive in and build your first flow!
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before starting, make sure you have:
|
||||
|
||||
1. Installed CrewAI following the [installation guide](/en/installation)
|
||||
2. Set up your LLM API key in your environment, following the [LLM setup
|
||||
guide](/en/concepts/llms#setting-up-your-llm)
|
||||
3. Basic understanding of Python
|
||||
|
||||
## Step 1: Create a New CrewAI Flow Project
|
||||
|
||||
First, let's create a new CrewAI Flow project using the CLI. This command sets up a scaffolded project with all the necessary directories and template files for your flow.
|
||||
|
||||
```bash
|
||||
crewai create flow guide_creator_flow
|
||||
cd guide_creator_flow
|
||||
```
|
||||
|
||||
This will generate a project with the basic structure needed for your flow.
|
||||
|
||||
<Frame caption="CrewAI Framework Overview">
|
||||
<img src="/images/flows.png" alt="CrewAI Framework Overview" />
|
||||
</Frame>
|
||||
|
||||
## Step 2: Understanding the Project Structure
|
||||
|
||||
The generated project has the following structure. Take a moment to familiarize yourself with it, as understanding this structure will help you create more complex flows in the future.
|
||||
|
||||
```
|
||||
guide_creator_flow/
|
||||
├── .gitignore
|
||||
├── pyproject.toml
|
||||
├── README.md
|
||||
├── .env
|
||||
├── main.py
|
||||
├── crews/
|
||||
│ └── poem_crew/
|
||||
│ ├── config/
|
||||
│ │ ├── agents.yaml
|
||||
│ │ └── tasks.yaml
|
||||
│ └── poem_crew.py
|
||||
└── tools/
|
||||
└── custom_tool.py
|
||||
```
|
||||
|
||||
This structure provides a clear separation between different components of your flow:
|
||||
- The main flow logic in the `main.py` file
|
||||
- Specialized crews in the `crews` directory
|
||||
- Custom tools in the `tools` directory
|
||||
|
||||
We'll modify this structure to create our guide creator flow, which will orchestrate the process of generating comprehensive learning guides.
|
||||
|
||||
## Step 3: Add a Content Writer Crew
|
||||
|
||||
Our flow will need a specialized crew to handle the content creation process. Let's use the CrewAI CLI to add a content writer crew:
|
||||
|
||||
```bash
|
||||
crewai flow add-crew content-crew
|
||||
```
|
||||
|
||||
This command automatically creates the necessary directories and template files for your crew. The content writer crew will be responsible for writing and reviewing sections of our guide, working within the overall flow orchestrated by our main application.
|
||||
|
||||
## Step 4: Configure the Content Writer Crew
|
||||
|
||||
Now, let's modify the generated files for the content writer crew. We'll set up two specialized agents - a writer and a reviewer - that will collaborate to create high-quality content for our guide.
|
||||
|
||||
1. First, update the agents configuration file to define our content creation team:
|
||||
|
||||
Remember to set `llm` to the provider you are using.
|
||||
|
||||
```yaml
|
||||
# src/guide_creator_flow/crews/content_crew/config/agents.yaml
|
||||
content_writer:
|
||||
role: >
|
||||
Educational Content Writer
|
||||
goal: >
|
||||
Create engaging, informative content that thoroughly explains the assigned topic
|
||||
and provides valuable insights to the reader
|
||||
backstory: >
|
||||
You are a talented educational writer with expertise in creating clear, engaging
|
||||
content. You have a gift for explaining complex concepts in accessible language
|
||||
and organizing information in a way that helps readers build their understanding.
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
|
||||
content_reviewer:
|
||||
role: >
|
||||
Educational Content Reviewer and Editor
|
||||
goal: >
|
||||
Ensure content is accurate, comprehensive, well-structured, and maintains
|
||||
consistency with previously written sections
|
||||
backstory: >
|
||||
You are a meticulous editor with years of experience reviewing educational
|
||||
content. You have an eye for detail, clarity, and coherence. You excel at
|
||||
improving content while maintaining the original author's voice and ensuring
|
||||
consistent quality across multiple sections.
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
```
|
||||
|
||||
These agent definitions establish the specialized roles and perspectives that will shape how our AI agents approach content creation. Notice how each agent has a distinct purpose and expertise.
|
||||
|
||||
2. Next, update the tasks configuration file to define the specific writing and reviewing tasks:
|
||||
|
||||
```yaml
|
||||
# src/guide_creator_flow/crews/content_crew/config/tasks.yaml
|
||||
write_section_task:
|
||||
description: >
|
||||
Write a comprehensive section on the topic: "{section_title}"
|
||||
|
||||
Section description: {section_description}
|
||||
Target audience: {audience_level} level learners
|
||||
|
||||
Your content should:
|
||||
1. Begin with a brief introduction to the section topic
|
||||
2. Explain all key concepts clearly with examples
|
||||
3. Include practical applications or exercises where appropriate
|
||||
4. End with a summary of key points
|
||||
5. Be approximately 500-800 words in length
|
||||
|
||||
Format your content in Markdown with appropriate headings, lists, and emphasis.
|
||||
|
||||
Previously written sections:
|
||||
{previous_sections}
|
||||
|
||||
Make sure your content maintains consistency with previously written sections
|
||||
and builds upon concepts that have already been explained.
|
||||
expected_output: >
|
||||
A well-structured, comprehensive section in Markdown format that thoroughly
|
||||
explains the topic and is appropriate for the target audience.
|
||||
agent: content_writer
|
||||
|
||||
review_section_task:
|
||||
description: >
|
||||
Review and improve the following section on "{section_title}":
|
||||
|
||||
{draft_content}
|
||||
|
||||
Target audience: {audience_level} level learners
|
||||
|
||||
Previously written sections:
|
||||
{previous_sections}
|
||||
|
||||
Your review should:
|
||||
1. Fix any grammatical or spelling errors
|
||||
2. Improve clarity and readability
|
||||
3. Ensure content is comprehensive and accurate
|
||||
4. Verify consistency with previously written sections
|
||||
5. Enhance the structure and flow
|
||||
6. Add any missing key information
|
||||
|
||||
Provide the improved version of the section in Markdown format.
|
||||
expected_output: >
|
||||
An improved, polished version of the section that maintains the original
|
||||
structure but enhances clarity, accuracy, and consistency.
|
||||
agent: content_reviewer
|
||||
context:
|
||||
- write_section_task
|
||||
```
|
||||
|
||||
These task definitions provide detailed instructions to our agents, ensuring they produce content that meets our quality standards. Note how the `context` parameter in the review task creates a workflow where the reviewer has access to the writer's output.
|
||||
|
||||
3. Now, update the crew implementation file to define how our agents and tasks work together:
|
||||
|
||||
```python
|
||||
# src/guide_creator_flow/crews/content_crew/content_crew.py
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from crewai.project import CrewBase, agent, crew, task
|
||||
from crewai.agents.agent_builder.base_agent import BaseAgent
|
||||
from typing import List
|
||||
|
||||
@CrewBase
|
||||
class ContentCrew():
|
||||
"""Content writing crew"""
|
||||
|
||||
agents: List[BaseAgent]
|
||||
tasks: List[Task]
|
||||
|
||||
@agent
|
||||
def content_writer(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['content_writer'], # type: ignore[index]
|
||||
verbose=True
|
||||
)
|
||||
|
||||
@agent
|
||||
def content_reviewer(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['content_reviewer'], # type: ignore[index]
|
||||
verbose=True
|
||||
)
|
||||
|
||||
@task
|
||||
def write_section_task(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['write_section_task'] # type: ignore[index]
|
||||
)
|
||||
|
||||
@task
|
||||
def review_section_task(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['review_section_task'], # type: ignore[index]
|
||||
context=[self.write_section_task()]
|
||||
)
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
"""Creates the content writing crew"""
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True,
|
||||
)
|
||||
```
|
||||
|
||||
This crew definition establishes the relationship between our agents and tasks, setting up a sequential process where the content writer creates a draft and then the reviewer improves it. While this crew can function independently, in our flow it will be orchestrated as part of a larger system.
|
||||
|
||||
## Step 5: Create the Flow
|
||||
|
||||
Now comes the exciting part - creating the flow that will orchestrate the entire guide creation process. This is where we'll combine regular Python code, direct LLM calls, and our content creation crew into a cohesive system.
|
||||
|
||||
Our flow will:
|
||||
1. Get user input for a topic and audience level
|
||||
2. Make a direct LLM call to create a structured guide outline
|
||||
3. Process each section sequentially using the content writer crew
|
||||
4. Combine everything into a final comprehensive document
|
||||
|
||||
Let's create our flow in the `main.py` file:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python
|
||||
import json
|
||||
import os
|
||||
from typing import List, Dict
|
||||
from pydantic import BaseModel, Field
|
||||
from crewai import LLM
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from guide_creator_flow.crews.content_crew.content_crew import ContentCrew
|
||||
|
||||
# Define our models for structured data
|
||||
class Section(BaseModel):
|
||||
title: str = Field(description="Title of the section")
|
||||
description: str = Field(description="Brief description of what the section should cover")
|
||||
|
||||
class GuideOutline(BaseModel):
|
||||
title: str = Field(description="Title of the guide")
|
||||
introduction: str = Field(description="Introduction to the topic")
|
||||
target_audience: str = Field(description="Description of the target audience")
|
||||
sections: List[Section] = Field(description="List of sections in the guide")
|
||||
conclusion: str = Field(description="Conclusion or summary of the guide")
|
||||
|
||||
# Define our flow state
|
||||
class GuideCreatorState(BaseModel):
|
||||
topic: str = ""
|
||||
audience_level: str = ""
|
||||
guide_outline: GuideOutline = None
|
||||
sections_content: Dict[str, str] = {}
|
||||
|
||||
class GuideCreatorFlow(Flow[GuideCreatorState]):
|
||||
"""Flow for creating a comprehensive guide on any topic"""
|
||||
|
||||
@start()
|
||||
def get_user_input(self):
|
||||
"""Get input from the user about the guide topic and audience"""
|
||||
print("\n=== Create Your Comprehensive Guide ===\n")
|
||||
|
||||
# Get user input
|
||||
self.state.topic = input("What topic would you like to create a guide for? ")
|
||||
|
||||
# Get audience level with validation
|
||||
while True:
|
||||
audience = input("Who is your target audience? (beginner/intermediate/advanced) ").lower()
|
||||
if audience in ["beginner", "intermediate", "advanced"]:
|
||||
self.state.audience_level = audience
|
||||
break
|
||||
print("Please enter 'beginner', 'intermediate', or 'advanced'")
|
||||
|
||||
print(f"\nCreating a guide on {self.state.topic} for {self.state.audience_level} audience...\n")
|
||||
return self.state
|
||||
|
||||
@listen(get_user_input)
|
||||
def create_guide_outline(self, state):
|
||||
"""Create a structured outline for the guide using a direct LLM call"""
|
||||
print("Creating guide outline...")
|
||||
|
||||
# Initialize the LLM
|
||||
llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline)
|
||||
|
||||
# Create the messages for the outline
|
||||
messages = [
|
||||
{"role": "system", "content": "You are a helpful assistant designed to output JSON."},
|
||||
{"role": "user", "content": f"""
|
||||
Create a detailed outline for a comprehensive guide on "{state.topic}" for {state.audience_level} level learners.
|
||||
|
||||
The outline should include:
|
||||
1. A compelling title for the guide
|
||||
2. An introduction to the topic
|
||||
3. 4-6 main sections that cover the most important aspects of the topic
|
||||
4. A conclusion or summary
|
||||
|
||||
For each section, provide a clear title and a brief description of what it should cover.
|
||||
"""}
|
||||
]
|
||||
|
||||
# Make the LLM call with JSON response format
|
||||
response = llm.call(messages=messages)
|
||||
|
||||
# Parse the JSON response
|
||||
outline_dict = json.loads(response)
|
||||
self.state.guide_outline = GuideOutline(**outline_dict)
|
||||
|
||||
# Ensure output directory exists before saving
|
||||
os.makedirs("output", exist_ok=True)
|
||||
|
||||
# Save the outline to a file
|
||||
with open("output/guide_outline.json", "w") as f:
|
||||
json.dump(outline_dict, f, indent=2)
|
||||
|
||||
print(f"Guide outline created with {len(self.state.guide_outline.sections)} sections")
|
||||
return self.state.guide_outline
|
||||
|
||||
@listen(create_guide_outline)
|
||||
def write_and_compile_guide(self, outline):
|
||||
"""Write all sections and compile the guide"""
|
||||
print("Writing guide sections and compiling...")
|
||||
completed_sections = []
|
||||
|
||||
# Process sections one by one to maintain context flow
|
||||
for section in outline.sections:
|
||||
print(f"Processing section: {section.title}")
|
||||
|
||||
# Build context from previous sections
|
||||
previous_sections_text = ""
|
||||
if completed_sections:
|
||||
previous_sections_text = "# Previously Written Sections\n\n"
|
||||
for title in completed_sections:
|
||||
previous_sections_text += f"## {title}\n\n"
|
||||
previous_sections_text += self.state.sections_content.get(title, "") + "\n\n"
|
||||
else:
|
||||
previous_sections_text = "No previous sections written yet."
|
||||
|
||||
# Run the content crew for this section
|
||||
result = ContentCrew().crew().kickoff(inputs={
|
||||
"section_title": section.title,
|
||||
"section_description": section.description,
|
||||
"audience_level": self.state.audience_level,
|
||||
"previous_sections": previous_sections_text,
|
||||
"draft_content": ""
|
||||
})
|
||||
|
||||
# Store the content
|
||||
self.state.sections_content[section.title] = result.raw
|
||||
completed_sections.append(section.title)
|
||||
print(f"Section completed: {section.title}")
|
||||
|
||||
# Compile the final guide
|
||||
guide_content = f"# {outline.title}\n\n"
|
||||
guide_content += f"## Introduction\n\n{outline.introduction}\n\n"
|
||||
|
||||
# Add each section in order
|
||||
for section in outline.sections:
|
||||
section_content = self.state.sections_content.get(section.title, "")
|
||||
guide_content += f"\n\n{section_content}\n\n"
|
||||
|
||||
# Add conclusion
|
||||
guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
|
||||
|
||||
# Save the guide
|
||||
with open("output/complete_guide.md", "w") as f:
|
||||
f.write(guide_content)
|
||||
|
||||
print("\nComplete guide compiled and saved to output/complete_guide.md")
|
||||
return "Guide creation completed successfully"
|
||||
|
||||
def kickoff():
|
||||
"""Run the guide creator flow"""
|
||||
GuideCreatorFlow().kickoff()
|
||||
print("\n=== Flow Complete ===")
|
||||
print("Your comprehensive guide is ready in the output directory.")
|
||||
print("Open output/complete_guide.md to view it.")
|
||||
|
||||
def plot():
|
||||
"""Generate a visualization of the flow"""
|
||||
flow = GuideCreatorFlow()
|
||||
flow.plot("guide_creator_flow")
|
||||
print("Flow visualization saved to guide_creator_flow.html")
|
||||
|
||||
if __name__ == "__main__":
|
||||
kickoff()
|
||||
```
|
||||
|
||||
Let's analyze what's happening in this flow:
|
||||
|
||||
1. We define Pydantic models for structured data, ensuring type safety and clear data representation
|
||||
2. We create a state class to maintain data across different steps of the flow
|
||||
3. We implement three main flow steps:
|
||||
- Getting user input with the `@start()` decorator
|
||||
- Creating a guide outline with a direct LLM call
|
||||
- Processing sections with our content crew
|
||||
4. We use the `@listen()` decorator to establish event-driven relationships between steps
|
||||
|
||||
This is the power of flows - combining different types of processing (user interaction, direct LLM calls, crew-based tasks) into a coherent, event-driven system.
|
||||
|
||||
## Step 6: Set Up Your Environment Variables
|
||||
|
||||
Create a `.env` file in your project root with your API keys. See the [LLM setup
|
||||
guide](/en/concepts/llms#setting-up-your-llm) for details on configuring a provider.
|
||||
|
||||
```sh .env
|
||||
OPENAI_API_KEY=your_openai_api_key
|
||||
# or
|
||||
GEMINI_API_KEY=your_gemini_api_key
|
||||
# or
|
||||
ANTHROPIC_API_KEY=your_anthropic_api_key
|
||||
```
|
||||
|
||||
## Step 7: Install Dependencies
|
||||
|
||||
Install the required dependencies:
|
||||
|
||||
```bash
|
||||
crewai install
|
||||
```
|
||||
|
||||
## Step 8: Run Your Flow
|
||||
|
||||
Now it's time to see your flow in action! Run it using the CrewAI CLI:
|
||||
|
||||
```bash
|
||||
crewai flow kickoff
|
||||
```
|
||||
|
||||
When you run this command, you'll see your flow spring to life:
|
||||
1. It will prompt you for a topic and audience level
|
||||
2. It will create a structured outline for your guide
|
||||
3. It will process each section, with the content writer and reviewer collaborating on each
|
||||
4. Finally, it will compile everything into a comprehensive guide
|
||||
|
||||
This demonstrates the power of flows to orchestrate complex processes involving multiple components, both AI and non-AI.
|
||||
|
||||
## Step 9: Visualize Your Flow
|
||||
|
||||
One of the powerful features of flows is the ability to visualize their structure:
|
||||
|
||||
```bash
|
||||
crewai flow plot
|
||||
```
|
||||
|
||||
This will create an HTML file that shows the structure of your flow, including the relationships between different steps and the data that flows between them. This visualization can be invaluable for understanding and debugging complex flows.
|
||||
|
||||
## Step 10: Review the Output
|
||||
|
||||
Once the flow completes, you'll find two files in the `output` directory:
|
||||
|
||||
1. `guide_outline.json`: Contains the structured outline of the guide
|
||||
2. `complete_guide.md`: The comprehensive guide with all sections
|
||||
|
||||
Take a moment to review these files and appreciate what you've built - a system that combines user input, direct AI interactions, and collaborative agent work to produce a complex, high-quality output.
|
||||
|
||||
## The Art of the Possible: Beyond Your First Flow
|
||||
|
||||
What you've learned in this guide provides a foundation for creating much more sophisticated AI systems. Here are some ways you could extend this basic flow:
|
||||
|
||||
### Enhancing User Interaction
|
||||
|
||||
You could create more interactive flows with:
|
||||
- Web interfaces for input and output
|
||||
- Real-time progress updates
|
||||
- Interactive feedback and refinement loops
|
||||
- Multi-stage user interactions
|
||||
|
||||
### Adding More Processing Steps
|
||||
|
||||
You could expand your flow with additional steps for:
|
||||
- Research before outline creation
|
||||
- Image generation for illustrations
|
||||
- Code snippet generation for technical guides
|
||||
- Final quality assurance and fact-checking
|
||||
|
||||
### Creating More Complex Flows
|
||||
|
||||
You could implement more sophisticated flow patterns:
|
||||
- Conditional branching based on user preferences or content type
|
||||
- Parallel processing of independent sections
|
||||
- Iterative refinement loops with feedback
|
||||
- Integration with external APIs and services
|
||||
|
||||
### Applying to Different Domains
|
||||
|
||||
The same patterns can be applied to create flows for:
|
||||
- **Interactive storytelling**: Create personalized stories based on user input
|
||||
- **Business intelligence**: Process data, generate insights, and create reports
|
||||
- **Product development**: Facilitate ideation, design, and planning
|
||||
- **Educational systems**: Create personalized learning experiences
|
||||
|
||||
## Key Features Demonstrated
|
||||
|
||||
This guide creator flow demonstrates several powerful features of CrewAI:
|
||||
|
||||
1. **User interaction**: The flow collects input directly from the user
|
||||
2. **Direct LLM calls**: Uses the LLM class for efficient, single-purpose AI interactions
|
||||
3. **Structured data with Pydantic**: Uses Pydantic models to ensure type safety
|
||||
4. **Sequential processing with context**: Writes sections in order, providing previous sections for context
|
||||
5. **Multi-agent crews**: Leverages specialized agents (writer and reviewer) for content creation
|
||||
6. **State management**: Maintains state across different steps of the process
|
||||
7. **Event-driven architecture**: Uses the `@listen` decorator to respond to events
|
||||
|
||||
## Understanding the Flow Structure
|
||||
|
||||
Let's break down the key components of flows to help you understand how to build your own:
|
||||
|
||||
### 1. Direct LLM Calls
|
||||
|
||||
Flows allow you to make direct calls to language models when you need simple, structured responses:
|
||||
|
||||
```python
|
||||
llm = LLM(
|
||||
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
response_format=GuideOutline
|
||||
)
|
||||
response = llm.call(messages=messages)
|
||||
```
|
||||
|
||||
This is more efficient than using a crew when you need a specific, structured output.
|
||||
|
||||
### 2. Event-Driven Architecture
|
||||
|
||||
Flows use decorators to establish relationships between components:
|
||||
|
||||
```python
|
||||
@start()
|
||||
def get_user_input(self):
|
||||
# First step in the flow
|
||||
# ...
|
||||
|
||||
@listen(get_user_input)
|
||||
def create_guide_outline(self, state):
|
||||
# This runs when get_user_input completes
|
||||
# ...
|
||||
```
|
||||
|
||||
This creates a clear, declarative structure for your application.
|
||||
|
||||
### 3. State Management
|
||||
|
||||
Flows maintain state across steps, making it easy to share data:
|
||||
|
||||
```python
|
||||
class GuideCreatorState(BaseModel):
|
||||
topic: str = ""
|
||||
audience_level: str = ""
|
||||
guide_outline: GuideOutline = None
|
||||
sections_content: Dict[str, str] = {}
|
||||
```
|
||||
|
||||
This provides a type-safe way to track and transform data throughout your flow.
|
||||
|
||||
### 4. Crew Integration
|
||||
|
||||
Flows can seamlessly integrate with crews for complex collaborative tasks:
|
||||
|
||||
```python
|
||||
result = ContentCrew().crew().kickoff(inputs={
|
||||
"section_title": section.title,
|
||||
# ...
|
||||
})
|
||||
```
|
||||
|
||||
This allows you to use the right tool for each part of your application - direct LLM calls for simple tasks and crews for complex collaboration.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you've built your first flow, you can:
|
||||
|
||||
1. Experiment with more complex flow structures and patterns
|
||||
2. Try using `@router()` to create conditional branches in your flows
|
||||
3. Explore the `and_` and `or_` functions for more complex parallel execution
|
||||
4. Connect your flow to external APIs, databases, or user interfaces
|
||||
5. Combine multiple specialized crews in a single flow
|
||||
|
||||
<Check>
|
||||
Congratulations! You've successfully built your first CrewAI Flow that combines regular code, direct LLM calls, and crew-based processing to create a comprehensive guide. These foundational skills enable you to create increasingly sophisticated AI applications that can tackle complex, multi-stage problems through a combination of procedural control and collaborative intelligence.
|
||||
</Check>
|
||||
771
docs/en/guides/flows/mastering-flow-state.mdx
Normal file
771
docs/en/guides/flows/mastering-flow-state.mdx
Normal file
@@ -0,0 +1,771 @@
|
||||
---
|
||||
title: Mastering Flow State Management
|
||||
description: A comprehensive guide to managing, persisting, and leveraging state in CrewAI Flows for building robust AI applications.
|
||||
icon: diagram-project
|
||||
---
|
||||
|
||||
## Understanding the Power of State in Flows
|
||||
|
||||
State management is the backbone of any sophisticated AI workflow. In CrewAI Flows, the state system allows you to maintain context, share data between steps, and build complex application logic. Mastering state management is essential for creating reliable, maintainable, and powerful AI applications.
|
||||
|
||||
This guide will walk you through everything you need to know about managing state in CrewAI Flows, from basic concepts to advanced techniques, with practical code examples along the way.
|
||||
|
||||
### Why State Management Matters
|
||||
|
||||
Effective state management enables you to:
|
||||
|
||||
1. **Maintain context across execution steps** - Pass information seamlessly between different stages of your workflow
|
||||
2. **Build complex conditional logic** - Make decisions based on accumulated data
|
||||
3. **Create persistent applications** - Save and restore workflow progress
|
||||
4. **Handle errors gracefully** - Implement recovery patterns for more robust applications
|
||||
5. **Scale your applications** - Support complex workflows with proper data organization
|
||||
6. **Enable conversational applications** - Store and access conversation history for context-aware AI interactions
|
||||
|
||||
Let's explore how to leverage these capabilities effectively.
|
||||
|
||||
## State Management Fundamentals
|
||||
|
||||
### The Flow State Lifecycle
|
||||
|
||||
In CrewAI Flows, the state follows a predictable lifecycle:
|
||||
|
||||
1. **Initialization** - When a flow is created, its state is initialized (either as an empty dictionary or a Pydantic model instance)
|
||||
2. **Modification** - Flow methods access and modify the state as they execute
|
||||
3. **Transmission** - State is passed automatically between flow methods
|
||||
4. **Persistence** (optional) - State can be saved to storage and later retrieved
|
||||
5. **Completion** - The final state reflects the cumulative changes from all executed methods
|
||||
|
||||
Understanding this lifecycle is crucial for designing effective flows.
|
||||
|
||||
### Two Approaches to State Management
|
||||
|
||||
CrewAI offers two ways to manage state in your flows:
|
||||
|
||||
1. **Unstructured State** - Using dictionary-like objects for flexibility
|
||||
2. **Structured State** - Using Pydantic models for type safety and validation
|
||||
|
||||
Let's examine each approach in detail.
|
||||
|
||||
## Unstructured State Management
|
||||
|
||||
Unstructured state uses a dictionary-like approach, offering flexibility and simplicity for straightforward applications.
|
||||
|
||||
### How It Works
|
||||
|
||||
With unstructured state:
|
||||
- You access state via `self.state` which behaves like a dictionary
|
||||
- You can freely add, modify, or remove keys at any point
|
||||
- All state is automatically available to all flow methods
|
||||
|
||||
### Basic Example
|
||||
|
||||
Here's a simple example of unstructured state management:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
|
||||
class UnstructuredStateFlow(Flow):
|
||||
@start()
|
||||
def initialize_data(self):
|
||||
print("Initializing flow data")
|
||||
# Add key-value pairs to state
|
||||
self.state["user_name"] = "Alex"
|
||||
self.state["preferences"] = {
|
||||
"theme": "dark",
|
||||
"language": "English"
|
||||
}
|
||||
self.state["items"] = []
|
||||
|
||||
# The flow state automatically gets a unique ID
|
||||
print(f"Flow ID: {self.state['id']}")
|
||||
|
||||
return "Initialized"
|
||||
|
||||
@listen(initialize_data)
|
||||
def process_data(self, previous_result):
|
||||
print(f"Previous step returned: {previous_result}")
|
||||
|
||||
# Access and modify state
|
||||
user = self.state["user_name"]
|
||||
print(f"Processing data for {user}")
|
||||
|
||||
# Add items to a list in state
|
||||
self.state["items"].append("item1")
|
||||
self.state["items"].append("item2")
|
||||
|
||||
# Add a new key-value pair
|
||||
self.state["processed"] = True
|
||||
|
||||
return "Processed"
|
||||
|
||||
@listen(process_data)
|
||||
def generate_summary(self, previous_result):
|
||||
# Access multiple state values
|
||||
user = self.state["user_name"]
|
||||
theme = self.state["preferences"]["theme"]
|
||||
items = self.state["items"]
|
||||
processed = self.state.get("processed", False)
|
||||
|
||||
summary = f"User {user} has {len(items)} items with {theme} theme. "
|
||||
summary += "Data is processed." if processed else "Data is not processed."
|
||||
|
||||
return summary
|
||||
|
||||
# Run the flow
|
||||
flow = UnstructuredStateFlow()
|
||||
result = flow.kickoff()
|
||||
print(f"Final result: {result}")
|
||||
print(f"Final state: {flow.state}")
|
||||
```
|
||||
|
||||
### When to Use Unstructured State
|
||||
|
||||
Unstructured state is ideal for:
|
||||
- Quick prototyping and simple flows
|
||||
- Dynamically evolving state needs
|
||||
- Cases where the structure may not be known in advance
|
||||
- Flows with simple state requirements
|
||||
|
||||
While flexible, unstructured state lacks type checking and schema validation, which can lead to errors in complex applications.
|
||||
|
||||
## Structured State Management
|
||||
|
||||
Structured state uses Pydantic models to define a schema for your flow's state, providing type safety, validation, and better developer experience.
|
||||
|
||||
### How It Works
|
||||
|
||||
With structured state:
|
||||
- You define a Pydantic model that represents your state structure
|
||||
- You pass this model type to your Flow class as a type parameter
|
||||
- You access state via `self.state`, which behaves like a Pydantic model instance
|
||||
- All fields are validated according to their defined types
|
||||
- You get IDE autocompletion and type checking support
|
||||
|
||||
### Basic Example
|
||||
|
||||
Here's how to implement structured state management:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Dict, Optional
|
||||
|
||||
# Define your state model
|
||||
class UserPreferences(BaseModel):
|
||||
theme: str = "light"
|
||||
language: str = "English"
|
||||
|
||||
class AppState(BaseModel):
|
||||
user_name: str = ""
|
||||
preferences: UserPreferences = UserPreferences()
|
||||
items: List[str] = []
|
||||
processed: bool = False
|
||||
completion_percentage: float = 0.0
|
||||
|
||||
# Create a flow with typed state
|
||||
class StructuredStateFlow(Flow[AppState]):
|
||||
@start()
|
||||
def initialize_data(self):
|
||||
print("Initializing flow data")
|
||||
# Set state values (type-checked)
|
||||
self.state.user_name = "Taylor"
|
||||
self.state.preferences.theme = "dark"
|
||||
|
||||
# The ID field is automatically available
|
||||
print(f"Flow ID: {self.state.id}")
|
||||
|
||||
return "Initialized"
|
||||
|
||||
@listen(initialize_data)
|
||||
def process_data(self, previous_result):
|
||||
print(f"Processing data for {self.state.user_name}")
|
||||
|
||||
# Modify state (with type checking)
|
||||
self.state.items.append("item1")
|
||||
self.state.items.append("item2")
|
||||
self.state.processed = True
|
||||
self.state.completion_percentage = 50.0
|
||||
|
||||
return "Processed"
|
||||
|
||||
@listen(process_data)
|
||||
def generate_summary(self, previous_result):
|
||||
# Access state (with autocompletion)
|
||||
summary = f"User {self.state.user_name} has {len(self.state.items)} items "
|
||||
summary += f"with {self.state.preferences.theme} theme. "
|
||||
summary += "Data is processed." if self.state.processed else "Data is not processed."
|
||||
summary += f" Completion: {self.state.completion_percentage}%"
|
||||
|
||||
return summary
|
||||
|
||||
# Run the flow
|
||||
flow = StructuredStateFlow()
|
||||
result = flow.kickoff()
|
||||
print(f"Final result: {result}")
|
||||
print(f"Final state: {flow.state}")
|
||||
```
|
||||
|
||||
### Benefits of Structured State
|
||||
|
||||
Using structured state provides several advantages:
|
||||
|
||||
1. **Type Safety** - Catch type errors at development time
|
||||
2. **Self-Documentation** - The state model clearly documents what data is available
|
||||
3. **Validation** - Automatic validation of data types and constraints
|
||||
4. **IDE Support** - Get autocomplete and inline documentation
|
||||
5. **Default Values** - Easily define fallbacks for missing data
|
||||
|
||||
### When to Use Structured State
|
||||
|
||||
Structured state is recommended for:
|
||||
- Complex flows with well-defined data schemas
|
||||
- Team projects where multiple developers work on the same code
|
||||
- Applications where data validation is important
|
||||
- Flows that need to enforce specific data types and constraints
|
||||
|
||||
## The Automatic State ID
|
||||
|
||||
Both unstructured and structured states automatically receive a unique identifier (UUID) to help track and manage state instances.
|
||||
|
||||
### How It Works
|
||||
|
||||
- For unstructured state, the ID is accessible as `self.state["id"]`
|
||||
- For structured state, the ID is accessible as `self.state.id`
|
||||
- This ID is generated automatically when the flow is created
|
||||
- The ID remains the same throughout the flow's lifecycle
|
||||
- The ID can be used for tracking, logging, and retrieving persisted states
|
||||
|
||||
This UUID is particularly valuable when implementing persistence or tracking multiple flow executions.
|
||||
|
||||
## Dynamic State Updates
|
||||
|
||||
Regardless of whether you're using structured or unstructured state, you can update state dynamically throughout your flow's execution.
|
||||
|
||||
### Passing Data Between Steps
|
||||
|
||||
Flow methods can return values that are then passed as arguments to listening methods:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
|
||||
class DataPassingFlow(Flow):
|
||||
@start()
|
||||
def generate_data(self):
|
||||
# This return value will be passed to listening methods
|
||||
return "Generated data"
|
||||
|
||||
@listen(generate_data)
|
||||
def process_data(self, data_from_previous_step):
|
||||
print(f"Received: {data_from_previous_step}")
|
||||
# You can modify the data and pass it along
|
||||
processed_data = f"{data_from_previous_step} - processed"
|
||||
# Also update state
|
||||
self.state["last_processed"] = processed_data
|
||||
return processed_data
|
||||
|
||||
@listen(process_data)
|
||||
def finalize_data(self, processed_data):
|
||||
print(f"Received processed data: {processed_data}")
|
||||
# Access both the passed data and state
|
||||
last_processed = self.state.get("last_processed", "")
|
||||
return f"Final: {processed_data} (from state: {last_processed})"
|
||||
```
|
||||
|
||||
This pattern allows you to combine direct data passing with state updates for maximum flexibility.
|
||||
|
||||
## Persisting Flow State
|
||||
|
||||
One of CrewAI's most powerful features is the ability to persist flow state across executions. This enables workflows that can be paused, resumed, and even recovered after failures.
|
||||
|
||||
### The @persist() Decorator
|
||||
|
||||
The `@persist()` decorator automates state persistence, saving your flow's state at key points in execution.
|
||||
|
||||
#### Class-Level Persistence
|
||||
|
||||
When applied at the class level, `@persist()` saves state after every method execution:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai.flow.persistence import persist
|
||||
from pydantic import BaseModel
|
||||
|
||||
class CounterState(BaseModel):
|
||||
value: int = 0
|
||||
|
||||
@persist() # Apply to the entire flow class
|
||||
class PersistentCounterFlow(Flow[CounterState]):
|
||||
@start()
|
||||
def increment(self):
|
||||
self.state.value += 1
|
||||
print(f"Incremented to {self.state.value}")
|
||||
return self.state.value
|
||||
|
||||
@listen(increment)
|
||||
def double(self, value):
|
||||
self.state.value = value * 2
|
||||
print(f"Doubled to {self.state.value}")
|
||||
return self.state.value
|
||||
|
||||
# First run
|
||||
flow1 = PersistentCounterFlow()
|
||||
result1 = flow1.kickoff()
|
||||
print(f"First run result: {result1}")
|
||||
|
||||
# Second run - state is automatically loaded
|
||||
flow2 = PersistentCounterFlow()
|
||||
result2 = flow2.kickoff()
|
||||
print(f"Second run result: {result2}") # Will be higher due to persisted state
|
||||
```
|
||||
|
||||
#### Method-Level Persistence
|
||||
|
||||
For more granular control, you can apply `@persist()` to specific methods:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai.flow.persistence import persist
|
||||
|
||||
class SelectivePersistFlow(Flow):
|
||||
@start()
|
||||
def first_step(self):
|
||||
self.state["count"] = 1
|
||||
return "First step"
|
||||
|
||||
@persist() # Only persist after this method
|
||||
@listen(first_step)
|
||||
def important_step(self, prev_result):
|
||||
self.state["count"] += 1
|
||||
self.state["important_data"] = "This will be persisted"
|
||||
return "Important step completed"
|
||||
|
||||
@listen(important_step)
|
||||
def final_step(self, prev_result):
|
||||
self.state["count"] += 1
|
||||
return f"Complete with count {self.state['count']}"
|
||||
```
|
||||
|
||||
|
||||
## Advanced State Patterns
|
||||
|
||||
### State-Based Conditional Logic
|
||||
|
||||
You can use state to implement complex conditional logic in your flows:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, router, start
|
||||
from pydantic import BaseModel
|
||||
|
||||
class PaymentState(BaseModel):
|
||||
amount: float = 0.0
|
||||
is_approved: bool = False
|
||||
retry_count: int = 0
|
||||
|
||||
class PaymentFlow(Flow[PaymentState]):
|
||||
@start()
|
||||
def process_payment(self):
|
||||
# Simulate payment processing
|
||||
self.state.amount = 100.0
|
||||
self.state.is_approved = self.state.amount < 1000
|
||||
return "Payment processed"
|
||||
|
||||
@router(process_payment)
|
||||
def check_approval(self, previous_result):
|
||||
if self.state.is_approved:
|
||||
return "approved"
|
||||
elif self.state.retry_count < 3:
|
||||
return "retry"
|
||||
else:
|
||||
return "rejected"
|
||||
|
||||
@listen("approved")
|
||||
def handle_approval(self):
|
||||
return f"Payment of ${self.state.amount} approved!"
|
||||
|
||||
@listen("retry")
|
||||
def handle_retry(self):
|
||||
self.state.retry_count += 1
|
||||
print(f"Retrying payment (attempt {self.state.retry_count})...")
|
||||
# Could implement retry logic here
|
||||
return "Retry initiated"
|
||||
|
||||
@listen("rejected")
|
||||
def handle_rejection(self):
|
||||
return f"Payment of ${self.state.amount} rejected after {self.state.retry_count} retries."
|
||||
```
|
||||
|
||||
### Handling Complex State Transformations
|
||||
|
||||
For complex state transformations, you can create dedicated methods:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
|
||||
class UserData(BaseModel):
|
||||
name: str
|
||||
active: bool = True
|
||||
login_count: int = 0
|
||||
|
||||
class ComplexState(BaseModel):
|
||||
users: Dict[str, UserData] = {}
|
||||
active_user_count: int = 0
|
||||
|
||||
class TransformationFlow(Flow[ComplexState]):
|
||||
@start()
|
||||
def initialize(self):
|
||||
# Add some users
|
||||
self.add_user("alice", "Alice")
|
||||
self.add_user("bob", "Bob")
|
||||
self.add_user("charlie", "Charlie")
|
||||
return "Initialized"
|
||||
|
||||
@listen(initialize)
|
||||
def process_users(self, _):
|
||||
# Increment login counts
|
||||
for user_id in self.state.users:
|
||||
self.increment_login(user_id)
|
||||
|
||||
# Deactivate one user
|
||||
self.deactivate_user("bob")
|
||||
|
||||
# Update active count
|
||||
self.update_active_count()
|
||||
|
||||
return f"Processed {len(self.state.users)} users"
|
||||
|
||||
# Helper methods for state transformations
|
||||
def add_user(self, user_id: str, name: str):
|
||||
self.state.users[user_id] = UserData(name=name)
|
||||
self.update_active_count()
|
||||
|
||||
def increment_login(self, user_id: str):
|
||||
if user_id in self.state.users:
|
||||
self.state.users[user_id].login_count += 1
|
||||
|
||||
def deactivate_user(self, user_id: str):
|
||||
if user_id in self.state.users:
|
||||
self.state.users[user_id].active = False
|
||||
self.update_active_count()
|
||||
|
||||
def update_active_count(self):
|
||||
self.state.active_user_count = sum(
|
||||
1 for user in self.state.users.values() if user.active
|
||||
)
|
||||
```
|
||||
|
||||
This pattern of creating helper methods keeps your flow methods clean while enabling complex state manipulations.
|
||||
|
||||
## State Management with Crews
|
||||
|
||||
One of the most powerful patterns in CrewAI is combining flow state management with crew execution.
|
||||
|
||||
### Passing State to Crews
|
||||
|
||||
You can use flow state to parameterize crews:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Process, Task
|
||||
from pydantic import BaseModel
|
||||
|
||||
class ResearchState(BaseModel):
|
||||
topic: str = ""
|
||||
depth: str = "medium"
|
||||
results: str = ""
|
||||
|
||||
class ResearchFlow(Flow[ResearchState]):
|
||||
@start()
|
||||
def get_parameters(self):
|
||||
# In a real app, this might come from user input
|
||||
self.state.topic = "Artificial Intelligence Ethics"
|
||||
self.state.depth = "deep"
|
||||
return "Parameters set"
|
||||
|
||||
@listen(get_parameters)
|
||||
def execute_research(self, _):
|
||||
# Create agents
|
||||
researcher = Agent(
|
||||
role="Research Specialist",
|
||||
goal=f"Research {self.state.topic} in {self.state.depth} detail",
|
||||
backstory="You are an expert researcher with a talent for finding accurate information."
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role="Content Writer",
|
||||
goal="Transform research into clear, engaging content",
|
||||
backstory="You excel at communicating complex ideas clearly and concisely."
|
||||
)
|
||||
|
||||
# Create tasks
|
||||
research_task = Task(
|
||||
description=f"Research {self.state.topic} with {self.state.depth} analysis",
|
||||
expected_output="Comprehensive research notes in markdown format",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description=f"Create a summary on {self.state.topic} based on the research",
|
||||
expected_output="Well-written article in markdown format",
|
||||
agent=writer,
|
||||
context=[research_task]
|
||||
)
|
||||
|
||||
# Create and run crew
|
||||
research_crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, writing_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run crew and store result in state
|
||||
result = research_crew.kickoff()
|
||||
self.state.results = result.raw
|
||||
|
||||
return "Research completed"
|
||||
|
||||
@listen(execute_research)
|
||||
def summarize_results(self, _):
|
||||
# Access the stored results
|
||||
result_length = len(self.state.results)
|
||||
return f"Research on {self.state.topic} completed with {result_length} characters of results."
|
||||
```
|
||||
|
||||
### Handling Crew Outputs in State
|
||||
|
||||
When a crew completes, you can process its output and store it in your flow state:
|
||||
|
||||
```python
|
||||
@listen(execute_crew)
|
||||
def process_crew_results(self, _):
|
||||
# Parse the raw results (assuming JSON output)
|
||||
import json
|
||||
try:
|
||||
results_dict = json.loads(self.state.raw_results)
|
||||
self.state.processed_results = {
|
||||
"title": results_dict.get("title", ""),
|
||||
"main_points": results_dict.get("main_points", []),
|
||||
"conclusion": results_dict.get("conclusion", "")
|
||||
}
|
||||
return "Results processed successfully"
|
||||
except json.JSONDecodeError:
|
||||
self.state.error = "Failed to parse crew results as JSON"
|
||||
return "Error processing results"
|
||||
```
|
||||
|
||||
## Best Practices for State Management
|
||||
|
||||
### 1. Keep State Focused
|
||||
|
||||
Design your state to contain only what's necessary:
|
||||
|
||||
```python
|
||||
# Too broad
|
||||
class BloatedState(BaseModel):
|
||||
user_data: Dict = {}
|
||||
system_settings: Dict = {}
|
||||
temporary_calculations: List = []
|
||||
debug_info: Dict = {}
|
||||
# ...many more fields
|
||||
|
||||
# Better: Focused state
|
||||
class FocusedState(BaseModel):
|
||||
user_id: str
|
||||
preferences: Dict[str, str]
|
||||
completion_status: Dict[str, bool]
|
||||
```
|
||||
|
||||
### 2. Use Structured State for Complex Flows
|
||||
|
||||
As your flows grow in complexity, structured state becomes increasingly valuable:
|
||||
|
||||
```python
|
||||
# Simple flow can use unstructured state
|
||||
class SimpleGreetingFlow(Flow):
|
||||
@start()
|
||||
def greet(self):
|
||||
self.state["name"] = "World"
|
||||
return f"Hello, {self.state['name']}!"
|
||||
|
||||
# Complex flow benefits from structured state
|
||||
class UserRegistrationState(BaseModel):
|
||||
username: str
|
||||
email: str
|
||||
verification_status: bool = False
|
||||
registration_date: datetime = Field(default_factory=datetime.now)
|
||||
last_login: Optional[datetime] = None
|
||||
|
||||
class RegistrationFlow(Flow[UserRegistrationState]):
|
||||
# Methods with strongly-typed state access
|
||||
```
|
||||
|
||||
### 3. Document State Transitions
|
||||
|
||||
For complex flows, document how state changes throughout the execution:
|
||||
|
||||
```python
|
||||
@start()
|
||||
def initialize_order(self):
|
||||
"""
|
||||
Initialize order state with empty values.
|
||||
|
||||
State before: {}
|
||||
State after: {order_id: str, items: [], status: 'new'}
|
||||
"""
|
||||
self.state.order_id = str(uuid.uuid4())
|
||||
self.state.items = []
|
||||
self.state.status = "new"
|
||||
return "Order initialized"
|
||||
```
|
||||
|
||||
### 4. Handle State Errors Gracefully
|
||||
|
||||
Implement error handling for state access:
|
||||
|
||||
```python
|
||||
@listen(previous_step)
|
||||
def process_data(self, _):
|
||||
try:
|
||||
# Try to access a value that might not exist
|
||||
user_preference = self.state.preferences.get("theme", "default")
|
||||
except (AttributeError, KeyError):
|
||||
# Handle the error gracefully
|
||||
self.state.errors = self.state.get("errors", [])
|
||||
self.state.errors.append("Failed to access preferences")
|
||||
user_preference = "default"
|
||||
|
||||
return f"Used preference: {user_preference}"
|
||||
```
|
||||
|
||||
### 5. Use State for Progress Tracking
|
||||
|
||||
Leverage state to track progress in long-running flows:
|
||||
|
||||
```python
|
||||
class ProgressTrackingFlow(Flow):
|
||||
@start()
|
||||
def initialize(self):
|
||||
self.state["total_steps"] = 3
|
||||
self.state["current_step"] = 0
|
||||
self.state["progress"] = 0.0
|
||||
self.update_progress()
|
||||
return "Initialized"
|
||||
|
||||
def update_progress(self):
|
||||
"""Helper method to calculate and update progress"""
|
||||
if self.state.get("total_steps", 0) > 0:
|
||||
self.state["progress"] = (self.state.get("current_step", 0) /
|
||||
self.state["total_steps"]) * 100
|
||||
print(f"Progress: {self.state['progress']:.1f}%")
|
||||
|
||||
@listen(initialize)
|
||||
def step_one(self, _):
|
||||
# Do work...
|
||||
self.state["current_step"] = 1
|
||||
self.update_progress()
|
||||
return "Step 1 complete"
|
||||
|
||||
# Additional steps...
|
||||
```
|
||||
|
||||
### 6. Use Immutable Operations When Possible
|
||||
|
||||
Especially with structured state, prefer immutable operations for clarity:
|
||||
|
||||
```python
|
||||
# Instead of modifying lists in place:
|
||||
self.state.items.append(new_item) # Mutable operation
|
||||
|
||||
# Consider creating new state:
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
|
||||
class ItemState(BaseModel):
|
||||
items: List[str] = []
|
||||
|
||||
class ImmutableFlow(Flow[ItemState]):
|
||||
@start()
|
||||
def add_item(self):
|
||||
# Create new list with the added item
|
||||
self.state.items = [*self.state.items, "new item"]
|
||||
return "Item added"
|
||||
```
|
||||
|
||||
## Debugging Flow State
|
||||
|
||||
### Logging State Changes
|
||||
|
||||
When developing, add logging to track state changes:
|
||||
|
||||
```python
|
||||
import logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
class LoggingFlow(Flow):
|
||||
def log_state(self, step_name):
|
||||
logging.info(f"State after {step_name}: {self.state}")
|
||||
|
||||
@start()
|
||||
def initialize(self):
|
||||
self.state["counter"] = 0
|
||||
self.log_state("initialize")
|
||||
return "Initialized"
|
||||
|
||||
@listen(initialize)
|
||||
def increment(self, _):
|
||||
self.state["counter"] += 1
|
||||
self.log_state("increment")
|
||||
return f"Incremented to {self.state['counter']}"
|
||||
```
|
||||
|
||||
### State Visualization
|
||||
|
||||
You can add methods to visualize your state for debugging:
|
||||
|
||||
```python
|
||||
def visualize_state(self):
|
||||
"""Create a simple visualization of the current state"""
|
||||
import json
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
|
||||
console = Console()
|
||||
|
||||
if hasattr(self.state, "model_dump"):
|
||||
# Pydantic v2
|
||||
state_dict = self.state.model_dump()
|
||||
elif hasattr(self.state, "dict"):
|
||||
# Pydantic v1
|
||||
state_dict = self.state.dict()
|
||||
else:
|
||||
# Unstructured state
|
||||
state_dict = dict(self.state)
|
||||
|
||||
# Remove id for cleaner output
|
||||
if "id" in state_dict:
|
||||
state_dict.pop("id")
|
||||
|
||||
state_json = json.dumps(state_dict, indent=2, default=str)
|
||||
console.print(Panel(state_json, title="Current Flow State"))
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
Mastering state management in CrewAI Flows gives you the power to build sophisticated, robust AI applications that maintain context, make complex decisions, and deliver consistent results.
|
||||
|
||||
Whether you choose unstructured or structured state, implementing proper state management practices will help you create flows that are maintainable, extensible, and effective at solving real-world problems.
|
||||
|
||||
As you develop more complex flows, remember that good state management is about finding the right balance between flexibility and structure, making your code both powerful and easy to understand.
|
||||
|
||||
<Check>
|
||||
You've now mastered the concepts and practices of state management in CrewAI Flows! With this knowledge, you can create robust AI workflows that effectively maintain context, share data between steps, and build sophisticated application logic.
|
||||
</Check>
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Experiment with both structured and unstructured state in your flows
|
||||
- Try implementing state persistence for long-running workflows
|
||||
- Explore [building your first crew](/en/guides/crews/first-crew) to see how crews and flows can work together
|
||||
- Check out the [Flow reference documentation](/en/concepts/flows) for more advanced features
|
||||
198
docs/en/installation.mdx
Normal file
198
docs/en/installation.mdx
Normal file
@@ -0,0 +1,198 @@
|
||||
---
|
||||
title: Installation
|
||||
description: Get started with CrewAI - Install, configure, and build your first AI crew
|
||||
icon: wrench
|
||||
---
|
||||
|
||||
## Video Tutorial
|
||||
Watch this video tutorial for a step-by-step demonstration of the installation process:
|
||||
|
||||
<iframe
|
||||
width="100%"
|
||||
height="400"
|
||||
src="https://www.youtube.com/embed/-kSOTtYzgEw"
|
||||
title="CrewAI Installation Guide"
|
||||
frameborder="0"
|
||||
style={{ borderRadius: '10px' }}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
|
||||
## Text Tutorial
|
||||
<Note>
|
||||
**Python Version Requirements**
|
||||
|
||||
CrewAI requires `Python >=3.10 and <3.14`. Here's how to check your version:
|
||||
```bash
|
||||
python3 --version
|
||||
```
|
||||
|
||||
If you need to update Python, visit [python.org/downloads](https://python.org/downloads)
|
||||
</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**.
|
||||
|
||||
<Steps>
|
||||
<Step title="Install uv">
|
||||
- **On macOS/Linux:**
|
||||
|
||||
Use `curl` to download the script and execute it with `sh`:
|
||||
|
||||
```shell
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
If your system doesn't have `curl`, you can use `wget`:
|
||||
|
||||
```shell
|
||||
wget -qO- https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
- **On Windows:**
|
||||
|
||||
Use `irm` to download the script and `iex` to execute it:
|
||||
|
||||
```shell
|
||||
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
|
||||
```
|
||||
If you run into any issues, refer to [UV's installation guide](https://docs.astral.sh/uv/getting-started/installation/) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Install CrewAI 🚀">
|
||||
- Run the following command to install `crewai` CLI:
|
||||
```shell
|
||||
uv tool install crewai
|
||||
```
|
||||
<Warning>
|
||||
If you encounter a `PATH` warning, run this command to update your shell:
|
||||
```shell
|
||||
uv tool update-shell
|
||||
```
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
If you encounter the `chroma-hnswlib==0.7.6` build error (`fatal error C1083: Cannot open include file: 'float.h'`) on Windows, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/) with *Desktop development with C++*.
|
||||
</Warning>
|
||||
|
||||
- To verify that `crewai` is installed, run:
|
||||
```shell
|
||||
uv tool list
|
||||
```
|
||||
- You should see something like:
|
||||
```shell
|
||||
crewai v0.102.0
|
||||
- crewai
|
||||
```
|
||||
- If you need to update `crewai`, run:
|
||||
```shell
|
||||
uv tool install crewai --upgrade
|
||||
```
|
||||
<Check>Installation successful! You're ready to create your first crew! 🎉</Check>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
# Creating a CrewAI Project
|
||||
|
||||
We recommend using the `YAML` template scaffolding for a structured approach to defining agents and tasks. Here's how to get started:
|
||||
|
||||
<Steps>
|
||||
<Step title="Generate Project Scaffolding">
|
||||
- Run the `crewai` CLI command:
|
||||
```shell
|
||||
crewai create crew <your_project_name>
|
||||
```
|
||||
|
||||
- This creates a new project with the following structure:
|
||||
```
|
||||
my_project/
|
||||
├── .gitignore
|
||||
├── knowledge/
|
||||
├── pyproject.toml
|
||||
├── README.md
|
||||
├── .env
|
||||
└── src/
|
||||
└── my_project/
|
||||
├── __init__.py
|
||||
├── main.py
|
||||
├── crew.py
|
||||
├── tools/
|
||||
│ ├── custom_tool.py
|
||||
│ └── __init__.py
|
||||
└── config/
|
||||
├── agents.yaml
|
||||
└── tasks.yaml
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Customize Your Project">
|
||||
- Your project will contain these essential files:
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `agents.yaml` | Define your AI agents and their roles |
|
||||
| `tasks.yaml` | Set up agent tasks and workflows |
|
||||
| `.env` | Store API keys and environment variables |
|
||||
| `main.py` | Project entry point and execution flow |
|
||||
| `crew.py` | Crew orchestration and coordination |
|
||||
| `tools/` | Directory for custom agent tools |
|
||||
| `knowledge/` | Directory for knowledge base |
|
||||
|
||||
- Start by editing `agents.yaml` and `tasks.yaml` to define your crew's behavior.
|
||||
- Keep sensitive information like API keys in `.env`.
|
||||
</Step>
|
||||
|
||||
<Step title="Run your Crew">
|
||||
- Before you run your crew, make sure to run:
|
||||
```bash
|
||||
crewai install
|
||||
```
|
||||
- If you need to install additional packages, use:
|
||||
```shell
|
||||
uv add <package-name>
|
||||
```
|
||||
- To run your crew, execute the following command in the root of your project:
|
||||
```bash
|
||||
crewai run
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Enterprise Installation Options
|
||||
|
||||
<Note type="info">
|
||||
For teams and organizations, CrewAI offers enterprise deployment options that eliminate setup complexity:
|
||||
|
||||
### CrewAI Enterprise (SaaS)
|
||||
- Zero installation required - just sign up for free at [app.crewai.com](https://app.crewai.com)
|
||||
- Automatic updates and maintenance
|
||||
- Managed infrastructure and scaling
|
||||
- Build Crews with no Code
|
||||
|
||||
### CrewAI Factory (Self-hosted)
|
||||
- Containerized deployment for your infrastructure
|
||||
- Supports any hyperscaler including on prem deployments
|
||||
- Integration with your existing security systems
|
||||
|
||||
<Card title="Explore Enterprise Options" icon="building" href="https://crewai.com/enterprise">
|
||||
Learn about CrewAI's enterprise offerings and schedule a demo
|
||||
</Card>
|
||||
</Note>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Build Your First Agent"
|
||||
icon="code"
|
||||
href="/en/quickstart"
|
||||
>
|
||||
Follow our quickstart guide to create your first CrewAI agent and get hands-on experience.
|
||||
</Card>
|
||||
<Card
|
||||
title="Join the Community"
|
||||
icon="comments"
|
||||
href="https://community.crewai.com"
|
||||
>
|
||||
Connect with other developers, get help, and share your CrewAI experiences.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
164
docs/en/introduction.mdx
Normal file
164
docs/en/introduction.mdx
Normal file
@@ -0,0 +1,164 @@
|
||||
---
|
||||
title: Introduction
|
||||
description: Build AI agent teams that work together to tackle complex tasks
|
||||
icon: handshake
|
||||
---
|
||||
|
||||
# What is CrewAI?
|
||||
|
||||
**CrewAI is a lean, lightning-fast Python framework built entirely from scratch—completely independent of LangChain or other agent frameworks.**
|
||||
|
||||
CrewAI empowers developers with both high-level simplicity and precise low-level control, ideal for creating autonomous AI agents tailored to any scenario:
|
||||
|
||||
- **[CrewAI Crews](/en/guides/crews/first-crew)**: Optimize for autonomy and collaborative intelligence, enabling you to create AI teams where each agent has specific roles, tools, and goals.
|
||||
- **[CrewAI Flows](/en/guides/flows/first-flow)**: Enable granular, event-driven control, single LLM calls for precise task orchestration and supports Crews natively.
|
||||
|
||||
With over 100,000 developers certified through our community courses, CrewAI is rapidly becoming the standard for enterprise-ready AI automation.
|
||||
|
||||
|
||||
## How Crews Work
|
||||
|
||||
<Note>
|
||||
Just like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.
|
||||
</Note>
|
||||
|
||||
<Frame caption="CrewAI Framework Overview">
|
||||
<img src="/images/crews.png" alt="CrewAI Framework Overview" />
|
||||
</Frame>
|
||||
|
||||
| Component | Description | Key Features |
|
||||
|:----------|:-----------:|:------------|
|
||||
| **Crew** | The top-level organization | • Manages AI agent teams<br/>• Oversees workflows<br/>• Ensures collaboration<br/>• Delivers outcomes |
|
||||
| **AI Agents** | Specialized team members | • Have specific roles (researcher, writer)<br/>• Use designated tools<br/>• Can delegate tasks<br/>• Make autonomous decisions |
|
||||
| **Process** | Workflow management system | • Defines collaboration patterns<br/>• Controls task assignments<br/>• Manages interactions<br/>• Ensures efficient execution |
|
||||
| **Tasks** | Individual assignments | • Have clear objectives<br/>• Use specific tools<br/>• Feed into larger process<br/>• Produce actionable results |
|
||||
|
||||
### How It All Works Together
|
||||
|
||||
1. The **Crew** organizes the overall operation
|
||||
2. **AI Agents** work on their specialized tasks
|
||||
3. The **Process** ensures smooth collaboration
|
||||
4. **Tasks** get completed to achieve the goal
|
||||
|
||||
## Key Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Role-Based Agents" icon="users">
|
||||
Create specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers
|
||||
</Card>
|
||||
<Card title="Flexible Tools" icon="screwdriver-wrench">
|
||||
Equip agents with custom tools and APIs to interact with external services and data sources
|
||||
</Card>
|
||||
<Card title="Intelligent Collaboration" icon="people-arrows">
|
||||
Agents work together, sharing insights and coordinating tasks to achieve complex objectives
|
||||
</Card>
|
||||
<Card title="Task Management" icon="list-check">
|
||||
Define sequential or parallel workflows, with agents automatically handling task dependencies
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## How Flows Work
|
||||
|
||||
<Note>
|
||||
While Crews excel at autonomous collaboration, Flows provide structured automations, offering granular control over workflow execution. Flows ensure tasks are executed reliably, securely, and efficiently, handling conditional logic, loops, and dynamic state management with precision. Flows integrate seamlessly with Crews, enabling you to balance high autonomy with exacting control.
|
||||
</Note>
|
||||
|
||||
<Frame caption="CrewAI Framework Overview">
|
||||
<img src="/images/flows.png" alt="CrewAI Framework Overview" />
|
||||
</Frame>
|
||||
|
||||
| Component | Description | Key Features |
|
||||
|:----------|:-----------:|:------------|
|
||||
| **Flow** | Structured workflow orchestration | • Manages execution paths<br/>• Handles state transitions<br/>• Controls task sequencing<br/>• Ensures reliable execution |
|
||||
| **Events** | Triggers for workflow actions | • Initiate specific processes<br/>• Enable dynamic responses<br/>• Support conditional branching<br/>• Allow for real-time adaptation |
|
||||
| **States** | Workflow execution contexts | • Maintain execution data<br/>• Enable persistence<br/>• Support resumability<br/>• Ensure execution integrity |
|
||||
| **Crew Support** | Enhances workflow automation | • Injects pockets of agency when needed<br/>• Complements structured workflows<br/>• Balances automation with intelligence<br/>• Enables adaptive decision-making |
|
||||
|
||||
### Key Capabilities
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Event-Driven Orchestration" icon="bolt">
|
||||
Define precise execution paths responding dynamically to events
|
||||
</Card>
|
||||
<Card title="Fine-Grained Control" icon="sliders">
|
||||
Manage workflow states and conditional execution securely and efficiently
|
||||
</Card>
|
||||
<Card title="Native Crew Integration" icon="puzzle-piece">
|
||||
Effortlessly combine with Crews for enhanced autonomy and intelligence
|
||||
</Card>
|
||||
<Card title="Deterministic Execution" icon="route">
|
||||
Ensure predictable outcomes with explicit control flow and error handling
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## When to Use Crews vs. Flows
|
||||
|
||||
<Note>
|
||||
Understanding when to use [Crews](/en/guides/crews/first-crew) versus [Flows](/en/guides/flows/first-flow) is key to maximizing the potential of CrewAI in your applications.
|
||||
</Note>
|
||||
|
||||
| Use Case | Recommended Approach | Why? |
|
||||
|:---------|:---------------------|:-----|
|
||||
| **Open-ended research** | [Crews](/en/guides/crews/first-crew) | When tasks require creative thinking, exploration, and adaptation |
|
||||
| **Content generation** | [Crews](/en/guides/crews/first-crew) | For collaborative creation of articles, reports, or marketing materials |
|
||||
| **Decision workflows** | [Flows](/en/guides/flows/first-flow) | When you need predictable, auditable decision paths with precise control |
|
||||
| **API orchestration** | [Flows](/en/guides/flows/first-flow) | For reliable integration with multiple external services in a specific sequence |
|
||||
| **Hybrid applications** | Combined approach | Use [Flows](/en/guides/flows/first-flow) to orchestrate overall process with [Crews](/en/guides/crews/first-crew) handling complex subtasks |
|
||||
|
||||
### Decision Framework
|
||||
|
||||
- **Choose [Crews](/en/guides/crews/first-crew) when:** You need autonomous problem-solving, creative collaboration, or exploratory tasks
|
||||
- **Choose [Flows](/en/guides/flows/first-flow) when:** You require deterministic outcomes, auditability, or precise control over execution
|
||||
- **Combine both when:** Your application needs both structured processes and pockets of autonomous intelligence
|
||||
|
||||
## Why Choose CrewAI?
|
||||
|
||||
- 🧠 **Autonomous Operation**: Agents make intelligent decisions based on their roles and available tools
|
||||
- 📝 **Natural Interaction**: Agents communicate and collaborate like human team members
|
||||
- 🛠️ **Extensible Design**: Easy to add new tools, roles, and capabilities
|
||||
- 🚀 **Production Ready**: Built for reliability and scalability in real-world applications
|
||||
- 🔒 **Security-Focused**: Designed with enterprise security requirements in mind
|
||||
- 💰 **Cost-Efficient**: Optimized to minimize token usage and API calls
|
||||
|
||||
## Ready to Start Building?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Build Your First Crew"
|
||||
icon="users-gear"
|
||||
href="/en/guides/crews/first-crew"
|
||||
>
|
||||
Step-by-step tutorial to create a collaborative AI team that works together to solve complex problems.
|
||||
</Card>
|
||||
<Card
|
||||
title="Build Your First Flow"
|
||||
icon="diagram-project"
|
||||
href="/en/guides/flows/first-flow"
|
||||
>
|
||||
Learn how to create structured, event-driven workflows with precise control over execution.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="Install CrewAI"
|
||||
icon="wrench"
|
||||
href="/en/installation"
|
||||
>
|
||||
Get started with CrewAI in your development environment.
|
||||
</Card>
|
||||
<Card
|
||||
title="Quick Start"
|
||||
icon="bolt"
|
||||
href="en/quickstart"
|
||||
>
|
||||
Follow our quickstart guide to create your first CrewAI agent and get hands-on experience.
|
||||
</Card>
|
||||
<Card
|
||||
title="Join the Community"
|
||||
icon="comments"
|
||||
href="https://community.crewai.com"
|
||||
>
|
||||
Connect with other developers, get help, and share your CrewAI experiences.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -12,7 +12,8 @@ The before kickoff hook is executed before the crew starts its tasks. It receive
|
||||
Here's an example of defining a before kickoff function in your `crew.py`:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase, before_kickoff
|
||||
from crewai import CrewBase
|
||||
from crewai.project import before_kickoff
|
||||
|
||||
@CrewBase
|
||||
class MyCrew:
|
||||
@@ -34,7 +35,8 @@ The after kickoff hook is executed after the crew has completed its tasks. It re
|
||||
Here's how you can define an after kickoff function in your `crew.py`:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase, after_kickoff
|
||||
from crewai import CrewBase
|
||||
from crewai.project import after_kickoff
|
||||
|
||||
@CrewBase
|
||||
class MyCrew:
|
||||
443
docs/en/learn/bring-your-own-agent.mdx
Normal file
443
docs/en/learn/bring-your-own-agent.mdx
Normal file
@@ -0,0 +1,443 @@
|
||||
---
|
||||
title: Bring your own agent
|
||||
description: Learn how to bring your own agents that work within a Crew.
|
||||
icon: robots
|
||||
---
|
||||
|
||||
Interoperability is a core concept in CrewAI. This guide will show you how to bring your own agents that work within a Crew.
|
||||
|
||||
|
||||
## Adapter Guide for Bringing your own agents (Langgraph Agents, OpenAI Agents, etc...)
|
||||
We require 3 adapters to turn any agent from different frameworks to work within crew.
|
||||
|
||||
1. BaseAgentAdapter
|
||||
2. BaseToolAdapter
|
||||
3. BaseConverter
|
||||
|
||||
|
||||
## BaseAgentAdapter
|
||||
This abstract class defines the common interface and functionality that all
|
||||
agent adapters must implement. It extends BaseAgent to maintain compatibility
|
||||
with the CrewAI framework while adding adapter-specific requirements.
|
||||
|
||||
Required Methods:
|
||||
|
||||
1. `def configure_tools`
|
||||
2. `def configure_structured_output`
|
||||
|
||||
## Creating your own Adapter
|
||||
To integrate an agent from a different framework (e.g., LangGraph, Autogen, OpenAI Assistants) into CrewAI, you need to create a custom adapter by inheriting from `BaseAgentAdapter`. This adapter acts as a compatibility layer, translating between the CrewAI interfaces and the specific requirements of your external agent.
|
||||
|
||||
Here's how you implement your custom adapter:
|
||||
|
||||
1. **Inherit from `BaseAgentAdapter`**:
|
||||
```python
|
||||
from crewai.agents.agent_adapters.base_agent_adapter import BaseAgentAdapter
|
||||
from crewai.tools import BaseTool
|
||||
from typing import List, Optional, Any, Dict
|
||||
|
||||
class MyCustomAgentAdapter(BaseAgentAdapter):
|
||||
# ... implementation details ...
|
||||
```
|
||||
|
||||
2. **Implement `__init__`**:
|
||||
The constructor should call the parent class constructor `super().__init__(**kwargs)` and perform any initialization specific to your external agent. You can use the optional `agent_config` dictionary passed during CrewAI's `Agent` initialization to configure your adapter and the underlying agent.
|
||||
|
||||
```python
|
||||
def __init__(self, agent_config: Optional[Dict[str, Any]] = None, **kwargs: Any):
|
||||
super().__init__(agent_config=agent_config, **kwargs)
|
||||
# Initialize your external agent here, possibly using agent_config
|
||||
# Example: self.external_agent = initialize_my_agent(agent_config)
|
||||
print(f"Initializing MyCustomAgentAdapter with config: {agent_config}")
|
||||
```
|
||||
|
||||
3. **Implement `configure_tools`**:
|
||||
This abstract method is crucial. It receives a list of CrewAI `BaseTool` instances. Your implementation must convert or adapt these tools into the format expected by your external agent framework. This might involve wrapping them, extracting specific attributes, or registering them with the external agent instance.
|
||||
|
||||
```python
|
||||
def configure_tools(self, tools: Optional[List[BaseTool]] = None) -> None:
|
||||
if tools:
|
||||
adapted_tools = []
|
||||
for tool in tools:
|
||||
# Adapt CrewAI BaseTool to the format your agent expects
|
||||
# Example: adapted_tool = adapt_to_my_framework(tool)
|
||||
# adapted_tools.append(adapted_tool)
|
||||
pass # Replace with your actual adaptation logic
|
||||
|
||||
# Configure the external agent with the adapted tools
|
||||
# Example: self.external_agent.set_tools(adapted_tools)
|
||||
print(f"Configuring tools for MyCustomAgentAdapter: {adapted_tools}") # Placeholder
|
||||
else:
|
||||
# Handle the case where no tools are provided
|
||||
# Example: self.external_agent.set_tools([])
|
||||
print("No tools provided for MyCustomAgentAdapter.")
|
||||
```
|
||||
|
||||
4. **Implement `configure_structured_output`**:
|
||||
This method is called when the CrewAI `Agent` is configured with structured output requirements (e.g., `output_json` or `output_pydantic`). Your adapter needs to ensure the external agent is set up to comply with these requirements. This might involve setting specific parameters on the external agent or ensuring its underlying model supports the requested format. If the external agent doesn't support structured output in a way compatible with CrewAI's expectations, you might need to handle the conversion or raise an appropriate error.
|
||||
|
||||
```python
|
||||
def configure_structured_output(self, structured_output: Any) -> None:
|
||||
# Configure your external agent to produce output in the specified format
|
||||
# Example: self.external_agent.set_output_format(structured_output)
|
||||
self.adapted_structured_output = True # Signal that structured output is handled
|
||||
print(f"Configuring structured output for MyCustomAgentAdapter: {structured_output}")
|
||||
```
|
||||
|
||||
By implementing these methods, your `MyCustomAgentAdapter` will allow your custom agent implementation to function correctly within a CrewAI crew, interacting with tasks and tools seamlessly. Remember to replace the example comments and print statements with your actual adaptation logic specific to the external agent framework you are integrating.
|
||||
|
||||
## BaseToolAdapter implementation
|
||||
The `BaseToolAdapter` class is responsible for converting CrewAI's native `BaseTool` objects into a format that your specific external agent framework can understand and utilize. Different agent frameworks (like LangGraph, OpenAI Assistants, etc.) have their own unique ways of defining and handling tools, and the `BaseToolAdapter` acts as the translator.
|
||||
|
||||
Here's how you implement your custom tool adapter:
|
||||
|
||||
1. **Inherit from `BaseToolAdapter`**:
|
||||
```python
|
||||
from crewai.agents.agent_adapters.base_tool_adapter import BaseToolAdapter
|
||||
from crewai.tools import BaseTool
|
||||
from typing import List, Any
|
||||
|
||||
class MyCustomToolAdapter(BaseToolAdapter):
|
||||
# ... implementation details ...
|
||||
```
|
||||
|
||||
2. **Implement `configure_tools`**:
|
||||
This is the core abstract method you must implement. It receives a list of CrewAI `BaseTool` instances provided to the agent. Your task is to iterate through this list, adapt each `BaseTool` into the format expected by your external framework, and store the converted tools in the `self.converted_tools` list (which is initialized in the base class constructor).
|
||||
|
||||
```python
|
||||
def configure_tools(self, tools: List[BaseTool]) -> None:
|
||||
"""Configure and convert CrewAI tools for the specific implementation."""
|
||||
self.converted_tools = [] # Reset in case it's called multiple times
|
||||
for tool in tools:
|
||||
# Sanitize the tool name if required by the target framework
|
||||
sanitized_name = self.sanitize_tool_name(tool.name)
|
||||
|
||||
# --- Your Conversion Logic Goes Here ---
|
||||
# Example: Convert BaseTool to a dictionary format for LangGraph
|
||||
# converted_tool = {
|
||||
# "name": sanitized_name,
|
||||
# "description": tool.description,
|
||||
# "parameters": tool.args_schema.schema() if tool.args_schema else {},
|
||||
# # Add any other framework-specific fields
|
||||
# }
|
||||
|
||||
# Example: Convert BaseTool to an OpenAI function definition
|
||||
# converted_tool = {
|
||||
# "type": "function",
|
||||
# "function": {
|
||||
# "name": sanitized_name,
|
||||
# "description": tool.description,
|
||||
# "parameters": tool.args_schema.schema() if tool.args_schema else {"type": "object", "properties": {}},
|
||||
# }
|
||||
# }
|
||||
|
||||
# --- Replace above examples with your actual adaptation ---
|
||||
converted_tool = self.adapt_tool_to_my_framework(tool, sanitized_name) # Placeholder
|
||||
|
||||
self.converted_tools.append(converted_tool)
|
||||
print(f"Adapted tool '{tool.name}' to '{sanitized_name}' for MyCustomToolAdapter") # Placeholder
|
||||
|
||||
print(f"MyCustomToolAdapter finished configuring tools: {len(self.converted_tools)} adapted.") # Placeholder
|
||||
|
||||
# --- Helper method for adaptation (Example) ---
|
||||
def adapt_tool_to_my_framework(self, tool: BaseTool, sanitized_name: str) -> Any:
|
||||
# Replace this with the actual logic to convert a CrewAI BaseTool
|
||||
# to the format needed by your specific external agent framework.
|
||||
# This will vary greatly depending on the target framework.
|
||||
adapted_representation = {
|
||||
"framework_specific_name": sanitized_name,
|
||||
"framework_specific_description": tool.description,
|
||||
"inputs": tool.args_schema.schema() if tool.args_schema else None,
|
||||
"implementation_reference": tool.run # Or however the framework needs to call it
|
||||
}
|
||||
# Also ensure the tool works both sync and async
|
||||
async def async_tool_wrapper(*args, **kwargs):
|
||||
output = tool.run(*args, **kwargs)
|
||||
if inspect.isawaitable(output):
|
||||
return await output
|
||||
else:
|
||||
return output
|
||||
|
||||
adapted_tool = MyFrameworkTool(
|
||||
name=sanitized_name,
|
||||
description=tool.description,
|
||||
inputs=tool.args_schema.schema() if tool.args_schema else None,
|
||||
implementation_reference=async_tool_wrapper
|
||||
)
|
||||
|
||||
return adapted_representation
|
||||
|
||||
```
|
||||
|
||||
3. **Using the Adapter**:
|
||||
Typically, you would instantiate your `MyCustomToolAdapter` within your `MyCustomAgentAdapter`'s `configure_tools` method and use it to process the tools before configuring your external agent.
|
||||
|
||||
```python
|
||||
# Inside MyCustomAgentAdapter.configure_tools
|
||||
def configure_tools(self, tools: Optional[List[BaseTool]] = None) -> None:
|
||||
if tools:
|
||||
tool_adapter = MyCustomToolAdapter() # Instantiate your tool adapter
|
||||
tool_adapter.configure_tools(tools) # Convert the tools
|
||||
adapted_tools = tool_adapter.tools() # Get the converted tools
|
||||
|
||||
# Now configure your external agent with the adapted_tools
|
||||
# Example: self.external_agent.set_tools(adapted_tools)
|
||||
print(f"Configuring external agent with adapted tools: {adapted_tools}") # Placeholder
|
||||
else:
|
||||
# Handle no tools case
|
||||
print("No tools provided for MyCustomAgentAdapter.")
|
||||
```
|
||||
|
||||
By creating a `BaseToolAdapter`, you decouple the tool conversion logic from the agent adaptation, making the integration cleaner and more modular. Remember to replace the placeholder examples with the actual conversion logic required by your specific external agent framework.
|
||||
|
||||
## BaseConverter
|
||||
The `BaseConverterAdapter` plays a crucial role when a CrewAI `Task` requires an agent to return its final output in a specific structured format, such as JSON or a Pydantic model. It bridges the gap between CrewAI's structured output requirements and the capabilities of your external agent.
|
||||
|
||||
Its primary responsibilities are:
|
||||
1. **Configuring the Agent for Structured Output:** Based on the `Task`'s requirements (`output_json` or `output_pydantic`), it instructs the associated `BaseAgentAdapter` (and indirectly, the external agent) on what format is expected.
|
||||
2. **Enhancing the System Prompt:** It modifies the agent's system prompt to include clear instructions on *how* to generate the output in the required structure.
|
||||
3. **Post-processing the Result:** It takes the raw output from the agent and attempts to parse, validate, and format it according to the required structure, ultimately returning a string representation (e.g., a JSON string).
|
||||
|
||||
Here's how you implement your custom converter adapter:
|
||||
|
||||
1. **Inherit from `BaseConverterAdapter`**:
|
||||
```python
|
||||
from crewai.agents.agent_adapters.base_converter_adapter import BaseConverterAdapter
|
||||
# Assuming you have your MyCustomAgentAdapter defined
|
||||
# from .my_custom_agent_adapter import MyCustomAgentAdapter
|
||||
from crewai.task import Task
|
||||
from typing import Any
|
||||
|
||||
class MyCustomConverterAdapter(BaseConverterAdapter):
|
||||
# Store the expected output type (e.g., 'json', 'pydantic', 'text')
|
||||
_output_type: str = 'text'
|
||||
_output_schema: Any = None # Store JSON schema or Pydantic model
|
||||
|
||||
# ... implementation details ...
|
||||
```
|
||||
|
||||
2. **Implement `__init__`**:
|
||||
The constructor must accept the corresponding `agent_adapter` instance it will work with.
|
||||
|
||||
```python
|
||||
def __init__(self, agent_adapter: Any): # Use your specific AgentAdapter type hint
|
||||
self.agent_adapter = agent_adapter
|
||||
print(f"Initializing MyCustomConverterAdapter for agent adapter: {type(agent_adapter).__name__}")
|
||||
```
|
||||
|
||||
3. **Implement `configure_structured_output`**:
|
||||
This method receives the CrewAI `Task` object. You need to check the task's `output_json` and `output_pydantic` attributes to determine the required output structure. Store this information (e.g., in `_output_type` and `_output_schema`) and potentially call configuration methods on your `self.agent_adapter` if the external agent needs specific setup for structured output (which might have been partially handled in the agent adapter's `configure_structured_output` already).
|
||||
|
||||
```python
|
||||
def configure_structured_output(self, task: Task) -> None:
|
||||
"""Configure the expected structured output based on the task."""
|
||||
if task.output_pydantic:
|
||||
self._output_type = 'pydantic'
|
||||
self._output_schema = task.output_pydantic
|
||||
print(f"Converter: Configured for Pydantic output: {self._output_schema.__name__}")
|
||||
elif task.output_json:
|
||||
self._output_type = 'json'
|
||||
self._output_schema = task.output_json
|
||||
print(f"Converter: Configured for JSON output with schema: {self._output_schema}")
|
||||
else:
|
||||
self._output_type = 'text'
|
||||
self._output_schema = None
|
||||
print("Converter: Configured for standard text output.")
|
||||
|
||||
# Optionally, inform the agent adapter if needed
|
||||
# self.agent_adapter.set_output_mode(self._output_type, self._output_schema)
|
||||
```
|
||||
|
||||
4. **Implement `enhance_system_prompt`**:
|
||||
This method takes the agent's base system prompt string and should append instructions tailored to the currently configured `_output_type` and `_output_schema`. The goal is to guide the LLM powering the agent to produce output in the correct format.
|
||||
|
||||
```python
|
||||
def enhance_system_prompt(self, base_prompt: str) -> str:
|
||||
"""Enhance the system prompt with structured output instructions."""
|
||||
if self._output_type == 'text':
|
||||
return base_prompt # No enhancement needed for plain text
|
||||
|
||||
instructions = "\n\nYour final answer MUST be formatted as "
|
||||
if self._output_type == 'json':
|
||||
schema_str = json.dumps(self._output_schema, indent=2)
|
||||
instructions += f"a JSON object conforming to the following schema:\n```json\n{schema_str}\n```"
|
||||
elif self._output_type == 'pydantic':
|
||||
schema_str = json.dumps(self._output_schema.model_json_schema(), indent=2)
|
||||
instructions += f"a JSON object conforming to the Pydantic model '{self._output_schema.__name__}' with the following schema:\n```json\n{schema_str}\n```"
|
||||
|
||||
instructions += "\nEnsure your entire response is ONLY the valid JSON object, without any introductory text, explanations, or concluding remarks."
|
||||
|
||||
print(f"Converter: Enhancing prompt for {self._output_type} output.")
|
||||
return base_prompt + instructions
|
||||
```
|
||||
*Note: The exact prompt engineering might need tuning based on the agent/LLM being used.*
|
||||
|
||||
5. **Implement `post_process_result`**:
|
||||
This method receives the raw string output from the agent. If structured output was requested (`json` or `pydantic`), you should attempt to parse the string into the expected format. Handle potential parsing errors (e.g., log them, attempt simple fixes, or raise an exception). Crucially, the method must **always return a string**, even if the intermediate format was a dictionary or Pydantic object (e.g., by serializing it back to a JSON string).
|
||||
|
||||
```python
|
||||
import json
|
||||
from pydantic import ValidationError
|
||||
|
||||
def post_process_result(self, result: str) -> str:
|
||||
"""Post-process the agent's result to ensure it matches the expected format."""
|
||||
print(f"Converter: Post-processing result for {self._output_type} output.")
|
||||
if self._output_type == 'json':
|
||||
try:
|
||||
# Attempt to parse and re-serialize to ensure validity and consistent format
|
||||
parsed_json = json.loads(result)
|
||||
# Optional: Validate against self._output_schema if it's a JSON schema dictionary
|
||||
# from jsonschema import validate
|
||||
# validate(instance=parsed_json, schema=self._output_schema)
|
||||
return json.dumps(parsed_json)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Failed to parse JSON output: {e}\nRaw output:\n{result}")
|
||||
# Handle error: return raw, raise exception, or try to fix
|
||||
return result # Example: return raw output on failure
|
||||
# except Exception as e: # Catch validation errors if using jsonschema
|
||||
# print(f"Error: JSON output failed schema validation: {e}\nRaw output:\n{result}")
|
||||
# return result
|
||||
elif self._output_type == 'pydantic':
|
||||
try:
|
||||
# Attempt to parse into the Pydantic model
|
||||
model_instance = self._output_schema.model_validate_json(result)
|
||||
# Return the model serialized back to JSON
|
||||
return model_instance.model_dump_json()
|
||||
except ValidationError as e:
|
||||
print(f"Error: Failed to validate Pydantic output: {e}\nRaw output:\n{result}")
|
||||
# Handle error
|
||||
return result # Example: return raw output on failure
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Failed to parse JSON for Pydantic model: {e}\nRaw output:\n{result}")
|
||||
return result
|
||||
else: # 'text'
|
||||
return result # No processing needed for plain text
|
||||
```
|
||||
|
||||
By implementing these methods, your `MyCustomConverterAdapter` ensures that structured output requests from CrewAI tasks are correctly handled by your integrated external agent, improving the reliability and usability of your custom agent within the CrewAI framework.
|
||||
|
||||
## Out of the Box Adapters
|
||||
|
||||
We provide out of the box adapters for the following frameworks:
|
||||
1. LangGraph
|
||||
2. OpenAI Agents
|
||||
|
||||
## Kicking off a crew with adapted agents:
|
||||
|
||||
```python
|
||||
import json
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
from crewai_tools import SerperDevTool
|
||||
from src.crewai import Agent, Crew, Task
|
||||
from langchain_openai import ChatOpenAI
|
||||
from pydantic import BaseModel
|
||||
|
||||
from crewai.agents.agent_adapters.langgraph.langgraph_adapter import (
|
||||
LangGraphAgentAdapter,
|
||||
)
|
||||
from crewai.agents.agent_adapters.openai_agents.openai_adapter import OpenAIAgentAdapter
|
||||
|
||||
# CrewAI Agent
|
||||
code_helper_agent = Agent(
|
||||
role="Code Helper",
|
||||
goal="Help users solve coding problems effectively and provide clear explanations.",
|
||||
backstory="You are an experienced programmer with deep knowledge across multiple programming languages and frameworks. You specialize in solving complex coding challenges and explaining solutions clearly.",
|
||||
allow_delegation=False,
|
||||
verbose=True,
|
||||
)
|
||||
# OpenAI Agent Adapter
|
||||
link_finder_agent = OpenAIAgentAdapter(
|
||||
role="Link Finder",
|
||||
goal="Find the most relevant and high-quality resources for coding tasks.",
|
||||
backstory="You are a research specialist with a talent for finding the most helpful resources. You're skilled at using search tools to discover documentation, tutorials, and examples that directly address the user's coding needs.",
|
||||
tools=[SerperDevTool()],
|
||||
allow_delegation=False,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
# LangGraph Agent Adapter
|
||||
reporter_agent = LangGraphAgentAdapter(
|
||||
role="Reporter",
|
||||
goal="Report the results of the tasks.",
|
||||
backstory="You are a reporter who reports the results of the other tasks",
|
||||
llm=ChatOpenAI(model="gpt-4o"),
|
||||
allow_delegation=True,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
|
||||
class Code(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
task = Task(
|
||||
description="Give an answer to the coding question: {task}",
|
||||
expected_output="A thorough answer to the coding question: {task}",
|
||||
agent=code_helper_agent,
|
||||
output_json=Code,
|
||||
)
|
||||
task2 = Task(
|
||||
description="Find links to resources that can help with coding tasks. Use the serper tool to find resources that can help.",
|
||||
expected_output="A list of links to resources that can help with coding tasks",
|
||||
agent=link_finder_agent,
|
||||
)
|
||||
|
||||
|
||||
class Report(BaseModel):
|
||||
code: str
|
||||
links: List[str]
|
||||
|
||||
|
||||
task3 = Task(
|
||||
description="Report the results of the tasks.",
|
||||
expected_output="A report of the results of the tasks. this is the code produced and then the links to the resources that can help with the coding task.",
|
||||
agent=reporter_agent,
|
||||
output_json=Report,
|
||||
)
|
||||
# Use in CrewAI
|
||||
crew = Crew(
|
||||
agents=[code_helper_agent, link_finder_agent, reporter_agent],
|
||||
tasks=[task, task2, task3],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = crew.kickoff(
|
||||
inputs={"task": "How do you implement an abstract class in python?"}
|
||||
)
|
||||
|
||||
# Print raw result first
|
||||
print("Raw result:", result)
|
||||
|
||||
# Handle result based on its type
|
||||
if hasattr(result, "json_dict") and result.json_dict:
|
||||
json_result = result.json_dict
|
||||
print("\nStructured JSON result:")
|
||||
print(f"{json.dumps(json_result, indent=2)}")
|
||||
|
||||
# Access fields safely
|
||||
if isinstance(json_result, dict):
|
||||
if "code" in json_result:
|
||||
print("\nCode:")
|
||||
print(
|
||||
json_result["code"][:200] + "..."
|
||||
if len(json_result["code"]) > 200
|
||||
else json_result["code"]
|
||||
)
|
||||
|
||||
if "links" in json_result:
|
||||
print("\nLinks:")
|
||||
for link in json_result["links"][:5]: # Print first 5 links
|
||||
print(f"- {link}")
|
||||
if len(json_result["links"]) > 5:
|
||||
print(f"...and {len(json_result['links']) - 5} more links")
|
||||
elif hasattr(result, "pydantic") and result.pydantic:
|
||||
print("\nPydantic model result:")
|
||||
print(result.pydantic.model_dump_json(indent=2))
|
||||
else:
|
||||
# Fallback to raw output
|
||||
print("\nNo structured result available, using raw output:")
|
||||
print(result.raw[:500] + "..." if len(result.raw) > 500 else result.raw)
|
||||
|
||||
```
|
||||
350
docs/en/learn/custom-llm.mdx
Normal file
350
docs/en/learn/custom-llm.mdx
Normal file
@@ -0,0 +1,350 @@
|
||||
---
|
||||
title: Custom LLM Implementation
|
||||
description: Learn how to create custom LLM implementations in CrewAI.
|
||||
icon: code
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CrewAI supports custom LLM implementations through the `BaseLLM` abstract base class. This allows you to integrate any LLM provider that doesn't have built-in support in LiteLLM, or implement custom authentication mechanisms.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Here's a minimal custom LLM implementation:
|
||||
|
||||
```python
|
||||
from crewai import BaseLLM
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
import requests
|
||||
|
||||
class CustomLLM(BaseLLM):
|
||||
def __init__(self, model: str, api_key: str, endpoint: str, temperature: Optional[float] = None):
|
||||
# IMPORTANT: Call super().__init__() with required parameters
|
||||
super().__init__(model=model, temperature=temperature)
|
||||
|
||||
self.api_key = api_key
|
||||
self.endpoint = endpoint
|
||||
|
||||
def call(
|
||||
self,
|
||||
messages: Union[str, List[Dict[str, str]]],
|
||||
tools: Optional[List[dict]] = None,
|
||||
callbacks: Optional[List[Any]] = None,
|
||||
available_functions: Optional[Dict[str, Any]] = None,
|
||||
) -> Union[str, Any]:
|
||||
"""Call the LLM with the given messages."""
|
||||
# Convert string to message format if needed
|
||||
if isinstance(messages, str):
|
||||
messages = [{"role": "user", "content": messages}]
|
||||
|
||||
# Prepare request
|
||||
payload = {
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"temperature": self.temperature,
|
||||
}
|
||||
|
||||
# Add tools if provided and supported
|
||||
if tools and self.supports_function_calling():
|
||||
payload["tools"] = tools
|
||||
|
||||
# Make API call
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
return result["choices"][0]["message"]["content"]
|
||||
|
||||
def supports_function_calling(self) -> bool:
|
||||
"""Override if your LLM supports function calling."""
|
||||
return True # Change to False if your LLM doesn't support tools
|
||||
|
||||
def get_context_window_size(self) -> int:
|
||||
"""Return the context window size of your LLM."""
|
||||
return 8192 # Adjust based on your model's actual context window
|
||||
```
|
||||
|
||||
## Using Your Custom LLM
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
# Assuming you have the CustomLLM class defined above
|
||||
# Create your custom LLM
|
||||
custom_llm = CustomLLM(
|
||||
model="my-custom-model",
|
||||
api_key="your-api-key",
|
||||
endpoint="https://api.example.com/v1/chat/completions",
|
||||
temperature=0.7
|
||||
)
|
||||
|
||||
# Use with an agent
|
||||
agent = Agent(
|
||||
role="Research Assistant",
|
||||
goal="Find and analyze information",
|
||||
backstory="You are a research assistant.",
|
||||
llm=custom_llm
|
||||
)
|
||||
|
||||
# Create and execute tasks
|
||||
task = Task(
|
||||
description="Research the latest developments in AI",
|
||||
expected_output="A comprehensive summary",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Required Methods
|
||||
|
||||
### Constructor: `__init__()`
|
||||
|
||||
**Critical**: You must call `super().__init__(model, temperature)` with the required parameters:
|
||||
|
||||
```python
|
||||
def __init__(self, model: str, api_key: str, temperature: Optional[float] = None):
|
||||
# REQUIRED: Call parent constructor with model and temperature
|
||||
super().__init__(model=model, temperature=temperature)
|
||||
|
||||
# Your custom initialization
|
||||
self.api_key = api_key
|
||||
```
|
||||
|
||||
### Abstract Method: `call()`
|
||||
|
||||
The `call()` method is the heart of your LLM implementation. It must:
|
||||
|
||||
- Accept messages (string or list of dicts with 'role' and 'content')
|
||||
- Return a string response
|
||||
- Handle tools and function calling if supported
|
||||
- Raise appropriate exceptions for errors
|
||||
|
||||
### Optional Methods
|
||||
|
||||
```python
|
||||
def supports_function_calling(self) -> bool:
|
||||
"""Return True if your LLM supports function calling."""
|
||||
return True # Default is True
|
||||
|
||||
def supports_stop_words(self) -> bool:
|
||||
"""Return True if your LLM supports stop sequences."""
|
||||
return True # Default is True
|
||||
|
||||
def get_context_window_size(self) -> int:
|
||||
"""Return the context window size."""
|
||||
return 4096 # Default is 4096
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Error Handling
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
def call(self, messages, tools=None, callbacks=None, available_functions=None):
|
||||
try:
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["choices"][0]["message"]["content"]
|
||||
|
||||
except requests.Timeout:
|
||||
raise TimeoutError("LLM request timed out")
|
||||
except requests.RequestException as e:
|
||||
raise RuntimeError(f"LLM request failed: {str(e)}")
|
||||
except (KeyError, IndexError) as e:
|
||||
raise ValueError(f"Invalid response format: {str(e)}")
|
||||
```
|
||||
|
||||
### Custom Authentication
|
||||
|
||||
```python
|
||||
from crewai import BaseLLM
|
||||
from typing import Optional
|
||||
|
||||
class CustomAuthLLM(BaseLLM):
|
||||
def __init__(self, model: str, auth_token: str, endpoint: str, temperature: Optional[float] = None):
|
||||
super().__init__(model=model, temperature=temperature)
|
||||
self.auth_token = auth_token
|
||||
self.endpoint = endpoint
|
||||
|
||||
def call(self, messages, tools=None, callbacks=None, available_functions=None):
|
||||
headers = {
|
||||
"Authorization": f"Custom {self.auth_token}", # Custom auth format
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
# Rest of implementation...
|
||||
```
|
||||
|
||||
### Stop Words Support
|
||||
|
||||
CrewAI automatically adds `"\nObservation:"` as a stop word to control agent behavior. If your LLM supports stop words:
|
||||
|
||||
```python
|
||||
def call(self, messages, tools=None, callbacks=None, available_functions=None):
|
||||
payload = {
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"stop": self.stop # Include stop words in API call
|
||||
}
|
||||
# Make API call...
|
||||
|
||||
def supports_stop_words(self) -> bool:
|
||||
return True # Your LLM supports stop sequences
|
||||
```
|
||||
|
||||
If your LLM doesn't support stop words natively:
|
||||
|
||||
```python
|
||||
def call(self, messages, tools=None, callbacks=None, available_functions=None):
|
||||
response = self._make_api_call(messages, tools)
|
||||
content = response["choices"][0]["message"]["content"]
|
||||
|
||||
# Manually truncate at stop words
|
||||
if self.stop:
|
||||
for stop_word in self.stop:
|
||||
if stop_word in content:
|
||||
content = content.split(stop_word)[0]
|
||||
break
|
||||
|
||||
return content
|
||||
|
||||
def supports_stop_words(self) -> bool:
|
||||
return False # Tell CrewAI we handle stop words manually
|
||||
```
|
||||
|
||||
## Function Calling
|
||||
|
||||
If your LLM supports function calling, implement the complete flow:
|
||||
|
||||
```python
|
||||
import json
|
||||
|
||||
def call(self, messages, tools=None, callbacks=None, available_functions=None):
|
||||
# Convert string to message format
|
||||
if isinstance(messages, str):
|
||||
messages = [{"role": "user", "content": messages}]
|
||||
|
||||
# Make API call
|
||||
response = self._make_api_call(messages, tools)
|
||||
message = response["choices"][0]["message"]
|
||||
|
||||
# Check for function calls
|
||||
if "tool_calls" in message and available_functions:
|
||||
return self._handle_function_calls(
|
||||
message["tool_calls"], messages, tools, available_functions
|
||||
)
|
||||
|
||||
return message["content"]
|
||||
|
||||
def _handle_function_calls(self, tool_calls, messages, tools, available_functions):
|
||||
"""Handle function calling with proper message flow."""
|
||||
for tool_call in tool_calls:
|
||||
function_name = tool_call["function"]["name"]
|
||||
|
||||
if function_name in available_functions:
|
||||
# Parse and execute function
|
||||
function_args = json.loads(tool_call["function"]["arguments"])
|
||||
function_result = available_functions[function_name](**function_args)
|
||||
|
||||
# Add function call and result to message history
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [tool_call]
|
||||
})
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call["id"],
|
||||
"name": function_name,
|
||||
"content": str(function_result)
|
||||
})
|
||||
|
||||
# Call LLM again with updated context
|
||||
return self.call(messages, tools, None, available_functions)
|
||||
|
||||
return "Function call failed"
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Constructor Errors**
|
||||
```python
|
||||
# ❌ Wrong - missing required parameters
|
||||
def __init__(self, api_key: str):
|
||||
super().__init__()
|
||||
|
||||
# ✅ Correct
|
||||
def __init__(self, model: str, api_key: str, temperature: Optional[float] = None):
|
||||
super().__init__(model=model, temperature=temperature)
|
||||
```
|
||||
|
||||
**Function Calling Not Working**
|
||||
- Ensure `supports_function_calling()` returns `True`
|
||||
- Check that you handle `tool_calls` in the response
|
||||
- Verify `available_functions` parameter is used correctly
|
||||
|
||||
**Authentication Failures**
|
||||
- Verify API key format and permissions
|
||||
- Check authentication header format
|
||||
- Ensure endpoint URLs are correct
|
||||
|
||||
**Response Parsing Errors**
|
||||
- Validate response structure before accessing nested fields
|
||||
- Handle cases where content might be None
|
||||
- Add proper error handling for malformed responses
|
||||
|
||||
## Testing Your Custom LLM
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
def test_custom_llm():
|
||||
llm = CustomLLM(
|
||||
model="test-model",
|
||||
api_key="test-key",
|
||||
endpoint="https://api.test.com"
|
||||
)
|
||||
|
||||
# Test basic call
|
||||
result = llm.call("Hello, world!")
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
# Test with CrewAI agent
|
||||
agent = Agent(
|
||||
role="Test Agent",
|
||||
goal="Test custom LLM",
|
||||
backstory="A test agent.",
|
||||
llm=llm
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Say hello",
|
||||
expected_output="A greeting",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
assert "hello" in result.raw.lower()
|
||||
```
|
||||
|
||||
This guide covers the essentials of implementing custom LLMs in CrewAI.
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Create Your Own Manager Agent
|
||||
title: Custom Manager Agent
|
||||
description: Learn how to set a custom agent as the manager in CrewAI, providing more control over task management and coordination.
|
||||
icon: user-shield
|
||||
---
|
||||
73
docs/en/learn/dalle-image-generation.mdx
Normal file
73
docs/en/learn/dalle-image-generation.mdx
Normal file
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: "Image Generation with DALL-E"
|
||||
description: "Learn how to use DALL-E for AI-powered image generation in your CrewAI projects"
|
||||
icon: "image"
|
||||
---
|
||||
|
||||
CrewAI supports integration with OpenAI's DALL-E, allowing your AI agents to generate images as part of their tasks. This guide will walk you through how to set up and use the DALL-E tool in your CrewAI projects.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- crewAI installed (latest version)
|
||||
- OpenAI API key with access to DALL-E
|
||||
|
||||
## Setting Up the DALL-E Tool
|
||||
|
||||
<Steps>
|
||||
<Step title="Import the DALL-E tool">
|
||||
```python
|
||||
from crewai_tools import DallETool
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Add the DALL-E tool to your agent configuration">
|
||||
```python
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'],
|
||||
tools=[SerperDevTool(), DallETool()], # Add DallETool to the list of tools
|
||||
allow_delegation=False,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Using the DALL-E Tool
|
||||
|
||||
Once you've added the DALL-E tool to your agent, it can generate images based on text prompts. The tool will return a URL to the generated image, which can be used in the agent's output or passed to other agents for further processing.
|
||||
|
||||
### Example Agent Configuration
|
||||
|
||||
```yaml
|
||||
role: >
|
||||
LinkedIn Profile Senior Data Researcher
|
||||
goal: >
|
||||
Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}
|
||||
Generate a Dall-e image based on domain {domain}
|
||||
backstory: >
|
||||
You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.
|
||||
Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting
|
||||
professional information clearly and concisely.
|
||||
```
|
||||
|
||||
### Expected Output
|
||||
|
||||
The agent with the DALL-E tool will be able to generate the image and provide a URL in its response. You can then download the image.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/dall-e-image.png" alt="DALL-E Image" />
|
||||
</Frame>
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Be specific in your image generation prompts** to get the best results.
|
||||
2. **Consider generation time** - Image generation can take some time, so factor this into your task planning.
|
||||
3. **Follow usage policies** - Always comply with OpenAI's usage policies when generating images.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
1. **Check API access** - Ensure your OpenAI API key has access to DALL-E.
|
||||
2. **Version compatibility** - Check that you're using the latest version of crewAI and crewai-tools.
|
||||
3. **Tool configuration** - Verify that the DALL-E tool is correctly added to the agent's tool list.
|
||||
@@ -48,7 +48,6 @@ Define a crew with a designated manager and establish a clear chain of command.
|
||||
</Tip>
|
||||
|
||||
```python Code
|
||||
from langchain_openai import ChatOpenAI
|
||||
from crewai import Crew, Process, Agent
|
||||
|
||||
# Agents are defined with attributes for backstory, cache, and verbose mode
|
||||
@@ -56,38 +55,51 @@ researcher = Agent(
|
||||
role='Researcher',
|
||||
goal='Conduct in-depth analysis',
|
||||
backstory='Experienced data analyst with a knack for uncovering hidden trends.',
|
||||
cache=True,
|
||||
verbose=False,
|
||||
# tools=[] # This can be optionally specified; defaults to an empty list
|
||||
use_system_prompt=True, # Enable or disable system prompts for this agent
|
||||
max_rpm=30, # Limit on the number of requests per minute
|
||||
max_iter=5 # Maximum number of iterations for a final answer
|
||||
)
|
||||
writer = Agent(
|
||||
role='Writer',
|
||||
goal='Create engaging content',
|
||||
backstory='Creative writer passionate about storytelling in technical domains.',
|
||||
cache=True,
|
||||
verbose=False,
|
||||
# tools=[] # Optionally specify tools; defaults to an empty list
|
||||
use_system_prompt=True, # Enable or disable system prompts for this agent
|
||||
max_rpm=30, # Limit on the number of requests per minute
|
||||
max_iter=5 # Maximum number of iterations for a final answer
|
||||
)
|
||||
|
||||
# Establishing the crew with a hierarchical process and additional configurations
|
||||
project_crew = Crew(
|
||||
tasks=[...], # Tasks to be delegated and executed under the manager's supervision
|
||||
agents=[researcher, writer],
|
||||
manager_llm=ChatOpenAI(temperature=0, model="gpt-4"), # Mandatory if manager_agent is not set
|
||||
process=Process.hierarchical, # Specifies the hierarchical management approach
|
||||
respect_context_window=True, # Enable respect of the context window for tasks
|
||||
memory=True, # Enable memory usage for enhanced task execution
|
||||
manager_agent=None, # Optional: explicitly set a specific agent as manager instead of the manager_llm
|
||||
planning=True, # Enable planning feature for pre-execution strategy
|
||||
manager_llm="gpt-4o", # Specify which LLM the manager should use
|
||||
process=Process.hierarchical,
|
||||
planning=True,
|
||||
)
|
||||
```
|
||||
|
||||
### Using a Custom Manager Agent
|
||||
|
||||
Alternatively, you can create a custom manager agent with specific attributes tailored to your project's management needs. This gives you more control over the manager's behavior and capabilities.
|
||||
|
||||
```python
|
||||
# Define a custom manager agent
|
||||
manager = Agent(
|
||||
role="Project Manager",
|
||||
goal="Efficiently manage the crew and ensure high-quality task completion",
|
||||
backstory="You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success.",
|
||||
allow_delegation=True,
|
||||
)
|
||||
|
||||
# Use the custom manager in your crew
|
||||
project_crew = Crew(
|
||||
tasks=[...],
|
||||
agents=[researcher, writer],
|
||||
manager_agent=manager, # Use your custom manager agent
|
||||
process=Process.hierarchical,
|
||||
planning=True,
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
For more details on creating and customizing a manager agent, check out the [Custom Manager Agent documentation](https://docs.crewai.com/how-to/custom-manager-agent#custom-manager-agent).
|
||||
</Tip>
|
||||
|
||||
|
||||
### Workflow in Action
|
||||
|
||||
1. **Task Assignment**: The manager assigns tasks strategically, considering each agent's capabilities and available tools.
|
||||
@@ -97,4 +109,4 @@ project_crew = Crew(
|
||||
## Conclusion
|
||||
|
||||
Adopting the hierarchical process in CrewAI, with the correct configurations and understanding of the system's capabilities, facilitates an organized and efficient approach to project management.
|
||||
Utilize the advanced features and customizations to tailor the workflow to your specific needs, ensuring optimal task execution and project success.
|
||||
Utilize the advanced features and customizations to tailor the workflow to your specific needs, ensuring optimal task execution and project success.
|
||||
78
docs/en/learn/human-in-the-loop.mdx
Normal file
78
docs/en/learn/human-in-the-loop.mdx
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
title: "Human-in-the-Loop (HITL) Workflows"
|
||||
description: "Learn how to implement Human-in-the-Loop workflows in CrewAI for enhanced decision-making"
|
||||
icon: "user-check"
|
||||
---
|
||||
|
||||
Human-in-the-Loop (HITL) is a powerful approach that combines artificial intelligence with human expertise to enhance decision-making and improve task outcomes. This guide shows you how to implement HITL within CrewAI.
|
||||
|
||||
## Setting Up HITL Workflows
|
||||
|
||||
<Steps>
|
||||
<Step title="Configure Your Task">
|
||||
Set up your task with human input enabled:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crew-human-input.png" alt="Crew Human Input" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Provide Webhook URL">
|
||||
When kicking off your crew, include a webhook URL for human input:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crew-webhook-url.png" alt="Crew Webhook URL" />
|
||||
</Frame>
|
||||
</Step>
|
||||
|
||||
<Step title="Receive Webhook Notification">
|
||||
Once the crew completes the task requiring human input, you'll receive a webhook notification containing:
|
||||
- Execution ID
|
||||
- Task ID
|
||||
- Task output
|
||||
</Step>
|
||||
|
||||
<Step title="Review Task Output">
|
||||
The system will pause in the `Pending Human Input` state. Review the task output carefully.
|
||||
</Step>
|
||||
|
||||
<Step title="Submit Human Feedback">
|
||||
Call the resume endpoint of your crew with the following information:
|
||||
<Frame>
|
||||
<img src="/images/enterprise/crew-resume-endpoint.png" alt="Crew Resume Endpoint" />
|
||||
</Frame>
|
||||
<Warning>
|
||||
**Feedback Impact on Task Execution**:
|
||||
It's crucial to exercise care when providing feedback, as the entire feedback content will be incorporated as additional context for further task executions.
|
||||
</Warning>
|
||||
This means:
|
||||
- All information in your feedback becomes part of the task's context.
|
||||
- Irrelevant details may negatively influence it.
|
||||
- Concise, relevant feedback helps maintain task focus and efficiency.
|
||||
- Always review your feedback carefully before submission to ensure it contains only pertinent information that will positively guide the task's execution.
|
||||
</Step>
|
||||
<Step title="Handle Negative Feedback">
|
||||
If you provide negative feedback:
|
||||
- The crew will retry the task with added context from your feedback.
|
||||
- You'll receive another webhook notification for further review.
|
||||
- Repeat steps 4-6 until satisfied.
|
||||
</Step>
|
||||
|
||||
<Step title="Execution Continuation">
|
||||
When you submit positive feedback, the execution will proceed to the next steps.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Be Specific**: Provide clear, actionable feedback that directly addresses the task at hand
|
||||
- **Stay Relevant**: Only include information that will help improve the task execution
|
||||
- **Be Timely**: Respond to HITL prompts promptly to avoid workflow delays
|
||||
- **Review Carefully**: Double-check your feedback before submitting to ensure accuracy
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
HITL workflows are particularly valuable for:
|
||||
- Quality assurance and validation
|
||||
- Complex decision-making scenarios
|
||||
- Sensitive or high-stakes operations
|
||||
- Creative tasks requiring human judgment
|
||||
- Compliance and regulatory reviews
|
||||
@@ -60,12 +60,12 @@ writer = Agent(
|
||||
# Create tasks for your agents
|
||||
task1 = Task(
|
||||
description=(
|
||||
"Conduct a comprehensive analysis of the latest advancements in AI in 2024. "
|
||||
"Conduct a comprehensive analysis of the latest advancements in AI in 2025. "
|
||||
"Identify key trends, breakthrough technologies, and potential industry impacts. "
|
||||
"Compile your findings in a detailed report. "
|
||||
"Make sure to check with a human if the draft is good before finalizing your answer."
|
||||
),
|
||||
expected_output='A comprehensive full report on the latest AI advancements in 2024, leave nothing out',
|
||||
expected_output='A comprehensive full report on the latest AI advancements in 2025, leave nothing out',
|
||||
agent=researcher,
|
||||
human_input=True
|
||||
)
|
||||
@@ -76,7 +76,7 @@ task2 = Task(
|
||||
"Your post should be informative yet accessible, catering to a tech-savvy audience. "
|
||||
"Aim for a narrative that captures the essence of these breakthroughs and their implications for the future."
|
||||
),
|
||||
expected_output='A compelling 3 paragraphs blog post formatted as markdown about the latest AI advancements in 2024',
|
||||
expected_output='A compelling 3 paragraphs blog post formatted as markdown about the latest AI advancements in 2025',
|
||||
agent=writer,
|
||||
human_input=True
|
||||
)
|
||||
@@ -54,7 +54,8 @@ coding_agent = Agent(
|
||||
# Create a task that requires code execution
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
# Create a crew and add the task
|
||||
@@ -91,12 +92,14 @@ coding_agent = Agent(
|
||||
# Create tasks that require code execution
|
||||
task_1 = Task(
|
||||
description="Analyze the first dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
task_2 = Task(
|
||||
description="Analyze the second dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
# Create two crews and add tasks
|
||||
@@ -105,6 +108,7 @@ crew_2 = Crew(agents=[coding_agent], tasks=[task_2])
|
||||
|
||||
# Async function to kickoff multiple crews asynchronously and wait for all to finish
|
||||
async def async_multiple_crews():
|
||||
# Create coroutines for concurrent execution
|
||||
result_1 = crew_1.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
result_2 = crew_2.kickoff_async(inputs={"ages": [20, 22, 24, 28, 30]})
|
||||
|
||||
@@ -116,4 +120,4 @@ async def async_multiple_crews():
|
||||
|
||||
# Run the async function
|
||||
asyncio.run(async_multiple_crews())
|
||||
```
|
||||
```
|
||||
@@ -39,8 +39,7 @@ analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task],
|
||||
verbose=True,
|
||||
memory=False,
|
||||
respect_context_window=True # enable by default
|
||||
memory=False
|
||||
)
|
||||
|
||||
datasets = [
|
||||
@@ -9,7 +9,7 @@ icon: brain-circuit
|
||||
CrewAI uses LiteLLM to connect to a wide variety of Language Models (LLMs). This integration provides extensive versatility, allowing you to use models from numerous providers with a simple, unified interface.
|
||||
|
||||
<Note>
|
||||
By default, CrewAI uses the `gpt-4o-mini` model. This is determined by the `OPENAI_MODEL_NAME` environment variable, which defaults to "gpt-4o-mini" if not set.
|
||||
By default, CrewAI uses the `gpt-4o-mini` model. This is determined by the `OPENAI_MODEL_NAME` environment variable, which defaults to "gpt-4o-mini" if not set.
|
||||
You can easily configure your agents to use a different model or provider as described in this guide.
|
||||
</Note>
|
||||
|
||||
@@ -23,6 +23,7 @@ LiteLLM supports a wide range of providers, including but not limited to:
|
||||
- Azure OpenAI
|
||||
- AWS (Bedrock, SageMaker)
|
||||
- Cohere
|
||||
- VoyageAI
|
||||
- Hugging Face
|
||||
- Ollama
|
||||
- Mistral AI
|
||||
@@ -33,6 +34,7 @@ LiteLLM supports a wide range of providers, including but not limited to:
|
||||
- DeepInfra
|
||||
- Groq
|
||||
- SambaNova
|
||||
- Nebius AI Studio
|
||||
- [NVIDIA NIMs](https://docs.api.nvidia.com/nim/reference/models-1)
|
||||
- And many more!
|
||||
|
||||
@@ -116,18 +118,27 @@ You can connect to OpenAI-compatible LLMs using either environment variables or
|
||||
<Tabs>
|
||||
<Tab title="Using Environment Variables">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
```python Generic
|
||||
import os
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your-api-key"
|
||||
os.environ["OPENAI_API_BASE"] = "https://api.your-provider.com/v1"
|
||||
os.environ["OPENAI_MODEL_NAME"] = "your-model-name"
|
||||
```
|
||||
|
||||
```python Google
|
||||
import os
|
||||
|
||||
# Example using Gemini's OpenAI-compatible API.
|
||||
os.environ["OPENAI_API_KEY"] = "your-gemini-key" # Should start with AIza...
|
||||
os.environ["OPENAI_API_BASE"] = "https://generativelanguage.googleapis.com/v1beta/openai/"
|
||||
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-2.0-flash" # Add your Gemini model here, under openai/
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="Using LLM Class Attributes">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
```python Generic
|
||||
llm = LLM(
|
||||
model="custom-model-name",
|
||||
api_key="your-api-key",
|
||||
@@ -135,6 +146,16 @@ You can connect to OpenAI-compatible LLMs using either environment variables or
|
||||
)
|
||||
agent = Agent(llm=llm, ...)
|
||||
```
|
||||
|
||||
```python Google
|
||||
# Example using Gemini's OpenAI-compatible API
|
||||
llm = LLM(
|
||||
model="openai/gemini-2.0-flash",
|
||||
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
api_key="your-gemini-key", # Should start with AIza...
|
||||
)
|
||||
agent = Agent(llm=llm, ...)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -168,7 +189,7 @@ For local models like those provided by Ollama:
|
||||
|
||||
You can change the base API URL for any LLM provider by setting the `base_url` parameter:
|
||||
|
||||
```python Code
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="custom-model-name",
|
||||
base_url="https://api.your-provider.com/v1",
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user