mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-07 17:33:33 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3bfc6f795 | ||
|
|
ebc130854d | ||
|
|
f40a5c1359 | ||
|
|
3284f7bbc6 | ||
|
|
87928611f7 | ||
|
|
2727bf5992 | ||
|
|
45d04163c3 | ||
|
|
477d0d2e26 | ||
|
|
77394f5e5f | ||
|
|
29e533c18c | ||
|
|
48dbea0566 | ||
|
|
969d6697e1 | ||
|
|
787d2508b1 | ||
|
|
ec42dc92e4 | ||
|
|
5b7bae2f43 | ||
|
|
69a1efac47 | ||
|
|
e6381139ec | ||
|
|
aca2a58971 | ||
|
|
7a07ebd05e | ||
|
|
418d6c810b | ||
|
|
8bcfdfe713 | ||
|
|
57f2fa0471 | ||
|
|
2fdffd2d8d | ||
|
|
471a6a106c | ||
|
|
7c51c3aad1 | ||
|
|
dfa261f5ef | ||
|
|
9a97f0b80f | ||
|
|
eef9a5f7ae | ||
|
|
510e9b1797 | ||
|
|
89f48cf7a2 | ||
|
|
97fb7fdd52 | ||
|
|
ea4cb42324 | ||
|
|
43da66d129 | ||
|
|
e1a61959ea | ||
|
|
71c5b929b7 | ||
|
|
c9edf19907 | ||
|
|
6cdc79f4a2 | ||
|
|
fdda350b72 | ||
|
|
85f748d5d1 | ||
|
|
bf24548598 | ||
|
|
a1622a2a79 | ||
|
|
209faff03c | ||
|
|
ad67089813 | ||
|
|
3e44eadd37 | ||
|
|
764e9aa838 | ||
|
|
ccfc92564e | ||
|
|
1f61000922 | ||
|
|
2164f3e658 | ||
|
|
739a9ff8b5 | ||
|
|
dbe63cbbc9 | ||
|
|
f4bff11e83 | ||
|
|
6552f61322 | ||
|
|
d5d898ff1b | ||
|
|
4df8d122fc | ||
|
|
766e5789e3 | ||
|
|
f9585e83cb | ||
|
|
e019bab987 | ||
|
|
54072a1d55 | ||
|
|
16ddcb8644 | ||
|
|
e0b9739b66 | ||
|
|
1bb6c8ca61 | ||
|
|
a242a26353 | ||
|
|
ff4f63fc54 | ||
|
|
48707686f0 | ||
|
|
1a414989bf | ||
|
|
141535c160 | ||
|
|
6911d6ad64 | ||
|
|
6b4be5ca2f | ||
|
|
a5d08f8f33 | ||
|
|
8e0fa939a4 | ||
|
|
359d02bd56 | ||
|
|
7630e35622 | ||
|
|
1fc3a22335 | ||
|
|
3d56de7d64 | ||
|
|
6008f5c9b6 | ||
|
|
6b9a186751 | ||
|
|
ce0e46b7f4 | ||
|
|
74563a2fbb | ||
|
|
92324d55d2 | ||
|
|
280c66ad94 | ||
|
|
dc9faba1c9 | ||
|
|
10d9f00fd5 | ||
|
|
5c9ac6f222 | ||
|
|
8ea7c3289f | ||
|
|
2ac83534d8 | ||
|
|
ba5af94dcb | ||
|
|
b1d9ef567b | ||
|
|
e633ad959d | ||
|
|
27065af652 | ||
|
|
46585a88e6 | ||
|
|
312d1a8734 | ||
|
|
311034e78b | ||
|
|
509d8492ec | ||
|
|
cb4ee28e7e | ||
|
|
7f23daf670 | ||
|
|
223650dad5 | ||
|
|
1e23d76742 | ||
|
|
83adac3709 | ||
|
|
e3a5f87a1f | ||
|
|
63f94c6a4d | ||
|
|
ecb4974333 | ||
|
|
955a05be59 | ||
|
|
b95b88d0cb | ||
|
|
f6526ab127 | ||
|
|
9b155e54e2 | ||
|
|
66dc2e3c48 | ||
|
|
90c3a90752 | ||
|
|
a2d7629492 | ||
|
|
a904673325 | ||
|
|
a6d1ef93e0 | ||
|
|
d1989159bc | ||
|
|
b2a0f5b341 | ||
|
|
caabe553ce | ||
|
|
f62601ed47 | ||
|
|
402796020c | ||
|
|
3a30c3813d | ||
|
|
8e16621f46 | ||
|
|
f86e9ef470 | ||
|
|
c4058143aa | ||
|
|
6b4ed568a8 | ||
|
|
1ba540f0ab | ||
|
|
ce4103d311 | ||
|
|
a21c9ea15a | ||
|
|
422d638cd4 | ||
|
|
baa5caf3c3 | ||
|
|
4a51cae4f8 | ||
|
|
caa4473871 | ||
|
|
acdfc54302 | ||
|
|
3856be09df | ||
|
|
81f0f49d15 | ||
|
|
13e425e0ac | ||
|
|
9c9a8b249e | ||
|
|
ff4ab536af | ||
|
|
7a7b9bd0d4 | ||
|
|
8900fdcc95 | ||
|
|
e7f7b1239c | ||
|
|
9596b49f3c | ||
|
|
6fa66157ae | ||
|
|
c50e3d94b5 | ||
|
|
0ef82bdf7e | ||
|
|
a7ce92f9ce | ||
|
|
f36415d4ea | ||
|
|
13c3e31458 | ||
|
|
41d550c4a5 | ||
|
|
ac570e5b93 | ||
|
|
65e389af03 | ||
|
|
a5465882ee | ||
|
|
f86b03e5d8 | ||
|
|
397a466f55 | ||
|
|
36c3066ba4 | ||
|
|
df06e794b3 | ||
|
|
71fe678d66 | ||
|
|
c8875eec81 | ||
|
|
f88204d2e8 | ||
|
|
fc01a80956 | ||
|
|
cd91565b12 | ||
|
|
d233d4597c | ||
|
|
a9fabce0ea | ||
|
|
6bcd3ba9bd | ||
|
|
37028b0dd2 | ||
|
|
6807d0e017 | ||
|
|
bca845d771 | ||
|
|
0596d2da2e | ||
|
|
368498452c | ||
|
|
47e5ad2a65 | ||
|
|
eb346be5f8 | ||
|
|
62ab76f3e9 | ||
|
|
ac26c5fbe8 | ||
|
|
22c10ff6ac | ||
|
|
494f835e73 | ||
|
|
3686eb2eaa | ||
|
|
58c63f0dd4 | ||
|
|
7bf5c0a4d8 | ||
|
|
082d802fd9 | ||
|
|
8cd926a244 | ||
|
|
987f63f032 | ||
|
|
bec938883d | ||
|
|
76079a92fe | ||
|
|
c14fb2ee5d | ||
|
|
31c9a6a994 | ||
|
|
b5b4370cc8 | ||
|
|
745f82b9c4 | ||
|
|
6845c7b0f6 | ||
|
|
e7be52722e | ||
|
|
e673189454 | ||
|
|
ab9192c57e | ||
|
|
819874275f | ||
|
|
0a36fdb966 | ||
|
|
768549bb52 | ||
|
|
5d1bc19e15 | ||
|
|
05a114f939 | ||
|
|
4b9d291d16 | ||
|
|
5eb8862a7e | ||
|
|
0bacff3997 | ||
|
|
ac8e6daadf | ||
|
|
f4cf97abdb | ||
|
|
2f0e3c0507 | ||
|
|
5e11f7566d | ||
|
|
66a8c9e074 | ||
|
|
2ef8250d49 | ||
|
|
090f1d1339 | ||
|
|
e299a5aaf3 | ||
|
|
15bda4df81 | ||
|
|
57fdc5e4ed | ||
|
|
54cb01426f | ||
|
|
f3d61459fe | ||
|
|
ff309010b9 | ||
|
|
53d7d7e7f7 | ||
|
|
c133e24816 | ||
|
|
318131bb92 | ||
|
|
6cfa8f30d7 | ||
|
|
f6b1517aa0 | ||
|
|
624837356e | ||
|
|
df12ae032f | ||
|
|
c405aaf121 | ||
|
|
03e2bb94f2 | ||
|
|
5e3e503dd9 | ||
|
|
633d724eb2 | ||
|
|
5cfda3fa54 | ||
|
|
370cb108f2 | ||
|
|
83cb80e907 | ||
|
|
f385de04e0 | ||
|
|
18695543e5 | ||
|
|
267f223a3e | ||
|
|
02bd52a06d | ||
|
|
076576af85 | ||
|
|
17547073ec | ||
|
|
124a95d7d0 | ||
|
|
8ca4e3285d | ||
|
|
5eac60dab3 | ||
|
|
59ee7cbbe5 | ||
|
|
81517b58e5 | ||
|
|
c1a8338a24 | ||
|
|
dba5a49569 | ||
|
|
6dab69e9d7 | ||
|
|
90563207f7 | ||
|
|
46330b0487 | ||
|
|
a133f0d5e2 | ||
|
|
fb22e6e1c7 | ||
|
|
e938fe63ea | ||
|
|
ef96e53843 | ||
|
|
036c463a43 | ||
|
|
0e6b4aefc3 | ||
|
|
bbb9f677ae | ||
|
|
0da201b3b6 | ||
|
|
a7b85043e1 | ||
|
|
dc393e1211 | ||
|
|
fdff17faf9 | ||
|
|
b3d893fae1 | ||
|
|
d92dede515 | ||
|
|
a1882233dc | ||
|
|
aa6b6ac62e | ||
|
|
c540ba34fb | ||
|
|
0abb1b659a | ||
|
|
81adb28688 | ||
|
|
5fbe6e948c | ||
|
|
6128e4c885 | ||
|
|
0e563989ed | ||
|
|
510a853e05 | ||
|
|
d6084cb7ce | ||
|
|
8d4b1c411b | ||
|
|
3be05c855b | ||
|
|
3e5a2f76f4 | ||
|
|
8eee881d2e | ||
|
|
d75f4be41a | ||
|
|
9ea89448ef | ||
|
|
0a5e2df278 | ||
|
|
cc3b64f89b | ||
|
|
546dc5a441 | ||
|
|
bd7422c7ca | ||
|
|
0c2c6da8dd | ||
|
|
b43688086f | ||
|
|
820619e8d9 | ||
|
|
94202adddd | ||
|
|
c7911629b1 | ||
|
|
5a4e3ba707 | ||
|
|
641057b622 | ||
|
|
db1dbf142e | ||
|
|
d9a19ae277 | ||
|
|
3c9d889b4f | ||
|
|
2f324e74db | ||
|
|
c22fef3e6d | ||
|
|
53bee19948 | ||
|
|
798fe68908 | ||
|
|
95796cd4c7 | ||
|
|
b447b7e6eb | ||
|
|
29dfe4b192 | ||
|
|
aca95b1713 | ||
|
|
b4cc3d7a8e | ||
|
|
c6c27e58a6 | ||
|
|
ae21881522 | ||
|
|
68efb982af | ||
|
|
c539306b96 | ||
|
|
c2f2d43d0d | ||
|
|
7847515b4b | ||
|
|
1f2c412521 | ||
|
|
355fe1e59c | ||
|
|
2ed64adc48 | ||
|
|
b8bc8583b1 | ||
|
|
51a3a065c4 | ||
|
|
4ba8745544 | ||
|
|
efc347f507 | ||
|
|
72a162c722 | ||
|
|
734a632dd4 | ||
|
|
dfaa3ed671 | ||
|
|
175b55704d | ||
|
|
084d1a2820 | ||
|
|
8518c3ae9d | ||
|
|
ac95c0000b | ||
|
|
8447e02f5d | ||
|
|
3e612f61dc | ||
|
|
b39c04dfb5 | ||
|
|
8fc367ee6d | ||
|
|
f7f157d3e7 | ||
|
|
05ede2a366 | ||
|
|
f8a2a93400 | ||
|
|
1a77826a21 | ||
|
|
adfd982547 | ||
|
|
facd52103e | ||
|
|
06d3d3decb | ||
|
|
7f35ac6113 | ||
|
|
e68fbb46f6 | ||
|
|
50a7bf6c91 | ||
|
|
eaf337b301 | ||
|
|
bce6e424d8 | ||
|
|
5cad05dc0d | ||
|
|
3ecc722866 | ||
|
|
2f73cf1882 | ||
|
|
c881fb3280 | ||
|
|
15f9cbbe47 | ||
|
|
f431347793 | ||
|
|
e0725c1296 | ||
|
|
b40295efb9 | ||
|
|
2f7769d334 | ||
|
|
c326aaf015 | ||
|
|
03874553eb | ||
|
|
97ae6647c9 | ||
|
|
046fb7cbe7 | ||
|
|
afdd6ab6f8 | ||
|
|
4581486a81 | ||
|
|
e10b991fab | ||
|
|
2d790f79a9 | ||
|
|
ec04dd7a91 | ||
|
|
bd49416f2b | ||
|
|
da2e11921c | ||
|
|
8287c3a3d4 | ||
|
|
6904f86557 | ||
|
|
cbebb3a900 | ||
|
|
413484ea9f | ||
|
|
785317c4fa | ||
|
|
c70f9ebf1f | ||
|
|
d278f2d2b2 | ||
|
|
df4596a699 | ||
|
|
dd0f47ec81 | ||
|
|
e53017a2fe | ||
|
|
fe034ba8f4 | ||
|
|
063e5780d6 | ||
|
|
904e21ca87 | ||
|
|
526665ea11 | ||
|
|
c2e97d2432 | ||
|
|
60be6a1f99 | ||
|
|
680949742e | ||
|
|
560219dcd7 | ||
|
|
0ba7d2e834 | ||
|
|
184b241395 | ||
|
|
4354e76fe5 | ||
|
|
4dd77efb75 | ||
|
|
11db6e18ba | ||
|
|
0d6f698e6c | ||
|
|
b8574f78e2 | ||
|
|
e631774a0f | ||
|
|
df735aa748 | ||
|
|
3bdf5b6c65 | ||
|
|
361fa67108 | ||
|
|
c5abcf362a | ||
|
|
7ed2d99a11 | ||
|
|
81307da7c8 | ||
|
|
fb75153b5c | ||
|
|
cddcfcf170 | ||
|
|
398b0473e0 | ||
|
|
c5d260782a | ||
|
|
116ac5a64d | ||
|
|
abf6e2e8d1 | ||
|
|
cb2b3617fa | ||
|
|
6de67c7d0d | ||
|
|
5699d90894 | ||
|
|
2982e8ea9c | ||
|
|
9dd2146342 | ||
|
|
f79184a6ee | ||
|
|
0985e12ad4 | ||
|
|
0fbb7972e1 | ||
|
|
5744ae853e | ||
|
|
bd6e3da4ff | ||
|
|
f2f51d9e8b | ||
|
|
4a1098603d | ||
|
|
5468e35bc1 | ||
|
|
b468267a87 | ||
|
|
48141bbd9e | ||
|
|
b3cdf53d07 | ||
|
|
aa594ddc32 | ||
|
|
5f330e8fb2 | ||
|
|
ff94e128de | ||
|
|
854a016fc5 | ||
|
|
12e8ed7b77 | ||
|
|
13c5f5537e | ||
|
|
e7c1614ac8 | ||
|
|
7cc6db2a34 | ||
|
|
b869bbc346 | ||
|
|
5492be4412 | ||
|
|
c2e33ef6a6 | ||
|
|
5b2e0a9417 | ||
|
|
2f6d9ebcc9 | ||
|
|
0610a5b3a4 | ||
|
|
7463744e62 | ||
|
|
c7428b8282 | ||
|
|
ff1deb6b97 | ||
|
|
bdbed2667d | ||
|
|
2810ec879c | ||
|
|
04a8c621bb | ||
|
|
17cbadaf64 | ||
|
|
fbcdf84350 | ||
|
|
ab3295caa1 | ||
|
|
95517f5007 | ||
|
|
3800825b38 | ||
|
|
f85e16ab87 | ||
|
|
dbdd3d3d9a | ||
|
|
1cc5dad01f | ||
|
|
3797e4fe25 | ||
|
|
d840e7d0ef | ||
|
|
6f9ca636aa | ||
|
|
f254d9e290 | ||
|
|
2e95279cd5 | ||
|
|
c218ad62ce | ||
|
|
d10849085d | ||
|
|
9594426fc2 | ||
|
|
1c6fc71a06 | ||
|
|
d7289acc1d | ||
|
|
54a748b4c7 | ||
|
|
9f62e9201a | ||
|
|
1b69360d9f | ||
|
|
9bdc6545ad | ||
|
|
06cd909367 | ||
|
|
67aeece7fc | ||
|
|
ef67d0753c | ||
|
|
f374f9f791 | ||
|
|
492fb29af9 | ||
|
|
cd56ebd5cf | ||
|
|
08e99f6ef7 | ||
|
|
670d653ae9 | ||
|
|
faa014b8b0 | ||
|
|
6d454d0c6e | ||
|
|
0ec3fe3510 | ||
|
|
707888cdf9 | ||
|
|
42051630bc | ||
|
|
bfcccb6355 | ||
|
|
e329afc394 | ||
|
|
9417cc6457 | ||
|
|
10a3d279ae | ||
|
|
2a916208e1 | ||
|
|
bcd0bbbd24 | ||
|
|
5701a40f11 | ||
|
|
3ffac395bb | ||
|
|
37119aa3ac | ||
|
|
8b2d324d3b | ||
|
|
6d0b29e60d | ||
|
|
583cbc5efa | ||
|
|
90dd84a152 | ||
|
|
ef7fa66e33 | ||
|
|
1659ed61bc | ||
|
|
b8939ef439 | ||
|
|
4bada9e5fc | ||
|
|
51c4cb00b0 | ||
|
|
ad96549ea3 | ||
|
|
183d10d7cc | ||
|
|
bce1559ab5 | ||
|
|
6f3fb87ba3 | ||
|
|
e7f6b2df67 | ||
|
|
08d72eeb80 | ||
|
|
11aefae90f | ||
|
|
10d5158d27 | ||
|
|
1d8b814fcd | ||
|
|
6e8a5b98a8 | ||
|
|
59d0ff8c95 | ||
|
|
b2109faa06 | ||
|
|
024eaed456 | ||
|
|
4fd3a572cf | ||
|
|
baaf8b6256 | ||
|
|
fe4550d2bc | ||
|
|
db09a94425 | ||
|
|
2db36dc932 | ||
|
|
8c0e4277a4 | ||
|
|
41448617d5 | ||
|
|
49ea23c676 | ||
|
|
bb0dc63680 | ||
|
|
7774f2c565 | ||
|
|
5533fd3476 | ||
|
|
262a90a235 | ||
|
|
60928dcb90 | ||
|
|
c8552e1158 | ||
|
|
c57d7db9bb | ||
|
|
236abc2c83 | ||
|
|
76c5f8fe3f | ||
|
|
82750020d2 | ||
|
|
f49ad9fbc2 | ||
|
|
c086c60fd6 | ||
|
|
4f8f4f2036 | ||
|
|
8e91c20967 | ||
|
|
6f092c1507 | ||
|
|
8f553d3a54 | ||
|
|
2d647e25b5 | ||
|
|
039bb772f5 | ||
|
|
459c2f2b70 | ||
|
|
ee59706357 | ||
|
|
2a51644773 | ||
|
|
cce908fa22 | ||
|
|
acf476f715 | ||
|
|
e5d77de79c | ||
|
|
9ab444b54c | ||
|
|
e13f543c6d | ||
|
|
4f235d358c | ||
|
|
b7847feb1e | ||
|
|
7ac730462c | ||
|
|
9cbc8d082d | ||
|
|
7fb0aed7ac | ||
|
|
206f0d01e7 | ||
|
|
e19a310314 | ||
|
|
1ea572689e | ||
|
|
96df649b05 | ||
|
|
5aed75837a | ||
|
|
9c8f68a05f | ||
|
|
9778a69c4d | ||
|
|
73c7994380 | ||
|
|
82b83ded41 | ||
|
|
fc80db32c2 | ||
|
|
3f115ca7ba | ||
|
|
a32d45e6da | ||
|
|
8823df26ff | ||
|
|
9c2126fbd6 | ||
|
|
741b01bdf0 | ||
|
|
6ed9a69cd8 | ||
|
|
56a42e6d95 | ||
|
|
d2b4affdd1 | ||
|
|
0d5c8b478f | ||
|
|
fdfad70319 | ||
|
|
fba6b2e2a0 | ||
|
|
f9bfb85f44 | ||
|
|
aab4b5b466 | ||
|
|
7ccadde004 | ||
|
|
22a9d5ff23 | ||
|
|
98a11209ea | ||
|
|
df3c97e73a | ||
|
|
27808964be | ||
|
|
b5daf16e0d | ||
|
|
a2cac05d16 | ||
|
|
ad9828d3bb | ||
|
|
85ddf04b47 | ||
|
|
1c1a1b719b | ||
|
|
a8e0914e05 | ||
|
|
ec6d883f4f | ||
|
|
d094cbfac5 | ||
|
|
14e3724aed | ||
|
|
92436277d9 | ||
|
|
3e0fd298e2 | ||
|
|
fad0b41b52 | ||
|
|
6c3e5ee187 | ||
|
|
f842ee7048 | ||
|
|
b0ff6f3f60 | ||
|
|
798f6dad14 | ||
|
|
629bf0d669 | ||
|
|
eaca447b82 | ||
|
|
bef3693627 | ||
|
|
aa62babed6 | ||
|
|
b73f181200 | ||
|
|
66d2998047 | ||
|
|
c5b6f8b91a | ||
|
|
823e46ca84 | ||
|
|
57040333a7 | ||
|
|
8c6800f876 | ||
|
|
0d701ae43c | ||
|
|
7a8c25621c | ||
|
|
218c5443b1 | ||
|
|
f56810341c | ||
|
|
4f601a573f |
No files matched your search
-1885
File diff suppressed because it is too large.
Load diff
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"extends": ["plugin:mdx/recommended"],
|
||||
// optional, if you want to lint code blocks at the same time
|
||||
"settings": {
|
||||
"mdx/code-blocks": true,
|
||||
// optional, if you want to disable language mapper, set it to `false`
|
||||
// if you want to override the default language mapper inside, you can provide your own
|
||||
"mdx/language-mapper": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
|
||||
@@ -19,22 +19,48 @@ jobs:
|
||||
python-version: ["3.10", "3.11"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v3
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install flake8 pytest
|
||||
python -m pip install ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
python -m pip install duckduckgo_search
|
||||
python -m pip install pytest-asyncio pytest-cov
|
||||
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
||||
|
||||
- name: Debug API Key Status
|
||||
run: |
|
||||
echo "🔍 Checking API key availability..."
|
||||
if [ -n "${{ secrets.OPENAI_API_KEY }}" ]; then
|
||||
echo "✅ GitHub secret OPENAI_API_KEY is available"
|
||||
echo "🔑 API key starts with: $(echo "$OPENAI_API_KEY" | cut -c1-7)..."
|
||||
else
|
||||
echo "⚠️ GitHub secret OPENAI_API_KEY is NOT set - using fallback"
|
||||
echo "🔑 Using fallback key: sk-test-key..."
|
||||
fi
|
||||
echo "🌐 API Base: $OPENAI_API_BASE"
|
||||
echo "🤖 Model: $OPENAI_MODEL_NAME"
|
||||
|
||||
# - name: Lint with flake8
|
||||
# run: |
|
||||
# # stop the build if there are Python syntax errors or undefined names
|
||||
# flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
|
||||
# # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
|
||||
# flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
|
||||
# - name: Test with pytest
|
||||
# run: |
|
||||
# pytest
|
||||
- name: Test with pytest
|
||||
run: |
|
||||
cd src/praisonai && python -m pytest
|
||||
@@ -21,9 +21,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v3
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.x'
|
||||
- name: Install dependencies
|
||||
@@ -31,9 +31,10 @@ jobs:
|
||||
python -m pip install --upgrade pip
|
||||
pip install build
|
||||
- name: Build package
|
||||
run: python -m build
|
||||
run: python -m build src/praisonai
|
||||
- name: Publish package
|
||||
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
|
||||
with:
|
||||
user: __token__
|
||||
password: ${{ secrets.PYPI_API_TOKEN }}
|
||||
packages_dir: src/praisonai/dist/
|
||||
@@ -64,7 +64,7 @@ jobs:
|
||||
git reset --hard ${{ steps.get_commit.outputs.commit_hash }}
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
cache: 'pip'
|
||||
@@ -422,7 +422,7 @@ jobs:
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: praisonai-output-${{ matrix.os }}-${{ matrix.framework }}
|
||||
path: test_output/
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
name: Comprehensive Test Suite
|
||||
|
||||
on:
|
||||
workflow_dispatch: # Allow manual triggering
|
||||
inputs:
|
||||
test_type:
|
||||
description: 'Type of tests to run'
|
||||
required: true
|
||||
default: 'all'
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- unit
|
||||
- integration
|
||||
- fast
|
||||
- performance
|
||||
- frameworks
|
||||
- autogen
|
||||
- crewai
|
||||
release:
|
||||
types: [published, prereleased]
|
||||
schedule:
|
||||
# Run comprehensive tests weekly on Sundays at 3 AM UTC
|
||||
- cron: '0 3 * * 0'
|
||||
|
||||
jobs:
|
||||
comprehensive-test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.11"]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system duckduckgo_search
|
||||
uv pip install --system pytest pytest-asyncio pytest-cov pytest-benchmark
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Run Comprehensive Test Suite
|
||||
run: |
|
||||
# Determine test type from input or default to 'all'
|
||||
TEST_TYPE="${{ github.event.inputs.test_type || 'all' }}"
|
||||
|
||||
echo "🧪 Running comprehensive test suite (type: $TEST_TYPE)"
|
||||
|
||||
case $TEST_TYPE in
|
||||
"unit")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern unit
|
||||
;;
|
||||
"integration")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern integration
|
||||
;;
|
||||
"fast")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern fast
|
||||
;;
|
||||
"performance")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern "performance"
|
||||
;;
|
||||
"frameworks")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern frameworks
|
||||
;;
|
||||
"autogen")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern autogen
|
||||
;;
|
||||
"crewai")
|
||||
cd src/praisonai && python tests/test_runner.py --pattern crewai
|
||||
;;
|
||||
"all"|*)
|
||||
cd src/praisonai && python tests/test_runner.py --pattern all
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Generate Comprehensive Test Report
|
||||
if: always()
|
||||
run: |
|
||||
echo "# 📋 Comprehensive Test Report" > comprehensive_report.md
|
||||
echo "" >> comprehensive_report.md
|
||||
echo "**Python Version:** ${{ matrix.python-version }}" >> comprehensive_report.md
|
||||
echo "**Test Type:** ${{ github.event.inputs.test_type || 'all' }}" >> comprehensive_report.md
|
||||
echo "**Trigger:** ${{ github.event_name }}" >> comprehensive_report.md
|
||||
echo "**Date:** $(date -u)" >> comprehensive_report.md
|
||||
echo "" >> comprehensive_report.md
|
||||
|
||||
echo "## 🧪 Test Categories Covered:" >> comprehensive_report.md
|
||||
echo "" >> comprehensive_report.md
|
||||
echo "### Unit Tests:" >> comprehensive_report.md
|
||||
echo "- ✅ Core agent functionality" >> comprehensive_report.md
|
||||
echo "- ✅ Async operations" >> comprehensive_report.md
|
||||
echo "- ✅ Tool integrations" >> comprehensive_report.md
|
||||
echo "- ✅ UI components" >> comprehensive_report.md
|
||||
echo "" >> comprehensive_report.md
|
||||
|
||||
echo "### Integration Tests:" >> comprehensive_report.md
|
||||
echo "- ✅ MCP (Model Context Protocol)" >> comprehensive_report.md
|
||||
echo "- ✅ RAG (Retrieval Augmented Generation)" >> comprehensive_report.md
|
||||
echo "- ✅ Base URL API mapping" >> comprehensive_report.md
|
||||
echo "- ✅ Multi-agent workflows" >> comprehensive_report.md
|
||||
echo "- ✅ AutoGen framework integration" >> comprehensive_report.md
|
||||
echo "- ✅ CrewAI framework integration" >> comprehensive_report.md
|
||||
echo "- 💬 LLM integrations (OpenAI, Anthropic, etc.)" >> comprehensive_report.md
|
||||
echo "- 🖥️ UI frameworks (Gradio, Streamlit)" >> comprehensive_report.md
|
||||
echo "- 📊 Memory and persistence" >> comprehensive_report.md
|
||||
echo "- 🌐 Multi-modal capabilities" >> comprehensive_report.md
|
||||
|
||||
echo "- ✅ AutoGen framework integration" >> comprehensive_report.md
|
||||
echo "- ✅ CrewAI framework integration" >> comprehensive_report.md
|
||||
echo "" >> comprehensive_report.md
|
||||
|
||||
echo "### Key Features Tested:" >> comprehensive_report.md
|
||||
echo "- 🤖 Agent creation and configuration" >> comprehensive_report.md
|
||||
echo "- 📋 Task management and execution" >> comprehensive_report.md
|
||||
echo "- 🔄 Sync/async workflows" >> comprehensive_report.md
|
||||
echo "- 🛠️ Custom tools and error handling" >> comprehensive_report.md
|
||||
echo "- 🧠 Knowledge bases and RAG" >> comprehensive_report.md
|
||||
echo "- 🔌 MCP server connections" >> comprehensive_report.md
|
||||
echo "- 💬 LLM integrations (OpenAI, Anthropic, etc.)" >> comprehensive_report.md
|
||||
|
||||
- name: Upload Comprehensive Test Results
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: comprehensive-test-results-python-${{ matrix.python-version }}
|
||||
path: |
|
||||
comprehensive_report.md
|
||||
htmlcov/
|
||||
coverage.xml
|
||||
.coverage
|
||||
retention-days: 30
|
||||
|
||||
test-matrix-summary:
|
||||
runs-on: ubuntu-latest
|
||||
needs: comprehensive-test
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
- name: Generate Matrix Summary
|
||||
run: |
|
||||
echo "# 🎯 Test Matrix Summary" > matrix_summary.md
|
||||
echo "" >> matrix_summary.md
|
||||
echo "## Python Version Results:" >> matrix_summary.md
|
||||
echo "- Python 3.10: ${{ needs.comprehensive-test.result }}" >> matrix_summary.md
|
||||
echo "- Python 3.11: ${{ needs.comprehensive-test.result }}" >> matrix_summary.md
|
||||
echo "" >> matrix_summary.md
|
||||
echo "## Overall Status:" >> matrix_summary.md
|
||||
if [ "${{ needs.comprehensive-test.result }}" == "success" ]; then
|
||||
echo "✅ **All tests passed across all Python versions!**" >> matrix_summary.md
|
||||
else
|
||||
echo "❌ **Some tests failed. Check individual job logs for details.**" >> matrix_summary.md
|
||||
fi
|
||||
|
||||
- name: Upload Matrix Summary
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: test-matrix-summary
|
||||
path: matrix_summary.md
|
||||
retention-days: 30
|
||||
@@ -0,0 +1,272 @@
|
||||
name: Core Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
pull_request:
|
||||
branches: [ main, develop ]
|
||||
|
||||
jobs:
|
||||
test-core:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [3.11]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system duckduckgo_search
|
||||
uv pip install --system pytest pytest-asyncio pytest-cov
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
|
||||
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
|
||||
# Also export to current shell session for immediate availability
|
||||
export OPENAI_API_KEY="${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}"
|
||||
export OPENAI_API_BASE="${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}"
|
||||
export OPENAI_MODEL_NAME="${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}"
|
||||
export LOGLEVEL=DEBUG
|
||||
# Verify immediate availability
|
||||
echo "🔧 Immediate verification in same step:"
|
||||
echo " OPENAI_API_KEY length in current session: ${#OPENAI_API_KEY}"
|
||||
echo " OPENAI_API_KEY starts with sk-: $(echo "$OPENAI_API_KEY" | grep -q '^sk-' && echo 'YES' || echo 'NO')"
|
||||
|
||||
- name: Debug API Key Status
|
||||
run: |
|
||||
echo "🔍 Checking API key availability..."
|
||||
if [ -n "${{ secrets.OPENAI_API_KEY }}" ]; then
|
||||
echo "✅ GitHub secret OPENAI_API_KEY is available"
|
||||
echo "🔑 API key starts with: $(echo "$OPENAI_API_KEY" | cut -c1-7)..."
|
||||
else
|
||||
echo "⚠️ GitHub secret OPENAI_API_KEY is NOT set - using fallback"
|
||||
echo "🔑 Using fallback key: sk-test-key..."
|
||||
fi
|
||||
echo "🌐 API Base: $OPENAI_API_BASE"
|
||||
echo "🤖 Model: $OPENAI_MODEL_NAME"
|
||||
echo "🐛 Log Level: $LOGLEVEL"
|
||||
echo "📊 Environment Check:"
|
||||
echo " - OPENAI_API_KEY length: ${#OPENAI_API_KEY}"
|
||||
echo " - OPENAI_API_BASE: $OPENAI_API_BASE"
|
||||
echo " - OPENAI_MODEL_NAME: $OPENAI_MODEL_NAME"
|
||||
echo " - LOGLEVEL: $LOGLEVEL"
|
||||
echo "🔍 Is API key actually set?"
|
||||
echo " - API key starts with sk-: $(echo "$OPENAI_API_KEY" | grep -q '^sk-' && echo 'YES' || echo 'NO')"
|
||||
echo " - API key is not test key: $([ "$OPENAI_API_KEY" != 'sk-test-key-for-github-actions-testing-only-not-real' ] && echo 'YES' || echo 'NO')"
|
||||
|
||||
- name: Debug Environment Variables Raw
|
||||
run: |
|
||||
echo "🔧 Raw environment variable check:"
|
||||
echo "OPENAI_API_KEY set: $(if [ -n "$OPENAI_API_KEY" ]; then echo 'YES'; else echo 'NO'; fi)"
|
||||
echo "OPENAI_API_KEY length: ${#OPENAI_API_KEY}"
|
||||
echo "OPENAI_API_KEY first 10 chars: ${OPENAI_API_KEY:0:10}"
|
||||
echo "OPENAI_API_KEY last 5 chars: ${OPENAI_API_KEY: -5}"
|
||||
printenv | grep OPENAI || echo "No OPENAI env vars found"
|
||||
|
||||
- name: Debug Python Environment Variables
|
||||
run: |
|
||||
python -c "
|
||||
import os
|
||||
print('🐍 Python Environment Variable Check:')
|
||||
api_key = os.environ.get('OPENAI_API_KEY', 'NOT_SET')
|
||||
if api_key != 'NOT_SET':
|
||||
print(f' ✅ OPENAI_API_KEY: {api_key[:7]}... (length: {len(api_key)})')
|
||||
else:
|
||||
print(' ❌ OPENAI_API_KEY: NOT_SET')
|
||||
print(f' 🌐 OPENAI_API_BASE: {os.environ.get(\"OPENAI_API_BASE\", \"NOT_SET\")}')
|
||||
print(f' 🤖 OPENAI_MODEL_NAME: {os.environ.get(\"OPENAI_MODEL_NAME\", \"NOT_SET\")}')
|
||||
print(f' 📋 All OPENAI env vars:')
|
||||
for key, value in os.environ.items():
|
||||
if key.startswith('OPENAI'):
|
||||
print(f' {key}: {value[:10] if len(value) > 10 else value}...')
|
||||
"
|
||||
|
||||
- name: Validate API Key
|
||||
run: |
|
||||
echo "🔑 Testing API key validity with minimal OpenAI call..."
|
||||
python -c "
|
||||
import os
|
||||
try:
|
||||
from openai import OpenAI
|
||||
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
|
||||
response = client.models.list()
|
||||
print('✅ API Key is VALID - OpenAI responded successfully')
|
||||
print(f'📊 Available models: {len(list(response.data))} models found')
|
||||
except Exception as e:
|
||||
print(f'❌ API Key is INVALID - Error: {e}')
|
||||
print('🔍 This explains why all API-dependent tests are failing')
|
||||
print('💡 The GitHub secret OPENAI_API_KEY needs to be updated with a valid key')
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Debug PraisonAI API Key Usage
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}
|
||||
OPENAI_API_BASE: ${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}
|
||||
OPENAI_MODEL_NAME: ${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}
|
||||
LOGLEVEL: DEBUG
|
||||
run: |
|
||||
echo "🔍 Testing PraisonAI API key usage directly..."
|
||||
cd src/praisonai
|
||||
python -c "
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
# Attempt to import SecretStr, otherwise use a dummy class
|
||||
try:
|
||||
from pydantic.types import SecretStr
|
||||
except ImportError:
|
||||
class SecretStr: # Dummy class if pydantic is not available in this minimal context
|
||||
def __init__(self, value): self._value = value
|
||||
def get_secret_value(self): return self._value
|
||||
|
||||
def get_key_display_value(key_value):
|
||||
if isinstance(key_value, SecretStr):
|
||||
return key_value.get_secret_value()[:10] if key_value.get_secret_value() else 'EMPTY_SECRET'
|
||||
elif isinstance(key_value, str):
|
||||
return key_value[:10] if key_value != 'nokey' and key_value != 'NOT_SET' else key_value
|
||||
return 'INVALID_TYPE'
|
||||
|
||||
print('🔧 Direct PraisonAI API Key Check:')
|
||||
env_api_key = os.environ.get(\\"OPENAI_API_KEY\\", \\"NOT_SET\\")
|
||||
print(f'Environment OPENAI_API_KEY: {get_key_display_value(env_api_key)}...')
|
||||
|
||||
from praisonai import PraisonAI
|
||||
praisonai = PraisonAI()
|
||||
|
||||
print(f'PraisonAI config_list: {praisonai.config_list}')
|
||||
api_key_from_config = praisonai.config_list[0].get('api_key', 'NOT_SET')
|
||||
print(f'API key from PraisonAI config: {get_key_display_value(api_key_from_config)}...')
|
||||
|
||||
from praisonai.inc.models import PraisonAIModel
|
||||
|
||||
print('\\\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
|
||||
model_with_explicit_key = PraisonAIModel(
|
||||
model='openai/gpt-4o-mini',
|
||||
base_url=praisonai.config_list[0].get('base_url'),
|
||||
api_key=api_key_from_config # This will be a string from praisonai.config_list
|
||||
)
|
||||
print(f' Model: {model_with_explicit_key.model}')
|
||||
print(f' Model name: {model_with_explicit_key.model_name}')
|
||||
print(f' API key var: {model_with_explicit_key.api_key_var}')
|
||||
# model_with_explicit_key.api_key is now a string, or 'nokey'
|
||||
print(f' API key (explicitly passed to PraisonAIModel): {get_key_display_value(model_with_explicit_key.api_key)}...')
|
||||
print(f' Base URL: {model_with_explicit_key.base_url}')
|
||||
|
||||
try:
|
||||
llm_instance = model_with_explicit_key.get_model()
|
||||
print(f' ✅ LLM instance created successfully: {type(llm_instance).__name__}')
|
||||
|
||||
# langchain_openai.ChatOpenAI stores the key in openai_api_key as SecretStr
|
||||
llm_api_key_attr = getattr(llm_instance, 'openai_api_key', 'NOT_FOUND')
|
||||
if llm_api_key_attr != 'NOT_FOUND':
|
||||
print(f' LLM instance API key: {get_key_display_value(llm_api_key_attr)}...')
|
||||
else:
|
||||
print(f' LLM instance API key attribute not found.')
|
||||
except Exception as e:
|
||||
print(f' ❌ Failed to create LLM instance: {e}')
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Run Unit Tests
|
||||
run: |
|
||||
cd src/praisonai && python -m pytest tests/unit/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=term-missing
|
||||
|
||||
- name: Run Integration Tests
|
||||
run: |
|
||||
cd src/praisonai && python -m pytest tests/integration/ -v --tb=short --disable-warnings
|
||||
|
||||
- name: Debug Directory Structure
|
||||
run: |
|
||||
echo "🔍 Debugging directory structure for CrewAI tests..."
|
||||
cd src/praisonai
|
||||
echo "Current working directory: $(pwd)"
|
||||
echo "📁 Contents of current directory:"
|
||||
ls -la
|
||||
echo ""
|
||||
echo "📁 Contents of tests directory:"
|
||||
ls -la tests/ || echo "❌ tests/ directory not found"
|
||||
echo ""
|
||||
echo "📁 Contents of tests/integration:"
|
||||
ls -la tests/integration/ || echo "❌ tests/integration/ directory not found"
|
||||
echo ""
|
||||
echo "📁 Looking for crewai directory:"
|
||||
find . -name "crewai" -type d 2>/dev/null || echo "❌ No crewai directories found"
|
||||
echo ""
|
||||
echo "📁 Full directory tree of tests:"
|
||||
tree tests/ || find tests/ -type d 2>/dev/null || echo "❌ Cannot explore tests directory"
|
||||
|
||||
- name: Test AutoGen Framework
|
||||
run: |
|
||||
echo "🤖 Testing AutoGen Framework Integration..."
|
||||
cd src/praisonai && python tests/test_runner.py --pattern autogen --verbose
|
||||
|
||||
- name: Test CrewAI Framework
|
||||
run: |
|
||||
echo "⛵ Testing CrewAI Framework Integration..."
|
||||
cd src/praisonai
|
||||
echo "🔍 Trying test runner first..."
|
||||
python tests/test_runner.py --pattern crewai --verbose || {
|
||||
echo "❌ Test runner failed, trying direct pytest..."
|
||||
echo "📁 Current directory: $(pwd)"
|
||||
echo "📁 Looking for CrewAI tests..."
|
||||
find . -name "*crewai*" -type f 2>/dev/null
|
||||
echo "🧪 Trying direct pytest on integration/crewai..."
|
||||
python -m pytest tests/integration/crewai/ -v --tb=short --disable-warnings || {
|
||||
echo "❌ Direct path failed, trying relative path..."
|
||||
python -m pytest integration/crewai/ -v --tb=short --disable-warnings || {
|
||||
echo "❌ All CrewAI test attempts failed"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- name: Run Legacy Tests with API Key
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}
|
||||
OPENAI_API_BASE: ${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}
|
||||
OPENAI_MODEL_NAME: ${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}
|
||||
LOGLEVEL: DEBUG
|
||||
run: |
|
||||
echo "🧪 Running legacy tests with real API key..."
|
||||
echo "🔧 Final environment check before pytest:"
|
||||
echo " OPENAI_API_KEY set: $([ -n "$OPENAI_API_KEY" ] && echo 'YES' || echo 'NO')"
|
||||
echo " OPENAI_API_KEY length: ${#OPENAI_API_KEY}"
|
||||
echo " OPENAI_API_KEY starts with sk-: $(echo "$OPENAI_API_KEY" | grep -q '^sk-' && echo 'YES' || echo 'NO')"
|
||||
export OPENAI_API_KEY="$OPENAI_API_KEY"
|
||||
export OPENAI_API_BASE="$OPENAI_API_BASE"
|
||||
export OPENAI_MODEL_NAME="$OPENAI_MODEL_NAME"
|
||||
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings
|
||||
|
||||
- name: Upload Coverage Reports
|
||||
if: matrix.python-version == '3.11'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage-reports
|
||||
path: |
|
||||
.coverage
|
||||
htmlcov/
|
||||
retention-days: 7
|
||||
@@ -0,0 +1,160 @@
|
||||
name: Extended Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
schedule:
|
||||
# Run nightly at 2 AM UTC
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch: # Allow manual triggering
|
||||
|
||||
jobs:
|
||||
test-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.11
|
||||
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system duckduckgo_search
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
|
||||
|
||||
- name: Test Key Example Scripts
|
||||
run: |
|
||||
echo "🧪 Testing key example scripts from praisonai-agents..."
|
||||
|
||||
# Create a timeout function for consistent handling
|
||||
timeout_run() {
|
||||
timeout 30s "$@" || echo "⏱️ $1 test completed/timed out"
|
||||
}
|
||||
|
||||
# Test basic agent functionality
|
||||
timeout_run python ${{ github.workspace }}/src/praisonai-agents/basic-agents.py
|
||||
|
||||
# Test async functionality
|
||||
timeout_run python ${{ github.workspace }}/src/praisonai-agents/async_example.py
|
||||
|
||||
# Test knowledge/RAG functionality
|
||||
timeout_run python ${{ github.workspace }}/src/praisonai-agents/knowledge-agents.py
|
||||
|
||||
# Test MCP functionality
|
||||
timeout_run python ${{ github.workspace }}/src/praisonai-agents/mcp-basic.py
|
||||
|
||||
# Test UI functionality
|
||||
timeout_run python ${{ github.workspace }}/src/praisonai-agents/ui.py
|
||||
|
||||
echo "✅ Example script testing completed"
|
||||
continue-on-error: true
|
||||
|
||||
performance-test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.11
|
||||
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system pytest pytest-benchmark
|
||||
|
||||
- name: Run Performance Benchmarks
|
||||
run: |
|
||||
echo "🏃 Running performance benchmarks..."
|
||||
python -c "
|
||||
import time
|
||||
import sys
|
||||
import statistics
|
||||
sys.path.insert(0, 'src/praisonai')
|
||||
|
||||
print('🏃 Testing agent creation performance...')
|
||||
times = []
|
||||
try:
|
||||
from praisonaiagents import Agent
|
||||
for i in range(5):
|
||||
start_time = time.time()
|
||||
agent = Agent(name=f'PerfAgent{i}')
|
||||
times.append(time.time() - start_time)
|
||||
|
||||
avg_time = statistics.mean(times)
|
||||
print(f'✅ Average agent creation time: {avg_time:.3f}s')
|
||||
print(f'📊 Min: {min(times):.3f}s, Max: {max(times):.3f}s')
|
||||
except Exception as e:
|
||||
print(f'❌ Agent creation benchmark failed: {e}')
|
||||
|
||||
print('🏃 Testing import performance...')
|
||||
start_time = time.time()
|
||||
try:
|
||||
import praisonaiagents
|
||||
import_time = time.time() - start_time
|
||||
print(f'✅ Import completed in {import_time:.3f}s')
|
||||
except Exception as e:
|
||||
print(f'❌ Import benchmark failed: {e}')
|
||||
|
||||
print('🏃 Testing memory usage...')
|
||||
try:
|
||||
import psutil
|
||||
import os
|
||||
process = psutil.Process(os.getpid())
|
||||
memory_mb = process.memory_info().rss / 1024 / 1024
|
||||
print(f'📊 Memory usage: {memory_mb:.1f} MB')
|
||||
except ImportError:
|
||||
print('⚠️ psutil not available for memory testing')
|
||||
except Exception as e:
|
||||
print(f'❌ Memory benchmark failed: {e}')
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Generate Performance Report
|
||||
run: |
|
||||
echo "## 📊 Performance Test Results" > performance_report.md
|
||||
echo "" >> performance_report.md
|
||||
echo "### Benchmarks Run:" >> performance_report.md
|
||||
echo "- ⚡ Agent creation speed" >> performance_report.md
|
||||
echo "- 📦 Import performance" >> performance_report.md
|
||||
echo "- 💾 Memory usage" >> performance_report.md
|
||||
echo "- 🧪 Example script execution" >> performance_report.md
|
||||
echo "" >> performance_report.md
|
||||
echo "_Performance results are logged in the CI output above._" >> performance_report.md
|
||||
|
||||
- name: Upload Performance Report
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: performance-report
|
||||
path: performance_report.md
|
||||
retention-days: 30
|
||||
@@ -0,0 +1,153 @@
|
||||
name: Framework Integration Tests
|
||||
|
||||
on:
|
||||
workflow_dispatch: # Allow manual triggering
|
||||
inputs:
|
||||
framework:
|
||||
description: 'Framework to test'
|
||||
required: true
|
||||
default: 'all'
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- autogen
|
||||
- crewai
|
||||
schedule:
|
||||
# Run framework tests daily at 6 AM UTC
|
||||
- cron: '0 6 * * *'
|
||||
push:
|
||||
paths:
|
||||
- 'tests/integration/autogen/**'
|
||||
- 'tests/integration/crewai/**'
|
||||
- '.github/workflows/test-frameworks.yml'
|
||||
|
||||
jobs:
|
||||
framework-tests:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [3.11]
|
||||
framework: [autogen, crewai]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system duckduckgo_search
|
||||
uv pip install --system pytest pytest-asyncio pytest-cov
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Test ${{ matrix.framework }} Framework
|
||||
run: |
|
||||
echo "🧪 Testing ${{ matrix.framework }} framework integration with Python ${{ matrix.python-version }}"
|
||||
cd src/praisonai && python tests/test_runner.py --pattern ${{ matrix.framework }} --verbose --coverage
|
||||
continue-on-error: false
|
||||
|
||||
- name: Generate Framework Test Report
|
||||
if: always()
|
||||
run: |
|
||||
echo "# 🤖 ${{ matrix.framework }} Framework Test Report" > ${{ matrix.framework }}_report.md
|
||||
echo "" >> ${{ matrix.framework }}_report.md
|
||||
echo "**Framework:** ${{ matrix.framework }}" >> ${{ matrix.framework }}_report.md
|
||||
echo "**Python Version:** ${{ matrix.python-version }}" >> ${{ matrix.framework }}_report.md
|
||||
echo "**Date:** $(date -u)" >> ${{ matrix.framework }}_report.md
|
||||
echo "**Trigger:** ${{ github.event_name }}" >> ${{ matrix.framework }}_report.md
|
||||
echo "" >> ${{ matrix.framework }}_report.md
|
||||
|
||||
if [ "${{ matrix.framework }}" == "autogen" ]; then
|
||||
echo "## AutoGen Integration Tests" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ AutoGen import verification" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Basic agent creation through PraisonAI" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Conversation flow testing" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Configuration validation" >> ${{ matrix.framework }}_report.md
|
||||
elif [ "${{ matrix.framework }}" == "crewai" ]; then
|
||||
echo "## CrewAI Integration Tests" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ CrewAI import verification" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Basic crew creation through PraisonAI" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Multi-agent workflow testing" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Agent collaboration verification" >> ${{ matrix.framework }}_report.md
|
||||
echo "- ✅ Configuration validation" >> ${{ matrix.framework }}_report.md
|
||||
fi
|
||||
|
||||
echo "" >> ${{ matrix.framework }}_report.md
|
||||
echo "## Test Commands" >> ${{ matrix.framework }}_report.md
|
||||
echo '```bash' >> ${{ matrix.framework }}_report.md
|
||||
echo "# Run ${{ matrix.framework }} tests locally:" >> ${{ matrix.framework }}_report.md
|
||||
echo "python tests/test_runner.py --pattern ${{ matrix.framework }} --verbose" >> ${{ matrix.framework }}_report.md
|
||||
echo '```' >> ${{ matrix.framework }}_report.md
|
||||
|
||||
- name: Upload Framework Test Results
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: ${{ matrix.framework }}-test-results-python-${{ matrix.python-version }}
|
||||
path: |
|
||||
${{ matrix.framework }}_report.md
|
||||
htmlcov/
|
||||
coverage.xml
|
||||
.coverage
|
||||
retention-days: 14
|
||||
|
||||
framework-summary:
|
||||
runs-on: ubuntu-latest
|
||||
needs: framework-tests
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
- name: Generate Framework Summary
|
||||
run: |
|
||||
echo "# 🚀 Framework Integration Test Summary" > framework_summary.md
|
||||
echo "" >> framework_summary.md
|
||||
echo "## Test Results by Framework and Python Version:" >> framework_summary.md
|
||||
echo "" >> framework_summary.md
|
||||
echo "### AutoGen Framework:" >> framework_summary.md
|
||||
echo "- Python 3.11: ${{ needs.framework-tests.result }}" >> framework_summary.md
|
||||
echo "" >> framework_summary.md
|
||||
echo "### CrewAI Framework:" >> framework_summary.md
|
||||
echo "- Python 3.11: ${{ needs.framework-tests.result }}" >> framework_summary.md
|
||||
echo "" >> framework_summary.md
|
||||
echo "## Overall Status:" >> framework_summary.md
|
||||
if [ "${{ needs.framework-tests.result }}" == "success" ]; then
|
||||
echo "✅ **All framework integration tests passed!**" >> framework_summary.md
|
||||
else
|
||||
echo "❌ **Some framework tests failed. Check individual job logs for details.**" >> framework_summary.md
|
||||
fi
|
||||
|
||||
echo "" >> framework_summary.md
|
||||
echo "## Frameworks Tested:" >> framework_summary.md
|
||||
echo "- **AutoGen**: Microsoft's conversational AI framework" >> framework_summary.md
|
||||
echo "- **CrewAI**: Multi-agent collaboration framework" >> framework_summary.md
|
||||
echo "" >> framework_summary.md
|
||||
echo "## Test Coverage:" >> framework_summary.md
|
||||
echo "- Import verification" >> framework_summary.md
|
||||
echo "- Agent/crew creation" >> framework_summary.md
|
||||
echo "- Workflow execution" >> framework_summary.md
|
||||
echo "- Configuration validation" >> framework_summary.md
|
||||
echo "- Integration with PraisonAI" >> framework_summary.md
|
||||
|
||||
- name: Upload Framework Summary
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: framework-test-summary
|
||||
path: framework_summary.md
|
||||
retention-days: 30
|
||||
@@ -0,0 +1,165 @@
|
||||
name: Real End-to-End Tests
|
||||
|
||||
# ⚠️ WARNING: This workflow makes real API calls and incurs costs!
|
||||
# Only runs when manually triggered to prevent accidental charges
|
||||
|
||||
on:
|
||||
workflow_dispatch: # Manual trigger only
|
||||
inputs:
|
||||
framework:
|
||||
description: 'Framework to test (⚠️ Will incur API costs!)'
|
||||
required: true
|
||||
default: 'none'
|
||||
type: choice
|
||||
options:
|
||||
- none
|
||||
- autogen
|
||||
- crewai
|
||||
- all
|
||||
confirm_costs:
|
||||
description: 'I understand this will make real API calls and may incur costs'
|
||||
required: true
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
real-tests:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.inputs.confirm_costs == 'true' && github.event.inputs.framework != 'none' }}
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [3.11] # Single version to minimize costs
|
||||
|
||||
steps:
|
||||
- name: 🚨 Cost Warning
|
||||
run: |
|
||||
echo "⚠️ WARNING: This workflow will make real API calls!"
|
||||
echo "💰 This may incur charges on your API accounts"
|
||||
echo "🎯 Framework: ${{ github.event.inputs.framework }}"
|
||||
echo "✅ Cost confirmation: ${{ github.event.inputs.confirm_costs }}"
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system pytest pytest-asyncio pytest-cov
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }}" >> $GITHUB_ENV
|
||||
echo "ANTHROPIC_API_KEY=${{ secrets.ANTHROPIC_API_KEY }}" >> $GITHUB_ENV
|
||||
echo "GOOGLE_API_KEY=${{ secrets.GOOGLE_API_KEY }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Verify API Keys
|
||||
run: |
|
||||
if [ -z "${{ secrets.OPENAI_API_KEY }}" ]; then
|
||||
echo "❌ OPENAI_API_KEY not set in secrets"
|
||||
echo "🔧 Add your API key to repository secrets"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ API keys configured"
|
||||
|
||||
- name: Run Real AutoGen Tests
|
||||
if: ${{ github.event.inputs.framework == 'autogen' || github.event.inputs.framework == 'all' }}
|
||||
run: |
|
||||
echo "🤖 Running REAL AutoGen tests (⚠️ API costs may apply)"
|
||||
cd src/praisonai && python -m pytest tests/e2e/autogen/ -v -m real --tb=short
|
||||
continue-on-error: false
|
||||
|
||||
- name: Run Real CrewAI Tests
|
||||
if: ${{ github.event.inputs.framework == 'crewai' || github.event.inputs.framework == 'all' }}
|
||||
run: |
|
||||
echo "⛵ Running REAL CrewAI tests (⚠️ API costs may apply)"
|
||||
cd src/praisonai && python -m pytest tests/e2e/crewai/ -v -m real --tb=short
|
||||
continue-on-error: false
|
||||
|
||||
- name: Generate Real Test Report
|
||||
if: always()
|
||||
run: |
|
||||
echo "# 🔥 Real End-to-End Test Report" > real_test_report.md
|
||||
echo "" >> real_test_report.md
|
||||
echo "⚠️ **WARNING: This report represents tests that made real API calls**" >> real_test_report.md
|
||||
echo "" >> real_test_report.md
|
||||
echo "**Framework Tested:** ${{ github.event.inputs.framework }}" >> real_test_report.md
|
||||
echo "**Python Version:** ${{ matrix.python-version }}" >> real_test_report.md
|
||||
echo "**Date:** $(date -u)" >> real_test_report.md
|
||||
echo "**Triggered by:** ${{ github.actor }}" >> real_test_report.md
|
||||
echo "" >> real_test_report.md
|
||||
|
||||
echo "## 🧪 Test Results" >> real_test_report.md
|
||||
echo "" >> real_test_report.md
|
||||
|
||||
if [ "${{ github.event.inputs.framework }}" == "autogen" ] || [ "${{ github.event.inputs.framework }}" == "all" ]; then
|
||||
echo "### AutoGen Real Tests:" >> real_test_report.md
|
||||
echo "- Environment verification" >> real_test_report.md
|
||||
echo "- Agent creation with real API calls" >> real_test_report.md
|
||||
echo "- Configuration validation" >> real_test_report.md
|
||||
echo "" >> real_test_report.md
|
||||
fi
|
||||
|
||||
if [ "${{ github.event.inputs.framework }}" == "crewai" ] || [ "${{ github.event.inputs.framework }}" == "all" ]; then
|
||||
echo "### CrewAI Real Tests:" >> real_test_report.md
|
||||
echo "- Environment verification" >> real_test_report.md
|
||||
echo "- Crew creation with real API calls" >> real_test_report.md
|
||||
echo "- Multi-agent setup validation" >> real_test_report.md
|
||||
echo "" >> real_test_report.md
|
||||
fi
|
||||
|
||||
echo "## 💰 Cost Considerations" >> real_test_report.md
|
||||
echo "- These tests made actual API calls to LLM providers" >> real_test_report.md
|
||||
echo "- Costs depend on your API pricing tier" >> real_test_report.md
|
||||
echo "- Tests are designed to be minimal to reduce costs" >> real_test_report.md
|
||||
echo "- Check your API provider dashboard for actual usage" >> real_test_report.md
|
||||
|
||||
echo "## 📋 Next Steps" >> real_test_report.md
|
||||
echo "- Review test results for any failures" >> real_test_report.md
|
||||
echo "- Check API usage in your provider dashboard" >> real_test_report.md
|
||||
echo "- Use mock tests (tests/integration/) for routine testing" >> real_test_report.md
|
||||
|
||||
- name: Upload Real Test Results
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: real-test-results-${{ github.event.inputs.framework }}-python-${{ matrix.python-version }}
|
||||
path: |
|
||||
real_test_report.md
|
||||
retention-days: 30
|
||||
|
||||
# Safety job that runs when costs not confirmed
|
||||
safety-check:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.inputs.confirm_costs != 'true' || github.event.inputs.framework == 'none' }}
|
||||
|
||||
steps:
|
||||
- name: 🛡️ Safety Check Failed
|
||||
run: |
|
||||
echo "🚨 Real tests not executed due to safety checks:"
|
||||
echo ""
|
||||
echo "✅ Costs confirmed: ${{ github.event.inputs.confirm_costs }}"
|
||||
echo "✅ Framework selected: ${{ github.event.inputs.framework }}"
|
||||
echo ""
|
||||
echo "To run real tests:"
|
||||
echo "1. Select a framework (autogen, crewai, or all)"
|
||||
echo "2. Check 'I understand this will make real API calls and may incur costs'"
|
||||
echo "3. Ensure API keys are set in repository secrets"
|
||||
echo ""
|
||||
echo "💡 For cost-free testing, use mock tests instead:"
|
||||
echo " - Run 'python -m pytest tests/integration/' locally"
|
||||
echo " - Or trigger other workflows that use mock tests"
|
||||
|
||||
exit 1
|
||||
+481
-14
@@ -1,36 +1,503 @@
|
||||
name: Run specific unittest
|
||||
name: Quick Validation Tests
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
quick-test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.11
|
||||
|
||||
- name: Install Poetry
|
||||
- name: Install UV
|
||||
run: |
|
||||
curl -sSL https://install.python-poetry.org | python3 -
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
poetry install
|
||||
poetry run python -m pip install duckduckgo_search
|
||||
cd src/praisonai
|
||||
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
|
||||
uv pip install --system duckduckgo_search
|
||||
uv pip install --system pytest pytest-asyncio pytest-cov
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
|
||||
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
|
||||
|
||||
- name: Run specific unittest
|
||||
- name: Backup Root Config Files
|
||||
run: |
|
||||
poetry run python -m unittest tests.test.TestExamples
|
||||
echo "🔄 Backing up root configuration files to prevent default file resolution interference..."
|
||||
echo "ℹ️ PraisonAI automatically uses 'agents.yaml' in working directory when no file specified"
|
||||
echo "ℹ️ This can interfere with test files that specify their own YAML files"
|
||||
if [ -f "agents.yaml" ]; then
|
||||
mv agents.yaml agents.yaml.backup
|
||||
echo "✅ Moved root agents.yaml to agents.yaml.backup"
|
||||
echo " - This prevents default file fallback during tests"
|
||||
fi
|
||||
if [ -f "tools.py" ]; then
|
||||
mv tools.py tools.py.backup
|
||||
echo "✅ Moved tools.py to tools.py.backup"
|
||||
fi
|
||||
|
||||
- name: Debug API Key Status
|
||||
run: |
|
||||
echo "🔍 Checking API key availability..."
|
||||
if [ -n "${{ secrets.OPENAI_API_KEY }}" ]; then
|
||||
echo "✅ GitHub secret OPENAI_API_KEY is available"
|
||||
echo "🔑 API key starts with: $(echo "$OPENAI_API_KEY" | cut -c1-7)..."
|
||||
else
|
||||
echo "⚠️ GitHub secret OPENAI_API_KEY is NOT set - using fallback"
|
||||
echo "🔑 Using fallback key: sk-test-key..."
|
||||
fi
|
||||
echo "🌐 API Base: $OPENAI_API_BASE"
|
||||
echo "🤖 Model: $OPENAI_MODEL_NAME"
|
||||
echo "🐛 Log Level: $LOGLEVEL"
|
||||
echo "📊 Environment Check:"
|
||||
echo " - OPENAI_API_KEY length: ${#OPENAI_API_KEY}"
|
||||
echo " - OPENAI_API_BASE: $OPENAI_API_BASE"
|
||||
echo " - OPENAI_MODEL_NAME: $OPENAI_MODEL_NAME"
|
||||
echo " - LOGLEVEL: $LOGLEVEL"
|
||||
|
||||
- name: Debug Python Environment Variables
|
||||
run: |
|
||||
python -c "
|
||||
import os
|
||||
print('🐍 Python Environment Variable Check:')
|
||||
api_key = os.environ.get('OPENAI_API_KEY', 'NOT_SET')
|
||||
if api_key != 'NOT_SET':
|
||||
print(f' ✅ OPENAI_API_KEY: {api_key[:7]}... (length: {len(api_key)})')
|
||||
else:
|
||||
print(' ❌ OPENAI_API_KEY: NOT_SET')
|
||||
print(f' 🌐 OPENAI_API_BASE: {os.environ.get(\"OPENAI_API_BASE\", \"NOT_SET\")}')
|
||||
print(f' 🤖 OPENAI_MODEL_NAME: {os.environ.get(\"OPENAI_MODEL_NAME\", \"NOT_SET\")}')
|
||||
print(f' 📋 All OPENAI env vars:')
|
||||
for key, value in os.environ.items():
|
||||
if key.startswith('OPENAI'):
|
||||
print(f' {key}: {value[:10] if len(value) > 10 else value}...')
|
||||
"
|
||||
|
||||
- name: Find Researcher Role Source
|
||||
run: |
|
||||
echo "🔍 Hunting for the mysterious 'Researcher' role..."
|
||||
cd src/praisonai
|
||||
python -c "
|
||||
import os
|
||||
import yaml
|
||||
import glob
|
||||
|
||||
print('📋 Searching for Researcher role in all YAML files:')
|
||||
yaml_files = glob.glob('src/praisonai/tests/*.yaml')
|
||||
|
||||
for yaml_file in yaml_files:
|
||||
try:
|
||||
with open(yaml_file, 'r') as f:
|
||||
config = yaml.safe_load(f)
|
||||
|
||||
# Check if any role contains 'researcher'
|
||||
roles = config.get('roles', {})
|
||||
for role_key, role_data in roles.items():
|
||||
role_name = role_data.get('role', '')
|
||||
if 'researcher' in role_key.lower() or 'researcher' in role_name.lower():
|
||||
print(f' 🎯 FOUND in {yaml_file}:')
|
||||
print(f' Framework: {config.get(\"framework\", \"NOT_SET\")}')
|
||||
print(f' Role key: {role_key}')
|
||||
print(f' Role name: {role_name}')
|
||||
print(f' All roles: {list(roles.keys())}')
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f' ❌ Error reading {yaml_file}: {e}')
|
||||
|
||||
print('🔍 Checking for default configurations...')
|
||||
# Check if there are any default configs or hardcoded roles
|
||||
try:
|
||||
import praisonai
|
||||
print(f' PraisonAI package location: {praisonai.__file__}')
|
||||
|
||||
# Check if there are any example YAML files in the package
|
||||
package_dir = os.path.dirname(praisonai.__file__)
|
||||
for root, dirs, files in os.walk(package_dir):
|
||||
for file in files:
|
||||
if file.endswith(('.yaml', '.yml')):
|
||||
file_path = os.path.join(root, file)
|
||||
print(f' 📁 Found YAML in package: {file_path}')
|
||||
except Exception as e:
|
||||
print(f' ❌ Error checking package: {e}')
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Trace AutoGen Execution Path
|
||||
run: |
|
||||
echo "🔍 Tracing AutoGen execution to find where it diverges..."
|
||||
cd src/praisonai
|
||||
python -c "
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
try:
|
||||
from praisonai import PraisonAI
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
|
||||
# Test the exact execution path
|
||||
print('🎯 Testing AutoGen execution path:')
|
||||
|
||||
praisonai = PraisonAI(agent_file='tests/autogen-agents.yaml')
|
||||
print(f' 1. PraisonAI framework: \"{praisonai.framework}\"')
|
||||
|
||||
agents_gen = AgentsGenerator(
|
||||
agent_file='tests/autogen-agents.yaml',
|
||||
framework=praisonai.framework,
|
||||
config_list=praisonai.config_list
|
||||
)
|
||||
print(f' 2. AgentsGenerator framework: \"{agents_gen.framework}\"')
|
||||
|
||||
# Load the YAML to check what it contains
|
||||
import yaml
|
||||
with open('src/praisonai/tests/autogen-agents.yaml', 'r') as f:
|
||||
config = yaml.safe_load(f)
|
||||
|
||||
framework = agents_gen.framework or config.get('framework')
|
||||
print(f' 3. Final framework decision: \"{framework}\"')
|
||||
print(f' 4. Available frameworks:')
|
||||
|
||||
# Check framework availability
|
||||
try:
|
||||
import autogen
|
||||
print(f' ✅ AutoGen available')
|
||||
except ImportError:
|
||||
print(f' ❌ AutoGen NOT available')
|
||||
|
||||
try:
|
||||
from praisonaiagents import Agent
|
||||
print(f' ✅ PraisonAI agents available')
|
||||
except ImportError:
|
||||
print(f' ❌ PraisonAI agents NOT available')
|
||||
|
||||
try:
|
||||
from crewai import Agent
|
||||
print(f' ✅ CrewAI available')
|
||||
except ImportError:
|
||||
print(f' ❌ CrewAI NOT available')
|
||||
|
||||
print(f' 5. Roles in YAML: {list(config.get(\"roles\", {}).keys())}')
|
||||
|
||||
# Now test the actual framework execution
|
||||
if framework == 'autogen':
|
||||
print(f' 6. ✅ Should execute _run_autogen')
|
||||
elif framework == 'praisonai':
|
||||
print(f' 6. ❌ Would execute _run_praisonai (WRONG!)')
|
||||
else:
|
||||
print(f' 6. ❌ Would execute _run_crewai (DEFAULT FALLBACK)')
|
||||
|
||||
except Exception as e:
|
||||
print(f'❌ Error tracing execution: {e}')
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Debug YAML Loading and Roles
|
||||
run: |
|
||||
echo "🔍 Tracing YAML file loading and role creation..."
|
||||
cd src/praisonai
|
||||
python -c "
|
||||
import os
|
||||
import sys
|
||||
import yaml
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
print('📁 Available YAML files in src/praisonai/tests/:')
|
||||
import glob
|
||||
yaml_files = glob.glob('tests/*.yaml')
|
||||
for f in yaml_files:
|
||||
print(f' {f}')
|
||||
|
||||
print()
|
||||
print('📋 Content of autogen-agents.yaml:')
|
||||
with open('tests/autogen-agents.yaml', 'r') as f:
|
||||
config = yaml.safe_load(f)
|
||||
print(f' Framework: {config.get(\"framework\")}')
|
||||
print(f' Topic: {config.get(\"topic\")}')
|
||||
print(f' Roles: {list(config.get(\"roles\", {}).keys())}')
|
||||
for role_key, role_data in config.get('roles', {}).items():
|
||||
print(f' {role_key} -> {role_data.get(\"role\", \"NO_ROLE\")}')
|
||||
|
||||
print()
|
||||
print('🔍 Checking if execution uses a different YAML:')
|
||||
|
||||
# Check other YAML files for 'Researcher' role
|
||||
for yaml_file in yaml_files:
|
||||
try:
|
||||
with open(yaml_file, 'r') as f:
|
||||
test_config = yaml.safe_load(f)
|
||||
roles = test_config.get('roles', {})
|
||||
for role_key, role_data in roles.items():
|
||||
if 'researcher' in role_key.lower() or 'researcher' in role_data.get('role', '').lower():
|
||||
print(f' 🎯 FOUND Researcher in {yaml_file}!')
|
||||
print(f' Framework: {test_config.get(\"framework\")}')
|
||||
print(f' Role key: {role_key} -> {role_data.get(\"role\")}')
|
||||
except:
|
||||
pass
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Debug Framework Detection
|
||||
run: |
|
||||
echo "🔍 Testing framework detection and config flow..."
|
||||
python -c "
|
||||
import os
|
||||
import sys
|
||||
import yaml
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
print('🔧 Testing framework detection:')
|
||||
|
||||
# Load the YAML file
|
||||
with open('tests/autogen-agents.yaml', 'r') as f:
|
||||
config = yaml.safe_load(f)
|
||||
|
||||
print(f' 📋 YAML framework: {config.get(\"framework\", \"NOT_SET\")}')
|
||||
print(f' 📋 YAML topic: {config.get(\"topic\", \"NOT_SET\")}')
|
||||
|
||||
try:
|
||||
from praisonai import PraisonAI
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
|
||||
# Test PraisonAI initialization
|
||||
praisonai = PraisonAI(agent_file='tests/autogen-agents.yaml')
|
||||
print(f' 🎯 PraisonAI framework: {praisonai.framework}')
|
||||
|
||||
# Test AgentsGenerator initialization
|
||||
agents_gen = AgentsGenerator(
|
||||
agent_file='tests/autogen-agents.yaml',
|
||||
framework=praisonai.framework,
|
||||
config_list=praisonai.config_list
|
||||
)
|
||||
print(f' ⚙️ AgentsGenerator framework: {agents_gen.framework}')
|
||||
print(f' ⚙️ Final framework decision: {agents_gen.framework or config.get(\"framework\")}')
|
||||
|
||||
# Check config_list
|
||||
print(f' 🔑 Config list model: {praisonai.config_list[0].get(\"model\")}')
|
||||
print(f' 🔑 Config list API key: {praisonai.config_list[0].get(\"api_key\", \"NOT_SET\")[:10]}...')
|
||||
|
||||
except Exception as e:
|
||||
print(f'❌ Error in framework detection: {e}')
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Debug PraisonAIModel API Key Flow
|
||||
run: |
|
||||
echo "🔍 Testing PraisonAIModel API key handling..."
|
||||
cd src/praisonai
|
||||
python -c "
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
print('🔑 Environment API Key Check:')
|
||||
env_key = os.environ.get('OPENAI_API_KEY', 'NOT_FOUND')
|
||||
print(f' OPENAI_API_KEY: {env_key[:10] if env_key != \"NOT_FOUND\" else \"NOT_FOUND\"}...')
|
||||
|
||||
try:
|
||||
from praisonai.inc.models import PraisonAIModel
|
||||
|
||||
# Test PraisonAIModel with openai/gpt-4o-mini (from YAML)
|
||||
model = PraisonAIModel(model='openai/gpt-4o-mini')
|
||||
|
||||
print('🤖 PraisonAIModel Configuration:')
|
||||
print(f' model: {model.model}')
|
||||
print(f' model_name: {model.model_name}')
|
||||
print(f' api_key_var: {model.api_key_var}')
|
||||
print(f' api_key: {model.api_key[:10] if model.api_key != \"nokey\" else \"DEFAULT_NOKEY\"}...')
|
||||
print(f' base_url: {model.base_url}')
|
||||
|
||||
if model.api_key == 'nokey':
|
||||
print('❌ FOUND THE ISSUE: PraisonAIModel is using default \"nokey\" instead of environment variable!')
|
||||
else:
|
||||
print('✅ PraisonAIModel has valid API key from environment')
|
||||
|
||||
except Exception as e:
|
||||
print(f'❌ Error testing PraisonAIModel: {e}')
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Validate API Key
|
||||
run: |
|
||||
echo "🔑 Testing API key validity with minimal OpenAI call..."
|
||||
python -c "
|
||||
import os
|
||||
try:
|
||||
from openai import OpenAI
|
||||
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
|
||||
# Make a minimal API call to test key validity
|
||||
response = client.models.list()
|
||||
print('✅ API Key is VALID - OpenAI responded successfully')
|
||||
print(f'📊 Available models: {len(list(response.data))} models found')
|
||||
except Exception as e:
|
||||
print(f'❌ API Key is INVALID - Error: {e}')
|
||||
print('🔍 This explains why all API-dependent tests are failing')
|
||||
print('💡 The GitHub secret OPENAI_API_KEY needs to be updated with a valid key')
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Test Direct PraisonAI Execution
|
||||
run: |
|
||||
echo "🧪 Testing direct PraisonAI execution (what works locally)..."
|
||||
python -m praisonai src/praisonai/tests/autogen-agents.yaml
|
||||
continue-on-error: true
|
||||
|
||||
- name: Comprehensive Execution Debug
|
||||
run: |
|
||||
echo "🔍 Comprehensive debugging of PraisonAI execution path..."
|
||||
cd src/praisonai
|
||||
python -c "
|
||||
import os
|
||||
import sys
|
||||
import yaml
|
||||
sys.path.insert(0, '.')
|
||||
|
||||
print('=' * 60)
|
||||
print('🔍 COMPREHENSIVE EXECUTION DEBUG')
|
||||
print('=' * 60)
|
||||
|
||||
# Check current working directory
|
||||
print(f'📁 Current working directory: {os.getcwd()}')
|
||||
|
||||
# List files in current directory
|
||||
print('📋 Files in current directory:')
|
||||
for f in os.listdir('.'):
|
||||
print(f' {f}')
|
||||
|
||||
print()
|
||||
print('📋 Files in src/praisonai/tests/ directory:')
|
||||
for f in os.listdir('tests'):
|
||||
if f.endswith('.yaml'):
|
||||
print(f' src/praisonai/tests/{f}')
|
||||
|
||||
# Check if root agents.yaml exists
|
||||
print()
|
||||
if os.path.exists('agents.yaml'):
|
||||
print('❌ ROOT agents.yaml EXISTS (this is the problem!)')
|
||||
with open('agents.yaml', 'r') as f:
|
||||
root_config = yaml.safe_load(f)
|
||||
print(f' Root framework: {root_config.get(\"framework\")}')
|
||||
print(f' Root roles: {list(root_config.get(\"roles\", {}).keys())}')
|
||||
else:
|
||||
print('✅ ROOT agents.yaml does NOT exist (good!)')
|
||||
|
||||
# Test the actual execution path
|
||||
print()
|
||||
print('🎯 Testing EXACT execution path:')
|
||||
|
||||
try:
|
||||
from praisonai import PraisonAI
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
|
||||
# Test with full path
|
||||
test_file = 'src/praisonai/tests/autogen-agents.yaml'
|
||||
print(f' Using test file: {test_file}')
|
||||
print(f' File exists: {os.path.exists(test_file)}')
|
||||
|
||||
# Load the test file directly
|
||||
with open(test_file, 'r') as f:
|
||||
test_config = yaml.safe_load(f)
|
||||
print(f' Test file framework: {test_config.get(\"framework\")}')
|
||||
print(f' Test file roles: {list(test_config.get(\"roles\", {}).keys())}')
|
||||
|
||||
# Create PraisonAI instance
|
||||
praisonai = PraisonAI(agent_file=test_file)
|
||||
print(f' PraisonAI.agent_file: {praisonai.agent_file}')
|
||||
print(f' PraisonAI.framework: {praisonai.framework}')
|
||||
|
||||
# Create AgentsGenerator
|
||||
agents_gen = AgentsGenerator(
|
||||
agent_file=test_file,
|
||||
framework=praisonai.framework,
|
||||
config_list=praisonai.config_list
|
||||
)
|
||||
print(f' AgentsGenerator.agent_file: {agents_gen.agent_file}')
|
||||
print(f' AgentsGenerator.framework: {agents_gen.framework}')
|
||||
|
||||
# Test what would happen in generate_crew_and_kickoff
|
||||
print()
|
||||
print('🔧 Testing generate_crew_and_kickoff logic:')
|
||||
|
||||
# Simulate the loading logic
|
||||
if agents_gen.agent_yaml:
|
||||
loaded_config = yaml.safe_load(agents_gen.agent_yaml)
|
||||
print(' Would load from agent_yaml')
|
||||
else:
|
||||
if agents_gen.agent_file == '/app/api:app' or agents_gen.agent_file == 'api:app':
|
||||
agents_gen.agent_file = 'agents.yaml'
|
||||
print(f' Would change agent_file to: {agents_gen.agent_file}')
|
||||
try:
|
||||
with open(agents_gen.agent_file, 'r') as f:
|
||||
loaded_config = yaml.safe_load(f)
|
||||
print(f' Successfully loaded: {agents_gen.agent_file}')
|
||||
except FileNotFoundError:
|
||||
print(f' FileNotFoundError: {agents_gen.agent_file}')
|
||||
loaded_config = None
|
||||
|
||||
if loaded_config:
|
||||
final_framework = agents_gen.framework or loaded_config.get('framework')
|
||||
print(f' Final framework decision: {final_framework}')
|
||||
print(f' Loaded roles: {list(loaded_config.get(\"roles\", {}).keys())}')
|
||||
|
||||
if 'researcher' in loaded_config.get('roles', {}):
|
||||
print(' ❌ FOUND Researcher role in loaded config!')
|
||||
else:
|
||||
print(' ✅ No Researcher role in loaded config')
|
||||
|
||||
except Exception as e:
|
||||
print(f'❌ Error during execution debug: {e}')
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Run Fast Tests
|
||||
run: |
|
||||
# Run the fastest, most essential tests
|
||||
cd src/praisonai && python tests/test_runner.py --pattern fast
|
||||
|
||||
- name: Run Real API Tests
|
||||
run: |
|
||||
echo "🔑 Running real API tests with actual OpenAI API key..."
|
||||
cd src/praisonai && python -m pytest tests/test_agents_playbook.py -v --tb=short --disable-warnings -m real
|
||||
continue-on-error: true
|
||||
|
||||
- name: Run E2E Real Tests
|
||||
run: |
|
||||
echo "🧪 Running E2E real tests..."
|
||||
cd src/praisonai && python -m pytest tests/e2e/ -v --tb=short --disable-warnings -m real
|
||||
continue-on-error: true
|
||||
|
||||
- name: Run Legacy Example Tests
|
||||
run: |
|
||||
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings
|
||||
continue-on-error: true
|
||||
|
||||
- name: Restore Root Config Files
|
||||
run: |
|
||||
echo "🔄 Restoring root configuration files..."
|
||||
if [ -f "agents.yaml.backup" ]; then
|
||||
mv agents.yaml.backup agents.yaml
|
||||
echo "✅ Restored agents.yaml"
|
||||
fi
|
||||
if [ -f "tools.py.backup" ]; then
|
||||
mv tools.py.backup tools.py
|
||||
echo "✅ Restored tools.py"
|
||||
fi
|
||||
if: always() # Always run this step, even if previous steps failed
|
||||
+10
-1
@@ -1,3 +1,4 @@
|
||||
workspace.code-workspace
|
||||
.vscode
|
||||
crewai
|
||||
.cache
|
||||
@@ -51,6 +52,10 @@ agentops.log
|
||||
|
||||
# crewAI
|
||||
crewAI
|
||||
!tests/integration/crewai
|
||||
!tests/e2e/crewai
|
||||
!src/praisonai/tests/integration/crewai
|
||||
!src/praisonai/tests/e2e/crewai
|
||||
|
||||
# virtualenv
|
||||
.venv
|
||||
@@ -65,4 +70,8 @@ outputs
|
||||
agents/praisonaiagents/build
|
||||
agents/praisonaiagents/dist
|
||||
agents/praisonaiagents/praisonaiagents.egg-info
|
||||
.codegpt
|
||||
.codegpt
|
||||
.praison
|
||||
# Local Netlify folder
|
||||
.netlify
|
||||
.qodo
|
||||
@@ -1,6 +0,0 @@
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN pip install flask praisonai==2.0.34 gunicorn markdown
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
|
||||
@@ -1,28 +0,0 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
python3-dev \
|
||||
portaudio19-dev \
|
||||
python3-pyaudio \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python packages
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonaiagents>=0.0.4 \
|
||||
praisonai_tools \
|
||||
"praisonai==2.0.18" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[chat]" \
|
||||
"praisonai[realtime]" \
|
||||
"embedchain[github,youtube]"
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Default command (will be overridden by docker-compose)
|
||||
CMD ["praisonai", "ui"]
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
</div>
|
||||
|
||||
PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human–agent collaboration.
|
||||
PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AG2 (Formerly AutoGen), and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
|
||||
|
||||
<div align="center">
|
||||
<a href="https://docs.praison.ai">
|
||||
@@ -37,35 +37,24 @@ PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application
|
||||
- 🧠 Reasoning AI Agents
|
||||
- 👁️ Multi Modal AI Agents
|
||||
- 🤝 Multi Agent Collaboration
|
||||
- ⚡ AI Agent Workflow
|
||||
- 🔄 Use CrewAI or AutoGen Framework
|
||||
- 🎭 AI Agent Workflow
|
||||
- 📚 Add Custom Knowledge
|
||||
- 🧠 Agents with Short and Long Term Memory
|
||||
- 📄 Chat with PDF Agents
|
||||
- 💻 Code Interpreter Agents
|
||||
- 📚 RAG Agents
|
||||
- 🤔 Async & Parallel Processing
|
||||
- 🔄 Auto Agents
|
||||
- 🔢 Math Agents
|
||||
- 🎯 Structured Output Agents
|
||||
- 🔗 LangChain Integrated Agents
|
||||
- 📞 Callback Agents
|
||||
- 🤏 Mini AI Agents
|
||||
- 🛠️ 100+ Custom Tools
|
||||
- 📄 YAML Configuration
|
||||
- 💯 100+ LLM Support
|
||||
- 💻 Chat with ENTIRE Codebase
|
||||
- 🎨 Interactive UIs
|
||||
- 📄 YAML-based Configuration
|
||||
- 🛠️ Custom Tool Integration
|
||||
- 🔍 Internet Search Capability (using Crawl4AI and Tavily)
|
||||
- 🖼️ Vision Language Model (VLM) Support
|
||||
- 🎙️ Real-time Voice Interaction
|
||||
|
||||
## Using No Code
|
||||
|
||||
### Auto Mode:
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
praisonai --auto create a movie script about Robots in Mars
|
||||
```
|
||||
|
||||
### Initialise Mode:
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
praisonai --init create a movie script about Robots in Mars
|
||||
praisonai
|
||||
```
|
||||
|
||||
## Using Coding
|
||||
## Using Python Code
|
||||
|
||||
Light weight package dedicated for coding:
|
||||
```bash
|
||||
@@ -76,58 +65,13 @@ pip install praisonaiagents
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
### 1. Single Agent
|
||||
|
||||
Create app.py file and add the code below:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# 1. Create agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI and data science",
|
||||
backstory="""You are an expert at a technology research group,
|
||||
skilled in identifying trends and analyzing complex data.""",
|
||||
verbose=True,
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
writer = Agent(
|
||||
name="Writer",
|
||||
role="Tech Content Strategist",
|
||||
goal="Craft compelling content on tech advancements",
|
||||
backstory="""You are a content strategist known for
|
||||
making complex tech topics interesting and easy to understand.""",
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# 2. Define Tasks
|
||||
task1 = Task(
|
||||
name="research_task",
|
||||
description="""Analyze 2024's AI advancements.
|
||||
Find major trends, new technologies, and their effects.""",
|
||||
expected_output="""A detailed report on 2024 AI advancements""",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="writing_task",
|
||||
description="""Create a blog post about major AI advancements using the insights you have.
|
||||
Make it interesting, clear, and suited for tech enthusiasts.
|
||||
It should be at least 4 paragraphs long.""",
|
||||
expected_output="A blog post of at least 4 paragraphs",
|
||||
agent=writer,
|
||||
)
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=False,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
from praisonaiagents import Agent
|
||||
agent = Agent(instructions="Your are a helpful AI assistant")
|
||||
agent.start("Write a movie script about a robot in Mars")
|
||||
```
|
||||
|
||||
Run:
|
||||
@@ -135,6 +79,396 @@ Run:
|
||||
python app.py
|
||||
```
|
||||
|
||||
### 2. Multi Agents
|
||||
|
||||
Create app.py file and add the code below:
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
research_agent = Agent(instructions="Research about AI")
|
||||
summarise_agent = Agent(instructions="Summarise research agent's findings")
|
||||
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
|
||||
Run:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
## Using No Code
|
||||
|
||||
### Auto Mode:
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
praisonai --auto create a movie script about Robots in Mars
|
||||
```
|
||||
|
||||
## Using JavaScript Code
|
||||
|
||||
```bash
|
||||
npm install praisonai
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
```javascript
|
||||
const { Agent } = require('praisonai');
|
||||
const agent = new Agent({ instructions: 'You are a helpful AI assistant' });
|
||||
agent.start('Write a movie script about a robot in Mars');
|
||||
```
|
||||
|
||||

|
||||
|
||||
## AI Agents Flow
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Define the main flow
|
||||
Start([▶ Start]) --> Agent1
|
||||
Agent1 --> Process[⚙ Process]
|
||||
Process --> Agent2
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
end
|
||||
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
end
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Start,Output,Task1,Task2 input
|
||||
class Process,AgentIcon1,AgentIcon2 process
|
||||
class Tools1,Tools2 tools
|
||||
class Agent1,Agent2 transparent
|
||||
```
|
||||
|
||||
## AI Agents with Tools
|
||||
|
||||
Create AI agents that can use tools to interact with external systems and perform actions.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Tools
|
||||
direction TB
|
||||
T3[Internet Search]
|
||||
T1[Code Execution]
|
||||
T2[Formatting]
|
||||
end
|
||||
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
T3 --> A1
|
||||
T1 --> A2
|
||||
T2 --> A3
|
||||
|
||||
style Tools fill:#189AB4,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## AI Agents with Memory
|
||||
|
||||
Create AI agents with memory capabilities for maintaining context and information across tasks.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Memory
|
||||
direction TB
|
||||
STM[Short Term]
|
||||
LTM[Long Term]
|
||||
end
|
||||
|
||||
subgraph Store
|
||||
direction TB
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
Memory <--> Store
|
||||
Store <--> A1
|
||||
Store <--> A2
|
||||
Store <--> A3
|
||||
|
||||
style Memory fill:#189AB4,color:#fff
|
||||
style Store fill:#2E8B57,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## AI Agents with Different Processes
|
||||
|
||||
### Sequential Process
|
||||
|
||||
The simplest form of task execution where tasks are performed one after another.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] --> A1
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
|
||||
end
|
||||
A3 --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class A1,A2,A3 process
|
||||
class Agents transparent
|
||||
```
|
||||
|
||||
### Hierarchical Process
|
||||
|
||||
Uses a manager agent to coordinate task execution and agent assignments.
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
Input[Input] --> Manager
|
||||
|
||||
subgraph Agents
|
||||
Manager[Manager Agent]
|
||||
|
||||
subgraph Workers
|
||||
direction LR
|
||||
W1[Worker 1]
|
||||
W2[Worker 2]
|
||||
W3[Worker 3]
|
||||
end
|
||||
|
||||
Manager --> W1
|
||||
Manager --> W2
|
||||
Manager --> W3
|
||||
end
|
||||
|
||||
W1 --> Manager
|
||||
W2 --> Manager
|
||||
W3 --> Manager
|
||||
Manager --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Manager,W1,W2,W3 process
|
||||
class Agents,Workers transparent
|
||||
```
|
||||
|
||||
### Workflow Process
|
||||
|
||||
Advanced process type supporting complex task relationships and conditional execution.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] --> Start
|
||||
|
||||
subgraph Workflow
|
||||
direction LR
|
||||
Start[Start] --> C1{Condition}
|
||||
C1 --> |Yes| A1[Agent 1]
|
||||
C1 --> |No| A2[Agent 2]
|
||||
A1 --> Join
|
||||
A2 --> Join
|
||||
Join --> A3[Agent 3]
|
||||
end
|
||||
|
||||
A3 --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Start,A1,A2,A3,Join process
|
||||
class C1 decision
|
||||
class Workflow transparent
|
||||
```
|
||||
|
||||
#### Agentic Routing Workflow
|
||||
|
||||
Create AI agents that can dynamically route tasks to specialized LLM instances.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Router[LLM Call Router]
|
||||
Router --> LLM1[LLM Call 1]
|
||||
Router --> LLM2[LLM Call 2]
|
||||
Router --> LLM3[LLM Call 3]
|
||||
LLM1 --> Out[Out]
|
||||
LLM2 --> Out
|
||||
LLM3 --> Out
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Orchestrator Worker
|
||||
|
||||
Create AI agents that orchestrate and distribute tasks among specialized workers.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Router[LLM Call Router]
|
||||
Router --> LLM1[LLM Call 1]
|
||||
Router --> LLM2[LLM Call 2]
|
||||
Router --> LLM3[LLM Call 3]
|
||||
LLM1 --> Synthesizer[Synthesizer]
|
||||
LLM2 --> Synthesizer
|
||||
LLM3 --> Synthesizer
|
||||
Synthesizer --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Synthesizer fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Autonomous Workflow
|
||||
|
||||
Create AI agents that can autonomously monitor, act, and adapt based on environment feedback.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Human[Human] <--> LLM[LLM Call]
|
||||
LLM -->|ACTION| Environment[Environment]
|
||||
Environment -->|FEEDBACK| LLM
|
||||
LLM --> Stop[Stop]
|
||||
|
||||
style Human fill:#8B0000,color:#fff
|
||||
style LLM fill:#2E8B57,color:#fff
|
||||
style Environment fill:#8B0000,color:#fff
|
||||
style Stop fill:#333,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Parallelization
|
||||
|
||||
Create AI agents that can execute tasks in parallel for improved performance.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> LLM2[LLM Call 2]
|
||||
In --> LLM1[LLM Call 1]
|
||||
In --> LLM3[LLM Call 3]
|
||||
LLM1 --> Aggregator[Aggregator]
|
||||
LLM2 --> Aggregator
|
||||
LLM3 --> Aggregator
|
||||
Aggregator --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Aggregator fill:#fff,color:#000
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Prompt Chaining
|
||||
|
||||
Create AI agents with sequential prompt chaining for complex workflows.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> LLM1[LLM Call 1] --> Gate{Gate}
|
||||
Gate -->|Pass| LLM2[LLM Call 2] -->|Output 2| LLM3[LLM Call 3] --> Out[Out]
|
||||
Gate -->|Fail| Exit[Exit]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style LLM1 fill:#2E8B57,color:#fff
|
||||
style LLM2 fill:#2E8B57,color:#fff
|
||||
style LLM3 fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
style Exit fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Agentic Evaluator Optimizer
|
||||
|
||||
Create AI agents that can generate and optimize solutions through iterative feedback.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Generator[LLM Call Generator]
|
||||
Generator -->|SOLUTION| Evaluator[LLM Call Evaluator] -->|ACCEPTED| Out[Out]
|
||||
Evaluator -->|REJECTED + FEEDBACK| Generator
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
#### Repetitive Agents
|
||||
|
||||
Create AI agents that can efficiently handle repetitive tasks through automated loops.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Input] --> LoopAgent[("Looping Agent")]
|
||||
LoopAgent --> Task[Task]
|
||||
Task --> |Next iteration| LoopAgent
|
||||
Task --> |Done| Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style LoopAgent fill:#2E8B57,color:#fff,shape:circle
|
||||
style Task fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## Adding Models
|
||||
|
||||
<div align="center">
|
||||
<a href="https://docs.praison.ai/models">
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/%F0%9F%93%9A_Models-Visit_docs.praison.ai-blue?style=for-the-badge&logo=bookstack&logoColor=white" alt="Models" />
|
||||
</p>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Ollama Integration
|
||||
```bash
|
||||
export OPENAI_BASE_URL=http://localhost:11434/v1
|
||||
@@ -147,267 +481,16 @@ export OPENAI_API_KEY=xxxxxxxxxxx
|
||||
export OPENAI_BASE_URL=https://api.groq.com/openai/v1
|
||||
```
|
||||
|
||||
## Logging
|
||||
```bash
|
||||
export LOGLEVEL=info
|
||||
```
|
||||
|
||||
Advanced logging:
|
||||
```bash
|
||||
export LOGLEVEL=debug
|
||||
```
|
||||
|
||||
<div align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/images/architecture-dark.png" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="docs/images/architecture-light.png" />
|
||||
<img alt="PraisonAI Architecture" src="docs/images/architecture-light.png" />
|
||||
</picture>
|
||||
</div>
|
||||
|
||||
## Different User Interfaces:
|
||||
|
||||
| Interface | Description | URL |
|
||||
|---|---|---|
|
||||
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
|
||||
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praison.ai/ui/chat](https://docs.praison.ai/ui/chat) |
|
||||
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praison.ai/ui/code](https://docs.praison.ai/ui/code) |
|
||||
| **Realtime** | Real-time voice interaction with AI | [https://docs.praison.ai/ui/realtime](https://docs.praison.ai/ui/realtime) |
|
||||
|
||||
| Other Features | Description | Docs |
|
||||
|---|---|---|
|
||||
| **Train** | Fine-tune LLMs using your custom data | [https://docs.praison.ai/train](https://docs.praison.ai/train) |
|
||||
|
||||
|
||||
## Google Colab Multi Agents
|
||||
|
||||
| | Cookbook | Open in Colab |
|
||||
| ------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Basic | PraisonAI | <a target="_blank" href="https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/cookbooks/praisonai-googlecolab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" /></a> |
|
||||
| Include Tools | PraisonAI Tools | <a target="_blank" href="https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/cookbooks/praisonai-tools-googlecolab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" /></a> |
|
||||
|
||||
## Installation Options
|
||||
|
||||
### Using pip
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
|
||||
### Framework-specific Installation
|
||||
```bash
|
||||
# Install with CrewAI support
|
||||
pip install "praisonai[crewai]"
|
||||
|
||||
# Install with AutoGen support
|
||||
pip install "praisonai[autogen]"
|
||||
|
||||
# Install with both frameworks
|
||||
pip install "praisonai[crewai,autogen]"
|
||||
```
|
||||
|
||||
### UI and Additional Features
|
||||
```bash
|
||||
# Install UI support
|
||||
pip install "praisonai[ui]"
|
||||
|
||||
# Install Chat interface
|
||||
pip install "praisonai[chat]"
|
||||
|
||||
# Install Code interface
|
||||
pip install "praisonai[code]"
|
||||
|
||||
# Install Realtime voice interaction
|
||||
pip install "praisonai[realtime]"
|
||||
|
||||
# Install Call feature
|
||||
pip install "praisonai[call]"
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Set your OpenAI API key
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
|
||||
# Initialize with CrewAI (default)
|
||||
praisonai --init "create a movie script about dog in moon"
|
||||
|
||||
# Or initialize with AutoGen
|
||||
praisonai --framework autogen --init "create a movie script about dog in moon"
|
||||
|
||||
# Run the agents
|
||||
praisonai
|
||||
```
|
||||
|
||||
## Full Automatic Mode
|
||||
|
||||
```bash
|
||||
# With CrewAI (default)
|
||||
praisonai --auto "create a movie script about Dog in Moon"
|
||||
|
||||
# With AutoGen
|
||||
praisonai --framework autogen --auto "create a movie script about Dog in Moon"
|
||||
```
|
||||
|
||||
## Framework-specific Features
|
||||
|
||||
### CrewAI
|
||||
When installing with `pip install "praisonai[crewai]"`, you get:
|
||||
- CrewAI framework support
|
||||
- PraisonAI tools integration
|
||||
- Task delegation capabilities
|
||||
- Sequential and parallel task execution
|
||||
|
||||
### AutoGen
|
||||
When installing with `pip install "praisonai[autogen]"`, you get:
|
||||
- AutoGen framework support
|
||||
- PraisonAI tools integration
|
||||
- Multi-agent conversation capabilities
|
||||
- Code execution environment
|
||||
|
||||
|
||||
|
||||
## TL;DR Multi Agents
|
||||
|
||||
```bash
|
||||
pip install praisonai
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
praisonai --init create a movie script about dog in moon
|
||||
praisonai
|
||||
```
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Initialise](#initialise)
|
||||
- [Run](#run)
|
||||
- [Full Automatic Mode](#full-automatic-mode)
|
||||
- [User Interface](#user-interface)
|
||||
- [Praison AI Chat](#praison-ai-chat)
|
||||
- [Create Custom Tools](#create-custom-tools)
|
||||
- [Agents Playbook](#agents-playbook)
|
||||
- [Include praisonai package in your project](#include-praisonai-package-in-your-project)
|
||||
- [Commands to Install Dev Dependencies](#commands-to-install-dependencies)
|
||||
- [Other Models](#other-models)
|
||||
- [Contributing](#contributing)
|
||||
- [Star History](#star-history)
|
||||
|
||||
## Installation Multi Agents
|
||||
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
|
||||
## Initialise
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
```
|
||||
|
||||
Generate your OPENAI API KEY from here: https://platform.openai.com/api-keys
|
||||
|
||||
Note: You can use other providers such as Ollama, Mistral ... etc. Details are provided at the bottom.
|
||||
|
||||
```bash
|
||||
praisonai --init create a movie script about dog in moon
|
||||
```
|
||||
|
||||
This will automatically create agents.yaml file in the current directory.
|
||||
|
||||
### To initialise with a specific agent framework (Optional):
|
||||
|
||||
```bash
|
||||
praisonai --framework autogen --init create movie script about cat in mars
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
praisonai
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
python -m praisonai
|
||||
```
|
||||
|
||||
### Specify the agent framework (Optional):
|
||||
|
||||
```bash
|
||||
praisonai --framework autogen
|
||||
```
|
||||
|
||||
### Full Automatic Mode
|
||||
|
||||
```bash
|
||||
praisonai --auto create a movie script about Dog in Moon
|
||||
```
|
||||
|
||||
## User Interface
|
||||
|
||||
## PraisonAI User Interfaces:
|
||||
|
||||
| Interface | Description | URL |
|
||||
| --------- | ------------------------------------------ | --------------------------------------------------------------------- |
|
||||
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praisonai.com/ui/ui](https://docs.praison.ai/ui/ui) |
|
||||
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praisonai.com/ui/chat](https://docs.praison.ai/ui/chat) |
|
||||
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praisonai.com/ui/code](https://docs.praison.ai/ui/code) |
|
||||
|
||||
```bash
|
||||
pip install -U "praisonai[ui]"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
chainlit create-secret
|
||||
export CHAINLIT_AUTH_SECRET=xxxxxxxx
|
||||
praisonai ui
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
python -m praisonai ui
|
||||
```
|
||||
|
||||
## Praison AI Chat
|
||||
|
||||
- https://docs.praison.ai/chat/
|
||||
|
||||
```bash
|
||||
pip install "praisonai[chat]"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
praisonai chat
|
||||
```
|
||||
|
||||
### Internet Search
|
||||
|
||||
Praison AI Chat and Praison AI Code now includes internet search capabilities using Crawl4AI and Tavily, allowing you to retrieve up-to-date information during your conversations.
|
||||
|
||||
### Vision Language Model Support
|
||||
|
||||
You can now upload images and ask questions based on them using Vision Language Models. This feature enables visual understanding and analysis within your chat sessions.
|
||||
|
||||
## Praison AI Code
|
||||
|
||||
```bash
|
||||
pip install "praisonai[code]"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
praisonai code
|
||||
```
|
||||
|
||||
### Internet Search
|
||||
|
||||
Praison AI Code also includes internet search functionality, enabling you to find relevant code snippets and programming information online.
|
||||
|
||||
## Create Custom Tools
|
||||
|
||||
- https://docs.praison.ai/tools/custom/
|
||||
## No Code Options
|
||||
|
||||
## Agents Playbook
|
||||
|
||||
### Simple Playbook Example
|
||||
|
||||
Create `agents.yaml` file and add the code below:
|
||||
|
||||
```yaml
|
||||
framework: crewai
|
||||
framework: praisonai
|
||||
topic: Artificial Intelligence
|
||||
roles:
|
||||
screenwriter:
|
||||
@@ -420,62 +503,25 @@ roles:
|
||||
expected_output: "Complete script ready for production."
|
||||
```
|
||||
|
||||
*To run the playbook:*
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
|
||||
## Use 100+ Models
|
||||
|
||||
- https://docs.praison.ai/models/
|
||||
<div align="center">
|
||||
<a href="https://docs.praison.ai">
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/📚_Documentation-Visit_docs.praison.ai-blue?style=for-the-badge&logo=bookstack&logoColor=white" alt="Documentation" />
|
||||
</p>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Include praisonai package in your project
|
||||
## Development:
|
||||
|
||||
- https://docs.praison.ai/developers/wrapper
|
||||
- https://docs.praison.ai/developers/wrapper-tools/
|
||||
|
||||
## Option 1: Using RAW YAML
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
|
||||
# Example agent_yaml content
|
||||
agent_yaml = """
|
||||
framework: "crewai"
|
||||
topic: "Space Exploration"
|
||||
|
||||
roles:
|
||||
astronomer:
|
||||
role: "Space Researcher"
|
||||
goal: "Discover new insights about {topic}"
|
||||
backstory: "You are a curious and dedicated astronomer with a passion for unraveling the mysteries of the cosmos."
|
||||
tasks:
|
||||
investigate_exoplanets:
|
||||
description: "Research and compile information about exoplanets discovered in the last decade."
|
||||
expected_output: "A summarized report on exoplanet discoveries, including their size, potential habitability, and distance from Earth."
|
||||
"""
|
||||
|
||||
# Create a PraisonAI instance with the agent_yaml content
|
||||
praisonai = PraisonAI(agent_yaml=agent_yaml)
|
||||
|
||||
# Run PraisonAI
|
||||
result = praisonai.run()
|
||||
|
||||
# Print the result
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Option 2: Using separate agents.yaml file
|
||||
|
||||
Note: Please create agents.yaml file before hand.
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
|
||||
def basic(): # Basic Mode
|
||||
praisonai = PraisonAI(agent_file="agents.yaml")
|
||||
praisonai.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
basic()
|
||||
```
|
||||
|
||||
## Commands to Install Dependencies:
|
||||
Below is used for development only.
|
||||
|
||||
### Using uv
|
||||
```bash
|
||||
@@ -500,18 +546,34 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
|
||||
- Submit a pull request via GitHub's web interface.
|
||||
- Await feedback from project maintainers.
|
||||
|
||||
## Other Features
|
||||
|
||||
- 🔄 Use CrewAI or AG2 (Formerly AutoGen) Framework
|
||||
- 💻 Chat with ENTIRE Codebase
|
||||
- 🎨 Interactive UIs
|
||||
- 📄 YAML-based Configuration
|
||||
- 🛠️ Custom Tool Integration
|
||||
- 🔍 Internet Search Capability (using Crawl4AI and Tavily)
|
||||
- 🖼️ Vision Language Model (VLM) Support
|
||||
- 🎙️ Real-time Voice Interaction
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://docs.praison.ai)
|
||||
|
||||
## License
|
||||
|
||||
Praison AI is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
|
||||
|
||||
## Video Tutorials
|
||||
|
||||
| Topic | Video |
|
||||
|-------|--------|
|
||||
| AI Agents with Self Reflection | [](https://www.youtube.com/watch?v=vLXobEN2Vc8) |
|
||||
| Reasoning Data Generating Agent | [](https://www.youtube.com/watch?v=fUT332Y2zA8) |
|
||||
| AI Agents with Reasoning | [](https://www.youtube.com/watch?v=KNDVWGN3TpM) |
|
||||
| Multimodal AI Agents | [](https://www.youtube.com/watch?v=hjAWmUT1qqY) |
|
||||
| AI Agents Workflow | [](https://www.youtube.com/watch?v=yWTH44QPl2A) |
|
||||
| Async AI Agents | [](https://www.youtube.com/watch?v=VhVQfgo00LE) |
|
||||
| Mini AI Agents | [](https://www.youtube.com/watch?v=OkvYp5aAGSg) |
|
||||
| AI Agents with Memory | [](https://www.youtube.com/watch?v=1hVfVxvPnnQ) |
|
||||
| Repetitive Agents | [](https://www.youtube.com/watch?v=dAYGxsjDOPg) |
|
||||
| Introduction | [](https://www.youtube.com/watch?v=Fn1lQjC0GO0) |
|
||||
| Tools Overview | [](https://www.youtube.com/watch?v=XaQRgRpV7jo) |
|
||||
| Custom Tools | [](https://www.youtube.com/watch?v=JSU2Rndh06c) |
|
||||
@@ -524,59 +586,5 @@ Praison AI is an open-sourced software licensed under the **[MIT license](https:
|
||||
| Training | [](https://www.youtube.com/watch?v=aLawE8kwCrI) |
|
||||
| Realtime Voice Interface | [](https://www.youtube.com/watch?v=frRHfevTCSw) |
|
||||
| Call Interface | [](https://www.youtube.com/watch?v=m1cwrUG2iAk) |
|
||||
| Reasoning Extract Agents | [](https://www.youtube.com/watch?v=2PPamsADjJA) |
|
||||
|
||||
## License
|
||||
|
||||
Praison AI is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
|
||||
|
||||
## Local Docker Development with Live Reload
|
||||
|
||||
To facilitate local development with live reload, you can use Docker. Follow the steps below:
|
||||
|
||||
1. **Create a `Dockerfile.dev`**:
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN pip install flask praisonai==2.0.18 watchdog
|
||||
|
||||
EXPOSE 5555
|
||||
|
||||
ENV FLASK_ENV=development
|
||||
|
||||
CMD ["flask", "run", "--host=0.0.0.0"]
|
||||
```
|
||||
|
||||
2. **Create a `docker-compose.yml`**:
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.dev
|
||||
volumes:
|
||||
- .:/app
|
||||
ports:
|
||||
- "5555:5555"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
command: flask run --host=0.0.0.0
|
||||
|
||||
watch:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- .:/app
|
||||
command: sh -c "apk add --no-cache inotify-tools && while inotifywait -r -e modify,create,delete /app; do kill -HUP 1; done"
|
||||
```
|
||||
|
||||
3. **Run Docker Compose**:
|
||||
```bash
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
This setup will allow you to develop locally with live reload, making it easier to test and iterate on your code.
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Agent module for AI agents"""
|
||||
from .agent import Agent
|
||||
|
||||
__all__ = ['Agent']
|
||||
@@ -1,714 +0,0 @@
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import List, Optional, Any, Dict, Union, Literal, TYPE_CHECKING
|
||||
from rich.console import Console
|
||||
from rich.live import Live
|
||||
from openai import AsyncOpenAI
|
||||
from ..main import (
|
||||
display_error,
|
||||
display_tool_call,
|
||||
display_instruction,
|
||||
display_interaction,
|
||||
display_generating,
|
||||
display_self_reflection,
|
||||
ReflectionOutput,
|
||||
client,
|
||||
error_logs
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..task.task import Task
|
||||
|
||||
class Agent:
|
||||
def _generate_tool_definition(self, function_name):
|
||||
"""
|
||||
Generate a tool definition from a function name by inspecting the function.
|
||||
"""
|
||||
logging.debug(f"Attempting to generate tool definition for: {function_name}")
|
||||
|
||||
# First try to get the tool definition if it exists
|
||||
tool_def_name = f"{function_name}_definition"
|
||||
tool_def = globals().get(tool_def_name)
|
||||
logging.debug(f"Looking for {tool_def_name} in globals: {tool_def is not None}")
|
||||
|
||||
if not tool_def:
|
||||
import __main__
|
||||
tool_def = getattr(__main__, tool_def_name, None)
|
||||
logging.debug(f"Looking for {tool_def_name} in __main__: {tool_def is not None}")
|
||||
|
||||
if tool_def:
|
||||
logging.debug(f"Found tool definition: {tool_def}")
|
||||
return tool_def
|
||||
|
||||
# Try to find the function in the agent's tools list first
|
||||
func = None
|
||||
for tool in self.tools:
|
||||
if callable(tool) and getattr(tool, '__name__', '') == function_name:
|
||||
func = tool
|
||||
break
|
||||
|
||||
logging.debug(f"Looking for {function_name} in agent tools: {func is not None}")
|
||||
|
||||
# If not found in tools, try globals and main
|
||||
if not func:
|
||||
func = globals().get(function_name)
|
||||
logging.debug(f"Looking for {function_name} in globals: {func is not None}")
|
||||
|
||||
if not func:
|
||||
import __main__
|
||||
func = getattr(__main__, function_name, None)
|
||||
logging.debug(f"Looking for {function_name} in __main__: {func is not None}")
|
||||
|
||||
if not func or not callable(func):
|
||||
logging.debug(f"Function {function_name} not found or not callable")
|
||||
return None
|
||||
|
||||
import inspect
|
||||
sig = inspect.signature(func)
|
||||
logging.debug(f"Function signature: {sig}")
|
||||
|
||||
parameters = {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": []
|
||||
}
|
||||
|
||||
# Parse docstring for parameter descriptions
|
||||
docstring = inspect.getdoc(func)
|
||||
logging.debug(f"Function docstring: {docstring}")
|
||||
|
||||
param_descriptions = {}
|
||||
if docstring:
|
||||
import re
|
||||
param_section = re.split(r'\s*Args:\s*', docstring)
|
||||
logging.debug(f"Param section split: {param_section}")
|
||||
if len(param_section) > 1:
|
||||
param_lines = param_section[1].split('\n')
|
||||
for line in param_lines:
|
||||
line = line.strip()
|
||||
if line and ':' in line:
|
||||
param_name, param_desc = line.split(':', 1)
|
||||
param_descriptions[param_name.strip()] = param_desc.strip()
|
||||
|
||||
logging.debug(f"Parameter descriptions: {param_descriptions}")
|
||||
|
||||
for name, param in sig.parameters.items():
|
||||
param_type = "string" # Default type
|
||||
if param.annotation != inspect.Parameter.empty:
|
||||
if param.annotation == int:
|
||||
param_type = "integer"
|
||||
elif param.annotation == float:
|
||||
param_type = "number"
|
||||
elif param.annotation == bool:
|
||||
param_type = "boolean"
|
||||
elif param.annotation == list:
|
||||
param_type = "array"
|
||||
elif param.annotation == dict:
|
||||
param_type = "object"
|
||||
|
||||
param_info = {"type": param_type}
|
||||
if name in param_descriptions:
|
||||
param_info["description"] = param_descriptions[name]
|
||||
|
||||
parameters["properties"][name] = param_info
|
||||
if param.default == inspect.Parameter.empty:
|
||||
parameters["required"].append(name)
|
||||
|
||||
logging.debug(f"Generated parameters: {parameters}")
|
||||
|
||||
# Extract description from docstring
|
||||
description = docstring.split('\n')[0] if docstring else f"Function {function_name}"
|
||||
|
||||
tool_def = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": function_name,
|
||||
"description": description,
|
||||
"parameters": parameters
|
||||
}
|
||||
}
|
||||
logging.debug(f"Generated tool definition: {tool_def}")
|
||||
return tool_def
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
role: Optional[str] = None,
|
||||
goal: Optional[str] = None,
|
||||
backstory: Optional[str] = None,
|
||||
instructions: Optional[str] = None,
|
||||
llm: Optional[Union[str, Any]] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
function_calling_llm: Optional[Any] = None,
|
||||
max_iter: int = 20,
|
||||
max_rpm: Optional[int] = None,
|
||||
max_execution_time: Optional[int] = None,
|
||||
memory: bool = True,
|
||||
verbose: bool = True,
|
||||
allow_delegation: bool = False,
|
||||
step_callback: Optional[Any] = None,
|
||||
cache: bool = True,
|
||||
system_template: Optional[str] = None,
|
||||
prompt_template: Optional[str] = None,
|
||||
response_template: Optional[str] = None,
|
||||
allow_code_execution: Optional[bool] = False,
|
||||
max_retry_limit: int = 2,
|
||||
respect_context_window: bool = True,
|
||||
code_execution_mode: Literal["safe", "unsafe"] = "safe",
|
||||
embedder_config: Optional[Dict[str, Any]] = None,
|
||||
knowledge_sources: Optional[List[Any]] = None,
|
||||
use_system_prompt: Optional[bool] = True,
|
||||
markdown: bool = True,
|
||||
self_reflect: Optional[bool] = None,
|
||||
max_reflect: int = 3,
|
||||
min_reflect: int = 1,
|
||||
reflect_llm: Optional[str] = None
|
||||
):
|
||||
# Handle backward compatibility for required fields
|
||||
if all(x is None for x in [name, role, goal, backstory, instructions]):
|
||||
raise ValueError("At least one of name, role, goal, backstory, or instructions must be provided")
|
||||
|
||||
# If instructions are provided, use them to set role, goal, and backstory
|
||||
if instructions:
|
||||
self.name = name or "Agent"
|
||||
self.role = role or "Assistant"
|
||||
self.goal = goal or instructions
|
||||
self.backstory = backstory or instructions
|
||||
# Set self_reflect to False by default for instruction-based agents
|
||||
self.self_reflect = False if self_reflect is None else self_reflect
|
||||
else:
|
||||
# Use provided values or defaults
|
||||
self.name = name or "Agent"
|
||||
self.role = role or "Assistant"
|
||||
self.goal = goal or "Help the user with their tasks"
|
||||
self.backstory = backstory or "I am an AI assistant"
|
||||
# Default to True for traditional agents if not specified
|
||||
self.self_reflect = True if self_reflect is None else self_reflect
|
||||
|
||||
self.instructions = instructions
|
||||
# Check for model name in environment variable if not provided
|
||||
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.tools = tools if tools else [] # Store original tools
|
||||
self.function_calling_llm = function_calling_llm
|
||||
self.max_iter = max_iter
|
||||
self.max_rpm = max_rpm
|
||||
self.max_execution_time = max_execution_time
|
||||
self.memory = memory
|
||||
self.verbose = verbose
|
||||
self.allow_delegation = allow_delegation
|
||||
self.step_callback = step_callback
|
||||
self.cache = cache
|
||||
self.system_template = system_template
|
||||
self.prompt_template = prompt_template
|
||||
self.response_template = response_template
|
||||
self.allow_code_execution = allow_code_execution
|
||||
self.max_retry_limit = max_retry_limit
|
||||
self.respect_context_window = respect_context_window
|
||||
self.code_execution_mode = code_execution_mode
|
||||
self.embedder_config = embedder_config
|
||||
self.knowledge_sources = knowledge_sources
|
||||
self.use_system_prompt = use_system_prompt
|
||||
self.chat_history = []
|
||||
self.markdown = markdown
|
||||
self.max_reflect = max_reflect
|
||||
self.min_reflect = min_reflect
|
||||
# Use the same model selection logic for reflect_llm
|
||||
self.reflect_llm = reflect_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.console = Console() # Create a single console instance for the agent
|
||||
|
||||
# Initialize system prompt
|
||||
self.system_prompt = f"""{self.backstory}\n
|
||||
Your Role: {self.role}\n
|
||||
Your Goal: {self.goal}
|
||||
"""
|
||||
|
||||
def generate_task(self) -> 'Task':
|
||||
"""Generate a Task object from the agent's instructions"""
|
||||
from ..task.task import Task
|
||||
|
||||
description = self.instructions if self.instructions else f"Execute task as {self.role} with goal: {self.goal}"
|
||||
expected_output = "Complete the assigned task successfully"
|
||||
|
||||
return Task(
|
||||
name=self.name,
|
||||
description=description,
|
||||
expected_output=expected_output,
|
||||
agent=self,
|
||||
tools=self.tools
|
||||
)
|
||||
|
||||
def execute_tool(self, function_name, arguments):
|
||||
"""
|
||||
Execute a tool dynamically based on the function name and arguments.
|
||||
"""
|
||||
logging.debug(f"{self.name} executing tool {function_name} with arguments: {arguments}")
|
||||
|
||||
# Try to find the function in the agent's tools list first
|
||||
func = None
|
||||
for tool in self.tools:
|
||||
if callable(tool) and getattr(tool, '__name__', '') == function_name:
|
||||
func = tool
|
||||
break
|
||||
|
||||
logging.debug(f"Looking for {function_name} in agent tools: {func is not None}")
|
||||
|
||||
# If not found in tools, try globals and main
|
||||
if not func:
|
||||
func = globals().get(function_name)
|
||||
logging.debug(f"Looking for {function_name} in globals: {func is not None}")
|
||||
|
||||
if not func:
|
||||
import __main__
|
||||
func = getattr(__main__, function_name, None)
|
||||
logging.debug(f"Looking for {function_name} in __main__: {func is not None}")
|
||||
|
||||
if func and callable(func):
|
||||
try:
|
||||
return func(**arguments)
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
logging.error(f"Error executing tool {function_name}: {error_msg}")
|
||||
return {"error": error_msg}
|
||||
|
||||
error_msg = f"Tool '{function_name}' is not callable"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
def clear_history(self):
|
||||
self.chat_history = []
|
||||
|
||||
def __str__(self):
|
||||
return f"Agent(name='{self.name}', role='{self.role}', goal='{self.goal}')"
|
||||
|
||||
def _chat_completion(self, messages, temperature=0.2, tools=None, stream=True):
|
||||
start_time = time.time()
|
||||
logging.debug(f"{self.name} sending messages to LLM: {messages}")
|
||||
|
||||
formatted_tools = []
|
||||
if tools is None:
|
||||
tools = self.tools
|
||||
if tools:
|
||||
for tool in tools:
|
||||
if isinstance(tool, str):
|
||||
# Generate tool definition for string tool names
|
||||
tool_def = self._generate_tool_definition(tool)
|
||||
if tool_def:
|
||||
formatted_tools.append(tool_def)
|
||||
else:
|
||||
logging.warning(f"Could not generate definition for tool: {tool}")
|
||||
elif isinstance(tool, dict):
|
||||
formatted_tools.append(tool)
|
||||
elif hasattr(tool, "to_openai_tool"):
|
||||
formatted_tools.append(tool.to_openai_tool())
|
||||
elif callable(tool):
|
||||
formatted_tools.append(self._generate_tool_definition(tool.__name__))
|
||||
else:
|
||||
logging.warning(f"Tool {tool} not recognized")
|
||||
|
||||
try:
|
||||
initial_response = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
tools=formatted_tools if formatted_tools else None,
|
||||
stream=False
|
||||
)
|
||||
|
||||
tool_calls = getattr(initial_response.choices[0].message, 'tool_calls', None)
|
||||
|
||||
if tool_calls:
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": initial_response.choices[0].message.content,
|
||||
"tool_calls": tool_calls
|
||||
})
|
||||
|
||||
for tool_call in tool_calls:
|
||||
function_name = tool_call.function.name
|
||||
arguments = json.loads(tool_call.function.arguments)
|
||||
|
||||
if self.verbose:
|
||||
display_tool_call(f"Agent {self.name} is calling function '{function_name}' with arguments: {arguments}")
|
||||
|
||||
tool_result = self.execute_tool(function_name, arguments)
|
||||
results_str = json.dumps(tool_result) if tool_result else "Function returned an empty output"
|
||||
|
||||
if self.verbose:
|
||||
display_tool_call(f"Function '{function_name}' returned: {results_str}")
|
||||
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"content": results_str
|
||||
})
|
||||
|
||||
if stream:
|
||||
response_stream = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
stream=True
|
||||
)
|
||||
full_response_text = ""
|
||||
|
||||
# Create Live display with proper configuration
|
||||
with Live(
|
||||
display_generating("", start_time),
|
||||
console=self.console,
|
||||
refresh_per_second=4,
|
||||
transient=False, # Changed to False to preserve output
|
||||
vertical_overflow="ellipsis",
|
||||
auto_refresh=True
|
||||
) as live:
|
||||
for chunk in response_stream:
|
||||
if chunk.choices[0].delta.content:
|
||||
full_response_text += chunk.choices[0].delta.content
|
||||
live.update(display_generating(full_response_text, start_time))
|
||||
|
||||
# Clear the last generating display with a blank line
|
||||
self.console.print()
|
||||
|
||||
final_response = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
stream=False
|
||||
)
|
||||
return final_response
|
||||
else:
|
||||
if tool_calls:
|
||||
final_response = client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
stream=False
|
||||
)
|
||||
return final_response
|
||||
else:
|
||||
return initial_response
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
return None
|
||||
|
||||
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
|
||||
if self.use_system_prompt:
|
||||
system_prompt = f"""{self.backstory}\n
|
||||
Your Role: {self.role}\n
|
||||
Your Goal: {self.goal}
|
||||
"""
|
||||
if output_json:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
|
||||
elif output_pydantic:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
|
||||
else:
|
||||
system_prompt = None
|
||||
|
||||
messages = []
|
||||
if system_prompt:
|
||||
messages.append({"role": "system", "content": system_prompt})
|
||||
messages.extend(self.chat_history)
|
||||
|
||||
# Modify prompt if output_json or output_pydantic is specified
|
||||
original_prompt = prompt
|
||||
if output_json or output_pydantic:
|
||||
if isinstance(prompt, str):
|
||||
prompt += "\nReturn ONLY a valid JSON object. No other text or explanation."
|
||||
elif isinstance(prompt, list):
|
||||
# For multimodal prompts, append to the text content
|
||||
for item in prompt:
|
||||
if item["type"] == "text":
|
||||
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
|
||||
break
|
||||
|
||||
if isinstance(prompt, list):
|
||||
# If we receive a multimodal prompt list, place it directly in the user message
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
else:
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
|
||||
final_response_text = None
|
||||
reflection_count = 0
|
||||
start_time = time.time()
|
||||
|
||||
while True:
|
||||
try:
|
||||
if self.verbose:
|
||||
# Handle both string and list prompts for instruction display
|
||||
display_text = prompt
|
||||
if isinstance(prompt, list):
|
||||
# Extract text content from multimodal prompt
|
||||
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
|
||||
|
||||
if display_text and str(display_text).strip():
|
||||
display_instruction(f"Agent {self.name} is processing prompt: {display_text}", console=self.console)
|
||||
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None)
|
||||
if not response:
|
||||
return None
|
||||
|
||||
tool_calls = getattr(response.choices[0].message, 'tool_calls', None)
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
|
||||
if tool_calls:
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": response_text,
|
||||
"tool_calls": tool_calls
|
||||
})
|
||||
|
||||
for tool_call in tool_calls:
|
||||
function_name = tool_call.function.name
|
||||
arguments = json.loads(tool_call.function.arguments)
|
||||
|
||||
if self.verbose:
|
||||
display_tool_call(f"Agent {self.name} is calling function '{function_name}' with arguments: {arguments}", console=self.console)
|
||||
|
||||
tool_result = self.execute_tool(function_name, arguments)
|
||||
|
||||
if tool_result:
|
||||
if self.verbose:
|
||||
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=self.console)
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"content": json.dumps(tool_result)
|
||||
})
|
||||
else:
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"content": "Function returned an empty output"
|
||||
})
|
||||
|
||||
response = self._chat_completion(messages, temperature=temperature)
|
||||
if not response:
|
||||
return None
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
|
||||
# Handle output_json or output_pydantic if specified
|
||||
if output_json or output_pydantic:
|
||||
# Add to chat history and return raw response
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if self.verbose:
|
||||
display_interaction(original_prompt, response_text, markdown=self.markdown,
|
||||
generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
if not self.self_reflect:
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if self.verbose:
|
||||
logging.info(f"Agent {self.name} final response: {response_text}")
|
||||
display_interaction(original_prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
reflection_prompt = f"""
|
||||
Reflect on your previous response: '{response_text}'.
|
||||
Identify any flaws, improvements, or actions.
|
||||
Provide a "satisfactory" status ('yes' or 'no').
|
||||
Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
"""
|
||||
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
|
||||
messages.append({"role": "user", "content": reflection_prompt})
|
||||
|
||||
try:
|
||||
reflection_response = client.beta.chat.completions.parse(
|
||||
model=self.reflect_llm if self.reflect_llm else self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
response_format=ReflectionOutput
|
||||
)
|
||||
|
||||
reflection_output = reflection_response.choices[0].message.parsed
|
||||
|
||||
if self.verbose:
|
||||
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
|
||||
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
|
||||
|
||||
# Only consider satisfactory after minimum reflections
|
||||
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
# Check if we've hit max reflections
|
||||
if reflection_count >= self.max_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
|
||||
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
|
||||
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=True)
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
reflection_count += 1
|
||||
continue # Continue the loop for more reflections
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
|
||||
logging.error("Reflection parsing failed.", exc_info=True)
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection failed."})
|
||||
reflection_count += 1
|
||||
continue # Continue even after error to try again
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat: {e}", console=self.console)
|
||||
return None
|
||||
|
||||
def clean_json_output(self, output: str) -> str:
|
||||
"""Clean and extract JSON from response text."""
|
||||
cleaned = output.strip()
|
||||
# Remove markdown code blocks if present
|
||||
if cleaned.startswith("```json"):
|
||||
cleaned = cleaned[len("```json"):].strip()
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned[len("```"):].strip()
|
||||
if cleaned.endswith("```"):
|
||||
cleaned = cleaned[:-3].strip()
|
||||
return cleaned
|
||||
|
||||
async def achat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
|
||||
"""Async version of chat method"""
|
||||
try:
|
||||
# Build system prompt
|
||||
system_prompt = self.system_prompt
|
||||
if output_json:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
|
||||
elif output_pydantic:
|
||||
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
|
||||
|
||||
# Build messages
|
||||
if isinstance(prompt, str):
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt + ("\nReturn ONLY a valid JSON object. No other text or explanation." if (output_json or output_pydantic) else "")}
|
||||
]
|
||||
else:
|
||||
# For multimodal prompts
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
]
|
||||
if output_json or output_pydantic:
|
||||
# Add JSON instruction to text content
|
||||
for item in messages[-1]["content"]:
|
||||
if item["type"] == "text":
|
||||
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
|
||||
break
|
||||
|
||||
# Format tools if provided
|
||||
formatted_tools = []
|
||||
if tools:
|
||||
for tool in tools:
|
||||
if isinstance(tool, str):
|
||||
tool_def = self._generate_tool_definition(tool)
|
||||
if tool_def:
|
||||
formatted_tools.append(tool_def)
|
||||
elif isinstance(tool, dict):
|
||||
formatted_tools.append(tool)
|
||||
elif hasattr(tool, "to_openai_tool"):
|
||||
formatted_tools.append(tool.to_openai_tool())
|
||||
elif callable(tool):
|
||||
formatted_tools.append(self._generate_tool_definition(tool.__name__))
|
||||
|
||||
# Create async OpenAI client
|
||||
async_client = AsyncOpenAI()
|
||||
|
||||
# Make the API call based on the type of request
|
||||
if tools:
|
||||
response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
tools=formatted_tools
|
||||
)
|
||||
return await self._achat_completion(response, tools)
|
||||
elif output_json or output_pydantic:
|
||||
response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
# Return the raw response
|
||||
return response.choices[0].message.content
|
||||
else:
|
||||
response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature
|
||||
)
|
||||
return response.choices[0].message.content
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
return None
|
||||
|
||||
async def _achat_completion(self, response, tools):
|
||||
"""Async version of _chat_completion method"""
|
||||
try:
|
||||
message = response.choices[0].message
|
||||
if not hasattr(message, 'tool_calls') or not message.tool_calls:
|
||||
return message.content
|
||||
|
||||
results = []
|
||||
for tool_call in message.tool_calls:
|
||||
try:
|
||||
function_name = tool_call.function.name
|
||||
arguments = json.loads(tool_call.function.arguments)
|
||||
|
||||
# Find the matching tool
|
||||
tool = next((t for t in tools if t.__name__ == function_name), None)
|
||||
if not tool:
|
||||
display_error(f"Tool {function_name} not found")
|
||||
continue
|
||||
|
||||
# Check if the tool is async
|
||||
if asyncio.iscoroutinefunction(tool):
|
||||
result = await tool(**arguments)
|
||||
else:
|
||||
# Run sync function in executor to avoid blocking
|
||||
loop = asyncio.get_event_loop()
|
||||
result = await loop.run_in_executor(None, lambda: tool(**arguments))
|
||||
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
display_error(f"Error executing tool {function_name}: {e}")
|
||||
results.append(None)
|
||||
|
||||
# If we have results, format them into a response
|
||||
if results:
|
||||
formatted_results = "\n".join([str(r) for r in results if r is not None])
|
||||
if formatted_results:
|
||||
messages = [
|
||||
{"role": "system", "content": self.system_prompt},
|
||||
{"role": "assistant", "content": "Here are the tool results:"},
|
||||
{"role": "user", "content": formatted_results + "\nPlease process these results and provide a final response."}
|
||||
]
|
||||
try:
|
||||
async_client = AsyncOpenAI()
|
||||
final_response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=messages,
|
||||
temperature=0.2
|
||||
)
|
||||
return final_response.choices[0].message.content
|
||||
except Exception as e:
|
||||
display_error(f"Error in final chat completion: {e}")
|
||||
return formatted_results
|
||||
return formatted_results
|
||||
return None
|
||||
except Exception as e:
|
||||
display_error(f"Error in _achat_completion: {e}")
|
||||
return None
|
||||
@@ -1,568 +0,0 @@
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, Optional, List
|
||||
from pydantic import BaseModel
|
||||
from rich.text import Text
|
||||
from rich.panel import Panel
|
||||
from rich.console import Console
|
||||
from ..main import display_error, TaskOutput, error_logs, client
|
||||
from ..agent.agent import Agent
|
||||
from ..task.task import Task
|
||||
from ..process.process import Process, LoopItems
|
||||
import asyncio
|
||||
|
||||
def encode_file_to_base64(file_path: str) -> str:
|
||||
"""Base64-encode a file."""
|
||||
import base64
|
||||
with open(file_path, "rb") as f:
|
||||
return base64.b64encode(f.read()).decode("utf-8")
|
||||
|
||||
def process_video(video_path: str, seconds_per_frame=2):
|
||||
"""Split video into frames (base64-encoded)."""
|
||||
import cv2
|
||||
import base64
|
||||
base64_frames = []
|
||||
video = cv2.VideoCapture(video_path)
|
||||
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
fps = video.get(cv2.CAP_PROP_FPS)
|
||||
frames_to_skip = int(fps * seconds_per_frame)
|
||||
curr_frame = 0
|
||||
while curr_frame < total_frames:
|
||||
video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
|
||||
success, frame = video.read()
|
||||
if not success:
|
||||
break
|
||||
_, buffer = cv2.imencode(".jpg", frame)
|
||||
base64_frames.append(base64.b64encode(buffer).decode("utf-8"))
|
||||
curr_frame += frames_to_skip
|
||||
video.release()
|
||||
return base64_frames
|
||||
|
||||
class PraisonAIAgents:
|
||||
def __init__(self, agents, tasks=None, verbose=0, completion_checker=None, max_retries=5, process="sequential", manager_llm=None):
|
||||
if not agents:
|
||||
raise ValueError("At least one agent must be provided")
|
||||
|
||||
self.agents = agents
|
||||
self.tasks = {}
|
||||
if max_retries < 3:
|
||||
max_retries = 3
|
||||
self.completion_checker = completion_checker if completion_checker else self.default_completion_checker
|
||||
self.task_id_counter = 0
|
||||
self.verbose = verbose
|
||||
self.max_retries = max_retries
|
||||
self.process = process
|
||||
|
||||
# Check for manager_llm in environment variable if not provided
|
||||
self.manager_llm = manager_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
if self.verbose:
|
||||
logging.info(f"Using model {self.manager_llm} for manager")
|
||||
|
||||
# If no tasks provided, generate them from agents
|
||||
if tasks is None:
|
||||
tasks = []
|
||||
for agent in self.agents:
|
||||
task = agent.generate_task()
|
||||
tasks.append(task)
|
||||
logging.info(f"Auto-generated {len(tasks)} tasks from agents")
|
||||
else:
|
||||
# Validate tasks for backward compatibility
|
||||
if not tasks:
|
||||
raise ValueError("If tasks are provided, at least one task must be present")
|
||||
logging.info(f"Using {len(tasks)} provided tasks")
|
||||
|
||||
# Add tasks and set their status
|
||||
for task in tasks:
|
||||
self.add_task(task)
|
||||
task.status = "not started"
|
||||
|
||||
# If tasks were auto-generated from agents or process is sequential, set up sequential flow
|
||||
if len(tasks) > 1 and (process == "sequential" or all(task.next_tasks == [] for task in tasks)):
|
||||
for i in range(len(tasks) - 1):
|
||||
# Set up next task relationship
|
||||
tasks[i].next_tasks = [tasks[i + 1].name]
|
||||
# Set up context for the next task to include the current task
|
||||
if tasks[i + 1].context is None:
|
||||
tasks[i + 1].context = []
|
||||
tasks[i + 1].context.append(tasks[i])
|
||||
logging.info("Set up sequential flow with automatic context passing")
|
||||
|
||||
self._state = {} # Add state storage at PraisonAIAgents level
|
||||
|
||||
def add_task(self, task):
|
||||
task_id = self.task_id_counter
|
||||
task.id = task_id
|
||||
self.tasks[task_id] = task
|
||||
self.task_id_counter += 1
|
||||
return task_id
|
||||
|
||||
def clean_json_output(self, output: str) -> str:
|
||||
cleaned = output.strip()
|
||||
if cleaned.startswith("```json"):
|
||||
cleaned = cleaned[len("```json"):].strip()
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned[len("```"):].strip()
|
||||
if cleaned.endswith("```"):
|
||||
cleaned = cleaned[:-3].strip()
|
||||
return cleaned
|
||||
|
||||
def default_completion_checker(self, task, agent_output):
|
||||
if task.output_json and task.result and task.result.json_dict:
|
||||
return True
|
||||
if task.output_pydantic and task.result and task.result.pydantic:
|
||||
return True
|
||||
return len(agent_output.strip()) > 0
|
||||
|
||||
async def aexecute_task(self, task_id):
|
||||
"""Async version of execute_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
|
||||
# Only import multimodal dependencies if task has images
|
||||
if task.images and task.status == "not started":
|
||||
try:
|
||||
import cv2
|
||||
import base64
|
||||
from moviepy import VideoFileClip
|
||||
except ImportError as e:
|
||||
display_error(f"Error: Missing required dependencies for image/video processing: {e}")
|
||||
display_error("Please install with: pip install opencv-python moviepy")
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
if task.status == "not started":
|
||||
task.status = "in progress"
|
||||
|
||||
executor_agent = task.agent
|
||||
|
||||
task_prompt = f"""
|
||||
You need to do the following task: {task.description}.
|
||||
Expected Output: {task.expected_output}.
|
||||
"""
|
||||
if task.context:
|
||||
context_results = ""
|
||||
for context_task in task.context:
|
||||
if context_task.result:
|
||||
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
|
||||
else:
|
||||
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
|
||||
task_prompt += f"""
|
||||
Here are the results of previous tasks that might be useful:\n
|
||||
{context_results}
|
||||
"""
|
||||
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
|
||||
|
||||
if self.verbose >= 2:
|
||||
logging.info(f"Executing task {task_id}: {task.description} using {executor_agent.name}")
|
||||
logging.debug(f"Starting execution of task {task_id} with prompt:\n{task_prompt}")
|
||||
|
||||
if task.images:
|
||||
def _get_multimodal_message(text_prompt, images):
|
||||
content = [{"type": "text", "text": text_prompt}]
|
||||
|
||||
for img in images:
|
||||
# If local file path for a valid image
|
||||
if os.path.exists(img):
|
||||
ext = os.path.splitext(img)[1].lower()
|
||||
# If it's a .mp4, convert to frames
|
||||
if ext == ".mp4":
|
||||
frames = process_video(img, seconds_per_frame=1)
|
||||
content.append({"type": "text", "text": "These are frames from the video."})
|
||||
for f in frames:
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpg;base64,{f}"}
|
||||
})
|
||||
else:
|
||||
encoded = encode_file_to_base64(img)
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/{ext.lstrip('.')};base64,{encoded}"
|
||||
}
|
||||
})
|
||||
else:
|
||||
# Treat as a remote URL
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": img}
|
||||
})
|
||||
return content
|
||||
|
||||
agent_output = await executor_agent.achat(
|
||||
_get_multimodal_message(task_prompt, task.images),
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
else:
|
||||
agent_output = await executor_agent.achat(
|
||||
task_prompt,
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
|
||||
if agent_output:
|
||||
task_output = TaskOutput(
|
||||
description=task.description,
|
||||
summary=task.description[:10],
|
||||
raw=agent_output,
|
||||
agent=executor_agent.name,
|
||||
output_format="RAW"
|
||||
)
|
||||
|
||||
if task.output_json:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
task_output.json_dict = parsed
|
||||
task_output.output_format = "JSON"
|
||||
except:
|
||||
logging.warning(f"Warning: Could not parse output of task {task_id} as JSON")
|
||||
logging.debug(f"Output that failed JSON parsing: {agent_output}")
|
||||
|
||||
if task.output_pydantic:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
pyd_obj = task.output_pydantic(**parsed)
|
||||
task_output.pydantic = pyd_obj
|
||||
task_output.output_format = "Pydantic"
|
||||
except:
|
||||
logging.warning(f"Warning: Could not parse output of task {task_id} as Pydantic Model")
|
||||
logging.debug(f"Output that failed Pydantic parsing: {agent_output}")
|
||||
|
||||
task.result = task_output
|
||||
return task_output
|
||||
else:
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
async def arun_task(self, task_id):
|
||||
"""Async version of run_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
if task.status == "completed":
|
||||
logging.info(f"Task with ID {task_id} is already completed")
|
||||
return
|
||||
|
||||
retries = 0
|
||||
while task.status != "completed" and retries < self.max_retries:
|
||||
logging.debug(f"Attempt {retries+1} for task {task_id}")
|
||||
if task.status in ["not started", "in progress"]:
|
||||
task_output = await self.aexecute_task(task_id)
|
||||
if task_output and self.completion_checker(task, task_output.raw):
|
||||
task.status = "completed"
|
||||
if task.callback:
|
||||
await task.execute_callback(task_output)
|
||||
self.save_output_to_file(task, task_output)
|
||||
if self.verbose >= 1:
|
||||
logging.info(f"Task {task_id} completed successfully.")
|
||||
else:
|
||||
task.status = "in progress"
|
||||
if self.verbose >= 1:
|
||||
logging.info(f"Task {task_id} not completed, retrying")
|
||||
await asyncio.sleep(1)
|
||||
retries += 1
|
||||
else:
|
||||
if task.status == "failed":
|
||||
logging.info("Task is failed, resetting to in-progress for another try...")
|
||||
task.status = "in progress"
|
||||
else:
|
||||
logging.info("Invalid Task status")
|
||||
break
|
||||
|
||||
if retries == self.max_retries and task.status != "completed":
|
||||
logging.info(f"Task {task_id} failed after {self.max_retries} retries.")
|
||||
|
||||
async def arun_all_tasks(self):
|
||||
"""Async version of run_all_tasks method"""
|
||||
process = Process(
|
||||
tasks=self.tasks,
|
||||
agents=self.agents,
|
||||
manager_llm=self.manager_llm,
|
||||
verbose=self.verbose
|
||||
)
|
||||
|
||||
if self.process == "workflow":
|
||||
async for task_id in process.aworkflow():
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
elif self.process == "sequential":
|
||||
async for task_id in process.asequential():
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
elif self.process == "hierarchical":
|
||||
async for task_id in process.ahierarchical():
|
||||
if isinstance(task_id, Task):
|
||||
task_id = self.add_task(task_id)
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
|
||||
async def astart(self):
|
||||
"""Async version of start method"""
|
||||
await self.arun_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
|
||||
}
|
||||
|
||||
def save_output_to_file(self, task, task_output):
|
||||
if task.output_file:
|
||||
try:
|
||||
if task.create_directory:
|
||||
os.makedirs(os.path.dirname(task.output_file), exist_ok=True)
|
||||
with open(task.output_file, "w") as f:
|
||||
f.write(str(task_output))
|
||||
if self.verbose >= 1:
|
||||
logging.info(f"Task output saved to {task.output_file}")
|
||||
except Exception as e:
|
||||
display_error(f"Error saving task output to file: {e}")
|
||||
|
||||
def execute_task(self, task_id):
|
||||
"""Synchronous version of execute_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
|
||||
# Only import multimodal dependencies if task has images
|
||||
if task.images and task.status == "not started":
|
||||
try:
|
||||
import cv2
|
||||
import base64
|
||||
from moviepy import VideoFileClip
|
||||
except ImportError as e:
|
||||
display_error(f"Error: Missing required dependencies for image/video processing: {e}")
|
||||
display_error("Please install with: pip install opencv-python moviepy")
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
if task.status == "not started":
|
||||
task.status = "in progress"
|
||||
|
||||
executor_agent = task.agent
|
||||
|
||||
task_prompt = f"""
|
||||
You need to do the following task: {task.description}.
|
||||
Expected Output: {task.expected_output}.
|
||||
"""
|
||||
if task.context:
|
||||
context_results = ""
|
||||
for context_task in task.context:
|
||||
if context_task.result:
|
||||
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
|
||||
else:
|
||||
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
|
||||
task_prompt += f"""
|
||||
Here are the results of previous tasks that might be useful:\n
|
||||
{context_results}
|
||||
"""
|
||||
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
|
||||
|
||||
if self.verbose >= 2:
|
||||
logging.info(f"Executing task {task_id}: {task.description} using {executor_agent.name}")
|
||||
logging.debug(f"Starting execution of task {task_id} with prompt:\n{task_prompt}")
|
||||
|
||||
if task.images:
|
||||
def _get_multimodal_message(text_prompt, images):
|
||||
content = [{"type": "text", "text": text_prompt}]
|
||||
|
||||
for img in images:
|
||||
# If local file path for a valid image
|
||||
if os.path.exists(img):
|
||||
ext = os.path.splitext(img)[1].lower()
|
||||
# If it's a .mp4, convert to frames
|
||||
if ext == ".mp4":
|
||||
frames = process_video(img, seconds_per_frame=1)
|
||||
content.append({"type": "text", "text": "These are frames from the video."})
|
||||
for f in frames:
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpg;base64,{f}"}
|
||||
})
|
||||
else:
|
||||
encoded = encode_file_to_base64(img)
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/{ext.lstrip('.')};base64,{encoded}"
|
||||
}
|
||||
})
|
||||
else:
|
||||
# Treat as a remote URL
|
||||
content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": img}
|
||||
})
|
||||
return content
|
||||
|
||||
agent_output = executor_agent.chat(
|
||||
_get_multimodal_message(task_prompt, task.images),
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
else:
|
||||
agent_output = executor_agent.chat(
|
||||
task_prompt,
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
)
|
||||
|
||||
if agent_output:
|
||||
task_output = TaskOutput(
|
||||
description=task.description,
|
||||
summary=task.description[:10],
|
||||
raw=agent_output,
|
||||
agent=executor_agent.name,
|
||||
output_format="RAW"
|
||||
)
|
||||
|
||||
if task.output_json:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
task_output.json_dict = parsed
|
||||
task_output.output_format = "JSON"
|
||||
except:
|
||||
logging.warning(f"Warning: Could not parse output of task {task_id} as JSON")
|
||||
logging.debug(f"Output that failed JSON parsing: {agent_output}")
|
||||
|
||||
if task.output_pydantic:
|
||||
cleaned = self.clean_json_output(agent_output)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
pyd_obj = task.output_pydantic(**parsed)
|
||||
task_output.pydantic = pyd_obj
|
||||
task_output.output_format = "Pydantic"
|
||||
except:
|
||||
logging.warning(f"Warning: Could not parse output of task {task_id} as Pydantic Model")
|
||||
logging.debug(f"Output that failed Pydantic parsing: {agent_output}")
|
||||
|
||||
task.result = task_output
|
||||
return task_output
|
||||
else:
|
||||
task.status = "failed"
|
||||
return None
|
||||
|
||||
def run_task(self, task_id):
|
||||
"""Synchronous version of run_task method"""
|
||||
if task_id not in self.tasks:
|
||||
display_error(f"Error: Task with ID {task_id} does not exist")
|
||||
return
|
||||
task = self.tasks[task_id]
|
||||
if task.status == "completed":
|
||||
logging.info(f"Task with ID {task_id} is already completed")
|
||||
return
|
||||
|
||||
retries = 0
|
||||
while task.status != "completed" and retries < self.max_retries:
|
||||
logging.debug(f"Attempt {retries+1} for task {task_id}")
|
||||
if task.status in ["not started", "in progress"]:
|
||||
task_output = self.execute_task(task_id)
|
||||
if task_output and self.completion_checker(task, task_output.raw):
|
||||
task.status = "completed"
|
||||
if task.callback:
|
||||
task.callback(task_output)
|
||||
self.save_output_to_file(task, task_output)
|
||||
if self.verbose >= 1:
|
||||
logging.info(f"Task {task_id} completed successfully.")
|
||||
else:
|
||||
task.status = "in progress"
|
||||
if self.verbose >= 1:
|
||||
logging.info(f"Task {task_id} not completed, retrying")
|
||||
time.sleep(1)
|
||||
retries += 1
|
||||
else:
|
||||
if task.status == "failed":
|
||||
logging.info("Task is failed, resetting to in-progress for another try...")
|
||||
task.status = "in progress"
|
||||
else:
|
||||
logging.info("Invalid Task status")
|
||||
break
|
||||
|
||||
if retries == self.max_retries and task.status != "completed":
|
||||
logging.info(f"Task {task_id} failed after {self.max_retries} retries.")
|
||||
|
||||
def run_all_tasks(self):
|
||||
"""Synchronous version of run_all_tasks method"""
|
||||
process = Process(
|
||||
tasks=self.tasks,
|
||||
agents=self.agents,
|
||||
manager_llm=self.manager_llm,
|
||||
verbose=self.verbose
|
||||
)
|
||||
|
||||
if self.process == "workflow":
|
||||
for task_id in process.workflow():
|
||||
self.run_task(task_id)
|
||||
elif self.process == "sequential":
|
||||
for task_id in process.sequential():
|
||||
self.run_task(task_id)
|
||||
elif self.process == "hierarchical":
|
||||
for task_id in process.hierarchical():
|
||||
if isinstance(task_id, Task):
|
||||
task_id = self.add_task(task_id)
|
||||
self.run_task(task_id)
|
||||
|
||||
def get_task_status(self, task_id):
|
||||
if task_id in self.tasks:
|
||||
return self.tasks[task_id].status
|
||||
return None
|
||||
|
||||
def get_all_tasks_status(self):
|
||||
return {task_id: self.tasks[task_id].status for task_id in self.tasks}
|
||||
|
||||
def get_task_result(self, task_id):
|
||||
if task_id in self.tasks:
|
||||
return self.tasks[task_id].result
|
||||
return None
|
||||
|
||||
def get_task_details(self, task_id):
|
||||
if task_id in self.tasks:
|
||||
return str(self.tasks[task_id])
|
||||
return None
|
||||
|
||||
def get_agent_details(self, agent_name):
|
||||
agent = [task.agent for task in self.tasks.values() if task.agent and task.agent.name == agent_name]
|
||||
if agent:
|
||||
return str(agent[0])
|
||||
return None
|
||||
|
||||
def start(self):
|
||||
self.run_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
|
||||
}
|
||||
|
||||
def set_state(self, key: str, value: Any) -> None:
|
||||
"""Set a state value"""
|
||||
self._state[key] = value
|
||||
|
||||
def get_state(self, key: str, default: Any = None) -> Any:
|
||||
"""Get a state value"""
|
||||
return self._state.get(key, default)
|
||||
|
||||
def update_state(self, updates: Dict) -> None:
|
||||
"""Update multiple state values"""
|
||||
self._state.update(updates)
|
||||
|
||||
def clear_state(self) -> None:
|
||||
"""Clear all state values"""
|
||||
self._state.clear()
|
||||
@@ -1,534 +0,0 @@
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import Dict, Optional, List, Any, AsyncGenerator
|
||||
from pydantic import BaseModel
|
||||
from ..agent.agent import Agent
|
||||
from ..task.task import Task
|
||||
from ..main import display_error, client
|
||||
|
||||
class LoopItems(BaseModel):
|
||||
items: List[Any]
|
||||
|
||||
class Process:
|
||||
def __init__(self, tasks: Dict[str, Task], agents: List[Agent], manager_llm: Optional[str] = None, verbose: bool = False):
|
||||
self.tasks = tasks
|
||||
self.agents = agents
|
||||
self.manager_llm = manager_llm
|
||||
self.verbose = verbose
|
||||
|
||||
async def aworkflow(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of workflow method"""
|
||||
# Build workflow relationships first
|
||||
for task in self.tasks.values():
|
||||
if task.next_tasks:
|
||||
for next_task_name in task.next_tasks:
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
if next_task:
|
||||
next_task.previous_tasks.append(task.name)
|
||||
|
||||
# Find start task
|
||||
start_task = None
|
||||
for task_id, task in self.tasks.items():
|
||||
if task.is_start:
|
||||
start_task = task
|
||||
break
|
||||
|
||||
if not start_task:
|
||||
start_task = list(self.tasks.values())[0]
|
||||
logging.info("No start task marked, using first task")
|
||||
|
||||
current_task = start_task
|
||||
visited_tasks = set()
|
||||
loop_data = {} # Store loop-specific data
|
||||
|
||||
while current_task and current_task.id not in visited_tasks:
|
||||
task_id = current_task.id
|
||||
logging.info(f"Executing workflow task: {current_task.name if current_task.name else task_id}")
|
||||
|
||||
# Add context from previous tasks to description
|
||||
if current_task.previous_tasks or current_task.context:
|
||||
context = "\nInput data from previous tasks:"
|
||||
|
||||
# Add data from previous tasks in workflow
|
||||
for prev_name in current_task.previous_tasks:
|
||||
prev_task = next((t for t in self.tasks.values() if t.name == prev_name), None)
|
||||
if prev_task and prev_task.result:
|
||||
# Handle loop data
|
||||
if current_task.task_type == "loop":
|
||||
# create a loop manager Agent
|
||||
loop_manager = Agent(
|
||||
name="Loop Manager",
|
||||
role="Loop data processor",
|
||||
goal="Process loop data and convert it to list format",
|
||||
backstory="Expert at handling loop data and converting it to proper format",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# get the loop data convert it to list using calling Agent class chat
|
||||
loop_prompt = f"""
|
||||
Process this data into a list format:
|
||||
{prev_task.result.raw}
|
||||
|
||||
Return a JSON object with an 'items' array containing the items to process.
|
||||
"""
|
||||
if current_task.async_execution:
|
||||
loop_data_str = await loop_manager.achat(
|
||||
prompt=loop_prompt,
|
||||
output_json=LoopItems
|
||||
)
|
||||
else:
|
||||
loop_data_str = loop_manager.chat(
|
||||
prompt=loop_prompt,
|
||||
output_json=LoopItems
|
||||
)
|
||||
|
||||
try:
|
||||
# The response will already be parsed into LoopItems model
|
||||
loop_data[f"loop_{current_task.name}"] = {
|
||||
"items": loop_data_str.items,
|
||||
"index": 0,
|
||||
"remaining": len(loop_data_str.items)
|
||||
}
|
||||
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
|
||||
except Exception as e:
|
||||
display_error(f"Failed to process loop data: {e}")
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
else:
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
|
||||
# Add data from context tasks
|
||||
if current_task.context:
|
||||
for ctx_task in current_task.context:
|
||||
if ctx_task.result and ctx_task.name != current_task.name:
|
||||
context += f"\n{ctx_task.name}: {ctx_task.result.raw}"
|
||||
|
||||
# Update task description with context
|
||||
current_task.description = current_task.description + context
|
||||
|
||||
# Execute task using existing run_task method
|
||||
yield task_id
|
||||
visited_tasks.add(task_id)
|
||||
|
||||
# Handle loop progression
|
||||
if current_task.task_type == "loop":
|
||||
loop_key = f"loop_{current_task.name}"
|
||||
if loop_key in loop_data:
|
||||
loop_info = loop_data[loop_key]
|
||||
loop_info["index"] += 1
|
||||
has_more = loop_info["remaining"] > 0
|
||||
|
||||
# Update result to trigger correct condition
|
||||
if current_task.result:
|
||||
result = current_task.result.raw
|
||||
if has_more:
|
||||
result += "\nmore"
|
||||
else:
|
||||
result += "\ndone"
|
||||
current_task.result.raw = result
|
||||
|
||||
# Determine next task based on result
|
||||
next_task = None
|
||||
if current_task.result:
|
||||
if current_task.task_type in ["decision", "loop"]:
|
||||
result = current_task.result.raw.lower()
|
||||
# Check conditions
|
||||
for condition, tasks in current_task.condition.items():
|
||||
if condition.lower() in result and tasks:
|
||||
next_task_name = tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
# For loops, allow revisiting the same task
|
||||
if next_task and next_task.id == current_task.id:
|
||||
visited_tasks.discard(current_task.id)
|
||||
break
|
||||
|
||||
if not next_task and current_task.next_tasks:
|
||||
next_task_name = current_task.next_tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
|
||||
current_task = next_task
|
||||
if not current_task:
|
||||
logging.info("Workflow execution completed")
|
||||
break
|
||||
|
||||
async def asequential(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of sequential method"""
|
||||
for task_id in self.tasks:
|
||||
if self.tasks[task_id].status != "completed":
|
||||
yield task_id
|
||||
|
||||
async def ahierarchical(self) -> AsyncGenerator[str, None]:
|
||||
"""Async version of hierarchical method"""
|
||||
logging.debug(f"Starting hierarchical task execution with {len(self.tasks)} tasks")
|
||||
manager_agent = Agent(
|
||||
name="Manager",
|
||||
role="Project manager",
|
||||
goal="Manage the entire flow of tasks and delegate them to the right agent",
|
||||
backstory="Expert project manager to coordinate tasks among agents",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True,
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
class ManagerInstructions(BaseModel):
|
||||
task_id: int
|
||||
agent_name: str
|
||||
action: str
|
||||
|
||||
manager_task = Task(
|
||||
name="manager_task",
|
||||
description="Decide the order of tasks and which agent executes them",
|
||||
expected_output="All tasks completed successfully",
|
||||
agent=manager_agent
|
||||
)
|
||||
manager_task_id = yield manager_task
|
||||
logging.info(f"Created manager task with ID {manager_task_id}")
|
||||
|
||||
completed_count = 0
|
||||
total_tasks = len(self.tasks) - 1
|
||||
logging.info(f"Need to complete {total_tasks} tasks (excluding manager task)")
|
||||
|
||||
while completed_count < total_tasks:
|
||||
tasks_summary = []
|
||||
for tid, tk in self.tasks.items():
|
||||
if tk.name == "manager_task":
|
||||
continue
|
||||
task_info = {
|
||||
"task_id": tid,
|
||||
"name": tk.name,
|
||||
"description": tk.description,
|
||||
"status": tk.status if tk.status else "not started",
|
||||
"agent": tk.agent.name if tk.agent else "No agent"
|
||||
}
|
||||
tasks_summary.append(task_info)
|
||||
logging.info(f"Task {tid} status: {task_info}")
|
||||
|
||||
manager_prompt = f"""
|
||||
Here is the current status of all tasks except yours (manager_task):
|
||||
{tasks_summary}
|
||||
|
||||
Provide a JSON with the structure:
|
||||
{{
|
||||
"task_id": <int>,
|
||||
"agent_name": "<string>",
|
||||
"action": "<execute or stop>"
|
||||
}}
|
||||
"""
|
||||
|
||||
try:
|
||||
logging.info("Requesting manager instructions...")
|
||||
if manager_task.async_execution:
|
||||
manager_response = await client.beta.chat.completions.parse(
|
||||
model=self.manager_llm,
|
||||
messages=[
|
||||
{"role": "system", "content": manager_task.description},
|
||||
{"role": "user", "content": manager_prompt}
|
||||
],
|
||||
temperature=0.7,
|
||||
response_format=ManagerInstructions
|
||||
)
|
||||
else:
|
||||
manager_response = client.beta.chat.completions.parse(
|
||||
model=self.manager_llm,
|
||||
messages=[
|
||||
{"role": "system", "content": manager_task.description},
|
||||
{"role": "user", "content": manager_prompt}
|
||||
],
|
||||
temperature=0.7,
|
||||
response_format=ManagerInstructions
|
||||
)
|
||||
parsed_instructions = manager_response.choices[0].message.parsed
|
||||
logging.info(f"Manager instructions: {parsed_instructions}")
|
||||
except Exception as e:
|
||||
display_error(f"Manager parse error: {e}")
|
||||
logging.error(f"Manager parse error: {str(e)}", exc_info=True)
|
||||
break
|
||||
|
||||
selected_task_id = parsed_instructions.task_id
|
||||
selected_agent_name = parsed_instructions.agent_name
|
||||
action = parsed_instructions.action
|
||||
|
||||
logging.info(f"Manager selected task_id={selected_task_id}, agent={selected_agent_name}, action={action}")
|
||||
|
||||
if action.lower() == "stop":
|
||||
logging.info("Manager decided to stop task execution")
|
||||
break
|
||||
|
||||
if selected_task_id not in self.tasks:
|
||||
error_msg = f"Manager selected invalid task id {selected_task_id}"
|
||||
display_error(error_msg)
|
||||
logging.error(error_msg)
|
||||
break
|
||||
|
||||
original_agent = self.tasks[selected_task_id].agent.name if self.tasks[selected_task_id].agent else "None"
|
||||
for a in self.agents:
|
||||
if a.name == selected_agent_name:
|
||||
self.tasks[selected_task_id].agent = a
|
||||
logging.info(f"Changed agent for task {selected_task_id} from {original_agent} to {selected_agent_name}")
|
||||
break
|
||||
|
||||
if self.tasks[selected_task_id].status != "completed":
|
||||
logging.info(f"Starting execution of task {selected_task_id}")
|
||||
yield selected_task_id
|
||||
logging.info(f"Finished execution of task {selected_task_id}, status: {self.tasks[selected_task_id].status}")
|
||||
|
||||
if self.tasks[selected_task_id].status == "completed":
|
||||
completed_count += 1
|
||||
logging.info(f"Task {selected_task_id} completed. Total completed: {completed_count}/{total_tasks}")
|
||||
|
||||
self.tasks[manager_task.id].status = "completed"
|
||||
if self.verbose >= 1:
|
||||
logging.info("All tasks completed under manager supervision.")
|
||||
logging.info("Hierarchical task execution finished")
|
||||
|
||||
def workflow(self):
|
||||
"""Synchronous version of workflow method"""
|
||||
# Build workflow relationships first
|
||||
for task in self.tasks.values():
|
||||
if task.next_tasks:
|
||||
for next_task_name in task.next_tasks:
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
if next_task:
|
||||
next_task.previous_tasks.append(task.name)
|
||||
|
||||
# Find start task
|
||||
start_task = None
|
||||
for task_id, task in self.tasks.items():
|
||||
if task.is_start:
|
||||
start_task = task
|
||||
break
|
||||
|
||||
if not start_task:
|
||||
start_task = list(self.tasks.values())[0]
|
||||
logging.info("No start task marked, using first task")
|
||||
|
||||
current_task = start_task
|
||||
visited_tasks = set()
|
||||
loop_data = {} # Store loop-specific data
|
||||
|
||||
while current_task and current_task.id not in visited_tasks:
|
||||
task_id = current_task.id
|
||||
logging.info(f"Executing workflow task: {current_task.name if current_task.name else task_id}")
|
||||
|
||||
# Add context from previous tasks to description
|
||||
if current_task.previous_tasks or current_task.context:
|
||||
context = "\nInput data from previous tasks:"
|
||||
|
||||
# Add data from previous tasks in workflow
|
||||
for prev_name in current_task.previous_tasks:
|
||||
prev_task = next((t for t in self.tasks.values() if t.name == prev_name), None)
|
||||
if prev_task and prev_task.result:
|
||||
# Handle loop data
|
||||
if current_task.task_type == "loop":
|
||||
# create a loop manager Agent
|
||||
loop_manager = Agent(
|
||||
name="Loop Manager",
|
||||
role="Loop data processor",
|
||||
goal="Process loop data and convert it to list format",
|
||||
backstory="Expert at handling loop data and converting it to proper format",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# get the loop data convert it to list using calling Agent class chat
|
||||
loop_prompt = f"""
|
||||
Process this data into a list format:
|
||||
{prev_task.result.raw}
|
||||
|
||||
Return a JSON object with an 'items' array containing the items to process.
|
||||
"""
|
||||
loop_data_str = loop_manager.chat(
|
||||
prompt=loop_prompt,
|
||||
output_json=LoopItems
|
||||
)
|
||||
|
||||
try:
|
||||
# The response will already be parsed into LoopItems model
|
||||
loop_data[f"loop_{current_task.name}"] = {
|
||||
"items": loop_data_str.items,
|
||||
"index": 0,
|
||||
"remaining": len(loop_data_str.items)
|
||||
}
|
||||
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
|
||||
except Exception as e:
|
||||
display_error(f"Failed to process loop data: {e}")
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
else:
|
||||
context += f"\n{prev_name}: {prev_task.result.raw}"
|
||||
|
||||
# Add data from context tasks
|
||||
if current_task.context:
|
||||
for ctx_task in current_task.context:
|
||||
if ctx_task.result and ctx_task.name != current_task.name:
|
||||
context += f"\n{ctx_task.name}: {ctx_task.result.raw}"
|
||||
|
||||
# Update task description with context
|
||||
current_task.description = current_task.description + context
|
||||
|
||||
# Execute task using existing run_task method
|
||||
yield task_id
|
||||
visited_tasks.add(task_id)
|
||||
|
||||
# Handle loop progression
|
||||
if current_task.task_type == "loop":
|
||||
loop_key = f"loop_{current_task.name}"
|
||||
if loop_key in loop_data:
|
||||
loop_info = loop_data[loop_key]
|
||||
loop_info["index"] += 1
|
||||
has_more = loop_info["remaining"] > 0
|
||||
|
||||
# Update result to trigger correct condition
|
||||
if current_task.result:
|
||||
result = current_task.result.raw
|
||||
if has_more:
|
||||
result += "\nmore"
|
||||
else:
|
||||
result += "\ndone"
|
||||
current_task.result.raw = result
|
||||
|
||||
# Determine next task based on result
|
||||
next_task = None
|
||||
if current_task.result:
|
||||
if current_task.task_type in ["decision", "loop"]:
|
||||
result = current_task.result.raw.lower()
|
||||
# Check conditions
|
||||
for condition, tasks in current_task.condition.items():
|
||||
if condition.lower() in result and tasks:
|
||||
next_task_name = tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
# For loops, allow revisiting the same task
|
||||
if next_task and next_task.id == current_task.id:
|
||||
visited_tasks.discard(current_task.id)
|
||||
break
|
||||
|
||||
if not next_task and current_task.next_tasks:
|
||||
next_task_name = current_task.next_tasks[0]
|
||||
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
|
||||
|
||||
current_task = next_task
|
||||
if not current_task:
|
||||
logging.info("Workflow execution completed")
|
||||
break
|
||||
|
||||
def sequential(self):
|
||||
"""Synchronous version of sequential method"""
|
||||
for task_id in self.tasks:
|
||||
if self.tasks[task_id].status != "completed":
|
||||
yield task_id
|
||||
|
||||
def hierarchical(self):
|
||||
"""Synchronous version of hierarchical method"""
|
||||
logging.debug(f"Starting hierarchical task execution with {len(self.tasks)} tasks")
|
||||
manager_agent = Agent(
|
||||
name="Manager",
|
||||
role="Project manager",
|
||||
goal="Manage the entire flow of tasks and delegate them to the right agent",
|
||||
backstory="Expert project manager to coordinate tasks among agents",
|
||||
llm=self.manager_llm,
|
||||
verbose=self.verbose,
|
||||
markdown=True,
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
class ManagerInstructions(BaseModel):
|
||||
task_id: int
|
||||
agent_name: str
|
||||
action: str
|
||||
|
||||
manager_task = Task(
|
||||
name="manager_task",
|
||||
description="Decide the order of tasks and which agent executes them",
|
||||
expected_output="All tasks completed successfully",
|
||||
agent=manager_agent
|
||||
)
|
||||
manager_task_id = yield manager_task
|
||||
logging.info(f"Created manager task with ID {manager_task_id}")
|
||||
|
||||
completed_count = 0
|
||||
total_tasks = len(self.tasks) - 1
|
||||
logging.info(f"Need to complete {total_tasks} tasks (excluding manager task)")
|
||||
|
||||
while completed_count < total_tasks:
|
||||
tasks_summary = []
|
||||
for tid, tk in self.tasks.items():
|
||||
if tk.name == "manager_task":
|
||||
continue
|
||||
task_info = {
|
||||
"task_id": tid,
|
||||
"name": tk.name,
|
||||
"description": tk.description,
|
||||
"status": tk.status if tk.status else "not started",
|
||||
"agent": tk.agent.name if tk.agent else "No agent"
|
||||
}
|
||||
tasks_summary.append(task_info)
|
||||
logging.info(f"Task {tid} status: {task_info}")
|
||||
|
||||
manager_prompt = f"""
|
||||
Here is the current status of all tasks except yours (manager_task):
|
||||
{tasks_summary}
|
||||
|
||||
Provide a JSON with the structure:
|
||||
{{
|
||||
"task_id": <int>,
|
||||
"agent_name": "<string>",
|
||||
"action": "<execute or stop>"
|
||||
}}
|
||||
"""
|
||||
|
||||
try:
|
||||
logging.info("Requesting manager instructions...")
|
||||
manager_response = client.beta.chat.completions.parse(
|
||||
model=self.manager_llm,
|
||||
messages=[
|
||||
{"role": "system", "content": manager_task.description},
|
||||
{"role": "user", "content": manager_prompt}
|
||||
],
|
||||
temperature=0.7,
|
||||
response_format=ManagerInstructions
|
||||
)
|
||||
parsed_instructions = manager_response.choices[0].message.parsed
|
||||
logging.info(f"Manager instructions: {parsed_instructions}")
|
||||
except Exception as e:
|
||||
display_error(f"Manager parse error: {e}")
|
||||
logging.error(f"Manager parse error: {str(e)}", exc_info=True)
|
||||
break
|
||||
|
||||
selected_task_id = parsed_instructions.task_id
|
||||
selected_agent_name = parsed_instructions.agent_name
|
||||
action = parsed_instructions.action
|
||||
|
||||
logging.info(f"Manager selected task_id={selected_task_id}, agent={selected_agent_name}, action={action}")
|
||||
|
||||
if action.lower() == "stop":
|
||||
logging.info("Manager decided to stop task execution")
|
||||
break
|
||||
|
||||
if selected_task_id not in self.tasks:
|
||||
error_msg = f"Manager selected invalid task id {selected_task_id}"
|
||||
display_error(error_msg)
|
||||
logging.error(error_msg)
|
||||
break
|
||||
|
||||
original_agent = self.tasks[selected_task_id].agent.name if self.tasks[selected_task_id].agent else "None"
|
||||
for a in self.agents:
|
||||
if a.name == selected_agent_name:
|
||||
self.tasks[selected_task_id].agent = a
|
||||
logging.info(f"Changed agent for task {selected_task_id} from {original_agent} to {selected_agent_name}")
|
||||
break
|
||||
|
||||
if self.tasks[selected_task_id].status != "completed":
|
||||
logging.info(f"Starting execution of task {selected_task_id}")
|
||||
yield selected_task_id
|
||||
logging.info(f"Finished execution of task {selected_task_id}, status: {self.tasks[selected_task_id].status}")
|
||||
|
||||
if self.tasks[selected_task_id].status == "completed":
|
||||
completed_count += 1
|
||||
logging.info(f"Task {selected_task_id} completed. Total completed: {completed_count}/{total_tasks}")
|
||||
|
||||
self.tasks[manager_task.id].status = "completed"
|
||||
if self.verbose >= 1:
|
||||
logging.info("All tasks completed under manager supervision.")
|
||||
logging.info("Hierarchical task execution finished")
|
||||
@@ -1,74 +0,0 @@
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import List, Optional, Dict, Any, Type, Callable, Union, Coroutine
|
||||
from pydantic import BaseModel
|
||||
from ..main import TaskOutput
|
||||
from ..agent.agent import Agent
|
||||
import uuid
|
||||
|
||||
class Task:
|
||||
def __init__(
|
||||
self,
|
||||
description: str,
|
||||
expected_output: str,
|
||||
agent: Optional[Agent] = None,
|
||||
name: Optional[str] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
context: Optional[List["Task"]] = None,
|
||||
async_execution: Optional[bool] = False,
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
output_file: Optional[str] = None,
|
||||
output_json: Optional[Type[BaseModel]] = None,
|
||||
output_pydantic: Optional[Type[BaseModel]] = None,
|
||||
callback: Optional[Union[Callable[[TaskOutput], Any], Callable[[TaskOutput], Coroutine[Any, Any, Any]]]] = None,
|
||||
status: str = "not started",
|
||||
result: Optional[TaskOutput] = None,
|
||||
create_directory: Optional[bool] = False,
|
||||
id: Optional[int] = None,
|
||||
images: Optional[List[str]] = None,
|
||||
next_tasks: Optional[List[str]] = None,
|
||||
task_type: str = "task",
|
||||
condition: Optional[Dict[str, List[str]]] = None,
|
||||
is_start: bool = False,
|
||||
loop_state: Optional[Dict[str, Union[str, int]]] = None
|
||||
):
|
||||
self.id = str(uuid.uuid4()) if id is None else str(id)
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.expected_output = expected_output
|
||||
self.agent = agent
|
||||
self.tools = tools if tools else []
|
||||
self.context = context if context else []
|
||||
self.async_execution = async_execution
|
||||
self.config = config if config else {}
|
||||
self.output_file = output_file
|
||||
self.output_json = output_json
|
||||
self.output_pydantic = output_pydantic
|
||||
self.callback = callback
|
||||
self.status = status
|
||||
self.result = result
|
||||
self.create_directory = create_directory
|
||||
self.images = images if images else []
|
||||
self.next_tasks = next_tasks if next_tasks else []
|
||||
self.task_type = task_type
|
||||
self.condition = condition if condition else {}
|
||||
self.is_start = is_start
|
||||
self.loop_state = loop_state if loop_state else {}
|
||||
|
||||
if self.output_json and self.output_pydantic:
|
||||
raise ValueError("Only one output type can be defined")
|
||||
|
||||
# Track previous tasks based on next_tasks relationships
|
||||
self.previous_tasks = []
|
||||
|
||||
def __str__(self):
|
||||
return f"Task(name='{self.name if self.name else 'None'}', description='{self.description}', agent='{self.agent.name if self.agent else 'None'}', status='{self.status}')"
|
||||
|
||||
async def execute_callback(self, task_output: TaskOutput) -> None:
|
||||
"""Execute the callback function, handling both sync and async callbacks"""
|
||||
if self.callback:
|
||||
if asyncio.iscoroutinefunction(self.callback):
|
||||
await self.callback(task_output)
|
||||
else:
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(None, self.callback, task_output)
|
||||
@@ -1,167 +0,0 @@
|
||||
"""Tools package for PraisonAI Agents"""
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
# Map of function names to their module and class (if any)
|
||||
TOOL_MAPPINGS = {
|
||||
# Direct functions
|
||||
'internet_search': ('.duckduckgo_tools', None),
|
||||
'duckduckgo': ('.duckduckgo_tools', None),
|
||||
|
||||
# Class methods from YFinance
|
||||
'get_stock_price': ('.yfinance_tools', 'YFinanceTools'),
|
||||
'get_stock_info': ('.yfinance_tools', 'YFinanceTools'),
|
||||
'get_historical_data': ('.yfinance_tools', 'YFinanceTools'),
|
||||
'yfinance': ('.yfinance_tools', 'YFinanceTools'),
|
||||
|
||||
# File Tools
|
||||
'read_file': ('.file_tools', 'FileTools'),
|
||||
'write_file': ('.file_tools', 'FileTools'),
|
||||
'list_files': ('.file_tools', 'FileTools'),
|
||||
'get_file_info': ('.file_tools', 'FileTools'),
|
||||
'copy_file': ('.file_tools', 'FileTools'),
|
||||
'move_file': ('.file_tools', 'FileTools'),
|
||||
'delete_file': ('.file_tools', 'FileTools'),
|
||||
'file_tools': ('.file_tools', 'FileTools'),
|
||||
|
||||
# CSV Tools
|
||||
'read_csv': ('.csv_tools', 'CSVTools'),
|
||||
'write_csv': ('.csv_tools', 'CSVTools'),
|
||||
'merge_csv': ('.csv_tools', 'CSVTools'),
|
||||
'analyze_csv': ('.csv_tools', 'CSVTools'),
|
||||
'split_csv': ('.csv_tools', 'CSVTools'),
|
||||
'csv_tools': ('.csv_tools', 'CSVTools'),
|
||||
|
||||
# JSON Tools
|
||||
'read_json': ('.json_tools', 'JSONTools'),
|
||||
'write_json': ('.json_tools', 'JSONTools'),
|
||||
'merge_json': ('.json_tools', 'JSONTools'),
|
||||
'validate_json': ('.json_tools', 'JSONTools'),
|
||||
'analyze_json': ('.json_tools', 'JSONTools'),
|
||||
'transform_json': ('.json_tools', 'JSONTools'),
|
||||
'json_tools': ('.json_tools', 'JSONTools'),
|
||||
|
||||
# Excel Tools
|
||||
'read_excel': ('.excel_tools', 'ExcelTools'),
|
||||
'write_excel': ('.excel_tools', 'ExcelTools'),
|
||||
'merge_excel': ('.excel_tools', 'ExcelTools'),
|
||||
'create_chart': ('.excel_tools', 'ExcelTools'),
|
||||
'add_chart_to_sheet': ('.excel_tools', 'ExcelTools'),
|
||||
'excel_tools': ('.excel_tools', 'ExcelTools'),
|
||||
|
||||
# XML Tools
|
||||
'read_xml': ('.xml_tools', 'XMLTools'),
|
||||
'write_xml': ('.xml_tools', 'XMLTools'),
|
||||
'transform_xml': ('.xml_tools', 'XMLTools'),
|
||||
'validate_xml': ('.xml_tools', 'XMLTools'),
|
||||
'xml_to_dict': ('.xml_tools', 'XMLTools'),
|
||||
'dict_to_xml': ('.xml_tools', 'XMLTools'),
|
||||
'xpath_query': ('.xml_tools', 'XMLTools'),
|
||||
'xml_tools': ('.xml_tools', 'XMLTools'),
|
||||
|
||||
# YAML Tools
|
||||
'read_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'write_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'merge_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'validate_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'analyze_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'transform_yaml': ('.yaml_tools', 'YAMLTools'),
|
||||
'yaml_tools': ('.yaml_tools', 'YAMLTools'),
|
||||
|
||||
# Calculator Tools
|
||||
'evaluate': ('.calculator_tools', 'CalculatorTools'),
|
||||
'solve_equation': ('.calculator_tools', 'CalculatorTools'),
|
||||
'convert_units': ('.calculator_tools', 'CalculatorTools'),
|
||||
'calculate_statistics': ('.calculator_tools', 'CalculatorTools'),
|
||||
'calculate_financial': ('.calculator_tools', 'CalculatorTools'),
|
||||
'calculator_tools': ('.calculator_tools', 'CalculatorTools'),
|
||||
|
||||
# Python Tools
|
||||
'execute_code': ('.python_tools', 'PythonTools'),
|
||||
'analyze_code': ('.python_tools', 'PythonTools'),
|
||||
'format_code': ('.python_tools', 'PythonTools'),
|
||||
'lint_code': ('.python_tools', 'PythonTools'),
|
||||
'disassemble_code': ('.python_tools', 'PythonTools'),
|
||||
'python_tools': ('.python_tools', 'PythonTools'),
|
||||
|
||||
# Pandas Tools
|
||||
'filter_data': ('.pandas_tools', 'PandasTools'),
|
||||
'get_summary': ('.pandas_tools', 'PandasTools'),
|
||||
'group_by': ('.pandas_tools', 'PandasTools'),
|
||||
'pivot_table': ('.pandas_tools', 'PandasTools'),
|
||||
'pandas_tools': ('.pandas_tools', 'PandasTools'),
|
||||
|
||||
# Wikipedia Tools
|
||||
'search': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'get_wikipedia_summary': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'get_wikipedia_page': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'get_random_wikipedia': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'set_wikipedia_language': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
'wikipedia_tools': ('.wikipedia_tools', 'WikipediaTools'),
|
||||
|
||||
# Newspaper Tools
|
||||
'get_article': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'get_news_sources': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'get_articles_from_source': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'get_trending_topics': ('.newspaper_tools', 'NewspaperTools'),
|
||||
'newspaper_tools': ('.newspaper_tools', 'NewspaperTools'),
|
||||
|
||||
# arXiv Tools
|
||||
'search_arxiv': ('.arxiv_tools', 'ArxivTools'),
|
||||
'get_arxiv_paper': ('.arxiv_tools', 'ArxivTools'),
|
||||
'get_papers_by_author': ('.arxiv_tools', 'ArxivTools'),
|
||||
'get_papers_by_category': ('.arxiv_tools', 'ArxivTools'),
|
||||
'arxiv_tools': ('.arxiv_tools', 'ArxivTools'),
|
||||
|
||||
# Spider Tools
|
||||
'scrape_page': ('.spider_tools', 'SpiderTools'),
|
||||
'extract_links': ('.spider_tools', 'SpiderTools'),
|
||||
'crawl': ('.spider_tools', 'SpiderTools'),
|
||||
'extract_text': ('.spider_tools', 'SpiderTools'),
|
||||
'spider_tools': ('.spider_tools', 'SpiderTools'),
|
||||
|
||||
# DuckDB Tools
|
||||
'query': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'create_table': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'load_data': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'export_data': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'get_table_info': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'analyze_data': ('.duckdb_tools', 'DuckDBTools'),
|
||||
'duckdb_tools': ('.duckdb_tools', 'DuckDBTools'),
|
||||
|
||||
# Shell Tools
|
||||
'execute_command': ('.shell_tools', 'ShellTools'),
|
||||
'list_processes': ('.shell_tools', 'ShellTools'),
|
||||
'kill_process': ('.shell_tools', 'ShellTools'),
|
||||
'get_system_info': ('.shell_tools', 'ShellTools'),
|
||||
'shell_tools': ('.shell_tools', 'ShellTools'),
|
||||
}
|
||||
|
||||
_instances = {} # Cache for class instances
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
"""Smart lazy loading of tools with class method support."""
|
||||
if name not in TOOL_MAPPINGS:
|
||||
raise AttributeError(f"module '{__package__}' has no attribute '{name}'")
|
||||
|
||||
module_path, class_name = TOOL_MAPPINGS[name]
|
||||
|
||||
if class_name is None:
|
||||
# Direct function import
|
||||
module = import_module(module_path, __package__)
|
||||
if name in ['duckduckgo', 'file_tools', 'pandas_tools', 'wikipedia_tools',
|
||||
'newspaper_tools', 'arxiv_tools', 'spider_tools', 'duckdb_tools', 'csv_tools', 'json_tools', 'excel_tools', 'xml_tools', 'yaml_tools', 'calculator_tools', 'python_tools', 'shell_tools']:
|
||||
return module # Returns the callable module
|
||||
return getattr(module, name)
|
||||
else:
|
||||
# Class method import
|
||||
if class_name not in _instances:
|
||||
module = import_module(module_path, __package__)
|
||||
class_ = getattr(module, class_name)
|
||||
_instances[class_name] = class_()
|
||||
|
||||
# Get the method and bind it to the instance
|
||||
method = getattr(_instances[class_name], name)
|
||||
return method
|
||||
|
||||
__all__ = list(TOOL_MAPPINGS.keys())
|
||||
@@ -1,16 +0,0 @@
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.25"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
authors = [
|
||||
{ name="Mervin Praison" }
|
||||
]
|
||||
dependencies = [
|
||||
"pydantic",
|
||||
"rich",
|
||||
"openai"
|
||||
]
|
||||
Generated
-321
@@ -1,321 +0,0 @@
|
||||
version = 1
|
||||
requires-python = ">=3.11"
|
||||
|
||||
[[package]]
|
||||
name = "annotated-types"
|
||||
version = "0.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyio"
|
||||
version = "4.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "idna" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f6/40/318e58f669b1a9e00f5c4453910682e2d9dd594334539c7b7817dabb765f/anyio-4.7.0.tar.gz", hash = "sha256:2f834749c602966b7d456a7567cafcb309f96482b5081d14ac93ccd457f9dd48", size = 177076 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/7a/4daaf3b6c08ad7ceffea4634ec206faeff697526421c20f07628c7372156/anyio-4.7.0-py3-none-any.whl", hash = "sha256:ea60c3723ab42ba6fff7e8ccb0488c898ec538ff4df1f1d5e642c3601d07e352", size = 93052 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2024.12.14"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/bd/1d41ee578ce09523c81a15426705dd20969f5abf006d1afe8aeff0dd776a/certifi-2024.12.14.tar.gz", hash = "sha256:b650d30f370c2b724812bee08008be0c4163b163ddaec3f2546c1caf65f191db", size = 166010 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/32/8f6669fc4798494966bf446c8c4a162e0b5d893dff088afddf76414f70e1/certifi-2024.12.14-py3-none-any.whl", hash = "sha256:1275f7a45be9464efc1173084eaa30f866fe2e47d389406136d332ed4967ec56", size = 164927 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colorama"
|
||||
version = "0.4.6"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "distro"
|
||||
version = "1.9.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h11"
|
||||
version = "0.14.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f5/38/3af3d3633a34a3316095b39c8e8fb4853a28a536e55d347bd8d8e9a14b03/h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d", size = 100418 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/95/04/ff642e65ad6b90db43e668d70ffb6736436c7ce41fcc549f4e9472234127/h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761", size = 58259 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httpcore"
|
||||
version = "1.0.7"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "certifi" },
|
||||
{ name = "h11" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6a/41/d7d0a89eb493922c37d343b607bc1b5da7f5be7e383740b4753ad8943e90/httpcore-1.0.7.tar.gz", hash = "sha256:8551cb62a169ec7162ac7be8d4817d561f60e08eaa485234898414bb5a8a0b4c", size = 85196 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/87/f5/72347bc88306acb359581ac4d52f23c0ef445b57157adedb9aee0cd689d2/httpcore-1.0.7-py3-none-any.whl", hash = "sha256:a3fff8f43dc260d5bd363d9f9cf1830fa3a458b332856f34282de498ed420edd", size = 78551 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httpx"
|
||||
version = "0.28.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "certifi" },
|
||||
{ name = "httpcore" },
|
||||
{ name = "idna" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "3.10"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiter"
|
||||
version = "0.8.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f8/70/90bc7bd3932e651486861df5c8ffea4ca7c77d28e8532ddefe2abc561a53/jiter-0.8.2.tar.gz", hash = "sha256:cd73d3e740666d0e639f678adb176fad25c1bcbdae88d8d7b857e1783bb4212d", size = 163007 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/b0/c1a7caa7f9dc5f1f6cfa08722867790fe2d3645d6e7170ca280e6e52d163/jiter-0.8.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:2dd61c5afc88a4fda7d8b2cf03ae5947c6ac7516d32b7a15bf4b49569a5c076b", size = 303666 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f5/97/0468bc9eeae43079aaa5feb9267964e496bf13133d469cfdc135498f8dd0/jiter-0.8.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a6c710d657c8d1d2adbbb5c0b0c6bfcec28fd35bd6b5f016395f9ac43e878a15", size = 311934 },
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/69/64058e18263d9a5f1e10f90c436853616d5f047d997c37c7b2df11b085ec/jiter-0.8.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a9584de0cd306072635fe4b89742bf26feae858a0683b399ad0c2509011b9dc0", size = 335506 },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/14/b747f9a77b8c0542141d77ca1e2a7523e854754af2c339ac89a8b66527d6/jiter-0.8.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5a90a923338531b7970abb063cfc087eebae6ef8ec8139762007188f6bc69a9f", size = 355849 },
|
||||
{ url = "https://files.pythonhosted.org/packages/53/e2/98a08161db7cc9d0e39bc385415890928ff09709034982f48eccfca40733/jiter-0.8.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d21974d246ed0181558087cd9f76e84e8321091ebfb3a93d4c341479a736f099", size = 381700 },
|
||||
{ url = "https://files.pythonhosted.org/packages/7a/38/1674672954d35bce3b1c9af99d5849f9256ac8f5b672e020ac7821581206/jiter-0.8.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:32475a42b2ea7b344069dc1e81445cfc00b9d0e3ca837f0523072432332e9f74", size = 389710 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/9b/92f9da9a9e107d019bcf883cd9125fa1690079f323f5a9d5c6986eeec3c0/jiter-0.8.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b9931fd36ee513c26b5bf08c940b0ac875de175341cbdd4fa3be109f0492586", size = 345553 },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/a6/6d030003394e9659cd0d7136bbeabd82e869849ceccddc34d40abbbbb269/jiter-0.8.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ce0820f4a3a59ddced7fce696d86a096d5cc48d32a4183483a17671a61edfddc", size = 376388 },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/8d/87b09e648e4aca5f9af89e3ab3cfb93db2d1e633b2f2931ede8dabd9b19a/jiter-0.8.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:8ffc86ae5e3e6a93765d49d1ab47b6075a9c978a2b3b80f0f32628f39caa0c88", size = 511226 },
|
||||
{ url = "https://files.pythonhosted.org/packages/77/95/8008ebe4cdc82eac1c97864a8042ca7e383ed67e0ec17bfd03797045c727/jiter-0.8.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:5127dc1abd809431172bc3fbe8168d6b90556a30bb10acd5ded41c3cfd6f43b6", size = 504134 },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/0d/3056a74de13e8b2562e4d526de6dac2f65d91ace63a8234deb9284a1d24d/jiter-0.8.2-cp311-cp311-win32.whl", hash = "sha256:66227a2c7b575720c1871c8800d3a0122bb8ee94edb43a5685aa9aceb2782d44", size = 203103 },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/1e/7f96b798f356e531ffc0f53dd2f37185fac60fae4d6c612bbbd4639b90aa/jiter-0.8.2-cp311-cp311-win_amd64.whl", hash = "sha256:cde031d8413842a1e7501e9129b8e676e62a657f8ec8166e18a70d94d4682855", size = 206717 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a1/17/c8747af8ea4e045f57d6cfd6fc180752cab9bc3de0e8a0c9ca4e8af333b1/jiter-0.8.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:e6ec2be506e7d6f9527dae9ff4b7f54e68ea44a0ef6b098256ddf895218a2f8f", size = 302027 },
|
||||
{ url = "https://files.pythonhosted.org/packages/3c/c1/6da849640cd35a41e91085723b76acc818d4b7d92b0b6e5111736ce1dd10/jiter-0.8.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:76e324da7b5da060287c54f2fabd3db5f76468006c811831f051942bf68c9d44", size = 310326 },
|
||||
{ url = "https://files.pythonhosted.org/packages/06/99/a2bf660d8ccffee9ad7ed46b4f860d2108a148d0ea36043fd16f4dc37e94/jiter-0.8.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:180a8aea058f7535d1c84183c0362c710f4750bef66630c05f40c93c2b152a0f", size = 334242 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a7/5f/cea1c17864828731f11427b9d1ab7f24764dbd9aaf4648a7f851164d2718/jiter-0.8.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:025337859077b41548bdcbabe38698bcd93cfe10b06ff66617a48ff92c9aec60", size = 356654 },
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/13/62774b7e5e7f5d5043efe1d0f94ead66e6d0f894ae010adb56b3f788de71/jiter-0.8.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ecff0dc14f409599bbcafa7e470c00b80f17abc14d1405d38ab02e4b42e55b57", size = 379967 },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/fb/096b34c553bb0bd3f2289d5013dcad6074948b8d55212aa13a10d44c5326/jiter-0.8.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ffd9fee7d0775ebaba131f7ca2e2d83839a62ad65e8e02fe2bd8fc975cedeb9e", size = 389252 },
|
||||
{ url = "https://files.pythonhosted.org/packages/17/61/beea645c0bf398ced8b199e377b61eb999d8e46e053bb285c91c3d3eaab0/jiter-0.8.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:14601dcac4889e0a1c75ccf6a0e4baf70dbc75041e51bcf8d0e9274519df6887", size = 345490 },
|
||||
{ url = "https://files.pythonhosted.org/packages/d5/df/834aa17ad5dcc3cf0118821da0a0cf1589ea7db9832589278553640366bc/jiter-0.8.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:92249669925bc1c54fcd2ec73f70f2c1d6a817928480ee1c65af5f6b81cdf12d", size = 376991 },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/80/87d140399d382fb4ea5b3d56e7ecaa4efdca17cd7411ff904c1517855314/jiter-0.8.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:e725edd0929fa79f8349ab4ec7f81c714df51dc4e991539a578e5018fa4a7152", size = 510822 },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/37/3394bb47bac1ad2cb0465601f86828a0518d07828a650722e55268cdb7e6/jiter-0.8.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bf55846c7b7a680eebaf9c3c48d630e1bf51bdf76c68a5f654b8524335b0ad29", size = 503730 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f9/e2/253fc1fa59103bb4e3aa0665d6ceb1818df1cd7bf3eb492c4dad229b1cd4/jiter-0.8.2-cp312-cp312-win32.whl", hash = "sha256:7efe4853ecd3d6110301665a5178b9856be7e2a9485f49d91aa4d737ad2ae49e", size = 203375 },
|
||||
{ url = "https://files.pythonhosted.org/packages/41/69/6d4bbe66b3b3b4507e47aa1dd5d075919ad242b4b1115b3f80eecd443687/jiter-0.8.2-cp312-cp312-win_amd64.whl", hash = "sha256:83c0efd80b29695058d0fd2fa8a556490dbce9804eac3e281f373bbc99045f6c", size = 204740 },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/b0/bfa1f6f2c956b948802ef5a021281978bf53b7a6ca54bb126fd88a5d014e/jiter-0.8.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:ca1f08b8e43dc3bd0594c992fb1fd2f7ce87f7bf0d44358198d6da8034afdf84", size = 301190 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a4/8f/396ddb4e292b5ea57e45ade5dc48229556b9044bad29a3b4b2dddeaedd52/jiter-0.8.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5672a86d55416ccd214c778efccf3266b84f87b89063b582167d803246354be4", size = 309334 },
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/68/805978f2f446fa6362ba0cc2e4489b945695940656edd844e110a61c98f8/jiter-0.8.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:58dc9bc9767a1101f4e5e22db1b652161a225874d66f0e5cb8e2c7d1c438b587", size = 333918 },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/99/0f71f7be667c33403fa9706e5b50583ae5106d96fab997fa7e2f38ee8347/jiter-0.8.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:37b2998606d6dadbb5ccda959a33d6a5e853252d921fec1792fc902351bb4e2c", size = 356057 },
|
||||
{ url = "https://files.pythonhosted.org/packages/8d/50/a82796e421a22b699ee4d2ce527e5bcb29471a2351cbdc931819d941a167/jiter-0.8.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4ab9a87f3784eb0e098f84a32670cfe4a79cb6512fd8f42ae3d0709f06405d18", size = 379790 },
|
||||
{ url = "https://files.pythonhosted.org/packages/3c/31/10fb012b00f6d83342ca9e2c9618869ab449f1aa78c8f1b2193a6b49647c/jiter-0.8.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:79aec8172b9e3c6d05fd4b219d5de1ac616bd8da934107325a6c0d0e866a21b6", size = 388285 },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/81/f15ebf7de57be488aa22944bf4274962aca8092e4f7817f92ffa50d3ee46/jiter-0.8.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:711e408732d4e9a0208008e5892c2966b485c783cd2d9a681f3eb147cf36c7ef", size = 344764 },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/e8/0cae550d72b48829ba653eb348cdc25f3f06f8a62363723702ec18e7be9c/jiter-0.8.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:653cf462db4e8c41995e33d865965e79641ef45369d8a11f54cd30888b7e6ff1", size = 376620 },
|
||||
{ url = "https://files.pythonhosted.org/packages/b8/50/e5478ff9d82534a944c03b63bc217c5f37019d4a34d288db0f079b13c10b/jiter-0.8.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:9c63eaef32b7bebac8ebebf4dabebdbc6769a09c127294db6babee38e9f405b9", size = 510402 },
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/1e/3de48bbebbc8f7025bd454cedc8c62378c0e32dd483dece5f4a814a5cb55/jiter-0.8.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:eb21aaa9a200d0a80dacc7a81038d2e476ffe473ffdd9c91eb745d623561de05", size = 503018 },
|
||||
{ url = "https://files.pythonhosted.org/packages/d5/cd/d5a5501d72a11fe3e5fd65c78c884e5164eefe80077680533919be22d3a3/jiter-0.8.2-cp313-cp313-win32.whl", hash = "sha256:789361ed945d8d42850f919342a8665d2dc79e7e44ca1c97cc786966a21f627a", size = 203190 },
|
||||
{ url = "https://files.pythonhosted.org/packages/51/bf/e5ca301245ba951447e3ad677a02a64a8845b185de2603dabd83e1e4b9c6/jiter-0.8.2-cp313-cp313-win_amd64.whl", hash = "sha256:ab7f43235d71e03b941c1630f4b6e3055d46b6cb8728a17663eaac9d8e83a865", size = 203551 },
|
||||
{ url = "https://files.pythonhosted.org/packages/2f/3c/71a491952c37b87d127790dd7a0b1ebea0514c6b6ad30085b16bbe00aee6/jiter-0.8.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:b426f72cd77da3fec300ed3bc990895e2dd6b49e3bfe6c438592a3ba660e41ca", size = 308347 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/4c/c02408042e6a7605ec063daed138e07b982fdb98467deaaf1c90950cf2c6/jiter-0.8.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b2dd880785088ff2ad21ffee205e58a8c1ddabc63612444ae41e5e4b321b39c0", size = 342875 },
|
||||
{ url = "https://files.pythonhosted.org/packages/91/61/c80ef80ed8a0a21158e289ef70dac01e351d929a1c30cb0f49be60772547/jiter-0.8.2-cp313-cp313t-win_amd64.whl", hash = "sha256:3ac9f578c46f22405ff7f8b1f5848fb753cc4b8377fbec8470a7dc3997ca7566", size = 202374 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "markdown-it-py"
|
||||
version = "3.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "mdurl" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mdurl"
|
||||
version = "0.1.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openai"
|
||||
version = "1.58.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "distro" },
|
||||
{ name = "httpx" },
|
||||
{ name = "jiter" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/27/3c/b1ecce430ed56fa3ac1b0676966d3250aab9c70a408232b71e419ea62148/openai-1.58.1.tar.gz", hash = "sha256:f5a035fd01e141fc743f4b0e02c41ca49be8fab0866d3b67f5f29b4f4d3c0973", size = 343411 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/5a/d22cd07f1a99b9e8b3c92ee0c1959188db4318828a3d88c9daac120bdd69/openai-1.58.1-py3-none-any.whl", hash = "sha256:e2910b1170a6b7f88ef491ac3a42c387f08bd3db533411f7ee391d166571d63c", size = 454279 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.25"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "openai" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "rich" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "openai" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "rich" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic"
|
||||
version = "2.10.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "annotated-types" },
|
||||
{ name = "pydantic-core" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/70/7e/fb60e6fee04d0ef8f15e4e01ff187a196fa976eb0f0ab524af4599e5754c/pydantic-2.10.4.tar.gz", hash = "sha256:82f12e9723da6de4fe2ba888b5971157b3be7ad914267dea8f05f82b28254f06", size = 762094 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f3/26/3e1bbe954fde7ee22a6e7d31582c642aad9e84ffe4b5fb61e63b87cd326f/pydantic-2.10.4-py3-none-any.whl", hash = "sha256:597e135ea68be3a37552fb524bc7d0d66dcf93d395acd93a00682f1efcb8ee3d", size = 431765 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic-core"
|
||||
version = "2.27.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fc/01/f3e5ac5e7c25833db5eb555f7b7ab24cd6f8c322d3a3ad2d67a952dc0abc/pydantic_core-2.27.2.tar.gz", hash = "sha256:eb026e5a4c1fee05726072337ff51d1efb6f59090b7da90d30ea58625b1ffb39", size = 413443 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c2/89/f3450af9d09d44eea1f2c369f49e8f181d742f28220f88cc4dfaae91ea6e/pydantic_core-2.27.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:8e10c99ef58cfdf2a66fc15d66b16c4a04f62bca39db589ae8cba08bc55331bc", size = 1893421 },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/e3/71fe85af2021f3f386da42d291412e5baf6ce7716bd7101ea49c810eda90/pydantic_core-2.27.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:26f32e0adf166a84d0cb63be85c562ca8a6fa8de28e5f0d92250c6b7e9e2aff7", size = 1814998 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/3c/724039e0d848fd69dbf5806894e26479577316c6f0f112bacaf67aa889ac/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8c19d1ea0673cd13cc2f872f6c9ab42acc4e4f492a7ca9d3795ce2b112dd7e15", size = 1826167 },
|
||||
{ url = "https://files.pythonhosted.org/packages/2b/5b/1b29e8c1fb5f3199a9a57c1452004ff39f494bbe9bdbe9a81e18172e40d3/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5e68c4446fe0810e959cdff46ab0a41ce2f2c86d227d96dc3847af0ba7def306", size = 1865071 },
|
||||
{ url = "https://files.pythonhosted.org/packages/89/6c/3985203863d76bb7d7266e36970d7e3b6385148c18a68cc8915fd8c84d57/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d9640b0059ff4f14d1f37321b94061c6db164fbe49b334b31643e0528d100d99", size = 2036244 },
|
||||
{ url = "https://files.pythonhosted.org/packages/0e/41/f15316858a246b5d723f7d7f599f79e37493b2e84bfc789e58d88c209f8a/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:40d02e7d45c9f8af700f3452f329ead92da4c5f4317ca9b896de7ce7199ea459", size = 2737470 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/7c/b860618c25678bbd6d1d99dbdfdf0510ccb50790099b963ff78a124b754f/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1c1fd185014191700554795c99b347d64f2bb637966c4cfc16998a0ca700d048", size = 1992291 },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/73/42c3742a391eccbeab39f15213ecda3104ae8682ba3c0c28069fbcb8c10d/pydantic_core-2.27.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d81d2068e1c1228a565af076598f9e7451712700b673de8f502f0334f281387d", size = 1994613 },
|
||||
{ url = "https://files.pythonhosted.org/packages/94/7a/941e89096d1175d56f59340f3a8ebaf20762fef222c298ea96d36a6328c5/pydantic_core-2.27.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:1a4207639fb02ec2dbb76227d7c751a20b1a6b4bc52850568e52260cae64ca3b", size = 2002355 },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/95/2359937a73d49e336a5a19848713555605d4d8d6940c3ec6c6c0ca4dcf25/pydantic_core-2.27.2-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:3de3ce3c9ddc8bbd88f6e0e304dea0e66d843ec9de1b0042b0911c1663ffd474", size = 2126661 },
|
||||
{ url = "https://files.pythonhosted.org/packages/2b/4c/ca02b7bdb6012a1adef21a50625b14f43ed4d11f1fc237f9d7490aa5078c/pydantic_core-2.27.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:30c5f68ded0c36466acede341551106821043e9afaad516adfb6e8fa80a4e6a6", size = 2153261 },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/9d/a241db83f973049a1092a079272ffe2e3e82e98561ef6214ab53fe53b1c7/pydantic_core-2.27.2-cp311-cp311-win32.whl", hash = "sha256:c70c26d2c99f78b125a3459f8afe1aed4d9687c24fd677c6a4436bc042e50d6c", size = 1812361 },
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/ef/013f07248041b74abd48a385e2110aa3a9bbfef0fbd97d4e6d07d2f5b89a/pydantic_core-2.27.2-cp311-cp311-win_amd64.whl", hash = "sha256:08e125dbdc505fa69ca7d9c499639ab6407cfa909214d500897d02afb816e7cc", size = 1982484 },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/1c/16b3a3e3398fd29dca77cea0a1d998d6bde3902fa2706985191e2313cc76/pydantic_core-2.27.2-cp311-cp311-win_arm64.whl", hash = "sha256:26f0d68d4b235a2bae0c3fc585c585b4ecc51382db0e3ba402a22cbc440915e4", size = 1867102 },
|
||||
{ url = "https://files.pythonhosted.org/packages/d6/74/51c8a5482ca447871c93e142d9d4a92ead74de6c8dc5e66733e22c9bba89/pydantic_core-2.27.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:9e0c8cfefa0ef83b4da9588448b6d8d2a2bf1a53c3f1ae5fca39eb3061e2f0b0", size = 1893127 },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/f3/c97e80721735868313c58b89d2de85fa80fe8dfeeed84dc51598b92a135e/pydantic_core-2.27.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:83097677b8e3bd7eaa6775720ec8e0405f1575015a463285a92bfdfe254529ef", size = 1811340 },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/91/840ec1375e686dbae1bd80a9e46c26a1e0083e1186abc610efa3d9a36180/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:172fce187655fece0c90d90a678424b013f8fbb0ca8b036ac266749c09438cb7", size = 1822900 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f6/31/4240bc96025035500c18adc149aa6ffdf1a0062a4b525c932065ceb4d868/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:519f29f5213271eeeeb3093f662ba2fd512b91c5f188f3bb7b27bc5973816934", size = 1869177 },
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/20/02fbaadb7808be578317015c462655c317a77a7c8f0ef274bc016a784c54/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:05e3a55d124407fffba0dd6b0c0cd056d10e983ceb4e5dbd10dda135c31071d6", size = 2038046 },
|
||||
{ url = "https://files.pythonhosted.org/packages/06/86/7f306b904e6c9eccf0668248b3f272090e49c275bc488a7b88b0823444a4/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9c3ed807c7b91de05e63930188f19e921d1fe90de6b4f5cd43ee7fcc3525cb8c", size = 2685386 },
|
||||
{ url = "https://files.pythonhosted.org/packages/8d/f0/49129b27c43396581a635d8710dae54a791b17dfc50c70164866bbf865e3/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6fb4aadc0b9a0c063206846d603b92030eb6f03069151a625667f982887153e2", size = 1997060 },
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/0f/943b4af7cd416c477fd40b187036c4f89b416a33d3cc0ab7b82708a667aa/pydantic_core-2.27.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:28ccb213807e037460326424ceb8b5245acb88f32f3d2777427476e1b32c48c4", size = 2004870 },
|
||||
{ url = "https://files.pythonhosted.org/packages/35/40/aea70b5b1a63911c53a4c8117c0a828d6790483f858041f47bab0b779f44/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:de3cd1899e2c279b140adde9357c4495ed9d47131b4a4eaff9052f23398076b3", size = 1999822 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/b3/807b94fd337d58effc5498fd1a7a4d9d59af4133e83e32ae39a96fddec9d/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:220f892729375e2d736b97d0e51466252ad84c51857d4d15f5e9692f9ef12be4", size = 2130364 },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/df/791c827cd4ee6efd59248dca9369fb35e80a9484462c33c6649a8d02b565/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a0fcd29cd6b4e74fe8ddd2c90330fd8edf2e30cb52acda47f06dd615ae72da57", size = 2158303 },
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/67/4e197c300976af185b7cef4c02203e175fb127e414125916bf1128b639a9/pydantic_core-2.27.2-cp312-cp312-win32.whl", hash = "sha256:1e2cb691ed9834cd6a8be61228471d0a503731abfb42f82458ff27be7b2186fc", size = 1834064 },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/ea/cd7209a889163b8dcca139fe32b9687dd05249161a3edda62860430457a5/pydantic_core-2.27.2-cp312-cp312-win_amd64.whl", hash = "sha256:cc3f1a99a4f4f9dd1de4fe0312c114e740b5ddead65bb4102884b384c15d8bc9", size = 1989046 },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/49/c54baab2f4658c26ac633d798dab66b4c3a9bbf47cff5284e9c182f4137a/pydantic_core-2.27.2-cp312-cp312-win_arm64.whl", hash = "sha256:3911ac9284cd8a1792d3cb26a2da18f3ca26c6908cc434a18f730dc0db7bfa3b", size = 1885092 },
|
||||
{ url = "https://files.pythonhosted.org/packages/41/b1/9bc383f48f8002f99104e3acff6cba1231b29ef76cfa45d1506a5cad1f84/pydantic_core-2.27.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:7d14bd329640e63852364c306f4d23eb744e0f8193148d4044dd3dacdaacbd8b", size = 1892709 },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/6c/e62b8657b834f3eb2961b49ec8e301eb99946245e70bf42c8817350cbefc/pydantic_core-2.27.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:82f91663004eb8ed30ff478d77c4d1179b3563df6cdb15c0817cd1cdaf34d154", size = 1811273 },
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/15/52cfe49c8c986e081b863b102d6b859d9defc63446b642ccbbb3742bf371/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71b24c7d61131bb83df10cc7e687433609963a944ccf45190cfc21e0887b08c9", size = 1823027 },
|
||||
{ url = "https://files.pythonhosted.org/packages/b1/1c/b6f402cfc18ec0024120602bdbcebc7bdd5b856528c013bd4d13865ca473/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fa8e459d4954f608fa26116118bb67f56b93b209c39b008277ace29937453dc9", size = 1868888 },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/7b/8cb75b66ac37bc2975a3b7de99f3c6f355fcc4d89820b61dffa8f1e81677/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ce8918cbebc8da707ba805b7fd0b382816858728ae7fe19a942080c24e5b7cd1", size = 2037738 },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/f1/786d8fe78970a06f61df22cba58e365ce304bf9b9f46cc71c8c424e0c334/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eda3f5c2a021bbc5d976107bb302e0131351c2ba54343f8a496dc8783d3d3a6a", size = 2685138 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/74/d12b2cd841d8724dc8ffb13fc5cef86566a53ed358103150209ecd5d1999/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd8086fa684c4775c27f03f062cbb9eaa6e17f064307e86b21b9e0abc9c0f02e", size = 1997025 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/6e/940bcd631bc4d9a06c9539b51f070b66e8f370ed0933f392db6ff350d873/pydantic_core-2.27.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8d9b3388db186ba0c099a6d20f0604a44eabdeef1777ddd94786cdae158729e4", size = 2004633 },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/cc/a46b34f1708d82498c227d5d80ce615b2dd502ddcfd8376fc14a36655af1/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:7a66efda2387de898c8f38c0cf7f14fca0b51a8ef0b24bfea5849f1b3c95af27", size = 1999404 },
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/2d/c365cfa930ed23bc58c41463bae347d1005537dc8db79e998af8ba28d35e/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:18a101c168e4e092ab40dbc2503bdc0f62010e95d292b27827871dc85450d7ee", size = 2130130 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f4/d7/eb64d015c350b7cdb371145b54d96c919d4db516817f31cd1c650cae3b21/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ba5dd002f88b78a4215ed2f8ddbdf85e8513382820ba15ad5ad8955ce0ca19a1", size = 2157946 },
|
||||
{ url = "https://files.pythonhosted.org/packages/a4/99/bddde3ddde76c03b65dfd5a66ab436c4e58ffc42927d4ff1198ffbf96f5f/pydantic_core-2.27.2-cp313-cp313-win32.whl", hash = "sha256:1ebaf1d0481914d004a573394f4be3a7616334be70261007e47c2a6fe7e50130", size = 1834387 },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/47/82b5e846e01b26ac6f1893d3c5f9f3a2eb6ba79be26eef0b759b4fe72946/pydantic_core-2.27.2-cp313-cp313-win_amd64.whl", hash = "sha256:953101387ecf2f5652883208769a79e48db18c6df442568a0b5ccd8c2723abee", size = 1990453 },
|
||||
{ url = "https://files.pythonhosted.org/packages/51/b2/b2b50d5ecf21acf870190ae5d093602d95f66c9c31f9d5de6062eb329ad1/pydantic_core-2.27.2-cp313-cp313-win_arm64.whl", hash = "sha256:ac4dbfd1691affb8f48c2c13241a2e3b60ff23247cbcf981759c768b6633cf8b", size = 1885186 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pygments"
|
||||
version = "2.18.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8e/62/8336eff65bcbc8e4cb5d05b55faf041285951b6e80f33e2bff2024788f31/pygments-2.18.0.tar.gz", hash = "sha256:786ff802f32e91311bff3889f6e9a86e81505fe99f2735bb6d60ae0c5004f199", size = 4891905 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/3f/01c8b82017c199075f8f788d0d906b9ffbbc5a47dc9918a945e13d5a2bda/pygments-2.18.0-py3-none-any.whl", hash = "sha256:b8e6aca0523f3ab76fee51799c488e38782ac06eafcf95e7ba832985c8e7b13a", size = 1205513 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rich"
|
||||
version = "13.9.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "markdown-it-py" },
|
||||
{ name = "pygments" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ab/3a/0316b28d0761c6734d6bc14e770d85506c986c85ffb239e688eeaab2c2bc/rich-13.9.4.tar.gz", hash = "sha256:439594978a49a09530cff7ebc4b5c7103ef57baf48d5ea3184f21d9a2befa098", size = 223149 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/19/71/39c7c0d87f8d4e6c020a393182060eaefeeae6c01dab6a84ec346f2567df/rich-13.9.4-py3-none-any.whl", hash = "sha256:6049d5e6ec054bf2779ab3358186963bac2ea89175919d699e378b99738c2a90", size = 242424 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tqdm"
|
||||
version = "4.67.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a8/4b/29b4ef32e036bb34e4ab51796dd745cdba7ed47ad142a9f4a1eb8e0c744d/tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2", size = 169737 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typing-extensions"
|
||||
version = "4.12.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/df/db/f35a00659bc03fec321ba8bce9420de607a1d37f8342eee1863174c69557/typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8", size = 85321 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/26/9f/ad63fc0248c5379346306f8668cda6e2e2e9c95e01216d2b8ffd9ff037d0/typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d", size = 37438 },
|
||||
]
|
||||
@@ -1,21 +0,0 @@
|
||||
services:
|
||||
ui:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.ui
|
||||
volumes:
|
||||
- .:/app
|
||||
ports:
|
||||
- "8082:8082"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
CHAINLIT_PORT: "8082"
|
||||
CHAINLIT_HOST: "0.0.0.0"
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
CHAINLIT_AUTH_SECRET: ${CHAINLIT_AUTH_SECRET}
|
||||
command: praisonai ui --host 0.0.0.0
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8082"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
@@ -0,0 +1,53 @@
|
||||
# PraisonAI Docker Environment Configuration
|
||||
# Copy this file to .env and update with your values
|
||||
|
||||
# Required: OpenAI API Key
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
|
||||
# Required: Chainlit Authentication Secret (generate a random string)
|
||||
CHAINLIT_AUTH_SECRET=your_chainlit_secret_here
|
||||
|
||||
# Optional: Additional API Keys
|
||||
ANTHROPIC_API_KEY=your_anthropic_api_key_here
|
||||
GOOGLE_API_KEY=your_google_api_key_here
|
||||
GROQ_API_KEY=your_groq_api_key_here
|
||||
COHERE_API_KEY=your_cohere_api_key_here
|
||||
|
||||
# Optional: Service Configuration
|
||||
FLASK_ENV=development
|
||||
CHAINLIT_HOST=0.0.0.0
|
||||
|
||||
# Optional: Port Configuration (modify if you have conflicts)
|
||||
UI_PORT=8082
|
||||
CHAT_PORT=8083
|
||||
API_PORT=8080
|
||||
|
||||
# Optional: Database Configuration
|
||||
DATABASE_URL=sqlite:///root/.praison/database.sqlite
|
||||
|
||||
# Optional: Logging Configuration
|
||||
LOG_LEVEL=INFO
|
||||
PYTHONPATH=/app
|
||||
|
||||
# Optional: Development Settings
|
||||
DEV_MODE=false
|
||||
DEBUG=false
|
||||
|
||||
# Optional: Model Configuration
|
||||
DEFAULT_MODEL=gpt-4
|
||||
DEFAULT_TEMPERATURE=0.7
|
||||
MAX_TOKENS=4000
|
||||
|
||||
# Optional: Security Settings
|
||||
CORS_ORIGINS=http://localhost:3000,http://localhost:8082,http://localhost:8083
|
||||
RATE_LIMIT=100
|
||||
|
||||
# Optional: Feature Flags
|
||||
ENABLE_CHAT=true
|
||||
ENABLE_UI=true
|
||||
ENABLE_API=true
|
||||
ENABLE_REALTIME=true
|
||||
|
||||
# Optional: Volume Paths (for custom mounting)
|
||||
PRAISON_DATA_PATH=~/.praison
|
||||
EXAMPLES_PATH=./examples
|
||||
@@ -0,0 +1,45 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
python3-dev \
|
||||
curl \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Create praison config directory
|
||||
RUN mkdir -p /root/.praison
|
||||
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
flask \
|
||||
"praisonai>=2.2.22" \
|
||||
"praisonai[api]" \
|
||||
gunicorn \
|
||||
markdown
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Set environment variables for directory management
|
||||
ENV PRAISON_CONFIG_DIR=/root/.praison
|
||||
ENV DOCKER_CONTAINER=true
|
||||
|
||||
# Create health check API if api.py doesn't exist
|
||||
RUN if [ ! -f api.py ]; then \
|
||||
echo "from flask import Flask\n\
|
||||
app = Flask(__name__)\n\
|
||||
\n\
|
||||
@app.route('/health')\n\
|
||||
def health():\n\
|
||||
return {'status': 'healthy'}, 200\n\
|
||||
\n\
|
||||
if __name__ == '__main__':\n\
|
||||
app.run()" > api.py; \
|
||||
fi
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
|
||||
@@ -7,18 +7,27 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
python3-dev \
|
||||
curl \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python packages
|
||||
# Create praison config directory
|
||||
RUN mkdir -p /root/.praison
|
||||
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonaiagents>=0.0.4 \
|
||||
praisonai_tools \
|
||||
"praisonai==2.0.18" \
|
||||
"praisonai>=2.2.22" \
|
||||
"praisonai[chat]" \
|
||||
"embedchain[github,youtube]"
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Set environment variables for directory management
|
||||
ENV PRAISON_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_DB_DIR=/root/.praison
|
||||
ENV DOCKER_CONTAINER=true
|
||||
|
||||
# Default command (will be overridden by docker-compose)
|
||||
CMD ["praisonai", "chat"]
|
||||
@@ -0,0 +1,47 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
python3-dev \
|
||||
portaudio19-dev \
|
||||
python3-pyaudio \
|
||||
curl \
|
||||
git \
|
||||
vim \
|
||||
nano \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Create praison config directory
|
||||
RUN mkdir -p /root/.praison
|
||||
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.2.22" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[chat]" \
|
||||
"praisonai[realtime]" \
|
||||
"praisonai[code]" \
|
||||
"embedchain[github,youtube]" \
|
||||
jupyter \
|
||||
jupyterlab \
|
||||
notebook \
|
||||
pytest \
|
||||
pytest-asyncio \
|
||||
mkdocs \
|
||||
mkdocs-material
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Set environment variables for directory management
|
||||
ENV PRAISON_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_DB_DIR=/root/.praison
|
||||
ENV DOCKER_CONTAINER=true
|
||||
|
||||
# Default command (will be overridden by docker-compose)
|
||||
CMD ["praisonai", "ui"]
|
||||
@@ -0,0 +1,32 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
python3-dev \
|
||||
curl \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Create praison config directory
|
||||
RUN mkdir -p /root/.praison
|
||||
|
||||
# Copy praisonaiagents source
|
||||
COPY src/praisonai-agents/ /app/praisonaiagents/
|
||||
WORKDIR /app/praisonaiagents
|
||||
|
||||
# Install praisonaiagents with all features (non-editable for production)
|
||||
RUN pip install --no-cache-dir ".[all]"
|
||||
|
||||
# Set environment variables for directory management
|
||||
ENV PRAISON_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_DB_DIR=/root/.praison
|
||||
ENV DOCKER_CONTAINER=true
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Default command
|
||||
CMD ["python", "-c", "import praisonaiagents; print('PraisonAI Agents installed successfully')"]
|
||||
@@ -7,18 +7,27 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
python3-dev \
|
||||
curl \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python packages
|
||||
# Create praison config directory
|
||||
RUN mkdir -p /root/.praison
|
||||
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonaiagents>=0.0.4 \
|
||||
praisonai_tools \
|
||||
"praisonai==2.0.18" \
|
||||
"praisonai>=2.2.22" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[crewai]"
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Set environment variables for directory management
|
||||
ENV PRAISON_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_CONFIG_DIR=/root/.praison
|
||||
ENV CHAINLIT_DB_DIR=/root/.praison
|
||||
ENV DOCKER_CONTAINER=true
|
||||
|
||||
# Default command (will be overridden by docker-compose)
|
||||
CMD ["praisonai", "ui"]
|
||||
@@ -0,0 +1,265 @@
|
||||
# PraisonAI Docker Setup
|
||||
|
||||
This directory contains Docker configurations for running PraisonAI services in containerized environments. The setup addresses directory management issues and provides comprehensive multi-service deployment options.
|
||||
|
||||
## 🐳 Available Services
|
||||
|
||||
### Core Services
|
||||
- **UI Service** (`port 8082`) - Chainlit-based web interface
|
||||
- **Chat Service** (`port 8083`) - Dedicated chat interface
|
||||
- **API Service** (`port 8080`) - REST API endpoint
|
||||
- **Agents Service** - Standalone PraisonAI Agents runtime
|
||||
|
||||
### Docker Files
|
||||
- `Dockerfile` - Basic API service
|
||||
- `Dockerfile.ui` - UI service with web interface
|
||||
- `Dockerfile.chat` - Chat-focused service
|
||||
- `Dockerfile.dev` - Development environment with tools
|
||||
- `Dockerfile.praisonaiagents` - Standalone agents framework
|
||||
- `docker-compose.yml` - Multi-service orchestration
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Single Service
|
||||
```bash
|
||||
# Run UI service
|
||||
docker run -p 8082:8082 -e OPENAI_API_KEY=your_key ghcr.io/mervinpraison/praisonai:ui
|
||||
|
||||
# Run Chat service
|
||||
docker run -p 8083:8083 -e OPENAI_API_KEY=your_key ghcr.io/mervinpraison/praisonai:chat
|
||||
|
||||
# Run API service
|
||||
docker run -p 8080:8080 -e OPENAI_API_KEY=your_key ghcr.io/mervinpraison/praisonai:api
|
||||
```
|
||||
|
||||
### Multi-Service with Docker Compose
|
||||
```bash
|
||||
# Create environment file
|
||||
cat > .env << EOF
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
CHAINLIT_AUTH_SECRET=your_secret_here
|
||||
EOF
|
||||
|
||||
# Start all services
|
||||
docker-compose up -d
|
||||
|
||||
# View logs
|
||||
docker-compose logs -f
|
||||
|
||||
# Stop services
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
## 📁 Directory Management
|
||||
|
||||
### Problem Solved
|
||||
The original issue was that files like `chainlit.md`, `.chainlit` directory, and `public` folder were cluttering the root directory.
|
||||
|
||||
### Solution Implemented
|
||||
All PraisonAI configuration and runtime files are now stored in `~/.praison/`:
|
||||
|
||||
```bash
|
||||
~/.praison/
|
||||
├── database.sqlite # Chainlit database
|
||||
├── chainlit.md # Chainlit configuration
|
||||
├── .chainlit/ # Chainlit runtime files
|
||||
└── config/ # PraisonAI configuration
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
```bash
|
||||
PRAISON_CONFIG_DIR=/root/.praison # Main config directory
|
||||
CHAINLIT_CONFIG_DIR=/root/.praison # Chainlit config location
|
||||
CHAINLIT_DB_DIR=/root/.praison # Database location
|
||||
```
|
||||
|
||||
## 🔧 Service Configuration
|
||||
|
||||
### UI Service (Port 8082)
|
||||
```yaml
|
||||
environment:
|
||||
- CHAINLIT_PORT=8082
|
||||
- CHAINLIT_HOST=0.0.0.0
|
||||
- OPENAI_API_KEY=${OPENAI_API_KEY}
|
||||
- CHAINLIT_AUTH_SECRET=${CHAINLIT_AUTH_SECRET}
|
||||
```
|
||||
|
||||
### Chat Service (Port 8083)
|
||||
```yaml
|
||||
environment:
|
||||
- CHAINLIT_PORT=8083
|
||||
- CHAINLIT_HOST=0.0.0.0
|
||||
- OPENAI_API_KEY=${OPENAI_API_KEY}
|
||||
```
|
||||
|
||||
### API Service (Port 8080)
|
||||
```yaml
|
||||
environment:
|
||||
- OPENAI_API_KEY=${OPENAI_API_KEY}
|
||||
```
|
||||
|
||||
## 🎯 Service Endpoints
|
||||
|
||||
| Service | Port | Endpoint | Description |
|
||||
|---------|------|----------|-------------|
|
||||
| UI | 8082 | http://localhost:8082 | Web interface |
|
||||
| Chat | 8083 | http://localhost:8083 | Chat interface |
|
||||
| API | 8080 | http://localhost:8080 | REST API |
|
||||
| API Health | 8080 | http://localhost:8080/health | Health check |
|
||||
|
||||
## 🔍 Health Checks
|
||||
|
||||
All services include health checks:
|
||||
```yaml
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:PORT"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
```
|
||||
|
||||
## 📦 Package Versions
|
||||
|
||||
All Docker images use consistent, up-to-date versions:
|
||||
- PraisonAI: `>=2.2.22`
|
||||
- PraisonAI Agents: `>=0.0.92`
|
||||
- Python: `3.11-slim`
|
||||
|
||||
## 🔒 Security Features
|
||||
|
||||
- Non-root user execution where possible
|
||||
- Minimal base image (python:3.11-slim)
|
||||
- No unnecessary packages installed
|
||||
- Environment variable-based configuration
|
||||
- Volume mounting for persistent data
|
||||
|
||||
## 🛠 Development
|
||||
|
||||
### Development Environment
|
||||
```bash
|
||||
# Use development Dockerfile with additional tools
|
||||
docker build -f Dockerfile.dev -t praisonai:dev .
|
||||
docker run -it -v $(pwd):/app praisonai:dev bash
|
||||
```
|
||||
|
||||
### Custom Configuration
|
||||
```bash
|
||||
# Mount custom config directory
|
||||
docker run -v ~/.praison:/root/.praison praisonai:ui
|
||||
```
|
||||
|
||||
## 📊 Monitoring
|
||||
|
||||
### Docker Compose Monitoring
|
||||
```bash
|
||||
# View service status
|
||||
docker-compose ps
|
||||
|
||||
# View resource usage
|
||||
docker-compose top
|
||||
|
||||
# View logs for specific service
|
||||
docker-compose logs ui
|
||||
docker-compose logs chat
|
||||
docker-compose logs api
|
||||
```
|
||||
|
||||
## 🚨 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Port conflicts**
|
||||
```bash
|
||||
# Check port usage
|
||||
netstat -tlnp | grep :8082
|
||||
|
||||
# Use different ports
|
||||
docker run -p 9082:8082 praisonai:ui
|
||||
```
|
||||
|
||||
2. **Environment variables not loading**
|
||||
```bash
|
||||
# Verify .env file
|
||||
cat .env
|
||||
|
||||
# Set variables directly
|
||||
docker run -e OPENAI_API_KEY=your_key praisonai:ui
|
||||
```
|
||||
|
||||
3. **Permission issues**
|
||||
```bash
|
||||
# Check volume permissions
|
||||
ls -la ~/.praison/
|
||||
|
||||
# Fix permissions
|
||||
sudo chown -R $(id -u):$(id -g) ~/.praison/
|
||||
```
|
||||
|
||||
4. **Service won't start**
|
||||
```bash
|
||||
# Check logs
|
||||
docker-compose logs service_name
|
||||
|
||||
# Restart service
|
||||
docker-compose restart service_name
|
||||
```
|
||||
|
||||
## 🔄 Updates
|
||||
|
||||
### Pulling Latest Images
|
||||
```bash
|
||||
# Pull latest images
|
||||
docker-compose pull
|
||||
|
||||
# Restart with new images
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
### Version Pinning
|
||||
To use specific versions, update the Dockerfile:
|
||||
```dockerfile
|
||||
RUN pip install "praisonai==2.2.22" "praisonaiagents==0.0.92"
|
||||
```
|
||||
|
||||
## 🌐 Production Deployment
|
||||
|
||||
### Recommended Production Setup
|
||||
```yaml
|
||||
# docker-compose.prod.yml
|
||||
version: '3.8'
|
||||
services:
|
||||
ui:
|
||||
image: ghcr.io/mervinpraison/praisonai:ui
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- CHAINLIT_HOST=0.0.0.0
|
||||
- CHAINLIT_PORT=8082
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
networks:
|
||||
- praison_network
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 1G
|
||||
reservations:
|
||||
memory: 512M
|
||||
```
|
||||
|
||||
### Load Balancer Configuration
|
||||
For production environments, consider using nginx or similar:
|
||||
```nginx
|
||||
upstream praisonai {
|
||||
server localhost:8082;
|
||||
server localhost:8083;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
location / {
|
||||
proxy_pass http://praisonai;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This Docker setup provides a clean, organized, and scalable way to deploy PraisonAI services while solving the directory management issues mentioned in the original request.
|
||||
@@ -0,0 +1,184 @@
|
||||
version: '3.8'
|
||||
|
||||
# Development Docker Compose Configuration
|
||||
# Extends the main docker-compose.yml with development-specific settings
|
||||
|
||||
services:
|
||||
# Development UI Service with hot reload
|
||||
ui-dev:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- ../src:/app/src:rw
|
||||
- ../examples:/app/examples:rw
|
||||
- ../docs:/app/docs:ro
|
||||
ports:
|
||||
- "${UI_PORT:-8082}:8082"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
CHAINLIT_PORT: "8082"
|
||||
CHAINLIT_HOST: "0.0.0.0"
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
CHAINLIT_AUTH_SECRET: ${CHAINLIT_AUTH_SECRET}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_DB_DIR: /root/.praison
|
||||
DEBUG: "true"
|
||||
DEV_MODE: "true"
|
||||
PYTHONPATH: /app/src
|
||||
command: praisonai ui --host 0.0.0.0 --reload
|
||||
networks:
|
||||
- praison_network
|
||||
depends_on:
|
||||
- database
|
||||
|
||||
# Development Chat Service
|
||||
chat-dev:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- ../src:/app/src:rw
|
||||
- ../examples:/app/examples:rw
|
||||
ports:
|
||||
- "${CHAT_PORT:-8083}:8083"
|
||||
environment:
|
||||
CHAINLIT_PORT: "8083"
|
||||
CHAINLIT_HOST: "0.0.0.0"
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
CHAINLIT_AUTH_SECRET: ${CHAINLIT_AUTH_SECRET}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_DB_DIR: /root/.praison
|
||||
DEBUG: "true"
|
||||
DEV_MODE: "true"
|
||||
PYTHONPATH: /app/src
|
||||
command: praisonai chat --host 0.0.0.0 --port 8083 --reload
|
||||
networks:
|
||||
- praison_network
|
||||
depends_on:
|
||||
- database
|
||||
|
||||
# Development API Service with hot reload
|
||||
api-dev:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- ../src:/app/src:rw
|
||||
- ../examples:/app/examples:rw
|
||||
ports:
|
||||
- "${API_PORT:-8080}:8080"
|
||||
environment:
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
FLASK_ENV: development
|
||||
DEBUG: "true"
|
||||
DEV_MODE: "true"
|
||||
PYTHONPATH: /app/src
|
||||
command: python -m flask --app api run --host 0.0.0.0 --port 8080 --debug
|
||||
networks:
|
||||
- praison_network
|
||||
depends_on:
|
||||
- database
|
||||
|
||||
# Development Jupyter Notebook Service
|
||||
jupyter:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- ../src:/app/src:rw
|
||||
- ../examples:/app/examples:rw
|
||||
- ../docs:/app/docs:rw
|
||||
ports:
|
||||
- "8888:8888"
|
||||
environment:
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
JUPYTER_ENABLE_LAB: "yes"
|
||||
PYTHONPATH: /app/src
|
||||
command: jupyter lab --ip=0.0.0.0 --port=8888 --no-browser --allow-root --LabApp.token='' --LabApp.password=''
|
||||
networks:
|
||||
- praison_network
|
||||
|
||||
# Development Testing Service
|
||||
test:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
volumes:
|
||||
- ../src:/app/src:rw
|
||||
- ../tests:/app/tests:rw
|
||||
- praison_data:/root/.praison
|
||||
environment:
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
PYTHONPATH: /app/src
|
||||
PYTEST_CURRENT_TEST: "true"
|
||||
command: python -m pytest tests/ -v
|
||||
networks:
|
||||
- praison_network
|
||||
profiles:
|
||||
- test
|
||||
|
||||
# Standalone database for development
|
||||
database:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_DB: praisonai_dev
|
||||
POSTGRES_USER: praisonai
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-praisonai_dev_pass}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
networks:
|
||||
- praison_network
|
||||
profiles:
|
||||
- database
|
||||
|
||||
# Redis for caching and session management
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
ports:
|
||||
- "6379:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
networks:
|
||||
- praison_network
|
||||
profiles:
|
||||
- cache
|
||||
|
||||
# Development documentation server
|
||||
docs:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
volumes:
|
||||
- ../docs:/app/docs:rw
|
||||
- ../README.md:/app/README.md:ro
|
||||
ports:
|
||||
- "8000:8000"
|
||||
command: sh -c "cd docs && mkdocs serve --dev-addr 0.0.0.0:8000"
|
||||
networks:
|
||||
- praison_network
|
||||
profiles:
|
||||
- docs
|
||||
|
||||
volumes:
|
||||
praison_data:
|
||||
driver: local
|
||||
postgres_data:
|
||||
driver: local
|
||||
redis_data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
praison_network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,99 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
# PraisonAI UI Service
|
||||
ui:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.ui
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- .:/app
|
||||
ports:
|
||||
- "8082:8082"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
CHAINLIT_PORT: "8082"
|
||||
CHAINLIT_HOST: "0.0.0.0"
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
CHAINLIT_AUTH_SECRET: ${CHAINLIT_AUTH_SECRET}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_DB_DIR: /root/.praison
|
||||
command: praisonai ui --host 0.0.0.0
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8082"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
networks:
|
||||
- praison_network
|
||||
|
||||
# PraisonAI Chat Service
|
||||
chat:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.chat
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- .:/app
|
||||
ports:
|
||||
- "8083:8083"
|
||||
environment:
|
||||
CHAINLIT_PORT: "8083"
|
||||
CHAINLIT_HOST: "0.0.0.0"
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
CHAINLIT_AUTH_SECRET: ${CHAINLIT_AUTH_SECRET}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_CONFIG_DIR: /root/.praison
|
||||
CHAINLIT_DB_DIR: /root/.praison
|
||||
command: praisonai chat --host 0.0.0.0 --port 8083
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8083"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
networks:
|
||||
- praison_network
|
||||
|
||||
# PraisonAI API Service
|
||||
api:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
networks:
|
||||
- praison_network
|
||||
|
||||
# PraisonAI Agents Service (standalone)
|
||||
agents:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.praisonaiagents
|
||||
volumes:
|
||||
- praison_data:/root/.praison
|
||||
- ./examples:/app/examples
|
||||
environment:
|
||||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||||
PRAISON_CONFIG_DIR: /root/.praison
|
||||
networks:
|
||||
- praison_network
|
||||
|
||||
volumes:
|
||||
praison_data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
praison_network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,289 @@
|
||||
#!/bin/bash
|
||||
|
||||
# PraisonAI Docker Quick Start Script
|
||||
# This script helps users quickly get started with PraisonAI using Docker
|
||||
|
||||
set -e
|
||||
|
||||
# Colors for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Function to print colored output
|
||||
print_status() {
|
||||
echo -e "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
print_success() {
|
||||
echo -e "${GREEN}[SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
print_warning() {
|
||||
echo -e "${YELLOW}[WARNING]${NC} $1"
|
||||
}
|
||||
|
||||
print_error() {
|
||||
echo -e "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
# Check if Docker is installed
|
||||
check_docker() {
|
||||
if ! command -v docker &> /dev/null; then
|
||||
print_error "Docker is not installed. Please install Docker first:"
|
||||
echo " - Visit: https://docs.docker.com/get-docker/"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
|
||||
print_error "Docker Compose is not available. Please install Docker Compose:"
|
||||
echo " - Visit: https://docs.docker.com/compose/install/"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
print_success "Docker and Docker Compose are available"
|
||||
}
|
||||
|
||||
# Check if .env file exists, create from template if not
|
||||
setup_environment() {
|
||||
if [ ! -f ".env" ]; then
|
||||
print_status "Creating .env file from template..."
|
||||
if [ -f ".env.template" ]; then
|
||||
cp .env.template .env
|
||||
else
|
||||
cat > .env << EOF
|
||||
# PraisonAI Docker Environment Configuration
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
CHAINLIT_AUTH_SECRET=$(openssl rand -hex 32 2>/dev/null || echo "your_chainlit_secret_here")
|
||||
FLASK_ENV=development
|
||||
CHAINLIT_HOST=0.0.0.0
|
||||
UI_PORT=8082
|
||||
CHAT_PORT=8083
|
||||
API_PORT=8080
|
||||
EOF
|
||||
fi
|
||||
print_warning "Please edit .env file and add your API keys before continuing"
|
||||
print_status "Required: OPENAI_API_KEY"
|
||||
read -p "Press Enter to continue after updating .env file..."
|
||||
else
|
||||
print_success ".env file already exists"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to show menu
|
||||
show_menu() {
|
||||
echo ""
|
||||
echo "=== PraisonAI Docker Quick Start ==="
|
||||
echo ""
|
||||
echo "1) Start UI Service (Web Interface) - Port 8082"
|
||||
echo "2) Start Chat Service - Port 8083"
|
||||
echo "3) Start API Service - Port 8080"
|
||||
echo "4) Start All Services (Recommended)"
|
||||
echo "5) Start Development Environment"
|
||||
echo "6) View Service Status"
|
||||
echo "7) View Logs"
|
||||
echo "8) Stop All Services"
|
||||
echo "9) Pull Latest Images"
|
||||
echo "10) Clean Up (Remove containers and volumes)"
|
||||
echo "11) Show Service URLs"
|
||||
echo "0) Exit"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Start specific service
|
||||
start_service() {
|
||||
local service=$1
|
||||
print_status "Starting $service service..."
|
||||
docker-compose up -d $service
|
||||
print_success "$service service started"
|
||||
}
|
||||
|
||||
# Start all services
|
||||
start_all_services() {
|
||||
print_status "Starting all PraisonAI services..."
|
||||
docker-compose up -d
|
||||
print_success "All services started"
|
||||
show_service_urls
|
||||
}
|
||||
|
||||
# Start development environment
|
||||
start_dev_environment() {
|
||||
print_status "Starting development environment..."
|
||||
if [ -f "docker-compose.dev.yml" ]; then
|
||||
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d ui-dev chat-dev api-dev
|
||||
print_success "Development environment started"
|
||||
echo ""
|
||||
echo "Development services available:"
|
||||
echo " - UI (with hot reload): http://localhost:${UI_PORT:-8082}"
|
||||
echo " - Chat (with hot reload): http://localhost:${CHAT_PORT:-8083}"
|
||||
echo " - API (with hot reload): http://localhost:${API_PORT:-8080}"
|
||||
echo " - Jupyter Lab: http://localhost:8888"
|
||||
echo ""
|
||||
else
|
||||
print_warning "Development configuration not found, starting regular services"
|
||||
start_all_services
|
||||
fi
|
||||
}
|
||||
|
||||
# Show service status
|
||||
show_status() {
|
||||
print_status "Service Status:"
|
||||
docker-compose ps
|
||||
}
|
||||
|
||||
# Show logs
|
||||
show_logs() {
|
||||
echo ""
|
||||
echo "Which service logs would you like to view?"
|
||||
echo "1) All services"
|
||||
echo "2) UI service"
|
||||
echo "3) Chat service"
|
||||
echo "4) API service"
|
||||
echo "5) Agents service"
|
||||
read -p "Enter choice (1-5): " log_choice
|
||||
|
||||
case $log_choice in
|
||||
1) docker-compose logs -f ;;
|
||||
2) docker-compose logs -f ui ;;
|
||||
3) docker-compose logs -f chat ;;
|
||||
4) docker-compose logs -f api ;;
|
||||
5) docker-compose logs -f agents ;;
|
||||
*) print_error "Invalid choice" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Stop all services
|
||||
stop_services() {
|
||||
print_status "Stopping all services..."
|
||||
docker-compose down
|
||||
print_success "All services stopped"
|
||||
}
|
||||
|
||||
# Pull latest images
|
||||
pull_images() {
|
||||
print_status "Pulling latest images..."
|
||||
docker-compose pull
|
||||
print_success "Images updated"
|
||||
}
|
||||
|
||||
# Clean up
|
||||
cleanup() {
|
||||
print_warning "This will remove all containers, networks, and volumes"
|
||||
read -p "Are you sure? (y/N): " confirm
|
||||
if [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]]; then
|
||||
print_status "Cleaning up..."
|
||||
docker-compose down -v --remove-orphans
|
||||
docker system prune -f
|
||||
print_success "Cleanup completed"
|
||||
fi
|
||||
}
|
||||
|
||||
# Show service URLs
|
||||
show_service_urls() {
|
||||
local ui_port=${UI_PORT:-8082}
|
||||
local chat_port=${CHAT_PORT:-8083}
|
||||
local api_port=${API_PORT:-8080}
|
||||
|
||||
echo ""
|
||||
echo "=== Service URLs ==="
|
||||
echo "UI Service: http://localhost:$ui_port"
|
||||
echo "Chat Service: http://localhost:$chat_port"
|
||||
echo "API Service: http://localhost:$api_port"
|
||||
echo "API Health: http://localhost:$api_port/health"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Check system requirements
|
||||
check_requirements() {
|
||||
print_status "Checking system requirements..."
|
||||
|
||||
# Check available memory
|
||||
if command -v free &> /dev/null; then
|
||||
available_ram=$(free -m | awk 'NR==2{printf "%.1f", $7/1024}')
|
||||
print_status "Available RAM: ${available_ram}GB"
|
||||
if (( $(echo "$available_ram < 2.0" | bc -l 2>/dev/null || echo "1") )); then
|
||||
print_warning "Low available memory. Recommended: 2GB+ available RAM"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check disk space
|
||||
if command -v df &> /dev/null; then
|
||||
available_space=$(df -BG . | awk 'NR==2{print $4}' | sed 's/G//')
|
||||
print_status "Available disk space: ${available_space}GB"
|
||||
if [ "$available_space" -lt 5 ]; then
|
||||
print_warning "Low disk space. Recommended: 5GB+ available space"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
clear
|
||||
echo "🤖 Welcome to PraisonAI Docker Setup!"
|
||||
echo ""
|
||||
|
||||
# Check prerequisites
|
||||
check_docker
|
||||
check_requirements
|
||||
setup_environment
|
||||
|
||||
# Main loop
|
||||
while true; do
|
||||
show_menu
|
||||
read -p "Enter your choice (0-11): " choice
|
||||
|
||||
case $choice in
|
||||
1)
|
||||
start_service "ui"
|
||||
echo "UI Service: http://localhost:${UI_PORT:-8082}"
|
||||
;;
|
||||
2)
|
||||
start_service "chat"
|
||||
echo "Chat Service: http://localhost:${CHAT_PORT:-8083}"
|
||||
;;
|
||||
3)
|
||||
start_service "api"
|
||||
echo "API Service: http://localhost:${API_PORT:-8080}"
|
||||
;;
|
||||
4)
|
||||
start_all_services
|
||||
;;
|
||||
5)
|
||||
start_dev_environment
|
||||
;;
|
||||
6)
|
||||
show_status
|
||||
;;
|
||||
7)
|
||||
show_logs
|
||||
;;
|
||||
8)
|
||||
stop_services
|
||||
;;
|
||||
9)
|
||||
pull_images
|
||||
;;
|
||||
10)
|
||||
cleanup
|
||||
;;
|
||||
11)
|
||||
show_service_urls
|
||||
;;
|
||||
0)
|
||||
print_success "Thank you for using PraisonAI!"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
print_error "Invalid choice. Please try again."
|
||||
;;
|
||||
esac
|
||||
|
||||
echo ""
|
||||
read -p "Press Enter to continue..."
|
||||
done
|
||||
}
|
||||
|
||||
# Run main function
|
||||
main
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: "AI Agents"
|
||||
description: "Overview of all available PraisonAI agents and their capabilities"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
PraisonAI provides a diverse set of specialized agents for various tasks. Each agent is designed with specific capabilities and tools to handle different types of tasks effectively.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Define the main flow
|
||||
Start([▶ Start]) --> Agent1
|
||||
Agent1 --> Process[⚙ Process]
|
||||
Process --> Agent2
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
end
|
||||
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
end
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Start,Output,Task1,Task2 input
|
||||
class Process,AgentIcon1,AgentIcon2 process
|
||||
class Tools1,Tools2 tools
|
||||
class Agent1,Agent2 transparent
|
||||
```
|
||||
|
||||
## Data & Analysis
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Data Analyst" icon="chart-line" href="/agents/data-analyst">
|
||||
Analyze data from various sources, create visualizations, and generate insights.
|
||||
</Card>
|
||||
<Card title="Finance" icon="money-bill-trend-up" href="/agents/finance">
|
||||
Track stocks, analyze financial data, and provide investment recommendations.
|
||||
</Card>
|
||||
<Card title="Research" icon="magnifying-glass-chart" href="/agents/research">
|
||||
Conduct comprehensive research and analysis across various topics.
|
||||
</Card>
|
||||
<Card title="Wikipedia" icon="book" href="/agents/wikipedia">
|
||||
Search and extract information from Wikipedia articles.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Media & Content
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Image Analysis" icon="image" href="/agents/image">
|
||||
Analyze and understand visual content from images.
|
||||
</Card>
|
||||
<Card title="Image to Text" icon="text" href="/agents/image-to-text">
|
||||
Convert images to textual descriptions and extract text content.
|
||||
</Card>
|
||||
<Card title="Video" icon="video" href="/agents/video">
|
||||
Analyze video content and extract meaningful information.
|
||||
</Card>
|
||||
<Card title="Markdown" icon="markdown" href="/agents/markdown">
|
||||
Generate and format content in Markdown syntax.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Search & Recommendations
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Web Search" icon="globe" href="/agents/websearch">
|
||||
Perform intelligent web searches and gather information.
|
||||
</Card>
|
||||
<Card title="Recommendation" icon="thumbs-up" href="/agents/recommendation">
|
||||
Generate personalized recommendations based on preferences.
|
||||
</Card>
|
||||
<Card title="Shopping" icon="shop" href="/agents/shopping">
|
||||
Compare prices and find the best deals across stores.
|
||||
</Card>
|
||||
<Card title="Planning" icon="calendar" href="/agents/planning">
|
||||
Create travel plans and detailed itineraries.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Development
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Programming" icon="code" href="/agents/programming">
|
||||
Write, analyze, and debug code across multiple languages.
|
||||
</Card>
|
||||
<Card title="Single Agent" icon="circle-1" href="/agents/single">
|
||||
Simple, focused agent for basic tasks without external tools.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Getting Started
|
||||
|
||||
Each agent can be easily initialized and customized for your specific needs. Here's a basic example:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create an agent with specific instructions
|
||||
agent = Agent(instructions="Your task-specific instructions")
|
||||
|
||||
# Start the agent with a task
|
||||
response = agent.start("Your task description")
|
||||
```
|
||||
|
||||
For more detailed information about each agent, click on the respective cards above.
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: "Data Analyst Agent"
|
||||
sidebarTitle: "Data Analyst"
|
||||
description: "Learn how to create AI agents for data analysis and insights generation."
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Data Source] --> Reader[Data Reader]
|
||||
Reader --> Analyzer[Data Analyzer]
|
||||
Analyzer --> Generator[Insights Generator]
|
||||
Generator --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Reader fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Data Analyst Agent can read data from various sources, analyze it, and generate insights.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `data_analysis.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import (
|
||||
read_csv, read_excel, write_csv, write_excel,
|
||||
filter_data, get_summary, group_by, pivot_table
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Data Analyst Agent",
|
||||
tools=[
|
||||
read_csv, read_excel, write_csv, write_excel,
|
||||
filter_data, get_summary, group_by, pivot_table
|
||||
]
|
||||
)
|
||||
|
||||
# Start analysis with a specific task
|
||||
agent.start(f"""
|
||||
Read the data from the csv file {os.path.join(os.path.dirname(__file__), "tesla-stock-price.csv")}
|
||||
Analyse the data and give me the insights
|
||||
read_csv to read the file
|
||||
""")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Data Analysis Workflow
|
||||
|
||||
The Data Analyst Agent is designed to perform comprehensive data analysis tasks using a suite of specialized tools. Here's how it works:
|
||||
|
||||
1. **Data Reading**: The agent can read data from various sources:
|
||||
- CSV files using `read_csv`
|
||||
- Excel files using `read_excel`
|
||||
|
||||
2. **Data Analysis**: Multiple analysis tools are available:
|
||||
- `filter_data`: Filter datasets based on conditions
|
||||
- `get_summary`: Generate statistical summaries
|
||||
- `group_by`: Group data by specific columns
|
||||
- `pivot_table`: Create pivot tables for analysis
|
||||
|
||||
3. **Data Export**: Results can be exported to:
|
||||
- CSV format using `write_csv`
|
||||
- Excel format using `write_excel`
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Multiple Data Sources" icon="table">
|
||||
Support for both CSV and Excel file formats.
|
||||
</Card>
|
||||
<Card title="Analysis Tools" icon="calculator">
|
||||
Comprehensive suite of analysis tools including filtering, summarization, and pivoting.
|
||||
</Card>
|
||||
<Card title="Data Export" icon="file-export">
|
||||
Export capabilities to various formats.
|
||||
</Card>
|
||||
<Card title="Automated Insights" icon="lightbulb">
|
||||
Automatic generation of data insights and patterns.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyzing stock data
|
||||
agent.start("""
|
||||
1. Read 'stock_data.csv'
|
||||
2. Filter data for the last 30 days
|
||||
3. Calculate daily returns
|
||||
4. Generate summary statistics
|
||||
5. Export results to 'analysis_results.xlsx'
|
||||
""")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex analysis workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
|
||||
- Check out other specialized agents like the [Finance Agent](/agents/finance) for specific use cases
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: "Finance Agent"
|
||||
sidebarTitle: "Finance"
|
||||
description: "Learn how to create AI agents for financial analysis and investment recommendations."
|
||||
icon: "money-bill-trend-up"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Request] --> Price[Stock Price]
|
||||
Price --> Info[Stock Info]
|
||||
Info --> History[Historical Data]
|
||||
History --> Out[Investment Advice]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Price fill:#2E8B57,color:#fff
|
||||
style Info fill:#2E8B57,color:#fff
|
||||
style History fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Finance Agent can analyze stock market data and provide investment recommendations.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `finance_analysis.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import get_stock_price, get_stock_info, get_historical_data
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Research Agent",
|
||||
tools=[get_stock_price, get_stock_info, get_historical_data]
|
||||
)
|
||||
agent.start("Understand current stock price and historical data of Apple and Google. Tell me if I can invest in them")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Financial Analysis
|
||||
|
||||
The Finance Agent specializes in stock market analysis and investment recommendations using three key components:
|
||||
|
||||
1. **Real-time Price Data**: Uses `get_stock_price` to fetch current market prices
|
||||
2. **Company Information**: Retrieves company details using `get_stock_info`
|
||||
3. **Historical Analysis**: Analyzes trends with `get_historical_data`
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Real-time Data" icon="clock">
|
||||
Access to current stock market prices and information.
|
||||
</Card>
|
||||
<Card title="Company Analysis" icon="building">
|
||||
Detailed company information and fundamentals.
|
||||
</Card>
|
||||
<Card title="Historical Trends" icon="chart-line">
|
||||
Analysis of historical price movements and patterns.
|
||||
</Card>
|
||||
<Card title="Investment Advice" icon="money-bill">
|
||||
AI-powered investment recommendations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyzing specific stocks
|
||||
agent.start("""
|
||||
1. Get current prices for AAPL and GOOGL
|
||||
2. Retrieve company information
|
||||
3. Analyze 6-month historical data
|
||||
4. Provide investment recommendations
|
||||
""")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex financial analysis
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
|
||||
- Check out the [Data Analyst Agent](/agents/data-analyst) for detailed data analysis capabilities
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
title: "Image to Text Agent"
|
||||
sidebarTitle: "Image to Text"
|
||||
description: "Learn how to create AI agents for converting images to textual descriptions and extracting text from images."
|
||||
icon: "text"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Image Input] --> OCR[Text Extractor]
|
||||
OCR --> Analyzer[Content Analyzer]
|
||||
Analyzer --> Generator[Description Generator]
|
||||
Generator --> Out[Text Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style OCR fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Image-to-Text Agent can extract text from images and generate comprehensive descriptions.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `image_to_text.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Image-to-Text Agent
|
||||
image_text_agent = Agent(
|
||||
name="ImageTextConverter",
|
||||
role="Image Text Extraction Specialist",
|
||||
goal="Convert image content to textual descriptions and extract text",
|
||||
backstory="""You are an expert in OCR and image understanding.
|
||||
You excel at extracting text from images and generating detailed descriptions.""",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create text extraction task
|
||||
extraction_task = Task(
|
||||
name="extract_text",
|
||||
description="Extract all text from this image and describe its layout.",
|
||||
expected_output="Extracted text and layout description",
|
||||
agent=image_text_agent,
|
||||
images=["document.jpg"]
|
||||
)
|
||||
|
||||
# Create description task
|
||||
description_task = Task(
|
||||
name="generate_description",
|
||||
description="Generate a detailed description of the image content.",
|
||||
expected_output="Comprehensive description of visual elements",
|
||||
agent=image_text_agent,
|
||||
images=["scene.jpg"]
|
||||
)
|
||||
|
||||
# Create PraisonAIAgents instance
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_text_agent],
|
||||
tasks=[extraction_task, description_task],
|
||||
process="sequential",
|
||||
verbose=1
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Image-to-Text Conversion
|
||||
|
||||
The Image-to-Text Agent combines multiple capabilities to convert visual content into textual form:
|
||||
|
||||
1. **OCR Processing**: Extracts text from images using optical character recognition
|
||||
2. **Layout Analysis**: Understands the spatial arrangement of text and visual elements
|
||||
3. **Content Description**: Generates natural language descriptions of image content
|
||||
4. **Text Formatting**: Preserves text formatting and structure where possible
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Text Extraction" icon="text">
|
||||
Advanced OCR capabilities for text extraction.
|
||||
</Card>
|
||||
<Card title="Layout Understanding" icon="table-layout">
|
||||
Analysis of text and content layout.
|
||||
</Card>
|
||||
<Card title="Content Description" icon="pen-to-square">
|
||||
Detailed descriptions of visual content.
|
||||
</Card>
|
||||
<Card title="Format Preservation" icon="paragraph">
|
||||
Maintains text formatting and structure.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Processing a document image
|
||||
document_task = Task(
|
||||
name="process_document",
|
||||
description="Extract text and analyze document layout",
|
||||
expected_output="Extracted text with layout information",
|
||||
agent=image_text_agent,
|
||||
images=["business_document.jpg"]
|
||||
)
|
||||
|
||||
# Run single task
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_text_agent],
|
||||
tasks=[document_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex document processing
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving text extraction accuracy
|
||||
- Check out the [Image Agent](/agents/image) for pure image analysis capabilities
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: "Image Analysis Agent"
|
||||
sidebarTitle: "Image Analysis"
|
||||
description: "Learn how to create AI agents for image analysis and visual content understanding."
|
||||
icon: "image"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Image Input] --> Analyzer[Image Analyzer]
|
||||
Analyzer --> Detector[Object Detector]
|
||||
Detector --> Generator[Description Generator]
|
||||
Generator --> Out[Analysis Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Detector fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Image Analysis Agent can process and analyze visual content, detect objects, and generate detailed descriptions.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `image_analysis.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Image Analysis Agent
|
||||
image_agent = Agent(
|
||||
name="ImageAnalyst",
|
||||
role="Image Analysis Specialist",
|
||||
goal="Analyze images and videos to extract meaningful information",
|
||||
backstory="""You are an expert in computer vision and image analysis.
|
||||
You excel at describing images, detecting objects, and understanding visual content.""",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create tasks for different types of analysis
|
||||
task1 = Task(
|
||||
name="analyze_landmark",
|
||||
description="Describe this famous landmark and its architectural features.",
|
||||
expected_output="Detailed description of the landmark's architecture and significance",
|
||||
agent=image_agent,
|
||||
images=["https://example.com/landmark.jpg"]
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="analyze_local_image",
|
||||
description="What objects can you see in this image? Describe their arrangement.",
|
||||
expected_output="Detailed description of objects and their spatial relationships",
|
||||
agent=image_agent,
|
||||
images=["local_image.jpg"]
|
||||
)
|
||||
|
||||
# Create PraisonAIAgents instance
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_agent],
|
||||
tasks=[task1, task2],
|
||||
process="sequential",
|
||||
verbose=1
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Image Analysis
|
||||
|
||||
The Image Analysis Agent is designed to process and understand visual content through several key capabilities:
|
||||
|
||||
1. **Image Input**: Supports both URL and local file inputs
|
||||
2. **Object Detection**: Identifies and locates objects within images
|
||||
3. **Architectural Analysis**: Specialized in analyzing architectural features
|
||||
4. **Spatial Understanding**: Describes spatial relationships between objects
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Multiple Input Sources" icon="images">
|
||||
Support for both URL and local image files.
|
||||
</Card>
|
||||
<Card title="Object Detection" icon="magnifying-glass">
|
||||
Advanced object detection and recognition.
|
||||
</Card>
|
||||
<Card title="Architectural Analysis" icon="building">
|
||||
Specialized analysis of architectural features.
|
||||
</Card>
|
||||
<Card title="Detailed Descriptions" icon="pen">
|
||||
Generation of comprehensive visual descriptions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyzing a landmark image
|
||||
landmark_task = Task(
|
||||
name="analyze_famous_landmark",
|
||||
description="Analyze this historical landmark",
|
||||
expected_output="Architectural details and historical significance",
|
||||
agent=image_agent,
|
||||
images=["https://example.com/landmark.jpg"]
|
||||
)
|
||||
|
||||
# Run single task
|
||||
agents = PraisonAIAgents(
|
||||
agents=[image_agent],
|
||||
tasks=[landmark_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex image analysis workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
|
||||
- Check out the [Video Agent](/agents/video) for video content analysis
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: "Markdown Agent"
|
||||
sidebarTitle: "Markdown"
|
||||
description: "Learn how to create AI agents for generating and formatting content in Markdown."
|
||||
icon: "markdown"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Content Request] --> Generator[Content Generator]
|
||||
Generator --> Formatter[Markdown Formatter]
|
||||
Formatter --> Validator[Format Validator]
|
||||
Validator --> Out[Markdown Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Formatter fill:#2E8B57,color:#fff
|
||||
style Validator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Markdown Agent can generate and format content in Markdown syntax.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `markdown_generator.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create Markdown Agent
|
||||
markdown_agent = Agent(
|
||||
name="MarkdownWriter",
|
||||
role="Markdown Content Specialist",
|
||||
goal="Generate well-formatted content in Markdown syntax",
|
||||
instructions="You are a Markdown Agent, output in markdown format",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Generate content
|
||||
response = markdown_agent.start(
|
||||
"Write a blog post about artificial intelligence"
|
||||
)
|
||||
|
||||
# Save to file
|
||||
with open('blog_post.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Markdown Generation
|
||||
|
||||
The Markdown Agent specializes in creating properly formatted Markdown content:
|
||||
|
||||
1. **Content Generation**: Creates original content based on prompts
|
||||
2. **Markdown Formatting**: Applies proper Markdown syntax
|
||||
3. **Structure Validation**: Ensures correct formatting
|
||||
4. **Document Organization**: Creates well-structured documents
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Content Creation" icon="pen-to-square">
|
||||
Generates original, well-structured content.
|
||||
</Card>
|
||||
<Card title="Markdown Syntax" icon="code">
|
||||
Proper implementation of Markdown formatting.
|
||||
</Card>
|
||||
<Card title="Document Structure" icon="sitemap">
|
||||
Organized document hierarchy and sections.
|
||||
</Card>
|
||||
<Card title="Format Validation" icon="check">
|
||||
Ensures correct Markdown syntax usage.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Generate a technical documentation
|
||||
agent = Agent(
|
||||
instructions="You are a Markdown Agent, output in markdown format"
|
||||
)
|
||||
|
||||
# Generate API documentation
|
||||
response = agent.start("""
|
||||
Create technical documentation for a REST API with:
|
||||
- Introduction
|
||||
- Authentication
|
||||
- Endpoints
|
||||
- Examples
|
||||
""")
|
||||
|
||||
# Save documentation
|
||||
with open('api_docs.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex document generation
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving content quality
|
||||
- Check out the [Documentation Agent](/agents/documentation) for specialized documentation generation
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "Planning Agent"
|
||||
sidebarTitle: "Planning"
|
||||
description: "Learn how to create AI agents for trip planning and itinerary generation."
|
||||
icon: "calendar"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Request] --> Search[Web Search]
|
||||
Search --> Analyzer[Options Analyzer]
|
||||
Analyzer --> Generator[Plan Generator]
|
||||
Generator --> Out[Itinerary]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Planning Agent can search for travel options and create detailed itineraries.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `travel_planner.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Planning Agent
|
||||
planning_agent = Agent(
|
||||
name="TravelPlanner",
|
||||
role="Travel Planning Specialist",
|
||||
goal="Create comprehensive travel plans and itineraries",
|
||||
instructions="You are a Planning Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Generate travel plan
|
||||
response = planning_agent.start(
|
||||
"I want to go to London next week, find me a good hotel and flight"
|
||||
)
|
||||
|
||||
# Save plan
|
||||
with open('travel_plan.txt', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Travel Planning
|
||||
|
||||
The Planning Agent combines multiple capabilities to create comprehensive travel plans:
|
||||
|
||||
1. **Web Search**: Uses DuckDuckGo to find current travel options
|
||||
2. **Options Analysis**: Evaluates and compares different choices
|
||||
3. **Plan Generation**: Creates detailed itineraries
|
||||
4. **Recommendations**: Provides personalized suggestions
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Flight Search" icon="plane">
|
||||
Finds and compares flight options.
|
||||
</Card>
|
||||
<Card title="Hotel Booking" icon="hotel">
|
||||
Recommends suitable accommodations.
|
||||
</Card>
|
||||
<Card title="Itinerary Creation" icon="calendar-days">
|
||||
Generates detailed travel schedules.
|
||||
</Card>
|
||||
<Card title="Real-time Data" icon="clock">
|
||||
Uses current pricing and availability.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Create a weekend trip plan
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Planning Agent", tools=[duckduckgo])
|
||||
agent.start("I want to go London next week, find me a good hotel and flight")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex travel planning
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendations
|
||||
- Check out the [Research Agent](/agents/research) for detailed destination research
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
title: "Programming Agent"
|
||||
sidebarTitle: "Programming"
|
||||
description: "Learn how to create AI agents for code development, analysis, and execution."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Code Request] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Generator[Code Generator]
|
||||
Generator --> Executor[Code Executor]
|
||||
Executor --> Debugger[Code Debugger]
|
||||
Debugger --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Executor fill:#2E8B57,color:#fff
|
||||
style Debugger fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Programming Agent can analyze, generate, execute, and debug code.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `code_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import execute_code, analyze_code, format_code, lint_code, disassemble_code # Code Tools
|
||||
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info # Shell Tools
|
||||
from praisonaiagents.tools import duckduckgo # Web Search Tool
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Programming Agent", self_reflect=True, min_reflect=5, max_reflect=10,
|
||||
tools=[execute_code, analyze_code, format_code, lint_code, disassemble_code, execute_command, list_processes, kill_process, get_system_info, duckduckgo]
|
||||
)
|
||||
agent.start(
|
||||
"Write a python script using yfinance to find the stock price of Tesla"
|
||||
"First check if required packages are installed"
|
||||
"Run it using execute_code"
|
||||
"execute_command if you want to run any terminal command"
|
||||
"search internet using duckduckgo if you want to know update python package information"
|
||||
"Analyse the output using analyze_code and fix error if required"
|
||||
"if no package is installed, install it"
|
||||
"then run the code"
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Code Development
|
||||
|
||||
The Programming Agent combines multiple tools for comprehensive code development:
|
||||
|
||||
1. **Code Tools**:
|
||||
- `execute_code`: Run Python code
|
||||
- `analyze_code`: Analyze code structure
|
||||
- `format_code`: Format code to standards
|
||||
- `lint_code`: Check code quality
|
||||
- `disassemble_code`: View bytecode
|
||||
|
||||
2. **Shell Tools**:
|
||||
- `execute_command`: Run terminal commands
|
||||
- `list_processes`: View running processes
|
||||
- `kill_process`: Terminate processes
|
||||
- `get_system_info`: System information
|
||||
|
||||
3. **Web Tools**:
|
||||
- `duckduckgo`: Search for programming resources
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Code Execution" icon="play">
|
||||
Run and test code directly.
|
||||
</Card>
|
||||
<Card title="Code Analysis" icon="magnifying-glass-code">
|
||||
Analyze and improve code quality.
|
||||
</Card>
|
||||
<Card title="System Integration" icon="terminal">
|
||||
Execute system commands and manage processes.
|
||||
</Card>
|
||||
<Card title="Package Management" icon="box">
|
||||
Handle dependencies and installations.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Create and run a data analysis script
|
||||
response = agent.start("""
|
||||
1. Create a script that:
|
||||
- Uses pandas for data analysis
|
||||
- Reads a CSV file
|
||||
- Performs basic statistics
|
||||
- Creates a visualization
|
||||
2. Check and install required packages
|
||||
3. Execute and analyze the results
|
||||
""")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex development workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving code quality
|
||||
- Check out the [Data Analyst Agent](/agents/data-analyst) for specialized data analysis
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "Recommendation Agent"
|
||||
sidebarTitle: "Recommendation"
|
||||
description: "Learn how to create AI agents for personalized recommendations across various domains."
|
||||
icon: "thumbs-up"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[User Preferences] --> Search[Content Search]
|
||||
Search --> Analyzer[Preference Analyzer]
|
||||
Analyzer --> Generator[Recommendation Generator]
|
||||
Generator --> Out[Recommendations]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Recommendation Agent can analyze preferences and generate personalized recommendations.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `recommendation_system.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Recommendation Agent
|
||||
recommendation_agent = Agent(
|
||||
name="RecommendationEngine",
|
||||
role="Recommendation Specialist",
|
||||
goal="Generate personalized recommendations based on preferences",
|
||||
instructions="You are a Recommendation Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Get recommendations
|
||||
response = recommendation_agent.start(
|
||||
"Recommend me a good movie to watch in 2025"
|
||||
)
|
||||
|
||||
# Save recommendations
|
||||
with open('recommendations.txt', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Recommendation System
|
||||
|
||||
The Recommendation Agent uses multiple approaches to generate personalized suggestions:
|
||||
|
||||
1. **Content Search**: Uses DuckDuckGo to find current options
|
||||
2. **Preference Analysis**: Understands user preferences
|
||||
3. **Recommendation Generation**: Creates personalized suggestions
|
||||
4. **Content Filtering**: Filters based on relevance and quality
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Personalization" icon="user">
|
||||
Tailored recommendations based on preferences.
|
||||
</Card>
|
||||
<Card title="Real-time Data" icon="clock">
|
||||
Up-to-date content and information.
|
||||
</Card>
|
||||
<Card title="Multi-domain" icon="layer-group">
|
||||
Recommendations across various categories.
|
||||
</Card>
|
||||
<Card title="Content Filtering" icon="filter">
|
||||
Quality-based content selection.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Get personalized recommendations
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Recommendation Agent", tools=[duckduckgo])
|
||||
agent.start("Recommend me a good movie to watch in 2025")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex recommendation systems
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
|
||||
- Check out the [Research Agent](/agents/research) for detailed content research
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
title: "Research Agent"
|
||||
sidebarTitle: "Research"
|
||||
description: "Learn how to create AI agents for conducting comprehensive research and analysis."
|
||||
icon: "magnifying-glass-chart"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Research Query] --> Search[Web Search]
|
||||
Search --> Analyzer[Content Analyzer]
|
||||
Analyzer --> Synthesizer[Information Synthesizer]
|
||||
Synthesizer --> Out[Research Report]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Synthesizer fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Research Agent can gather, analyze, and synthesize information from various sources.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `research_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Research Agent
|
||||
research_agent = Agent(
|
||||
name="ResearchAssistant",
|
||||
role="Research Specialist",
|
||||
goal="Conduct comprehensive research and analysis",
|
||||
instructions="You are a Research Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Conduct research
|
||||
response = research_agent.start(
|
||||
"Research about AI developments in 2024"
|
||||
)
|
||||
|
||||
# Save research findings
|
||||
with open('research_report.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Research Process
|
||||
|
||||
The Research Agent employs a systematic approach to information gathering and analysis:
|
||||
|
||||
1. **Web Search**: Uses DuckDuckGo to find relevant sources
|
||||
2. **Content Analysis**: Evaluates source credibility and relevance
|
||||
3. **Information Synthesis**: Combines findings into coherent insights
|
||||
4. **Report Generation**: Creates structured research reports
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Web Research" icon="globe">
|
||||
Comprehensive online information gathering.
|
||||
</Card>
|
||||
<Card title="Content Analysis" icon="microscope">
|
||||
In-depth evaluation of sources.
|
||||
</Card>
|
||||
<Card title="Information Synthesis" icon="layer-group">
|
||||
Integration of multiple sources.
|
||||
</Card>
|
||||
<Card title="Report Generation" icon="file-lines">
|
||||
Structured research documentation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
|
||||
agent.start("Research about AI 2024")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex research projects
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
|
||||
- Check out the [Data Analyst Agent](/agents/data-analyst) for data-driven research
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
title: "Shopping Agent"
|
||||
sidebarTitle: "Shopping"
|
||||
description: "Learn how to create AI agents for price comparison and shopping assistance."
|
||||
icon: "shop"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Product Query] --> Search[Store Search]
|
||||
Search --> Analyzer[Price Analyzer]
|
||||
Analyzer --> Comparator[Price Comparator]
|
||||
Comparator --> Out[Price Report]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Comparator fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Shopping Agent can search for products, compare prices, and provide shopping recommendations.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `shopping_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Shopping Agent
|
||||
shopping_agent = Agent(
|
||||
name="ShoppingAssistant",
|
||||
role="Shopping Specialist",
|
||||
goal="Find the best prices and deals across stores",
|
||||
instructions="You are a Shopping Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Search for product prices
|
||||
response = shopping_agent.start(
|
||||
"I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table"
|
||||
)
|
||||
|
||||
# Save price comparison
|
||||
with open('price_comparison.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Shopping Assistant
|
||||
|
||||
The Shopping Agent combines multiple capabilities for effective price comparison:
|
||||
|
||||
1. **Store Search**: Uses DuckDuckGo to find retailers
|
||||
2. **Price Analysis**: Gathers pricing information
|
||||
3. **Price Comparison**: Compares prices across stores
|
||||
4. **Deal Finding**: Identifies special offers and discounts
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Price Comparison" icon="scale-balanced">
|
||||
Compare prices across multiple stores.
|
||||
</Card>
|
||||
<Card title="Deal Detection" icon="tag">
|
||||
Find special offers and discounts.
|
||||
</Card>
|
||||
<Card title="Store Analysis" icon="store">
|
||||
Evaluate retailer reliability.
|
||||
</Card>
|
||||
<Card title="Price Tracking" icon="chart-line">
|
||||
Monitor price changes over time.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Compare product prices
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(instructions="You are a Shopping Agent", tools=[duckduckgo])
|
||||
agent.start("I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex shopping research
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving price accuracy
|
||||
- Check out the [Research Agent](/agents/research) for detailed product research
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
title: "Single Agent"
|
||||
sidebarTitle: "Single"
|
||||
description: "Learn how to create a basic single-purpose AI agent for simple tasks."
|
||||
icon: "circle-1"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Input] --> Agent[Single Agent]
|
||||
Agent --> Out[Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Agent fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how to create and use a simple single-purpose agent.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `simple_agent.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="You are a Markdown Agent, output in markdown format")
|
||||
agent.start("Write a blog post about AI")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Single Agent
|
||||
|
||||
The Single Agent is the simplest form of PraisonAI agent:
|
||||
|
||||
1. **Simple Setup**: Minimal configuration required
|
||||
2. **Single Purpose**: Focused on one specific task
|
||||
3. **Direct Execution**: Straightforward input-output flow
|
||||
4. **No Dependencies**: No external tools required
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Simple Setup" icon="square-1">
|
||||
Minimal configuration needed.
|
||||
</Card>
|
||||
<Card title="Focused Task" icon="bullseye">
|
||||
Single-purpose execution.
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt">
|
||||
Rapid implementation.
|
||||
</Card>
|
||||
<Card title="No Tools" icon="toolbox">
|
||||
No external dependencies.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Create a content generation agent
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create content agent
|
||||
agent = Agent(
|
||||
instructions="You are a Content Generation Agent, create engaging content"
|
||||
)
|
||||
|
||||
# Generate content
|
||||
response = agent.start("""
|
||||
Write a short story about:
|
||||
- A future world
|
||||
- With advanced AI
|
||||
- And human collaboration
|
||||
""")
|
||||
|
||||
# Save the story
|
||||
with open('ai_story.txt', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for more complex workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving output quality
|
||||
- Check out other specialized agents like the [Markdown Agent](/agents/markdown) for specific use cases
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
title: "Video Agent"
|
||||
sidebarTitle: "Video"
|
||||
description: "Learn how to create AI agents for video analysis and content understanding."
|
||||
icon: "video"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Video Input] --> Analyzer[Content Analyzer]
|
||||
Analyzer --> Detector[Object Detector]
|
||||
Detector --> Transcriber[Text Transcriber]
|
||||
Transcriber --> Out[Analysis Report]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Detector fill:#2E8B57,color:#fff
|
||||
style Transcriber fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Video Agent can analyze video content, detect objects, and extract meaningful information.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `video_analyzer.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Video Analysis Agent
|
||||
video_agent = Agent(
|
||||
name="VideoAnalyst",
|
||||
role="Video Analysis Specialist",
|
||||
goal="Analyze videos to extract meaningful information",
|
||||
backstory="""You are an expert in computer vision and video analysis.
|
||||
You excel at describing content, detecting objects, and understanding context.""",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create video analysis task
|
||||
analysis_task = Task(
|
||||
name="analyze_video",
|
||||
description="""Analyze this video and provide:
|
||||
1. Summary of main events
|
||||
2. Key objects and people
|
||||
3. Text and important information
|
||||
4. Context and setting""",
|
||||
expected_output="Comprehensive video analysis",
|
||||
agent=video_agent,
|
||||
images=["video.mp4"]
|
||||
)
|
||||
|
||||
# Create PraisonAIAgents instance
|
||||
agents = PraisonAIAgents(
|
||||
agents=[video_agent],
|
||||
tasks=[analysis_task],
|
||||
process="sequential",
|
||||
verbose=1
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Video Analysis
|
||||
|
||||
The Video Agent combines multiple capabilities for comprehensive video understanding:
|
||||
|
||||
1. **Content Analysis**: Analyzes video scenes and events
|
||||
2. **Object Detection**: Identifies objects and people
|
||||
3. **Text Extraction**: Captures text shown in videos
|
||||
4. **Context Understanding**: Interprets settings and situations
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Scene Analysis" icon="film">
|
||||
Detailed analysis of video scenes.
|
||||
</Card>
|
||||
<Card title="Object Detection" icon="cube">
|
||||
Identification of objects and people.
|
||||
</Card>
|
||||
<Card title="Text Extraction" icon="closed-captioning">
|
||||
Capture of text and captions.
|
||||
</Card>
|
||||
<Card title="Context Analysis" icon="sitemap">
|
||||
Understanding of video context.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Analyze a presentation video
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
video_agent = Agent(
|
||||
name="VideoAnalyst",
|
||||
role="Video Analysis Specialist",
|
||||
goal="Extract information from presentation videos",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create presentation analysis task
|
||||
presentation_task = Task(
|
||||
name="analyze_presentation",
|
||||
description="""Analyze this presentation video:
|
||||
1. Extract key points
|
||||
2. Capture slide content
|
||||
3. Note speaker's main arguments
|
||||
4. Summarize Q&A session""",
|
||||
expected_output="Detailed presentation summary",
|
||||
agent=video_agent,
|
||||
images=["presentation.mp4"]
|
||||
)
|
||||
|
||||
# Run analysis
|
||||
agents = PraisonAIAgents(
|
||||
agents=[video_agent],
|
||||
tasks=[presentation_task],
|
||||
process="sequential"
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex video analysis
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
|
||||
- Check out the [Image Agent](/agents/image) for still image analysis
|
||||
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: "Web Search Agent"
|
||||
sidebarTitle: "Web Search"
|
||||
description: "Learn how to create AI agents for intelligent web searching and information gathering."
|
||||
icon: "globe"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Search Query] --> Search[Web Search]
|
||||
Search --> Filter[Content Filter]
|
||||
Filter --> Summarizer[Content Summarizer]
|
||||
Summarizer --> Out[Search Results]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Filter fill:#2E8B57,color:#fff
|
||||
style Summarizer fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Web Search Agent can perform intelligent searches and process web content.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `web_search.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create Web Search Agent
|
||||
search_agent = Agent(
|
||||
name="WebSearcher",
|
||||
role="Web Search Specialist",
|
||||
goal="Perform intelligent web searches and gather information",
|
||||
instructions="You are a Web Search Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Perform search
|
||||
response = search_agent.start(
|
||||
"Search about AI developments in 2024"
|
||||
)
|
||||
|
||||
# Save search results
|
||||
with open('search_results.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Web Search
|
||||
|
||||
The Web Search Agent employs sophisticated search strategies:
|
||||
|
||||
1. **Query Processing**: Optimizes search queries
|
||||
2. **Content Filtering**: Filters relevant results
|
||||
3. **Information Extraction**: Extracts key information
|
||||
4. **Result Summarization**: Summarizes findings
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Smart Search" icon="magnifying-glass">
|
||||
Intelligent query processing.
|
||||
</Card>
|
||||
<Card title="Content Filtering" icon="filter">
|
||||
Relevance-based filtering.
|
||||
</Card>
|
||||
<Card title="Information Extraction" icon="scissors">
|
||||
Key information extraction.
|
||||
</Card>
|
||||
<Card title="Result Summary" icon="list">
|
||||
Concise result summaries.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Perform topic research
|
||||
from praisonaiagents import Agent, Tools
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Web Search Agent",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Research specific topic
|
||||
response = agent.start("""
|
||||
Search for information about quantum computing:
|
||||
- Recent breakthroughs
|
||||
- Leading companies
|
||||
- Current applications
|
||||
- Future predictions
|
||||
""")
|
||||
|
||||
# Save research results
|
||||
with open('quantum_computing_research.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex search workflows
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving search relevance
|
||||
- Check out the [Research Agent](/agents/research) for comprehensive research capabilities
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
title: "Wikipedia Agent"
|
||||
sidebarTitle: "Wikipedia"
|
||||
description: "Learn how to create AI agents for searching and extracting information from Wikipedia."
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[Query] --> Search[Wiki Search]
|
||||
Search --> Page[Page Retrieval]
|
||||
Page --> Summary[Content Summary]
|
||||
Summary --> Out[Knowledge Output]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Search fill:#2E8B57,color:#fff
|
||||
style Page fill:#2E8B57,color:#fff
|
||||
style Summary fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how the Wikipedia Agent can search, retrieve, and summarize Wikipedia content.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `wikipedia_assistant.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import (
|
||||
wiki_search,
|
||||
wiki_summary,
|
||||
wiki_page,
|
||||
wiki_random,
|
||||
wiki_language
|
||||
)
|
||||
|
||||
# Create Wikipedia Agent
|
||||
wiki_agent = Agent(
|
||||
name="WikipediaAssistant",
|
||||
role="Wikipedia Research Specialist",
|
||||
goal="Extract and summarize Wikipedia content",
|
||||
instructions="You are a Wikipedia Agent",
|
||||
tools=[
|
||||
wiki_search,
|
||||
wiki_summary,
|
||||
wiki_page,
|
||||
wiki_random,
|
||||
wiki_language
|
||||
],
|
||||
self_reflect=True,
|
||||
min_reflect=3,
|
||||
max_reflect=5
|
||||
)
|
||||
|
||||
# Research a topic
|
||||
response = wiki_agent.start("""
|
||||
What is the history of AI?
|
||||
First search the history of AI
|
||||
Read the page of the history of AI
|
||||
Get the summary of the page
|
||||
""")
|
||||
|
||||
# Save research results
|
||||
with open('ai_history.md', 'w') as f:
|
||||
f.write(response)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding Wikipedia Research
|
||||
|
||||
The Wikipedia Agent provides comprehensive Wikipedia access through multiple tools:
|
||||
|
||||
1. **Wiki Search**: `wiki_search` for finding relevant articles
|
||||
2. **Page Access**: `wiki_page` for retrieving full articles
|
||||
3. **Summarization**: `wiki_summary` for concise overviews
|
||||
4. **Random Articles**: `wiki_random` for discovering content
|
||||
5. **Language Support**: `wiki_language` for multilingual access
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Article Search" icon="magnifying-glass">
|
||||
Find relevant Wikipedia articles.
|
||||
</Card>
|
||||
<Card title="Content Retrieval" icon="book-open">
|
||||
Access complete article content.
|
||||
</Card>
|
||||
<Card title="Summarization" icon="compress">
|
||||
Generate concise article summaries.
|
||||
</Card>
|
||||
<Card title="Multilingual" icon="language">
|
||||
Access content in multiple languages.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
# Example: Research a scientific topic
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a Wikipedia Agent",
|
||||
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
|
||||
self_reflect=True,
|
||||
min_reflect=3,
|
||||
max_reflect=5,
|
||||
)
|
||||
agent.start(
|
||||
"What is the history of AI?"
|
||||
"First search the history of AI"
|
||||
"Read the page of the history of AI"
|
||||
"Get the summary of the page"
|
||||
)
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining) for complex Wikipedia research
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
|
||||
- Check out the [Research Agent](/agents/research) for broader research capabilities
|
||||
@@ -30,7 +30,7 @@ Features:
|
||||
- Built-in tools
|
||||
- Structured workflows
|
||||
|
||||
### AutoGen Integration
|
||||
### AG2 (Formerly AutoGen) Integration
|
||||
Requires installation with:
|
||||
```bash
|
||||
pip install "praisonai[autogen]"
|
||||
|
||||
+4
-4
@@ -23,7 +23,7 @@ from praisonai.auto import AutoGenerator
|
||||
### praisonai.agents_generator
|
||||
Framework-specific agent generation and orchestration:
|
||||
- CrewAI support (requires `praisonai[crewai]`)
|
||||
- AutoGen support (requires `praisonai[autogen]`)
|
||||
- AG2 (Formerly AutoGen) support (requires `praisonai[autogen]`)
|
||||
|
||||
```python
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
@@ -51,7 +51,7 @@ pip install praisonai
|
||||
|
||||
# Framework-specific installations
|
||||
pip install "praisonai[crewai]" # Install with CrewAI support
|
||||
pip install "praisonai[autogen]" # Install with AutoGen support
|
||||
pip install "praisonai[autogen]" # Install with AG2 support
|
||||
pip install "praisonai[crewai,autogen]" # Install both frameworks
|
||||
|
||||
# Additional features
|
||||
@@ -71,9 +71,9 @@ When installing with `pip install "praisonai[crewai]"`, you get:
|
||||
- Task delegation capabilities
|
||||
- Sequential and parallel task execution
|
||||
|
||||
### AutoGen
|
||||
### AG2 (Formerly AutoGen)
|
||||
When installing with `pip install "praisonai[autogen]"`, you get:
|
||||
- AutoGen framework support
|
||||
- AG2 framework support
|
||||
- PraisonAI tools integration
|
||||
- Multi-agent conversation capabilities
|
||||
- Code execution environment
|
||||
@@ -110,7 +110,7 @@ Loads environment variables from .env file or system and sets them.</p>
|
||||
file.write("FROM python:3.11-slim\n")
|
||||
file.write("WORKDIR /app\n")
|
||||
file.write("COPY . .\n")
|
||||
file.write("RUN pip install flask praisonai==2.0.34 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.2.22 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: "AutoAgents Module"
|
||||
description: "Documentation for the praisonaiagents.agents.autoagents module"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
# Module praisonaiagents.agents.autoagents
|
||||
|
||||
The AutoAgents module provides automatic creation and management of AI agents and tasks based on high-level instructions.
|
||||
|
||||
## Classes
|
||||
|
||||
### AutoAgents
|
||||
The main class for automatically creating and managing AI agents and tasks.
|
||||
|
||||
#### Parameters
|
||||
- `instructions: str` - High-level task description for the agents
|
||||
- `tools: Optional[List[Any]] = None` - List of tools available to the agents
|
||||
- `verbose: bool = False` - Enable detailed logging
|
||||
- `process: str = "sequential"` - Process type (sequential or hierarchical)
|
||||
- `manager_llm: Optional[str] = None` - Language model for manager agent
|
||||
- `max_retries: int = 5` - Maximum retry attempts
|
||||
- `completion_checker: Optional[Any] = None` - Custom completion checker
|
||||
- `allow_code_execution: bool = False` - Allow code execution
|
||||
- `memory: bool = True` - Enable agent memory
|
||||
- `markdown: bool = True` - Enable markdown formatting
|
||||
- `self_reflect: bool = False` - Enable agent self-reflection
|
||||
- `max_reflect: int = 3` - Maximum reflection iterations
|
||||
- `min_reflect: int = 1` - Minimum reflection iterations
|
||||
- `llm: Optional[str] = None` - Language model for agents
|
||||
- `function_calling_llm: Optional[str] = None` - Language model for tool calling
|
||||
- `respect_context_window: bool = True` - Respect model context window
|
||||
- `code_execution_mode: str = "safe"` - Code execution mode (safe/unsafe)
|
||||
- `embedder_config: Optional[Dict[str, Any]] = None` - Embedder configuration
|
||||
- `knowledge_sources: Optional[List[Any]] = None` - Knowledge sources
|
||||
- `use_system_prompt: bool = True` - Use system prompts
|
||||
- `cache: bool = True` - Enable caching
|
||||
- `allow_delegation: bool = False` - Allow task delegation
|
||||
- `step_callback: Optional[Any] = None` - Callback for each step
|
||||
- `system_template: Optional[str] = None` - Custom system template
|
||||
- `prompt_template: Optional[str] = None` - Custom prompt template
|
||||
- `response_template: Optional[str] = None` - Custom response template
|
||||
- `max_rpm: Optional[int] = None` - Maximum requests per minute
|
||||
- `max_execution_time: Optional[int] = None` - Maximum execution time
|
||||
- `max_iter: int = 20` - Maximum iterations
|
||||
- `reflect_llm: Optional[str] = None` - Language model for reflection
|
||||
- `max_agents: int = 3` - Maximum number of agents to create
|
||||
|
||||
#### Methods
|
||||
|
||||
##### start()
|
||||
Start the agents synchronously.
|
||||
|
||||
```python
|
||||
def start(self):
|
||||
"""
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return super().start()
|
||||
```
|
||||
|
||||
##### astart()
|
||||
Start the agents asynchronously.
|
||||
|
||||
```python
|
||||
async def astart(self):
|
||||
"""
|
||||
Async version of start() method.
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return await super().astart()
|
||||
```
|
||||
|
||||
#### Internal Methods
|
||||
|
||||
##### _generate_config()
|
||||
Generate the configuration for agents and tasks.
|
||||
|
||||
```python
|
||||
def _generate_config(self) -> AutoAgentsConfig:
|
||||
"""
|
||||
Generate the configuration for agents and tasks based on instructions.
|
||||
Returns AutoAgentsConfig object containing agent and task configurations.
|
||||
"""
|
||||
```
|
||||
|
||||
##### _create_agents_and_tasks()
|
||||
Create agents and tasks from configuration.
|
||||
|
||||
```python
|
||||
def _create_agents_and_tasks(self, config: AutoAgentsConfig) -> tuple[List[Agent], List[Task]]:
|
||||
"""
|
||||
Create agents and tasks based on the generated configuration.
|
||||
Returns tuple of (agents, tasks).
|
||||
"""
|
||||
```
|
||||
|
||||
##### _assign_tools_to_agent()
|
||||
Assign appropriate tools to an agent.
|
||||
|
||||
```python
|
||||
def _assign_tools_to_agent(self, agent_config: AgentConfig) -> List[Any]:
|
||||
"""
|
||||
Assign tools to an agent based on its role and tasks.
|
||||
Returns list of assigned tools.
|
||||
"""
|
||||
```
|
||||
|
||||
## Pydantic Models
|
||||
|
||||
### TaskConfig
|
||||
Configuration for a task.
|
||||
|
||||
#### Attributes
|
||||
- `name: str` - Task name
|
||||
- `description: str` - Task description
|
||||
- `expected_output: str` - Expected output description
|
||||
- `tools: List[str]` - Required tools for the task
|
||||
|
||||
### AgentConfig
|
||||
Configuration for an agent.
|
||||
|
||||
#### Attributes
|
||||
- `name: str` - Agent name
|
||||
- `role: str` - Agent role
|
||||
- `goal: str` - Agent goal
|
||||
- `backstory: str` - Agent backstory
|
||||
- `tools: List[str]` - Required tools
|
||||
- `tasks: List[TaskConfig]` - Tasks assigned to the agent
|
||||
|
||||
### AutoAgentsConfig
|
||||
Overall configuration for AutoAgents.
|
||||
|
||||
#### Attributes
|
||||
- `main_instruction: str` - Main instruction for the agents
|
||||
- `process_type: str` - Process type (sequential/hierarchical)
|
||||
- `agents: List[AgentConfig]` - List of agent configurations
|
||||
|
||||
## Example Usage
|
||||
|
||||
### Basic Usage
|
||||
```python
|
||||
from praisonaiagents import AutoAgents
|
||||
from praisonaiagents.tools import SerperDevTool
|
||||
|
||||
agents = AutoAgents(
|
||||
instructions="Research recent AI developments",
|
||||
tools=[SerperDevTool()],
|
||||
verbose=True
|
||||
)
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
### Async Usage
|
||||
```python
|
||||
async def main():
|
||||
agents = AutoAgents(
|
||||
instructions="Research recent AI developments",
|
||||
tools=[SerperDevTool()],
|
||||
process="hierarchical"
|
||||
)
|
||||
result = await agents.astart()
|
||||
|
||||
import asyncio
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### Advanced Configuration
|
||||
```python
|
||||
agents = AutoAgents(
|
||||
instructions="Complex research task",
|
||||
tools=[SerperDevTool()],
|
||||
max_agents=5,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o",
|
||||
memory=True,
|
||||
allow_delegation=True,
|
||||
max_execution_time=600,
|
||||
self_reflect=True
|
||||
)
|
||||
```
|
||||
|
||||
<Note>
|
||||
For optimal results, provide clear instructions and appropriate tools for your use case.
|
||||
</Note>
|
||||
@@ -1,69 +0,0 @@
|
||||
---
|
||||
title: Installation
|
||||
description: Set up PraisonAI in your development environment
|
||||
icon: download
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
|
||||
- Python 3.10 or higher
|
||||
- pip package manager
|
||||
- Virtual environment (recommended)
|
||||
</Note>
|
||||
|
||||
# Installing PraisonAI
|
||||
|
||||
Follow these steps to set up PraisonAI in your development environment.
|
||||
|
||||
<Steps>
|
||||
<Step title="Create Virtual Environment (Optional)">
|
||||
First, create and activate a virtual environment:
|
||||
<CodeGroup>
|
||||
```bash Mac/Linux
|
||||
python -m venv praisonai-env
|
||||
source praisonai-env/bin/activate
|
||||
```
|
||||
|
||||
```bash Windows
|
||||
python -m venv praisonai-env
|
||||
.\praisonai-env\Scripts\activate
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package and tools:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
You can also use other LLM providers like Anthropic, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Quick Start Guide"
|
||||
icon="bolt"
|
||||
href="/code/quickstart"
|
||||
>
|
||||
Build your first AI agent
|
||||
</Card>
|
||||
<Card
|
||||
title="API Reference"
|
||||
icon="code"
|
||||
href="/api/praisonaiagents/index"
|
||||
>
|
||||
Explore the API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -1,188 +0,0 @@
|
||||
---
|
||||
title: "Introduction"
|
||||
description: "Welcome to PraisonAI - The Next Generation AI Agent Framework"
|
||||
icon: "book-open"
|
||||
---
|
||||
|
||||
<Note>
|
||||
PraisonAI is a powerful framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
|
||||
</Note>
|
||||
|
||||
# What is PraisonAI?
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Define the main flow
|
||||
Start([▶ Start]) --> Agent1
|
||||
Agent1 --> Process[⚙ Process]
|
||||
Process --> Agent2
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[" "]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
|
||||
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Agent2[" "]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
|
||||
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Style for agent containers
|
||||
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agents" icon="user-robot">
|
||||
Autonomous AI entities that can understand context and execute tasks
|
||||
</Card>
|
||||
<Card title="Tasks" icon="list-check">
|
||||
Units of work that agents can execute independently or collaboratively
|
||||
</Card>
|
||||
<Card title="Process" icon="diagram-project">
|
||||
Workflow management for coordinating agent activities
|
||||
</Card>
|
||||
<Card title="Tools" icon="toolbox">
|
||||
Extensible capabilities that agents can leverage
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Key Features
|
||||
|
||||
<Steps>
|
||||
<Step title="Autonomous Agents">
|
||||
Create intelligent agents that can:
|
||||
- Understand natural language instructions
|
||||
- Make decisions based on context
|
||||
- Execute complex tasks autonomously
|
||||
</Step>
|
||||
<Step title="Flexible Architecture">
|
||||
Build with:
|
||||
- Modular components
|
||||
- Extensible tools
|
||||
- Customizable workflows
|
||||
</Step>
|
||||
<Step title="Advanced Capabilities">
|
||||
Leverage:
|
||||
- Multi-agent collaboration
|
||||
- Memory and context management
|
||||
- Tool integration
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Use Cases
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Customer Service" icon="headset">
|
||||
Build intelligent support agents that can handle customer inquiries and resolve issues autonomously.
|
||||
</Card>
|
||||
<Card title="Data Analysis" icon="chart-line">
|
||||
Create agents that can process, analyze, and derive insights from complex datasets.
|
||||
</Card>
|
||||
<Card title="Content Creation" icon="pen-nib">
|
||||
Deploy agents that can generate, edit, and optimize content across various formats.
|
||||
</Card>
|
||||
<Card title="Process Automation" icon="gears">
|
||||
Automate complex workflows with intelligent agents that can coordinate and execute tasks.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Getting Started
|
||||
|
||||
<Warning>
|
||||
Before proceeding, ensure you have Python 3.9+ installed on your system.
|
||||
</Warning>
|
||||
|
||||
### Quick Setup
|
||||
|
||||
<CodeGroup>
|
||||
```bash pip
|
||||
pip install praisonai
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Basic Example
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create an agent
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o"
|
||||
)
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Installation"
|
||||
icon="download"
|
||||
href="/code/installation"
|
||||
>
|
||||
Complete installation guide and setup instructions
|
||||
</Card>
|
||||
<Card
|
||||
title="Quick Start"
|
||||
icon="play"
|
||||
href="/code/quickstart"
|
||||
>
|
||||
Build your first AI agent in minutes
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
Join our community on [Discord](https://www.youtube.com/redirect?event=channel_description&redir_token=QUFFLUhqbUpiZE00YlF1MjB1LVNIeTFxTnV6MWRRc18wZ3xBQ3Jtc0ttQVZ0aFJ4RXRDanlBQU1Vd3lHU3BBcml3bzhoek1pTmlkZkFkWjlNVDBpRkxZd1dTOWhPc20xbHJOb1NibmNYeTEydklJT0pZOVJFQW93MmJOQXU0WkJNVzNsd29SZ3FBNFVwMTFGNThNSHBWVUhjSQ&q=https%3A%2F%2Fdiscord.gg%2FnNZu5gGT59) to connect with other developers and get help!
|
||||
</Tip>
|
||||
@@ -1,195 +0,0 @@
|
||||
---
|
||||
title: Quick Start
|
||||
description: Build your first AI agent with PraisonAI
|
||||
icon: bolt
|
||||
---
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
You can also use other LLM providers like Anthropic, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent">
|
||||
Create `app.py`:
|
||||
## Code Example
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create an agent
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o"
|
||||
)
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
```python Advanced
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create multiple agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
name="Writer",
|
||||
role="Tech Content Strategist",
|
||||
goal="Craft compelling content on tech advancements",
|
||||
backstory="You are a content strategist",
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# Define multiple tasks
|
||||
task1 = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="writing_task",
|
||||
description="Create a blog post about AI advancements",
|
||||
expected_output="A blog post",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Run with hierarchical process
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=False,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Program">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
|
||||
You should see:
|
||||
- Agent initialization
|
||||
- Agents progress
|
||||
- Final results
|
||||
- Generated report
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Creating Custom Tool
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Agent
|
||||
data_agent = Agent(
|
||||
name="DataCollector",
|
||||
role="Search Specialist",
|
||||
goal="Perform internet searches to collect relevant information.",
|
||||
backstory="Expert in finding and organising internet data.",
|
||||
tools=[internet_search_tool],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# 3. Tasks
|
||||
collect_task = Task(
|
||||
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
|
||||
expected_output="List of search results with titles, URLs, and snippets.",
|
||||
agent=data_agent,
|
||||
name="collect_data",
|
||||
)
|
||||
|
||||
# 4. Start Agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[data_agent],
|
||||
tasks=[collect_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Core Concepts"
|
||||
icon="book"
|
||||
href="/concepts/agents"
|
||||
>
|
||||
Learn about agents, tasks, and processes
|
||||
</Card>
|
||||
<Card
|
||||
title="API Reference"
|
||||
icon="code"
|
||||
href="/api/praisonaiagents/index"
|
||||
>
|
||||
Explore detailed API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
+186
-53
@@ -4,11 +4,8 @@ description: "Understanding Agents in PraisonAI"
|
||||
icon: "user"
|
||||
---
|
||||
|
||||
<Note>
|
||||
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
|
||||
</Note>
|
||||
|
||||
# Understanding Agents
|
||||
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
@@ -19,45 +16,34 @@ graph LR
|
||||
Agent2 --> Output([✓ Output])
|
||||
Process -.-> Agent1
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Define subgraphs for agents and their tasks
|
||||
subgraph Agent1[" "]
|
||||
subgraph Agent1[ ]
|
||||
Task1[📋 Task]
|
||||
AgentIcon1[🤖 AI Agent]
|
||||
Tools1[🔧 Tools]
|
||||
|
||||
Task1 --- AgentIcon1
|
||||
AgentIcon1 --- Tools1
|
||||
|
||||
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Agent2[" "]
|
||||
subgraph Agent2[ ]
|
||||
Task2[📋 Task]
|
||||
AgentIcon2[🤖 AI Agent]
|
||||
Tools2[🔧 Tools]
|
||||
|
||||
Task2 --- AgentIcon2
|
||||
AgentIcon2 --- Tools2
|
||||
|
||||
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Style for agent containers
|
||||
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Start,Output,Task1,Task2 input
|
||||
class Process,AgentIcon1,AgentIcon2 process
|
||||
class Tools1,Tools2 tools
|
||||
class Agent1,Agent2 transparent
|
||||
```
|
||||
|
||||
## Key Components
|
||||
@@ -105,43 +91,190 @@ graph LR
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Agent Types
|
||||
|
||||
<Steps>
|
||||
<Step title="Basic Agent">
|
||||
- Single-purpose focus
|
||||
- Direct user interaction
|
||||
- Limited tool set
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
<Step title="Specialized Agent">
|
||||
- Domain expertise
|
||||
- Advanced capabilities
|
||||
- Custom tools
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
<Step title="Collaborative Agent">
|
||||
- Team interaction
|
||||
- Task delegation
|
||||
- Shared context
|
||||
|
||||
<Step title="Create Agent">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="Your are a helpful AI assistant")
|
||||
agent.start("Write a movie script about a robot in Mars")
|
||||
```
|
||||
|
||||
```python Multi Agents
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
research_agent = Agent(instructions="Research about AI")
|
||||
summarise_agent = Agent(instructions="Summarise research agent's findings")
|
||||
|
||||
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
|
||||
You should see:
|
||||
- Agent initialization
|
||||
- Agents progress
|
||||
- Final results
|
||||
- Generated report
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Agent Types
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Basic Agent" icon="user" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Overview">
|
||||
Perfect for straightforward tasks and direct interactions
|
||||
</Accordion>
|
||||
<Accordion title="Features">
|
||||
- Single-purpose focus
|
||||
- Direct user interaction
|
||||
- Limited tool set
|
||||
- Ideal for simple tasks
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
|
||||
<Card title="Specialized Agent" icon="user-gear" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Overview">
|
||||
Experts in specific domains with advanced capabilities
|
||||
</Accordion>
|
||||
<Accordion title="Features">
|
||||
- Domain expertise
|
||||
- Advanced capabilities
|
||||
- Custom tools
|
||||
- Deep knowledge base
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
|
||||
<Card title="Collaborative Agent" icon="users" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Overview">
|
||||
Designed for team-based operations and complex workflows
|
||||
</Accordion>
|
||||
<Accordion title="Features">
|
||||
- Team interaction
|
||||
- Task delegation
|
||||
- Shared context
|
||||
- Coordinated actions
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<Warning>
|
||||
Always implement proper error handling and resource management in your agent configurations.
|
||||
</Warning>
|
||||
<Note>
|
||||
Always implement proper error handling and resource management in your agent configurations.
|
||||
</Note>
|
||||
|
||||
### Agent Design
|
||||
1. Clear role definition
|
||||
2. Specific, measurable goals
|
||||
3. Relevant tool selection
|
||||
4. Appropriate memory configuration
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent Design" icon="compass-drafting" iconType="solid">
|
||||
<Steps>
|
||||
<Step title="Role Definition">
|
||||
Define clear, specific roles for each agent
|
||||
</Step>
|
||||
<Step title="Goal Setting">
|
||||
Set specific, measurable goals
|
||||
</Step>
|
||||
<Step title="Tool Selection">
|
||||
Choose relevant tools for the task
|
||||
</Step>
|
||||
<Step title="Memory Setup">
|
||||
Configure appropriate memory settings
|
||||
</Step>
|
||||
</Steps>
|
||||
</Card>
|
||||
|
||||
### Agent Interaction
|
||||
1. Clear communication protocols
|
||||
2. Defined delegation rules
|
||||
3. Error handling mechanisms
|
||||
4. Resource management
|
||||
<Card title="Agent Interaction" icon="network-wired" iconType="solid">
|
||||
<Steps>
|
||||
<Step title="Communication">
|
||||
Establish clear communication protocols
|
||||
</Step>
|
||||
<Step title="Delegation">
|
||||
Define explicit delegation rules
|
||||
</Step>
|
||||
<Step title="Error Handling">
|
||||
Implement robust error handling
|
||||
</Step>
|
||||
<Step title="Resource Management">
|
||||
Set up efficient resource allocation
|
||||
</Step>
|
||||
</Steps>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Async Capabilities
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Features" icon="bolt" iconType="solid">
|
||||
<Tabs>
|
||||
<Tab title="Async Support">
|
||||
```python
|
||||
async def main():
|
||||
agent = Agent(name="AsyncAgent")
|
||||
result = await agent.aprocess_task()
|
||||
```
|
||||
- Full async/await support
|
||||
- Non-blocking operations
|
||||
- Enhanced performance
|
||||
</Tab>
|
||||
|
||||
<Tab title="Parallel Execution">
|
||||
```python
|
||||
async def parallel_tasks():
|
||||
tasks = [agent1.task(), agent2.task()]
|
||||
results = await asyncio.gather(*tasks)
|
||||
```
|
||||
- Parallel task execution
|
||||
- Efficient resource usage
|
||||
- Improved throughput
|
||||
</Tab>
|
||||
|
||||
<Tab title="Integration">
|
||||
```python
|
||||
@agent.async_tool
|
||||
async def custom_tool():
|
||||
async with aiohttp.ClientSession() as session:
|
||||
# Async operations
|
||||
pass
|
||||
```
|
||||
- Async tool integration
|
||||
- Callback support
|
||||
- Mixed sync/async operations
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Features
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
---
|
||||
title: "AI Agents with Knowledge"
|
||||
sidebarTitle: "Knowledge"
|
||||
description: "Learn how to create AI agents with custom knowledge bases"
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph In[Input]
|
||||
PDF[PDF]
|
||||
TXT[TXT]
|
||||
MD[MD]
|
||||
end
|
||||
|
||||
subgraph Router[Vector Store]
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
subgraph Out[Agents]
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
|
||||
In --> Router
|
||||
Router --> A1
|
||||
Router --> A2
|
||||
Router --> A3
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Router fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
|
||||
| Purpose | Provide static reference information | Store dynamic context and interactions |
|
||||
| Storage | Read-only knowledge base | Read-write memory store |
|
||||
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
|
||||
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install PraisonAI Agents with knowledge support:
|
||||
```bash
|
||||
pip install "praisonaiagents[knowledge]"
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key:
|
||||
```bash
|
||||
export OPENAI_API_KEY=xxxxx
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create Script">
|
||||
Create a new file `app.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"]
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Basic Usage
|
||||
|
||||
The simplest way to create a knowledge-based agent is without any configuration:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"]
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
For more control over the knowledge base, you can specify a configuration:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "custom_knowledge",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"],
|
||||
knowledge_config=config
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
|
||||
## Multi-Agent Knowledge System
|
||||
|
||||
For more complex scenarios, you can create a knowledge-based system with multiple agents:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import logging
|
||||
import os
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Define the configuration for the Knowledge instance
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "knowledge_test",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create an agent with knowledge capabilities
|
||||
knowledge_agent = Agent(
|
||||
name="KnowledgeAgent",
|
||||
role="Information Specialist",
|
||||
goal="Store and retrieve knowledge efficiently",
|
||||
backstory="Expert in managing and utilizing stored knowledge",
|
||||
knowledge=["sample.pdf"],
|
||||
knowledge_config=config,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Define a task for the agent
|
||||
knowledge_task = Task(
|
||||
name="knowledge_task",
|
||||
description="Who is Mervin Praison?",
|
||||
expected_output="Answer to the question",
|
||||
agent=knowledge_agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[knowledge_agent],
|
||||
tasks=[knowledge_task],
|
||||
process="sequential",
|
||||
user_id="user1"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
## Understanding Knowledge Configuration
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Vector Store Options">
|
||||
- **Provider**: Choose between different vector store backends (e.g., "chroma")
|
||||
- **Collection Name**: Name for your knowledge collection
|
||||
- **Path**: Location to store the vector database
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Supported File Types">
|
||||
- PDF documents (*.pdf)
|
||||
- Text files (*.txt)
|
||||
- Markdown files (*.md, *.mdx)
|
||||
- And more...
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Multi-Agent Setup">
|
||||
- **Role**: Define specialized roles for knowledge agents
|
||||
- **Goal**: Set specific knowledge management objectives
|
||||
- **Process**: Choose between sequential or parallel execution
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Custom Knowledge" icon="book">
|
||||
Import your own documents and data as knowledge sources
|
||||
</Card>
|
||||
<Card title="Vector Storage" icon="database">
|
||||
Efficient storage and retrieval of knowledge embeddings
|
||||
</Card>
|
||||
<Card title="Multiple Sources" icon="layer-group">
|
||||
Combine multiple documents and file types
|
||||
</Card>
|
||||
<Card title="Persistent Storage" icon="hard-drive">
|
||||
Save and reuse knowledge bases across sessions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Document Preparation**
|
||||
- Clean and well-formatted documents work best
|
||||
- Break large documents into smaller chunks
|
||||
- Use consistent formatting
|
||||
|
||||
2. **Knowledge Organization**
|
||||
- Group related documents together
|
||||
- Use meaningful file names
|
||||
- Keep knowledge bases focused and relevant
|
||||
|
||||
3. **Performance Optimization**
|
||||
- Monitor vector store size
|
||||
- Clean up unused collections
|
||||
- Use appropriate chunk sizes
|
||||
|
||||
4. **Multi-Agent Coordination**
|
||||
- Define clear roles and responsibilities
|
||||
- Set appropriate logging levels for debugging
|
||||
- Use unique collection names for different agent groups
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Memory Management](/concepts/memory) for long-term recall
|
||||
- Explore [Tool Integration](/concepts/tools) for enhanced capabilities
|
||||
- Check out [Examples](/examples) for implementation ideas
|
||||
@@ -0,0 +1,472 @@
|
||||
---
|
||||
title: "AI Agents with Memory"
|
||||
sidebarTitle: "Memory"
|
||||
description: "Learn how to create AI agents with memory capabilities for maintaining context and information across tasks."
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Memory
|
||||
direction TB
|
||||
STM[Short Term]
|
||||
LTM[Long Term]
|
||||
end
|
||||
|
||||
subgraph Store
|
||||
direction TB
|
||||
DB[(Vector DB)]
|
||||
end
|
||||
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
Memory <--> Store
|
||||
Store <--> A1
|
||||
Store <--> A2
|
||||
Store <--> A3
|
||||
|
||||
style Memory fill:#189AB4,color:#fff
|
||||
style Store fill:#2E8B57,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
|
||||
| Purpose | Provide static reference information | Store dynamic context and interactions |
|
||||
| Storage | Read-only knowledge base | Read-write memory store |
|
||||
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
|
||||
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install "praisonaiagents[memory]" duckduckgo_search
|
||||
```
|
||||
duckduckgo_search is a tool that allows agents to search the web.
|
||||
It is required for the multiple agents example shown below.
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create blog writer agent
|
||||
blog_agent = Agent(
|
||||
role="Blog Writer",
|
||||
goal="Write a blog post about AI",
|
||||
backstory="Expert at writing blog posts",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create blog writing task
|
||||
blog_task = Task(
|
||||
description="Write a blog post about AI trends",
|
||||
expected_output="Well-written blog post about AI trends",
|
||||
agent=blog_agent
|
||||
)
|
||||
|
||||
# Create and start the agents with memory enabled
|
||||
agents = PraisonAIAgents(
|
||||
agents=[blog_agent],
|
||||
tasks=[blog_task],
|
||||
memory=True
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
print(result)
|
||||
```
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create research agent with memory
|
||||
research_agent = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Research and document key information about topics",
|
||||
backstory="Expert at analyzing and storing information in memory",
|
||||
llm="gpt-4o-mini",
|
||||
tools=[duckduckgo]
|
||||
)
|
||||
|
||||
# Create blog writer agent
|
||||
blog_agent = Agent(
|
||||
role="Blog Writer",
|
||||
goal="Write a blog post about the research",
|
||||
backstory="Expert at writing blog posts",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create research task
|
||||
research_task = Task(
|
||||
description="Research and document key information about AI trends",
|
||||
expected_output="Detailed research findings about AI trends",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
# Create blog writing task
|
||||
blog_task = Task(
|
||||
description="Write a blog post about the research findings",
|
||||
expected_output="Well-written blog post based on research",
|
||||
agent=blog_agent
|
||||
)
|
||||
|
||||
# Create and start the agents with advanced memory configuration
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, blog_agent],
|
||||
tasks=[research_task, blog_task],
|
||||
memory=True
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
print(result)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
Install the PraisonAI package:
|
||||
```bash
|
||||
pip install praisonai
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create a file">
|
||||
Create a new file `agents.yaml` with the basic setup:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
memory: true
|
||||
roles:
|
||||
researcher:
|
||||
backstory: Expert at analyzing and storing information in memory.
|
||||
goal: Research and document key information about topics
|
||||
role: Research Analyst
|
||||
llm: gpt-4o-mini
|
||||
tools:
|
||||
- duckduckgo
|
||||
tasks:
|
||||
research_task:
|
||||
description: Research and document key information about topics.
|
||||
expected_output: Detailed research findings.
|
||||
|
||||
writer:
|
||||
backstory: Expert at writing blog posts.
|
||||
goal: Write a blog post about the research
|
||||
role: Blog Writer
|
||||
llm: gpt-4o-mini
|
||||
tasks:
|
||||
blog_task:
|
||||
description: Write a blog post about the research.
|
||||
expected_output: Well-written blog post based on research.
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Memory
|
||||
|
||||
<Card title="What is Agent Memory?" icon="question">
|
||||
Memory in AI agents enables them to:
|
||||
- Maintain context across multiple tasks
|
||||
- Remember previous interactions and findings
|
||||
- Build upon past knowledge
|
||||
- Share information between agents
|
||||
- Create more coherent and contextual responses
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Context Retention" icon="brain">
|
||||
Maintain information across multiple interactions.
|
||||
</Card>
|
||||
<Card title="Information Sharing" icon="share-nodes">
|
||||
Share knowledge between multiple agents.
|
||||
</Card>
|
||||
<Card title="Long-term Storage" icon="database">
|
||||
Store and retrieve information over extended periods.
|
||||
</Card>
|
||||
<Card title="Memory Types" icon="layer-group">
|
||||
Support for different memory types (short-term, long-term).
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent Memory
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create first agent for research
|
||||
researcher = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Research and analyze market trends",
|
||||
backstory="Expert in market research and data analysis",
|
||||
tools=[duckduckgo],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create second agent for report writing
|
||||
writer = Agent(
|
||||
role="Report Writer",
|
||||
goal="Create comprehensive market reports",
|
||||
backstory="Expert in technical writing and report creation",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create research task
|
||||
research_task = Task(
|
||||
description="Research current market trends",
|
||||
expected_output="Detailed market analysis",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Create writing task
|
||||
report_task = Task(
|
||||
description="Create a market report based on research",
|
||||
expected_output="Comprehensive market report",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Create and start the agents with memory
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, report_task],
|
||||
memory=True,
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
memory: true
|
||||
roles:
|
||||
researcher:
|
||||
backstory: Expert in market research and data analysis.
|
||||
goal: Research and analyze market trends
|
||||
role: Research Analyst
|
||||
tools:
|
||||
- duckduckgo
|
||||
tasks:
|
||||
research_task:
|
||||
description: Research current market trends.
|
||||
expected_output: Detailed market analysis.
|
||||
|
||||
writer:
|
||||
backstory: Expert in technical writing and report creation.
|
||||
goal: Create comprehensive market reports
|
||||
role: Report Writer
|
||||
tasks:
|
||||
report_task:
|
||||
description: Create a market report based on research.
|
||||
expected_output: Comprehensive market report.
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with memory configuration
|
||||
agent = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Research and retain information",
|
||||
backstory="Expert in research and analysis",
|
||||
tools=[duckduckgo],
|
||||
verbose=True, # Enable detailed logging
|
||||
llm="gpt-4o" # Language model to use
|
||||
)
|
||||
|
||||
# Create agents with memory options
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
memory=True, # Enable memory
|
||||
memory_config={
|
||||
"provider": "rag", # Use RAG for semantic search
|
||||
"use_embedding": True, # Enable embeddings for better search
|
||||
"short_db": ".praison/short_term.db", # Path for short-term memory
|
||||
"long_db": ".praison/long_term.db", # Path for long-term memory
|
||||
"rag_db_path": ".praison/chroma_db" # Path for vector database
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Memory Issues" icon="triangle-exclamation">
|
||||
If memory isn't working as expected:
|
||||
- Check memory configuration
|
||||
- Enable verbose mode for debugging
|
||||
- Verify memory provider settings
|
||||
</Card>
|
||||
|
||||
<Card title="Context Flow" icon="code">
|
||||
If context isn't being maintained:
|
||||
- Review task dependencies
|
||||
- Check memory configuration
|
||||
- Verify agent communication
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="../features/autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="../features/mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, configure memory settings based on your specific use case requirements and expected interaction patterns.
|
||||
</Note>
|
||||
|
||||
### Memory Configuration Options
|
||||
|
||||
The memory system in PraisonAI supports various configuration options to customize how agents store and retrieve information:
|
||||
|
||||
```python
|
||||
memory_config = {
|
||||
# Memory Provider
|
||||
"provider": "rag", # Options: "rag", "mem0", "none"
|
||||
"use_embedding": True, # Enable semantic search with embeddings
|
||||
|
||||
# Storage Paths
|
||||
"short_db": ".praison/short_term.db", # Short-term memory SQLite DB
|
||||
"long_db": ".praison/long_term.db", # Long-term memory SQLite DB
|
||||
"rag_db_path": ".praison/chroma_db", # Vector database path
|
||||
|
||||
# Memory Settings
|
||||
"ttl": 3600, # Time to live for memory items (in seconds)
|
||||
|
||||
# Optional Mem0 Config (if using mem0 provider)
|
||||
"config": {
|
||||
"api_key": "...", # Mem0 API key
|
||||
"org_id": "...", # Organization ID
|
||||
"project_id": "..." # Project ID
|
||||
}
|
||||
}
|
||||
|
||||
# Create agents with memory configuration
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
memory=True,
|
||||
memory_config=memory_config
|
||||
)
|
||||
```
|
||||
|
||||
### Memory Types
|
||||
|
||||
PraisonAI's memory system includes several types of memory:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Short-term Memory" icon="bolt">
|
||||
- Temporary storage for current context
|
||||
- Automatically cleared between sessions
|
||||
- Fast access for immediate task context
|
||||
</Card>
|
||||
<Card title="Long-term Memory" icon="database">
|
||||
- Persistent storage for important information
|
||||
- Semantic search capabilities with RAG
|
||||
- Quality-based storage decisions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Memory Quality Control
|
||||
|
||||
PraisonAI includes built-in quality control for memory storage:
|
||||
|
||||
```python
|
||||
# Example of storing with quality metrics
|
||||
agents.memory.store_long_term(
|
||||
text="Important information to remember",
|
||||
metadata={
|
||||
"task_id": "task_123",
|
||||
"agent": "research_agent"
|
||||
},
|
||||
completeness=0.9, # How complete is the information
|
||||
relevance=0.85, # How relevant to the task
|
||||
clarity=0.95, # How clear and well-structured
|
||||
accuracy=0.9, # How accurate is the information
|
||||
weights={ # Custom weights for quality score
|
||||
"completeness": 0.3,
|
||||
"relevance": 0.3,
|
||||
"clarity": 0.2,
|
||||
"accuracy": 0.2
|
||||
}
|
||||
)
|
||||
|
||||
# Search with quality filter
|
||||
results = agents.memory.search_long_term(
|
||||
query="search query",
|
||||
min_quality=0.8, # Only return high-quality matches
|
||||
limit=5 # Maximum number of results
|
||||
)
|
||||
+403
-170
@@ -10,96 +10,287 @@ Process types in PraisonAI define how tasks are executed and how agents collabor
|
||||
|
||||
## Process Types Overview
|
||||
|
||||
Three types of processes are implemented in PraisonAI:
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="Sequential Process"
|
||||
icon="arrow-right"
|
||||
href="/sequential-process"
|
||||
>
|
||||
Linear task execution in a predefined order
|
||||
</Card>
|
||||
<Card
|
||||
title="Hierarchical Process"
|
||||
icon="sitemap"
|
||||
href="/hierarchical-process"
|
||||
>
|
||||
Manager-coordinated task execution with dynamic assignment
|
||||
</Card>
|
||||
<Card
|
||||
title="Workflow Process"
|
||||
icon="diagram-project"
|
||||
href="/workflow-process"
|
||||
>
|
||||
Complex task flows with conditional execution and state management
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Frame>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
|
||||
<svg className="w-6 h-6 text-blue-600 dark:text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16m-7 6h7" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-lg font-semibold">Sequential Process</h3>
|
||||
</div>
|
||||
<p>Linear task execution in a predefined order</p>
|
||||
</div>
|
||||
## Sequential Process
|
||||
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
|
||||
<svg className="w-6 h-6 text-green-600 dark:text-green-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-lg font-semibold">Hierarchical Process</h3>
|
||||
</div>
|
||||
<p>Manager-coordinated task execution with dynamic assignment</p>
|
||||
</div>
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] --> A1
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
|
||||
end
|
||||
A3 --> Output[Output]
|
||||
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
|
||||
<svg className="w-6 h-6 text-purple-600 dark:text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-lg font-semibold">Workflow Process</h3>
|
||||
</div>
|
||||
<p>Complex task flows with conditional execution and state management</p>
|
||||
</div>
|
||||
</div>
|
||||
</Frame>
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class A1,A2,A3 process
|
||||
class Agents transparent
|
||||
```
|
||||
|
||||
### Sequential Process
|
||||
The simplest form of task execution where tasks are performed one after another.
|
||||
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
#### Characteristics
|
||||
- Linear execution flow
|
||||
- Predictable order
|
||||
- Simple dependency management
|
||||
- Direct task progression
|
||||
<Card>
|
||||
### Characteristics
|
||||
- Linear execution flow
|
||||
- Predictable order
|
||||
- Simple dependency management
|
||||
- Direct task progression
|
||||
|
||||
#### Usage
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent1, agent2],
|
||||
tasks=[task1, task2, task3],
|
||||
process="sequential"
|
||||
)
|
||||
```
|
||||
</div>
|
||||
</Frame>
|
||||
### Usage
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent1, agent2],
|
||||
tasks=[task1, task2, task3],
|
||||
process="sequential"
|
||||
)
|
||||
```
|
||||
</Card>
|
||||
|
||||
## Hierarchical Process
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
Input[Input] --> Manager
|
||||
|
||||
subgraph Agents
|
||||
Manager[Manager Agent]
|
||||
|
||||
subgraph Workers
|
||||
direction LR
|
||||
W1[Worker 1]
|
||||
W2[Worker 2]
|
||||
W3[Worker 3]
|
||||
end
|
||||
|
||||
Manager --> W1
|
||||
Manager --> W2
|
||||
Manager --> W3
|
||||
end
|
||||
|
||||
W1 --> Manager
|
||||
W2 --> Manager
|
||||
W3 --> Manager
|
||||
Manager --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Manager,W1,W2,W3 process
|
||||
class Agents,Workers transparent
|
||||
```
|
||||
|
||||
### Hierarchical Process
|
||||
Uses a manager agent to coordinate task execution and agent assignments.
|
||||
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
#### Characteristics
|
||||
- Manager-driven coordination
|
||||
- Dynamic task assignment
|
||||
- Flexible execution order
|
||||
- Intelligent resource allocation
|
||||
<Card>
|
||||
### Characteristics
|
||||
- Manager-driven coordination
|
||||
- Dynamic task assignment
|
||||
- Flexible execution order
|
||||
- Intelligent resource allocation
|
||||
|
||||
#### Configuration
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[manager_agent, worker_agent1, worker_agent2],
|
||||
tasks=[task1, task2],
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
```
|
||||
</div>
|
||||
</Frame>
|
||||
### Configuration
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[manager_agent, worker_agent1, worker_agent2],
|
||||
tasks=[task1, task2],
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
```
|
||||
</Card>
|
||||
|
||||
## Workflow Process
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] --> Start
|
||||
|
||||
subgraph Workflow
|
||||
direction LR
|
||||
Start[Start] --> C1{Condition}
|
||||
C1 --> |Yes| A1[Agent 1]
|
||||
C1 --> |No| A2[Agent 2]
|
||||
A1 --> Join
|
||||
A2 --> Join
|
||||
Join --> A3[Agent 3]
|
||||
end
|
||||
|
||||
A3 --> Output[Output]
|
||||
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
class Input,Output input
|
||||
class Start,A1,A2,A3,Join process
|
||||
class C1 decision
|
||||
class Workflow transparent
|
||||
```
|
||||
|
||||
### Workflow Process
|
||||
Advanced process type supporting complex task relationships and conditional execution.
|
||||
|
||||
<Card>
|
||||
### Features
|
||||
- Task dependencies
|
||||
- Conditional branching
|
||||
- Loop handling
|
||||
- Context sharing
|
||||
- State management
|
||||
|
||||
### Implementation
|
||||
```python
|
||||
task_workflow = {
|
||||
"start_task": {
|
||||
"next": ["decision_task"],
|
||||
"type": "task"
|
||||
},
|
||||
"decision_task": {
|
||||
"type": "decision",
|
||||
"conditions": {
|
||||
"success": ["process_task"],
|
||||
"failure": ["error_task"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</Card>
|
||||
|
||||
## Getting Started
|
||||
|
||||
<Steps>
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent Sequential Process
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create an agent
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o"
|
||||
)
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False,
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
```python Multiple Agents Hierarchical Process
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create multiple agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
name="Writer",
|
||||
role="Tech Content Strategist",
|
||||
goal="Craft compelling content on tech advancements",
|
||||
backstory="You are a content strategist",
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# Define multiple tasks
|
||||
task1 = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="writing_task",
|
||||
description="Create a blog post about AI advancements",
|
||||
expected_output="A blog post",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Run with hierarchical process
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=False,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
</Steps>
|
||||
<br /><br />
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
@@ -111,110 +302,152 @@ Advanced process type supporting complex task relationships and conditional exec
|
||||
</div>
|
||||
<br />
|
||||
|
||||
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
#### Features
|
||||
- Task dependencies
|
||||
- Conditional branching
|
||||
- Loop handling
|
||||
- Context sharing
|
||||
- State management
|
||||
|
||||
#### Implementation
|
||||
```python
|
||||
task_workflow = {
|
||||
"start_task": {
|
||||
"next": ["decision_task"],
|
||||
"type": "task"
|
||||
},
|
||||
"decision_task": {
|
||||
"type": "decision",
|
||||
"conditions": {
|
||||
"success": ["process_task"],
|
||||
"failure": ["error_task"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</div>
|
||||
</Frame>
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### State Management
|
||||
- Task state tracking
|
||||
- Context preservation
|
||||
- Data flow control
|
||||
<CardGroup cols={2}>
|
||||
<Card title="State Management" icon="database" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Task State Tracking">
|
||||
Monitor and manage the progress of each task in real-time
|
||||
</Accordion>
|
||||
<Accordion title="Context Preservation">
|
||||
Maintain important information across different stages of execution
|
||||
</Accordion>
|
||||
<Accordion title="Data Flow Control">
|
||||
Manage how data moves between tasks and agents efficiently
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
|
||||
### Error Handling
|
||||
- Graceful failure recovery
|
||||
- Alternative path execution
|
||||
- Error reporting
|
||||
<Card title="Error Handling" icon="shield-check" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Graceful Recovery">
|
||||
Automatically handle failures and continue execution
|
||||
</Accordion>
|
||||
<Accordion title="Alternative Paths">
|
||||
Switch to backup plans when primary execution fails
|
||||
</Accordion>
|
||||
<Accordion title="Error Reporting">
|
||||
Detailed error logs and diagnostic information
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
|
||||
### Monitoring
|
||||
- Progress tracking
|
||||
- Performance metrics
|
||||
- Resource utilization
|
||||
<Card title="Monitoring" icon="chart-line" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Progress Tracking">
|
||||
Real-time visibility into task completion status
|
||||
</Accordion>
|
||||
<Accordion title="Performance Metrics">
|
||||
Measure execution time and resource efficiency
|
||||
</Accordion>
|
||||
<Accordion title="Resource Usage">
|
||||
Monitor system resource utilization
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
|
||||
### Integration
|
||||
- External system coordination
|
||||
- API synchronization
|
||||
- Event handling
|
||||
<Card title="Integration" icon="plug" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="External Systems">
|
||||
Connect with other services and platforms
|
||||
</Accordion>
|
||||
<Accordion title="API Sync">
|
||||
Maintain data consistency across systems
|
||||
</Accordion>
|
||||
<Accordion title="Event Handling">
|
||||
React to system and external events
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Async Process Execution
|
||||
All process types (sequential, workflow, hierarchical) support async execution through async generators. This enables efficient handling of async tasks and parallel processing.
|
||||
## Async Processing
|
||||
|
||||
### Async Process Methods
|
||||
- `asequential`: Async version of sequential process
|
||||
- `aworkflow`: Async version of workflow process
|
||||
- `ahierarchical`: Async version of hierarchical process
|
||||
<Note>
|
||||
All process types support asynchronous execution through async generators, enabling efficient parallel processing and non-blocking operations.
|
||||
</Note>
|
||||
|
||||
### Example Usage:
|
||||
### Core Async Methods
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
<CardGroup cols={3}>
|
||||
<Card title="asequential" icon="arrow-right">
|
||||
Async version of sequential process for non-blocking linear execution
|
||||
</Card>
|
||||
<Card title="aworkflow" icon="diagram-project">
|
||||
Async workflow process for complex parallel task execution
|
||||
</Card>
|
||||
<Card title="ahierarchical" icon="sitemap">
|
||||
Async hierarchical process for distributed task management
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
async def main():
|
||||
# Create agents and tasks
|
||||
agents = [async_agent1, async_agent2]
|
||||
tasks = [async_task1, async_task2]
|
||||
### Process-Specific Features
|
||||
|
||||
# Initialize PraisonAIAgents with async workflow
|
||||
agents = PraisonAIAgents(
|
||||
agents=agents,
|
||||
tasks=tasks,
|
||||
process="workflow" # or "sequential" or "hierarchical"
|
||||
)
|
||||
<Tabs>
|
||||
<Tab title="Sequential Process">
|
||||
<Card>
|
||||
- Tasks execute in order but don't block
|
||||
- Maintains sequence while allowing async operations
|
||||
- Perfect for I/O-heavy tasks
|
||||
```python
|
||||
async def main():
|
||||
agents = PraisonAIAgents(
|
||||
process="sequential",
|
||||
async_mode=True
|
||||
)
|
||||
await agents.astart()
|
||||
```
|
||||
</Card>
|
||||
</Tab>
|
||||
|
||||
<Tab title="Workflow Process">
|
||||
<Card>
|
||||
- Parallel execution of independent tasks
|
||||
- Async branching and merging
|
||||
- Dynamic task scheduling based on conditions
|
||||
```python
|
||||
async def main():
|
||||
agents = PraisonAIAgents(
|
||||
process="workflow",
|
||||
async_mode=True,
|
||||
parallel_tasks=True
|
||||
)
|
||||
await agents.astart()
|
||||
```
|
||||
</Card>
|
||||
</Tab>
|
||||
|
||||
<Tab title="Hierarchical Process">
|
||||
<Card>
|
||||
- Async manager delegation
|
||||
- Parallel subtask execution
|
||||
- Dynamic worker assignment
|
||||
```python
|
||||
async def main():
|
||||
agents = PraisonAIAgents(
|
||||
process="hierarchical",
|
||||
async_mode=True,
|
||||
dynamic_assignment=True
|
||||
)
|
||||
await agents.astart()
|
||||
```
|
||||
</Card>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
# Start async execution
|
||||
result = await agents.astart()
|
||||
print(result)
|
||||
### Key Benefits
|
||||
|
||||
# Run the async workflow
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### Async Process Features:
|
||||
- Parallel task execution in workflow
|
||||
- Async task delegation in hierarchical process
|
||||
- Non-blocking task execution
|
||||
- Efficient resource utilization
|
||||
- Mixed sync/async task support
|
||||
|
||||
### Process-Specific Async Behavior:
|
||||
1. **Sequential Process**:
|
||||
- Tasks are executed in order
|
||||
- Async tasks don't block other tasks
|
||||
- Maintains sequential order while allowing async execution
|
||||
|
||||
2. **Workflow Process**:
|
||||
- Parallel execution of independent tasks
|
||||
- Async branching and merging
|
||||
- Dynamic task scheduling
|
||||
|
||||
3. **Hierarchical Process**:
|
||||
- Async manager delegation
|
||||
- Parallel subtask execution
|
||||
- Dynamic task assignment
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Performance" icon="bolt">
|
||||
- Efficient resource utilization
|
||||
- Reduced waiting time
|
||||
- Better throughput
|
||||
</Card>
|
||||
|
||||
<Card title="Flexibility" icon="puzzle-piece">
|
||||
- Mix sync and async tasks
|
||||
- Adaptable execution patterns
|
||||
- Easy scaling
|
||||
</Card>
|
||||
</CardGroup>
|
||||
+391
-178
@@ -4,117 +4,36 @@ description: "Understanding Tasks in PraisonAI"
|
||||
icon: "list-check"
|
||||
---
|
||||
|
||||
<Note>
|
||||
Tasks are the fundamental units of work in PraisonAI, defining what needs to be done, how it should be done, and who should do it.
|
||||
</Note>
|
||||
|
||||
# Understanding Tasks
|
||||
Tasks are units of work that agents execute. Each task has a clear goal, input requirements, and expected outputs.
|
||||
|
||||
<Frame>
|
||||
<div className="p-6 bg-white dark:bg-gray-800 rounded-lg">
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
{/* Task Flow Steps */}
|
||||
<div className="flex justify-between items-center">
|
||||
{/* Task Definition */}
|
||||
<div className="flex-1 p-4 border-2 border-blue-500 rounded-lg text-center">
|
||||
<div className="flex items-center justify-center mb-2">
|
||||
<div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-full">
|
||||
<svg className="w-6 h-6 text-blue-600 dark:text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h4 className="font-semibold">Task Definition</h4>
|
||||
<p className="text-sm mt-1">Description & Requirements</p>
|
||||
</div>
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Input] ---> Task
|
||||
|
||||
subgraph Task
|
||||
direction LR
|
||||
Role[Role]
|
||||
Goal[Goal]
|
||||
Story[Backstory]
|
||||
Expected[Expected Output]
|
||||
|
||||
Role --> Goal
|
||||
Goal --> Story
|
||||
Story --> Expected
|
||||
end
|
||||
|
||||
Task ---> Output[Output]
|
||||
|
||||
{/* Arrow 1 */}
|
||||
<div className="flex-none px-4">
|
||||
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
|
||||
</svg>
|
||||
</div>
|
||||
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
|
||||
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
|
||||
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
|
||||
classDef transparent fill:none,stroke:none
|
||||
|
||||
{/* Agent Assignment */}
|
||||
<div className="flex-1 p-4 border-2 border-green-500 rounded-lg text-center">
|
||||
<div className="flex items-center justify-center mb-2">
|
||||
<div className="p-2 bg-green-100 dark:bg-green-900 rounded-full">
|
||||
<svg className="w-6 h-6 text-green-600 dark:text-green-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h4 className="font-semibold">Agent Assignment</h4>
|
||||
<p className="text-sm mt-1">Matching & Delegation</p>
|
||||
</div>
|
||||
|
||||
{/* Arrow 2 */}
|
||||
<div className="flex-none px-4">
|
||||
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Execution */}
|
||||
<div className="flex-1 p-4 border-2 border-purple-500 rounded-lg text-center">
|
||||
<div className="flex items-center justify-center mb-2">
|
||||
<div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-full">
|
||||
<svg className="w-6 h-6 text-purple-600 dark:text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h4 className="font-semibold">Execution</h4>
|
||||
<p className="text-sm mt-1">Processing & Tools</p>
|
||||
</div>
|
||||
|
||||
{/* Arrow 3 */}
|
||||
<div className="flex-none px-4">
|
||||
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Output */}
|
||||
<div className="flex-1 p-4 border-2 border-yellow-500 rounded-lg text-center">
|
||||
<div className="flex items-center justify-center mb-2">
|
||||
<div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-full">
|
||||
<svg className="w-6 h-6 text-yellow-600 dark:text-yellow-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h4 className="font-semibold">Output</h4>
|
||||
<p className="text-sm mt-1">Results & Validation</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Task States */}
|
||||
<div className="grid grid-cols-4 gap-4 mt-4">
|
||||
<div className="p-3 border border-gray-200 rounded-lg bg-blue-50 dark:bg-blue-900">
|
||||
<div className="flex items-center justify-center">
|
||||
<span className="font-semibold">Pending</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 border border-gray-200 rounded-lg bg-yellow-50 dark:bg-yellow-900">
|
||||
<div className="flex items-center justify-center">
|
||||
<span className="font-semibold">In Progress</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 border border-gray-200 rounded-lg bg-green-50 dark:bg-green-900">
|
||||
<div className="flex items-center justify-center">
|
||||
<span className="font-semibold">Completed</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 border border-gray-200 rounded-lg bg-red-50 dark:bg-red-900">
|
||||
<div className="flex items-center justify-center">
|
||||
<span className="font-semibold">Failed</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Frame>
|
||||
class Input,Output input
|
||||
class Role,Goal,Story,Expected process
|
||||
class Task transparent
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
@@ -155,6 +74,79 @@ icon: "list-check"
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
# Understanding Tasks
|
||||
<br />
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Task Flow Steps
|
||||
Start([▶ Start]) --> TaskDef
|
||||
TaskDef --> AgentAssign
|
||||
AgentAssign --> Exec
|
||||
Exec --> Output([✓ Output])
|
||||
|
||||
%% Define subgraphs for each step
|
||||
subgraph TaskDef[" "]
|
||||
TD_Icon[📋 Task Definition]
|
||||
TD_Desc[Description & Requirements]
|
||||
|
||||
TD_Icon --- TD_Desc
|
||||
|
||||
style TD_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style TD_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph AgentAssign[" "]
|
||||
AA_Icon[🤖 Agent Assignment]
|
||||
AA_Desc[Matching & Delegation]
|
||||
|
||||
AA_Icon --- AA_Desc
|
||||
|
||||
style AA_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AA_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Exec[" "]
|
||||
E_Icon[⚙️ Execution]
|
||||
E_Desc[Processing & Tools]
|
||||
|
||||
E_Icon --- E_Desc
|
||||
|
||||
style E_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style E_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Style for containers
|
||||
style TaskDef fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style AgentAssign fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Exec fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
<br /><br />
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Task States
|
||||
Pending([📥 Pending]) --> InProgress([⚡ In Progress])
|
||||
InProgress --> Completed([✅ Completed])
|
||||
InProgress --> Failed([❌ Failed])
|
||||
|
||||
%% Styling
|
||||
style Pending fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style InProgress fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Completed fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Failed fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
|
||||
## Task Types
|
||||
|
||||
<Steps>
|
||||
@@ -223,17 +215,300 @@ task_b = Task(
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Getting Started
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent">
|
||||
Create `app.py`:
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create an agent
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o"
|
||||
)
|
||||
|
||||
# Define a task
|
||||
task = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
verbose=False
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create multiple agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Senior Research Analyst",
|
||||
goal="Uncover cutting-edge developments in AI",
|
||||
backstory="You are an expert at a technology research group",
|
||||
verbose=True,
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
name="Writer",
|
||||
role="Tech Content Strategist",
|
||||
goal="Craft compelling content on tech advancements",
|
||||
backstory="You are a content strategist",
|
||||
llm="gpt-4o",
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# Define multiple tasks
|
||||
task1 = Task(
|
||||
name="research_task",
|
||||
description="Analyze 2024's AI advancements",
|
||||
expected_output="A detailed report",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
name="writing_task",
|
||||
description="Create a blog post about AI advancements",
|
||||
expected_output="A blog post",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Run with hierarchical process
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=False,
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<Tip>
|
||||
Design tasks to be atomic and focused. Each task should have a single, clear responsibility.
|
||||
</Tip>
|
||||
<Note>
|
||||
Design tasks to be atomic and focused. Each task should have a single, clear responsibility.
|
||||
</Note>
|
||||
|
||||
1. Clear task descriptions
|
||||
2. Well-defined success criteria
|
||||
3. Appropriate tool selection
|
||||
4. Error handling consideration
|
||||
5. Resource management
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Task Design Principles" icon="compass-drafting" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Clear Task Descriptions">
|
||||
Write precise, unambiguous task descriptions that clearly state the task's purpose and requirements.
|
||||
```python
|
||||
task = Task(
|
||||
description=(
|
||||
"Analyze Q4 2024 sales data "
|
||||
"and generate growth metrics"
|
||||
),
|
||||
expected_output="Sales growth report"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Success Criteria">
|
||||
Define measurable success criteria to ensure task completion can be properly evaluated.
|
||||
```python
|
||||
task = Task(
|
||||
success_criteria={
|
||||
"format": "markdown",
|
||||
"metrics": [
|
||||
"growth_rate",
|
||||
"revenue_change"
|
||||
],
|
||||
"min_confidence": 0.95
|
||||
}
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task Dependencies">
|
||||
Specify any dependencies or prerequisites for the task.
|
||||
```python
|
||||
task = Task(
|
||||
description="Generate final report",
|
||||
dependencies=[
|
||||
data_collection_task,
|
||||
analysis_task
|
||||
],
|
||||
wait_for_dependencies=True
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
|
||||
<Card title="Resource Management" icon="server" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Tool Selection">
|
||||
Choose appropriate tools that match your task's requirements.
|
||||
```python
|
||||
task = Task(
|
||||
tools=[
|
||||
DataAnalyzer(),
|
||||
ReportGenerator(),
|
||||
MetricsCalculator()
|
||||
],
|
||||
tool_config={
|
||||
"timeout": 30,
|
||||
"retry": True
|
||||
}
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Error Handling">
|
||||
Implement comprehensive error management strategies.
|
||||
```python
|
||||
task = Task(
|
||||
error_strategy="retry",
|
||||
max_retries=3,
|
||||
fallback_handler=handler,
|
||||
error_callbacks=[
|
||||
log_error,
|
||||
notify_admin
|
||||
]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Resource Limits">
|
||||
Set appropriate resource constraints for optimal performance.
|
||||
```python
|
||||
task = Task(
|
||||
memory_limit="2GB",
|
||||
timeout=300,
|
||||
max_concurrent=5,
|
||||
cpu_priority="high",
|
||||
auto_scale=True
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Performance Monitoring">
|
||||
Configure monitoring and logging for task execution.
|
||||
```python
|
||||
task = Task(
|
||||
monitoring={
|
||||
"metrics": ["duration", "memory", "cpu"],
|
||||
"log_level": "INFO",
|
||||
"trace_enabled": True,
|
||||
"alert_threshold": 0.85
|
||||
}
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Async Task Execution
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Async Task Features" icon="bolt" iconType="solid">
|
||||
<Tabs>
|
||||
<Tab title="Basic Configuration">
|
||||
```python
|
||||
async_task = Task(
|
||||
description="Perform async operation",
|
||||
expected_output="Async result",
|
||||
agent=async_agent,
|
||||
async_execution=True, # Enable async execution
|
||||
callback=async_callback # Optional async callback
|
||||
)
|
||||
```
|
||||
- Enable async execution with `async_execution=True`
|
||||
- Perfect for I/O-heavy operations
|
||||
- Supports parallel task execution
|
||||
</Tab>
|
||||
|
||||
<Tab title="Async Callbacks">
|
||||
```python
|
||||
async def async_callback(output: TaskOutput):
|
||||
await asyncio.sleep(1) # Simulate async operation
|
||||
print(f"Processed output: {output.raw}")
|
||||
|
||||
task = Task(
|
||||
description="Task with async callback",
|
||||
expected_output="Result",
|
||||
agent=agent,
|
||||
async_execution=True,
|
||||
callback=async_callback
|
||||
)
|
||||
```
|
||||
- Support for async callbacks
|
||||
- Process results asynchronously
|
||||
- Handle task completion events
|
||||
</Tab>
|
||||
|
||||
<Tab title="Mixed Execution">
|
||||
```python
|
||||
# Create mixed task types
|
||||
sync_task = Task(
|
||||
description="Synchronous operation",
|
||||
async_execution=False
|
||||
)
|
||||
|
||||
async_task = Task(
|
||||
description="Asynchronous operation",
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
# Run with mixed execution
|
||||
agents = PraisonAIAgents(
|
||||
agents=[sync_agent, async_agent],
|
||||
tasks=[sync_task, async_task]
|
||||
)
|
||||
result = await agents.astart()
|
||||
```
|
||||
- Mix sync and async tasks
|
||||
- Flexible execution patterns
|
||||
- Optimal resource utilization
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
**Pro Tip**: Use async execution for tasks that involve I/O operations (like API calls or file operations) to improve overall performance. Keep CPU-intensive tasks synchronous.
|
||||
</Tip>
|
||||
|
||||
## Next Steps
|
||||
|
||||
@@ -252,66 +527,4 @@ task_b = Task(
|
||||
>
|
||||
Explore the complete Task API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Async Task Execution
|
||||
Tasks can be executed asynchronously by setting `async_execution=True`. This is particularly useful for tasks that involve I/O operations or when you want to run multiple tasks in parallel.
|
||||
|
||||
### Async Task Configuration
|
||||
```python
|
||||
async_task = Task(
|
||||
description="Perform async operation",
|
||||
expected_output="Async result",
|
||||
agent=async_agent,
|
||||
async_execution=True, # Enable async execution
|
||||
callback=async_callback # Optional async callback
|
||||
)
|
||||
```
|
||||
|
||||
### Async Callbacks
|
||||
Tasks support both synchronous and asynchronous callbacks:
|
||||
|
||||
```python
|
||||
async def async_callback(output: TaskOutput):
|
||||
await asyncio.sleep(1) # Simulate async operation
|
||||
print(f"Processed output: {output.raw}")
|
||||
|
||||
# Task with async callback
|
||||
task = Task(
|
||||
description="Task with async callback",
|
||||
expected_output="Result",
|
||||
agent=agent,
|
||||
async_execution=True,
|
||||
callback=async_callback
|
||||
)
|
||||
```
|
||||
|
||||
### Mixing Sync and Async Tasks
|
||||
You can mix synchronous and asynchronous tasks in the same workflow:
|
||||
|
||||
```python
|
||||
# Sync task
|
||||
sync_task = Task(
|
||||
description="Synchronous operation",
|
||||
expected_output="Sync result",
|
||||
agent=sync_agent,
|
||||
async_execution=False
|
||||
)
|
||||
|
||||
# Async task
|
||||
async_task = Task(
|
||||
description="Asynchronous operation",
|
||||
expected_output="Async result",
|
||||
agent=async_agent,
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
# Create agents with mixed tasks
|
||||
agents = PraisonAIAgents(
|
||||
agents=[sync_agent, async_agent],
|
||||
tasks=[sync_task, async_task]
|
||||
)
|
||||
|
||||
# Run asynchronously
|
||||
result = await agents.astart()
|
||||
```
|
||||
</CardGroup>
|
||||
+538
-226
@@ -1,54 +1,49 @@
|
||||
---
|
||||
title: "Tools"
|
||||
description: "Understanding Tools in PraisonAI"
|
||||
title: "AI Agents with Tools"
|
||||
sidebarTitle: "Tools"
|
||||
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Understanding Tools
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Tools
|
||||
direction TB
|
||||
T3[Internet Search]
|
||||
T1[Code Execution]
|
||||
T2[Formatting]
|
||||
end
|
||||
|
||||
Tools in PraisonAI are functions that agents can use to interact with external systems, perform computations, or access data. They extend the capabilities of agents beyond just language processing.
|
||||
Input[Input] ---> Agents
|
||||
subgraph Agents
|
||||
direction LR
|
||||
A1[Agent 1]
|
||||
A2[Agent 2]
|
||||
A3[Agent 3]
|
||||
end
|
||||
Agents ---> Output[Output]
|
||||
|
||||
## Tools Overview
|
||||
T3 --> A1
|
||||
T1 --> A2
|
||||
T2 --> A3
|
||||
|
||||
<Frame>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
|
||||
<svg className="w-6 h-6 text-blue-600 dark:text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-lg font-semibold">Search Tools</h3>
|
||||
</div>
|
||||
<p>Tools for searching and retrieving information from various sources</p>
|
||||
</div>
|
||||
style Tools fill:#189AB4,color:#fff
|
||||
style Agents fill:#8B0000,color:#fff
|
||||
style Input fill:#8B0000,color:#fff
|
||||
style Output fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
|
||||
<svg className="w-6 h-6 text-green-600 dark:text-green-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-lg font-semibold">File Tools</h3>
|
||||
</div>
|
||||
<p>Tools for reading, writing, and manipulating files</p>
|
||||
</div>
|
||||
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|
||||
|---------|--------------------------------|---------------------------|
|
||||
| Purpose | Static reference information | Dynamic interaction capabilities |
|
||||
| Access | Read-only reference | Execute actions and commands |
|
||||
| Updates | Manual through files | Real-time through tool calls |
|
||||
| Storage | Knowledge base | Assigned to specific agents |
|
||||
| Persistence | Permanent until changed | Available during agent execution |
|
||||
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<div className="flex items-center mb-4">
|
||||
<div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
|
||||
<svg className="w-6 h-6 text-purple-600 dark:text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="ml-3 text-lg font-semibold">API Tools</h3>
|
||||
</div>
|
||||
<p>Tools for interacting with external APIs and services</p>
|
||||
</div>
|
||||
</div>
|
||||
</Frame>
|
||||
## Quick Start
|
||||
|
||||
Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.
|
||||
|
||||
## Creating Custom Tool
|
||||
<Steps>
|
||||
@@ -99,237 +94,554 @@ Assign the tool to an agent
|
||||
</Card>
|
||||
|
||||
## Implementing Tools Full Code Example
|
||||
<Tabs>
|
||||
|
||||
Tools are implemented as Python functions with type hints and docstrings. Here's a complete example:
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents duckduckgo-search
|
||||
```
|
||||
</Step>
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
# 1. Tool Implementation
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search using DuckDuckGo
|
||||
<Step title="Create Agent with Tool">
|
||||
Create `app.py`
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool Implementation
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search using DuckDuckGo
|
||||
|
||||
Args:
|
||||
query (str): The search query string
|
||||
|
||||
Args:
|
||||
query (str): The search query string
|
||||
|
||||
Returns:
|
||||
List[Dict]: List of search results containing title, URL, and snippet
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
Returns:
|
||||
List[Dict]: List of search results containing title, URL, and snippet
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Assign the tool to an agent
|
||||
data_agent = Agent(
|
||||
name="DataCollector",
|
||||
role="Search Specialist",
|
||||
goal="Perform internet searches to collect relevant information.",
|
||||
backstory="Expert in finding and organising internet data.",
|
||||
tools=[internet_search_tool],
|
||||
self_reflect=False
|
||||
)
|
||||
# 2. Assign the tool to an agent
|
||||
data_agent = Agent(
|
||||
name="DataCollector",
|
||||
role="Search Specialist",
|
||||
goal="Perform internet searches to collect relevant information.",
|
||||
backstory="Expert in finding and organising internet data.",
|
||||
tools=[internet_search_tool],
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# 3. Task Definition
|
||||
collect_task = Task(
|
||||
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
|
||||
expected_output="List of search results with titles, URLs, and snippets.",
|
||||
agent=data_agent,
|
||||
name="collect_data",
|
||||
)
|
||||
# 3. Task Definition
|
||||
collect_task = Task(
|
||||
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
|
||||
expected_output="List of search results with titles, URLs, and snippets.",
|
||||
agent=data_agent,
|
||||
name="collect_data",
|
||||
)
|
||||
|
||||
# 4. Start Agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[data_agent],
|
||||
tasks=[collect_task],
|
||||
process="sequential"
|
||||
)
|
||||
# 4. Start Agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[data_agent],
|
||||
tasks=[collect_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
agents.start()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package and duckduckgo_search package:
|
||||
```bash Terminal
|
||||
pip install praisonai duckduckgo_search
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Custom Tool">
|
||||
<Info>
|
||||
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
|
||||
</Info>
|
||||
Create a new file `tools.py` with the following content:
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Agent">
|
||||
|
||||
Create a new file `agents.yaml` with the following content:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
topic: create movie script about cat in mars
|
||||
roles:
|
||||
scriptwriter:
|
||||
backstory: Expert in dialogue and script structure, translating concepts into
|
||||
scripts.
|
||||
goal: Write a movie script about a cat in Mars
|
||||
role: Scriptwriter
|
||||
tools:
|
||||
- internet_search_tool # <-- Tool assigned to Agent here
|
||||
tasks:
|
||||
scriptwriting_task:
|
||||
description: Turn the story concept into a production-ready movie script,
|
||||
including dialogue and scene details.
|
||||
expected_output: Final movie script with dialogue and scene details.
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## In-build Tools in PraisonAI
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Search Tools" icon="magnifying-glass" href="/tools/search">
|
||||
Tools for searching and retrieving information from various sources
|
||||
</Card>
|
||||
<Card title="Python Tools" icon="python" href="/tools/python_tools">
|
||||
Essential Python utilities for data manipulation and scripting
|
||||
</Card>
|
||||
<Card title="Spider Tools" icon="spider" href="/tools/spider_tools">
|
||||
Web crawling and scraping capabilities for data extraction
|
||||
</Card>
|
||||
<Card title="Arxiv Tools" icon="book" href="/tools/arxiv_tools">
|
||||
Access and search academic papers from arXiv repository
|
||||
</Card>
|
||||
<Card title="Newspaper Tools" icon="newspaper" href="/tools/newspaper_tools">
|
||||
Extract and parse content from news articles and websites
|
||||
</Card>
|
||||
<Card title="DuckDB Tools" icon="database" href="/tools/duckdb_tools">
|
||||
Fast analytical SQL database operations and queries
|
||||
</Card>
|
||||
<Card title="DuckDuckGo Tools" icon="duck" href="/tools/duckduckgo_tools">
|
||||
Web search functionality using DuckDuckGo's API
|
||||
</Card>
|
||||
<Card title="Calculator Tools" icon="calculator" href="/tools/calculator_tools">
|
||||
Perform mathematical calculations and conversions
|
||||
</Card>
|
||||
<Card title="YAML Tools" icon="file-code" href="/tools/yaml_tools">
|
||||
Parse and manipulate YAML format data
|
||||
</Card>
|
||||
<Card title="JSON Tools" icon="brackets-curly" href="/tools/json_tools">
|
||||
Handle JSON data structures and operations
|
||||
</Card>
|
||||
<Card title="Pandas Tools" icon="table" href="/tools/pandas_tools">
|
||||
Data analysis and manipulation using Pandas
|
||||
</Card>
|
||||
<Card title="YFinance Tools" icon="chart-line" href="/tools/yfinance_tools">
|
||||
Fetch financial market data from Yahoo Finance
|
||||
</Card>
|
||||
<Card title="Shell Tools" icon="terminal" href="/tools/shell_tools">
|
||||
Execute shell commands and system operations
|
||||
</Card>
|
||||
<Card title="Wikipedia Tools" icon="book-open" href="/tools/wikipedia_tools">
|
||||
Access and search Wikipedia articles and data
|
||||
</Card>
|
||||
<Card title="XML Tools" icon="code" href="/tools/xml_tools">
|
||||
Process and manipulate XML format data
|
||||
</Card>
|
||||
<Card title="File Tools" icon="file" href="/tools/file_tools">
|
||||
File system operations and management utilities
|
||||
</Card>
|
||||
<Card title="Excel Tools" icon="file-excel" href="/tools/excel_tools">
|
||||
Work with Excel spreadsheets and workbooks
|
||||
</Card>
|
||||
<Card title="CSV Tools" icon="file-csv" href="/tools/csv_tools">
|
||||
Handle CSV file operations and transformations
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Tools Overview
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card
|
||||
title="Search Tools"
|
||||
icon="magnifying-glass"
|
||||
iconType="solid"
|
||||
>
|
||||
Tools for searching and retrieving information from various sources
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="File Tools"
|
||||
icon="file"
|
||||
iconType="solid"
|
||||
>
|
||||
Tools for reading, writing, and manipulating files
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="API Tools"
|
||||
icon="code"
|
||||
iconType="solid"
|
||||
>
|
||||
Tools for interacting with external APIs and services
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Tool Features
|
||||
|
||||
### Tool Configuration
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
```python
|
||||
def configured_tool(
|
||||
query: str,
|
||||
max_results: int = 5,
|
||||
timeout: int = 10
|
||||
) -> List[Dict]:
|
||||
"""
|
||||
Example of a configurable tool
|
||||
```python
|
||||
def configured_tool(
|
||||
query: str,
|
||||
max_results: int = 5,
|
||||
timeout: int = 10
|
||||
) -> List[Dict]:
|
||||
"""
|
||||
Example of a configurable tool
|
||||
|
||||
Args:
|
||||
query (str): Search query
|
||||
max_results (int): Maximum number of results
|
||||
timeout (int): Request timeout in seconds
|
||||
|
||||
Args:
|
||||
query (str): Search query
|
||||
max_results (int): Maximum number of results
|
||||
timeout (int): Request timeout in seconds
|
||||
|
||||
Returns:
|
||||
List[Dict]: Search results
|
||||
"""
|
||||
# Tool implementation
|
||||
pass
|
||||
```
|
||||
</div>
|
||||
Returns:
|
||||
List[Dict]: Search results
|
||||
"""
|
||||
# Tool implementation
|
||||
pass
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Chaining
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
```python
|
||||
def chain_tools(input_data: str) -> Dict:
|
||||
"""
|
||||
Example of chaining multiple tools
|
||||
```python
|
||||
def chain_tools(input_data: str) -> Dict:
|
||||
"""
|
||||
Example of chaining multiple tools
|
||||
|
||||
Args:
|
||||
input_data (str): Input data
|
||||
|
||||
Args:
|
||||
input_data (str): Input data
|
||||
|
||||
Returns:
|
||||
Dict: Processed results
|
||||
"""
|
||||
# 1. Search for data
|
||||
search_results = internet_search_tool(input_data)
|
||||
|
||||
# 2. Process results
|
||||
processed_data = process_tool(search_results)
|
||||
|
||||
# 3. Format output
|
||||
return format_tool(processed_data)
|
||||
```
|
||||
</div>
|
||||
Returns:
|
||||
Dict: Processed results
|
||||
"""
|
||||
# 1. Search for data
|
||||
search_results = internet_search_tool(input_data)
|
||||
|
||||
# 2. Process results
|
||||
processed_data = process_tool(search_results)
|
||||
|
||||
# 3. Format output
|
||||
return format_tool(processed_data)
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Categories
|
||||
|
||||
1. **Data Collection Tools**
|
||||
- Web scraping
|
||||
- API integration
|
||||
- Database queries
|
||||
|
||||
2. **Processing Tools**
|
||||
- Data transformation
|
||||
- Text analysis
|
||||
- Image processing
|
||||
|
||||
3. **Output Tools**
|
||||
- File generation
|
||||
- Report creation
|
||||
- Data visualization
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Data Collection Tools">
|
||||
- Web scraping
|
||||
- API integration
|
||||
- Database queries
|
||||
</Card>
|
||||
|
||||
<Card title="Processing Tools">
|
||||
- Data transformation
|
||||
- Text analysis
|
||||
- Image processing
|
||||
</Card>
|
||||
|
||||
<Card title="Output Tools">
|
||||
- File generation
|
||||
- Report creation
|
||||
- Data visualization
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Tool Integration
|
||||
|
||||
### Adding Tools to Agents
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
```python
|
||||
# Multiple tools
|
||||
agent = Agent(
|
||||
name="MultiTool Agent",
|
||||
tools=[
|
||||
internet_search_tool,
|
||||
file_processing_tool,
|
||||
api_integration_tool
|
||||
]
|
||||
)
|
||||
```
|
||||
</div>
|
||||
```python
|
||||
# Multiple tools
|
||||
agent = Agent(
|
||||
name="MultiTool Agent",
|
||||
tools=[
|
||||
internet_search_tool,
|
||||
file_processing_tool,
|
||||
api_integration_tool
|
||||
]
|
||||
)
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Dependencies
|
||||
<Frame>
|
||||
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
|
||||
```python
|
||||
# Tool with dependencies
|
||||
def advanced_tool(data: Dict) -> Dict:
|
||||
"""
|
||||
Tool that depends on external libraries
|
||||
```python
|
||||
# Tool with dependencies
|
||||
def advanced_tool(data: Dict) -> Dict:
|
||||
"""
|
||||
Tool that depends on external libraries
|
||||
|
||||
Args:
|
||||
data (Dict): Input data
|
||||
|
||||
Args:
|
||||
data (Dict): Input data
|
||||
|
||||
Returns:
|
||||
Dict: Processed data
|
||||
"""
|
||||
try:
|
||||
import required_library
|
||||
# Tool implementation
|
||||
return processed_result
|
||||
except ImportError:
|
||||
raise Exception("Required library not installed")
|
||||
```
|
||||
</div>
|
||||
Returns:
|
||||
Dict: Processed data
|
||||
"""
|
||||
try:
|
||||
import required_library
|
||||
# Tool implementation
|
||||
return processed_result
|
||||
except ImportError:
|
||||
raise Exception("Required library not installed")
|
||||
```
|
||||
</Frame>
|
||||
|
||||
## Tool Guidelines
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<h3 className="text-lg font-semibold mb-3">Best Practices</h3>
|
||||
1. **Type Hints**
|
||||
- Use Python type hints
|
||||
- Define clear input/output types
|
||||
- Document complex types
|
||||
|
||||
2. **Documentation**
|
||||
- Write clear docstrings
|
||||
- Explain parameters
|
||||
- Provide usage examples
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Best Practices">
|
||||
1. **Type Hints**
|
||||
- Use Python type hints
|
||||
- Define clear input/output types
|
||||
- Document complex types
|
||||
|
||||
3. **Error Handling**
|
||||
- Handle exceptions gracefully
|
||||
- Return meaningful errors
|
||||
- Validate inputs
|
||||
</div>
|
||||
2. **Documentation**
|
||||
- Write clear docstrings
|
||||
- Explain parameters
|
||||
- Provide usage examples
|
||||
|
||||
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
|
||||
<h3 className="text-lg font-semibold mb-3">Tool Types</h3>
|
||||
1. **Search Tools**
|
||||
- Web search
|
||||
- Database queries
|
||||
- Document search
|
||||
3. **Error Handling**
|
||||
- Handle exceptions gracefully
|
||||
- Return meaningful errors
|
||||
- Validate inputs
|
||||
</Card>
|
||||
|
||||
2. **File Tools**
|
||||
- Read/write operations
|
||||
- File conversion
|
||||
- Data extraction
|
||||
<Card title="Tool Types">
|
||||
1. **Search Tools**
|
||||
- Web search
|
||||
- Database queries
|
||||
- Document search
|
||||
|
||||
3. **API Tools**
|
||||
- REST API calls
|
||||
- GraphQL queries
|
||||
- Service integration
|
||||
</div>
|
||||
</div>
|
||||
2. **File Tools**
|
||||
- Read/write operations
|
||||
- File conversion
|
||||
- Data extraction
|
||||
|
||||
3. **API Tools**
|
||||
- REST API calls
|
||||
- GraphQL queries
|
||||
- Service integration
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices Summary
|
||||
|
||||
1. **Design Principles**
|
||||
- Single responsibility
|
||||
- Clear interfaces
|
||||
- Proper documentation
|
||||
- Error handling
|
||||
<Note>
|
||||
Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.
|
||||
</Note>
|
||||
|
||||
2. **Performance**
|
||||
- Efficient processing
|
||||
- Resource management
|
||||
- Caching when appropriate
|
||||
- Asynchronous operations
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Design Principles" icon="compass-drafting" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Single Responsibility">
|
||||
Each tool should have one clear purpose and do it well. Avoid creating tools that try to do too many things.
|
||||
```python
|
||||
# Good Example
|
||||
def process_image(image: np.array) -> np.array:
|
||||
return processed_image
|
||||
|
||||
3. **Security**
|
||||
- Input validation
|
||||
- Rate limiting
|
||||
- API key management
|
||||
- Error masking
|
||||
# Avoid
|
||||
def process_and_save_and_upload(image):
|
||||
# Too many responsibilities
|
||||
pass
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Clear Interfaces">
|
||||
Define explicit input/output types and maintain consistent parameter naming.
|
||||
```python
|
||||
def search_tool(
|
||||
query: str,
|
||||
max_results: int = 10
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Search for information with clear parameters
|
||||
"""
|
||||
pass
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Documentation">
|
||||
Always include detailed docstrings and type hints.
|
||||
```python
|
||||
def analyze_text(
|
||||
text: str,
|
||||
language: str = "en"
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Analyze text sentiment and emotions.
|
||||
|
||||
Args:
|
||||
text: Input text to analyze
|
||||
language: ISO language code
|
||||
|
||||
Returns:
|
||||
Dict with sentiment scores
|
||||
"""
|
||||
pass
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<br />
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Performance Optimization" icon="bolt" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Efficient Processing">
|
||||
Optimize resource usage and processing time.
|
||||
```python
|
||||
# Use generators for large datasets
|
||||
def process_large_data():
|
||||
for chunk in data_generator():
|
||||
yield process_chunk(chunk)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Resource Management">
|
||||
Properly handle resource allocation and cleanup.
|
||||
```python
|
||||
async with aiohttp.ClientSession() as session:
|
||||
# Resource automatically managed
|
||||
await process_data(session)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Caching">
|
||||
Implement caching for frequently accessed data.
|
||||
```python
|
||||
@cache.memoize(timeout=300)
|
||||
def expensive_operation(data: str) -> Dict:
|
||||
return process_expensive(data)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Async Operations">
|
||||
Use async/await for I/O-bound operations.
|
||||
```python
|
||||
async def fetch_data(urls: List[str]):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
tasks = [fetch_url(session, url) for url in urls]
|
||||
return await asyncio.gather(*tasks)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<br />
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Security Best Practices" icon="shield-check" iconType="solid">
|
||||
<AccordionGroup>
|
||||
<Accordion title="Input Validation">
|
||||
Always validate and sanitize inputs to prevent security vulnerabilities.
|
||||
```python
|
||||
def process_user_input(data: str) -> str:
|
||||
if not isinstance(data, str):
|
||||
raise ValueError("Input must be string")
|
||||
return sanitize_input(data.strip())
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Rate Limiting">
|
||||
Implement rate limiting for API calls to prevent abuse.
|
||||
```python
|
||||
@rate_limit(calls=100, period=60)
|
||||
async def api_call():
|
||||
return await make_request()
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="API Key Management">
|
||||
Securely handle API keys and credentials using environment variables.
|
||||
```python
|
||||
# Use environment variables
|
||||
api_key = os.getenv('API_KEY')
|
||||
if not api_key:
|
||||
raise ConfigError("API key not found")
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Error Masking">
|
||||
Hide sensitive information in error messages to prevent information leakage.
|
||||
```python
|
||||
try:
|
||||
result = process_sensitive_data()
|
||||
except Exception as e:
|
||||
# Log detailed error internally
|
||||
logger.error(f"Detailed error: {str(e)}")
|
||||
# Return sanitized error to user
|
||||
raise PublicError("Processing failed")
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<br />
|
||||
|
||||
<Tip>
|
||||
**Pro Tip**: Start with these practices from the beginning of your project. It's easier to maintain good practices than to retrofit them later.
|
||||
</Tip>
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
title: "Introduction to AI Agents"
|
||||
description: "Welcome to the beginner's course on AI Agents"
|
||||
icon: "book-open"
|
||||
---
|
||||
|
||||
# Introduction to AI Agents
|
||||
|
||||
Welcome to the beginners' course on AI Agents! This course is designed to help you understand and build your own AI agents, even if you have little to no programming experience.
|
||||
|
||||
## What Are AI Agents?
|
||||
|
||||
An AI agent is a software program that can:
|
||||
- Understand information from its environment
|
||||
- Make decisions based on that information
|
||||
- Take actions to achieve specific goals
|
||||
|
||||
Think of an AI agent like a helpful assistant that can perform tasks for you automatically.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Perceive Information] --> B[Make Decisions]
|
||||
B --> C[Take Actions]
|
||||
C --> A
|
||||
```
|
||||
|
||||
## Examples in Daily Life
|
||||
|
||||
You might already be using AI agents without realizing it:
|
||||
|
||||
- **Virtual Assistants**: Siri, Alexa, and Google Assistant are AI agents that respond to your voice commands
|
||||
- **Recommendation Systems**: Netflix, YouTube, and Amazon use AI agents to suggest content you might like
|
||||
- **Smart Home Devices**: Devices that adjust temperature or lighting based on your preferences
|
||||
|
||||
## What You'll Learn in This Course
|
||||
|
||||
Throughout this course, you will:
|
||||
|
||||
1. Understand the basic concepts of AI agents
|
||||
2. Learn about different types of AI agents
|
||||
3. Explore how AI agents make decisions
|
||||
4. Discover how to build simple AI agents without complex programming
|
||||
5. Create your own functional AI agents
|
||||
|
||||
## Who This Course Is For
|
||||
|
||||
This course is perfect for:
|
||||
- Complete beginners with no prior knowledge of AI
|
||||
- Non-technical professionals interested in how AI can solve problems
|
||||
- Students curious about artificial intelligence
|
||||
- Anyone who wants to understand and use AI agents in practical ways
|
||||
|
||||
Let's begin our journey into the fascinating world of AI agents!
|
||||
<iframe
|
||||
id="codeExecutionFrame"
|
||||
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
|
||||
width="100%"
|
||||
height="600px"
|
||||
frameborder="0"
|
||||
allow="clipboard-read; clipboard-write"
|
||||
scrolling="yes"
|
||||
onload="resizeIframe(this)"
|
||||
></iframe>
|
||||
|
||||
<IframeWithAutoHeight />
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Ready to Start?" icon="rocket">
|
||||
Continue to the next lesson to learn about the different types of AI agents.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,113 @@
|
||||
---
|
||||
title: "Types of AI Agents"
|
||||
description: "Understanding the different categories of AI agents"
|
||||
icon: "sitemap"
|
||||
---
|
||||
|
||||
# Types of AI Agents
|
||||
|
||||
AI agents come in different forms, each designed for specific purposes and with varying levels of complexity. Understanding these types will help you choose the right approach for your needs.
|
||||
|
||||
## Simple Reflex Agents
|
||||
|
||||
These are the most basic type of AI agents that operate using simple if-then rules.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="lightbulb">
|
||||
- React directly to current input only
|
||||
- No memory of past events
|
||||
- No prediction of future states
|
||||
- Use predefined rules to determine actions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: A basic thermostat that turns heating on when temperature drops below a set point.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Sensor Input] --> B{If-Then Rules}
|
||||
B --> C[Action]
|
||||
```
|
||||
|
||||
## Model-Based Agents
|
||||
|
||||
These agents maintain an internal model of their environment to make better decisions.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="brain">
|
||||
- Build and maintain an internal representation of the world
|
||||
- Can work with partial information
|
||||
- Can consider "what if" scenarios
|
||||
- Make decisions based on their understanding of how the world works
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: A GPS navigation system that models roads and traffic conditions.
|
||||
|
||||
## Goal-Based Agents
|
||||
|
||||
These agents make decisions based on how their actions will help achieve specific goals.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="bullseye">
|
||||
- Consider future consequences of actions
|
||||
- Evaluate which actions will lead toward goals
|
||||
- Can plan sequences of actions
|
||||
- Choose actions that maximize goal attainment
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: A chess-playing AI that plans moves to achieve checkmate.
|
||||
|
||||
## Utility-Based Agents
|
||||
|
||||
These agents choose actions that maximize a specific utility (or happiness) function.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="chart-line">
|
||||
- Assign a utility value to different possible outcomes
|
||||
- Consider probability and risk
|
||||
- Choose actions that maximize expected utility
|
||||
- Can balance competing objectives
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: An investment robo-advisor that balances risk and return.
|
||||
|
||||
## Learning Agents
|
||||
|
||||
These agents improve their performance over time through experience.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Key Characteristics" icon="graduation-cap">
|
||||
- Learn from past experiences
|
||||
- Adapt to changing environments
|
||||
- Improve decision-making over time
|
||||
- Can discover new strategies
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**Real-world example**: Recommendation systems that learn your preferences over time.
|
||||
|
||||
## Understanding Agent Complexity
|
||||
|
||||
<Tip>
|
||||
As you move from Simple Reflex Agents toward Learning Agents, both capability and complexity increase. For beginners, starting with simpler agent types is often best.
|
||||
</Tip>
|
||||
|
||||
## Which Agent Type Should You Build?
|
||||
|
||||
The best type of agent for your project depends on:
|
||||
|
||||
1. **The problem complexity**: Simple problems may only need reflex agents
|
||||
2. **Available data**: Learning agents need training data
|
||||
3. **Required adaptability**: Will your agent need to adapt to new situations?
|
||||
4. **Available resources**: More complex agents require more computational power
|
||||
|
||||
In this course, we'll focus primarily on goal-based and simple learning agents as they provide a good balance of capability and complexity for beginners.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Next Steps" icon="arrow-right">
|
||||
In the next lesson, we'll explore how agents process information and make decisions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,157 @@
|
||||
---
|
||||
title: "Agent Architecture"
|
||||
description: "Understanding how AI agents are structured"
|
||||
icon: "layer-group"
|
||||
---
|
||||
|
||||
# Agent Architecture
|
||||
|
||||
Understanding how AI agents are structured will help you build more effective agents. This lesson covers the fundamental components of an agent's architecture.
|
||||
|
||||
## Basic Components of an AI Agent
|
||||
|
||||
Every AI agent, regardless of complexity, has these basic components:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Sensors/Input] --> B[Processing Unit]
|
||||
B --> C[Decision-Making]
|
||||
C --> D[Actions/Output]
|
||||
```
|
||||
|
||||
### 1. Input (Sensors)
|
||||
|
||||
This is how agents receive information from their environment.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Examples of Input" icon="eye">
|
||||
- Text input from users
|
||||
- Data from databases
|
||||
- Image or audio input
|
||||
- API responses
|
||||
- Sensor readings (in physical agents)
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 2. Processing Unit
|
||||
|
||||
This component processes information and converts it into a format the agent can understand.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Processing Functions" icon="gears">
|
||||
- Data cleaning and transformation
|
||||
- Feature extraction
|
||||
- Context building
|
||||
- Information retrieval
|
||||
- Pattern recognition
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 3. Decision-Making Core
|
||||
|
||||
The "brain" of the agent that determines what actions to take.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Decision Components" icon="brain">
|
||||
- Language models (like GPT-4)
|
||||
- Rule systems
|
||||
- Planning algorithms
|
||||
- Knowledge base
|
||||
- Memory systems
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 4. Output (Actions)
|
||||
|
||||
The actions the agent can perform to achieve its goals.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Action Examples" icon="hand">
|
||||
- Generating text responses
|
||||
- Creating visual content
|
||||
- Making API calls
|
||||
- Controlling other systems
|
||||
- Updating databases
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## The Agent Loop
|
||||
|
||||
Agents operate in a continuous loop:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Perceive] --> B[Process]
|
||||
B --> C[Decide]
|
||||
C --> D[Act]
|
||||
D --> A
|
||||
```
|
||||
|
||||
This cycle allows agents to continuously:
|
||||
1. Gather information
|
||||
2. Update their understanding
|
||||
3. Make new decisions
|
||||
4. Take appropriate actions
|
||||
|
||||
## PraisonAI Agent Architecture
|
||||
|
||||
In the PraisonAI framework, agents follow a specific architecture:
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="PraisonAI Agent Components" icon="puzzle-piece">
|
||||
- **Instructions**: Defines the agent's purpose and behavior
|
||||
- **Language Model**: Powers the agent's intelligence (e.g., GPT-4)
|
||||
- **Memory**: Stores context and previous interactions
|
||||
- **Tools**: Specialized capabilities an agent can use
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Simple Agent Structure
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a simple agent
|
||||
research_agent = Agent(
|
||||
instructions="Research the latest developments in renewable energy",
|
||||
name="ResearchAgent"
|
||||
)
|
||||
|
||||
# Start the agent
|
||||
research_agent.start()
|
||||
```
|
||||
|
||||
## Understanding Agent Communication
|
||||
|
||||
Multi-agent systems allow agents to communicate with each other:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent 1] --> B[Agent 2]
|
||||
B --> C[Agent 3]
|
||||
C --> A
|
||||
```
|
||||
|
||||
Each agent can:
|
||||
- Pass information to other agents
|
||||
- Request assistance from specialized agents
|
||||
- Collaborate on complex tasks
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Component Importance" icon="check">
|
||||
Each component plays a vital role in the agent's functionality
|
||||
</Card>
|
||||
<Card title="Agent Customization" icon="gear">
|
||||
You can customize each component based on your specific needs
|
||||
</Card>
|
||||
<Card title="Component Balance" icon="scale-balanced">
|
||||
A well-designed agent balances all components effectively
|
||||
</Card>
|
||||
<Card title="Continuous Improvement" icon="arrow-trend-up">
|
||||
Agents can be improved by enhancing individual components
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to define effective instructions for your AI agents.
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: "Creating Effective Agent Instructions"
|
||||
description: "How to write clear instructions for your AI agents"
|
||||
icon: "file-lines"
|
||||
---
|
||||
|
||||
# Creating Effective Agent Instructions
|
||||
|
||||
The instructions you give to your AI agent are crucial to its performance. Well-crafted instructions lead to agents that understand their purpose and execute tasks effectively.
|
||||
|
||||
## Why Instructions Matter
|
||||
|
||||
Instructions serve as the agent's "job description" and guide its behavior:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clarity" icon="glasses">
|
||||
Clear instructions reduce confusion and misinterpretation
|
||||
</Card>
|
||||
<Card title="Focus" icon="bullseye">
|
||||
Specific instructions keep the agent on task
|
||||
</Card>
|
||||
<Card title="Boundaries" icon="border-all">
|
||||
Good instructions define what an agent should and shouldn't do
|
||||
</Card>
|
||||
<Card title="Personality" icon="face-smile">
|
||||
Instructions can shape how an agent communicates
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Elements of Effective Instructions
|
||||
|
||||
### 1. Role Definition
|
||||
|
||||
Tell the agent who it is and what its expertise should be.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
You are a financial analyst with expertise in market trends and investment strategies.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
You are a helper.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 2. Purpose and Goals
|
||||
|
||||
Clearly state what the agent should accomplish.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
Your goal is to analyze company quarterly reports and provide actionable investment insights.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
Help with finance stuff.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 3. Process Guidelines
|
||||
|
||||
Explain how the agent should approach tasks.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
First analyze the data trends, then identify key risk factors, and finally make recommendations based on the client's risk tolerance.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
Just do a good analysis.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 4. Response Format
|
||||
|
||||
Specify how you want information presented.
|
||||
|
||||
<CodeGroup>
|
||||
```text Good Example
|
||||
Present your analysis in a structured format with: Summary, Key Findings, Risk Assessment, and Recommendations.
|
||||
```
|
||||
|
||||
```text Weak Example
|
||||
Tell me what you find.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Instructions Template
|
||||
|
||||
Here's a template you can use to create effective agent instructions:
|
||||
|
||||
```
|
||||
You are a [ROLE] specializing in [EXPERTISE AREAS].
|
||||
|
||||
Your goal is to [MAIN OBJECTIVE].
|
||||
|
||||
When approaching tasks:
|
||||
1. [FIRST STEP/APPROACH]
|
||||
2. [SECOND STEP/APPROACH]
|
||||
3. [THIRD STEP/APPROACH]
|
||||
|
||||
Present your results in [FORMAT PREFERENCES].
|
||||
|
||||
Additional guidelines:
|
||||
- [SPECIFIC BEHAVIOR 1]
|
||||
- [SPECIFIC BEHAVIOR 2]
|
||||
- [SPECIFIC BEHAVIOR 3]
|
||||
```
|
||||
|
||||
## Examples in PraisonAI
|
||||
|
||||
Let's look at how instructions are implemented in PraisonAI:
|
||||
|
||||
<CodeGroup>
|
||||
```python Simple Example
|
||||
from praisonaiagents import Agent
|
||||
|
||||
research_agent = Agent(
|
||||
instructions="You are a research assistant specializing in climate science. Your goal is to find the latest research on rising sea levels and summarize key findings in bullet points."
|
||||
)
|
||||
|
||||
research_agent.start()
|
||||
```
|
||||
|
||||
```python Detailed Example
|
||||
from praisonaiagents import Agent
|
||||
|
||||
content_agent = Agent(
|
||||
name="ContentCreator",
|
||||
instructions="""
|
||||
You are a content creation specialist with expertise in digital marketing.
|
||||
|
||||
Your goal is to create engaging blog content that drives traffic and conversions.
|
||||
|
||||
When creating content:
|
||||
1. Research the target keyword thoroughly
|
||||
2. Create an attention-grabbing headline
|
||||
3. Develop well-structured content with clear sections
|
||||
4. Include actionable takeaways for readers
|
||||
|
||||
Present content in markdown format with proper headings, bullet points, and emphasis where appropriate.
|
||||
|
||||
Additional guidelines:
|
||||
- Maintain a conversational but professional tone
|
||||
- Include 2-3 relevant statistics to support key points
|
||||
- Add a call-to-action at the end of each piece
|
||||
"""
|
||||
)
|
||||
|
||||
content_agent.start("Create a blog post about sustainable living tips")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Common Instruction Mistakes
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Being Too Vague" icon="cloud">
|
||||
Vague instructions lead to unpredictable outputs
|
||||
</Card>
|
||||
<Card title="Information Overload" icon="bomb">
|
||||
Too many details can confuse the agent's priorities
|
||||
</Card>
|
||||
<Card title="Contradictory Guidelines" icon="arrows-split-up-and-left">
|
||||
Conflicting instructions create confusion
|
||||
</Card>
|
||||
<Card title="Missing Context" icon="puzzle-piece-missing">
|
||||
Insufficient background information leads to generic outputs
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Refining Your Instructions
|
||||
|
||||
<Tip>
|
||||
Good instructions often require iteration. Start with basic instructions, review the agent's performance, and refine as needed.
|
||||
</Tip>
|
||||
|
||||
Effective instruction improvement follows this cycle:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Write Initial Instructions] --> B[Test Agent Performance]
|
||||
B --> C[Identify Issues/Gaps]
|
||||
C --> D[Refine Instructions]
|
||||
D --> B
|
||||
```
|
||||
|
||||
In the next lesson, we'll explore how agents use tools to extend their capabilities.
|
||||
@@ -0,0 +1,183 @@
|
||||
---
|
||||
title: "Agent Tools"
|
||||
description: "Understanding how tools extend agent capabilities"
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Agent Tools
|
||||
|
||||
Tools allow AI agents to interact with the world and perform specific actions. Think of tools as the "hands" of your agent that let it accomplish tasks beyond just generating text.
|
||||
|
||||
## What Are Agent Tools?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="toolbox">
|
||||
Tools are functions or capabilities that agents can access to perform specific actions, retrieve information, or interact with external systems.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
Just as humans use tools to extend their physical abilities, AI agents use digital tools to extend their capabilities.
|
||||
|
||||
## Why Tools Matter
|
||||
|
||||
Tools transform agents from simple chat interfaces into powerful assistants that can:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Access Information" icon="database">
|
||||
Retrieve data from various sources
|
||||
</Card>
|
||||
<Card title="Perform Calculations" icon="calculator">
|
||||
Analyze numbers and data accurately
|
||||
</Card>
|
||||
<Card title="Create Content" icon="pen-to-square">
|
||||
Generate images, code, or other media
|
||||
</Card>
|
||||
<Card title="Control Systems" icon="gears">
|
||||
Interact with other software or hardware
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Common Types of Tools
|
||||
|
||||
### 1. Information Retrieval Tools
|
||||
|
||||
These tools help agents access information beyond their training data.
|
||||
|
||||
**Examples:**
|
||||
- Web search tools
|
||||
- Database query tools
|
||||
- Document retrieval tools
|
||||
|
||||
```python
|
||||
# Example of a simple web search tool
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def web_search(query):
|
||||
# Simplified example
|
||||
return f"Results for: {query}"
|
||||
|
||||
agent = Agent(
|
||||
instructions="Research assistant",
|
||||
tools=[web_search]
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Computation Tools
|
||||
|
||||
These tools perform calculations or data processing.
|
||||
|
||||
**Examples:**
|
||||
- Calculator tools
|
||||
- Data analysis tools
|
||||
- Conversion tools
|
||||
|
||||
### 3. Content Creation Tools
|
||||
|
||||
These tools help generate or modify various types of content.
|
||||
|
||||
**Examples:**
|
||||
- Image generation tools
|
||||
- Code writing tools
|
||||
- Document formatting tools
|
||||
|
||||
### 4. External API Tools
|
||||
|
||||
These tools connect to third-party services.
|
||||
|
||||
**Examples:**
|
||||
- Weather API tools
|
||||
- Translation API tools
|
||||
- E-commerce API tools
|
||||
|
||||
## How Tools Work in PraisonAI
|
||||
|
||||
In the PraisonAI framework, tools follow a simple pattern:
|
||||
|
||||
1. Tools are defined as functions
|
||||
2. Tools are registered with an agent
|
||||
3. The agent decides when to use appropriate tools
|
||||
4. Tool results are incorporated into the agent's reasoning
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Agent Receives Task] --> B{Needs a Tool?}
|
||||
B -->|Yes| C[Select Appropriate Tool]
|
||||
C --> D[Execute Tool]
|
||||
D --> E[Process Tool Results]
|
||||
E --> F[Continue Task]
|
||||
B -->|No| F
|
||||
```
|
||||
|
||||
## Creating Basic Tools
|
||||
|
||||
Here's a simple example of creating and using tools in PraisonAI:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Define a simple calculator tool
|
||||
def calculator(expression):
|
||||
try:
|
||||
return str(eval(expression))
|
||||
except:
|
||||
return "Error: Could not calculate"
|
||||
|
||||
# Create an agent with the tool
|
||||
math_agent = Agent(
|
||||
instructions="You are a math tutor helping students solve problems",
|
||||
tools=[calculator]
|
||||
)
|
||||
|
||||
# Use the agent
|
||||
math_agent.start("Calculate 24 * 17 and explain the steps")
|
||||
```
|
||||
|
||||
## Tool Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Descriptions" icon="comment">
|
||||
Provide detailed descriptions so the agent knows when to use each tool
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="shield">
|
||||
Make tools robust with proper error handling
|
||||
</Card>
|
||||
<Card title="Focused Purpose" icon="bullseye">
|
||||
Each tool should do one thing well
|
||||
</Card>
|
||||
<Card title="Input Validation" icon="check-double">
|
||||
Validate inputs to prevent misuse
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Building a Toolbox
|
||||
|
||||
As you advance, you'll want to create a collection of tools your agent can use:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tool
|
||||
|
||||
# Define multiple tools
|
||||
def weather(location):
|
||||
return f"Weather in {location}: Sunny, 75°F"
|
||||
|
||||
def translator(text, target_language):
|
||||
return f"Translated to {target_language}: {text} (placeholder)"
|
||||
|
||||
def reminder(message, time):
|
||||
return f"Reminder set for {time}: {message}"
|
||||
|
||||
# Create tool collection
|
||||
tools = [
|
||||
Tool(name="weather", function=weather, description="Get weather for a location"),
|
||||
Tool(name="translator", function=translator, description="Translate text"),
|
||||
Tool(name="reminder", function=reminder, description="Set a reminder")
|
||||
]
|
||||
|
||||
# Create agent with multiple tools
|
||||
assistant = Agent(
|
||||
instructions="You are a helpful personal assistant",
|
||||
tools=tools
|
||||
)
|
||||
```
|
||||
|
||||
In the next lesson, we'll explore how agents use memory to maintain context across interactions.
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
title: "Agent Memory"
|
||||
description: "Understanding how agents maintain context and learn"
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
# Agent Memory
|
||||
|
||||
Memory enables AI agents to remember past interactions, maintain context, and provide more coherent responses over time. Without memory, agents would treat each interaction as if it was their first.
|
||||
|
||||
## Why Memory Matters
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Context Awareness" icon="comments">
|
||||
Remembers previous parts of a conversation
|
||||
</Card>
|
||||
<Card title="Personalization" icon="user-gear">
|
||||
Recalls user preferences and history
|
||||
</Card>
|
||||
<Card title="Continuous Learning" icon="graduation-cap">
|
||||
Builds on past experiences
|
||||
</Card>
|
||||
<Card title="Task Persistence" icon="list-check">
|
||||
Maintains progress on long-running tasks
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Types of Agent Memory
|
||||
|
||||
### 1. Short-Term Memory (Conversation Memory)
|
||||
|
||||
This type of memory stores recent interactions within a session.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[User Input 1] --> B[Agent Response 1]
|
||||
B --> C[User Input 2]
|
||||
C --> D[Agent Response 2]
|
||||
D --> E[User Input 3]
|
||||
```
|
||||
|
||||
The agent can refer back to earlier messages in the same conversation.
|
||||
|
||||
### 2. Long-Term Memory
|
||||
|
||||
This allows agents to remember information across different sessions.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Use Cases" icon="clock">
|
||||
- Remembering user preferences
|
||||
- Recalling previous tasks completed
|
||||
- Storing learned information
|
||||
- Maintaining relationship history
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 3. Working Memory
|
||||
|
||||
This is where agents process current information and combine it with retrieved memories.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Current Input] --> D[Working Memory]
|
||||
B[Short-Term Memory] --> D
|
||||
C[Long-Term Memory] --> D
|
||||
D --> E[Agent Response]
|
||||
```
|
||||
|
||||
## How Memory Works in PraisonAI
|
||||
|
||||
In the PraisonAI framework, memory is handled automatically for basic cases and can be customized for more advanced needs:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Basic agent with default memory handling
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant that remembers our conversations"
|
||||
)
|
||||
|
||||
# The conversation history is maintained automatically
|
||||
agent.start("My name is Alex")
|
||||
agent.continue("What's my name?")# Note: TODO: This Feature yet to be developed # Agent will remember "Alex"
|
||||
```
|
||||
|
||||
## Memory Limitations
|
||||
|
||||
<Tip>
|
||||
All AI memories have limitations. They aren't perfect and may occasionally forget or misremember information.
|
||||
</Tip>
|
||||
|
||||
Common limitations include:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Memory Capacity" icon="database">
|
||||
Limit to how much information can be stored
|
||||
</Card>
|
||||
<Card title="Context Window" icon="window">
|
||||
Only a portion of memory fits in the active context
|
||||
</Card>
|
||||
<Card title="Memory Decay" icon="hourglass-half">
|
||||
Older memories may become less accessible
|
||||
</Card>
|
||||
<Card title="Memory Retrieval" icon="magnifying-glass">
|
||||
Finding the right memory at the right time
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Implementing Persistent Memory
|
||||
|
||||
For more advanced applications, you can implement custom memory systems:
|
||||
|
||||
```python
|
||||
# Note: TODO: This Feature yet to be tested
|
||||
from praisonaiagents import Agent, Memory
|
||||
|
||||
# Create a simple memory store
|
||||
memory = Memory()
|
||||
|
||||
# Add information to memory
|
||||
memory.add("user_name", "Alex")
|
||||
memory.add("favorite_color", "blue")
|
||||
|
||||
# Create agent with this memory
|
||||
agent = Agent(
|
||||
instructions="You are a personal assistant",
|
||||
memory=memory
|
||||
)
|
||||
|
||||
# The agent can now access these memories
|
||||
agent.start("What's my favorite color?") # Agent should respond "blue"
|
||||
```
|
||||
|
||||
## Memory Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prioritize Important Info" icon="star">
|
||||
Not everything needs to be remembered
|
||||
</Card>
|
||||
<Card title="Verify When Uncertain" icon="question">
|
||||
Have agents confirm uncertain memories
|
||||
</Card>
|
||||
<Card title="Structured Storage" icon="folder-tree">
|
||||
Organize memories by categories
|
||||
</Card>
|
||||
<Card title="Regular Updates" icon="arrows-rotate">
|
||||
Update memories when information changes
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Memory in Multi-Agent Systems
|
||||
|
||||
In systems with multiple agents, memory can be:
|
||||
|
||||
1. **Private**: Each agent has its own memories
|
||||
2. **Shared**: Agents have access to a common memory store
|
||||
3. **Hybrid**: Some memories are private, others are shared
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Agent 1] --> B[Private Memory 1]
|
||||
C[Agent 2] --> D[Private Memory 2]
|
||||
A -.-> E[Shared Memory]
|
||||
C -.-> E
|
||||
```
|
||||
|
||||
In the next lesson, we'll learn about how to set up multiple agents to work together effectively.
|
||||
@@ -0,0 +1,171 @@
|
||||
---
|
||||
title: "Multi-Agent Systems"
|
||||
description: "How multiple agents can work together"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
# Multi-Agent Systems
|
||||
|
||||
Multi-agent systems allow multiple AI agents to work together, each handling different parts of a complex task. This approach mirrors how human teams collaborate, with each member contributing their specialized skills.
|
||||
|
||||
## Why Use Multiple Agents?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Specialization" icon="star">
|
||||
Each agent can focus on its area of expertise
|
||||
</Card>
|
||||
<Card title="Complex Tasks" icon="puzzle-piece">
|
||||
Break down difficult problems into manageable pieces
|
||||
</Card>
|
||||
<Card title="Scalability" icon="arrows-up-down">
|
||||
Add more agents as tasks become more complex
|
||||
</Card>
|
||||
<Card title="Diverse Perspectives" icon="lightbulb">
|
||||
Different agents can approach problems differently
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Basic Multi-Agent Architecture
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Research Agent] --> B[Analysis Agent]
|
||||
B --> C[Writing Agent]
|
||||
C --> D[Final Output]
|
||||
```
|
||||
|
||||
In this example:
|
||||
1. The Research Agent gathers information
|
||||
2. The Analysis Agent processes and interprets the data
|
||||
3. The Writing Agent creates the final content
|
||||
|
||||
## Multi-Agent Patterns
|
||||
|
||||
### 1. Pipeline Pattern
|
||||
|
||||
Agents work in sequence, with each agent handling a specific stage of the process.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent 1] --> B[Agent 2]
|
||||
B --> C[Agent 3]
|
||||
```
|
||||
|
||||
**Example Use Case**: Content creation where one agent researches, another drafts, and a third edits.
|
||||
|
||||
### 2. Expert Panel Pattern
|
||||
|
||||
Multiple specialist agents work in parallel on the same problem, then their outputs are combined.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Task --> A[Expert Agent 1]
|
||||
Task --> B[Expert Agent 2]
|
||||
Task --> C[Expert Agent 3]
|
||||
A --> D[Coordination Agent]
|
||||
B --> D
|
||||
C --> D
|
||||
D --> Result
|
||||
```
|
||||
|
||||
**Example Use Case**: Financial analysis where different experts analyze market trends, economic indicators, and company performance.
|
||||
|
||||
### 3. Hierarchical Pattern
|
||||
|
||||
A manager agent delegates tasks to worker agents and coordinates their efforts.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Manager Agent] --> B[Worker Agent 1]
|
||||
A --> C[Worker Agent 2]
|
||||
A --> D[Worker Agent 3]
|
||||
B --> A
|
||||
C --> A
|
||||
D --> A
|
||||
```
|
||||
|
||||
**Example Use Case**: Project management where a coordinator assigns tasks and integrates results.
|
||||
|
||||
## Implementing Multi-Agent Systems in PraisonAI
|
||||
|
||||
Here's a simple example of creating a multi-agent system:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Create individual agents
|
||||
research_agent = Agent(
|
||||
name="Researcher",
|
||||
instructions="Research the latest trends in renewable energy"
|
||||
)
|
||||
|
||||
analysis_agent = Agent(
|
||||
name="Analyst",
|
||||
instructions="Analyze the research findings and identify key insights"
|
||||
)
|
||||
|
||||
writing_agent = Agent(
|
||||
name="Writer",
|
||||
instructions="Create a clear, engaging report based on the analysis"
|
||||
)
|
||||
|
||||
# Create a multi-agent system
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, analysis_agent, writing_agent]
|
||||
)
|
||||
|
||||
# Start the agents
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Agent Communication
|
||||
|
||||
For agents to work together effectively, they need to communicate. This happens through:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Output Passing" icon="arrow-right">
|
||||
One agent's output becomes another's input
|
||||
</Card>
|
||||
<Card title="Shared Memory" icon="database">
|
||||
Agents can access common information
|
||||
</Card>
|
||||
<Card title="Message Exchange" icon="comments">
|
||||
Agents can send specific messages to each other
|
||||
</Card>
|
||||
<Card title="Coordination Protocols" icon="traffic-light">
|
||||
Rules that determine how agents interact
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Challenges in Multi-Agent Systems
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Coordination" icon="shuffle">
|
||||
Ensuring agents work together smoothly
|
||||
</Card>
|
||||
<Card title="Conflicting Goals" icon="arrows-split-up-and-left">
|
||||
Managing agents with different objectives
|
||||
</Card>
|
||||
<Card title="Information Transfer" icon="exchange">
|
||||
Passing information effectively between agents
|
||||
</Card>
|
||||
<Card title="Resource Management" icon="microchip">
|
||||
Allocating computational resources efficiently
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Designing Effective Multi-Agent Systems
|
||||
|
||||
<Tip>
|
||||
Start simple with just 2-3 agents and a clear workflow before scaling to more complex systems.
|
||||
</Tip>
|
||||
|
||||
Key principles for effective design:
|
||||
|
||||
1. **Clear Role Definition**: Each agent should have a specific and well-defined role
|
||||
2. **Minimized Dependencies**: Reduce complex interdependencies between agents
|
||||
3. **Standardized Communication**: Use consistent formats for information exchange
|
||||
4. **Failure Handling**: Plan for cases where an agent fails to complete its task
|
||||
5. **Performance Monitoring**: Track how well each agent and the overall system performs
|
||||
|
||||
In the next lesson, we'll explore how to create effective agent workflows using the Process component.
|
||||
@@ -0,0 +1,152 @@
|
||||
---
|
||||
title: "Agent Process"
|
||||
description: "Understanding agent workflows and processes"
|
||||
icon: "diagram-project"
|
||||
---
|
||||
|
||||
# Agent Process
|
||||
|
||||
The Process component in AI agent systems defines how agents work together and the flow of information between them. Think of it as the "playbook" that coordinates how agents complete tasks.
|
||||
|
||||
## What is an Agent Process?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="route">
|
||||
A process is a structured workflow that defines the sequence of steps, decision points, and information flow between agents to complete a task.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Process Flow Basics
|
||||
|
||||
A simple process flow might look like this:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Start] --> B[Gather Information]
|
||||
B --> C[Process Information]
|
||||
C --> D[Make Decision]
|
||||
D --> E[Take Action]
|
||||
E --> F[Report Results]
|
||||
```
|
||||
|
||||
Each step could be handled by a different agent or by the same agent in different stages.
|
||||
|
||||
## Types of Process Flows
|
||||
|
||||
### 1. Sequential Process
|
||||
|
||||
Agents work in a straight line, one after another.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Agent 1] --> B[Agent 2]
|
||||
B --> C[Agent 3]
|
||||
C --> D[Complete]
|
||||
```
|
||||
|
||||
**Best for**: Tasks with clear, linear stages
|
||||
|
||||
### 2. Parallel Process
|
||||
|
||||
Multiple agents work simultaneously on different parts of a task.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Start] --> B[Agent 1]
|
||||
A --> C[Agent 2]
|
||||
A --> D[Agent 3]
|
||||
B --> E[Combine Results]
|
||||
C --> E
|
||||
D --> E
|
||||
E --> F[Complete]
|
||||
```
|
||||
|
||||
**Best for**: Tasks that can be broken into independent pieces
|
||||
|
||||
### 3. Conditional Process
|
||||
|
||||
The workflow changes based on decisions or conditions.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Start] --> B{Decision Point}
|
||||
B -->|Condition A| C[Agent 1]
|
||||
B -->|Condition B| D[Agent 2]
|
||||
C --> E[Complete]
|
||||
D --> E
|
||||
```
|
||||
|
||||
**Best for**: Tasks requiring different approaches based on circumstances
|
||||
|
||||
## Implementing Process in PraisonAI
|
||||
|
||||
Here's a simple example of creating a process in PraisonAI:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Process, PraisonAIAgents
|
||||
|
||||
# Create agents
|
||||
research_agent = Agent(
|
||||
name="Researcher",
|
||||
instructions="Research the topic and gather key information about AI"
|
||||
)
|
||||
|
||||
writing_agent = Agent(
|
||||
name="Writer",
|
||||
instructions="Create content based on the research"
|
||||
)
|
||||
|
||||
editing_agent = Agent(
|
||||
name="Editor",
|
||||
instructions="Review and improve the content"
|
||||
)
|
||||
|
||||
# Create the multi-agent system with the process
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, writing_agent, editing_agent],
|
||||
process="hierarchical"
|
||||
)
|
||||
|
||||
# Start the process
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Process Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Step Definitions" icon="list-check">
|
||||
Define exactly what each step should accomplish
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="bug">
|
||||
Include steps for handling unexpected situations
|
||||
</Card>
|
||||
<Card title="Feedback Loops" icon="repeat">
|
||||
Allow agents to request clarification when needed
|
||||
</Card>
|
||||
<Card title="Modular Design" icon="cubes">
|
||||
Create reusable process components
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
Start with simple processes and gradually add complexity as you become more comfortable with the system.
|
||||
</Tip>
|
||||
|
||||
## Monitoring Process Execution
|
||||
|
||||
It's important to track how your processes are running:
|
||||
|
||||
```python
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, writing_agent, editing_agent],
|
||||
process=content_process,
|
||||
verbose=True # Enables detailed logging
|
||||
)
|
||||
```
|
||||
|
||||
This will provide information about:
|
||||
- Which step is currently running
|
||||
- The inputs and outputs of each step
|
||||
- Any errors or issues encountered
|
||||
|
||||
In the next lesson, we'll explore how to use knowledge bases to enhance agent capabilities.
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
title: "Knowledge Bases"
|
||||
description: "Enhancing agents with specialized knowledge"
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
# Knowledge Bases
|
||||
|
||||
Knowledge bases provide agents with specialized information beyond their training data. They help agents answer specific questions, follow guidelines, or work within defined domains.
|
||||
|
||||
## What is a Knowledge Base?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="database">
|
||||
A knowledge base is a structured collection of information that an agent can access to answer questions or make decisions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
Think of a knowledge base as a specialized reference library for your agent.
|
||||
|
||||
## Why Use Knowledge Bases?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Domain Expertise" icon="user-graduate">
|
||||
Provide specialized information for specific fields
|
||||
</Card>
|
||||
<Card title="Current Information" icon="clock">
|
||||
Include data beyond the agent's training cutoff
|
||||
</Card>
|
||||
<Card title="Custom Guidelines" icon="list">
|
||||
Define rules and policies for the agent to follow
|
||||
</Card>
|
||||
<Card title="Consistent Responses" icon="equals">
|
||||
Ensure agents provide standardized answers
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Types of Knowledge Bases
|
||||
|
||||
### 1. Document Collections
|
||||
|
||||
Text documents, articles, guides, or manuals that agents can reference.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Query] --> B[Search Documents]
|
||||
B --> C[Find Relevant Content]
|
||||
C --> D[Generate Response]
|
||||
```
|
||||
|
||||
### 2. Structured Data
|
||||
|
||||
Databases, tables, or other structured formats that organize information systematically.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Examples" icon="table">
|
||||
- Product catalogs with specifications
|
||||
- Customer information databases
|
||||
- Statistical data collections
|
||||
- Reference tables for compliance information
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### 3. Vector Databases
|
||||
|
||||
Special databases that store information as numerical representations (vectors) for semantic search.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[User Question] --> B[Convert to Vector]
|
||||
B --> C[Find Similar Vectors]
|
||||
C --> D[Retrieve Related Information]
|
||||
D --> E[Generate Answer]
|
||||
```
|
||||
|
||||
## Implementing Knowledge Bases in PraisonAI
|
||||
|
||||
Here's an example of how to use a knowledge base with an agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"]
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
For more control over the knowledge base, you can specify a configuration:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"collection_name": "custom_knowledge",
|
||||
"path": ".praison",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
instructions="You answer questions based on the provided knowledge.",
|
||||
knowledge=["small.pdf"],
|
||||
knowledge_config=config
|
||||
)
|
||||
|
||||
agent.start("What is KAG in one line?")
|
||||
```
|
||||
|
||||
## Knowledge Retrieval Process
|
||||
|
||||
When an agent uses a knowledge base, this typical process occurs:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[User Question] --> B[Query Processing]
|
||||
B --> C[Search Knowledge Base]
|
||||
C --> D[Rank Results]
|
||||
D --> E[Synthesize Answer]
|
||||
```
|
||||
|
||||
1. **Query Processing**: The user's question is analyzed
|
||||
2. **Search**: The system searches the knowledge base for relevant information
|
||||
3. **Ranking**: Results are ranked by relevance
|
||||
4. **Synthesis**: The agent creates an answer using the retrieved information
|
||||
|
||||
## Best Practices for Knowledge Bases
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Keep Information Current" icon="arrows-rotate">
|
||||
Regularly update your knowledge base
|
||||
</Card>
|
||||
<Card title="Organize Logically" icon="folder-tree">
|
||||
Structure information in intuitive categories
|
||||
</Card>
|
||||
<Card title="Prioritize Quality" icon="star">
|
||||
Focus on accurate, high-quality information
|
||||
</Card>
|
||||
<Card title="Include Examples" icon="list">
|
||||
Add examples to illustrate complex concepts
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## When to Use Knowledge Bases
|
||||
|
||||
Knowledge bases are particularly valuable when:
|
||||
|
||||
1. Your agent needs to reference specific information that may change over time
|
||||
2. You need to ensure consistent answers to common questions
|
||||
3. Your agent needs to follow specific guidelines or protocols
|
||||
4. You want to provide expertise in specialized domains
|
||||
|
||||
<Tip>
|
||||
Start with a small knowledge base focusing on the most important information, then expand as needed.
|
||||
</Tip>
|
||||
|
||||
## Creating a Simple Knowledge Base
|
||||
|
||||
For beginners, you can start with a simple text-based knowledge base:
|
||||
|
||||
```
|
||||
# Company FAQ Knowledge Base
|
||||
|
||||
## Return Policy
|
||||
Our return policy allows customers to return products within 30 days of purchase for a full refund.
|
||||
|
||||
## Shipping Information
|
||||
Standard shipping takes 3-5 business days. Express shipping takes 1-2 business days.
|
||||
|
||||
## Product Warranty
|
||||
All products come with a 1-year limited warranty covering manufacturing defects.
|
||||
```
|
||||
|
||||
Save this as a text file and add it to your knowledge base:
|
||||
|
||||
```python
|
||||
kb = KnowledgeBase()
|
||||
kb.add_document("company_faq.txt")
|
||||
```
|
||||
|
||||
In the next lesson, we'll explore how agents handle tasks and the task management process.
|
||||
@@ -0,0 +1,274 @@
|
||||
---
|
||||
title: "Agent Tasks"
|
||||
description: "Understanding how agents handle and manage tasks"
|
||||
icon: "clipboard-list"
|
||||
---
|
||||
|
||||
# Agent Tasks
|
||||
|
||||
Tasks are the specific units of work that AI agents perform. Understanding how to define and manage tasks is essential for creating effective agent systems.
|
||||
|
||||
## What is an Agent Task?
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Definition" icon="list-check">
|
||||
A task is a specific, well-defined piece of work assigned to an agent with clear inputs, expected outputs, and success criteria.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
Just as human jobs are broken into specific responsibilities, agent systems work best when complex goals are divided into manageable tasks.
|
||||
|
||||
## Anatomy of a Task
|
||||
|
||||
A well-defined task includes:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Objective" icon="bullseye">
|
||||
What the task should accomplish
|
||||
</Card>
|
||||
<Card title="Inputs" icon="arrow-right-to-bracket">
|
||||
Information provided to complete the task
|
||||
</Card>
|
||||
<Card title="Process" icon="gears">
|
||||
Steps to follow or approach to take
|
||||
</Card>
|
||||
<Card title="Outputs" icon="arrow-right-from-bracket">
|
||||
Expected results or deliverables
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Task Types
|
||||
|
||||
### 1. Information Tasks
|
||||
|
||||
These tasks involve finding, analyzing, or summarizing information.
|
||||
|
||||
**Examples:**
|
||||
- Research a topic
|
||||
- Summarize a document
|
||||
- Extract data from text
|
||||
- Answer questions
|
||||
|
||||
### 2. Creation Tasks
|
||||
|
||||
These tasks involve generating new content.
|
||||
|
||||
**Examples:**
|
||||
- Write an article
|
||||
- Create a marketing plan
|
||||
- Generate images (with appropriate tools)
|
||||
- Design a workflow
|
||||
|
||||
### 3. Analysis Tasks
|
||||
|
||||
These tasks involve evaluating information and drawing conclusions.
|
||||
|
||||
**Examples:**
|
||||
- Analyze data trends
|
||||
- Review content for quality
|
||||
- Evaluate options
|
||||
- Identify patterns
|
||||
|
||||
### 4. Interaction Tasks
|
||||
|
||||
These tasks involve communicating or working with users or other systems.
|
||||
|
||||
**Examples:**
|
||||
- Answer customer questions
|
||||
- Guide users through processes
|
||||
- Collect information from users
|
||||
- Notify about events
|
||||
|
||||
## Creating Tasks in PraisonAI
|
||||
|
||||
### Task Flow
|
||||
|
||||
The typical lifecycle of a task follows this pattern:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Define Task] --> B[Assign to Agent]
|
||||
B --> C[Execute Task]
|
||||
C --> D[Return Results]
|
||||
D --> E[Evaluate Success]
|
||||
```
|
||||
|
||||
### Task Configuration
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
task = Task(
|
||||
description="Research AI trends",
|
||||
expected_output="Summary report",
|
||||
agent=research_agent
|
||||
)
|
||||
```
|
||||
```python Advanced
|
||||
task = Task(
|
||||
description="Analyze market data",
|
||||
expected_output="Detailed analysis",
|
||||
agent=analyst_agent,
|
||||
tools=[AnalysisTool()],
|
||||
output_file="analysis.md",
|
||||
async_execution=True
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
# Understanding Tasks
|
||||
<br />
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Task Flow Steps
|
||||
Start([▶ Start]) --> TaskDef
|
||||
TaskDef --> AgentAssign
|
||||
AgentAssign --> Exec
|
||||
Exec --> Output([✓ Output])
|
||||
|
||||
%% Define subgraphs for each step
|
||||
subgraph TaskDef[" "]
|
||||
TD_Icon[📋 Task Definition]
|
||||
TD_Desc[Description & Requirements]
|
||||
|
||||
TD_Icon --- TD_Desc
|
||||
|
||||
style TD_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style TD_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph AgentAssign[" "]
|
||||
AA_Icon[🤖 Agent Assignment]
|
||||
AA_Desc[Matching & Delegation]
|
||||
|
||||
AA_Icon --- AA_Desc
|
||||
|
||||
style AA_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style AA_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
subgraph Exec[" "]
|
||||
E_Icon[⚙️ Execution]
|
||||
E_Desc[Processing & Tools]
|
||||
|
||||
E_Icon --- E_Desc
|
||||
|
||||
style E_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style E_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
end
|
||||
|
||||
%% Styling for main elements
|
||||
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Style for containers
|
||||
style TaskDef fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style AgentAssign fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
style Exec fill:#1B1F3B,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
<br /><br />
|
||||
```mermaid
|
||||
graph LR
|
||||
%% Task States
|
||||
Pending([📥 Pending]) --> InProgress([⚡ In Progress])
|
||||
InProgress --> Completed([✅ Completed])
|
||||
InProgress --> Failed([❌ Failed])
|
||||
|
||||
%% Styling
|
||||
style Pending fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style InProgress fill:#5C80BC,stroke:#7C90A0,color:#fff
|
||||
style Completed fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
style Failed fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
|
||||
%% Global styles
|
||||
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
|
||||
linkStyle default stroke:#7C90A0,stroke-width:2px
|
||||
```
|
||||
|
||||
## Task Types
|
||||
|
||||
<Steps>
|
||||
<Step title="Basic Task">
|
||||
Simple, single-operation tasks with clear inputs and outputs
|
||||
</Step>
|
||||
<Step title="Decision Task">
|
||||
Tasks involving choices and conditional paths
|
||||
```python
|
||||
decision_task = Task(
|
||||
type="decision",
|
||||
conditions={
|
||||
"success": ["next_task"],
|
||||
"failure": ["error_task"]
|
||||
}
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
<Step title="Loop Task">
|
||||
Repetitive operations over collections
|
||||
```python
|
||||
loop_task = Task(
|
||||
type="loop",
|
||||
items=data_list,
|
||||
operation="process_item"
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Task Relationships
|
||||
|
||||
<Warning>
|
||||
Properly managing task dependencies is crucial for complex workflows. Always ensure proper context sharing and error handling.
|
||||
</Warning>
|
||||
|
||||
### Context Sharing
|
||||
```python
|
||||
task_a = Task(name="research")
|
||||
task_b = Task(
|
||||
name="analyze",
|
||||
context=[task_a] # Uses task_a's output
|
||||
)
|
||||
```
|
||||
|
||||
## Task Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Be Specific" icon="magnifying-glass">
|
||||
Clearly define what the task should accomplish
|
||||
</Card>
|
||||
<Card title="One Goal Per Task" icon="check-double">
|
||||
Each task should focus on a single objective
|
||||
</Card>
|
||||
<Card title="Provide Context" icon="circle-info">
|
||||
Include necessary background information
|
||||
</Card>
|
||||
<Card title="Define Success" icon="trophy">
|
||||
Specify what a successful outcome looks like
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Tip>
|
||||
Break complex goals into multiple smaller tasks rather than creating one large, complex task.
|
||||
</Tip>
|
||||
|
||||
## Common Task Mistakes
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Vague Instructions" icon="question">
|
||||
Unclear about what the agent should do
|
||||
</Card>
|
||||
<Card title="Too Many Objectives" icon="list-ol">
|
||||
Asking for too many things in one task
|
||||
</Card>
|
||||
<Card title="Missing Context" icon="puzzle-piece-missing">
|
||||
Not providing necessary background information
|
||||
</Card>
|
||||
<Card title="Unrealistic Expectations" icon="mountain-sun">
|
||||
Asking for tasks beyond agent capabilities
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll learn about creating your first complete agent application.
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
title: "Creating Your First Agent"
|
||||
description: "A step-by-step guide to building your first AI agent"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
# Creating Your First Agent
|
||||
|
||||
In this lesson, we'll walk through the process of building a simple AI agent. We'll focus on practical implementation without complex programming.
|
||||
|
||||
## What We'll Build
|
||||
|
||||
We'll create a basic research assistant agent that can:
|
||||
- Understand simple instructions
|
||||
- Respond to questions
|
||||
- Provide helpful information
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, make sure you have:
|
||||
|
||||
1. A basic understanding of the concepts from previous lessons
|
||||
2. Python installed on your computer (if following the code examples)
|
||||
3. An OpenAI API key (or access to another supported language model)
|
||||
|
||||
## Step 1: Installation
|
||||
|
||||
First, install the PraisonAI package:
|
||||
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
|
||||
## Step 2: Setup Your Environment
|
||||
|
||||
Create a file called `first_agent.py` and set up your API key:
|
||||
|
||||
```python
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Set your API key
|
||||
# Option 1: Set it in your environment (recommended)
|
||||
# export OPENAI_API_KEY=your_key_here
|
||||
|
||||
# Option 2: Set it in your code (not recommended for production)
|
||||
# os.environ["OPENAI_API_KEY"] = "your_key_here"
|
||||
```
|
||||
|
||||
## Step 3: Define Your Agent
|
||||
|
||||
Now, let's create a simple agent:
|
||||
|
||||
```python
|
||||
# Create a research assistant agent
|
||||
research_assistant = Agent(
|
||||
name="ResearchAssistant",
|
||||
instructions="""
|
||||
You are a helpful research assistant that provides clear,
|
||||
accurate information on various topics. When answering:
|
||||
|
||||
1. Be concise and to the point
|
||||
2. Explain complex concepts in simple terms
|
||||
3. When appropriate, organize information with bullet points
|
||||
4. If you don't know something, admit it instead of guessing
|
||||
"""
|
||||
)
|
||||
```
|
||||
|
||||
## Step 4: Start Your Agent
|
||||
|
||||
Now let's use our agent to answer a question:
|
||||
|
||||
```python
|
||||
# Start the agent with a specific query
|
||||
response = research_assistant.start("Explain how solar panels work in simple terms")
|
||||
|
||||
# Print the response
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Step 5: Run Your Agent
|
||||
|
||||
Save the file and run it from your terminal:
|
||||
|
||||
```bash
|
||||
python first_agent.py
|
||||
```
|
||||
|
||||
You should see the agent's response explaining how solar panels work in simple terms.
|
||||
|
||||
## Experimenting with Your Agent
|
||||
|
||||
Try changing the question to see how your agent responds to different topics:
|
||||
|
||||
```python
|
||||
# Try different questions
|
||||
response = research_assistant.start("What are the benefits of exercise?")
|
||||
# or
|
||||
response = research_assistant.start("How does artificial intelligence work?")
|
||||
```
|
||||
|
||||
## Modifying Agent Behavior
|
||||
|
||||
You can change how your agent behaves by adjusting its instructions:
|
||||
|
||||
```python
|
||||
# Create an agent with different instructions
|
||||
creative_writer = Agent(
|
||||
name="CreativeWriter",
|
||||
instructions="""
|
||||
You are a creative writer that specializes in short, engaging stories.
|
||||
Your writing should:
|
||||
|
||||
1. Include vivid descriptions
|
||||
2. Have interesting characters
|
||||
3. Include some dialogue
|
||||
4. Have a clear beginning, middle, and end
|
||||
"""
|
||||
)
|
||||
|
||||
# Ask for a story
|
||||
story = creative_writer.start("Write a short story about a lost dog finding its way home")
|
||||
print(story)
|
||||
```
|
||||
|
||||
## Examining How It Works
|
||||
|
||||
What's happening behind the scenes:
|
||||
|
||||
1. The agent receives your instructions and query
|
||||
2. The language model (like GPT-4) processes the information
|
||||
3. The model generates a response based on the instructions and query
|
||||
4. The response is returned to you
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Your Instructions] --> B[Agent]
|
||||
C[Your Query] --> B
|
||||
B --> D[Language Model]
|
||||
D --> E[Generated Response]
|
||||
E --> F[Output to You]
|
||||
```
|
||||
|
||||
## Common Challenges
|
||||
|
||||
If you encounter issues, check these common problems:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="API Key Issues" icon="key">
|
||||
Make sure your API key is set correctly
|
||||
</Card>
|
||||
<Card title="Connection Problems" icon="wifi">
|
||||
Check your internet connection
|
||||
</Card>
|
||||
<Card title="Unclear Instructions" icon="circle-question">
|
||||
Try making your instructions more specific
|
||||
</Card>
|
||||
<Card title="Rate Limits" icon="hand">
|
||||
You might be making too many API calls
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you've created your first agent, you can:
|
||||
- Experiment with different instructions
|
||||
- Try more complex queries
|
||||
- Add specialized capabilities (we'll cover this in upcoming lessons)
|
||||
- Create agents for specific use cases
|
||||
|
||||
Congratulations on creating your first AI agent! In the next lesson, we'll explore how to add tools to enhance your agent's capabilities.
|
||||
@@ -0,0 +1,275 @@
|
||||
---
|
||||
title: "Adding Tools to Agents"
|
||||
description: "Enhancing your agents with specialized capabilities"
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Adding Tools to Agents
|
||||
|
||||
In this lesson, we'll learn how to enhance your agents by adding tools. Tools allow agents to perform specific actions beyond just generating text, making them much more useful for real-world tasks.
|
||||
|
||||
## What You'll Learn
|
||||
|
||||
By the end of this lesson, you'll understand:
|
||||
- What agent tools are and why they're useful
|
||||
- How to create simple tools for your agents
|
||||
- How to integrate tools with your agents
|
||||
- Best practices for tool design
|
||||
|
||||
## Understanding Agent Tools
|
||||
|
||||
Tools give your agents the ability to:
|
||||
- Perform calculations
|
||||
- Access specific information
|
||||
- Interact with external systems
|
||||
- Generate different types of content
|
||||
|
||||
<Tabs>
|
||||
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package:
|
||||
```bash Terminal
|
||||
pip install praisonaiagents duckduckgo-search
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure Environment">
|
||||
```bash Terminal
|
||||
export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
|
||||
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
|
||||
</Step>
|
||||
|
||||
<Step title="Create Agent with Tool">
|
||||
Create `app.py`
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
# 1. Define the tool
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Assign the tool to an agent
|
||||
search_agent = Agent(
|
||||
instructions="Perform internet searches to collect relevant information.",
|
||||
tools=[internet_search_tool] # <--- Tool Assignment
|
||||
)
|
||||
|
||||
# 3. Start Agent
|
||||
search_agent.start("Search about AI job trends in 2025")
|
||||
```
|
||||
|
||||
```python Multiple Agents
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
# 1. Define the tool
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
# 2. Assign the tool to an agent
|
||||
search_agent = Agent(
|
||||
instructions="Search about AI job trends in 2025",
|
||||
tools=[internet_search_tool] # <--- Tool Assignment
|
||||
)
|
||||
|
||||
blog_agent = Agent(
|
||||
instructions="Write a blog article based on the previous agent's search results."
|
||||
)
|
||||
|
||||
# 3. Start Agents
|
||||
agents = PraisonAIAgents(agents=[search_agent, blog_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install PraisonAI">
|
||||
Install the core package and duckduckgo_search package:
|
||||
```bash Terminal
|
||||
pip install praisonai duckduckgo_search
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Custom Tool">
|
||||
<Info>
|
||||
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
|
||||
</Info>
|
||||
Create a new file `tools.py` with the following content:
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
from typing import List, Dict
|
||||
|
||||
# 1. Tool
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Agent">
|
||||
|
||||
Create a new file `agents.yaml` with the following content:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
topic: create movie script about cat in mars
|
||||
roles:
|
||||
scriptwriter:
|
||||
backstory: Expert in dialogue and script structure, translating concepts into
|
||||
scripts.
|
||||
goal: Write a movie script about a cat in Mars
|
||||
role: Scriptwriter
|
||||
tools:
|
||||
- internet_search_tool # <-- Tool assigned to Agent here
|
||||
tasks:
|
||||
scriptwriting_task:
|
||||
description: Turn the story concept into a production-ready movie script,
|
||||
including dialogue and scene details.
|
||||
expected_output: Final movie script with dialogue and scene details.
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
|
||||
Execute your script:
|
||||
```bash Terminal
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
|
||||
## Creating Custom Tool
|
||||
<Steps>
|
||||
<Step>
|
||||
Create any function that you want to use as a tool, that performs a specific task.
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
Assign the tool to an agent
|
||||
```python
|
||||
data_agent = Agent(
|
||||
instructions="Search about AI job trends in 2025",
|
||||
tools=[internet_search_tool], # <-- Tool Assignment
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Card title="That's it!">
|
||||
<Check>You have created a custom tool and assigned it to an agent.</Check>
|
||||
</Card>
|
||||
|
||||
## When Does the Agent Use Tools?
|
||||
|
||||
The agent decides when to use tools based on:
|
||||
1. The nature of the user's request
|
||||
2. The tools available to it
|
||||
3. The instructions you've provided
|
||||
|
||||
If your agent isn't using tools when expected, you might need to:
|
||||
- Make your instructions more explicit about when to use tools
|
||||
- Provide more descriptive tool definitions
|
||||
- Ensure the tools are appropriate for the task
|
||||
|
||||
## Tool Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Specific Purpose" icon="bullseye">
|
||||
Each tool should have a clear, specific purpose
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="shield-check">
|
||||
Tools should handle errors gracefully
|
||||
</Card>
|
||||
<Card title="Descriptive Names" icon="tag">
|
||||
Use clear names that indicate functionality
|
||||
</Card>
|
||||
<Card title="Clear Documentation" icon="file-lines">
|
||||
Include detailed descriptions and examples
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Real-World Tool Examples
|
||||
|
||||
In production systems, you might create tools for:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Database Access" icon="database">
|
||||
Retrieve or store information in databases
|
||||
</Card>
|
||||
<Card title="API Integration" icon="link">
|
||||
Connect to external services
|
||||
</Card>
|
||||
<Card title="File Operations" icon="folder">
|
||||
Read from or write to files
|
||||
</Card>
|
||||
<Card title="Image Generation" icon="image">
|
||||
Create images based on descriptions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Tool Concepts
|
||||
|
||||
As you become more comfortable with tools, you can explore:
|
||||
- Tools that call other tools
|
||||
- Tools with complex parameters
|
||||
- Tools that maintain state
|
||||
- Dynamically generated tools
|
||||
|
||||
In the next lesson, we'll explore how to create a multi-agent system for more complex tasks.
|
||||
@@ -0,0 +1,218 @@
|
||||
---
|
||||
title: "Building a Multi-Agent System"
|
||||
description: "Creating a system with multiple cooperative agents"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
# Building a Multi-Agent System
|
||||
|
||||
In this lesson, we'll create a simple multi-agent system where several agents work together to accomplish a task. This approach allows you to divide complex problems into smaller, more manageable pieces.
|
||||
|
||||
## What We'll Build
|
||||
|
||||
We'll create a content creation system with three specialized agents:
|
||||
1. A research agent to gather information
|
||||
2. A writing agent to create content
|
||||
3. An editing agent to improve and refine the content
|
||||
|
||||
## Step 1: Setting Up
|
||||
|
||||
First, let's import the necessary modules and set up our environment:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
# Make sure your API key is set in your environment:
|
||||
# export OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
|
||||
## Step 2: Creating Specialized Agents
|
||||
|
||||
Now, let's create our three specialized agents:
|
||||
|
||||
```python
|
||||
# Research Agent
|
||||
research_agent = Agent(
|
||||
name="Researcher",
|
||||
instructions="""
|
||||
You are a research specialist who excels at finding relevant information.
|
||||
Your job is to:
|
||||
1. Thoroughly research the given topic
|
||||
2. Identify key facts, statistics, and insights
|
||||
3. Organize the information in a clear, structured format
|
||||
4. Provide accurate information with no fabrications
|
||||
5. Focus on the most relevant and current information
|
||||
"""
|
||||
)
|
||||
|
||||
# Writing Agent
|
||||
writing_agent = Agent(
|
||||
name="Writer",
|
||||
instructions="""
|
||||
You are a content writer who creates engaging, reader-friendly content.
|
||||
Your job is to:
|
||||
1. Use the research provided to create well-structured content
|
||||
2. Write in a clear, engaging style
|
||||
3. Include an attention-grabbing introduction
|
||||
4. Organize the content with appropriate headings
|
||||
5. Conclude with a summary and call-to-action when appropriate
|
||||
"""
|
||||
)
|
||||
|
||||
# Editing Agent
|
||||
editing_agent = Agent(
|
||||
name="Editor",
|
||||
instructions="""
|
||||
You are an editor who refines and improves content.
|
||||
Your job is to:
|
||||
1. Correct any grammatical or spelling errors
|
||||
2. Improve clarity and flow
|
||||
3. Ensure consistency in tone and style
|
||||
4. Check for logical structure and organization
|
||||
5. Enhance readability for the target audience
|
||||
"""
|
||||
)
|
||||
```
|
||||
|
||||
## Step 3: Creating the Multi-Agent System
|
||||
|
||||
Now, let's combine these agents into a multi-agent system:
|
||||
|
||||
```python
|
||||
# Create a multi-agent system
|
||||
content_team = PraisonAIAgents(
|
||||
agents=[research_agent, writing_agent, editing_agent]
|
||||
)
|
||||
```
|
||||
|
||||
## Step 4: Setting Up the Workflow
|
||||
|
||||
Next, we need to define how our agents will work together:
|
||||
|
||||
```python
|
||||
# Define a topic
|
||||
topic = "The Benefits of Regular Exercise"
|
||||
|
||||
# Start the multi-agent process
|
||||
results = content_team.start(
|
||||
f"""
|
||||
Task: Create a comprehensive blog post about {topic}
|
||||
|
||||
Process:
|
||||
1. Researcher: Research {topic} and provide key information including:
|
||||
- Main benefits of exercise (physical and mental)
|
||||
- Recommended exercise guidelines
|
||||
- Scientific studies supporting the benefits
|
||||
- Common misconceptions
|
||||
|
||||
2. Writer: Use the research to create a 500-word blog post about {topic} with:
|
||||
- An engaging introduction
|
||||
- Clear sections with headings
|
||||
- Practical advice for readers
|
||||
- A compelling conclusion
|
||||
|
||||
3. Editor: Review and improve the blog post by:
|
||||
- Correcting any errors
|
||||
- Enhancing clarity and flow
|
||||
- Ensuring a consistent tone
|
||||
- Making the content more engaging
|
||||
"""
|
||||
)
|
||||
|
||||
# Print the final result
|
||||
print(results)
|
||||
```
|
||||
|
||||
## Understanding the Workflow
|
||||
|
||||
Let's examine how the multi-agent system works:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Start] --> B[Research Agent]
|
||||
B --> C[Writing Agent]
|
||||
C --> D[Editing Agent]
|
||||
D --> E[Final Output]
|
||||
```
|
||||
|
||||
1. The research agent gathers and organizes relevant information
|
||||
2. The writing agent uses that research to create the initial content
|
||||
3. The editing agent refines and improves the content
|
||||
4. The final polished content is returned
|
||||
|
||||
## Customizing Agent Interactions
|
||||
|
||||
You can customize how agents interact by modifying the process instructions. For example, you could add feedback loops:
|
||||
|
||||
```python
|
||||
process_with_feedback = """
|
||||
Task: Create a comprehensive blog post about {topic}
|
||||
|
||||
Process:
|
||||
1. Researcher: Research {topic} and provide key information
|
||||
|
||||
2. Writer: Use the research to create a blog post
|
||||
|
||||
3. Editor: Review the blog post and provide feedback
|
||||
|
||||
4. Writer: Revise the blog post based on the editor's feedback
|
||||
|
||||
5. Editor: Make final improvements to the revised blog post
|
||||
"""
|
||||
```
|
||||
|
||||
## Alternative Agent Configurations
|
||||
|
||||
You can organize multi-agent systems in different ways:
|
||||
|
||||
### Parallel Processing
|
||||
|
||||
```python
|
||||
parallel_process = """
|
||||
Task: Create a marketing campaign for a new product
|
||||
|
||||
Process:
|
||||
1. Market Researcher: Research the target market and competitors
|
||||
Content Researcher: Research the product features and benefits
|
||||
[These tasks happen in parallel]
|
||||
|
||||
2. Strategy Agent: Use both research results to create a marketing strategy
|
||||
|
||||
3. Content Creator: Create the marketing materials based on the strategy
|
||||
"""
|
||||
```
|
||||
|
||||
### Expert Panel
|
||||
|
||||
```python
|
||||
expert_panel = """
|
||||
Task: Evaluate a business idea
|
||||
|
||||
Process:
|
||||
1. Financial Expert: Analyze financial viability
|
||||
Market Expert: Analyze market potential
|
||||
Technical Expert: Analyze technical feasibility
|
||||
[These assessments happen in parallel]
|
||||
|
||||
2. Coordinator: Compile all expert opinions into a final recommendation
|
||||
"""
|
||||
```
|
||||
|
||||
## Best Practices for Multi-Agent Systems
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Role Definition" icon="user-tag">
|
||||
Define exactly what each agent is responsible for
|
||||
</Card>
|
||||
<Card title="Explicit Handoffs" icon="arrow-right-arrow-left">
|
||||
Specify how information passes between agents
|
||||
</Card>
|
||||
<Card title="Avoid Redundancy" icon="copy">
|
||||
Don't have multiple agents do the same work
|
||||
</Card>
|
||||
<Card title="Include Error Handling" icon="triangle-exclamation">
|
||||
Plan for cases where an agent might fail
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll learn how to create a conversational agent that can maintain context across multiple interactions.
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
title: "Building Conversational Agents"
|
||||
description: "Creating agents that maintain context in conversations"
|
||||
icon: "comments"
|
||||
---
|
||||
|
||||
# Building Conversational Agents
|
||||
|
||||
In this lesson, we'll learn how to create conversational agents that can maintain context across multiple interactions. This is essential for creating assistants that feel natural to interact with.
|
||||
|
||||
## What Makes a Good Conversational Agent?
|
||||
|
||||
A good conversational agent should:
|
||||
- Remember previous parts of the conversation
|
||||
- Understand context and references
|
||||
- Provide coherent, relevant responses
|
||||
- Maintain a consistent personality
|
||||
|
||||
## Creating a Simple Conversational Agent
|
||||
|
||||
Let's build a basic conversational agent:
|
||||
|
||||
```python
|
||||
# Note: TODO: This Feature yet to be developed
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a conversational agent
|
||||
chat_agent = Agent(
|
||||
name="Conversational Assistant",
|
||||
instructions="""
|
||||
You are a friendly, helpful conversational assistant.
|
||||
|
||||
When chatting with users:
|
||||
1. Maintain a warm, friendly tone
|
||||
2. Remember information shared earlier in the conversation
|
||||
3. Ask clarifying questions when needed
|
||||
4. Keep responses concise but informative
|
||||
5. Be helpful while respecting boundaries
|
||||
"""
|
||||
)
|
||||
|
||||
# Start a conversation
|
||||
response = chat_agent.start("Hi there! My name is Jamie.")
|
||||
print(response)
|
||||
|
||||
# Continue the conversation
|
||||
response = chat_agent.continue("What can you help me with today?")
|
||||
print(response)
|
||||
|
||||
# The agent should remember the user's name
|
||||
response = chat_agent.continue("Can you remember my name?")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## How Context Works
|
||||
|
||||
PraisonAI automatically manages conversation context for you:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[User Message 1] --> B[Agent]
|
||||
B --> C[Response 1]
|
||||
D[User Message 2] --> E[Agent + Context]
|
||||
E --> F[Response 2]
|
||||
G[User Message 3] --> H[Agent + More Context]
|
||||
H --> I[Response 3]
|
||||
```
|
||||
|
||||
The agent maintains a memory of the conversation, allowing it to refer back to previous messages.
|
||||
|
||||
## Conversation Settings
|
||||
|
||||
You can customize how your conversational agent behaves:
|
||||
|
||||
```python
|
||||
# Create an agent with specific conversation settings
|
||||
custom_chat_agent = Agent(
|
||||
name="Custom Chat Assistant",
|
||||
instructions="You are a helpful assistant",
|
||||
memory_size=10, # Remember the last 10 messages
|
||||
temperature=0.7 # Slightly more creative in responses
|
||||
)
|
||||
```
|
||||
|
||||
## Handling Different Types of Conversations
|
||||
|
||||
Different use cases require different conversation styles:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Customer Support" icon="headset">
|
||||
- Professional and helpful tone
|
||||
- Focus on problem resolution
|
||||
- Remember customer details
|
||||
</Card>
|
||||
<Card title="Educational Tutor" icon="graduation-cap">
|
||||
- Patient and explanatory
|
||||
- Builds on previous lessons
|
||||
- Adjusts to learning pace
|
||||
</Card>
|
||||
<Card title="Personal Assistant" icon="calendar">
|
||||
- Remembers preferences
|
||||
- Provides reminders
|
||||
- Handles scheduling
|
||||
</Card>
|
||||
<Card title="Companion Chat" icon="user-group">
|
||||
- More casual tone
|
||||
- Focuses on engagement
|
||||
- Shows personality
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example: Customer Support Agent
|
||||
|
||||
Let's create a specialized customer support agent:
|
||||
|
||||
```python
|
||||
support_agent = Agent(
|
||||
name="Support Agent",
|
||||
instructions="""
|
||||
You are a customer support specialist for a tech company.
|
||||
|
||||
When helping customers:
|
||||
1. Greet them professionally
|
||||
2. Show empathy for their issues
|
||||
3. Ask for necessary information to troubleshoot
|
||||
4. Provide clear step-by-step solutions
|
||||
5. Confirm if the issue is resolved
|
||||
6. End with an offer for additional help
|
||||
|
||||
Remember product details and customer information throughout the conversation.
|
||||
"""
|
||||
)
|
||||
|
||||
# Example conversation
|
||||
print(support_agent.start("Hi, I'm having trouble logging into my account."))
|
||||
print(support_agent.continue("My username is user123."))
|
||||
print(support_agent.continue("I've tried resetting my password but I'm not receiving the email."))
|
||||
```
|
||||
|
||||
## Building Multi-Turn Conversations
|
||||
|
||||
To create engaging multi-turn conversations, consider:
|
||||
|
||||
1. **Appropriate follow-up questions**: Keep the conversation flowing
|
||||
2. **Acknowledgment**: Reference what the user has said
|
||||
3. **Progressive disclosure**: Don't overwhelm with information at once
|
||||
4. **Conversation repair**: Gracefully handle misunderstandings
|
||||
|
||||
## Example: Multi-Turn Educational Conversation
|
||||
|
||||
```python
|
||||
tutor_agent = Agent(
|
||||
name="Math Tutor",
|
||||
instructions="""
|
||||
You are a patient, encouraging math tutor.
|
||||
|
||||
When teaching:
|
||||
1. Gauge the student's current understanding
|
||||
2. Explain concepts using clear, simple language
|
||||
3. Provide examples to illustrate points
|
||||
4. Ask questions to check understanding
|
||||
5. Give positive reinforcement for progress
|
||||
|
||||
Adapt your explanations based on the student's responses.
|
||||
"""
|
||||
)
|
||||
|
||||
# Example tutoring session
|
||||
print(tutor_agent.start("Can you help me understand algebra?"))
|
||||
print(tutor_agent.continue("I'm struggling with equations like 2x + 5 = 13"))
|
||||
print(tutor_agent.continue("So I subtract 5 from both sides first?"))
|
||||
print(tutor_agent.continue("Then I divide by 2 to get x = 4?"))
|
||||
print(tutor_agent.continue("Could you give me another example to practice?"))
|
||||
```
|
||||
|
||||
## Conversation Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Clear Transitions" icon="arrow-right">
|
||||
Signal when changing topics
|
||||
</Card>
|
||||
<Card title="Manageable Chunks" icon="layer-group">
|
||||
Break complex information into smaller pieces
|
||||
</Card>
|
||||
<Card title="Engagement Checks" icon="hand">
|
||||
Periodically confirm understanding
|
||||
</Card>
|
||||
<Card title="Personality Consistency" icon="masks-theater">
|
||||
Maintain a consistent tone and style
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build agents that can search and retrieve information from external sources.
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
title: "Building Research Agents"
|
||||
description: "Creating agents that can gather and analyze information"
|
||||
icon: "magnifying-glass"
|
||||
---
|
||||
|
||||
# Building Research Agents
|
||||
|
||||
In this lesson, we'll build agents specialized in gathering, analyzing, and summarizing information. Research agents are valuable for quickly obtaining insights on various topics.
|
||||
|
||||
## What is a Research Agent?
|
||||
|
||||
A research agent is designed to:
|
||||
- Find relevant information on specific topics
|
||||
- Analyze and synthesize data
|
||||
- Present findings in a clear, structured format
|
||||
- Answer questions based on gathered information
|
||||
|
||||
## Creating a Basic Research Agent
|
||||
|
||||
Let's start by building a simple research agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic research agent
|
||||
research_agent = Agent(
|
||||
name="ResearchAgent",
|
||||
instructions="""
|
||||
You are a research specialist who finds and summarizes information.
|
||||
|
||||
When researching topics:
|
||||
1. Focus on finding accurate, current information
|
||||
2. Organize findings in a logical structure
|
||||
3. Identify key points and insights
|
||||
4. Cite sources when available
|
||||
5. Present information in a clear, concise format
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the research agent
|
||||
research_results = research_agent.start("Research the impact of renewable energy on reducing carbon emissions")
|
||||
print(research_results)
|
||||
```
|
||||
|
||||
## Adding Web Search Capability
|
||||
|
||||
To make our research agent more powerful, let's add web search capability:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tool
|
||||
|
||||
# Define a web search function (simulated for this example)
|
||||
def web_search(query):
|
||||
"""
|
||||
Simulated web search function.
|
||||
In a real application, this would connect to a search API.
|
||||
|
||||
Args:
|
||||
query (str): The search query
|
||||
|
||||
Returns:
|
||||
str: Search results
|
||||
"""
|
||||
# This is just a simulation - in a real application, you'd call a search API
|
||||
if "renewable energy" in query.lower():
|
||||
return """
|
||||
Search results for 'renewable energy carbon emissions':
|
||||
|
||||
1. According to the IEA, renewable energy prevented 2.1 billion tonnes of CO2 emissions in 2022.
|
||||
|
||||
2. Solar and wind power generate electricity with 95-98% lower carbon emissions than coal-based electricity.
|
||||
|
||||
3. The IPCC reports that renewable energy could deliver more than half of the emission reductions needed by 2030.
|
||||
"""
|
||||
else:
|
||||
return f"Search results for '{query}' (simulated data)"
|
||||
|
||||
# Create the web search tool
|
||||
search_tool = Tool(
|
||||
name="web_search",
|
||||
function=web_search,
|
||||
description="Search the web for current information on a topic"
|
||||
)
|
||||
|
||||
# Create a research agent with web search capability
|
||||
enhanced_research_agent = Agent(
|
||||
name="EnhancedResearchAgent",
|
||||
instructions="""
|
||||
You are a research specialist who finds and summarizes information.
|
||||
|
||||
When researching topics:
|
||||
1. Use the web_search tool to find current information
|
||||
2. Analyze and synthesize the search results
|
||||
3. Organize findings in a logical structure
|
||||
4. Identify key points and insights
|
||||
5. Present information in a clear, concise format
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the enhanced research agent
|
||||
enhanced_results = enhanced_research_agent.start("What is the impact of renewable energy on carbon emissions?")
|
||||
print(enhanced_results)
|
||||
```
|
||||
|
||||
## Research Agent with Structured Output
|
||||
|
||||
For more organized research results, we can instruct the agent to provide structured output:
|
||||
|
||||
```python
|
||||
structured_research_agent = Agent(
|
||||
name="StructuredResearchAgent",
|
||||
instructions="""
|
||||
You are a research specialist who finds and organizes information.
|
||||
|
||||
When researching topics:
|
||||
1. Use available tools to find current information
|
||||
2. Analyze and synthesize the findings
|
||||
|
||||
Always structure your response in this format:
|
||||
|
||||
## Summary
|
||||
[Brief 2-3 sentence overview of the topic]
|
||||
|
||||
## Key Facts
|
||||
- [Important fact 1]
|
||||
- [Important fact 2]
|
||||
- [Important fact 3]
|
||||
|
||||
## Analysis
|
||||
[Deeper analysis of the information, including implications]
|
||||
|
||||
## Sources
|
||||
[List of sources if available]
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the structured research agent
|
||||
structured_results = structured_research_agent.start("Research the latest advancements in quantum computing")
|
||||
print(structured_results)
|
||||
```
|
||||
|
||||
## Specialized Research Agents
|
||||
|
||||
Different research tasks require different approaches. Here are some specialized research agents:
|
||||
|
||||
### Comparison Research Agent
|
||||
|
||||
```python
|
||||
comparison_agent = Agent(
|
||||
name="ComparisonAgent",
|
||||
instructions="""
|
||||
You are a research specialist who compares different options or topics.
|
||||
|
||||
When comparing items:
|
||||
1. Identify the key criteria for comparison
|
||||
2. Research each option thoroughly
|
||||
3. Create a clear side-by-side comparison
|
||||
4. Highlight advantages and disadvantages of each option
|
||||
5. Provide a balanced conclusion
|
||||
|
||||
Present your findings in a structured table format when appropriate.
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the comparison agent
|
||||
comparison_results = comparison_agent.start("Compare solar and wind energy for residential use")
|
||||
print(comparison_results)
|
||||
```
|
||||
|
||||
### Literature Review Agent
|
||||
|
||||
```python
|
||||
literature_agent = Agent(
|
||||
name="LiteratureAgent",
|
||||
instructions="""
|
||||
You are a research specialist who reviews academic and professional literature.
|
||||
|
||||
When reviewing literature:
|
||||
1. Identify key papers, articles, and studies on the topic
|
||||
2. Summarize the main findings and methodologies
|
||||
3. Identify trends, agreements, and contradictions
|
||||
4. Evaluate the strength of evidence
|
||||
5. Highlight gaps in current research
|
||||
|
||||
Structure your review in a clear, academic format.
|
||||
""",
|
||||
tools=[search_tool]
|
||||
)
|
||||
|
||||
# Use the literature review agent
|
||||
literature_results = literature_agent.start("Review recent research on artificial intelligence in healthcare")
|
||||
print(literature_results)
|
||||
```
|
||||
|
||||
## Research Process Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Define Scope" icon="bullseye">
|
||||
Set clear boundaries for the research
|
||||
</Card>
|
||||
<Card title="Verify Information" icon="check-double">
|
||||
Cross-check facts from multiple sources
|
||||
</Card>
|
||||
<Card title="Consider Bias" icon="scale-balanced">
|
||||
Be aware of potential biases in sources
|
||||
</Card>
|
||||
<Card title="Prioritize Relevance" icon="filter">
|
||||
Focus on information most relevant to the query
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build agents that can assist with creative tasks like content creation.
|
||||
@@ -0,0 +1,252 @@
|
||||
---
|
||||
title: "Content Creation Agents"
|
||||
description: "Building agents that generate various types of content"
|
||||
icon: "pen-to-square"
|
||||
---
|
||||
|
||||
# Content Creation Agents
|
||||
|
||||
Content creation agents can help generate various types of content, from blog posts to marketing materials. In this lesson, we'll learn how to build effective content creation agents.
|
||||
|
||||
## What is a Content Creation Agent?
|
||||
|
||||
A content creation agent is designed to:
|
||||
- Generate written content based on specific requirements
|
||||
- Structure content in appropriate formats
|
||||
- Adapt tone and style to match the target audience
|
||||
- Create content that achieves specific goals (inform, persuade, entertain)
|
||||
|
||||
## Creating a Basic Content Creation Agent
|
||||
|
||||
Let's start with a simple content creation agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic content creation agent
|
||||
content_agent = Agent(
|
||||
name="ContentCreator",
|
||||
instructions="""
|
||||
You are a versatile content creator who specializes in writing engaging material.
|
||||
|
||||
When creating content:
|
||||
1. Understand the purpose and target audience
|
||||
2. Create a logical structure with clear sections
|
||||
3. Use an engaging, appropriate writing style
|
||||
4. Include a strong introduction and conclusion
|
||||
5. Format content for easy readability
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the content creation agent
|
||||
blog_post = content_agent.start(
|
||||
"""
|
||||
Create a blog post about the benefits of meditation.
|
||||
Target audience: Busy professionals
|
||||
Length: Approximately 500 words
|
||||
Tone: Informative but conversational
|
||||
"""
|
||||
)
|
||||
print(blog_post)
|
||||
```
|
||||
|
||||
## Specialized Content Creation Agents
|
||||
|
||||
Different types of content require different approaches. Let's create specialized agents for various content needs:
|
||||
|
||||
### Blog Post Agent
|
||||
|
||||
```python
|
||||
blog_agent = Agent(
|
||||
name="BlogWriter",
|
||||
instructions="""
|
||||
You are a blog post writer who creates engaging, informative articles.
|
||||
|
||||
When writing blog posts:
|
||||
1. Create attention-grabbing headlines
|
||||
2. Start with a compelling introduction
|
||||
3. Use subheadings to organize content
|
||||
4. Include relevant examples and evidence
|
||||
5. Incorporate a clear call-to-action at the end
|
||||
|
||||
Format your content with proper Markdown formatting including:
|
||||
- Headings (## for main sections, ### for subsections)
|
||||
- Bullet points for lists
|
||||
- *Italic* for emphasis
|
||||
- **Bold** for important points
|
||||
- > Blockquotes for notable quotes
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the blog agent
|
||||
blog_content = blog_agent.start(
|
||||
"""
|
||||
Topic: 5 Ways to Improve Your Productivity
|
||||
Target audience: Remote workers
|
||||
Style: Practical, actionable advice
|
||||
Length: 800 words
|
||||
Include: Tips, examples, and research-backed information
|
||||
"""
|
||||
)
|
||||
print(blog_content)
|
||||
```
|
||||
|
||||
### Social Media Content Agent
|
||||
|
||||
```python
|
||||
social_media_agent = Agent(
|
||||
name="SocialMediaCreator",
|
||||
instructions="""
|
||||
You are a social media content creator who crafts engaging posts.
|
||||
|
||||
When creating social media content:
|
||||
1. Create attention-grabbing, concise content
|
||||
2. Adapt to the specific platform requirements
|
||||
3. Include relevant hashtags when appropriate
|
||||
4. Craft content that encourages engagement
|
||||
5. Consider visual elements that would pair well with the text
|
||||
|
||||
For each platform, follow these guidelines:
|
||||
- Twitter/X: 280 characters max, punchy, relevant hashtags
|
||||
- LinkedIn: Professional tone, industry insights, 1-3 paragraphs
|
||||
- Instagram: Visual-focused descriptions, emoji-friendly, hashtags
|
||||
- Facebook: Conversational, can be longer, question-based engagement
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the social media agent
|
||||
social_content = social_media_agent.start(
|
||||
"""
|
||||
Create posts for Twitter, LinkedIn, and Facebook announcing:
|
||||
|
||||
Event: Free Webinar on "Future of AI in Business"
|
||||
Date: March 15, 2025
|
||||
Time: 2:00 PM EST
|
||||
Registration link: example.com/webinar
|
||||
Key speakers: Dr. Jane Smith, AI Ethics Expert & Tom Johnson, Business AI Implementation Specialist
|
||||
"""
|
||||
)
|
||||
print(social_content)
|
||||
```
|
||||
|
||||
### Email Campaign Agent
|
||||
|
||||
```python
|
||||
email_agent = Agent(
|
||||
name="EmailWriter",
|
||||
instructions="""
|
||||
You are an email marketing specialist who creates effective email campaigns.
|
||||
|
||||
When writing marketing emails:
|
||||
1. Create compelling subject lines that increase open rates
|
||||
2. Write engaging opening lines that hook the reader
|
||||
3. Keep content concise and focused on a single main message
|
||||
4. Include clear calls-to-action
|
||||
5. Use a tone appropriate for the brand and audience
|
||||
|
||||
Structure your emails with:
|
||||
- Subject line
|
||||
- Greeting
|
||||
- Opening hook
|
||||
- Main content (2-3 paragraphs maximum)
|
||||
- Call-to-action
|
||||
- Sign-off
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the email agent
|
||||
email_content = email_agent.start(
|
||||
"""
|
||||
Create a promotional email for:
|
||||
|
||||
Product: Premium Fitness Subscription
|
||||
Key benefit: Personalized workout plans and nutrition advice
|
||||
Special offer: 30% off first 3 months
|
||||
Target audience: Health-conscious professionals aged 25-45
|
||||
CTA: Sign up for the discounted offer
|
||||
Tone: Motivational but not aggressive
|
||||
"""
|
||||
)
|
||||
print(email_content)
|
||||
```
|
||||
|
||||
## Content Creation with Templates
|
||||
|
||||
Templates can help create more consistent content. Let's build an agent that works with templates:
|
||||
|
||||
```python
|
||||
template_agent = Agent(
|
||||
name="TemplateWriter",
|
||||
instructions="""
|
||||
You are a content creator who works with templates to create consistent content.
|
||||
|
||||
When filling a template:
|
||||
1. Maintain the overall structure of the template
|
||||
2. Replace placeholder text with appropriate content
|
||||
3. Ensure consistency in tone and style
|
||||
4. Adapt content to the specific requirements
|
||||
5. Review for coherence and flow
|
||||
|
||||
Always preserve formatting elements like headings, lists, and emphasis.
|
||||
"""
|
||||
)
|
||||
|
||||
# Example template
|
||||
product_review_template = """
|
||||
# {Product Name} Review: {Brief Opinion}
|
||||
|
||||
## Quick Summary
|
||||
**Rating:** {Rating}/10
|
||||
**Price:** {Price Range}
|
||||
**Recommended For:** {Target User}
|
||||
|
||||
## What We Liked
|
||||
- {Positive Point 1}
|
||||
- {Positive Point 2}
|
||||
- {Positive Point 3}
|
||||
|
||||
## What Could Be Better
|
||||
- {Negative Point 1}
|
||||
- {Negative Point 2}
|
||||
|
||||
## Bottom Line
|
||||
{Conclusion Paragraph}
|
||||
|
||||
"""
|
||||
|
||||
# Use the template agent
|
||||
filled_template = template_agent.start(
|
||||
f"""
|
||||
Fill the following template for a product review:
|
||||
|
||||
{product_review_template}
|
||||
|
||||
Product: Wireless Noise-Cancelling Headphones XZ200
|
||||
Key features: 30-hour battery life, active noise cancellation, voice assistant integration
|
||||
Price: $249.99
|
||||
Target audience: Commuters and office workers
|
||||
Notable pros: Sound quality, comfort, battery life
|
||||
Notable cons: Price, occasional Bluetooth connectivity issues
|
||||
"""
|
||||
)
|
||||
print(filled_template)
|
||||
```
|
||||
|
||||
## Content Creation Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Know Your Audience" icon="users">
|
||||
Understand who will consume the content
|
||||
</Card>
|
||||
<Card title="Clear Purpose" icon="bullseye">
|
||||
Define what the content should achieve
|
||||
</Card>
|
||||
<Card title="Consistent Voice" icon="comment">
|
||||
Maintain a consistent tone and style
|
||||
</Card>
|
||||
<Card title="Readability" icon="eye">
|
||||
Make content easy to scan and understand
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build AI agents that can analyze and work with data.
|
||||
@@ -0,0 +1,333 @@
|
||||
---
|
||||
title: "Data Analysis Agents"
|
||||
description: "Creating agents that analyze and interpret data"
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
# Data Analysis Agents
|
||||
|
||||
Data analysis agents can help process, analyze, and extract insights from data. In this lesson, we'll learn how to build agents that can work with data effectively.
|
||||
|
||||
## What is a Data Analysis Agent?
|
||||
|
||||
A data analysis agent is designed to:
|
||||
- Process and interpret data
|
||||
- Identify patterns and trends
|
||||
- Generate insights and recommendations
|
||||
- Present findings in an understandable format
|
||||
|
||||
## Creating a Basic Data Analysis Agent
|
||||
|
||||
Let's start by building a simple data analysis agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic data analysis agent
|
||||
data_analysis_agent = Agent(
|
||||
name="DataAnalyst",
|
||||
instructions="""
|
||||
You are a data analysis specialist who interprets and explains data.
|
||||
|
||||
When analyzing data:
|
||||
1. First understand what the data represents
|
||||
2. Identify key patterns, trends, or anomalies
|
||||
3. Generate meaningful insights
|
||||
4. Explain findings in simple, clear language
|
||||
5. Provide actionable recommendations when appropriate
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the data analysis agent with sample data
|
||||
sample_data = """
|
||||
Monthly Sales Data (2024):
|
||||
January: $12,500
|
||||
February: $13,200
|
||||
March: $15,800
|
||||
April: $14,300
|
||||
May: $16,700
|
||||
June: $18,900
|
||||
"""
|
||||
|
||||
analysis = data_analysis_agent.start(
|
||||
f"""
|
||||
Analyze the following sales data and provide insights:
|
||||
|
||||
{sample_data}
|
||||
|
||||
Questions to answer:
|
||||
1. What is the overall sales trend?
|
||||
2. Which month had the highest sales?
|
||||
3. What is the average monthly sales?
|
||||
4. What recommendations would you make based on this data?
|
||||
"""
|
||||
)
|
||||
print(analysis)
|
||||
```
|
||||
|
||||
## Adding Data Processing Tools
|
||||
|
||||
Let's enhance our agent with basic data processing capabilities:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Tool
|
||||
|
||||
# Define a simple calculation tool
|
||||
def calculate_statistics(data_string):
|
||||
"""
|
||||
Calculate basic statistics from a string of numbers.
|
||||
|
||||
Args:
|
||||
data_string (str): A string with numbers separated by commas
|
||||
|
||||
Returns:
|
||||
str: Statistical summary
|
||||
"""
|
||||
try:
|
||||
# Convert string to list of numbers
|
||||
data = [float(x.strip()) for x in data_string.split(',')]
|
||||
|
||||
# Calculate statistics
|
||||
total = sum(data)
|
||||
average = total / len(data)
|
||||
minimum = min(data)
|
||||
maximum = max(data)
|
||||
|
||||
return f"""
|
||||
Statistical summary:
|
||||
- Count: {len(data)}
|
||||
- Sum: {total}
|
||||
- Average: {average:.2f}
|
||||
- Minimum: {minimum}
|
||||
- Maximum: {maximum}
|
||||
- Range: {maximum - minimum}
|
||||
"""
|
||||
except Exception as e:
|
||||
return f"Error processing data: {str(e)}"
|
||||
|
||||
# Create the tool
|
||||
stats_tool = Tool(
|
||||
name="calculate_statistics",
|
||||
function=calculate_statistics,
|
||||
description="Calculate basic statistics from a list of numbers (comma-separated)"
|
||||
)
|
||||
|
||||
# Create an agent with the statistics tool
|
||||
enhanced_data_agent = Agent(
|
||||
name="EnhancedDataAnalyst",
|
||||
instructions="""
|
||||
You are a data analysis specialist who interprets and explains data.
|
||||
|
||||
When analyzing data:
|
||||
1. First understand what the data represents
|
||||
2. Use the calculate_statistics tool for numerical data
|
||||
3. Identify key patterns, trends, or anomalies
|
||||
4. Generate meaningful insights
|
||||
5. Explain findings in simple, clear language
|
||||
6. Provide actionable recommendations when appropriate
|
||||
""",
|
||||
tools=[stats_tool]
|
||||
)
|
||||
|
||||
# Use the enhanced data agent
|
||||
numerical_data = "12500, 13200, 15800, 14300, 16700, 18900"
|
||||
enhanced_analysis = enhanced_data_agent.start(
|
||||
f"""
|
||||
Analyze the following monthly sales data for the first half of 2024:
|
||||
|
||||
{numerical_data}
|
||||
|
||||
Provide a complete analysis with trends and recommendations.
|
||||
"""
|
||||
)
|
||||
print(enhanced_analysis)
|
||||
```
|
||||
|
||||
## Specialized Data Analysis Agents
|
||||
|
||||
Different analysis tasks require specialized approaches. Let's create some specialized agents:
|
||||
|
||||
### Market Trend Analysis Agent
|
||||
|
||||
```python
|
||||
market_analysis_agent = Agent(
|
||||
name="MarketAnalyst",
|
||||
instructions="""
|
||||
You are a market trend analyst who specializes in identifying patterns and making predictions.
|
||||
|
||||
When analyzing market data:
|
||||
1. Identify long-term trends and short-term patterns
|
||||
2. Compare data points to industry benchmarks
|
||||
3. Identify potential causes for changes
|
||||
4. Assess future implications
|
||||
5. Provide strategic recommendations
|
||||
|
||||
Present your analysis with clear sections for:
|
||||
- Overall Market Assessment
|
||||
- Key Trends Identified
|
||||
- Growth Opportunities
|
||||
- Risk Factors
|
||||
- Strategic Recommendations
|
||||
""",
|
||||
tools=[stats_tool]
|
||||
)
|
||||
|
||||
# Use the market analysis agent
|
||||
market_data = """
|
||||
Industry Growth Rates (2021-2024):
|
||||
2021: 3.2%
|
||||
2022: 2.8%
|
||||
2023: 4.5%
|
||||
2024: 5.1%
|
||||
|
||||
Our Company Growth:
|
||||
2021: 2.9%
|
||||
2022: 3.1%
|
||||
2023: 4.8%
|
||||
2024: 6.3%
|
||||
|
||||
Competitor A Growth:
|
||||
2021: 3.5%
|
||||
2022: 3.7%
|
||||
2023: 4.2%
|
||||
2024: 4.5%
|
||||
|
||||
Competitor B Growth:
|
||||
2021: 3.0%
|
||||
2022: 2.5%
|
||||
2023: 5.0%
|
||||
2024: 5.8%
|
||||
"""
|
||||
|
||||
market_analysis = market_analysis_agent.start(
|
||||
f"""
|
||||
Analyze the following market and company growth data:
|
||||
|
||||
{market_data}
|
||||
|
||||
Provide a comprehensive market analysis and strategic recommendations.
|
||||
"""
|
||||
)
|
||||
print(market_analysis)
|
||||
```
|
||||
|
||||
### Customer Data Analysis Agent
|
||||
|
||||
```python
|
||||
customer_analysis_agent = Agent(
|
||||
name="CustomerAnalyst",
|
||||
instructions="""
|
||||
You are a customer data analyst who specializes in understanding customer behavior.
|
||||
|
||||
When analyzing customer data:
|
||||
1. Identify customer segments and patterns
|
||||
2. Analyze purchasing behavior
|
||||
3. Evaluate customer satisfaction metrics
|
||||
4. Identify opportunities to improve customer experience
|
||||
5. Recommend strategies for customer retention and growth
|
||||
|
||||
Present your analysis with sections for:
|
||||
- Customer Segmentation
|
||||
- Behavior Patterns
|
||||
- Key Insights
|
||||
- Recommended Actions
|
||||
""",
|
||||
tools=[stats_tool]
|
||||
)
|
||||
|
||||
# Use the customer analysis agent
|
||||
customer_data = """
|
||||
Customer Segments by Age:
|
||||
18-24: 15% of customers (Avg. Purchase: $45)
|
||||
25-34: 32% of customers (Avg. Purchase: $78)
|
||||
35-44: 28% of customers (Avg. Purchase: $92)
|
||||
45-54: 18% of customers (Avg. Purchase: $85)
|
||||
55+: 7% of customers (Avg. Purchase: $65)
|
||||
|
||||
Customer Satisfaction:
|
||||
Very Satisfied: 42%
|
||||
Satisfied: 35%
|
||||
Neutral: 15%
|
||||
Dissatisfied: 6%
|
||||
Very Dissatisfied: 2%
|
||||
|
||||
Repeat Purchase Rate:
|
||||
One-time: 40%
|
||||
2-5 purchases: 35%
|
||||
6-10 purchases: 15%
|
||||
10+ purchases: 10%
|
||||
"""
|
||||
|
||||
customer_analysis = customer_analysis_agent.start(
|
||||
f"""
|
||||
Analyze the following customer data:
|
||||
|
||||
{customer_data}
|
||||
|
||||
Provide insights on customer segments, behavior patterns, and recommendations to improve customer retention.
|
||||
"""
|
||||
)
|
||||
print(customer_analysis)
|
||||
```
|
||||
|
||||
## Data Visualization Recommendations
|
||||
|
||||
While our agents can't directly create visualizations, they can recommend appropriate visualization types:
|
||||
|
||||
```python
|
||||
visualization_agent = Agent(
|
||||
name="VisualizationAdvisor",
|
||||
instructions="""
|
||||
You are a data visualization specialist who helps select the best ways to visually represent data.
|
||||
|
||||
When recommending visualizations:
|
||||
1. Understand the nature of the data (categorical, numerical, time-series, etc.)
|
||||
2. Consider the key relationships or patterns to highlight
|
||||
3. Recommend the most appropriate chart or graph type
|
||||
4. Explain why your recommendation is effective
|
||||
5. Provide suggestions for layout, color scheme, and labeling
|
||||
|
||||
Common visualization types to consider:
|
||||
- Line charts (for trends over time)
|
||||
- Bar charts (for comparing categories)
|
||||
- Pie charts (for showing composition, use sparingly)
|
||||
- Scatter plots (for showing relationships between variables)
|
||||
- Heatmaps (for showing patterns in complex data)
|
||||
- Box plots (for showing distributions)
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the visualization agent
|
||||
viz_recommendations = visualization_agent.start(
|
||||
"""
|
||||
I have the following data and need visualization recommendations:
|
||||
|
||||
1. Monthly sales data for the past year
|
||||
2. Customer satisfaction ratings across 5 product categories
|
||||
3. Market share compared to 3 competitors
|
||||
4. Customer age distribution
|
||||
|
||||
What visualizations would you recommend for each of these datasets and why?
|
||||
"""
|
||||
)
|
||||
print(viz_recommendations)
|
||||
```
|
||||
|
||||
## Data Analysis Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Data Quality" icon="shield-check">
|
||||
Ensure data is accurate and complete
|
||||
</Card>
|
||||
<Card title="Context Matters" icon="circle-info">
|
||||
Consider external factors affecting data
|
||||
</Card>
|
||||
<Card title="Clear Communication" icon="comments">
|
||||
Present findings in understandable terms
|
||||
</Card>
|
||||
<Card title="Actionable Insights" icon="bolt">
|
||||
Focus on insights that lead to action
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build AI agents that can assist with customer support tasks.
|
||||
@@ -0,0 +1,260 @@
|
||||
---
|
||||
title: "Customer Support Agents"
|
||||
description: "Building agents that handle customer inquiries and issues"
|
||||
icon: "headset"
|
||||
---
|
||||
|
||||
# Customer Support Agents
|
||||
|
||||
Customer support agents can handle inquiries, resolve issues, and provide assistance to users. In this lesson, we'll learn how to build effective customer support agents.
|
||||
|
||||
## What is a Customer Support Agent?
|
||||
|
||||
A customer support agent is designed to:
|
||||
- Answer frequently asked questions
|
||||
- Troubleshoot common problems
|
||||
- Provide information about products or services
|
||||
- Collect information for support tickets
|
||||
- Guide users through processes or procedures
|
||||
|
||||
## Creating a Basic Customer Support Agent
|
||||
|
||||
Let's start by building a simple customer support agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic customer support agent
|
||||
support_agent = Agent(
|
||||
name="SupportAgent",
|
||||
instructions="""
|
||||
You are a helpful customer support representative for a software company.
|
||||
|
||||
When helping customers:
|
||||
1. Greet them professionally and warmly
|
||||
2. Understand their issue completely before attempting to solve it
|
||||
3. Provide clear, step-by-step solutions when possible
|
||||
4. Maintain a friendly, patient tone throughout
|
||||
5. If you cannot solve the issue, explain how to escalate it
|
||||
|
||||
Our software product is a productivity app with features for:
|
||||
- Task management
|
||||
- Calendar scheduling
|
||||
- Note-taking
|
||||
- Team collaboration
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the support agent
|
||||
response = support_agent.start("I'm having trouble syncing my calendar with my phone. Can you help?")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Adding a Knowledge Base
|
||||
|
||||
Let's enhance our agent with a simple knowledge base to answer common questions:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, KnowledgeBase
|
||||
|
||||
# Create a simple knowledge base
|
||||
faq_kb = KnowledgeBase()
|
||||
|
||||
# Add FAQ content (in a real scenario, you would load this from files)
|
||||
faq_kb.add_text("""
|
||||
# Frequently Asked Questions
|
||||
|
||||
## Account Issues
|
||||
|
||||
### How do I reset my password?
|
||||
To reset your password:
|
||||
1. Go to the login page
|
||||
2. Click on "Forgot Password"
|
||||
3. Enter your email address
|
||||
4. Follow the instructions sent to your email
|
||||
|
||||
### How do I change my email address?
|
||||
To change your email address:
|
||||
1. Log in to your account
|
||||
2. Go to Settings > Account
|
||||
3. Click on "Change Email"
|
||||
4. Enter your new email and confirm with your password
|
||||
|
||||
## Subscription and Billing
|
||||
|
||||
### What subscription plans do you offer?
|
||||
We offer three plans:
|
||||
- Basic: $9.99/month - Includes core features for individuals
|
||||
- Pro: $19.99/month - Includes advanced features and team capabilities for up to 5 users
|
||||
- Enterprise: Custom pricing - Full feature set with advanced security and support
|
||||
|
||||
### How do I cancel my subscription?
|
||||
To cancel your subscription:
|
||||
1. Log in to your account
|
||||
2. Go to Settings > Billing
|
||||
3. Click "Cancel Subscription"
|
||||
4. Follow the confirmation steps
|
||||
|
||||
## Technical Issues
|
||||
|
||||
### Why isn't my calendar syncing?
|
||||
Common reasons for calendar sync issues:
|
||||
1. Outdated app version - Try updating the app
|
||||
2. Account permission issues - Check sync permissions in Settings > Integrations
|
||||
3. Internet connectivity problems - Ensure you have a stable connection
|
||||
|
||||
### How do I export my data?
|
||||
To export your data:
|
||||
1. Go to Settings > Data
|
||||
2. Click "Export Data"
|
||||
3. Choose the data types you want to export
|
||||
4. Select your preferred format (CSV or JSON)
|
||||
5. Click "Export" and save the file
|
||||
""")
|
||||
|
||||
# Create an agent with the knowledge base
|
||||
kb_support_agent = Agent(
|
||||
name="KnowledgeBaseAgent",
|
||||
instructions="""
|
||||
You are a helpful customer support representative with access to our FAQ knowledge base.
|
||||
|
||||
When helping customers:
|
||||
1. Greet them professionally and warmly
|
||||
2. Search the knowledge base for relevant information
|
||||
3. Provide clear, accurate answers based on the knowledge base
|
||||
4. If the knowledge base doesn't cover the question, provide general helpful guidance
|
||||
5. Maintain a friendly, supportive tone throughout
|
||||
""",
|
||||
knowledge_base=faq_kb
|
||||
)
|
||||
|
||||
# Use the knowledge base support agent
|
||||
kb_response = kb_support_agent.start("How do I cancel my subscription?")
|
||||
print(kb_response)
|
||||
```
|
||||
|
||||
## Creating a Troubleshooting Agent
|
||||
|
||||
Let's create an agent specialized in technical troubleshooting:
|
||||
|
||||
```python
|
||||
troubleshooting_agent = Agent(
|
||||
name="TroubleshootingAgent",
|
||||
instructions="""
|
||||
You are a technical support specialist who helps users troubleshoot problems.
|
||||
|
||||
When troubleshooting:
|
||||
1. Ask clarifying questions to understand the exact issue
|
||||
2. Identify the most likely causes of the problem
|
||||
3. Provide step-by-step solutions, starting with the simplest fixes
|
||||
4. Explain what each step does and why it might help
|
||||
5. Confirm if the issue is resolved or suggest next steps
|
||||
|
||||
Common troubleshooting areas:
|
||||
- Login and account access issues
|
||||
- App installation and updates
|
||||
- Feature functionality problems
|
||||
- Data synchronization
|
||||
- Performance issues
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the troubleshooting agent
|
||||
troubleshooting_response = troubleshooting_agent.start("The app keeps crashing when I try to open it on my iPhone")
|
||||
print(troubleshooting_response)
|
||||
```
|
||||
|
||||
## Building a Conversational Support Agent
|
||||
|
||||
Let's create a support agent that can handle multi-turn conversations:
|
||||
|
||||
```python
|
||||
conversational_support = Agent(
|
||||
name="ConversationalSupport",
|
||||
instructions="""
|
||||
You are a customer support representative who handles support conversations.
|
||||
|
||||
When handling support conversations:
|
||||
1. Maintain context throughout the conversation
|
||||
2. Ask follow-up questions when needed
|
||||
3. Verify understanding before providing solutions
|
||||
4. Be patient with users who may be frustrated
|
||||
5. Summarize the conversation and next steps at the end
|
||||
|
||||
Our product is a mobile banking app with features for:
|
||||
- Account balance checking
|
||||
- Money transfers
|
||||
- Bill payments
|
||||
- Mobile check deposits
|
||||
- Budget tracking
|
||||
"""
|
||||
)
|
||||
|
||||
# Start a support conversation
|
||||
initial_response = conversational_support.start("I can't find where to deposit checks in the app")
|
||||
print("Initial Response:", initial_response)
|
||||
|
||||
# Continue the conversation
|
||||
follow_up_response = conversational_support.continue("I'm using version 2.5 of the app on Android")
|
||||
print("Follow-up Response:", follow_up_response)
|
||||
|
||||
# Further continuation
|
||||
resolution_response = conversational_support.continue("I found the deposit button now, but it's giving me an error when I try to take a photo")
|
||||
print("Resolution Response:", resolution_response)
|
||||
```
|
||||
|
||||
## Support Ticket Creation Agent
|
||||
|
||||
Let's create an agent that can gather information for support tickets:
|
||||
|
||||
```python
|
||||
ticket_agent = Agent(
|
||||
name="TicketCreationAgent",
|
||||
instructions="""
|
||||
You are a support ticket creation specialist who gathers the necessary information to create support tickets.
|
||||
|
||||
When creating a ticket:
|
||||
1. Collect the customer's name and contact information
|
||||
2. Identify the category of the issue
|
||||
3. Gather a detailed description of the problem
|
||||
4. Determine the severity level
|
||||
5. Collect relevant technical details (device, software version, etc.)
|
||||
6. Organize all information in a structured ticket format
|
||||
|
||||
Present the final ticket in a clearly formatted structure.
|
||||
"""
|
||||
)
|
||||
|
||||
# Use the ticket creation agent
|
||||
ticket = ticket_agent.start(
|
||||
"""
|
||||
Create a support ticket for the following issue:
|
||||
|
||||
Customer: Jane Smith
|
||||
Email: [email protected]
|
||||
Issue: Cannot access premium features after payment
|
||||
Details: Completed payment yesterday, received confirmation email, but premium features are still locked in the app
|
||||
Using: iPhone 13, app version 3.2.1
|
||||
"""
|
||||
)
|
||||
print(ticket)
|
||||
```
|
||||
|
||||
## Customer Support Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Empathy First" icon="heart">
|
||||
Show understanding before offering solutions
|
||||
</Card>
|
||||
<Card title="Clear Communication" icon="comment">
|
||||
Use simple language, avoid jargon
|
||||
</Card>
|
||||
<Card title="Consistent Responses" icon="equals">
|
||||
Provide consistent answers to similar questions
|
||||
</Card>
|
||||
<Card title="Know Escalation Paths" icon="arrow-up-right">
|
||||
Have clear processes for escalating complex issues
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to build AI agents that can assist with personal productivity tasks.
|
||||
@@ -0,0 +1,270 @@
|
||||
---
|
||||
title: "Personal Assistant Agents"
|
||||
description: "Building agents that help with personal tasks and productivity"
|
||||
icon: "calendar-check"
|
||||
---
|
||||
|
||||
# Personal Assistant Agents
|
||||
|
||||
Personal assistant agents can help users manage tasks, organize information, and increase productivity. In this lesson, we'll learn how to build effective personal assistant agents.
|
||||
|
||||
## What is a Personal Assistant Agent?
|
||||
|
||||
A personal assistant agent is designed to:
|
||||
- Manage tasks and reminders
|
||||
- Organize information
|
||||
- Answer questions
|
||||
- Provide recommendations
|
||||
- Help with personal productivity
|
||||
|
||||
## Creating a Basic Personal Assistant Agent
|
||||
|
||||
Let's start by building a simple personal assistant agent:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Create a basic personal assistant agent
|
||||
assistant_agent = Agent(
|
||||
name="PersonalAssistant",
|
||||
instructions="""
|
||||
You are a helpful personal assistant who helps users manage tasks and information.
|
||||
|
||||
When assisting users:
|
||||
1. Be concise and efficient in your responses
|
||||
2. Prioritize user requests based on importance and urgency
|
||||
3. Maintain a helpful, friendly tone
|
||||
4. Remember important information the user shares
|
||||
5. Proactively suggest relevant information when appropriate
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the personal assistant agent
|
||||
response = assistant_agent.start("I need to plan a meeting with my team next Tuesday at 2 PM")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Task Management Assistant
|
||||
|
||||
Let's create an agent specialized in task management:
|
||||
|
||||
```python
|
||||
task_agent = Agent(
|
||||
name="TaskManager",
|
||||
instructions="""
|
||||
You are a task management assistant who helps users organize and prioritize tasks.
|
||||
|
||||
When managing tasks:
|
||||
1. Help identify and clarify tasks
|
||||
2. Assist with prioritization
|
||||
3. Break down complex tasks into manageable steps
|
||||
4. Track deadlines and progress
|
||||
5. Provide reminders and follow-ups
|
||||
|
||||
For each task, collect:
|
||||
- Task description
|
||||
- Priority (High, Medium, Low)
|
||||
- Deadline (if applicable)
|
||||
- Dependencies (other tasks that must be completed first)
|
||||
- Estimated time required
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the task management agent
|
||||
task_response = task_agent.start(
|
||||
"""
|
||||
I need help organizing these tasks for the week:
|
||||
|
||||
- Prepare quarterly report (due Friday)
|
||||
- Meet with client about new project (Wednesday, 2 PM)
|
||||
- Review team's project proposals
|
||||
- Finish budget planning for next quarter
|
||||
- Send feedback on marketing materials
|
||||
"""
|
||||
)
|
||||
print(task_response)
|
||||
```
|
||||
|
||||
## Information Organization Assistant
|
||||
|
||||
Let's create an agent that helps organize information:
|
||||
|
||||
```python
|
||||
info_agent = Agent(
|
||||
name="InformationOrganizer",
|
||||
instructions="""
|
||||
You are an information organization assistant who helps users structure and categorize information.
|
||||
|
||||
When organizing information:
|
||||
1. Identify the main categories and topics
|
||||
2. Create logical groupings
|
||||
3. Suggest clear labels and headers
|
||||
4. Establish relationships between different pieces of information
|
||||
5. Present information in a structured, easily navigable format
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the information organization agent
|
||||
info_response = info_agent.start(
|
||||
"""
|
||||
Help me organize my research notes on climate change:
|
||||
|
||||
- Rising sea levels affecting coastal cities
|
||||
- Carbon dioxide levels increasing annually
|
||||
- Renewable energy adoption statistics by country
|
||||
- Impact of deforestation on carbon sequestration
|
||||
- Climate policy differences between EU and US
|
||||
- Economic impacts of extreme weather events
|
||||
- Public opinion polls on climate action
|
||||
- Arctic ice sheet measurements over 50 years
|
||||
- Agricultural adaptations to changing climate
|
||||
"""
|
||||
)
|
||||
print(info_response)
|
||||
```
|
||||
|
||||
## Daily Planning Assistant
|
||||
|
||||
Let's create an agent that helps with daily planning:
|
||||
|
||||
```python
|
||||
planning_agent = Agent(
|
||||
name="DailyPlanner",
|
||||
instructions="""
|
||||
You are a daily planning assistant who helps users organize their day efficiently.
|
||||
|
||||
When helping with daily planning:
|
||||
1. Prioritize tasks based on importance and deadlines
|
||||
2. Consider time constraints and commitments
|
||||
3. Suggest efficient scheduling
|
||||
4. Allow for breaks and transitions
|
||||
5. Balance work tasks with personal needs
|
||||
|
||||
Create a structured daily plan with time blocks and priorities.
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the daily planning agent
|
||||
planning_response = planning_agent.start(
|
||||
"""
|
||||
Help me plan my day tomorrow. I have:
|
||||
|
||||
- A team meeting from 9:30-10:30 AM
|
||||
- A report due by end of day
|
||||
- Emails to catch up on (about 1 hour's worth)
|
||||
- Lunch with a colleague at 12:30 PM
|
||||
- A dentist appointment at 3:00 PM (will take about 1 hour including travel)
|
||||
- Need to prepare a presentation for Friday
|
||||
|
||||
I typically work from 8:30 AM to 5:30 PM and prefer to have short breaks between tasks.
|
||||
"""
|
||||
)
|
||||
print(planning_response)
|
||||
```
|
||||
|
||||
## Decision Support Assistant
|
||||
|
||||
Let's create an agent that helps with decision-making:
|
||||
|
||||
```python
|
||||
decision_agent = Agent(
|
||||
name="DecisionSupport",
|
||||
instructions="""
|
||||
You are a decision support assistant who helps users make informed choices.
|
||||
|
||||
When supporting decisions:
|
||||
1. Help clarify the decision to be made
|
||||
2. Identify relevant criteria and factors
|
||||
3. Present pros and cons for each option
|
||||
4. Ask questions to understand preferences and priorities
|
||||
5. Provide a structured analysis without making the final decision
|
||||
|
||||
Present options with balanced information to help the user make their own informed choice.
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the decision support agent
|
||||
decision_response = decision_agent.start(
|
||||
"""
|
||||
I'm trying to decide whether to buy a new laptop now or wait 3 months.
|
||||
|
||||
Current situation:
|
||||
- My current laptop is 4 years old and running slow
|
||||
- It still works but has battery issues
|
||||
- I use it daily for work (programming and video calls)
|
||||
- I've heard new models are coming out in 3 months
|
||||
- My budget is around $1,500
|
||||
|
||||
What should I consider in making this decision?
|
||||
"""
|
||||
)
|
||||
print(decision_response)
|
||||
```
|
||||
|
||||
## Recommendation Assistant
|
||||
|
||||
Let's create an agent that provides personalized recommendations:
|
||||
|
||||
```python
|
||||
recommendation_agent = Agent(
|
||||
name="RecommendationAssistant",
|
||||
instructions="""
|
||||
You are a recommendation assistant who provides personalized suggestions.
|
||||
|
||||
When making recommendations:
|
||||
1. Understand the user's preferences and requirements
|
||||
2. Consider constraints (budget, time, location, etc.)
|
||||
3. Provide diverse options that match the criteria
|
||||
4. Explain why each recommendation might be suitable
|
||||
5. Give enough detail for the user to evaluate options
|
||||
|
||||
For each recommendation, include:
|
||||
- A brief description
|
||||
- Key features or highlights
|
||||
- Why it matches the user's needs
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
# Use the recommendation agent
|
||||
recommendation_response = recommendation_agent.start(
|
||||
"""
|
||||
Can you recommend some books for me? I enjoy:
|
||||
|
||||
- Science fiction and fantasy
|
||||
- Books with complex, morally gray characters
|
||||
- Intricate world-building
|
||||
- Books that explore philosophical themes
|
||||
|
||||
I've recently read and enjoyed:
|
||||
- "The Fifth Season" by N.K. Jemisin
|
||||
- "Dune" by Frank Herbert
|
||||
- "The Lies of Locke Lamora" by Scott Lynch
|
||||
"""
|
||||
)
|
||||
print(recommendation_response)
|
||||
```
|
||||
|
||||
## Personal Assistant Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Respect Privacy" icon="lock">
|
||||
Be careful with personal information
|
||||
</Card>
|
||||
<Card title="Customize Interactions" icon="sliders">
|
||||
Adapt to the user's preferences
|
||||
</Card>
|
||||
<Card title="Clear Communication" icon="comment">
|
||||
Keep responses direct and easy to understand
|
||||
</Card>
|
||||
<Card title="Contextual Awareness" icon="puzzle-piece">
|
||||
Remember relevant context from previous interactions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
In the next lesson, we'll explore how to deploy and share your AI agents with others.
|
||||
@@ -0,0 +1,342 @@
|
||||
---
|
||||
title: "Deploying Agents"
|
||||
description: "How to deploy and share your AI agents with others"
|
||||
icon: "rocket"
|
||||
---
|
||||
|
||||
# Deploying Agents
|
||||
|
||||
After creating your AI agents, the next step is deploying them for use by yourself or others. In this final lesson, we'll explore different deployment options and best practices.
|
||||
|
||||
## Deployment Options
|
||||
|
||||
There are several ways to deploy your AI agents:
|
||||
|
||||
### 1. Local Deployment
|
||||
|
||||
Running your agents locally is the simplest approach:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def run_local_agent():
|
||||
agent = Agent(
|
||||
name="SimpleAgent",
|
||||
instructions="You are a helpful assistant that answers questions concisely.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
while True:
|
||||
user_input = input("Ask a question (type 'exit' to quit): ")
|
||||
if user_input.lower() == 'exit':
|
||||
break
|
||||
|
||||
response = agent.start(user_input)
|
||||
print("\nAgent response:")
|
||||
print(response)
|
||||
print("\n" + "-"*50 + "\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_local_agent()
|
||||
```
|
||||
|
||||
### 2. Web Application Deployment
|
||||
|
||||
You can deploy your agents as part of a web application:
|
||||
|
||||
```python
|
||||
from flask import Flask, request, jsonify
|
||||
from praisonaiagents import Agent
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Create agent once at startup
|
||||
support_agent = Agent(
|
||||
name="SupportAgent",
|
||||
instructions="You are a customer support agent that helps users with product questions.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
@app.route('/api/support', methods=['POST'])
|
||||
def get_support():
|
||||
data = request.json
|
||||
user_query = data.get('query', '')
|
||||
|
||||
if not user_query:
|
||||
return jsonify({"error": "No query provided"}), 400
|
||||
|
||||
try:
|
||||
response = support_agent.start(user_query)
|
||||
return jsonify({"response": response})
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
```
|
||||
|
||||
### 3. Serverless Function Deployment
|
||||
|
||||
For scalable, event-driven deployments, serverless functions work well:
|
||||
|
||||
```python
|
||||
# Example AWS Lambda function
|
||||
import json
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Initialize agent outside the handler for reuse across invocations
|
||||
agent = Agent(
|
||||
name="ServerlessAgent",
|
||||
instructions="You provide concise, helpful responses to user questions.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
def lambda_handler(event, context):
|
||||
try:
|
||||
# Get the user query from the event
|
||||
body = json.loads(event.get('body', '{}'))
|
||||
user_query = body.get('query', '')
|
||||
|
||||
if not user_query:
|
||||
return {
|
||||
'statusCode': 400,
|
||||
'body': json.dumps({'error': 'No query provided'})
|
||||
}
|
||||
|
||||
# Process with the agent
|
||||
response = agent.start(user_query)
|
||||
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': json.dumps({'response': response})
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'statusCode': 500,
|
||||
'body': json.dumps({'error': str(e)})
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables and Security
|
||||
|
||||
When deploying agents, it's crucial to handle API keys and secrets securely:
|
||||
|
||||
```python
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# Access API key from environment variable
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
|
||||
# Create agent with API key
|
||||
agent = Agent(
|
||||
name="SecureAgent",
|
||||
instructions="You are a helpful assistant.",
|
||||
llm="gpt-4o-mini", # Using the specified model
|
||||
api_key=api_key # Pass API key securely
|
||||
)
|
||||
```
|
||||
|
||||
## Creating a Simple Chat Interface
|
||||
|
||||
Here's a simple command-line chat interface for your agent:
|
||||
|
||||
```python
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def create_chat_interface():
|
||||
# Initialize agent
|
||||
agent = Agent(
|
||||
name="ChatAgent",
|
||||
instructions="""
|
||||
You are a conversational assistant that maintains context throughout the conversation.
|
||||
Respond in a helpful, concise manner.
|
||||
""",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
print("Chat with AI Assistant (type 'exit' to quit)")
|
||||
print("-" * 50)
|
||||
|
||||
# Start conversation
|
||||
conversation_active = True
|
||||
first_message = True
|
||||
|
||||
while conversation_active:
|
||||
# Get user input
|
||||
user_message = input("You: ")
|
||||
|
||||
# Check if user wants to exit
|
||||
if user_message.lower() == 'exit':
|
||||
print("Goodbye!")
|
||||
conversation_active = False
|
||||
continue
|
||||
|
||||
# Get agent response
|
||||
try:
|
||||
if first_message:
|
||||
response = agent.start(user_message)
|
||||
first_message = False
|
||||
else:
|
||||
response = agent.continue(user_message)
|
||||
|
||||
print("\nAssistant:", response)
|
||||
print("\n" + "-" * 50)
|
||||
except Exception as e:
|
||||
print(f"Error: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_chat_interface()
|
||||
```
|
||||
|
||||
## Scaling Considerations
|
||||
|
||||
As you deploy agents for wider use, consider these scaling factors:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Rate Limiting" icon="gauge-high">
|
||||
Implement rate limiting to manage API usage and costs
|
||||
</Card>
|
||||
<Card title="Caching" icon="database">
|
||||
Cache common responses to improve performance and reduce API calls
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="triangle-exclamation">
|
||||
Implement robust error handling for API failures
|
||||
</Card>
|
||||
<Card title="Monitoring" icon="chart-line">
|
||||
Set up monitoring for usage patterns and performance issues
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Best Practices for Deployment
|
||||
|
||||
### 1. Testing Before Deployment
|
||||
|
||||
Always test your agents thoroughly before deployment:
|
||||
|
||||
```python
|
||||
def test_agent_functionality():
|
||||
"""Test basic agent functionality with various inputs"""
|
||||
agent = Agent(
|
||||
name="TestAgent",
|
||||
instructions="You are a helpful assistant for testing.",
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
test_cases = [
|
||||
"What is artificial intelligence?",
|
||||
"How do I reset my password?",
|
||||
"Tell me about machine learning"
|
||||
]
|
||||
|
||||
for test_case in test_cases:
|
||||
print(f"\nTesting: {test_case}")
|
||||
response = agent.start(test_case)
|
||||
print(f"Response: {response[:100]}...") # Print first 100 chars
|
||||
|
||||
# Add assertions or validation logic here
|
||||
assert len(response) > 0, "Response should not be empty"
|
||||
```
|
||||
|
||||
### 2. Documentation
|
||||
|
||||
Create clear documentation for users of your agent:
|
||||
|
||||
```python
|
||||
"""
|
||||
# Customer Support Agent API
|
||||
|
||||
This API provides access to an AI customer support agent
|
||||
that can answer questions about our products.
|
||||
|
||||
## Authentication
|
||||
|
||||
Include your API key in the request header:
|
||||
```
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
```
|
||||
|
||||
## Endpoints
|
||||
|
||||
POST /api/support
|
||||
- Request body: {"query": "Your question here"}
|
||||
- Response: {"response": "Agent's answer"}
|
||||
|
||||
## Example
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://api.example.com/api/support",
|
||||
headers={"Authorization": "Bearer YOUR_API_KEY"},
|
||||
json={"query": "How do I reset my password?"}
|
||||
)
|
||||
|
||||
print(response.json())
|
||||
```
|
||||
"""
|
||||
```
|
||||
|
||||
### 3. Version Control
|
||||
|
||||
Implement version control for your agents to track changes:
|
||||
|
||||
```python
|
||||
class VersionedAgent:
|
||||
def __init__(self, name, version, instructions):
|
||||
self.name = name
|
||||
self.version = version
|
||||
self.agent = Agent(
|
||||
name=f"{name}_v{version}",
|
||||
instructions=instructions,
|
||||
llm="gpt-4o-mini" # Using the specified model
|
||||
)
|
||||
|
||||
def get_response(self, query):
|
||||
response = self.agent.start(query)
|
||||
return {
|
||||
"agent_name": self.name,
|
||||
"version": self.version,
|
||||
"response": response,
|
||||
"timestamp": datetime.now().isoformat()
|
||||
}
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
Congratulations on completing the AI Agents Course! You've learned how to:
|
||||
|
||||
1. Understand different types of AI agents and their architectures
|
||||
2. Create effective agent instructions and tools
|
||||
3. Implement memory and context for your agents
|
||||
4. Build specialized agents for various tasks
|
||||
5. Create multi-agent systems
|
||||
6. Deploy your agents for real-world use
|
||||
|
||||
As AI agent technology continues to evolve, keep experimenting with new capabilities and use cases. Remember that the best agents are those that effectively solve real problems for users while being trustworthy, reliable, and helpful.
|
||||
|
||||
We hope this course has provided you with the knowledge and skills to build powerful AI agents that enhance productivity and creativity!
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Join the Community" icon="users">
|
||||
Participate in discussions and share your agent projects
|
||||
</Card>
|
||||
<Card title="Stay Updated" icon="newspaper">
|
||||
Follow updates in AI agent technology and new features
|
||||
</Card>
|
||||
<Card title="Share Your Feedback" icon="comment">
|
||||
Let us know how you're using agents and what you'd like to learn next
|
||||
</Card>
|
||||
<Card title="Build Real Solutions" icon="lightbulb">
|
||||
Apply your knowledge to build solutions for real-world problems
|
||||
</Card>
|
||||
</CardGroup>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 134 KiB |
@@ -0,0 +1,416 @@
|
||||
---
|
||||
title: "Deploying to AWS"
|
||||
sidebarTitle: "AWS"
|
||||
description: "Deploy PraisonAI agents to Amazon Web Services for scalable production environments"
|
||||
icon: "aws"
|
||||
---
|
||||
|
||||
# Deploying PraisonAI Agents to AWS
|
||||
|
||||
This guide provides step-by-step instructions for deploying PraisonAI agents to Amazon Web Services (AWS), offering multiple deployment options to suit different requirements.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- AWS account with appropriate permissions
|
||||
- AWS CLI installed and configured
|
||||
- Docker installed on your local machine (for container-based deployments)
|
||||
- Basic knowledge of AWS services and cloud deployment
|
||||
|
||||
## Deployment Options
|
||||
|
||||
There are several ways to deploy PraisonAI agents to AWS:
|
||||
|
||||
1. **AWS Lambda with API Gateway** (for serverless deployments)
|
||||
2. **Amazon ECS/Fargate** (for containerized deployments)
|
||||
3. **Amazon EC2** (for traditional VM-based deployments)
|
||||
4. **AWS App Runner** (for simplified container deployments)
|
||||
|
||||
## Option 1: Deploying to EC2 (Traditional VM)
|
||||
|
||||
<Steps>
|
||||
<Step title="Launch an EC2 Instance">
|
||||
1. Go to the AWS Management Console
|
||||
2. Navigate to EC2 and click "Launch Instance"
|
||||
3. Choose Amazon Linux 2 or Ubuntu Server
|
||||
4. Select an instance type (t2.micro for testing, t2.medium or larger for production)
|
||||
5. Configure security groups to allow HTTP/HTTPS traffic
|
||||
6. Launch the instance and connect to it via SSH
|
||||
</Step>
|
||||
|
||||
<Step title="Set Up the Environment">
|
||||
```bash
|
||||
# Update system packages
|
||||
sudo apt update && sudo apt upgrade -y
|
||||
|
||||
# Install Python and pip
|
||||
sudo apt install -y python3 python3-pip
|
||||
|
||||
# Install required packages
|
||||
pip3 install "praisonaiagents[api]>=0.0.79"
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create the API Application">
|
||||
Create a file named `api.py`:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=8080, host="0.0.0.0")
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set Up a Systemd Service">
|
||||
Create a systemd service file to run your application as a background service:
|
||||
|
||||
```bash
|
||||
sudo nano /etc/systemd/system/praisonai-agent.service
|
||||
```
|
||||
|
||||
Add the following content:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=PraisonAI Agent API Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=ubuntu
|
||||
WorkingDirectory=/home/ubuntu
|
||||
Environment="OPENAI_API_KEY=your_api_key"
|
||||
ExecStart=/usr/bin/python3 /home/ubuntu/api.py
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
Enable and start the service:
|
||||
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable praisonai-agent
|
||||
sudo systemctl start praisonai-agent
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set Up Nginx as a Reverse Proxy">
|
||||
```bash
|
||||
# Install Nginx
|
||||
sudo apt install -y nginx
|
||||
|
||||
# Create a configuration file
|
||||
sudo nano /etc/nginx/sites-available/praisonai-agent
|
||||
```
|
||||
|
||||
Add the following configuration:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name your_domain.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Enable the site and restart Nginx:
|
||||
|
||||
```bash
|
||||
sudo ln -s /etc/nginx/sites-available/praisonai-agent /etc/nginx/sites-enabled/
|
||||
sudo nginx -t
|
||||
sudo systemctl restart nginx
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Option 2: Deploying with Docker and ECS/Fargate
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Run the application
|
||||
CMD ["python", "api.py"]
|
||||
```
|
||||
|
||||
Create a `requirements.txt` file:
|
||||
```
|
||||
praisonaiagents[api]>=0.0.79
|
||||
```
|
||||
|
||||
Create your `api.py` file:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=8080, host="0.0.0.0")
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Build and Push the Docker Image to ECR">
|
||||
```bash
|
||||
# Create an ECR repository
|
||||
aws ecr create-repository --repository-name praisonai-agent
|
||||
|
||||
# Get the login command
|
||||
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
|
||||
|
||||
# Build the Docker image
|
||||
docker build -t praisonai-agent .
|
||||
|
||||
# Tag the image
|
||||
docker tag praisonai-agent:latest YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest
|
||||
|
||||
# Push the image to ECR
|
||||
docker push YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create an ECS Cluster and Task Definition">
|
||||
```bash
|
||||
# Create an ECS cluster
|
||||
aws ecs create-cluster --cluster-name praisonai-cluster
|
||||
|
||||
# Create a task definition (JSON file)
|
||||
cat > task-definition.json << EOF
|
||||
{
|
||||
"family": "praisonai-agent",
|
||||
"networkMode": "awsvpc",
|
||||
"executionRoleArn": "arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/ecsTaskExecutionRole",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "praisonai-agent",
|
||||
"image": "YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest",
|
||||
"essential": true,
|
||||
"portMappings": [
|
||||
{
|
||||
"containerPort": 8080,
|
||||
"hostPort": 8080,
|
||||
"protocol": "tcp"
|
||||
}
|
||||
],
|
||||
"environment": [
|
||||
{
|
||||
"name": "OPENAI_API_KEY",
|
||||
"value": "your_api_key"
|
||||
}
|
||||
],
|
||||
"logConfiguration": {
|
||||
"logDriver": "awslogs",
|
||||
"options": {
|
||||
"awslogs-group": "/ecs/praisonai-agent",
|
||||
"awslogs-region": "us-east-1",
|
||||
"awslogs-stream-prefix": "ecs"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"requiresCompatibilities": [
|
||||
"FARGATE"
|
||||
],
|
||||
"cpu": "256",
|
||||
"memory": "512"
|
||||
}
|
||||
EOF
|
||||
|
||||
# Register the task definition
|
||||
aws ecs register-task-definition --cli-input-json file://task-definition.json
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a Fargate Service">
|
||||
```bash
|
||||
# Create a service
|
||||
aws ecs create-service \
|
||||
--cluster praisonai-cluster \
|
||||
--service-name praisonai-service \
|
||||
--task-definition praisonai-agent:1 \
|
||||
--desired-count 1 \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345678],securityGroups=[sg-12345678],assignPublicIp=ENABLED}" \
|
||||
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef,containerName=praisonai-agent,containerPort=8080"
|
||||
```
|
||||
|
||||
Note: You'll need to create an Application Load Balancer and target group before running this command.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Multi-Agent Deployment
|
||||
|
||||
For deploying multiple agents, you can use a single service with different endpoints:
|
||||
|
||||
```python
|
||||
# multi-agent-api.py
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=8080, host="0.0.0.0")
|
||||
stock_agent.launch(path="/stock", port=8080, host="0.0.0.0")
|
||||
travel_agent.launch(path="/travel", port=8080, host="0.0.0.0")
|
||||
```
|
||||
|
||||
## Option 3: Serverless Deployment with AWS Lambda
|
||||
|
||||
For lightweight agents that don't require long-running processes, you can use AWS Lambda with API Gateway:
|
||||
|
||||
```python
|
||||
# lambda_function.py
|
||||
from praisonaiagents import Agent
|
||||
import json
|
||||
|
||||
# Initialize the agent outside the handler for better cold start performance
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
|
||||
def lambda_handler(event, context):
|
||||
try:
|
||||
# Extract the message from the event
|
||||
body = json.loads(event.get('body', '{}'))
|
||||
message = body.get('message', '')
|
||||
|
||||
# Process the message with the agent
|
||||
response = agent.process(message)
|
||||
|
||||
# Return the response
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'headers': {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
},
|
||||
'body': json.dumps({
|
||||
'response': response
|
||||
})
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'statusCode': 500,
|
||||
'headers': {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
},
|
||||
'body': json.dumps({
|
||||
'error': str(e)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Scaling and Performance
|
||||
|
||||
### Auto Scaling
|
||||
|
||||
For EC2 deployments, set up an Auto Scaling group:
|
||||
|
||||
```bash
|
||||
# Create a launch template
|
||||
aws ec2 create-launch-template \
|
||||
--launch-template-name praisonai-template \
|
||||
--version-description "Initial version" \
|
||||
--launch-template-data '{"ImageId":"ami-12345678","InstanceType":"t2.medium","UserData":"#!/bin/bash\ncd /home/ubuntu\npython3 api.py &"}'
|
||||
|
||||
# Create an Auto Scaling group
|
||||
aws autoscaling create-auto-scaling-group \
|
||||
--auto-scaling-group-name praisonai-asg \
|
||||
--launch-template "LaunchTemplateName=praisonai-template,Version=1" \
|
||||
--min-size 1 \
|
||||
--max-size 5 \
|
||||
--desired-capacity 2 \
|
||||
--vpc-zone-identifier "subnet-12345678,subnet-87654321" \
|
||||
--target-group-arns "arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef"
|
||||
```
|
||||
|
||||
### Load Balancing
|
||||
|
||||
Set up an Application Load Balancer to distribute traffic:
|
||||
|
||||
```bash
|
||||
# Create a load balancer
|
||||
aws elbv2 create-load-balancer \
|
||||
--name praisonai-alb \
|
||||
--subnets subnet-12345678 subnet-87654321 \
|
||||
--security-groups sg-12345678
|
||||
|
||||
# Create a target group
|
||||
aws elbv2 create-target-group \
|
||||
--name praisonai-tg \
|
||||
--protocol HTTP \
|
||||
--port 8080 \
|
||||
--vpc-id vpc-12345678 \
|
||||
--target-type instance
|
||||
|
||||
# Create a listener
|
||||
aws elbv2 create-listener \
|
||||
--load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:loadbalancer/app/praisonai-alb/1234567890abcdef \
|
||||
--protocol HTTP \
|
||||
--port 80 \
|
||||
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Secret Management**: Use AWS Secrets Manager for API keys
|
||||
```bash
|
||||
# Store a secret
|
||||
aws secretsmanager create-secret \
|
||||
--name OPENAI_API_KEY \
|
||||
--secret-string "your_api_key"
|
||||
```
|
||||
|
||||
2. **IAM Roles**: Use the principle of least privilege
|
||||
3. **VPC**: Deploy in a private subnet with controlled access
|
||||
4. **WAF**: Set up AWS WAF to protect against common web exploits
|
||||
5. **API Gateway**: Implement request validation and throttling
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
1. **CloudWatch**: Set up dashboards and alarms
|
||||
```bash
|
||||
# Create a CloudWatch alarm for high CPU utilization
|
||||
aws cloudwatch put-metric-alarm \
|
||||
--alarm-name praisonai-high-cpu \
|
||||
--alarm-description "Alarm when CPU exceeds 80%" \
|
||||
--metric-name CPUUtilization \
|
||||
--namespace AWS/EC2 \
|
||||
--statistic Average \
|
||||
--period 300 \
|
||||
--threshold 80 \
|
||||
--comparison-operator GreaterThanThreshold \
|
||||
--dimensions Name=AutoScalingGroupName,Value=praisonai-asg \
|
||||
--evaluation-periods 2 \
|
||||
--alarm-actions arn:aws:sns:us-east-1:YOUR_AWS_ACCOUNT_ID:praisonai-alerts
|
||||
```
|
||||
|
||||
2. **X-Ray**: Enable tracing for detailed request analysis
|
||||
3. **CloudTrail**: Monitor API calls for security analysis
|
||||
4. **Log Insights**: Query and analyze logs with CloudWatch Log Insights
|
||||
@@ -0,0 +1,223 @@
|
||||
---
|
||||
title: "Deploying PraisonAI Agents as APIs"
|
||||
sidebarTitle: "API Deployment"
|
||||
description: "Learn how to deploy PraisonAI agents as RESTful APIs for production environments"
|
||||
icon: "server"
|
||||
---
|
||||
|
||||
PraisonAI agents can be easily deployed as RESTful APIs, allowing you to integrate them into various applications and services. This guide covers how to deploy both single and multiple agents as APIs.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
Make sure you have the required packages installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[api]"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY="your_api_key"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy a Simple Agent API">
|
||||
Create a file named `simple-api.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=3030)
|
||||
```
|
||||
</Step>
|
||||
<Step title="Run the API Server">
|
||||
```bash
|
||||
python simple-api.py
|
||||
```
|
||||
|
||||
Your API will be available at `http://localhost:3030/ask`
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Making API Requests
|
||||
|
||||
Once your agent is deployed, you can make POST requests to interact with it:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3030/ask \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "What is artificial intelligence?"}'
|
||||
```
|
||||
|
||||
The response will be in JSON format:
|
||||
|
||||
```json
|
||||
{
|
||||
"response": "Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. It encompasses various technologies including machine learning, natural language processing, computer vision, and robotics. AI systems can perform tasks that typically require human intelligence such as understanding natural language, recognizing patterns, solving problems, and making decisions."
|
||||
}
|
||||
```
|
||||
|
||||
## Multi-Agent API Deployment
|
||||
|
||||
You can deploy multiple agents on the same server, each with its own endpoint:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=3030)
|
||||
stock_agent.launch(path="/stock", port=3030)
|
||||
travel_agent.launch(path="/travel", port=3030)
|
||||
```
|
||||
|
||||
With this setup, you can access:
|
||||
- Weather agent at `http://localhost:3030/weather`
|
||||
- Stock agent at `http://localhost:3030/stock`
|
||||
- Travel agent at `http://localhost:3030/travel`
|
||||
|
||||
## Production Deployment Options
|
||||
|
||||
For production environments, consider the following deployment options:
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3030
|
||||
|
||||
CMD ["python", "api.py"]
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create requirements.txt">
|
||||
```
|
||||
praisonaiagents[api]>=0.0.79
|
||||
```
|
||||
</Step>
|
||||
<Step title="Build and Run Docker Container">
|
||||
```bash
|
||||
docker build -t praisonai-api .
|
||||
docker run -p 3030:3030 -e OPENAI_API_KEY=your_api_key praisonai-api
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Cloud Deployment
|
||||
|
||||
#### Deploying to AWS
|
||||
|
||||
<Steps>
|
||||
<Step title="Create an EC2 Instance">
|
||||
Launch an EC2 instance with Ubuntu or Amazon Linux.
|
||||
</Step>
|
||||
<Step title="Install Dependencies">
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y python3-pip
|
||||
pip install "praisonaiagents[api]"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Configure Security Group">
|
||||
Make sure to open port 3030 in your security group settings.
|
||||
</Step>
|
||||
<Step title="Run with Systemd">
|
||||
Create a systemd service file for automatic startup and management.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
#### Deploying to Google Cloud Run
|
||||
|
||||
<Steps>
|
||||
<Step title="Build Docker Image">
|
||||
```bash
|
||||
docker build -t gcr.io/your-project/praisonai-api .
|
||||
```
|
||||
</Step>
|
||||
<Step title="Push to Container Registry">
|
||||
```bash
|
||||
docker push gcr.io/your-project/praisonai-api
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy to Cloud Run">
|
||||
```bash
|
||||
gcloud run deploy praisonai-api \
|
||||
--image gcr.io/your-project/praisonai-api \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars="OPENAI_API_KEY=your_api_key"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## API Configuration Options
|
||||
|
||||
When launching your agent as an API, you can customize various parameters:
|
||||
|
||||
```python
|
||||
agent.launch(
|
||||
path="/custom-endpoint", # API endpoint path
|
||||
port=8080, # Port number
|
||||
host="0.0.0.0", # Host address (0.0.0.0 for external access)
|
||||
debug=True, # Enable debug mode
|
||||
cors_origins=["*"], # CORS configuration
|
||||
api_key="your-api-key" # Optional API key for authentication
|
||||
)
|
||||
```
|
||||
|
||||
## Securing Your API
|
||||
|
||||
For production deployments, consider implementing:
|
||||
|
||||
1. **API Key Authentication**: Require API keys for all requests
|
||||
2. **Rate Limiting**: Limit the number of requests per client
|
||||
3. **HTTPS**: Use SSL/TLS certificates for encrypted communication
|
||||
4. **Input Validation**: Validate all input data before processing
|
||||
|
||||
## Monitoring and Scaling
|
||||
|
||||
For production environments, consider:
|
||||
|
||||
1. **Load Balancing**: Distribute traffic across multiple instances
|
||||
2. **Auto-Scaling**: Automatically adjust resources based on demand
|
||||
3. **Logging**: Implement comprehensive logging for debugging
|
||||
4. **Monitoring**: Set up alerts for errors and performance issues
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="RESTful API" icon="server">
|
||||
Deploy your agents as standard RESTful APIs for easy integration.
|
||||
</Card>
|
||||
<Card title="Multi-Agent Support" icon="users">
|
||||
Deploy multiple agents with different endpoints on the same server.
|
||||
</Card>
|
||||
<Card title="Customizable" icon="gear">
|
||||
Configure ports, paths, CORS settings, and more.
|
||||
</Card>
|
||||
<Card title="Production-Ready" icon="rocket">
|
||||
Easily deploy to Docker, AWS, Google Cloud, or other cloud platforms.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,248 @@
|
||||
---
|
||||
title: "Deploying to Google Cloud"
|
||||
sidebarTitle: "Google Cloud"
|
||||
description: "Deploy PraisonAI agents to Google Cloud Platform for scalable production environments"
|
||||
icon: "google"
|
||||
---
|
||||
|
||||
# Deploying PraisonAI Agents to Google Cloud
|
||||
|
||||
This guide provides step-by-step instructions for deploying PraisonAI agents to Google Cloud Platform using Cloud Run, which offers a serverless environment for containerized applications.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Google Cloud account with billing enabled
|
||||
- Google Cloud SDK installed and configured
|
||||
- Docker installed on your local machine
|
||||
- Basic knowledge of containerization and cloud deployment
|
||||
|
||||
## Deployment Options
|
||||
|
||||
There are several ways to deploy PraisonAI agents to Google Cloud:
|
||||
|
||||
1. **Google Cloud Run** (recommended for most use cases)
|
||||
2. **Google Compute Engine** (for custom VM requirements)
|
||||
3. **Google Kubernetes Engine** (for complex, scalable deployments)
|
||||
|
||||
This guide focuses on Cloud Run as it's the simplest and most cost-effective option for most deployments.
|
||||
|
||||
## Deploying to Google Cloud Run
|
||||
|
||||
<Steps>
|
||||
<Step title="Prepare Your Application">
|
||||
Create a simple API file named `api.py`:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
|
||||
agent.launch(path="/ask", port=8080, host="0.0.0.0")
|
||||
```
|
||||
|
||||
Note: Cloud Run expects your application to listen on the port defined by the `PORT` environment variable, which defaults to 8080.
|
||||
</Step>
|
||||
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Set environment variables
|
||||
ENV PORT=8080
|
||||
|
||||
# Run the application
|
||||
CMD exec python api.py
|
||||
```
|
||||
|
||||
Create a `requirements.txt` file:
|
||||
```
|
||||
praisonaiagents[api]>=0.0.79
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Build and Push the Docker Image">
|
||||
```bash
|
||||
# Build the Docker image
|
||||
docker build -t gcr.io/YOUR_PROJECT_ID/praisonai-agent .
|
||||
|
||||
# Configure Docker to use Google Cloud credentials
|
||||
gcloud auth configure-docker
|
||||
|
||||
# Push the image to Google Container Registry
|
||||
docker push gcr.io/YOUR_PROJECT_ID/praisonai-agent
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Deploy to Cloud Run">
|
||||
```bash
|
||||
gcloud run deploy praisonai-agent \
|
||||
--image gcr.io/YOUR_PROJECT_ID/praisonai-agent \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars="OPENAI_API_KEY=your_api_key"
|
||||
```
|
||||
|
||||
Note: For production deployments, it's recommended to use Secret Manager for API keys instead of environment variables.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Multi-Agent Deployment
|
||||
|
||||
For deploying multiple agents, you can use a single Cloud Run service with different endpoints:
|
||||
|
||||
```python
|
||||
# multi-agent-api.py
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=8080, host="0.0.0.0")
|
||||
stock_agent.launch(path="/stock", port=8080, host="0.0.0.0")
|
||||
travel_agent.launch(path="/travel", port=8080, host="0.0.0.0")
|
||||
```
|
||||
|
||||
## Scaling and Performance
|
||||
|
||||
Google Cloud Run automatically scales based on traffic, from zero to many instances. You can configure:
|
||||
|
||||
- **Minimum instances**: Keep a certain number of instances warm to avoid cold starts
|
||||
- **Maximum instances**: Limit the number of instances to control costs
|
||||
- **Memory allocation**: Allocate more memory for complex agents
|
||||
- **CPU allocation**: Allocate dedicated CPUs for compute-intensive workloads
|
||||
|
||||
```bash
|
||||
gcloud run services update praisonai-agent \
|
||||
--min-instances=1 \
|
||||
--max-instances=10 \
|
||||
--memory=2Gi \
|
||||
--cpu=1
|
||||
```
|
||||
|
||||
## Continuous Deployment
|
||||
|
||||
Set up continuous deployment with Cloud Build:
|
||||
|
||||
```yaml
|
||||
# cloudbuild.yaml
|
||||
steps:
|
||||
# Build the container image
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args: ['build', '-t', 'gcr.io/$PROJECT_ID/praisonai-agent', '.']
|
||||
# Push the container image to Container Registry
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args: ['push', 'gcr.io/$PROJECT_ID/praisonai-agent']
|
||||
# Deploy container image to Cloud Run
|
||||
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
|
||||
entrypoint: gcloud
|
||||
args:
|
||||
- 'run'
|
||||
- 'deploy'
|
||||
- 'praisonai-agent'
|
||||
- '--image'
|
||||
- 'gcr.io/$PROJECT_ID/praisonai-agent'
|
||||
- '--region'
|
||||
- 'us-central1'
|
||||
- '--platform'
|
||||
- 'managed'
|
||||
- '--allow-unauthenticated'
|
||||
substitutions:
|
||||
_REGION: us-central1
|
||||
images:
|
||||
- 'gcr.io/$PROJECT_ID/praisonai-agent'
|
||||
```
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
Google Cloud provides comprehensive monitoring and logging capabilities:
|
||||
|
||||
- **Cloud Monitoring**: Set up dashboards and alerts for your deployed agents
|
||||
- **Cloud Logging**: View and analyze logs from your applications
|
||||
- **Error Reporting**: Automatically detect and group errors
|
||||
|
||||
Access logs through the Google Cloud Console or using the gcloud command:
|
||||
|
||||
```bash
|
||||
gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=praisonai-agent" --limit=10
|
||||
```
|
||||
|
||||
## Cost Optimization
|
||||
|
||||
Cloud Run charges based on the resources your service uses only when it's processing requests. To optimize costs:
|
||||
|
||||
1. Set appropriate memory and CPU allocations
|
||||
2. Configure minimum instances based on traffic patterns
|
||||
3. Use regional deployments closest to your users
|
||||
4. Implement caching for frequent requests
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Secret Management**: Store API keys and credentials in Secret Manager
|
||||
```bash
|
||||
# Create a secret
|
||||
echo -n "your_api_key" | gcloud secrets create openai-api-key --data-file=-
|
||||
|
||||
# Grant access to the Cloud Run service
|
||||
gcloud secrets add-iam-policy-binding openai-api-key \
|
||||
--member=serviceAccount:YOUR_SERVICE_ACCOUNT \
|
||||
--role=roles/secretmanager.secretAccessor
|
||||
|
||||
# Reference in deployment
|
||||
gcloud run deploy praisonai-agent \
|
||||
--image gcr.io/YOUR_PROJECT_ID/praisonai-agent \
|
||||
--set-secrets=OPENAI_API_KEY=openai-api-key:latest
|
||||
```
|
||||
|
||||
2. **Service Identity**: Use dedicated service accounts with minimal permissions
|
||||
3. **Network Security**: Configure VPC Service Controls for sensitive deployments
|
||||
4. **API Authentication**: Implement authentication for your API endpoints
|
||||
|
||||
## All in One
|
||||
|
||||
```bash
|
||||
gcloud init
|
||||
gcloud services enable run.googleapis.com
|
||||
gcloud services enable containerregistry.googleapis.com
|
||||
gcloud services enable cloudbuild.googleapis.com
|
||||
|
||||
export OPENAI_MODEL_NAME="gpt-4o"
|
||||
export OPENAI_API_KEY="Enter your API key"
|
||||
export OPENAI_API_BASE="https://api.openai.com/v1"
|
||||
|
||||
yes | gcloud auth configure-docker us-central1-docker.pkg.dev
|
||||
gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1
|
||||
|
||||
PROJECT_ID=$(gcloud config get-value project)
|
||||
TAG="latest"
|
||||
docker build --platform linux/amd64 -t gcr.io/${PROJECT_ID}/praisonai-app:${TAG} .
|
||||
docker tag gcr.io/${PROJECT_ID}/praisonai-app:${TAG} us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
|
||||
docker push us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
|
||||
|
||||
gcloud run deploy praisonai-service \
|
||||
--image us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG} \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars OPENAI_MODEL_NAME=${OPENAI_MODEL_NAME},OPENAI_API_KEY=${OPENAI_API_KEY},OPENAI_API_BASE=${OPENAI_API_BASE}
|
||||
```
|
||||
@@ -0,0 +1,405 @@
|
||||
---
|
||||
title: "Deploying MCP Servers"
|
||||
sidebarTitle: "MCP Servers"
|
||||
description: "Learn how to deploy Model Context Protocol (MCP) servers for production environments"
|
||||
icon: "server-rack"
|
||||
---
|
||||
|
||||
# Deploying MCP Servers
|
||||
|
||||
This guide focuses on deploying Model Context Protocol (MCP) servers for production environments. MCP servers allow AI models to access tools and external systems through a standardized protocol.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
Make sure you have the required packages installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[mcp]"
|
||||
```
|
||||
|
||||
For the multi-agent example with search capabilities:
|
||||
```bash
|
||||
pip install "praisonaiagents[mcp]" duckduckgo-search
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create MCP Server Files">
|
||||
**Single Agent MCP Server**
|
||||
|
||||
Create a file named `simple-mcp-server.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(instructions="Create a Tweet based on the topic provided")
|
||||
agent.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
|
||||
**Multi-Agent MCP Server with Custom Tools**
|
||||
|
||||
Create a file named `simple-mcp-multi-agents-server.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
agent = Agent(instructions="You Search the internet for information", tools=[internet_search_tool])
|
||||
agent2 = Agent(instructions="You Summarise the information")
|
||||
|
||||
agents = Agents(agents=[agent, agent2])
|
||||
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
|
||||
**Simple Multi-Agent MCP Server**
|
||||
|
||||
Create a file named `simple-multi-agents-server.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents
|
||||
|
||||
agent = Agent(instructions="You Search the internet for information")
|
||||
agent2 = Agent(instructions="You Summarise the information")
|
||||
|
||||
agents = Agents(agents=[agent, agent2])
|
||||
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def internet_search_tool(query: str):
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=5):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
agent = Agent(instructions="You Search the internet for information", tools=[internet_search_tool])
|
||||
agent2 = Agent(instructions="You Summarise the information")
|
||||
|
||||
agents = Agents(agents=[agent, agent2])
|
||||
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Containerization with Docker
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Expose the port
|
||||
EXPOSE 8080
|
||||
|
||||
# Run the MCP server
|
||||
CMD ["python", "simple-mcp-server.py"]
|
||||
```
|
||||
|
||||
Create a `requirements.txt` file:
|
||||
```
|
||||
praisonaiagents[mcp]
|
||||
duckduckgo-search # Only needed for the multi-agent example
|
||||
```
|
||||
</Step>
|
||||
<Step title="Build and Run the Docker Container">
|
||||
```bash
|
||||
# Build the Docker image
|
||||
docker build -t mcp-server .
|
||||
|
||||
# Run the container
|
||||
docker run -p 8080:8080 -e OPENAI_API_KEY=your_api_key mcp-server
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Cloud Deployment
|
||||
|
||||
### AWS Elastic Container Service (ECS)
|
||||
|
||||
<Steps>
|
||||
<Step title="Push Docker Image to ECR">
|
||||
```bash
|
||||
# Create an ECR repository
|
||||
aws ecr create-repository --repository-name mcp-server
|
||||
|
||||
# Authenticate Docker to ECR
|
||||
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
|
||||
|
||||
# Tag and push the image
|
||||
docker tag mcp-server:latest YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest
|
||||
docker push YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create ECS Task Definition">
|
||||
```json
|
||||
{
|
||||
"family": "mcp-server",
|
||||
"networkMode": "awsvpc",
|
||||
"executionRoleArn": "arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/ecsTaskExecutionRole",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "mcp-server",
|
||||
"image": "YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest",
|
||||
"essential": true,
|
||||
"portMappings": [
|
||||
{
|
||||
"containerPort": 8080,
|
||||
"hostPort": 8080,
|
||||
"protocol": "tcp"
|
||||
}
|
||||
],
|
||||
"environment": [
|
||||
{
|
||||
"name": "OPENAI_API_KEY",
|
||||
"value": "your_api_key"
|
||||
}
|
||||
],
|
||||
"logConfiguration": {
|
||||
"logDriver": "awslogs",
|
||||
"options": {
|
||||
"awslogs-group": "/ecs/mcp-server",
|
||||
"awslogs-region": "us-east-1",
|
||||
"awslogs-stream-prefix": "ecs"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"requiresCompatibilities": [
|
||||
"FARGATE"
|
||||
],
|
||||
"cpu": "256",
|
||||
"memory": "512"
|
||||
}
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy to ECS">
|
||||
```bash
|
||||
# Create a service
|
||||
aws ecs create-service \
|
||||
--cluster your-cluster \
|
||||
--service-name mcp-server \
|
||||
--task-definition mcp-server:1 \
|
||||
--desired-count 1 \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345678],securityGroups=[sg-12345678],assignPublicIp=ENABLED}" \
|
||||
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/mcp-server-tg/1234567890abcdef,containerName=mcp-server,containerPort=8080"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Google Cloud Run
|
||||
|
||||
<Steps>
|
||||
<Step title="Push Docker Image to Google Container Registry">
|
||||
```bash
|
||||
# Configure Docker to use Google Cloud credentials
|
||||
gcloud auth configure-docker
|
||||
|
||||
# Build and tag the image
|
||||
docker build -t gcr.io/YOUR_PROJECT_ID/mcp-server .
|
||||
|
||||
# Push the image
|
||||
docker push gcr.io/YOUR_PROJECT_ID/mcp-server
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy to Cloud Run">
|
||||
```bash
|
||||
gcloud run deploy mcp-server \
|
||||
--image gcr.io/YOUR_PROJECT_ID/mcp-server \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--set-env-vars="OPENAI_API_KEY=your_api_key"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Production Configuration
|
||||
|
||||
### Security
|
||||
|
||||
For production deployments, implement these security measures:
|
||||
|
||||
1. **API Key Authentication**:
|
||||
```python
|
||||
agent.launch(port=8080, host="0.0.0.0", protocol="mcp", api_key="your-secret-key")
|
||||
```
|
||||
|
||||
2. **HTTPS with SSL/TLS**:
|
||||
Set up a reverse proxy like Nginx with SSL certificates:
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name your-mcp-server.com;
|
||||
|
||||
ssl_certificate /path/to/cert.pem;
|
||||
ssl_certificate_key /path/to/key.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Secret Management**:
|
||||
Use environment variables or a secrets manager for API keys:
|
||||
```bash
|
||||
# AWS Secrets Manager
|
||||
aws secretsmanager create-secret \
|
||||
--name OPENAI_API_KEY \
|
||||
--secret-string "your_api_key"
|
||||
|
||||
# Google Secret Manager
|
||||
echo -n "your_api_key" | gcloud secrets create openai-api-key --data-file=-
|
||||
```
|
||||
|
||||
### Scaling
|
||||
|
||||
For high-traffic MCP servers, consider these scaling strategies:
|
||||
|
||||
1. **Load Balancing**:
|
||||
Deploy multiple instances behind a load balancer.
|
||||
|
||||
2. **Auto Scaling**:
|
||||
Configure auto-scaling based on CPU/memory usage or request count.
|
||||
|
||||
3. **Resource Allocation**:
|
||||
Allocate sufficient CPU and memory for your MCP servers:
|
||||
```bash
|
||||
# AWS ECS
|
||||
aws ecs update-service \
|
||||
--cluster your-cluster \
|
||||
--service mcp-server \
|
||||
--desired-count 3
|
||||
|
||||
# Google Cloud Run
|
||||
gcloud run services update mcp-server \
|
||||
--min-instances=2 \
|
||||
--max-instances=10 \
|
||||
--memory=2Gi \
|
||||
--cpu=1
|
||||
```
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
Set up comprehensive monitoring for your MCP servers:
|
||||
|
||||
1. **Application Logging**:
|
||||
```python
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
handlers=[
|
||||
logging.FileHandler("mcp-server.log"),
|
||||
logging.StreamHandler()
|
||||
]
|
||||
)
|
||||
|
||||
logger = logging.getLogger("mcp-server")
|
||||
```
|
||||
|
||||
2. **Health Checks**:
|
||||
Create a health check endpoint:
|
||||
```python
|
||||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/health')
|
||||
def health_check():
|
||||
return {"status": "healthy"}, 200
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8081)
|
||||
```
|
||||
|
||||
3. **Metrics Collection**:
|
||||
Use Prometheus or similar tools to collect metrics.
|
||||
|
||||
## Testing MCP Servers
|
||||
|
||||
Before deploying to production, thoroughly test your MCP server:
|
||||
|
||||
```python
|
||||
import requests
|
||||
import json
|
||||
|
||||
def test_mcp_server():
|
||||
url = "http://localhost:8080/v1/chat/completions"
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
data = {
|
||||
"messages": [
|
||||
{"role": "user", "content": "Create a tweet about artificial intelligence"}
|
||||
]
|
||||
}
|
||||
|
||||
response = requests.post(url, headers=headers, data=json.dumps(data))
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
print(f"Response: {response.json()}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_mcp_server()
|
||||
```
|
||||
|
||||
## Deployment Checklist
|
||||
|
||||
Before going live with your MCP server, ensure you've addressed these items:
|
||||
|
||||
- [ ] Implemented proper authentication
|
||||
- [ ] Set up HTTPS with valid SSL certificates
|
||||
- [ ] Configured proper logging and monitoring
|
||||
- [ ] Tested the server under load
|
||||
- [ ] Implemented rate limiting
|
||||
- [ ] Secured all API keys and credentials
|
||||
- [ ] Set up automated backups
|
||||
- [ ] Created a disaster recovery plan
|
||||
- [ ] Documented the deployment process
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Containerized Deployment" icon="docker">
|
||||
Package your MCP servers in Docker containers for consistent deployment.
|
||||
</Card>
|
||||
<Card title="Cloud-Ready" icon="cloud">
|
||||
Deploy to AWS, Google Cloud, or other cloud providers with ease.
|
||||
</Card>
|
||||
<Card title="Scalable Architecture" icon="server">
|
||||
Scale your MCP servers to handle production workloads.
|
||||
</Card>
|
||||
<Card title="Security-Focused" icon="shield">
|
||||
Implement best practices for secure MCP server deployments.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: "Deploying Multi-Agent Systems as APIs"
|
||||
sidebarTitle: "Multi-Agent Deployment"
|
||||
description: "Learn how to deploy PraisonAI multi-agent systems as RESTful APIs for production environments"
|
||||
icon: "network-wired"
|
||||
---
|
||||
|
||||
# Deploying Multi-Agent Systems as APIs
|
||||
|
||||
PraisonAI allows you to deploy sophisticated multi-agent systems as RESTful APIs, enabling seamless integration with various applications and services. This guide covers different approaches to deploying multi-agent systems.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Dependencies">
|
||||
Make sure you have the required packages installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[api]>=0.0.81"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Set API Key">
|
||||
```bash
|
||||
export OPENAI_API_KEY="your_api_key"
|
||||
```
|
||||
</Step>
|
||||
<Step title="Deploy a Multi-Agent System">
|
||||
Create a file named `multi-agents-api.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents, Tools
|
||||
|
||||
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
|
||||
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
|
||||
agents = Agents(agents=[research_agent, summarise_agent])
|
||||
agents.launch(path="/agents", port=3030)
|
||||
```
|
||||
</Step>
|
||||
<Step title="Run the API Server">
|
||||
```bash
|
||||
python multi-agents-api.py
|
||||
```
|
||||
|
||||
Your multi-agent API will be available at `http://localhost:3030/agents`
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Making API Requests
|
||||
|
||||
Once your multi-agent system is deployed, you can make POST requests to interact with it:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3030/agents \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "What are the latest developments in AI in 2024?"}'
|
||||
```
|
||||
|
||||
The response will include the collaborative output from both the research and summarization agents:
|
||||
|
||||
```json
|
||||
{
|
||||
"response": "# Latest AI Developments in 2024\n\n- Multimodal AI models have become mainstream, combining text, image, audio, and video understanding\n- Significant advancements in AI reasoning capabilities with models like GPT-4o and Claude 3\n- Increased focus on AI alignment and safety research\n- Emergence of specialized AI agents for specific domains\n- Growth in open-source AI models and frameworks\n- Regulatory frameworks for AI being established globally"
|
||||
}
|
||||
```
|
||||
|
||||
## Multiple Agent Groups
|
||||
|
||||
You can deploy multiple agent groups on the same server, each with its own endpoint:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Agents, Tools
|
||||
|
||||
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
|
||||
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
|
||||
agents = Agents(agents=[research_agent, summarise_agent])
|
||||
agents2 = Agents(agents=[research_agent])
|
||||
agents.launch(path="/agents", port=3030)
|
||||
agents2.launch(path="/agents2", port=3030)
|
||||
```
|
||||
|
||||
With this setup, you can access:
|
||||
- The full agent group at `http://localhost:3030/agents`
|
||||
- Just the research agent at `http://localhost:3030/agents2`
|
||||
|
||||
## Independent Multi-Agent Deployment
|
||||
|
||||
You can also deploy multiple independent agents on the same server:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
weather_agent = Agent(
|
||||
instructions="""You are a weather agent that can provide weather information for a given city.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
stock_agent = Agent(
|
||||
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
travel_agent = Agent(
|
||||
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
weather_agent.launch(path="/weather", port=3030)
|
||||
stock_agent.launch(path="/stock", port=3030)
|
||||
travel_agent.launch(path="/travel", port=3030)
|
||||
```
|
||||
|
||||
## Production Deployment Options
|
||||
|
||||
For production environments, consider the following deployment options:
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
<Steps>
|
||||
<Step title="Create a Dockerfile">
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3030
|
||||
|
||||
CMD ["python", "multi-agents-api.py"]
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create requirements.txt">
|
||||
```
|
||||
praisonaiagents[api]>=0.0.81
|
||||
```
|
||||
</Step>
|
||||
<Step title="Build and Run Docker Container">
|
||||
```bash
|
||||
docker build -t praisonai-multi-agent .
|
||||
docker run -p 3030:3030 -e OPENAI_API_KEY=your_api_key praisonai-multi-agent
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Cloud Deployment
|
||||
|
||||
For detailed cloud deployment instructions, refer to:
|
||||
- [AWS Deployment Guide](/deploy/aws)
|
||||
- [Google Cloud Deployment Guide](/deploy/googlecloud)
|
||||
|
||||
## Scaling Multi-Agent Systems
|
||||
|
||||
When deploying multi-agent systems to production, consider these scaling strategies:
|
||||
|
||||
1. **Horizontal Scaling**: Deploy multiple instances behind a load balancer
|
||||
2. **Vertical Scaling**: Allocate more CPU and memory resources for complex agent interactions
|
||||
3. **Caching**: Implement response caching for frequently asked questions
|
||||
4. **Asynchronous Processing**: Use message queues for handling long-running agent tasks
|
||||
|
||||
## API Configuration Options
|
||||
|
||||
When launching your multi-agent system as an API, you can customize various parameters:
|
||||
|
||||
```python
|
||||
agents.launch(
|
||||
path="/custom-endpoint", # API endpoint path
|
||||
port=8080, # Port number
|
||||
host="0.0.0.0", # Host address (0.0.0.0 for external access)
|
||||
debug=True, # Enable debug mode
|
||||
cors_origins=["*"], # CORS configuration
|
||||
api_key="your-api-key" # Optional API key for authentication
|
||||
)
|
||||
```
|
||||
|
||||
## Securing Your Multi-Agent API
|
||||
|
||||
For production deployments, consider implementing:
|
||||
|
||||
1. **API Key Authentication**: Require API keys for all requests
|
||||
2. **Rate Limiting**: Limit the number of requests per client
|
||||
3. **HTTPS**: Use SSL/TLS certificates for encrypted communication
|
||||
4. **Input Validation**: Validate all input data before processing
|
||||
5. **Output Filtering**: Implement content filtering for agent responses
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
For production environments, consider:
|
||||
|
||||
1. **Centralized Logging**: Collect logs from all agents in a central location
|
||||
2. **Performance Metrics**: Track response times and resource usage
|
||||
3. **Error Tracking**: Monitor and alert on agent failures
|
||||
4. **Usage Analytics**: Track which agents are used most frequently
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Collaborative Agents" icon="users-gear">
|
||||
Deploy agent systems that collaborate to solve complex problems.
|
||||
</Card>
|
||||
<Card title="Specialized Endpoints" icon="sitemap">
|
||||
Create dedicated endpoints for different agent groups or individual agents.
|
||||
</Card>
|
||||
<Card title="Tool Integration" icon="screwdriver-wrench">
|
||||
Deploy agents with specialized tools like web search capabilities.
|
||||
</Card>
|
||||
<Card title="Scalable Architecture" icon="server">
|
||||
Scale your multi-agent systems to handle production workloads.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: 'Local Development'
|
||||
description: 'Set up local development environment with Docker and live reload'
|
||||
---
|
||||
|
||||
## Logging
|
||||
```bash
|
||||
export LOGLEVEL=info
|
||||
```
|
||||
|
||||
Advanced logging:
|
||||
```bash
|
||||
export LOGLEVEL=debug
|
||||
```
|
||||
|
||||
## Local Docker Development with Live Reload
|
||||
|
||||
To facilitate local development with live reload, you can use Docker. Follow the steps below:
|
||||
|
||||
### 1. Create Dockerfile.dev
|
||||
|
||||
<CodeGroup>
|
||||
```dockerfile Dockerfile.dev
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN pip install flask praisonai==2.2.22 watchdog
|
||||
|
||||
EXPOSE 5555
|
||||
|
||||
ENV FLASK_ENV=development
|
||||
|
||||
CMD ["flask", "run", "--host=0.0.0.0"]
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 2. Create docker-compose.yml
|
||||
|
||||
<CodeGroup>
|
||||
```yaml docker-compose.yml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.dev
|
||||
volumes:
|
||||
- .:/app
|
||||
ports:
|
||||
- "5555:5555"
|
||||
environment:
|
||||
FLASK_ENV: development
|
||||
command: flask run --host=0.0.0.0
|
||||
|
||||
watch:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- .:/app
|
||||
command: sh -c "apk add --no-cache inotify-tools && while inotifywait -r -e modify,create,delete /app; do kill -HUP 1; done"
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 3. Run Docker Compose
|
||||
|
||||
<CodeGroup>
|
||||
```bash Terminal
|
||||
docker-compose up
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
This setup will allow you to develop locally with live reload, making it easier to test and iterate on your code.
|
||||
@@ -65,14 +65,14 @@ def basic(): # Basic Mode
|
||||
def advanced(): # Advanced Mode with options
|
||||
praisonai = PraisonAI(
|
||||
agent_file="agents.yaml",
|
||||
framework="autogen",
|
||||
framework="autogen", # use AG2 framework (Formerly AutoGen)
|
||||
)
|
||||
praisonai.run()
|
||||
|
||||
def auto(): # Full Automatic Mode
|
||||
praisonai = PraisonAI(
|
||||
auto="Create a movie script about car in mars",
|
||||
framework="autogen"
|
||||
framework="autogen" # use AG2 framework
|
||||
)
|
||||
print(praisonai.framework)
|
||||
praisonai.run()
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
---
|
||||
title: "Adaptive Learning"
|
||||
description: "Learn how to create AI agents for personalized adaptive learning experiences."
|
||||
icon: "graduation-cap"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Assessor[Student Assessor]
|
||||
Assessor --> Generator[Content Generator]
|
||||
Generator --> Evaluator[Performance Evaluator]
|
||||
Evaluator --> Adapter[Difficulty Adapter]
|
||||
Adapter --> |decrease/increase| Generator
|
||||
Adapter --> |maintain| Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Assessor fill:#2E8B57,color:#fff
|
||||
style Generator fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style Adapter fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
Learn how to implement an adaptive learning system using AI agents for personalized education and dynamic content adjustment.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict
|
||||
|
||||
def assess_student_level():
|
||||
"""Simulates student assessment"""
|
||||
levels = ["beginner", "intermediate", "advanced"]
|
||||
current_time = int(time.time())
|
||||
return levels[current_time % 3]
|
||||
|
||||
def generate_content(level: str):
|
||||
"""Simulates content generation"""
|
||||
content_types = {
|
||||
"beginner": "basic concepts and examples",
|
||||
"intermediate": "practice problems and applications",
|
||||
"advanced": "complex scenarios and projects"
|
||||
}
|
||||
return content_types.get(level, "basic concepts")
|
||||
|
||||
def evaluate_performance():
|
||||
"""Simulates performance evaluation"""
|
||||
scores = ["low", "medium", "high"]
|
||||
current_time = int(time.time())
|
||||
return scores[current_time % 3]
|
||||
|
||||
def adapt_difficulty(performance: str):
|
||||
"""Simulates difficulty adaptation"""
|
||||
adaptations = {
|
||||
"low": "decrease",
|
||||
"medium": "maintain",
|
||||
"high": "increase"
|
||||
}
|
||||
return adaptations.get(performance, "maintain")
|
||||
|
||||
# Create specialized agents
|
||||
assessor = Agent(
|
||||
name="Student Assessor",
|
||||
role="Level Assessment",
|
||||
goal="Assess student's current level",
|
||||
instructions="Evaluate student's knowledge and skills",
|
||||
tools=[assess_student_level]
|
||||
)
|
||||
|
||||
generator = Agent(
|
||||
name="Content Generator",
|
||||
role="Content Creation",
|
||||
goal="Generate appropriate learning content",
|
||||
instructions="Create content based on student's level",
|
||||
tools=[generate_content]
|
||||
)
|
||||
|
||||
evaluator = Agent(
|
||||
name="Performance Evaluator",
|
||||
role="Performance Assessment",
|
||||
goal="Evaluate student's performance",
|
||||
instructions="Assess learning outcomes",
|
||||
tools=[evaluate_performance]
|
||||
)
|
||||
|
||||
adapter = Agent(
|
||||
name="Difficulty Adapter",
|
||||
role="Content Adaptation",
|
||||
goal="Adapt content difficulty",
|
||||
instructions="Adjust difficulty based on performance",
|
||||
tools=[adapt_difficulty]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
assessment_task = Task(
|
||||
name="assess_level",
|
||||
description="Assess student's current level",
|
||||
expected_output="Student's proficiency level",
|
||||
agent=assessor,
|
||||
is_start=True,
|
||||
next_tasks=["generate_content"]
|
||||
)
|
||||
|
||||
generation_task = Task(
|
||||
name="generate_content",
|
||||
description="Generate appropriate content",
|
||||
expected_output="Learning content",
|
||||
agent=generator,
|
||||
next_tasks=["evaluate_performance"]
|
||||
)
|
||||
|
||||
evaluation_task = Task(
|
||||
name="evaluate_performance",
|
||||
description="Evaluate student's performance",
|
||||
expected_output="Performance assessment",
|
||||
agent=evaluator,
|
||||
next_tasks=["adapt_difficulty"]
|
||||
)
|
||||
|
||||
adaptation_task = Task(
|
||||
name="adapt_difficulty",
|
||||
description="Adapt content difficulty",
|
||||
expected_output="Difficulty adjustment",
|
||||
agent=adapter,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"decrease": ["generate_content"],
|
||||
"maintain": "",
|
||||
"increase": ["generate_content"]
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[assessor, generator, evaluator, adapter],
|
||||
tasks=[assessment_task, generation_task, evaluation_task, adaptation_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Adaptive Learning Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nAdaptive Learning Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Run your adaptive learning system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
</Note>
|
||||
|
||||
## Understanding Adaptive Learning
|
||||
|
||||
<Card title="What is Adaptive Learning?" icon="question">
|
||||
Adaptive learning enables:
|
||||
- Personalized learning experiences
|
||||
- Dynamic content adjustment
|
||||
- Performance-based progression
|
||||
- Continuous skill assessment
|
||||
- Intelligent difficulty scaling
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Student Assessment" icon="user-graduate">
|
||||
Evaluate student proficiency:
|
||||
- Knowledge level assessment
|
||||
- Skill gap identification
|
||||
- Learning style analysis
|
||||
</Card>
|
||||
<Card title="Content Generation" icon="book">
|
||||
Create personalized content:
|
||||
- Level-appropriate materials
|
||||
- Custom learning paths
|
||||
- Interactive exercises
|
||||
</Card>
|
||||
<Card title="Performance Tracking" icon="chart-line">
|
||||
Monitor learning progress:
|
||||
- Real-time evaluation
|
||||
- Progress tracking
|
||||
- Achievement metrics
|
||||
</Card>
|
||||
<Card title="Dynamic Adaptation" icon="sliders">
|
||||
Adjust learning experience:
|
||||
- Difficulty scaling
|
||||
- Content optimization
|
||||
- Pace adjustment
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about chaining prompts for complex workflows
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
|
||||
Explore how to optimize and evaluate solutions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,297 @@
|
||||
---
|
||||
title: "Climate Impact"
|
||||
description: "Learn how to create AI agents for climate impact analysis and adaptation strategies."
|
||||
icon: "cloud-sun"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Monitor[Environmental Monitor]
|
||||
Monitor --> Urban[Urban Analyzer]
|
||||
Urban --> Climate[Climate Modeler]
|
||||
Climate --> Impact[Impact Predictor]
|
||||
Impact --> Strategy[Strategy Generator]
|
||||
Strategy --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Monitor fill:#2E8B57,color:#fff
|
||||
style Urban fill:#2E8B57,color:#fff
|
||||
style Climate fill:#2E8B57,color:#fff
|
||||
style Impact fill:#2E8B57,color:#fff
|
||||
style Strategy fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Climate Impact Analysis?
|
||||
|
||||
Climate Impact Analysis is a systematic process of collecting environmental data, analyzing urban factors, modeling microclimates, predicting impacts, and generating adaptation strategies. This helps cities and communities understand and prepare for climate change effects, ensuring sustainable urban development and public health.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Environmental Monitoring" icon="temperature-high">
|
||||
Collection of temperature, humidity, and air quality data with trend analysis.
|
||||
</Card>
|
||||
<Card title="Urban Analysis" icon="city">
|
||||
Assessment of building density, green spaces, traffic flow, and heat islands.
|
||||
</Card>
|
||||
<Card title="Climate Modeling" icon="chart-line">
|
||||
Microclimate modeling for different urban locations with temperature and air quality impacts.
|
||||
</Card>
|
||||
<Card title="Impact Prediction" icon="chart-mixed">
|
||||
Prediction of health impacts, energy consumption, and livability scores.
|
||||
</Card>
|
||||
<Card title="Adaptation Strategies" icon="leaf">
|
||||
Generation of location-specific strategies for climate adaptation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def collect_environmental_data():
|
||||
"""Simulates environmental data collection"""
|
||||
data = {
|
||||
"temperature": {
|
||||
"current": 25 + (time.time() % 10),
|
||||
"historical": [24, 25, 26, 24, 23],
|
||||
"trend": "increasing"
|
||||
},
|
||||
"humidity": {
|
||||
"current": 60 + (time.time() % 20),
|
||||
"historical": [65, 62, 58, 63, 61],
|
||||
"trend": "stable"
|
||||
},
|
||||
"air_quality": {
|
||||
"pm25": 35 + (time.time() % 15),
|
||||
"co2": 415 + (time.time() % 30),
|
||||
"trend": "deteriorating"
|
||||
}
|
||||
}
|
||||
return data
|
||||
|
||||
def analyze_urban_factors():
|
||||
"""Simulates urban environment analysis"""
|
||||
factors = {
|
||||
"building_density": 75 + (time.time() % 20),
|
||||
"green_spaces": 25 + (time.time() % 10),
|
||||
"traffic_flow": {
|
||||
"peak_hours": [8, 17],
|
||||
"congestion_level": "high"
|
||||
},
|
||||
"heat_islands": [
|
||||
{"location": "downtown", "intensity": "high"},
|
||||
{"location": "industrial", "intensity": "medium"}
|
||||
]
|
||||
}
|
||||
return factors
|
||||
|
||||
def model_microclimate(env_data: Dict, urban_factors: Dict):
|
||||
"""Models microclimate conditions"""
|
||||
models = []
|
||||
locations = ["downtown", "residential", "industrial", "parks"]
|
||||
|
||||
for location in locations:
|
||||
models.append({
|
||||
"location": location,
|
||||
"temperature_delta": 2 + (time.time() % 3),
|
||||
"air_quality_impact": "moderate" if "park" in location else "significant",
|
||||
"humidity_variation": 5 + (time.time() % 5)
|
||||
})
|
||||
return models
|
||||
|
||||
def predict_impacts(models: List[Dict]):
|
||||
"""Predicts climate impacts"""
|
||||
predictions = []
|
||||
for model in models:
|
||||
predictions.append({
|
||||
"location": model["location"],
|
||||
"health_impact": "high" if model["air_quality_impact"] == "significant" else "medium",
|
||||
"energy_consumption": {
|
||||
"cooling_need": model["temperature_delta"] * 10,
|
||||
"trend": "increasing" if model["temperature_delta"] > 2.5 else "stable"
|
||||
},
|
||||
"livability_score": 70 - (model["temperature_delta"] * 5)
|
||||
})
|
||||
return predictions
|
||||
|
||||
def generate_adaptation_strategies(predictions: List[Dict]):
|
||||
"""Generates adaptation strategies"""
|
||||
strategies = []
|
||||
for pred in predictions:
|
||||
if pred["health_impact"] == "high":
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"increase_green_spaces",
|
||||
"traffic_reduction",
|
||||
"building_retrofitting"
|
||||
],
|
||||
"priority": "immediate",
|
||||
"cost_estimate": "high"
|
||||
})
|
||||
else:
|
||||
strategies.append({
|
||||
"location": pred["location"],
|
||||
"actions": [
|
||||
"tree_planting",
|
||||
"cool_roofs"
|
||||
],
|
||||
"priority": "medium",
|
||||
"cost_estimate": "moderate"
|
||||
})
|
||||
return strategies
|
||||
|
||||
# Create specialized agents
|
||||
environmental_monitor = Agent(
|
||||
name="Environmental Monitor",
|
||||
role="Data Collection",
|
||||
goal="Collect environmental data",
|
||||
instructions="Monitor and collect climate data",
|
||||
tools=[collect_environmental_data]
|
||||
)
|
||||
|
||||
urban_analyzer = Agent(
|
||||
name="Urban Analyzer",
|
||||
role="Urban Analysis",
|
||||
goal="Analyze urban environment",
|
||||
instructions="Assess urban factors affecting climate",
|
||||
tools=[analyze_urban_factors]
|
||||
)
|
||||
|
||||
climate_modeler = Agent(
|
||||
name="Climate Modeler",
|
||||
role="Climate Modeling",
|
||||
goal="Model microclimate conditions",
|
||||
instructions="Create detailed climate models",
|
||||
tools=[model_microclimate]
|
||||
)
|
||||
|
||||
impact_predictor = Agent(
|
||||
name="Impact Predictor",
|
||||
role="Impact Analysis",
|
||||
goal="Predict climate impacts",
|
||||
instructions="Assess potential climate impacts",
|
||||
tools=[predict_impacts]
|
||||
)
|
||||
|
||||
strategy_generator = Agent(
|
||||
name="Strategy Generator",
|
||||
role="Strategy Development",
|
||||
goal="Generate adaptation strategies",
|
||||
instructions="Develop climate adaptation strategies",
|
||||
tools=[generate_adaptation_strategies]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
monitoring_task = Task(
|
||||
name="collect_data",
|
||||
description="Collect environmental data",
|
||||
expected_output="Environmental measurements",
|
||||
agent=environmental_monitor,
|
||||
is_start=True,
|
||||
next_tasks=["analyze_urban"]
|
||||
)
|
||||
|
||||
urban_task = Task(
|
||||
name="analyze_urban",
|
||||
description="Analyze urban factors",
|
||||
expected_output="Urban analysis",
|
||||
agent=urban_analyzer,
|
||||
next_tasks=["model_climate"]
|
||||
)
|
||||
|
||||
modeling_task = Task(
|
||||
name="model_climate",
|
||||
description="Model microclimate",
|
||||
expected_output="Climate models",
|
||||
agent=climate_modeler,
|
||||
context=[monitoring_task, urban_task],
|
||||
next_tasks=["predict_impacts"]
|
||||
)
|
||||
|
||||
prediction_task = Task(
|
||||
name="predict_impacts",
|
||||
description="Predict climate impacts",
|
||||
expected_output="Impact predictions",
|
||||
agent=impact_predictor,
|
||||
next_tasks=["generate_strategies"]
|
||||
)
|
||||
|
||||
strategy_task = Task(
|
||||
name="generate_strategies",
|
||||
description="Generate adaptation strategies",
|
||||
expected_output="Adaptation strategies",
|
||||
agent=strategy_generator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"immediate": ["collect_data"], # Continuous monitoring for high priority
|
||||
"medium": "", # End workflow for medium priority
|
||||
"low": "" # End workflow for low priority
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[environmental_monitor, urban_analyzer, climate_modeler,
|
||||
impact_predictor, strategy_generator],
|
||||
tasks=[monitoring_task, urban_task, modeling_task,
|
||||
prediction_task, strategy_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Climate Impact Prediction Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nClimate Impact Analysis Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
title: "Code Analysis Agent"
|
||||
description: "Learn how to create AI agents for comprehensive code analysis and quality assessment."
|
||||
icon: "code-merge"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Quality[Quality Assessment]
|
||||
Quality --> Metrics[Core Metrics]
|
||||
Metrics --> Technical[Technical Review]
|
||||
Technical --> Recommendations[Recommendations]
|
||||
Recommendations --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Quality fill:#2E8B57,color:#fff
|
||||
style Metrics fill:#2E8B57,color:#fff
|
||||
style Technical fill:#2E8B57,color:#fff
|
||||
style Recommendations fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Code Analysis?
|
||||
|
||||
Code Analysis is a systematic process of evaluating source code to assess its quality, maintainability, performance, and security. This helps developers and organizations maintain high code standards and identify areas for improvement.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quality Assessment" icon="chart-simple">
|
||||
Comprehensive evaluation of code quality with numerical scoring.
|
||||
</Card>
|
||||
<Card title="Core Metrics Analysis" icon="gauge">
|
||||
Analysis of architecture, maintainability, performance, and security.
|
||||
</Card>
|
||||
<Card title="Technical Assessment" icon="code">
|
||||
Review of tech stack, complexity, and best practices adherence.
|
||||
</Card>
|
||||
<Card title="Risk Assessment" icon="shield">
|
||||
Identification of potential risks and security vulnerabilities.
|
||||
</Card>
|
||||
<Card title="Recommendations" icon="lightbulb">
|
||||
Actionable suggestions for improvements and enhancements.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents gitingest
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `code_analysis.py` with the following code:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict
|
||||
from gitingest import ingest
|
||||
|
||||
class CodeMetrics(BaseModel):
|
||||
category: str
|
||||
score: int
|
||||
findings: List[str]
|
||||
|
||||
class CodeAnalysisReport(BaseModel):
|
||||
overall_quality: int
|
||||
code_metrics: List[CodeMetrics]
|
||||
architecture_score: int
|
||||
maintainability_score: int
|
||||
performance_score: int
|
||||
security_score: int
|
||||
test_coverage: int
|
||||
key_strengths: List[str]
|
||||
improvement_areas: List[str]
|
||||
tech_stack: List[str]
|
||||
recommendations: List[str]
|
||||
complexity_metrics: Dict[str, int]
|
||||
best_practices: List[Dict[str, str]]
|
||||
potential_risks: List[str]
|
||||
documentation_quality: int
|
||||
|
||||
code_analyzer = Agent(
|
||||
role="Code Analysis Expert",
|
||||
goal="Provide comprehensive code evaluation and recommendations",
|
||||
backstory="""Expert code analyst specializing in architecture review,
|
||||
best practices, and technical debt assessment.""",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
code_analysis_task = Task(
|
||||
description="""Analyze code repository and provide structured evaluation:
|
||||
|
||||
1. Overall Quality (0-100)
|
||||
2. Core Metrics Analysis:
|
||||
- Architecture and Design
|
||||
- Code Maintainability
|
||||
- Performance Optimization
|
||||
- Security Practices
|
||||
- Test Coverage
|
||||
3. Technical Assessment:
|
||||
- Technology Stack Review
|
||||
- Code Complexity Analysis
|
||||
- Best Practices Adherence
|
||||
- Risk Assessment
|
||||
4. Recommendations:
|
||||
- Key Improvements
|
||||
- Architecture Suggestions
|
||||
- Security Enhancements""",
|
||||
expected_output="Detailed code analysis report with metrics and recommendations",
|
||||
agent=code_analyzer,
|
||||
output_pydantic=CodeAnalysisReport
|
||||
)
|
||||
|
||||
def analyze_code(code_source: str) -> CodeAnalysisReport:
|
||||
"""
|
||||
Analyze code from directory path or GitHub URL
|
||||
"""
|
||||
# Ingest code content
|
||||
summary, tree, content = ingest(code_source)
|
||||
|
||||
# Concatenate context into structured format
|
||||
context_text = f"""
|
||||
CODE REPOSITORY ANALYSIS
|
||||
=======================
|
||||
|
||||
SUMMARY
|
||||
-------
|
||||
{summary}
|
||||
|
||||
REPOSITORY STRUCTURE
|
||||
-------------------
|
||||
{tree}
|
||||
|
||||
SOURCE CODE
|
||||
-----------
|
||||
{content}
|
||||
"""
|
||||
|
||||
# Initialize and run analysis
|
||||
agents = PraisonAIAgents(
|
||||
agents=[code_analyzer],
|
||||
tasks=[code_analysis_task]
|
||||
)
|
||||
|
||||
return agents.start(context_text)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory
|
||||
result = analyze_code(code_source)
|
||||
print(result)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Understanding the Output
|
||||
|
||||
The code analysis generates a comprehensive report with the following components:
|
||||
|
||||
- Overall Quality Score (0-100)
|
||||
- Core Metrics Analysis
|
||||
- Architecture and Design Score
|
||||
- Code Maintainability Score
|
||||
- Performance Score
|
||||
- Security Score
|
||||
- Test Coverage Percentage
|
||||
- Technical Assessment
|
||||
- Technology Stack
|
||||
- Complexity Metrics
|
||||
- Best Practices Review
|
||||
- Risk Assessment
|
||||
- Recommendations
|
||||
- Key Improvements
|
||||
- Architecture Suggestions
|
||||
- Security Enhancements
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
<Card title="API Reference" icon="code" href="/api-reference">
|
||||
Explore the complete API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,207 @@
|
||||
---
|
||||
title: "Code Review"
|
||||
sidebarTitle: "Code Review"
|
||||
description: "Learn how to create AI agents for automated code review and issue resolution."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Code Analyzer]
|
||||
Analyzer --> Suggester[Fix Suggester]
|
||||
Suggester --> Applier[Fix Applier]
|
||||
Applier -->|fixed| Out[Out]
|
||||
Applier -->|manual_review| Suggester
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Suggester fill:#2E8B57,color:#fff
|
||||
style Applier fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
A workflow demonstrating how AI agents can automate code review, from analysis through fix suggestion and application.
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import List, Dict
|
||||
|
||||
def analyze_code_changes():
|
||||
"""Simulates code analysis"""
|
||||
issues = [
|
||||
{"type": "style", "severity": "low", "file": "main.py"},
|
||||
{"type": "security", "severity": "high", "file": "auth.py"},
|
||||
{"type": "performance", "severity": "medium", "file": "data.py"}
|
||||
]
|
||||
return issues[int(time.time()) % 3]
|
||||
|
||||
def suggest_fixes(issue: Dict):
|
||||
"""Simulates fix suggestions"""
|
||||
fixes = {
|
||||
"style": "Apply PEP 8 formatting",
|
||||
"security": "Implement input validation",
|
||||
"performance": "Use list comprehension"
|
||||
}
|
||||
return fixes.get(issue["type"], "Review manually")
|
||||
|
||||
def apply_automated_fix(fix: str):
|
||||
"""Simulates applying automated fixes"""
|
||||
success = int(time.time()) % 2 == 0
|
||||
return "fixed" if success else "manual_review"
|
||||
|
||||
# Create specialized agents
|
||||
analyzer = Agent(
|
||||
name="Code Analyzer",
|
||||
role="Code analysis",
|
||||
goal="Analyze code changes and identify issues",
|
||||
instructions="Review code changes and report issues",
|
||||
tools=[analyze_code_changes]
|
||||
)
|
||||
|
||||
fix_suggester = Agent(
|
||||
name="Fix Suggester",
|
||||
role="Solution provider",
|
||||
goal="Suggest fixes for identified issues",
|
||||
instructions="Provide appropriate fix suggestions",
|
||||
tools=[suggest_fixes]
|
||||
)
|
||||
|
||||
fix_applier = Agent(
|
||||
name="Fix Applier",
|
||||
role="Fix implementation",
|
||||
goal="Apply suggested fixes automatically when possible",
|
||||
instructions="Implement suggested fixes and report results",
|
||||
tools=[apply_automated_fix]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_code",
|
||||
description="Analyze code changes for issues",
|
||||
expected_output="Identified code issues",
|
||||
agent=analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["suggest_fixes"]
|
||||
)
|
||||
|
||||
suggestion_task = Task(
|
||||
name="suggest_fixes",
|
||||
description="Suggest fixes for identified issues",
|
||||
expected_output="Fix suggestions",
|
||||
agent=fix_suggester,
|
||||
next_tasks=["apply_fixes"]
|
||||
)
|
||||
|
||||
fix_task = Task(
|
||||
name="apply_fixes",
|
||||
description="Apply suggested fixes",
|
||||
expected_output="Fix application status",
|
||||
agent=fix_applier,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"fixed": "",
|
||||
"manual_review": ["suggest_fixes"] # Loop back for manual review
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[analyzer, fix_suggester, fix_applier],
|
||||
tasks=[analysis_task, suggestion_task, fix_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Code Review Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nCode Review Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
|
||||
- Basic understanding of Python
|
||||
</Note>
|
||||
|
||||
## Understanding Code Review
|
||||
|
||||
<Card title="What is Code Review?" icon="question">
|
||||
Automated code review workflow enables:
|
||||
- Automated issue detection
|
||||
- Intelligent fix suggestions
|
||||
- Automated fix application
|
||||
- Manual review routing when needed
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Issue Detection" icon="magnifying-glass">
|
||||
Automatically identify code issues and their severity.
|
||||
</Card>
|
||||
<Card title="Fix Suggestions" icon="lightbulb">
|
||||
Generate appropriate fix suggestions based on issue type.
|
||||
</Card>
|
||||
<Card title="Automated Fixes" icon="wand-magic-sparkles">
|
||||
Apply fixes automatically when possible.
|
||||
</Card>
|
||||
<Card title="Manual Review" icon="user-check">
|
||||
Route complex issues for manual review.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
|
||||
Learn about sequential prompt execution
|
||||
</Card>
|
||||
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
|
||||
Explore optimization techniques
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,316 @@
|
||||
---
|
||||
title: "Crypto Validator"
|
||||
description: "Learn how to create AI agents for post-quantum cryptographic scheme validation and security analysis."
|
||||
icon: "key"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Analyzer[Crypto Analyzer]
|
||||
Analyzer --> Quantum[Attack Simulator]
|
||||
Analyzer --> Perf[Performance Benchmarker]
|
||||
Quantum --> Security[Implementation Assessor]
|
||||
Perf --> Security
|
||||
Security --> Compliance[Compliance Validator]
|
||||
Compliance --> Out[Out]
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Analyzer fill:#2E8B57,color:#fff
|
||||
style Quantum fill:#2E8B57,color:#fff
|
||||
style Perf fill:#2E8B57,color:#fff
|
||||
style Security fill:#2E8B57,color:#fff
|
||||
style Compliance fill:#2E8B57,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
```
|
||||
|
||||
## What is Post-Quantum Cryptography?
|
||||
|
||||
Post-quantum cryptography focuses on developing cryptographic systems that are secure against both quantum and classical computers. This involves analyzing cryptographic schemes, simulating quantum attacks, and ensuring compliance with security standards.
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Cryptographic Analysis" icon="shield-check">
|
||||
Analyze quantum-resistant cryptographic schemes including lattice-based encryption and multivariate signatures.
|
||||
</Card>
|
||||
<Card title="Attack Simulation" icon="bug">
|
||||
Test resistance against quantum attacks including Grover's algorithm and Shor's algorithm.
|
||||
</Card>
|
||||
<Card title="Performance Testing" icon="gauge-high">
|
||||
Benchmark key generation, encryption/decryption speeds, and throughput metrics.
|
||||
</Card>
|
||||
<Card title="Security Assessment" icon="lock">
|
||||
Evaluate implementation security including side-channel resistance and hardening measures.
|
||||
</Card>
|
||||
<Card title="Compliance Validation" icon="certificate">
|
||||
Verify compliance with NIST PQC, Common Criteria, and FIPS standards.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
import asyncio
|
||||
|
||||
def analyze_cryptographic_scheme():
|
||||
"""Simulates cryptographic scheme analysis"""
|
||||
schemes = [
|
||||
{
|
||||
"name": "lattice_based",
|
||||
"type": "encryption",
|
||||
"key_size": 2048,
|
||||
"security_level": "AES-256 equivalent",
|
||||
"parameters": {
|
||||
"lattice_dimension": 1024,
|
||||
"modulus": "q = 2^32 - 1",
|
||||
"error_distribution": "discrete_gaussian"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "multivariate",
|
||||
"type": "signature",
|
||||
"key_size": 4096,
|
||||
"security_level": "SHA-384 equivalent",
|
||||
"parameters": {
|
||||
"variables": 128,
|
||||
"equations": 128,
|
||||
"field_size": "2^8"
|
||||
}
|
||||
}
|
||||
]
|
||||
return schemes[int(time.time()) % 2]
|
||||
|
||||
def simulate_quantum_attacks(scheme: Dict):
|
||||
"""Simulates quantum attack scenarios"""
|
||||
attacks = {
|
||||
"grover_search": {
|
||||
"effectiveness": "reduced",
|
||||
"quantum_speedup": "quadratic",
|
||||
"estimated_qubits": 2048,
|
||||
"time_complexity": "O(2^n/2)"
|
||||
},
|
||||
"shor_algorithm": {
|
||||
"effectiveness": "ineffective",
|
||||
"quantum_speedup": "none",
|
||||
"vulnerability": "resistant",
|
||||
"classical_hardness": "maintained"
|
||||
},
|
||||
"quantum_hidden_subgroup": {
|
||||
"effectiveness": "partial",
|
||||
"applicability": "limited",
|
||||
"mitigation": "parameter_adjustment"
|
||||
}
|
||||
}
|
||||
return attacks
|
||||
|
||||
def benchmark_performance(scheme: Dict):
|
||||
"""Benchmarks cryptographic performance"""
|
||||
benchmarks = {
|
||||
"key_generation": {
|
||||
"time": 0.5 + (time.time() % 1) / 10, # seconds
|
||||
"memory": 128 + (int(time.time()) % 64) # MB
|
||||
},
|
||||
"encryption_speed": {
|
||||
"small_message": 0.001 + (time.time() % 1) / 1000, # seconds
|
||||
"large_message": 0.1 + (time.time() % 1) / 10 # seconds
|
||||
},
|
||||
"decryption_speed": {
|
||||
"small_message": 0.002 + (time.time() % 1) / 1000,
|
||||
"large_message": 0.15 + (time.time() % 1) / 10
|
||||
},
|
||||
"throughput": {
|
||||
"encryption": 100 + (int(time.time()) % 50), # MB/s
|
||||
"decryption": 80 + (int(time.time()) % 40) # MB/s
|
||||
}
|
||||
}
|
||||
return benchmarks
|
||||
|
||||
def assess_implementation(scheme: Dict, benchmarks: Dict):
|
||||
"""Assesses implementation security"""
|
||||
assessment = {
|
||||
"side_channel_resistance": {
|
||||
"timing_attacks": "protected",
|
||||
"power_analysis": "partial_vulnerability",
|
||||
"cache_attacks": "mitigated"
|
||||
},
|
||||
"implementation_hardening": {
|
||||
"constant_time": True,
|
||||
"memory_protection": True,
|
||||
"error_handling": "secure"
|
||||
},
|
||||
"compiler_optimizations": {
|
||||
"safety": "verified",
|
||||
"performance_impact": -0.05 + (time.time() % 1) / 10
|
||||
}
|
||||
}
|
||||
return assessment
|
||||
|
||||
def validate_compliance(scheme: Dict, assessment: Dict):
|
||||
"""Validates compliance and standards"""
|
||||
compliance = {
|
||||
"nist_pqc": {
|
||||
"status": "submitted",
|
||||
"round": 3,
|
||||
"requirements_met": True
|
||||
},
|
||||
"common_criteria": {
|
||||
"evaluation_level": "EAL4+",
|
||||
"protection_profile": "compliant"
|
||||
},
|
||||
"fips_140_3": {
|
||||
"security_level": 3,
|
||||
"validation_status": "in_process"
|
||||
}
|
||||
}
|
||||
return compliance
|
||||
|
||||
# Create specialized agents
|
||||
crypto_analyzer = Agent(
|
||||
name="Crypto Analyzer",
|
||||
role="Cryptographic Analysis",
|
||||
goal="Analyze cryptographic schemes",
|
||||
instructions="Evaluate quantum-resistant cryptographic schemes",
|
||||
tools=[analyze_cryptographic_scheme]
|
||||
)
|
||||
|
||||
attack_simulator = Agent(
|
||||
name="Attack Simulator",
|
||||
role="Attack Simulation",
|
||||
goal="Simulate quantum attacks",
|
||||
instructions="Test resistance against quantum attacks",
|
||||
tools=[simulate_quantum_attacks]
|
||||
)
|
||||
|
||||
performance_benchmarker = Agent(
|
||||
name="Performance Benchmarker",
|
||||
role="Performance Testing",
|
||||
goal="Benchmark cryptographic performance",
|
||||
instructions="Measure performance metrics",
|
||||
tools=[benchmark_performance]
|
||||
)
|
||||
|
||||
implementation_assessor = Agent(
|
||||
name="Implementation Assessor",
|
||||
role="Implementation Assessment",
|
||||
goal="Assess implementation security",
|
||||
instructions="Evaluate implementation security",
|
||||
tools=[assess_implementation]
|
||||
)
|
||||
|
||||
compliance_validator = Agent(
|
||||
name="Compliance Validator",
|
||||
role="Compliance Validation",
|
||||
goal="Validate standards compliance",
|
||||
instructions="Verify compliance with standards",
|
||||
tools=[validate_compliance]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_crypto",
|
||||
description="Analyze cryptographic scheme",
|
||||
expected_output="Cryptographic analysis",
|
||||
agent=crypto_analyzer,
|
||||
is_start=True,
|
||||
next_tasks=["simulate_attacks", "benchmark_performance"]
|
||||
)
|
||||
|
||||
attack_task = Task(
|
||||
name="simulate_attacks",
|
||||
description="Simulate quantum attacks",
|
||||
expected_output="Attack simulation results",
|
||||
agent=attack_simulator,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
benchmark_task = Task(
|
||||
name="benchmark_performance",
|
||||
description="Benchmark performance",
|
||||
expected_output="Performance benchmarks",
|
||||
agent=performance_benchmarker,
|
||||
next_tasks=["assess_implementation"]
|
||||
)
|
||||
|
||||
assessment_task = Task(
|
||||
name="assess_implementation",
|
||||
description="Assess implementation",
|
||||
expected_output="Implementation assessment",
|
||||
agent=implementation_assessor,
|
||||
context=[attack_task, benchmark_task],
|
||||
next_tasks=["validate_compliance"]
|
||||
)
|
||||
|
||||
compliance_task = Task(
|
||||
name="validate_compliance",
|
||||
description="Validate compliance",
|
||||
expected_output="Compliance validation",
|
||||
agent=compliance_validator,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"compliant": "", # End workflow if compliant
|
||||
"non_compliant": ["assess_implementation"] # Reassess if non-compliant
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[crypto_analyzer, attack_simulator, performance_benchmarker,
|
||||
implementation_assessor, compliance_validator],
|
||||
tasks=[analysis_task, attack_task, benchmark_task,
|
||||
assessment_task, compliance_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
async def main():
|
||||
print("\nStarting Quantum-Resistant Cryptography Validation Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = await workflow.astart()
|
||||
|
||||
# Print results
|
||||
print("\nCryptography Validation Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Introduction" icon="book" href="/introduction">
|
||||
Learn more about PraisonAI and its core concepts
|
||||
</Card>
|
||||
<Card title="Quick Start" icon="bolt" href="/quickstart">
|
||||
Get started with the basics of PraisonAI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -0,0 +1,206 @@
|
||||
---
|
||||
title: Customer Service
|
||||
sidebar_title: Customer Service
|
||||
icon: "user-group"
|
||||
---
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
In[In] --> Classifier[Query Classifier]
|
||||
Classifier --> Handler[Query Handler]
|
||||
Handler --> Evaluator[Satisfaction Evaluator]
|
||||
Evaluator --> Optimizer[Response Optimizer]
|
||||
Optimizer --> Out[Out]
|
||||
Optimizer --> Classifier
|
||||
|
||||
style In fill:#8B0000,color:#fff
|
||||
style Out fill:#8B0000,color:#fff
|
||||
style Classifier fill:#2E8B57,color:#fff
|
||||
style Handler fill:#2E8B57,color:#fff
|
||||
style Evaluator fill:#2E8B57,color:#fff
|
||||
style Optimizer fill:#2E8B57,color:#fff
|
||||
```
|
||||
|
||||
Learn how to create AI agents for automated customer service and response optimization.
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
|
||||
2. Set your OpenAI API key:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
3. Create a file named `app.py`:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
import time
|
||||
from typing import Dict, List
|
||||
|
||||
def classify_query():
|
||||
"""Simulates query classification"""
|
||||
query_types = [
|
||||
{"type": "technical", "priority": "high", "complexity": "complex"},
|
||||
{"type": "billing", "priority": "medium", "complexity": "simple"},
|
||||
{"type": "general", "priority": "low", "complexity": "simple"}
|
||||
]
|
||||
return query_types[int(time.time()) % 3]
|
||||
|
||||
def handle_query(query: Dict):
|
||||
"""Simulates query handling"""
|
||||
responses = {
|
||||
"technical": "Technical support solution provided",
|
||||
"billing": "Billing inquiry resolved",
|
||||
"general": "General information provided"
|
||||
}
|
||||
return responses.get(query["type"], "Query forwarded to specialist")
|
||||
|
||||
def evaluate_satisfaction():
|
||||
"""Simulates satisfaction evaluation"""
|
||||
scores = ["satisfied", "neutral", "unsatisfied"]
|
||||
return scores[int(time.time()) % 3]
|
||||
|
||||
def optimize_response(satisfaction: str):
|
||||
"""Simulates response optimization"""
|
||||
optimizations = {
|
||||
"satisfied": "maintain_approach",
|
||||
"neutral": "minor_adjustments",
|
||||
"unsatisfied": "major_revision"
|
||||
}
|
||||
return optimizations.get(satisfaction, "review_process")
|
||||
|
||||
# Create specialized agents
|
||||
classifier = Agent(
|
||||
name="Query Classifier",
|
||||
role="Query Classification",
|
||||
goal="Classify incoming customer queries",
|
||||
instructions="Analyze and categorize customer queries",
|
||||
tools=[classify_query]
|
||||
)
|
||||
|
||||
handler = Agent(
|
||||
name="Query Handler",
|
||||
role="Query Resolution",
|
||||
goal="Handle customer queries appropriately",
|
||||
instructions="Provide appropriate responses to queries",
|
||||
tools=[handle_query]
|
||||
)
|
||||
|
||||
evaluator = Agent(
|
||||
name="Satisfaction Evaluator",
|
||||
role="Satisfaction Assessment",
|
||||
goal="Evaluate customer satisfaction",
|
||||
instructions="Assess response effectiveness",
|
||||
tools=[evaluate_satisfaction]
|
||||
)
|
||||
|
||||
optimizer = Agent(
|
||||
name="Response Optimizer",
|
||||
role="Service Optimization",
|
||||
goal="Optimize service based on feedback",
|
||||
instructions="Improve response strategies",
|
||||
tools=[optimize_response]
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
classification_task = Task(
|
||||
name="classify_query",
|
||||
description="Classify customer query",
|
||||
expected_output="Query classification",
|
||||
agent=classifier,
|
||||
is_start=True,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"high": ["handle_query", "evaluate_satisfaction"],
|
||||
"medium": ["handle_query", "evaluate_satisfaction"],
|
||||
"low": ["handle_query"]
|
||||
}
|
||||
)
|
||||
|
||||
handling_task = Task(
|
||||
name="handle_query",
|
||||
description="Handle customer query",
|
||||
expected_output="Query response",
|
||||
agent=handler,
|
||||
next_tasks=["evaluate_satisfaction"]
|
||||
)
|
||||
|
||||
evaluation_task = Task(
|
||||
name="evaluate_satisfaction",
|
||||
description="Evaluate customer satisfaction",
|
||||
expected_output="Satisfaction level",
|
||||
agent=evaluator,
|
||||
next_tasks=["optimize_response"]
|
||||
)
|
||||
|
||||
optimization_task = Task(
|
||||
name="optimize_response",
|
||||
description="Optimize response strategy",
|
||||
expected_output="Optimization recommendations",
|
||||
agent=optimizer,
|
||||
task_type="decision",
|
||||
condition={
|
||||
"major_revision": ["classify_query"],
|
||||
"minor_adjustments": "",
|
||||
"maintain_approach": ""
|
||||
}
|
||||
)
|
||||
|
||||
# Create workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[classifier, handler, evaluator, optimizer],
|
||||
tasks=[classification_task, handling_task, evaluation_task, optimization_task],
|
||||
process="workflow",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def main():
|
||||
print("\nStarting Customer Service Optimization Workflow...")
|
||||
print("=" * 50)
|
||||
|
||||
# Run workflow
|
||||
results = workflow.start()
|
||||
|
||||
# Print results
|
||||
print("\nCustomer Service Results:")
|
||||
print("=" * 50)
|
||||
for task_id, result in results["task_results"].items():
|
||||
if result:
|
||||
print(f"\nTask: {task_id}")
|
||||
print(f"Result: {result.raw}")
|
||||
print("-" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
4. Run the system:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
<Note>
|
||||
**Requirements**
|
||||
- Python 3.10 or higher
|
||||
- OpenAI API key
|
||||
</Note>
|
||||
|
||||
## Understanding Customer Service
|
||||
|
||||
The customer service workflow demonstrates how AI agents can automate and optimize customer support operations. The system uses specialized agents to classify queries, handle responses, evaluate satisfaction, and continuously improve service quality through feedback-driven optimization.
|
||||
|
||||
## Features
|
||||
|
||||
- **Query Classification**: Automatically categorizes customer inquiries based on type, priority, and complexity
|
||||
- **Intelligent Response Handling**: Provides appropriate responses based on query classification
|
||||
- **Satisfaction Evaluation**: Assesses customer satisfaction with provided solutions
|
||||
- **Response Optimization**: Continuously improves service quality through feedback analysis
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Prompt Chaining](/features/promptchaining)
|
||||
- Explore [Evaluator Optimizer](/features/evaluator-optimiser)
|
||||
Loaded 100 of 941 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user