mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-07 17:33:33 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79883f1af2 | ||
|
|
a098eb0150 | ||
|
|
b9ce3b4ccb | ||
|
|
58b44280df | ||
|
|
4dba09d6b1 | ||
|
|
a538513bec | ||
|
|
4fb79207cf | ||
|
|
0b444fae34 | ||
|
|
bd34e45bbc | ||
|
|
f4f051e57e | ||
|
|
3c2610cc3c | ||
|
|
9788454134 | ||
|
|
e618004e60 | ||
|
|
384803ba8e | ||
|
|
d3bb366a51 | ||
|
|
e579e84b52 | ||
|
|
61440403f5 | ||
|
|
b615782175 | ||
|
|
eeb77cfd20 | ||
|
|
00d7994601 | ||
|
|
10aa49addc | ||
|
|
79c9cf8bf9 | ||
|
|
a9416fb7fc | ||
|
|
547b40ee72 | ||
|
|
4fc35d1b10 | ||
|
|
c72d74987b | ||
|
|
430ec6571a | ||
|
|
e88288773a | ||
|
|
9af03e3fef | ||
|
|
7a7560621b | ||
|
|
531c58ac70 | ||
|
|
274ade8154 | ||
|
|
83f4f874e9 | ||
|
|
99cd88dd30 | ||
|
|
1d22818662 | ||
|
|
4f38e7250a | ||
|
|
b736567375 | ||
|
|
d014ea8d18 | ||
|
|
fd6db3ccfa | ||
|
|
1f2f26c5cf | ||
|
|
1965f296b0 | ||
|
|
cc7036784b | ||
|
|
826a68c33e | ||
|
|
88ceba804b | ||
|
|
dc5b10fba8 | ||
|
|
f0172e8339 | ||
|
|
5c498a12de | ||
|
|
88410881e1 | ||
|
|
791d59f96e | ||
|
|
cdbe1303ad | ||
|
|
b63f931bea | ||
|
|
ff25b96f91 | ||
|
|
603f0ea008 | ||
|
|
db38b55174 | ||
|
|
cebd175d61 | ||
|
|
01ff75e573 | ||
|
|
28629f2203 | ||
|
|
ac5c463362 | ||
|
|
84dc57583e | ||
|
|
460e8b45a7 | ||
|
|
f6bbbd7cd6 | ||
|
|
8a435571f4 | ||
|
|
204106daa8 | ||
|
|
6a1e14f97a | ||
|
|
333777b991 | ||
|
|
b02cd85290 | ||
|
|
3bc0c2b533 | ||
|
|
68d4f34bb7 | ||
|
|
a24d900a8c | ||
|
|
552a10df9e | ||
|
|
9c57aa3165 | ||
|
|
40fe92f1d0 | ||
|
|
179cc9566d | ||
|
|
d9cf9ba534 | ||
|
|
4ec0366e79 | ||
|
|
d6a3bd1240 | ||
|
|
0a18e27f54 | ||
|
|
b824d950b5 | ||
|
|
a5b768c213 | ||
|
|
068bdbebc5 | ||
|
|
4d80d795f8 | ||
|
|
2e3b5cd29b | ||
|
|
d948b6de2c | ||
|
|
3adb06950c | ||
|
|
e45e85975c | ||
|
|
8a7935dc2c | ||
|
|
b31edc90d5 | ||
|
|
d2841ccb3a | ||
|
|
e22fda805f | ||
|
|
2cde2fd731 | ||
|
|
f7534681e5 | ||
|
|
8c9e3e34cb | ||
|
|
c470494d76 | ||
|
|
fdf3cac3e7 | ||
|
|
ec98cd12c8 | ||
|
|
f318ef02a9 | ||
|
|
f086566a2d | ||
|
|
6de011b69e | ||
|
|
89d7821bc9 | ||
|
|
9bff7eddbd | ||
|
|
82e5f11acf | ||
|
|
0a4aaeb80d | ||
|
|
70915e2535 | ||
|
|
f35dd76623 | ||
|
|
fccd1197a8 | ||
|
|
9390da7099 | ||
|
|
8044fd7927 | ||
|
|
cd5ba2017e | ||
|
|
8c6773b86e | ||
|
|
01539581c9 | ||
|
|
bef8713769 | ||
|
|
f84445949e | ||
|
|
7c74df7cf9 | ||
|
|
f576afa22c | ||
|
|
79c4ef1de3 | ||
|
|
47e7c5b272 | ||
|
|
ec9310b1d1 | ||
|
|
359bfd3759 | ||
|
|
c57e4724c1 | ||
|
|
0b4739a6f9 | ||
|
|
e90c78219d | ||
|
|
a640f0710d | ||
|
|
7216afbf13 | ||
|
|
3f7ea07fa2 | ||
|
|
5d6792762c | ||
|
|
092113cedd | ||
|
|
314eed51d5 | ||
|
|
df26978b3c | ||
|
|
0ba0a6415c | ||
|
|
0bd8e9f535 | ||
|
|
2dc02ed5a6 | ||
|
|
ea4a2f3b69 | ||
|
|
4df08daf36 | ||
|
|
a156c2e4a2 | ||
|
|
d039c2395b | ||
|
|
e6bd8d73e4 | ||
|
|
e3e4de9f13 | ||
|
|
25b06caa75 | ||
|
|
0a4470dd17 | ||
|
|
b65fae4b38 | ||
|
|
aa6ef5a94d | ||
|
|
cb551debfe | ||
|
|
fabd852002 | ||
|
|
99de9f4d4f | ||
|
|
daaf92cbeb | ||
|
|
d8375cb50b | ||
|
|
36ea8d381e | ||
|
|
8a8f96e5e5 | ||
|
|
7234587829 | ||
|
|
d916d0926a | ||
|
|
cd09b2de96 | ||
|
|
58b8ad1969 | ||
|
|
5e5b6672eb | ||
|
|
f7ce10b92e | ||
|
|
eead19802d | ||
|
|
208c8aad3b | ||
|
|
fb2b086dd5 | ||
|
|
75972372a6 | ||
|
|
108053bb32 | ||
|
|
fbddda54ba | ||
|
|
83427ca929 | ||
|
|
36e5047e53 | ||
|
|
05d8136433 | ||
|
|
af9b251b59 | ||
|
|
c8a6744469 | ||
|
|
678fd462c3 | ||
|
|
ba03a0d893 | ||
|
|
3be4c4c70e | ||
|
|
709640240f | ||
|
|
93d526eb7b | ||
|
|
624a2cfa17 | ||
|
|
4d2a6a2e2e | ||
|
|
a1bdb056a0 | ||
|
|
b4a6401bae | ||
|
|
772ce7d2e2 | ||
|
|
20c2d28f35 | ||
|
|
f8589e4363 | ||
|
|
97d368d2e2 | ||
|
|
49d9d40199 | ||
|
|
445cc037ce | ||
|
|
c4e7b7dc7f | ||
|
|
9e7c172f55 | ||
|
|
d89570b085 | ||
|
|
ee5dfddccd | ||
|
|
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 |
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 }}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Run tests and upload coverage
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
pull_request:
|
||||
branches: [ main, develop ]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run tests and collect coverage
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- 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
|
||||
uv pip install --system pytest pytest-cov pytest-asyncio
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd src/praisonai
|
||||
pytest --cov=praisonai --cov-branch --cov-report=xml tests/unit/
|
||||
|
||||
- name: Upload results to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
file: src/praisonai/coverage.xml
|
||||
flags: unit-tests
|
||||
name: unit-tests-coverage
|
||||
fail_ci_if_error: false
|
||||
verbose: true
|
||||
@@ -19,22 +19,50 @@ 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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
python -m pip install "praisonaiagents[knowledge]"
|
||||
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 tests/test_runner.py --pattern fast
|
||||
@@ -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,190 @@
|
||||
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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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 -m pytest tests/unit/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=xml --cov-branch
|
||||
;;
|
||||
"integration")
|
||||
cd src/praisonai && python -m pytest tests/integration/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=xml --cov-branch
|
||||
;;
|
||||
"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 coverage reports to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
file: src/praisonai/coverage.xml
|
||||
flags: comprehensive-tests
|
||||
name: comprehensive-tests-coverage
|
||||
fail_ci_if_error: false
|
||||
verbose: true
|
||||
|
||||
- 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
|
||||
src/praisonai/htmlcov/
|
||||
src/praisonai/coverage.xml
|
||||
src/praisonai/.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,286 @@
|
||||
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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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 --cov-report=xml --cov-branch
|
||||
|
||||
- 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 to Codecov
|
||||
if: matrix.python-version == '3.11'
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
file: src/praisonai/coverage.xml
|
||||
flags: core-tests
|
||||
name: core-tests-coverage
|
||||
fail_ci_if_error: false
|
||||
verbose: true
|
||||
|
||||
- name: Upload Coverage Reports (Artifacts)
|
||||
if: matrix.python-version == '3.11'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage-reports
|
||||
path: |
|
||||
src/praisonai/.coverage
|
||||
src/praisonai/htmlcov/
|
||||
src/praisonai/coverage.xml
|
||||
retention-days: 7
|
||||
@@ -0,0 +1,164 @@
|
||||
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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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,167 @@
|
||||
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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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
|
||||
+493
-14
@@ -1,36 +1,515 @@
|
||||
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
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- 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 with coverage
|
||||
cd src/praisonai && python -m pytest tests/unit/test_core_agents.py -v --tb=short --disable-warnings --cov=praisonai --cov-report=xml --cov-branch
|
||||
|
||||
- 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: Upload coverage reports to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
file: src/praisonai/coverage.xml
|
||||
flags: quick-validation
|
||||
name: quick-validation-coverage
|
||||
fail_ci_if_error: false
|
||||
verbose: 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
|
||||
+11
-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,9 @@ outputs
|
||||
agents/praisonaiagents/build
|
||||
agents/praisonaiagents/dist
|
||||
agents/praisonaiagents/praisonaiagents.egg-info
|
||||
.codegpt
|
||||
.codegpt
|
||||
.praison
|
||||
# Local Netlify folder
|
||||
.netlify
|
||||
.qodo
|
||||
CopilotKit*
|
||||
@@ -1,23 +0,0 @@
|
||||
# .readthedocs.yaml
|
||||
# Read the Docs configuration file
|
||||
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
|
||||
|
||||
# Required
|
||||
version: 2
|
||||
|
||||
# Set the OS, Python version and other tools you might need
|
||||
build:
|
||||
os: ubuntu-22.04
|
||||
tools:
|
||||
python: "3.12"
|
||||
jobs:
|
||||
post_install:
|
||||
- bash docs/generate_docs.sh
|
||||
|
||||
mkdocs:
|
||||
configuration: mkdocs.yml
|
||||
fail_on_warning: true
|
||||
|
||||
python:
|
||||
install:
|
||||
- requirements: docs/requirements.txt
|
||||
@@ -1,6 +0,0 @@
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN pip install flask praisonai==2.0.38 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,35 +0,0 @@
|
||||
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
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]
|
||||
)
|
||||
|
||||
blog_agent = Agent(
|
||||
role="Blog Writer",
|
||||
goal="Write a blog post about the research",
|
||||
backstory="Expert at writing blog posts",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
research_task = Task(
|
||||
description="Research and document key information about topics",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
blog_task = Task(
|
||||
description="Write a blog post about the research",
|
||||
agent=blog_agent
|
||||
)
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent, blog_agent],
|
||||
tasks=[research_task, blog_task],
|
||||
memory=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
@@ -1,51 +0,0 @@
|
||||
"""
|
||||
Praison AI Agents - A package for hierarchical AI agent task execution
|
||||
"""
|
||||
|
||||
from .agent.agent import Agent
|
||||
from .agents.agents import PraisonAIAgents
|
||||
from .task.task import Task
|
||||
from .tools.tools import Tools
|
||||
from .agents.autoagents import AutoAgents
|
||||
from .memory.memory import Memory
|
||||
from .main import (
|
||||
TaskOutput,
|
||||
ReflectionOutput,
|
||||
display_interaction,
|
||||
display_self_reflection,
|
||||
display_instruction,
|
||||
display_tool_call,
|
||||
display_error,
|
||||
display_generating,
|
||||
clean_triple_backticks,
|
||||
error_logs,
|
||||
register_display_callback,
|
||||
sync_display_callbacks,
|
||||
async_display_callbacks,
|
||||
)
|
||||
|
||||
# Add Agents as an alias for PraisonAIAgents
|
||||
Agents = PraisonAIAgents
|
||||
|
||||
__all__ = [
|
||||
'Agent',
|
||||
'PraisonAIAgents',
|
||||
'Agents',
|
||||
'Tools',
|
||||
'Task',
|
||||
'TaskOutput',
|
||||
'ReflectionOutput',
|
||||
'AutoAgents',
|
||||
'Memory',
|
||||
'display_interaction',
|
||||
'display_self_reflection',
|
||||
'display_instruction',
|
||||
'display_tool_call',
|
||||
'display_error',
|
||||
'display_generating',
|
||||
'clean_triple_backticks',
|
||||
'error_logs',
|
||||
'register_display_callback',
|
||||
'sync_display_callbacks',
|
||||
'async_display_callbacks',
|
||||
]
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Agent module for AI agents"""
|
||||
from .agent import Agent
|
||||
|
||||
__all__ = ['Agent']
|
||||
@@ -1,740 +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
|
||||
)
|
||||
import inspect
|
||||
|
||||
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
|
||||
# Langchain tools
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
original_func = func
|
||||
func = func.run
|
||||
function_name = original_func.__name__
|
||||
|
||||
sig = inspect.signature(func)
|
||||
logging.debug(f"Function signature: {sig}")
|
||||
|
||||
# Skip self, *args, **kwargs, so they don't get passed in arguments
|
||||
parameters_list = []
|
||||
for name, param in sig.parameters.items():
|
||||
if name == "self":
|
||||
continue
|
||||
if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
|
||||
continue
|
||||
parameters_list.append((name, param))
|
||||
|
||||
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 parameters_list:
|
||||
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: Optional[Any] = None,
|
||||
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: bool = False,
|
||||
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) or \
|
||||
(inspect.isclass(tool) and tool.__name__ == function_name):
|
||||
func = tool
|
||||
break
|
||||
|
||||
if func is None:
|
||||
# If not found in tools, try globals and main
|
||||
func = globals().get(function_name)
|
||||
if not func:
|
||||
import __main__
|
||||
func = getattr(__main__, function_name, None)
|
||||
|
||||
if func:
|
||||
try:
|
||||
# If it's a class with run method, instantiate and call run
|
||||
if inspect.isclass(func) and hasattr(func, 'run'):
|
||||
instance = func()
|
||||
# Extract only the parameters that run() expects
|
||||
run_params = {k: v for k, v in arguments.items()
|
||||
if k in inspect.signature(instance.run).parameters
|
||||
and k != 'self'}
|
||||
return instance.run(**run_params)
|
||||
# Otherwise treat as regular function
|
||||
elif callable(func):
|
||||
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
|
||||
|
||||
def run(self):
|
||||
"""Alias for start() method"""
|
||||
return self.start()
|
||||
@@ -1,702 +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
|
||||
|
||||
# Set up logger
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
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, memory=False, memory_config=None, embedder=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')
|
||||
|
||||
# Set logger level based on verbose
|
||||
if verbose >= 5:
|
||||
logger.setLevel(logging.INFO)
|
||||
else:
|
||||
logger.setLevel(logging.WARNING)
|
||||
|
||||
# Also set third-party loggers to WARNING
|
||||
logging.getLogger('chromadb').setLevel(logging.WARNING)
|
||||
logging.getLogger('openai').setLevel(logging.WARNING)
|
||||
logging.getLogger('httpx').setLevel(logging.WARNING)
|
||||
logging.getLogger('httpcore').setLevel(logging.WARNING)
|
||||
|
||||
if self.verbose:
|
||||
logger.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)
|
||||
logger.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")
|
||||
logger.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])
|
||||
logger.info("Set up sequential flow with automatic context passing")
|
||||
|
||||
self._state = {} # Add state storage at PraisonAIAgents level
|
||||
|
||||
# Initialize memory system
|
||||
self.shared_memory = None
|
||||
if memory:
|
||||
try:
|
||||
from ..memory.memory import Memory
|
||||
|
||||
# Get memory config from parameter or first task
|
||||
mem_cfg = memory_config
|
||||
if not mem_cfg:
|
||||
mem_cfg = next((t.config.get('memory_config') for t in tasks if hasattr(t, 'config') and t.config), None)
|
||||
|
||||
# Set default memory config if none provided
|
||||
if not mem_cfg:
|
||||
mem_cfg = {
|
||||
"provider": "rag",
|
||||
"use_embedding": True,
|
||||
"storage": {
|
||||
"type": "sqlite",
|
||||
"path": "./.praison/memory.db"
|
||||
},
|
||||
"rag_db_path": "./.praison/chroma_db"
|
||||
}
|
||||
|
||||
# Add embedder config if provided
|
||||
if embedder:
|
||||
if isinstance(embedder, dict):
|
||||
mem_cfg = mem_cfg or {}
|
||||
mem_cfg["embedder"] = embedder
|
||||
else:
|
||||
# Handle direct embedder function
|
||||
mem_cfg = mem_cfg or {}
|
||||
mem_cfg["embedder_function"] = embedder
|
||||
|
||||
if mem_cfg:
|
||||
# Pass verbose level to Memory
|
||||
self.shared_memory = Memory(config=mem_cfg, verbose=verbose)
|
||||
if verbose >= 5:
|
||||
logger.info("Initialized shared memory for PraisonAIAgents")
|
||||
|
||||
# Distribute memory to tasks
|
||||
for task in tasks:
|
||||
if not task.memory:
|
||||
task.memory = self.shared_memory
|
||||
if verbose >= 5:
|
||||
logger.info(f"Assigned shared memory to task {task.id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize shared memory: {e}")
|
||||
|
||||
# Update tasks with shared memory
|
||||
if self.shared_memory:
|
||||
for task in tasks:
|
||||
if not task.memory:
|
||||
task.memory = self.shared_memory
|
||||
logger.info(f"Assigned shared memory to task {task.id}")
|
||||
|
||||
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:
|
||||
logger.info(f"Executing task {task_id}: {task.description} using {executor_agent.name}")
|
||||
logger.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:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as JSON")
|
||||
logger.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:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as Pydantic Model")
|
||||
logger.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":
|
||||
logger.info(f"Task with ID {task_id} is already completed")
|
||||
return
|
||||
|
||||
retries = 0
|
||||
while task.status != "completed" and retries < self.max_retries:
|
||||
logger.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"
|
||||
# Run execute_callback for memory operations
|
||||
try:
|
||||
await task.execute_callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing memory callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
# Run task callback if exists
|
||||
if task.callback:
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(task.callback):
|
||||
await task.callback(task_output)
|
||||
else:
|
||||
task.callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing task callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
self.save_output_to_file(task, task_output)
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} completed successfully.")
|
||||
else:
|
||||
task.status = "in progress"
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} not completed, retrying")
|
||||
await asyncio.sleep(1)
|
||||
retries += 1
|
||||
else:
|
||||
if task.status == "failed":
|
||||
logger.info("Task is failed, resetting to in-progress for another try...")
|
||||
task.status = "in progress"
|
||||
else:
|
||||
logger.info("Invalid Task status")
|
||||
break
|
||||
|
||||
if retries == self.max_retries and task.status != "completed":
|
||||
logger.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:
|
||||
logger.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]
|
||||
|
||||
logger.info(f"Starting execution of task {task_id}")
|
||||
logger.info(f"Task config: {task.config}")
|
||||
|
||||
# Initialize memory before task execution
|
||||
if not task.memory:
|
||||
task.memory = task.initialize_memory()
|
||||
|
||||
logger.info(f"Task memory status: {'Initialized' if task.memory else 'Not initialized'}")
|
||||
|
||||
# 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}
|
||||
"""
|
||||
# Add memory context if available
|
||||
if task.memory:
|
||||
try:
|
||||
memory_context = task.memory.build_context_for_task(task.description)
|
||||
if memory_context:
|
||||
task_prompt += f"\n\nRelevant memory context:\n{memory_context}"
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting memory context: {e}")
|
||||
|
||||
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
|
||||
|
||||
if self.verbose >= 2:
|
||||
logger.info(f"Executing task {task_id}: {task.description} using {executor_agent.name}")
|
||||
logger.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:
|
||||
# Store the response in memory
|
||||
if task.memory:
|
||||
try:
|
||||
task.store_in_memory(
|
||||
content=agent_output,
|
||||
agent_name=executor_agent.name,
|
||||
task_id=task_id
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to store agent output in memory: {e}")
|
||||
|
||||
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:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as JSON")
|
||||
logger.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:
|
||||
logger.warning(f"Warning: Could not parse output of task {task_id} as Pydantic Model")
|
||||
logger.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":
|
||||
logger.info(f"Task with ID {task_id} is already completed")
|
||||
return
|
||||
|
||||
retries = 0
|
||||
while task.status != "completed" and retries < self.max_retries:
|
||||
logger.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"
|
||||
# Run execute_callback for memory operations
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_until_complete(task.execute_callback(task_output))
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing memory callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
# Run task callback if exists
|
||||
if task.callback:
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(task.callback):
|
||||
loop.run_until_complete(task.callback(task_output))
|
||||
else:
|
||||
task.callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing task callback for task {task_id}: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
self.save_output_to_file(task, task_output)
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} completed successfully.")
|
||||
else:
|
||||
task.status = "in progress"
|
||||
if self.verbose >= 1:
|
||||
logger.info(f"Task {task_id} not completed, retrying")
|
||||
time.sleep(1)
|
||||
retries += 1
|
||||
else:
|
||||
if task.status == "failed":
|
||||
logger.info("Task is failed, resetting to in-progress for another try...")
|
||||
task.status = "in progress"
|
||||
else:
|
||||
logger.info("Invalid Task status")
|
||||
break
|
||||
|
||||
if retries == self.max_retries and task.status != "completed":
|
||||
logger.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,222 +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
|
||||
import os
|
||||
import time
|
||||
|
||||
# Set up logger
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class Task:
|
||||
def __init__(
|
||||
self,
|
||||
description: str,
|
||||
expected_output: Optional[str] = None,
|
||||
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,
|
||||
memory=None,
|
||||
quality_check=True
|
||||
):
|
||||
self.id = str(uuid.uuid4()) if id is None else str(id)
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.expected_output = expected_output if expected_output is not None else "Complete the task successfully"
|
||||
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 {}
|
||||
self.memory = memory
|
||||
self.quality_check = quality_check
|
||||
|
||||
# Set logger level based on config verbose level
|
||||
verbose = self.config.get("verbose", 0)
|
||||
if verbose >= 5:
|
||||
logger.setLevel(logging.INFO)
|
||||
else:
|
||||
logger.setLevel(logging.WARNING)
|
||||
|
||||
# Also set third-party loggers to WARNING
|
||||
logging.getLogger('chromadb').setLevel(logging.WARNING)
|
||||
logging.getLogger('openai').setLevel(logging.WARNING)
|
||||
logging.getLogger('httpx').setLevel(logging.WARNING)
|
||||
logging.getLogger('httpcore').setLevel(logging.WARNING)
|
||||
|
||||
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}')"
|
||||
|
||||
def initialize_memory(self):
|
||||
"""Initialize memory if config exists but memory doesn't"""
|
||||
if not self.memory and self.config.get('memory_config'):
|
||||
try:
|
||||
from ..memory.memory import Memory
|
||||
logger.info(f"Task {self.id}: Initializing memory from config: {self.config['memory_config']}")
|
||||
self.memory = Memory(config=self.config['memory_config'])
|
||||
logger.info(f"Task {self.id}: Memory initialized successfully")
|
||||
|
||||
# Verify database was created
|
||||
if os.path.exists(self.config['memory_config']['storage']['path']):
|
||||
logger.info(f"Task {self.id}: Memory database exists after initialization")
|
||||
else:
|
||||
logger.error(f"Task {self.id}: Failed to create memory database!")
|
||||
return self.memory
|
||||
except Exception as e:
|
||||
logger.error(f"Task {self.id}: Failed to initialize memory: {e}")
|
||||
logger.exception(e)
|
||||
return None
|
||||
|
||||
def store_in_memory(self, content: str, agent_name: str = None, task_id: str = None):
|
||||
"""Store content in memory with metadata"""
|
||||
if self.memory:
|
||||
try:
|
||||
logger.info(f"Task {self.id}: Storing content in memory...")
|
||||
self.memory.store_long_term(
|
||||
text=content,
|
||||
metadata={
|
||||
"agent_name": agent_name or "Agent",
|
||||
"task_id": task_id or self.id,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
)
|
||||
logger.info(f"Task {self.id}: Content stored in memory")
|
||||
except Exception as e:
|
||||
logger.error(f"Task {self.id}: Failed to store content in memory: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
async def execute_callback(self, task_output: TaskOutput) -> None:
|
||||
"""Execute callback and store quality metrics if enabled"""
|
||||
logger.info(f"Task {self.id}: execute_callback called")
|
||||
logger.info(f"Quality check enabled: {self.quality_check}")
|
||||
|
||||
# Initialize memory if not already initialized
|
||||
if not self.memory:
|
||||
self.memory = self.initialize_memory()
|
||||
|
||||
logger.info(f"Memory object exists: {self.memory is not None}")
|
||||
if self.memory:
|
||||
logger.info(f"Memory config: {self.memory.cfg}")
|
||||
# Store task output in memory
|
||||
try:
|
||||
logger.info(f"Task {self.id}: Storing task output in memory...")
|
||||
self.store_in_memory(
|
||||
content=task_output.raw,
|
||||
agent_name=self.agent.name if self.agent else "Agent",
|
||||
task_id=self.id
|
||||
)
|
||||
logger.info(f"Task {self.id}: Task output stored in memory")
|
||||
except Exception as e:
|
||||
logger.error(f"Task {self.id}: Failed to store task output in memory: {e}")
|
||||
logger.exception(e)
|
||||
|
||||
logger.info(f"Task output: {task_output.raw[:100]}...")
|
||||
|
||||
if self.quality_check and self.memory:
|
||||
try:
|
||||
logger.info(f"Task {self.id}: Starting memory operations")
|
||||
logger.info(f"Task {self.id}: Calculating quality metrics for output: {task_output.raw[:100]}...")
|
||||
|
||||
# Get quality metrics from LLM
|
||||
metrics = self.memory.calculate_quality_metrics(
|
||||
task_output.raw,
|
||||
self.expected_output
|
||||
)
|
||||
logger.info(f"Task {self.id}: Quality metrics calculated: {metrics}")
|
||||
|
||||
quality_score = metrics.get("accuracy", 0.0)
|
||||
logger.info(f"Task {self.id}: Quality score: {quality_score}")
|
||||
|
||||
# Store in both short and long-term memory with higher threshold
|
||||
logger.info(f"Task {self.id}: Finalizing task output in memory...")
|
||||
self.memory.finalize_task_output(
|
||||
content=task_output.raw,
|
||||
agent_name=self.agent.name if self.agent else "Agent",
|
||||
quality_score=quality_score,
|
||||
threshold=0.7, # Only high quality outputs in long-term memory
|
||||
metrics=metrics,
|
||||
task_id=self.id
|
||||
)
|
||||
logger.info(f"Task {self.id}: Finalized task output in memory")
|
||||
|
||||
# Store quality metrics separately
|
||||
logger.info(f"Task {self.id}: Storing quality metrics...")
|
||||
self.memory.store_quality(
|
||||
text=task_output.raw,
|
||||
quality_score=quality_score,
|
||||
task_id=self.id,
|
||||
metrics=metrics
|
||||
)
|
||||
|
||||
# Store in both short and long-term memory with higher threshold
|
||||
self.memory.finalize_task_output(
|
||||
content=task_output.raw,
|
||||
agent_name=self.agent.name if self.agent else "Agent",
|
||||
quality_score=quality_score,
|
||||
threshold=0.7 # Only high quality outputs in long-term memory
|
||||
)
|
||||
|
||||
# Build context for next tasks
|
||||
if self.next_tasks:
|
||||
logger.info(f"Task {self.id}: Building context for next tasks...")
|
||||
context = self.memory.build_context_for_task(
|
||||
task_descr=task_output.raw,
|
||||
max_items=5
|
||||
)
|
||||
logger.info(f"Task {self.id}: Built context for next tasks: {len(context)} items")
|
||||
|
||||
logger.info(f"Task {self.id}: Memory operations complete")
|
||||
except Exception as e:
|
||||
logger.error(f"Task {self.id}: Failed to process memory operations: {e}")
|
||||
logger.exception(e) # Print full stack trace
|
||||
# Continue execution even if memory operations fail
|
||||
|
||||
# Execute original callback
|
||||
if self.callback:
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(self.callback):
|
||||
await self.callback(task_output)
|
||||
else:
|
||||
self.callback(task_output)
|
||||
except Exception as e:
|
||||
logger.error(f"Task {self.id}: Failed to execute callback: {e}")
|
||||
logger.exception(e)
|
||||
@@ -1,21 +0,0 @@
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.30"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
authors = [
|
||||
{ name="Mervin Praison" }
|
||||
]
|
||||
dependencies = [
|
||||
"pydantic",
|
||||
"rich",
|
||||
"openai"
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
memory = [
|
||||
"chromadb>=0.6.0"
|
||||
]
|
||||
Generated
-1590
File diff suppressed because it is too large.
Load diff
@@ -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.32" \
|
||||
"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.32" \
|
||||
"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.32" \
|
||||
"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.32" \
|
||||
"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.32`
|
||||
- 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.32" "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,201 @@
|
||||
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:
|
||||
security_opt:
|
||||
- "no-new-privileges:true"
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_DB: praisonai_dev
|
||||
POSTGRES_USER: praisonai
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-praisonai_dev_pass}
|
||||
volumes:
|
||||
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
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
- /var/tmp
|
||||
ports:
|
||||
- "5432:5432"
|
||||
networks:
|
||||
- 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.
@@ -1 +0,0 @@
|
||||
docs.praison.ai
|
||||
@@ -1,20 +0,0 @@
|
||||
# Minimal makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line, and also
|
||||
# from the environment for the first two.
|
||||
SPHINXOPTS ?=
|
||||
SPHINXBUILD ?= sphinx-build
|
||||
SOURCEDIR = .
|
||||
BUILDDIR = _build
|
||||
|
||||
# Put it first so that "make" without argument is like "make help".
|
||||
help:
|
||||
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||
|
||||
.PHONY: help Makefile
|
||||
|
||||
# Catch-all target: route all unknown targets to Sphinx using the new
|
||||
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
||||
%: Makefile
|
||||
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
title: 'API Reference'
|
||||
description: 'PraisonAI API documentation with framework-specific details'
|
||||
icon: "book-open"
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
This section provides detailed information about the PraisonAI API and its framework-specific implementations.
|
||||
|
||||
## Core Modules
|
||||
|
||||
- [praisonai](../api/praisonai/index) - Core package functionality
|
||||
- [praisonai.auto](../api/praisonai/auto) - Automated agent generation
|
||||
- [praisonai.agents_generator](../api/praisonai/agents_generator) - Framework-specific agent generation
|
||||
- [praisonai.cli](../api/praisonai/cli) - Command-line interface
|
||||
- [praisonai.deploy](../api/praisonai/deploy) - Deployment utilities
|
||||
|
||||
## Framework Support
|
||||
|
||||
### CrewAI Integration
|
||||
Requires installation with:
|
||||
```bash
|
||||
pip install "praisonai[crewai]"
|
||||
```
|
||||
|
||||
Features:
|
||||
- Task delegation
|
||||
- Sequential/parallel execution
|
||||
- Built-in tools
|
||||
- Structured workflows
|
||||
|
||||
### AutoGen Integration
|
||||
Requires installation with:
|
||||
```bash
|
||||
pip install "praisonai[autogen]"
|
||||
```
|
||||
|
||||
Features:
|
||||
- Multi-agent conversations
|
||||
- Code execution
|
||||
- Built-in tools
|
||||
- Flexible interactions
|
||||
|
||||
For detailed API documentation of each module, please refer to the generated files in the `api` folder.
|
||||
@@ -1,79 +0,0 @@
|
||||
---
|
||||
title: "API Reference"
|
||||
description: "Complete API reference for PraisonAI, including core modules, installation options, and framework-specific features"
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
## Core Modules
|
||||
|
||||
### praisonai
|
||||
The main package containing core functionality.
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
```
|
||||
|
||||
### praisonai.auto
|
||||
Automated agent generation functionality.
|
||||
|
||||
```python
|
||||
from praisonai.auto import AutoGenerator
|
||||
```
|
||||
|
||||
### praisonai.agents_generator
|
||||
Framework-specific agent generation and orchestration:
|
||||
- CrewAI support (requires `praisonai[crewai]`)
|
||||
- AutoGen support (requires `praisonai[autogen]`)
|
||||
|
||||
```python
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
```
|
||||
|
||||
### praisonai.cli
|
||||
Command-line interface with framework-specific handling.
|
||||
|
||||
```python
|
||||
from praisonai.cli import PraisonAI
|
||||
```
|
||||
|
||||
### praisonai.deploy
|
||||
Deployment utilities.
|
||||
|
||||
```python
|
||||
from praisonai.deploy import CloudDeployer
|
||||
```
|
||||
|
||||
## Installation Options
|
||||
|
||||
```bash
|
||||
# Basic installation
|
||||
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[crewai,autogen]" # Install both frameworks
|
||||
|
||||
# Additional features
|
||||
pip install "praisonai[ui]" # Install UI support
|
||||
pip install "praisonai[chat]" # Install Chat interface
|
||||
pip install "praisonai[code]" # Install Code interface
|
||||
pip install "praisonai[realtime]" # Install Realtime voice interaction
|
||||
pip install "praisonai[call]" # Install Call feature
|
||||
```
|
||||
|
||||
## 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
|
||||
@@ -1,566 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.agents_generator API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.agents_generator</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.agents_generator.disable_crewai_telemetry"><code class="name flex">
|
||||
<span>def <span class="ident">disable_crewai_telemetry</span></span>(<span>)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.agents_generator.noop"><code class="name flex">
|
||||
<span>def <span class="ident">noop</span></span>(<span>*args, **kwargs)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.agents_generator.AgentsGenerator"><code class="flex name class">
|
||||
<span>class <span class="ident">AgentsGenerator</span></span>
|
||||
<span>(</span><span>agent_file, framework, config_list, log_level=None, agent_callback=None, task_callback=None, agent_yaml=None, tools=None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Initialize the AgentsGenerator object.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>agent_file (str): The path to the agent file.
|
||||
framework (str): The framework to be used for the agents.
|
||||
config_list (list): A list of configurations for the agents.
|
||||
log_level (int, optional): The logging level to use. Defaults to logging.INFO.
|
||||
agent_callback (callable, optional): A callback function to be executed after each agent step.
|
||||
task_callback (callable, optional): A callback function to be executed after each tool run.
|
||||
agent_yaml (str, optional): The content of the YAML file. Defaults to None.
|
||||
tools (dict, optional): A dictionary containing the tools to be used for the agents. Defaults to None.</p>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<dl>
|
||||
<dt><strong><code>agent_file</code></strong> : <code>str</code></dt>
|
||||
<dd>The path to the agent file.</dd>
|
||||
<dt><strong><code>framework</code></strong> : <code>str</code></dt>
|
||||
<dd>The framework to be used for the agents.</dd>
|
||||
<dt><strong><code>config_list</code></strong> : <code>list</code></dt>
|
||||
<dd>A list of configurations for the agents.</dd>
|
||||
<dt><strong><code>log_level</code></strong> : <code>int</code></dt>
|
||||
<dd>The logging level to use.</dd>
|
||||
<dt><strong><code>agent_callback</code></strong> : <code>callable</code>, optional</dt>
|
||||
<dd>A callback function to be executed after each agent step.</dd>
|
||||
<dt><strong><code>task_callback</code></strong> : <code>callable</code>, optional</dt>
|
||||
<dd>A callback function to be executed after each tool run.</dd>
|
||||
<dt><strong><code>tools</code></strong> : <code>dict</code></dt>
|
||||
<dd>A dictionary containing the tools to be used for the agents.</dd>
|
||||
</dl></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class AgentsGenerator:
|
||||
def __init__(self, agent_file, framework, config_list, log_level=None, agent_callback=None, task_callback=None, agent_yaml=None, tools=None):
|
||||
"""
|
||||
Initialize the AgentsGenerator object.
|
||||
|
||||
Parameters:
|
||||
agent_file (str): The path to the agent file.
|
||||
framework (str): The framework to be used for the agents.
|
||||
config_list (list): A list of configurations for the agents.
|
||||
log_level (int, optional): The logging level to use. Defaults to logging.INFO.
|
||||
agent_callback (callable, optional): A callback function to be executed after each agent step.
|
||||
task_callback (callable, optional): A callback function to be executed after each tool run.
|
||||
agent_yaml (str, optional): The content of the YAML file. Defaults to None.
|
||||
tools (dict, optional): A dictionary containing the tools to be used for the agents. Defaults to None.
|
||||
|
||||
Attributes:
|
||||
agent_file (str): The path to the agent file.
|
||||
framework (str): The framework to be used for the agents.
|
||||
config_list (list): A list of configurations for the agents.
|
||||
log_level (int): The logging level to use.
|
||||
agent_callback (callable, optional): A callback function to be executed after each agent step.
|
||||
task_callback (callable, optional): A callback function to be executed after each tool run.
|
||||
tools (dict): A dictionary containing the tools to be used for the agents.
|
||||
"""
|
||||
self.agent_file = agent_file
|
||||
self.framework = framework
|
||||
self.config_list = config_list
|
||||
self.log_level = log_level
|
||||
self.agent_callback = agent_callback
|
||||
self.task_callback = task_callback
|
||||
self.agent_yaml = agent_yaml
|
||||
self.tools = tools or [] # Store tool class names as a list
|
||||
self.log_level = log_level or logging.getLogger().getEffectiveLevel()
|
||||
if self.log_level == logging.NOTSET:
|
||||
self.log_level = os.environ.get('LOGLEVEL', 'INFO').upper()
|
||||
|
||||
logging.basicConfig(level=self.log_level, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.setLevel(self.log_level)
|
||||
|
||||
def is_function_or_decorated(self, obj):
|
||||
"""
|
||||
Checks if the given object is a function or has a __call__ method.
|
||||
|
||||
Parameters:
|
||||
obj (object): The object to be checked.
|
||||
|
||||
Returns:
|
||||
bool: True if the object is a function or has a __call__ method, False otherwise.
|
||||
"""
|
||||
return inspect.isfunction(obj) or hasattr(obj, '__call__')
|
||||
|
||||
def load_tools_from_module(self, module_path):
|
||||
"""
|
||||
Loads tools from a specified module path.
|
||||
|
||||
Parameters:
|
||||
module_path (str): The path to the module containing the tools.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the names of the tools as keys and the corresponding functions or objects as values.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the specified module path does not exist.
|
||||
"""
|
||||
spec = importlib.util.spec_from_file_location("tools_module", module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return {name: obj for name, obj in inspect.getmembers(module, self.is_function_or_decorated)}
|
||||
|
||||
def load_tools_from_module_class(self, module_path):
|
||||
"""
|
||||
Loads tools from a specified module path containing classes that inherit from BaseTool or are part of langchain_community.tools package.
|
||||
|
||||
Parameters:
|
||||
module_path (str): The path to the module containing the tools.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the specified module path does not exist.
|
||||
"""
|
||||
spec = importlib.util.spec_from_file_location("tools_module", module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return {name: obj() for name, obj in inspect.getmembers(module, lambda x: inspect.isclass(x) and (x.__module__.startswith('langchain_community.tools') or issubclass(x, BaseTool)) and x is not BaseTool)}
|
||||
|
||||
def load_tools_from_package(self, package_path):
|
||||
"""
|
||||
Loads tools from a specified package path containing modules with functions or classes.
|
||||
|
||||
Parameters:
|
||||
package_path (str): The path to the package containing the tools.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the specified package path does not exist.
|
||||
|
||||
This function iterates through all the .py files in the specified package path, excluding those that start with "__". For each file, it imports the corresponding module and checks if it contains any functions or classes that can be loaded as tools. The function then returns a dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
|
||||
"""
|
||||
tools_dict = {}
|
||||
for module_file in os.listdir(package_path):
|
||||
if module_file.endswith('.py') and not module_file.startswith('__'):
|
||||
module_name = f"{package_path.name}.{module_file[:-3]}" # Remove .py for import
|
||||
module = importlib.import_module(module_name)
|
||||
for name, obj in inspect.getmembers(module, self.is_function_or_decorated):
|
||||
tools_dict[name] = obj
|
||||
return tools_dict
|
||||
|
||||
def generate_crew_and_kickoff(self):
|
||||
"""
|
||||
Generates a crew of agents and initiates tasks based on the provided configuration.
|
||||
|
||||
Parameters:
|
||||
agent_file (str): The path to the agent file.
|
||||
framework (str): The framework to be used for the agents.
|
||||
config_list (list): A list of configurations for the agents.
|
||||
|
||||
Returns:
|
||||
str: The output of the tasks performed by the crew of agents.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the specified agent file does not exist.
|
||||
|
||||
This function first loads the agent configuration from the specified file. It then initializes the tools required for the agents based on the specified framework. If the specified framework is "autogen", it loads the LLM configuration dynamically and creates an AssistantAgent for each role in the configuration. It then adds tools to the agents if specified in the configuration. Finally, it prepares tasks for the agents based on the configuration and initiates the tasks using the crew of agents. If the specified framework is not "autogen", it creates a crew of agents and initiates tasks based on the configuration.
|
||||
"""
|
||||
if self.agent_yaml:
|
||||
config = yaml.safe_load(self.agent_yaml)
|
||||
else:
|
||||
if self.agent_file == '/app/api:app' or self.agent_file == 'api:app':
|
||||
self.agent_file = 'agents.yaml'
|
||||
try:
|
||||
with open(self.agent_file, 'r') as f:
|
||||
config = yaml.safe_load(f)
|
||||
except FileNotFoundError:
|
||||
print(f"File not found: {self.agent_file}")
|
||||
return
|
||||
|
||||
topic = config['topic']
|
||||
tools_dict = {
|
||||
'CodeDocsSearchTool': CodeDocsSearchTool(),
|
||||
'CSVSearchTool': CSVSearchTool(),
|
||||
'DirectorySearchTool': DirectorySearchTool(),
|
||||
'DOCXSearchTool': DOCXSearchTool(),
|
||||
'DirectoryReadTool': DirectoryReadTool(),
|
||||
'FileReadTool': FileReadTool(),
|
||||
# 'GithubSearchTool': GithubSearchTool(),
|
||||
# 'SeperDevTool': SeperDevTool(),
|
||||
'TXTSearchTool': TXTSearchTool(),
|
||||
'JSONSearchTool': JSONSearchTool(),
|
||||
'MDXSearchTool': MDXSearchTool(),
|
||||
'PDFSearchTool': PDFSearchTool(),
|
||||
# 'PGSearchTool': PGSearchTool(),
|
||||
'RagTool': RagTool(),
|
||||
'ScrapeElementFromWebsiteTool': ScrapeElementFromWebsiteTool(),
|
||||
'ScrapeWebsiteTool': ScrapeWebsiteTool(),
|
||||
'WebsiteSearchTool': WebsiteSearchTool(),
|
||||
'XMLSearchTool': XMLSearchTool(),
|
||||
'YoutubeChannelSearchTool': YoutubeChannelSearchTool(),
|
||||
'YoutubeVideoSearchTool': YoutubeVideoSearchTool(),
|
||||
}
|
||||
|
||||
# Add tools from class names
|
||||
for tool_class in self.tools:
|
||||
if isinstance(tool_class, type) and issubclass(tool_class, BaseTool):
|
||||
tool_name = tool_class.__name__
|
||||
tools_dict[tool_name] = tool_class()
|
||||
self.logger.debug(f"Added tool: {tool_name}")
|
||||
|
||||
root_directory = os.getcwd()
|
||||
tools_py_path = os.path.join(root_directory, 'tools.py')
|
||||
tools_dir_path = Path(root_directory) / 'tools'
|
||||
|
||||
if os.path.isfile(tools_py_path):
|
||||
tools_dict.update(self.load_tools_from_module_class(tools_py_path))
|
||||
self.logger.debug("tools.py exists in the root directory. Loading tools.py and skipping tools folder.")
|
||||
elif tools_dir_path.is_dir():
|
||||
tools_dict.update(self.load_tools_from_module_class(tools_dir_path))
|
||||
self.logger.debug("tools folder exists in the root directory")
|
||||
|
||||
framework = self.framework or config.get('framework')
|
||||
|
||||
agents = {}
|
||||
tasks = []
|
||||
if framework == "autogen":
|
||||
# Load the LLM configuration dynamically
|
||||
# print(self.config_list)
|
||||
llm_config = {"config_list": self.config_list}
|
||||
|
||||
if agentops_exists:
|
||||
agentops.init(os.environ.get("AGENTOPS_API_KEY"), tags=["autogen"])
|
||||
# Assuming the user proxy agent is set up as per your requirements
|
||||
user_proxy = autogen.UserProxyAgent(
|
||||
name="User",
|
||||
human_input_mode="NEVER",
|
||||
is_termination_msg=lambda x: (x.get("content") or "").rstrip().rstrip(".").lower().endswith("terminate") or "TERMINATE" in (x.get("content") or ""),
|
||||
code_execution_config={
|
||||
"work_dir": "coding",
|
||||
"use_docker": False,
|
||||
},
|
||||
# additional setup for the user proxy agent
|
||||
)
|
||||
|
||||
for role, details in config['roles'].items():
|
||||
agent_name = details['role'].format(topic=topic).replace("{topic}", topic)
|
||||
agent_goal = details['goal'].format(topic=topic)
|
||||
# Creating an AssistantAgent for each role dynamically
|
||||
agents[role] = autogen.AssistantAgent(
|
||||
name=agent_name,
|
||||
llm_config=llm_config,
|
||||
system_message=details['backstory'].format(topic=topic)+". Must Reply \"TERMINATE\" in the end when everything is done.",
|
||||
)
|
||||
for tool in details.get('tools', []):
|
||||
if tool in tools_dict:
|
||||
try:
|
||||
tool_class = globals()[f'autogen_{type(tools_dict[tool]).__name__}']
|
||||
print(f"Found {tool_class.__name__} for {tool}")
|
||||
except KeyError:
|
||||
print(f"Warning: autogen_{type(tools_dict[tool]).__name__} function not found. Skipping this tool.")
|
||||
continue
|
||||
tool_class(agents[role], user_proxy)
|
||||
|
||||
# Preparing tasks for initiate_chats
|
||||
for task_name, task_details in details.get('tasks', {}).items():
|
||||
description_filled = task_details['description'].format(topic=topic)
|
||||
expected_output_filled = task_details['expected_output'].format(topic=topic)
|
||||
|
||||
chat_task = {
|
||||
"recipient": agents[role],
|
||||
"message": description_filled,
|
||||
"summary_method": "last_msg",
|
||||
# Additional fields like carryover can be added based on dependencies
|
||||
}
|
||||
tasks.append(chat_task)
|
||||
response = user_proxy.initiate_chats(tasks)
|
||||
result = "### Output ###\n"+response[-1].summary if hasattr(response[-1], 'summary') else ""
|
||||
if agentops_exists:
|
||||
agentops.end_session("Success")
|
||||
else: # framework=crewai
|
||||
if agentops_exists:
|
||||
agentops.init(os.environ.get("AGENTOPS_API_KEY"), tags=["crewai"])
|
||||
|
||||
tasks_dict = {}
|
||||
|
||||
for role, details in config['roles'].items():
|
||||
role_filled = details['role'].format(topic=topic)
|
||||
goal_filled = details['goal'].format(topic=topic)
|
||||
backstory_filled = details['backstory'].format(topic=topic)
|
||||
|
||||
# Adding tools to the agent if exists
|
||||
agent_tools = [tools_dict[tool] for tool in details.get('tools', []) if tool in tools_dict]
|
||||
|
||||
llm_model = details.get('llm') # Get the llm configuration
|
||||
if llm_model:
|
||||
llm = PraisonAIModel(
|
||||
model=llm_model.get("model", os.environ.get("MODEL_NAME", "openai/gpt-4o")),
|
||||
).get_model()
|
||||
else:
|
||||
llm = PraisonAIModel().get_model()
|
||||
|
||||
function_calling_llm_model = details.get('function_calling_llm')
|
||||
if function_calling_llm_model:
|
||||
function_calling_llm = PraisonAIModel(
|
||||
model=function_calling_llm_model.get("model", os.environ.get("MODEL_NAME", "openai/gpt-4o")),
|
||||
).get_model()
|
||||
else:
|
||||
function_calling_llm = PraisonAIModel().get_model()
|
||||
|
||||
agent = Agent(
|
||||
role=role_filled,
|
||||
goal=goal_filled,
|
||||
backstory=backstory_filled,
|
||||
tools=agent_tools,
|
||||
allow_delegation=details.get('allow_delegation', False),
|
||||
llm=llm,
|
||||
function_calling_llm=function_calling_llm,
|
||||
max_iter=details.get('max_iter', 15),
|
||||
max_rpm=details.get('max_rpm'),
|
||||
max_execution_time=details.get('max_execution_time'),
|
||||
verbose=details.get('verbose', True),
|
||||
cache=details.get('cache', True),
|
||||
system_template=details.get('system_template'),
|
||||
prompt_template=details.get('prompt_template'),
|
||||
response_template=details.get('response_template'),
|
||||
)
|
||||
|
||||
# Set agent callback if provided
|
||||
if self.agent_callback:
|
||||
agent.step_callback = self.agent_callback
|
||||
|
||||
agents[role] = agent
|
||||
|
||||
for task_name, task_details in details.get('tasks', {}).items():
|
||||
description_filled = task_details['description'].format(topic=topic)
|
||||
expected_output_filled = task_details['expected_output'].format(topic=topic)
|
||||
|
||||
task = Task(
|
||||
description=description_filled, # Clear, concise statement of what the task entails
|
||||
expected_output=expected_output_filled, # Detailed description of what task's completion looks like
|
||||
agent=agent, # The agent responsible for the task
|
||||
tools=task_details.get('tools', []), # Functions or capabilities the agent can utilize
|
||||
async_execution=task_details.get('async_execution') if task_details.get('async_execution') is not None else False, # Execute asynchronously if set
|
||||
context=[], ## TODO:
|
||||
config=task_details.get('config') if task_details.get('config') is not None else {}, # Additional configuration details
|
||||
output_json=task_details.get('output_json') if task_details.get('output_json') is not None else None, # Outputs a JSON object
|
||||
output_pydantic=task_details.get('output_pydantic') if task_details.get('output_pydantic') is not None else None, # Outputs a Pydantic model object
|
||||
output_file=task_details.get('output_file') if task_details.get('output_file') is not None else "", # Saves the task output to a file
|
||||
callback=task_details.get('callback') if task_details.get('callback') is not None else None, # Python callable executed with the task's output
|
||||
human_input=task_details.get('human_input') if task_details.get('human_input') is not None else False, # Indicates if the task requires human feedback
|
||||
create_directory=task_details.get('create_directory') if task_details.get('create_directory') is not None else False # Indicates if a directory needs to be created
|
||||
)
|
||||
|
||||
# Set tool callback if provided
|
||||
if self.task_callback:
|
||||
task.callback = self.task_callback
|
||||
|
||||
tasks.append(task)
|
||||
tasks_dict[task_name] = task
|
||||
|
||||
for role, details in config['roles'].items():
|
||||
for task_name, task_details in details.get('tasks', {}).items():
|
||||
task = tasks_dict[task_name]
|
||||
context_tasks = [tasks_dict[ctx] for ctx in task_details.get('context', []) if ctx in tasks_dict]
|
||||
task.context = context_tasks
|
||||
|
||||
crew = Crew(
|
||||
agents=list(agents.values()),
|
||||
tasks=tasks,
|
||||
verbose=2
|
||||
)
|
||||
|
||||
self.logger.debug("Final Crew Configuration:")
|
||||
self.logger.debug(f"Agents: {crew.agents}")
|
||||
self.logger.debug(f"Tasks: {crew.tasks}")
|
||||
|
||||
response = crew.kickoff()
|
||||
result = f"### Task Output ###\n{response}"
|
||||
if agentops_exists:
|
||||
agentops.end_session("Success")
|
||||
return result</code></pre>
|
||||
</details>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.agents_generator.AgentsGenerator.generate_crew_and_kickoff"><code class="name flex">
|
||||
<span>def <span class="ident">generate_crew_and_kickoff</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Generates a crew of agents and initiates tasks based on the provided configuration.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>agent_file (str): The path to the agent file.
|
||||
framework (str): The framework to be used for the agents.
|
||||
config_list (list): A list of configurations for the agents.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>str</code></dt>
|
||||
<dd>The output of the tasks performed by the crew of agents.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>FileNotFoundError</code></dt>
|
||||
<dd>If the specified agent file does not exist.</dd>
|
||||
</dl>
|
||||
<p>This function first loads the agent configuration from the specified file. It then initializes the tools required for the agents based on the specified framework. If the specified framework is "autogen", it loads the LLM configuration dynamically and creates an AssistantAgent for each role in the configuration. It then adds tools to the agents if specified in the configuration. Finally, it prepares tasks for the agents based on the configuration and initiates the tasks using the crew of agents. If the specified framework is not "autogen", it creates a crew of agents and initiates tasks based on the configuration.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.agents_generator.AgentsGenerator.is_function_or_decorated"><code class="name flex">
|
||||
<span>def <span class="ident">is_function_or_decorated</span></span>(<span>self, obj)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Checks if the given object is a function or has a <strong>call</strong> method.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>obj (object): The object to be checked.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>bool</code></dt>
|
||||
<dd>True if the object is a function or has a <strong>call</strong> method, False otherwise.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.agents_generator.AgentsGenerator.load_tools_from_module"><code class="name flex">
|
||||
<span>def <span class="ident">load_tools_from_module</span></span>(<span>self, module_path)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Loads tools from a specified module path.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>module_path (str): The path to the module containing the tools.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>dict</code></dt>
|
||||
<dd>A dictionary containing the names of the tools as keys and the corresponding functions or objects as values.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>FileNotFoundError</code></dt>
|
||||
<dd>If the specified module path does not exist.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.agents_generator.AgentsGenerator.load_tools_from_module_class"><code class="name flex">
|
||||
<span>def <span class="ident">load_tools_from_module_class</span></span>(<span>self, module_path)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Loads tools from a specified module path containing classes that inherit from BaseTool or are part of langchain_community.tools package.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>module_path (str): The path to the module containing the tools.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>dict</code></dt>
|
||||
<dd>A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>FileNotFoundError</code></dt>
|
||||
<dd>If the specified module path does not exist.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.agents_generator.AgentsGenerator.load_tools_from_package"><code class="name flex">
|
||||
<span>def <span class="ident">load_tools_from_package</span></span>(<span>self, package_path)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Loads tools from a specified package path containing modules with functions or classes.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>package_path (str): The path to the package containing the tools.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>dict</code></dt>
|
||||
<dd>A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>FileNotFoundError</code></dt>
|
||||
<dd>If the specified package path does not exist.</dd>
|
||||
</dl>
|
||||
<p>This function iterates through all the .py files in the specified package path, excluding those that start with "__". For each file, it imports the corresponding module and checks if it contains any functions or classes that can be loaded as tools. The function then returns a dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.agents_generator.disable_crewai_telemetry" href="#praisonai.agents_generator.disable_crewai_telemetry">disable_crewai_telemetry</a></code></li>
|
||||
<li><code><a title="praisonai.agents_generator.noop" href="#praisonai.agents_generator.noop">noop</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.agents_generator.AgentsGenerator" href="#praisonai.agents_generator.AgentsGenerator">AgentsGenerator</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.agents_generator.AgentsGenerator.generate_crew_and_kickoff" href="#praisonai.agents_generator.AgentsGenerator.generate_crew_and_kickoff">generate_crew_and_kickoff</a></code></li>
|
||||
<li><code><a title="praisonai.agents_generator.AgentsGenerator.is_function_or_decorated" href="#praisonai.agents_generator.AgentsGenerator.is_function_or_decorated">is_function_or_decorated</a></code></li>
|
||||
<li><code><a title="praisonai.agents_generator.AgentsGenerator.load_tools_from_module" href="#praisonai.agents_generator.AgentsGenerator.load_tools_from_module">load_tools_from_module</a></code></li>
|
||||
<li><code><a title="praisonai.agents_generator.AgentsGenerator.load_tools_from_module_class" href="#praisonai.agents_generator.AgentsGenerator.load_tools_from_module_class">load_tools_from_module_class</a></code></li>
|
||||
<li><code><a title="praisonai.agents_generator.AgentsGenerator.load_tools_from_package" href="#praisonai.agents_generator.AgentsGenerator.load_tools_from_package">load_tools_from_package</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,622 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.auto API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.auto</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.auto.AutoGenerator"><code class="flex name class">
|
||||
<span>class <span class="ident">AutoGenerator</span></span>
|
||||
<span>(</span><span>topic='Movie Story writing about AI', agent_file='test.yaml', framework='crewai', config_list: Optional[List[Dict]] = None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Initialize the AutoGenerator class with the specified topic, agent file, and framework.
|
||||
Note: autogen framework is different from this AutoGenerator class.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>topic</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The topic for the generated team structure. Defaults to "Movie Story writing about AI".</dd>
|
||||
<dt><strong><code>agent_file</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The name of the YAML file to save the generated team structure. Defaults to "test.yaml".</dd>
|
||||
<dt><strong><code>framework</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The framework for the generated team structure. Defaults to "crewai".</dd>
|
||||
<dt><strong><code>config_list</code></strong> : <code>Optional[List[Dict]]</code>, optional</dt>
|
||||
<dd>A list containing the configuration details for the OpenAI API.
|
||||
If None, it defaults to using environment variables or hardcoded values.</dd>
|
||||
</dl>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<dl>
|
||||
<dt><strong><code>config_list</code></strong> : <code>list</code></dt>
|
||||
<dd>A list containing the configuration details for the OpenAI API.</dd>
|
||||
<dt><strong><code>topic</code></strong> : <code>str</code></dt>
|
||||
<dd>The specified topic for the generated team structure.</dd>
|
||||
<dt><strong><code>agent_file</code></strong> : <code>str</code></dt>
|
||||
<dd>The specified name of the YAML file to save the generated team structure.</dd>
|
||||
<dt><strong><code>framework</code></strong> : <code>str</code></dt>
|
||||
<dd>The specified framework for the generated team structure.</dd>
|
||||
<dt><strong><code>client</code></strong> : <code>instructor.Client</code></dt>
|
||||
<dd>An instance of the instructor.Client class initialized with the specified OpenAI API configuration.</dd>
|
||||
</dl></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class AutoGenerator:
|
||||
def __init__(self, topic="Movie Story writing about AI", agent_file="test.yaml", framework="crewai", config_list: Optional[List[Dict]] = None):
|
||||
"""
|
||||
Initialize the AutoGenerator class with the specified topic, agent file, and framework.
|
||||
Note: autogen framework is different from this AutoGenerator class.
|
||||
|
||||
Args:
|
||||
topic (str, optional): The topic for the generated team structure. Defaults to "Movie Story writing about AI".
|
||||
agent_file (str, optional): The name of the YAML file to save the generated team structure. Defaults to "test.yaml".
|
||||
framework (str, optional): The framework for the generated team structure. Defaults to "crewai".
|
||||
config_list (Optional[List[Dict]], optional): A list containing the configuration details for the OpenAI API.
|
||||
If None, it defaults to using environment variables or hardcoded values.
|
||||
Attributes:
|
||||
config_list (list): A list containing the configuration details for the OpenAI API.
|
||||
topic (str): The specified topic for the generated team structure.
|
||||
agent_file (str): The specified name of the YAML file to save the generated team structure.
|
||||
framework (str): The specified framework for the generated team structure.
|
||||
client (instructor.Client): An instance of the instructor.Client class initialized with the specified OpenAI API configuration.
|
||||
"""
|
||||
self.config_list = config_list or [
|
||||
{
|
||||
'model': os.environ.get("OPENAI_MODEL_NAME", "gpt-4o"),
|
||||
'base_url': os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
|
||||
'api_key': os.environ.get("OPENAI_API_KEY")
|
||||
}
|
||||
]
|
||||
self.topic = topic
|
||||
self.agent_file = agent_file
|
||||
self.framework = framework or "crewai"
|
||||
self.client = instructor.patch(
|
||||
OpenAI(
|
||||
base_url=self.config_list[0]['base_url'],
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
),
|
||||
mode=instructor.Mode.JSON,
|
||||
)
|
||||
|
||||
def generate(self):
|
||||
"""
|
||||
Generates a team structure for the specified topic.
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
str: The full path of the YAML file containing the generated team structure.
|
||||
|
||||
Raises:
|
||||
Exception: If the generation process fails.
|
||||
|
||||
Usage:
|
||||
generator = AutoGenerator(framework="crewai", topic="Create a movie script about Cat in Mars")
|
||||
path = generator.generate()
|
||||
print(path)
|
||||
"""
|
||||
response = self.client.chat.completions.create(
|
||||
model=self.config_list[0]['model'],
|
||||
response_model=TeamStructure,
|
||||
max_retries=10,
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a helpful assistant designed to output complex team structures."},
|
||||
{"role": "user", "content": self.get_user_content()}
|
||||
]
|
||||
)
|
||||
json_data = json.loads(response.model_dump_json())
|
||||
self.convert_and_save(json_data)
|
||||
full_path = os.path.abspath(self.agent_file)
|
||||
return full_path
|
||||
|
||||
def convert_and_save(self, json_data):
|
||||
"""Converts the provided JSON data into the desired YAML format and saves it to a file.
|
||||
|
||||
Args:
|
||||
json_data (dict): The JSON data representing the team structure.
|
||||
topic (str, optional): The topic to be inserted into the YAML. Defaults to "Artificial Intelligence".
|
||||
agent_file (str, optional): The name of the YAML file to save. Defaults to "test.yaml".
|
||||
"""
|
||||
|
||||
yaml_data = {
|
||||
"framework": self.framework,
|
||||
"topic": self.topic,
|
||||
"roles": {},
|
||||
"dependencies": []
|
||||
}
|
||||
|
||||
for role_id, role_details in json_data['roles'].items():
|
||||
yaml_data['roles'][role_id] = {
|
||||
"backstory": "" + role_details['backstory'],
|
||||
"goal": role_details['goal'],
|
||||
"role": role_details['role'],
|
||||
"tasks": {},
|
||||
# "tools": role_details.get('tools', []),
|
||||
"tools": ['']
|
||||
}
|
||||
|
||||
for task_id, task_details in role_details['tasks'].items():
|
||||
yaml_data['roles'][role_id]['tasks'][task_id] = {
|
||||
"description": "" + task_details['description'],
|
||||
"expected_output": "" + task_details['expected_output']
|
||||
}
|
||||
|
||||
# Save to YAML file, maintaining the order
|
||||
with open(self.agent_file, 'w') as f:
|
||||
yaml.dump(yaml_data, f, allow_unicode=True, sort_keys=False)
|
||||
|
||||
def get_user_content(self):
|
||||
"""
|
||||
Generates a prompt for the OpenAI API to generate a team structure.
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
str: The prompt for the OpenAI API.
|
||||
|
||||
Usage:
|
||||
generator = AutoGenerator(framework="crewai", topic="Create a movie script about Cat in Mars")
|
||||
prompt = generator.get_user_content()
|
||||
print(prompt)
|
||||
"""
|
||||
user_content = """Generate a team structure for \"""" + self.topic + """\" task.
|
||||
No Input data will be provided to the team.
|
||||
The team will work in sequence. First role will pass the output to the next role, and so on.
|
||||
The last role will generate the final output.
|
||||
Think step by step.
|
||||
With maximum 3 roles, each with 1 task. Include role goals, backstories, task descriptions, and expected outputs.
|
||||
List of Available Tools: CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool, FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool, ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool, YoutubeChannelSearchTool, YoutubeVideoSearchTool.
|
||||
Only use Available Tools. Do Not use any other tools.
|
||||
Example Below:
|
||||
Use below example to understand the structure of the output.
|
||||
The final role you create should satisfy the provided task: """ + self.topic + """.
|
||||
{
|
||||
"roles": {
|
||||
"narrative_designer": {
|
||||
"role": "Narrative Designer",
|
||||
"goal": "Create AI storylines",
|
||||
"backstory": "Skilled in narrative development for AI, with a focus on story resonance.",
|
||||
"tools": ["ScrapeWebsiteTool"],
|
||||
"tasks": {
|
||||
"story_concept_development": {
|
||||
"description": "Craft a unique AI story concept with depth and engagement using concept from this page the content https://www.asthebirdfliesblog.com/posts/how-to-write-book-story-development .",
|
||||
"expected_output": "Document with narrative arcs, character bios, and settings."
|
||||
}
|
||||
}
|
||||
},
|
||||
"scriptwriter": {
|
||||
"role": "Scriptwriter",
|
||||
"goal": "Write scripts from AI concepts",
|
||||
"backstory": "Expert in dialogue and script structure, translating concepts into scripts.",
|
||||
"tasks": {
|
||||
"scriptwriting_task": {
|
||||
"description": "Turn narrative concepts into scripts, including dialogue and scenes.",
|
||||
"expected_output": "Production-ready script with dialogue and scene details."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
return user_content</code></pre>
|
||||
</details>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.auto.AutoGenerator.convert_and_save"><code class="name flex">
|
||||
<span>def <span class="ident">convert_and_save</span></span>(<span>self, json_data)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Converts the provided JSON data into the desired YAML format and saves it to a file.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>json_data</code></strong> : <code>dict</code></dt>
|
||||
<dd>The JSON data representing the team structure.</dd>
|
||||
<dt><strong><code>topic</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The topic to be inserted into the YAML. Defaults to "Artificial Intelligence".</dd>
|
||||
<dt><strong><code>agent_file</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The name of the YAML file to save. Defaults to "test.yaml".</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.AutoGenerator.generate"><code class="name flex">
|
||||
<span>def <span class="ident">generate</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Generates a team structure for the specified topic.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<p>None</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>str</code></dt>
|
||||
<dd>The full path of the YAML file containing the generated team structure.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>Exception</code></dt>
|
||||
<dd>If the generation process fails.</dd>
|
||||
</dl>
|
||||
<h2 id="usage">Usage</h2>
|
||||
<p>generator = AutoGenerator(framework="crewai", topic="Create a movie script about Cat in Mars")
|
||||
path = generator.generate()
|
||||
print(path)</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.AutoGenerator.get_user_content"><code class="name flex">
|
||||
<span>def <span class="ident">get_user_content</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Generates a prompt for the OpenAI API to generate a team structure.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<p>None</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>str</code></dt>
|
||||
<dd>The prompt for the OpenAI API.</dd>
|
||||
</dl>
|
||||
<h2 id="usage">Usage</h2>
|
||||
<p>generator = AutoGenerator(framework="crewai", topic="Create a movie script about Cat in Mars")
|
||||
prompt = generator.get_user_content()
|
||||
print(prompt)</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails"><code class="flex name class">
|
||||
<span>class <span class="ident">RoleDetails</span></span>
|
||||
<span>(</span><span>**data: Any)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Usage docs: <a href="https://docs.pydantic.dev/2.9/concepts/models/">https://docs.pydantic.dev/2.9/concepts/models/</a></p>
|
||||
<p>A base class for creating Pydantic models.</p>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<dl>
|
||||
<dt><strong><code>__class_vars__</code></strong></dt>
|
||||
<dd>The names of the class variables defined on the model.</dd>
|
||||
<dt><strong><code>__private_attributes__</code></strong></dt>
|
||||
<dd>Metadata about the private attributes of the model.</dd>
|
||||
<dt><strong><code>__signature__</code></strong></dt>
|
||||
<dd>The synthesized <code>__init__</code> [<code>Signature</code>][inspect.Signature] of the model.</dd>
|
||||
<dt><strong><code>__pydantic_complete__</code></strong></dt>
|
||||
<dd>Whether model building is completed, or if there are still undefined fields.</dd>
|
||||
<dt><strong><code>__pydantic_core_schema__</code></strong></dt>
|
||||
<dd>The core schema of the model.</dd>
|
||||
<dt><strong><code>__pydantic_custom_init__</code></strong></dt>
|
||||
<dd>Whether the model has a custom <code>__init__</code> function.</dd>
|
||||
<dt><strong><code>__pydantic_decorators__</code></strong></dt>
|
||||
<dd>Metadata containing the decorators defined on the model.
|
||||
This replaces <code>Model.__validators__</code> and <code>Model.__root_validators__</code> from Pydantic V1.</dd>
|
||||
<dt><strong><code>__pydantic_generic_metadata__</code></strong></dt>
|
||||
<dd>Metadata for generic models; contains data used for a similar purpose to
|
||||
<strong>args</strong>, <strong>origin</strong>, <strong>parameters</strong> in typing-module generics. May eventually be replaced by these.</dd>
|
||||
<dt><strong><code>__pydantic_parent_namespace__</code></strong></dt>
|
||||
<dd>Parent namespace of the model, used for automatic rebuilding of models.</dd>
|
||||
<dt><strong><code>__pydantic_post_init__</code></strong></dt>
|
||||
<dd>The name of the post-init method for the model, if defined.</dd>
|
||||
<dt><strong><code>__pydantic_root_model__</code></strong></dt>
|
||||
<dd>Whether the model is a [<code>RootModel</code>][pydantic.root_model.RootModel].</dd>
|
||||
<dt><strong><code>__pydantic_serializer__</code></strong></dt>
|
||||
<dd>The <code>pydantic-core</code> <code>SchemaSerializer</code> used to dump instances of the model.</dd>
|
||||
<dt><strong><code>__pydantic_validator__</code></strong></dt>
|
||||
<dd>The <code>pydantic-core</code> <code>SchemaValidator</code> used to validate instances of the model.</dd>
|
||||
<dt><strong><code>__pydantic_extra__</code></strong></dt>
|
||||
<dd>A dictionary containing extra values, if [<code>extra</code>][pydantic.config.ConfigDict.extra]
|
||||
is set to <code>'allow'</code>.</dd>
|
||||
<dt><strong><code>__pydantic_fields_set__</code></strong></dt>
|
||||
<dd>The names of fields explicitly set during instantiation.</dd>
|
||||
<dt><strong><code>__pydantic_private__</code></strong></dt>
|
||||
<dd>Values of private attributes set on the model instance.</dd>
|
||||
</dl>
|
||||
<p>Create a new model by parsing and validating input data from keyword arguments.</p>
|
||||
<p>Raises [<code>ValidationError</code>][pydantic_core.ValidationError] if the input data cannot be
|
||||
validated to form a valid model.</p>
|
||||
<p><code>self</code> is explicitly positional-only to allow <code>self</code> as a field name.</p></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class RoleDetails(BaseModel):
|
||||
role: str
|
||||
goal: str
|
||||
backstory: str
|
||||
tasks: Dict[str, TaskDetails]
|
||||
tools: List[str]</code></pre>
|
||||
</details>
|
||||
<h3>Ancestors</h3>
|
||||
<ul class="hlist">
|
||||
<li>pydantic.main.BaseModel</li>
|
||||
</ul>
|
||||
<h3>Class variables</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.auto.RoleDetails.backstory"><code class="name">var <span class="ident">backstory</span> : str</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.goal"><code class="name">var <span class="ident">goal</span> : str</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.model_computed_fields"><code class="name">var <span class="ident">model_computed_fields</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.model_config"><code class="name">var <span class="ident">model_config</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.model_fields"><code class="name">var <span class="ident">model_fields</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.role"><code class="name">var <span class="ident">role</span> : str</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.tasks"><code class="name">var <span class="ident">tasks</span> : Dict[str, <a title="praisonai.auto.TaskDetails" href="#praisonai.auto.TaskDetails">TaskDetails</a>]</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.RoleDetails.tools"><code class="name">var <span class="ident">tools</span> : List[str]</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TaskDetails"><code class="flex name class">
|
||||
<span>class <span class="ident">TaskDetails</span></span>
|
||||
<span>(</span><span>**data: Any)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Usage docs: <a href="https://docs.pydantic.dev/2.9/concepts/models/">https://docs.pydantic.dev/2.9/concepts/models/</a></p>
|
||||
<p>A base class for creating Pydantic models.</p>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<dl>
|
||||
<dt><strong><code>__class_vars__</code></strong></dt>
|
||||
<dd>The names of the class variables defined on the model.</dd>
|
||||
<dt><strong><code>__private_attributes__</code></strong></dt>
|
||||
<dd>Metadata about the private attributes of the model.</dd>
|
||||
<dt><strong><code>__signature__</code></strong></dt>
|
||||
<dd>The synthesized <code>__init__</code> [<code>Signature</code>][inspect.Signature] of the model.</dd>
|
||||
<dt><strong><code>__pydantic_complete__</code></strong></dt>
|
||||
<dd>Whether model building is completed, or if there are still undefined fields.</dd>
|
||||
<dt><strong><code>__pydantic_core_schema__</code></strong></dt>
|
||||
<dd>The core schema of the model.</dd>
|
||||
<dt><strong><code>__pydantic_custom_init__</code></strong></dt>
|
||||
<dd>Whether the model has a custom <code>__init__</code> function.</dd>
|
||||
<dt><strong><code>__pydantic_decorators__</code></strong></dt>
|
||||
<dd>Metadata containing the decorators defined on the model.
|
||||
This replaces <code>Model.__validators__</code> and <code>Model.__root_validators__</code> from Pydantic V1.</dd>
|
||||
<dt><strong><code>__pydantic_generic_metadata__</code></strong></dt>
|
||||
<dd>Metadata for generic models; contains data used for a similar purpose to
|
||||
<strong>args</strong>, <strong>origin</strong>, <strong>parameters</strong> in typing-module generics. May eventually be replaced by these.</dd>
|
||||
<dt><strong><code>__pydantic_parent_namespace__</code></strong></dt>
|
||||
<dd>Parent namespace of the model, used for automatic rebuilding of models.</dd>
|
||||
<dt><strong><code>__pydantic_post_init__</code></strong></dt>
|
||||
<dd>The name of the post-init method for the model, if defined.</dd>
|
||||
<dt><strong><code>__pydantic_root_model__</code></strong></dt>
|
||||
<dd>Whether the model is a [<code>RootModel</code>][pydantic.root_model.RootModel].</dd>
|
||||
<dt><strong><code>__pydantic_serializer__</code></strong></dt>
|
||||
<dd>The <code>pydantic-core</code> <code>SchemaSerializer</code> used to dump instances of the model.</dd>
|
||||
<dt><strong><code>__pydantic_validator__</code></strong></dt>
|
||||
<dd>The <code>pydantic-core</code> <code>SchemaValidator</code> used to validate instances of the model.</dd>
|
||||
<dt><strong><code>__pydantic_extra__</code></strong></dt>
|
||||
<dd>A dictionary containing extra values, if [<code>extra</code>][pydantic.config.ConfigDict.extra]
|
||||
is set to <code>'allow'</code>.</dd>
|
||||
<dt><strong><code>__pydantic_fields_set__</code></strong></dt>
|
||||
<dd>The names of fields explicitly set during instantiation.</dd>
|
||||
<dt><strong><code>__pydantic_private__</code></strong></dt>
|
||||
<dd>Values of private attributes set on the model instance.</dd>
|
||||
</dl>
|
||||
<p>Create a new model by parsing and validating input data from keyword arguments.</p>
|
||||
<p>Raises [<code>ValidationError</code>][pydantic_core.ValidationError] if the input data cannot be
|
||||
validated to form a valid model.</p>
|
||||
<p><code>self</code> is explicitly positional-only to allow <code>self</code> as a field name.</p></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class TaskDetails(BaseModel):
|
||||
description: str
|
||||
expected_output: str</code></pre>
|
||||
</details>
|
||||
<h3>Ancestors</h3>
|
||||
<ul class="hlist">
|
||||
<li>pydantic.main.BaseModel</li>
|
||||
</ul>
|
||||
<h3>Class variables</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.auto.TaskDetails.description"><code class="name">var <span class="ident">description</span> : str</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TaskDetails.expected_output"><code class="name">var <span class="ident">expected_output</span> : str</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TaskDetails.model_computed_fields"><code class="name">var <span class="ident">model_computed_fields</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TaskDetails.model_config"><code class="name">var <span class="ident">model_config</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TaskDetails.model_fields"><code class="name">var <span class="ident">model_fields</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TeamStructure"><code class="flex name class">
|
||||
<span>class <span class="ident">TeamStructure</span></span>
|
||||
<span>(</span><span>**data: Any)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Usage docs: <a href="https://docs.pydantic.dev/2.9/concepts/models/">https://docs.pydantic.dev/2.9/concepts/models/</a></p>
|
||||
<p>A base class for creating Pydantic models.</p>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<dl>
|
||||
<dt><strong><code>__class_vars__</code></strong></dt>
|
||||
<dd>The names of the class variables defined on the model.</dd>
|
||||
<dt><strong><code>__private_attributes__</code></strong></dt>
|
||||
<dd>Metadata about the private attributes of the model.</dd>
|
||||
<dt><strong><code>__signature__</code></strong></dt>
|
||||
<dd>The synthesized <code>__init__</code> [<code>Signature</code>][inspect.Signature] of the model.</dd>
|
||||
<dt><strong><code>__pydantic_complete__</code></strong></dt>
|
||||
<dd>Whether model building is completed, or if there are still undefined fields.</dd>
|
||||
<dt><strong><code>__pydantic_core_schema__</code></strong></dt>
|
||||
<dd>The core schema of the model.</dd>
|
||||
<dt><strong><code>__pydantic_custom_init__</code></strong></dt>
|
||||
<dd>Whether the model has a custom <code>__init__</code> function.</dd>
|
||||
<dt><strong><code>__pydantic_decorators__</code></strong></dt>
|
||||
<dd>Metadata containing the decorators defined on the model.
|
||||
This replaces <code>Model.__validators__</code> and <code>Model.__root_validators__</code> from Pydantic V1.</dd>
|
||||
<dt><strong><code>__pydantic_generic_metadata__</code></strong></dt>
|
||||
<dd>Metadata for generic models; contains data used for a similar purpose to
|
||||
<strong>args</strong>, <strong>origin</strong>, <strong>parameters</strong> in typing-module generics. May eventually be replaced by these.</dd>
|
||||
<dt><strong><code>__pydantic_parent_namespace__</code></strong></dt>
|
||||
<dd>Parent namespace of the model, used for automatic rebuilding of models.</dd>
|
||||
<dt><strong><code>__pydantic_post_init__</code></strong></dt>
|
||||
<dd>The name of the post-init method for the model, if defined.</dd>
|
||||
<dt><strong><code>__pydantic_root_model__</code></strong></dt>
|
||||
<dd>Whether the model is a [<code>RootModel</code>][pydantic.root_model.RootModel].</dd>
|
||||
<dt><strong><code>__pydantic_serializer__</code></strong></dt>
|
||||
<dd>The <code>pydantic-core</code> <code>SchemaSerializer</code> used to dump instances of the model.</dd>
|
||||
<dt><strong><code>__pydantic_validator__</code></strong></dt>
|
||||
<dd>The <code>pydantic-core</code> <code>SchemaValidator</code> used to validate instances of the model.</dd>
|
||||
<dt><strong><code>__pydantic_extra__</code></strong></dt>
|
||||
<dd>A dictionary containing extra values, if [<code>extra</code>][pydantic.config.ConfigDict.extra]
|
||||
is set to <code>'allow'</code>.</dd>
|
||||
<dt><strong><code>__pydantic_fields_set__</code></strong></dt>
|
||||
<dd>The names of fields explicitly set during instantiation.</dd>
|
||||
<dt><strong><code>__pydantic_private__</code></strong></dt>
|
||||
<dd>Values of private attributes set on the model instance.</dd>
|
||||
</dl>
|
||||
<p>Create a new model by parsing and validating input data from keyword arguments.</p>
|
||||
<p>Raises [<code>ValidationError</code>][pydantic_core.ValidationError] if the input data cannot be
|
||||
validated to form a valid model.</p>
|
||||
<p><code>self</code> is explicitly positional-only to allow <code>self</code> as a field name.</p></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class TeamStructure(BaseModel):
|
||||
roles: Dict[str, RoleDetails]</code></pre>
|
||||
</details>
|
||||
<h3>Ancestors</h3>
|
||||
<ul class="hlist">
|
||||
<li>pydantic.main.BaseModel</li>
|
||||
</ul>
|
||||
<h3>Class variables</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.auto.TeamStructure.model_computed_fields"><code class="name">var <span class="ident">model_computed_fields</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TeamStructure.model_config"><code class="name">var <span class="ident">model_config</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TeamStructure.model_fields"><code class="name">var <span class="ident">model_fields</span></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.auto.TeamStructure.roles"><code class="name">var <span class="ident">roles</span> : Dict[str, <a title="praisonai.auto.RoleDetails" href="#praisonai.auto.RoleDetails">RoleDetails</a>]</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.auto.AutoGenerator" href="#praisonai.auto.AutoGenerator">AutoGenerator</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.auto.AutoGenerator.convert_and_save" href="#praisonai.auto.AutoGenerator.convert_and_save">convert_and_save</a></code></li>
|
||||
<li><code><a title="praisonai.auto.AutoGenerator.generate" href="#praisonai.auto.AutoGenerator.generate">generate</a></code></li>
|
||||
<li><code><a title="praisonai.auto.AutoGenerator.get_user_content" href="#praisonai.auto.AutoGenerator.get_user_content">get_user_content</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.auto.RoleDetails" href="#praisonai.auto.RoleDetails">RoleDetails</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.auto.RoleDetails.backstory" href="#praisonai.auto.RoleDetails.backstory">backstory</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.goal" href="#praisonai.auto.RoleDetails.goal">goal</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.model_computed_fields" href="#praisonai.auto.RoleDetails.model_computed_fields">model_computed_fields</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.model_config" href="#praisonai.auto.RoleDetails.model_config">model_config</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.model_fields" href="#praisonai.auto.RoleDetails.model_fields">model_fields</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.role" href="#praisonai.auto.RoleDetails.role">role</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.tasks" href="#praisonai.auto.RoleDetails.tasks">tasks</a></code></li>
|
||||
<li><code><a title="praisonai.auto.RoleDetails.tools" href="#praisonai.auto.RoleDetails.tools">tools</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.auto.TaskDetails" href="#praisonai.auto.TaskDetails">TaskDetails</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.auto.TaskDetails.description" href="#praisonai.auto.TaskDetails.description">description</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TaskDetails.expected_output" href="#praisonai.auto.TaskDetails.expected_output">expected_output</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TaskDetails.model_computed_fields" href="#praisonai.auto.TaskDetails.model_computed_fields">model_computed_fields</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TaskDetails.model_config" href="#praisonai.auto.TaskDetails.model_config">model_config</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TaskDetails.model_fields" href="#praisonai.auto.TaskDetails.model_fields">model_fields</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.auto.TeamStructure" href="#praisonai.auto.TeamStructure">TeamStructure</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.auto.TeamStructure.model_computed_fields" href="#praisonai.auto.TeamStructure.model_computed_fields">model_computed_fields</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TeamStructure.model_config" href="#praisonai.auto.TeamStructure.model_config">model_config</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TeamStructure.model_fields" href="#praisonai.auto.TeamStructure.model_fields">model_fields</a></code></li>
|
||||
<li><code><a title="praisonai.auto.TeamStructure.roles" href="#praisonai.auto.TeamStructure.roles">roles</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,664 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.cli API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.cli</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.cli.stream_subprocess"><code class="name flex">
|
||||
<span>def <span class="ident">stream_subprocess</span></span>(<span>command, env=None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Execute a subprocess command and stream the output to the terminal in real-time.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>command</code></strong> : <code>list</code></dt>
|
||||
<dd>A list containing the command and its arguments.</dd>
|
||||
<dt><strong><code>env</code></strong> : <code>dict</code>, optional</dt>
|
||||
<dd>Environment variables for the subprocess.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.cli.PraisonAI"><code class="flex name class">
|
||||
<span>class <span class="ident">PraisonAI</span></span>
|
||||
<span>(</span><span>agent_file='agents.yaml', framework='', auto=False, init=False, agent_yaml=None, tools=None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Initialize the PraisonAI object with default parameters.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>agent_file (str): The default agent file to use. Defaults to "agents.yaml".
|
||||
framework (str): The default framework to use. Defaults to "crewai".
|
||||
auto (bool): A flag indicating whether to enable auto mode. Defaults to False.
|
||||
init (bool): A flag indicating whether to enable initialization mode. Defaults to False.</p>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<dl>
|
||||
<dt><strong><code>config_list</code></strong> : <code>list</code></dt>
|
||||
<dd>A list of configuration dictionaries for the OpenAI API.</dd>
|
||||
<dt><strong><code>agent_file</code></strong> : <code>str</code></dt>
|
||||
<dd>The agent file to use.</dd>
|
||||
<dt><strong><code>framework</code></strong> : <code>str</code></dt>
|
||||
<dd>The framework to use.</dd>
|
||||
<dt><strong><code>auto</code></strong> : <code>bool</code></dt>
|
||||
<dd>A flag indicating whether to enable auto mode.</dd>
|
||||
<dt><strong><code>init</code></strong> : <code>bool</code></dt>
|
||||
<dd>A flag indicating whether to enable initialization mode.</dd>
|
||||
<dt><strong><code>agent_yaml</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The content of the YAML file. Defaults to None.</dd>
|
||||
</dl></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class PraisonAI:
|
||||
def __init__(self, agent_file="agents.yaml", framework="", auto=False, init=False, agent_yaml=None, tools=None):
|
||||
"""
|
||||
Initialize the PraisonAI object with default parameters.
|
||||
|
||||
Parameters:
|
||||
agent_file (str): The default agent file to use. Defaults to "agents.yaml".
|
||||
framework (str): The default framework to use. Defaults to "crewai".
|
||||
auto (bool): A flag indicating whether to enable auto mode. Defaults to False.
|
||||
init (bool): A flag indicating whether to enable initialization mode. Defaults to False.
|
||||
|
||||
Attributes:
|
||||
config_list (list): A list of configuration dictionaries for the OpenAI API.
|
||||
agent_file (str): The agent file to use.
|
||||
framework (str): The framework to use.
|
||||
auto (bool): A flag indicating whether to enable auto mode.
|
||||
init (bool): A flag indicating whether to enable initialization mode.
|
||||
agent_yaml (str, optional): The content of the YAML file. Defaults to None.
|
||||
"""
|
||||
self.agent_yaml = agent_yaml
|
||||
self.config_list = [
|
||||
{
|
||||
'model': os.environ.get("OPENAI_MODEL_NAME", "gpt-4o"),
|
||||
'base_url': os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
|
||||
'api_key': os.environ.get("OPENAI_API_KEY")
|
||||
}
|
||||
]
|
||||
self.agent_file = agent_file
|
||||
self.framework = framework
|
||||
self.auto = auto
|
||||
self.init = init
|
||||
self.tools = tools or [] # Store tool class names as a list
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Run the PraisonAI application.
|
||||
"""
|
||||
self.main()
|
||||
|
||||
def main(self):
|
||||
"""
|
||||
The main function of the PraisonAI object. It parses the command-line arguments,
|
||||
initializes the necessary attributes, and then calls the appropriate methods based on the
|
||||
provided arguments.
|
||||
|
||||
Args:
|
||||
self (PraisonAI): An instance of the PraisonAI class.
|
||||
|
||||
Returns:
|
||||
Any: Depending on the arguments provided, the function may return a result from the
|
||||
AgentsGenerator, a deployment result from the CloudDeployer, or a message indicating
|
||||
the successful creation of a file.
|
||||
"""
|
||||
args = self.parse_args()
|
||||
if args is None:
|
||||
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
|
||||
result = agents_generator.generate_crew_and_kickoff()
|
||||
return result
|
||||
if args.deploy:
|
||||
from .deploy import CloudDeployer
|
||||
deployer = CloudDeployer()
|
||||
deployer.run_commands()
|
||||
return
|
||||
|
||||
if getattr(args, 'chat', False):
|
||||
self.create_chainlit_chat_interface()
|
||||
return
|
||||
|
||||
if getattr(args, 'code', False):
|
||||
self.create_code_interface()
|
||||
return
|
||||
|
||||
if getattr(args, 'realtime', False):
|
||||
self.create_realtime_interface()
|
||||
return
|
||||
|
||||
if getattr(args, 'call', False):
|
||||
call_args = []
|
||||
if args.public:
|
||||
call_args.append('--public')
|
||||
call_module.main(call_args)
|
||||
return
|
||||
|
||||
if args.agent_file == 'train':
|
||||
package_root = os.path.dirname(os.path.abspath(__file__))
|
||||
config_yaml_destination = os.path.join(os.getcwd(), 'config.yaml')
|
||||
|
||||
# Create config.yaml only if it doesn't exist or --model or --dataset is provided
|
||||
if not os.path.exists(config_yaml_destination) or args.model or args.dataset:
|
||||
config = generate_config(
|
||||
model_name=args.model,
|
||||
hf_model_name=args.hf,
|
||||
ollama_model_name=args.ollama,
|
||||
dataset=[{
|
||||
"name": args.dataset
|
||||
}]
|
||||
)
|
||||
with open('config.yaml', 'w') as f:
|
||||
yaml.dump(config, f, default_flow_style=False, indent=2)
|
||||
|
||||
# Overwrite huggingface_save and ollama_save if --hf or --ollama are provided
|
||||
if args.hf:
|
||||
config["huggingface_save"] = "true"
|
||||
if args.ollama:
|
||||
config["ollama_save"] = "true"
|
||||
|
||||
if 'init' in sys.argv:
|
||||
from praisonai.setup.setup_conda_env import main as setup_conda_main
|
||||
setup_conda_main()
|
||||
print("All packages installed")
|
||||
return
|
||||
|
||||
try:
|
||||
result = subprocess.check_output(['conda', 'env', 'list'])
|
||||
if 'praison_env' in result.decode('utf-8'):
|
||||
print("Conda environment 'praison_env' found.")
|
||||
else:
|
||||
raise subprocess.CalledProcessError(1, 'grep')
|
||||
except subprocess.CalledProcessError:
|
||||
print("Conda environment 'praison_env' not found. Setting it up...")
|
||||
from praisonai.setup.setup_conda_env import main as setup_conda_main
|
||||
setup_conda_main()
|
||||
print("All packages installed.")
|
||||
|
||||
train_args = sys.argv[2:] # Get all arguments after 'train'
|
||||
train_script_path = os.path.join(package_root, 'train.py')
|
||||
|
||||
# Set environment variables
|
||||
env = os.environ.copy()
|
||||
env['PYTHONUNBUFFERED'] = '1'
|
||||
|
||||
stream_subprocess(['conda', 'run', '--no-capture-output', '--name', 'praison_env', 'python', '-u', train_script_path, 'train'], env=env)
|
||||
return
|
||||
|
||||
invocation_cmd = "praisonai"
|
||||
version_string = f"PraisonAI version {__version__}"
|
||||
|
||||
self.framework = args.framework or self.framework
|
||||
|
||||
if args.agent_file:
|
||||
if args.agent_file.startswith("tests.test"): # Argument used for testing purposes. eg: python -m unittest tests.test
|
||||
print("test")
|
||||
else:
|
||||
self.agent_file = args.agent_file
|
||||
|
||||
|
||||
if args.auto or args.init:
|
||||
temp_topic = ' '.join(args.auto) if args.auto else ' '.join(args.init)
|
||||
self.topic = temp_topic
|
||||
elif self.auto or self.init: # Use the auto attribute if args.auto is not provided
|
||||
self.topic = self.auto
|
||||
|
||||
if args.auto or self.auto:
|
||||
self.agent_file = "test.yaml"
|
||||
generator = AutoGenerator(topic=self.topic , framework=self.framework, agent_file=self.agent_file)
|
||||
self.agent_file = generator.generate()
|
||||
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
|
||||
result = agents_generator.generate_crew_and_kickoff()
|
||||
return result
|
||||
elif args.init or self.init:
|
||||
self.agent_file = "agents.yaml"
|
||||
generator = AutoGenerator(topic=self.topic , framework=self.framework, agent_file=self.agent_file)
|
||||
self.agent_file = generator.generate()
|
||||
print("File {} created successfully".format(self.agent_file))
|
||||
return "File {} created successfully".format(self.agent_file)
|
||||
|
||||
if args.ui:
|
||||
if args.ui == "gradio":
|
||||
self.create_gradio_interface()
|
||||
elif args.ui == "chainlit":
|
||||
self.create_chainlit_interface()
|
||||
else:
|
||||
# Modify below code to allow default ui
|
||||
agents_generator = AgentsGenerator(
|
||||
self.agent_file,
|
||||
self.framework,
|
||||
self.config_list,
|
||||
agent_yaml=self.agent_yaml,
|
||||
tools=self.tools # Pass tools to AgentsGenerator
|
||||
)
|
||||
result = agents_generator.generate_crew_and_kickoff()
|
||||
return result
|
||||
else:
|
||||
agents_generator = AgentsGenerator(
|
||||
self.agent_file,
|
||||
self.framework,
|
||||
self.config_list,
|
||||
agent_yaml=self.agent_yaml,
|
||||
tools=self.tools # Pass tools to AgentsGenerator
|
||||
)
|
||||
result = agents_generator.generate_crew_and_kickoff()
|
||||
return result
|
||||
|
||||
def parse_args(self):
|
||||
"""
|
||||
Parse the command-line arguments for the PraisonAI CLI.
|
||||
|
||||
Args:
|
||||
self (PraisonAI): An instance of the PraisonAI class.
|
||||
|
||||
Returns:
|
||||
argparse.Namespace: An object containing the parsed command-line arguments.
|
||||
|
||||
Raises:
|
||||
argparse.ArgumentError: If the arguments provided are invalid.
|
||||
|
||||
Example:
|
||||
>>> args = praison_ai.parse_args()
|
||||
>>> print(args.agent_file) # Output: 'agents.yaml'
|
||||
"""
|
||||
parser = argparse.ArgumentParser(prog="praisonai", description="praisonAI command-line interface")
|
||||
parser.add_argument("--framework", choices=["crewai", "autogen"], help="Specify the framework")
|
||||
parser.add_argument("--ui", choices=["chainlit", "gradio"], help="Specify the UI framework (gradio or chainlit).")
|
||||
parser.add_argument("--auto", nargs=argparse.REMAINDER, help="Enable auto mode and pass arguments for it")
|
||||
parser.add_argument("--init", nargs=argparse.REMAINDER, help="Enable auto mode and pass arguments for it")
|
||||
parser.add_argument("agent_file", nargs="?", help="Specify the agent file")
|
||||
parser.add_argument("--deploy", action="store_true", help="Deploy the application")
|
||||
parser.add_argument("--model", type=str, help="Model name")
|
||||
parser.add_argument("--hf", type=str, help="Hugging Face model name")
|
||||
parser.add_argument("--ollama", type=str, help="Ollama model name")
|
||||
parser.add_argument("--dataset", type=str, help="Dataset name for training", default="yahma/alpaca-cleaned")
|
||||
parser.add_argument("--realtime", action="store_true", help="Start the realtime voice interaction interface")
|
||||
parser.add_argument("--call", action="store_true", help="Start the PraisonAI Call server")
|
||||
parser.add_argument("--public", action="store_true", help="Use ngrok to expose the server publicly (only with --call)")
|
||||
args, unknown_args = parser.parse_known_args()
|
||||
|
||||
if unknown_args and unknown_args[0] == '-b' and unknown_args[1] == 'api:app':
|
||||
args.agent_file = 'agents.yaml'
|
||||
if args.agent_file == 'api:app' or args.agent_file == '/app/api:app':
|
||||
args.agent_file = 'agents.yaml'
|
||||
if args.agent_file == 'ui':
|
||||
args.ui = 'chainlit'
|
||||
if args.agent_file == 'chat':
|
||||
args.ui = 'chainlit'
|
||||
args.chat = True
|
||||
if args.agent_file == 'code':
|
||||
args.ui = 'chainlit'
|
||||
args.code = True
|
||||
if args.agent_file == 'realtime':
|
||||
args.realtime = True
|
||||
if args.agent_file == 'call':
|
||||
args.call = True
|
||||
|
||||
return args
|
||||
|
||||
def create_chainlit_chat_interface(self):
|
||||
"""
|
||||
Create a Chainlit interface for the chat application.
|
||||
|
||||
This function sets up a Chainlit application that listens for messages.
|
||||
When a message is received, it runs PraisonAI with the provided message as the topic.
|
||||
The generated agents are then used to perform tasks.
|
||||
|
||||
Returns:
|
||||
None: This function does not return any value. It starts the Chainlit application.
|
||||
"""
|
||||
if CHAINLIT_AVAILABLE:
|
||||
import praisonai
|
||||
os.environ["CHAINLIT_PORT"] = "8084"
|
||||
root_path = os.path.join(os.path.expanduser("~"), ".praison")
|
||||
os.environ["CHAINLIT_APP_ROOT"] = root_path
|
||||
public_folder = os.path.join(os.path.dirname(praisonai.__file__), 'public')
|
||||
if not os.path.exists(os.path.join(root_path, "public")): # Check if the folder exists in the current directory
|
||||
if os.path.exists(public_folder):
|
||||
shutil.copytree(public_folder, os.path.join(root_path, "public"), dirs_exist_ok=True)
|
||||
logging.info("Public folder copied successfully!")
|
||||
else:
|
||||
logging.info("Public folder not found in the package.")
|
||||
else:
|
||||
logging.info("Public folder already exists.")
|
||||
chat_ui_path = os.path.join(os.path.dirname(praisonai.__file__), 'ui', 'chat.py')
|
||||
chainlit_run([chat_ui_path])
|
||||
else:
|
||||
print("ERROR: Chat UI is not installed. Please install it with 'pip install \"praisonai\[chat]\"' to use the chat UI.")
|
||||
|
||||
def create_code_interface(self):
|
||||
"""
|
||||
Create a Chainlit interface for the code application.
|
||||
|
||||
This function sets up a Chainlit application that listens for messages.
|
||||
When a message is received, it runs PraisonAI with the provided message as the topic.
|
||||
The generated agents are then used to perform tasks.
|
||||
|
||||
Returns:
|
||||
None: This function does not return any value. It starts the Chainlit application.
|
||||
"""
|
||||
if CHAINLIT_AVAILABLE:
|
||||
import praisonai
|
||||
os.environ["CHAINLIT_PORT"] = "8086"
|
||||
root_path = os.path.join(os.path.expanduser("~"), ".praison")
|
||||
os.environ["CHAINLIT_APP_ROOT"] = root_path
|
||||
public_folder = os.path.join(os.path.dirname(__file__), 'public')
|
||||
if not os.path.exists(os.path.join(root_path, "public")): # Check if the folder exists in the current directory
|
||||
if os.path.exists(public_folder):
|
||||
shutil.copytree(public_folder, os.path.join(root_path, "public"), dirs_exist_ok=True)
|
||||
logging.info("Public folder copied successfully!")
|
||||
else:
|
||||
logging.info("Public folder not found in the package.")
|
||||
else:
|
||||
logging.info("Public folder already exists.")
|
||||
code_ui_path = os.path.join(os.path.dirname(praisonai.__file__), 'ui', 'code.py')
|
||||
chainlit_run([code_ui_path])
|
||||
else:
|
||||
print("ERROR: Code UI is not installed. Please install it with 'pip install \"praisonai\[code]\"' to use the code UI.")
|
||||
|
||||
def create_gradio_interface(self):
|
||||
"""
|
||||
Create a Gradio interface for generating agents and performing tasks.
|
||||
|
||||
Args:
|
||||
self (PraisonAI): An instance of the PraisonAI class.
|
||||
|
||||
Returns:
|
||||
None: This method does not return any value. It launches the Gradio interface.
|
||||
|
||||
Raises:
|
||||
None: This method does not raise any exceptions.
|
||||
|
||||
Example:
|
||||
>>> praison_ai.create_gradio_interface()
|
||||
"""
|
||||
if GRADIO_AVAILABLE:
|
||||
def generate_crew_and_kickoff_interface(auto_args, framework):
|
||||
"""
|
||||
Generate a crew and kick off tasks based on the provided auto arguments and framework.
|
||||
|
||||
Args:
|
||||
auto_args (list): Topic.
|
||||
framework (str): The framework to use for generating agents.
|
||||
|
||||
Returns:
|
||||
str: A string representing the result of generating the crew and kicking off tasks.
|
||||
|
||||
Raises:
|
||||
None: This method does not raise any exceptions.
|
||||
|
||||
Example:
|
||||
>>> result = generate_crew_and_kickoff_interface("Create a movie about Cat in Mars", "crewai")
|
||||
>>> print(result)
|
||||
"""
|
||||
self.framework = framework
|
||||
self.agent_file = "test.yaml"
|
||||
generator = AutoGenerator(topic=auto_args , framework=self.framework)
|
||||
self.agent_file = generator.generate()
|
||||
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
|
||||
result = agents_generator.generate_crew_and_kickoff()
|
||||
return result
|
||||
|
||||
gr.Interface(
|
||||
fn=generate_crew_and_kickoff_interface,
|
||||
inputs=[gr.Textbox(lines=2, label="Auto Args"), gr.Dropdown(choices=["crewai", "autogen"], label="Framework")],
|
||||
outputs="textbox",
|
||||
title="Praison AI Studio",
|
||||
description="Create Agents and perform tasks",
|
||||
theme="default"
|
||||
).launch()
|
||||
else:
|
||||
print("ERROR: Gradio is not installed. Please install it with 'pip install gradio' to use this feature.")
|
||||
|
||||
def create_chainlit_interface(self):
|
||||
"""
|
||||
Create a Chainlit interface for generating agents and performing tasks.
|
||||
|
||||
This function sets up a Chainlit application that listens for messages.
|
||||
When a message is received, it runs PraisonAI with the provided message as the topic.
|
||||
The generated agents are then used to perform tasks.
|
||||
|
||||
Returns:
|
||||
None: This function does not return any value. It starts the Chainlit application.
|
||||
"""
|
||||
if CHAINLIT_AVAILABLE:
|
||||
import praisonai
|
||||
os.environ["CHAINLIT_PORT"] = "8082"
|
||||
# Get the path to the 'public' folder within the package
|
||||
public_folder = os.path.join(os.path.dirname(praisonai.__file__), 'public')
|
||||
if not os.path.exists("public"): # Check if the folder exists in the current directory
|
||||
if os.path.exists(public_folder):
|
||||
shutil.copytree(public_folder, 'public', dirs_exist_ok=True)
|
||||
logging.info("Public folder copied successfully!")
|
||||
else:
|
||||
logging.info("Public folder not found in the package.")
|
||||
else:
|
||||
logging.info("Public folder already exists.")
|
||||
chainlit_ui_path = os.path.join(os.path.dirname(praisonai.__file__), 'chainlit_ui.py')
|
||||
chainlit_run([chainlit_ui_path])
|
||||
else:
|
||||
print("ERROR: Chainlit is not installed. Please install it with 'pip install \"praisonai\[ui]\"' to use the UI.")
|
||||
|
||||
def create_realtime_interface(self):
|
||||
"""
|
||||
Create a Chainlit interface for the realtime voice interaction application.
|
||||
"""
|
||||
if CHAINLIT_AVAILABLE:
|
||||
import praisonai
|
||||
os.environ["CHAINLIT_PORT"] = "8088" # Ensure this port is not in use by another service
|
||||
root_path = os.path.join(os.path.expanduser("~"), ".praison")
|
||||
os.environ["CHAINLIT_APP_ROOT"] = root_path
|
||||
public_folder = os.path.join(os.path.dirname(praisonai.__file__), 'public')
|
||||
if not os.path.exists(os.path.join(root_path, "public")):
|
||||
if os.path.exists(public_folder):
|
||||
shutil.copytree(public_folder, os.path.join(root_path, "public"), dirs_exist_ok=True)
|
||||
logging.info("Public folder copied successfully!")
|
||||
else:
|
||||
logging.info("Public folder not found in the package.")
|
||||
else:
|
||||
logging.info("Public folder already exists.")
|
||||
realtime_ui_path = os.path.join(os.path.dirname(praisonai.__file__), 'ui', 'realtime.py')
|
||||
chainlit_run([realtime_ui_path])
|
||||
else:
|
||||
print("ERROR: Realtime UI is not installed. Please install it with 'pip install \"praisonai[realtime]\"' to use the realtime UI.")</code></pre>
|
||||
</details>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.cli.PraisonAI.create_chainlit_chat_interface"><code class="name flex">
|
||||
<span>def <span class="ident">create_chainlit_chat_interface</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Create a Chainlit interface for the chat application.</p>
|
||||
<p>This function sets up a Chainlit application that listens for messages.
|
||||
When a message is received, it runs PraisonAI with the provided message as the topic.
|
||||
The generated agents are then used to perform tasks.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>None</code></dt>
|
||||
<dd>This function does not return any value. It starts the Chainlit application.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.create_chainlit_interface"><code class="name flex">
|
||||
<span>def <span class="ident">create_chainlit_interface</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Create a Chainlit interface for generating agents and performing tasks.</p>
|
||||
<p>This function sets up a Chainlit application that listens for messages.
|
||||
When a message is received, it runs PraisonAI with the provided message as the topic.
|
||||
The generated agents are then used to perform tasks.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>None</code></dt>
|
||||
<dd>This function does not return any value. It starts the Chainlit application.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.create_code_interface"><code class="name flex">
|
||||
<span>def <span class="ident">create_code_interface</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Create a Chainlit interface for the code application.</p>
|
||||
<p>This function sets up a Chainlit application that listens for messages.
|
||||
When a message is received, it runs PraisonAI with the provided message as the topic.
|
||||
The generated agents are then used to perform tasks.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>None</code></dt>
|
||||
<dd>This function does not return any value. It starts the Chainlit application.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.create_gradio_interface"><code class="name flex">
|
||||
<span>def <span class="ident">create_gradio_interface</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Create a Gradio interface for generating agents and performing tasks.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>self</code></strong> : <code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></dt>
|
||||
<dd>An instance of the PraisonAI class.</dd>
|
||||
</dl>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>None</code></dt>
|
||||
<dd>This method does not return any value. It launches the Gradio interface.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>None</code></dt>
|
||||
<dd>This method does not raise any exceptions.</dd>
|
||||
</dl>
|
||||
<h2 id="example">Example</h2>
|
||||
<pre><code class="language-python-repl">>>> praison_ai.create_gradio_interface()
|
||||
</code></pre></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.create_realtime_interface"><code class="name flex">
|
||||
<span>def <span class="ident">create_realtime_interface</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Create a Chainlit interface for the realtime voice interaction application.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.main"><code class="name flex">
|
||||
<span>def <span class="ident">main</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>The main function of the PraisonAI object. It parses the command-line arguments,
|
||||
initializes the necessary attributes, and then calls the appropriate methods based on the
|
||||
provided arguments.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>self</code></strong> : <code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></dt>
|
||||
<dd>An instance of the PraisonAI class.</dd>
|
||||
</dl>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>Any</code></dt>
|
||||
<dd>Depending on the arguments provided, the function may return a result from the</dd>
|
||||
</dl>
|
||||
<p>AgentsGenerator, a deployment result from the CloudDeployer, or a message indicating
|
||||
the successful creation of a file.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.parse_args"><code class="name flex">
|
||||
<span>def <span class="ident">parse_args</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Parse the command-line arguments for the PraisonAI CLI.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>self</code></strong> : <code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></dt>
|
||||
<dd>An instance of the PraisonAI class.</dd>
|
||||
</dl>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>argparse.Namespace</code></dt>
|
||||
<dd>An object containing the parsed command-line arguments.</dd>
|
||||
</dl>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<dl>
|
||||
<dt><code>argparse.ArgumentError</code></dt>
|
||||
<dd>If the arguments provided are invalid.</dd>
|
||||
</dl>
|
||||
<h2 id="example">Example</h2>
|
||||
<pre><code class="language-python-repl">>>> args = praison_ai.parse_args()
|
||||
>>> print(args.agent_file) # Output: 'agents.yaml'
|
||||
</code></pre></div>
|
||||
</dd>
|
||||
<dt id="praisonai.cli.PraisonAI.run"><code class="name flex">
|
||||
<span>def <span class="ident">run</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Run the PraisonAI application.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.cli.stream_subprocess" href="#praisonai.cli.stream_subprocess">stream_subprocess</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.cli.PraisonAI.create_chainlit_chat_interface" href="#praisonai.cli.PraisonAI.create_chainlit_chat_interface">create_chainlit_chat_interface</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.create_chainlit_interface" href="#praisonai.cli.PraisonAI.create_chainlit_interface">create_chainlit_interface</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.create_code_interface" href="#praisonai.cli.PraisonAI.create_code_interface">create_code_interface</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.create_gradio_interface" href="#praisonai.cli.PraisonAI.create_gradio_interface">create_gradio_interface</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.create_realtime_interface" href="#praisonai.cli.PraisonAI.create_realtime_interface">create_realtime_interface</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.main" href="#praisonai.cli.PraisonAI.main">main</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.parse_args" href="#praisonai.cli.PraisonAI.parse_args">parse_args</a></code></li>
|
||||
<li><code><a title="praisonai.cli.PraisonAI.run" href="#praisonai.cli.PraisonAI.run">run</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,279 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.deploy API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.deploy</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.deploy.CloudDeployer"><code class="flex name class">
|
||||
<span>class <span class="ident">CloudDeployer</span></span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>A class for deploying a cloud-based application.</p>
|
||||
<h2 id="attributes">Attributes</h2>
|
||||
<p>None</p>
|
||||
<h2 id="methods">Methods</h2>
|
||||
<p><strong>init</strong>(self):
|
||||
Loads environment variables from .env file or system and sets them.</p>
|
||||
<p>Loads environment variables from .env file or system and sets them.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>self: An instance of the CloudDeployer class.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<p>None</p>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<p>None</p></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class CloudDeployer:
|
||||
"""
|
||||
A class for deploying a cloud-based application.
|
||||
|
||||
Attributes:
|
||||
None
|
||||
|
||||
Methods:
|
||||
__init__(self):
|
||||
Loads environment variables from .env file or system and sets them.
|
||||
|
||||
"""
|
||||
def __init__(self):
|
||||
"""
|
||||
Loads environment variables from .env file or system and sets them.
|
||||
|
||||
Parameters:
|
||||
self: An instance of the CloudDeployer class.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
|
||||
"""
|
||||
# Load environment variables from .env file or system
|
||||
load_dotenv()
|
||||
self.set_environment_variables()
|
||||
|
||||
def create_dockerfile(self):
|
||||
"""
|
||||
Creates a Dockerfile for the application.
|
||||
|
||||
Parameters:
|
||||
self: An instance of the CloudDeployer class.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
|
||||
This method creates a Dockerfile in the current directory with the specified content.
|
||||
The Dockerfile is used to build a Docker image for the application.
|
||||
The content of the Dockerfile includes instructions to use the Python 3.11-slim base image,
|
||||
set the working directory to /app, copy the current directory contents into the container,
|
||||
install the required Python packages (flask, praisonai, gunicorn, and markdown),
|
||||
expose port 8080, and run the application using Gunicorn.
|
||||
"""
|
||||
with open("Dockerfile", "w") as file:
|
||||
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.38 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
def create_api_file(self):
|
||||
"""
|
||||
Creates an API file for the application.
|
||||
|
||||
Parameters:
|
||||
self (CloudDeployer): An instance of the CloudDeployer class.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
This method creates an API file named "api.py" in the current directory. The file contains a basic Flask application that uses the PraisonAI library to run a simple agent and returns the output as an HTML page. The application listens on the root path ("/") and uses the Markdown library to format the output.
|
||||
"""
|
||||
with open("api.py", "w") as file:
|
||||
file.write("from flask import Flask\n")
|
||||
file.write("from praisonai import PraisonAI\n")
|
||||
file.write("import markdown\n\n")
|
||||
file.write("app = Flask(__name__)\n\n")
|
||||
file.write("def basic():\n")
|
||||
file.write(" praisonai = PraisonAI(agent_file=\"agents.yaml\")\n")
|
||||
file.write(" return praisonai.run()\n\n")
|
||||
file.write("@app.route('/')\n")
|
||||
file.write("def home():\n")
|
||||
file.write(" output = basic()\n")
|
||||
file.write(" html_output = markdown.markdown(output)\n")
|
||||
file.write(" return f'<html><body>{html_output}</body></html>'\n\n")
|
||||
file.write("if __name__ == \"__main__\":\n")
|
||||
file.write(" app.run(debug=True)\n")
|
||||
|
||||
def set_environment_variables(self):
|
||||
"""Sets environment variables with fallback to .env values or defaults."""
|
||||
os.environ["OPENAI_MODEL_NAME"] = os.getenv("OPENAI_MODEL_NAME", "gpt-4o")
|
||||
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "Enter your API key")
|
||||
os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1")
|
||||
|
||||
def run_commands(self):
|
||||
"""
|
||||
Sets environment variables with fallback to .env values or defaults.
|
||||
|
||||
Parameters:
|
||||
None
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
|
||||
This method sets environment variables for the application. It uses the `os.environ` dictionary to set the following environment variables:
|
||||
|
||||
- `OPENAI_MODEL_NAME`: The name of the OpenAI model to use. If not specified in the .env file, it defaults to "gpt-4o".
|
||||
- `OPENAI_API_KEY`: The API key for accessing the OpenAI API. If not specified in the .env file, it defaults to "Enter your API key".
|
||||
- `OPENAI_API_BASE`: The base URL for the OpenAI API. If not specified in the .env file, it defaults to "https://api.openai.com/v1".
|
||||
"""
|
||||
self.create_api_file()
|
||||
self.create_dockerfile()
|
||||
"""Runs a sequence of shell commands for deployment, continues on error."""
|
||||
commands = [
|
||||
"yes | gcloud auth configure-docker us-central1-docker.pkg.dev",
|
||||
"gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1",
|
||||
"docker build --platform linux/amd64 -t gcr.io/$(gcloud config get-value project)/praisonai-app:latest .",
|
||||
"docker tag gcr.io/$(gcloud config get-value project)/praisonai-app:latest us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest",
|
||||
"docker push us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest",
|
||||
"gcloud run deploy praisonai-service --image us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest --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}"
|
||||
]
|
||||
|
||||
for cmd in commands:
|
||||
try:
|
||||
subprocess.run(cmd, shell=True, check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"ERROR: Command '{e.cmd}' failed with exit status {e.returncode}")
|
||||
print(f"Continuing with the next command...")</code></pre>
|
||||
</details>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.deploy.CloudDeployer.create_api_file"><code class="name flex">
|
||||
<span>def <span class="ident">create_api_file</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Creates an API file for the application.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>self (CloudDeployer): An instance of the CloudDeployer class.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<p>None
|
||||
This method creates an API file named "api.py" in the current directory. The file contains a basic Flask application that uses the PraisonAI library to run a simple agent and returns the output as an HTML page. The application listens on the root path ("/") and uses the Markdown library to format the output.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.deploy.CloudDeployer.create_dockerfile"><code class="name flex">
|
||||
<span>def <span class="ident">create_dockerfile</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Creates a Dockerfile for the application.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>self: An instance of the CloudDeployer class.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<p>None</p>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<p>None
|
||||
This method creates a Dockerfile in the current directory with the specified content.
|
||||
The Dockerfile is used to build a Docker image for the application.
|
||||
The content of the Dockerfile includes instructions to use the Python 3.11-slim base image,
|
||||
set the working directory to /app, copy the current directory contents into the container,
|
||||
install the required Python packages (flask, praisonai, gunicorn, and markdown),
|
||||
expose port 8080, and run the application using Gunicorn.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.deploy.CloudDeployer.run_commands"><code class="name flex">
|
||||
<span>def <span class="ident">run_commands</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Sets environment variables with fallback to .env values or defaults.</p>
|
||||
<h2 id="parameters">Parameters</h2>
|
||||
<p>None</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<p>None</p>
|
||||
<h2 id="raises">Raises</h2>
|
||||
<p>None
|
||||
This method sets environment variables for the application. It uses the <code>os.environ</code> dictionary to set the following environment variables:</p>
|
||||
<ul>
|
||||
<li><code>OPENAI_MODEL_NAME</code>: The name of the OpenAI model to use. If not specified in the .env file, it defaults to "gpt-4o".</li>
|
||||
<li><code>OPENAI_API_KEY</code>: The API key for accessing the OpenAI API. If not specified in the .env file, it defaults to "Enter your API key".</li>
|
||||
<li><code>OPENAI_API_BASE</code>: The base URL for the OpenAI API. If not specified in the .env file, it defaults to "https://api.openai.com/v1".</li>
|
||||
</ul></div>
|
||||
</dd>
|
||||
<dt id="praisonai.deploy.CloudDeployer.set_environment_variables"><code class="name flex">
|
||||
<span>def <span class="ident">set_environment_variables</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Sets environment variables with fallback to .env values or defaults.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.deploy.CloudDeployer" href="#praisonai.deploy.CloudDeployer">CloudDeployer</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.deploy.CloudDeployer.create_api_file" href="#praisonai.deploy.CloudDeployer.create_api_file">create_api_file</a></code></li>
|
||||
<li><code><a title="praisonai.deploy.CloudDeployer.create_dockerfile" href="#praisonai.deploy.CloudDeployer.create_dockerfile">create_dockerfile</a></code></li>
|
||||
<li><code><a title="praisonai.deploy.CloudDeployer.run_commands" href="#praisonai.deploy.CloudDeployer.run_commands">run_commands</a></code></li>
|
||||
<li><code><a title="praisonai.deploy.CloudDeployer.set_environment_variables" href="#praisonai.deploy.CloudDeployer.set_environment_variables">set_environment_variables</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,188 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.inbuilt_tools.autogen_tools API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.inbuilt_tools.autogen_tools</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_CSVSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_CSVSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_CodeDocsSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_CodeDocsSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_DOCXSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_DOCXSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_DirectoryReadTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_DirectoryReadTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_DirectorySearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_DirectorySearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_FileReadTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_FileReadTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_JSONSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_JSONSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_MDXSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_MDXSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_PDFSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_PDFSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_RagTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_RagTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeElementFromWebsiteTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_ScrapeElementFromWebsiteTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeWebsiteTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_ScrapeWebsiteTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_TXTSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_TXTSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_WebsiteSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_WebsiteSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_XMLSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_XMLSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeChannelSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_YoutubeChannelSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeVideoSearchTool"><code class="name flex">
|
||||
<span>def <span class="ident">autogen_YoutubeVideoSearchTool</span></span>(<span>assistant, user_proxy)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.inbuilt_tools.autogen_tools.create_autogen_tool_function"><code class="name flex">
|
||||
<span>def <span class="ident">create_autogen_tool_function</span></span>(<span>tool_name)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.inbuilt_tools" href="index.html">praisonai.inbuilt_tools</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_CSVSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_CSVSearchTool">autogen_CSVSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_CodeDocsSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_CodeDocsSearchTool">autogen_CodeDocsSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_DOCXSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_DOCXSearchTool">autogen_DOCXSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_DirectoryReadTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_DirectoryReadTool">autogen_DirectoryReadTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_DirectorySearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_DirectorySearchTool">autogen_DirectorySearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_FileReadTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_FileReadTool">autogen_FileReadTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_JSONSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_JSONSearchTool">autogen_JSONSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_MDXSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_MDXSearchTool">autogen_MDXSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_PDFSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_PDFSearchTool">autogen_PDFSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_RagTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_RagTool">autogen_RagTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeElementFromWebsiteTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeElementFromWebsiteTool">autogen_ScrapeElementFromWebsiteTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeWebsiteTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeWebsiteTool">autogen_ScrapeWebsiteTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_TXTSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_TXTSearchTool">autogen_TXTSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_WebsiteSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_WebsiteSearchTool">autogen_WebsiteSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_XMLSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_XMLSearchTool">autogen_XMLSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeChannelSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeChannelSearchTool">autogen_YoutubeChannelSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeVideoSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeVideoSearchTool">autogen_YoutubeVideoSearchTool</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.create_autogen_tool_function" href="#praisonai.inbuilt_tools.autogen_tools.create_autogen_tool_function">create_autogen_tool_function</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,67 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.inbuilt_tools API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.inbuilt_tools</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
|
||||
<dl>
|
||||
<dt><code class="name"><a title="praisonai.inbuilt_tools.autogen_tools" href="autogen_tools.html">praisonai.inbuilt_tools.autogen_tools</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.inbuilt_tools.autogen_tools" href="autogen_tools.html">praisonai.inbuilt_tools.autogen_tools</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,69 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.inc.config API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.inc.config</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.inc.config.generate_config"><code class="name flex">
|
||||
<span>def <span class="ident">generate_config</span></span>(<span>ollama_save=None, huggingface_save=None, train=None, model_name=None, hf_model_name=None, ollama_model_name=None, model_parameters=None, max_seq_length=None, load_in_4bit=None, lora_r=None, lora_target_modules=None, lora_alpha=None, lora_dropout=None, lora_bias=None, use_gradient_checkpointing=None, random_state=None, use_rslora=None, loftq_config=None, dataset=None, dataset_text_field=None, dataset_num_proc=None, packing=None, per_device_train_batch_size=None, gradient_accumulation_steps=None, warmup_steps=None, num_train_epochs=None, max_steps=None, learning_rate=None, logging_steps=None, optim=None, weight_decay=None, lr_scheduler_type=None, seed=None, output_dir=None, quantization_method=None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Generates the configuration for PraisonAI with dynamic overrides.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.inc" href="index.html">praisonai.inc</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.inc.config.generate_config" href="#praisonai.inc.config.generate_config">generate_config</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,72 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.inc API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.inc</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
|
||||
<dl>
|
||||
<dt><code class="name"><a title="praisonai.inc.config" href="config.html">praisonai.inc.config</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.inc.models" href="models.html">praisonai.inc.models</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.inc.config" href="config.html">praisonai.inc.config</a></code></li>
|
||||
<li><code><a title="praisonai.inc.models" href="models.html">praisonai.inc.models</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,200 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.inc.models API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.inc.models</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.inc.models.PraisonAIModel"><code class="flex name class">
|
||||
<span>class <span class="ident">PraisonAIModel</span></span>
|
||||
<span>(</span><span>model=None, api_key_var=None, base_url=None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Initializes the PraisonAIModel with the provided parameters or environment variables.</p>
|
||||
<h2 id="args">Args</h2>
|
||||
<dl>
|
||||
<dt><strong><code>model</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The name of the OpenAI model. Defaults to None.</dd>
|
||||
<dt><strong><code>api_key_var</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The OpenAI API key. Defaults to None.</dd>
|
||||
<dt><strong><code>base_url</code></strong> : <code>str</code>, optional</dt>
|
||||
<dd>The base URL for the OpenAI API. Defaults to None.</dd>
|
||||
</dl></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class PraisonAIModel:
|
||||
def __init__(self, model=None, api_key_var=None, base_url=None):
|
||||
"""
|
||||
Initializes the PraisonAIModel with the provided parameters or environment variables.
|
||||
|
||||
Args:
|
||||
model (str, optional): The name of the OpenAI model. Defaults to None.
|
||||
api_key_var (str, optional): The OpenAI API key. Defaults to None.
|
||||
base_url (str, optional): The base URL for the OpenAI API. Defaults to None.
|
||||
"""
|
||||
self.model = model or os.getenv("OPENAI_MODEL_NAME", "gpt-4o")
|
||||
if self.model.startswith("openai/"):
|
||||
self.api_key_var = "OPENAI_API_KEY"
|
||||
self.base_url = base_url or "https://api.openai.com/v1"
|
||||
self.model_name = self.model.replace("openai/", "")
|
||||
elif self.model.startswith("groq/"):
|
||||
self.api_key_var = "GROQ_API_KEY"
|
||||
self.base_url = base_url or "https://api.groq.com/openai/v1"
|
||||
self.model_name = self.model.replace("groq/", "")
|
||||
elif self.model.startswith("cohere/"):
|
||||
self.api_key_var = "COHERE_API_KEY"
|
||||
self.base_url = ""
|
||||
self.model_name = self.model.replace("cohere/", "")
|
||||
elif self.model.startswith("ollama/"):
|
||||
self.api_key_var = "OLLAMA_API_KEY"
|
||||
self.base_url = base_url or "http://localhost:11434/v1"
|
||||
self.model_name = self.model.replace("ollama/", "")
|
||||
elif self.model.startswith("anthropic/"):
|
||||
self.api_key_var = "ANTHROPIC_API_KEY"
|
||||
self.base_url = ""
|
||||
self.model_name = self.model.replace("anthropic/", "")
|
||||
elif self.model.startswith("google/"):
|
||||
self.api_key_var = "GOOGLE_API_KEY"
|
||||
self.base_url = ""
|
||||
self.model_name = self.model.replace("google/", "")
|
||||
elif self.model.startswith("openrouter/"):
|
||||
self.api_key_var = "OPENROUTER_API_KEY"
|
||||
self.base_url = base_url or "https://openrouter.ai/api/v1"
|
||||
self.model_name = self.model.replace("openrouter/", "")
|
||||
else:
|
||||
self.api_key_var = api_key_var or "OPENAI_API_KEY"
|
||||
self.base_url = base_url or os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1")
|
||||
self.model_name = self.model
|
||||
logger.debug(f"Initialized PraisonAIModel with model {self.model_name}, api_key_var {self.api_key_var}, and base_url {self.base_url}")
|
||||
self.api_key = os.environ.get(self.api_key_var, "nokey")
|
||||
|
||||
def get_model(self):
|
||||
"""
|
||||
Returns an instance of the langchain Chat client with the configured parameters.
|
||||
|
||||
Returns:
|
||||
Chat: An instance of the langchain Chat client.
|
||||
"""
|
||||
if self.model.startswith("google/"):
|
||||
if GOOGLE_GENAI_AVAILABLE:
|
||||
return ChatGoogleGenerativeAI(
|
||||
model=self.model_name,
|
||||
google_api_key=self.api_key
|
||||
)
|
||||
else:
|
||||
raise ImportError(
|
||||
"Required Langchain Integration 'langchain-google-genai' not found. "
|
||||
"Please install with 'pip install langchain-google-genai'"
|
||||
)
|
||||
elif self.model.startswith("cohere/"):
|
||||
if COHERE_AVAILABLE:
|
||||
return ChatCohere(
|
||||
model=self.model_name,
|
||||
cohere_api_key=self.api_key,
|
||||
)
|
||||
else:
|
||||
raise ImportError(
|
||||
"Required Langchain Integration 'langchain-cohere' not found. "
|
||||
"Please install with 'pip install langchain-cohere'"
|
||||
)
|
||||
elif self.model.startswith("anthropic/"):
|
||||
if ANTHROPIC_AVAILABLE:
|
||||
return ChatAnthropic(
|
||||
model=self.model_name,
|
||||
anthropic_api_key=self.api_key,
|
||||
)
|
||||
else:
|
||||
raise ImportError(
|
||||
"Required Langchain Integration 'langchain-anthropic' not found. "
|
||||
"Please install with 'pip install langchain-anthropic'"
|
||||
)
|
||||
elif OPENAI_AVAILABLE:
|
||||
return ChatOpenAI(
|
||||
model=self.model_name,
|
||||
api_key=self.api_key,
|
||||
base_url=self.base_url,
|
||||
)
|
||||
else:
|
||||
raise ImportError(
|
||||
"Required Langchain Integration 'langchain-openai' not found. "
|
||||
"Please install with 'pip install langchain-openai'"
|
||||
)</code></pre>
|
||||
</details>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.inc.models.PraisonAIModel.get_model"><code class="name flex">
|
||||
<span>def <span class="ident">get_model</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Returns an instance of the langchain Chat client with the configured parameters.</p>
|
||||
<h2 id="returns">Returns</h2>
|
||||
<dl>
|
||||
<dt><code>Chat</code></dt>
|
||||
<dd>An instance of the langchain Chat client.</dd>
|
||||
</dl></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.inc" href="index.html">praisonai.inc</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.inc.models.PraisonAIModel" href="#praisonai.inc.models.PraisonAIModel">PraisonAIModel</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.inc.models.PraisonAIModel.get_model" href="#praisonai.inc.models.PraisonAIModel.get_model">get_model</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,107 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Package <code>praisonai</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
|
||||
<dl>
|
||||
<dt><code class="name"><a title="praisonai.agents_generator" href="agents_generator.html">praisonai.agents_generator</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.auto" href="auto.html">praisonai.auto</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.cli" href="cli.html">praisonai.cli</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.deploy" href="deploy.html">praisonai.deploy</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.inbuilt_tools" href="inbuilt_tools/index.html">praisonai.inbuilt_tools</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.inc" href="inc/index.html">praisonai.inc</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.setup" href="setup/index.html">praisonai.setup</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.test" href="test.html">praisonai.test</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.ui" href="ui/index.html">praisonai.ui</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.version" href="version.html">praisonai.version</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.agents_generator" href="agents_generator.html">praisonai.agents_generator</a></code></li>
|
||||
<li><code><a title="praisonai.auto" href="auto.html">praisonai.auto</a></code></li>
|
||||
<li><code><a title="praisonai.cli" href="cli.html">praisonai.cli</a></code></li>
|
||||
<li><code><a title="praisonai.deploy" href="deploy.html">praisonai.deploy</a></code></li>
|
||||
<li><code><a title="praisonai.inbuilt_tools" href="inbuilt_tools/index.html">praisonai.inbuilt_tools</a></code></li>
|
||||
<li><code><a title="praisonai.inc" href="inc/index.html">praisonai.inc</a></code></li>
|
||||
<li><code><a title="praisonai.setup" href="setup/index.html">praisonai.setup</a></code></li>
|
||||
<li><code><a title="praisonai.test" href="test.html">praisonai.test</a></code></li>
|
||||
<li><code><a title="praisonai.ui" href="ui/index.html">praisonai.ui</a></code></li>
|
||||
<li><code><a title="praisonai.version" href="version.html">praisonai.version</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,69 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.setup.build API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.setup.build</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.setup.build.build"><code class="name flex">
|
||||
<span>def <span class="ident">build</span></span>(<span>setup_kwargs)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.setup" href="index.html">praisonai.setup</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.setup.build.build" href="#praisonai.setup.build.build">build</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,77 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.setup API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.setup</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
|
||||
<dl>
|
||||
<dt><code class="name"><a title="praisonai.setup.build" href="build.html">praisonai.setup.build</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.setup.post_install" href="post_install.html">praisonai.setup.post_install</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.setup.setup_conda_env" href="setup_conda_env.html">praisonai.setup.setup_conda_env</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.setup.build" href="build.html">praisonai.setup.build</a></code></li>
|
||||
<li><code><a title="praisonai.setup.post_install" href="post_install.html">praisonai.setup.post_install</a></code></li>
|
||||
<li><code><a title="praisonai.setup.setup_conda_env" href="setup_conda_env.html">praisonai.setup.setup_conda_env</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,69 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.setup.post_install API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.setup.post_install</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.setup.post_install.main"><code class="name flex">
|
||||
<span>def <span class="ident">main</span></span>(<span>)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.setup" href="index.html">praisonai.setup</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.setup.post_install.main" href="#praisonai.setup.post_install.main">main</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,69 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.setup.setup_conda_env API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.setup.setup_conda_env</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.setup.setup_conda_env.main"><code class="name flex">
|
||||
<span>def <span class="ident">main</span></span>(<span>)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.setup" href="index.html">praisonai.setup</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.setup.setup_conda_env.main" href="#praisonai.setup.setup_conda_env.main">main</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,73 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.test API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.test</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.test.generate_crew_and_kickoff"><code class="name flex">
|
||||
<span>def <span class="ident">generate_crew_and_kickoff</span></span>(<span>agent_file)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>This function generates a crew of agents and kicks off tasks based on the configuration provided in a YAML file.</p>
|
||||
<p>Parameters:
|
||||
agent_file (str): The path to the YAML file containing the configuration for the agents and tasks.</p>
|
||||
<p>Returns:
|
||||
str: The result of the last task executed by the crew.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.test.generate_crew_and_kickoff" href="#praisonai.test.generate_crew_and_kickoff">generate_crew_and_kickoff</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,428 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.ui.context API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.ui.context</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.ui.context.main"><code class="name flex">
|
||||
<span>def <span class="ident">main</span></span>(<span>)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.ui.context.ContextGatherer"><code class="flex name class">
|
||||
<span>class <span class="ident">ContextGatherer</span></span>
|
||||
<span>(</span><span>directory='.', output_file='context.txt', relevant_extensions=None, max_file_size=1000000, max_tokens=900000)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class ContextGatherer:
|
||||
def __init__(self, directory='.', output_file='context.txt',
|
||||
relevant_extensions=None, max_file_size=1_000_000, max_tokens=900000):
|
||||
self.directory = directory
|
||||
self.output_file = output_file
|
||||
self.relevant_extensions = relevant_extensions or [
|
||||
'.py', '.js', '.ts', '.java', '.rb', '.php', '.pl', '.pm', '.c', '.h',
|
||||
'.cpp', '.hpp', '.cs', '.vb', '.swift', '.kt', '.m', '.mm', '.go', '.rs',
|
||||
'.hs', '.r', '.lua', '.sh', '.bat', '.clj', '.scala', '.erl', '.ex',
|
||||
'.ml', '.fs', '.groovy', '.jsm', '.jsx', '.tsx', '.yaml'
|
||||
]
|
||||
self.max_file_size = max_file_size
|
||||
self.max_tokens = int(os.getenv("PRAISONAI_MAX_TOKENS", max_tokens))
|
||||
self.ignore_patterns = self.get_ignore_patterns()
|
||||
self.include_paths = self.get_include_paths()
|
||||
self.included_files = []
|
||||
|
||||
def get_ignore_patterns(self):
|
||||
"""
|
||||
Loads ignore patterns from various sources, prioritizing them in
|
||||
the following order:
|
||||
1. .praisonignore
|
||||
2. settings.yaml (under code.ignore_files)
|
||||
3. PRAISONAI_IGNORE_FILES environment variable
|
||||
4. .gitignore
|
||||
5. Default patterns
|
||||
"""
|
||||
ignore_patterns = []
|
||||
|
||||
def load_from_file(filepath):
|
||||
if os.path.exists(filepath):
|
||||
with open(filepath, 'r') as f:
|
||||
ignore_patterns.extend(
|
||||
line.strip() for line in f
|
||||
if line.strip() and not line.startswith('#')
|
||||
)
|
||||
|
||||
# 1. Load from .praisonignore
|
||||
load_from_file(os.path.join(self.directory, '.praisonignore'))
|
||||
|
||||
# 2. Load from settings.yaml
|
||||
settings_path = os.path.join(self.directory, 'settings.yaml')
|
||||
if os.path.exists(settings_path):
|
||||
with open(settings_path, 'r') as f:
|
||||
settings = yaml.safe_load(f)
|
||||
if 'code' in settings and 'ignore_files' in settings['code']:
|
||||
ignore_patterns.extend(settings['code']['ignore_files'])
|
||||
|
||||
# 3. Load from environment variable
|
||||
ignore_files_env = os.getenv("PRAISONAI_IGNORE_FILES")
|
||||
if ignore_files_env:
|
||||
ignore_patterns.extend(ignore_files_env.split(","))
|
||||
|
||||
# 4. Load from .gitignore
|
||||
load_from_file(os.path.join(self.directory, '.gitignore'))
|
||||
|
||||
# 5. Default patterns (only if no patterns loaded from above sources)
|
||||
if not ignore_patterns:
|
||||
ignore_patterns = [
|
||||
".*", "*.pyc", "__pycache__", ".git", ".gitignore", ".vscode",
|
||||
".idea", ".DS_Store", "*.lock", "*.pyc", ".env", "docs", "tests",
|
||||
"test", "tmp", "temp", "*.txt", "*.md", "*.json", "*.csv", "*.tsv",
|
||||
"public", "*.sql", "*.sqlite", "*.db", "*.db3", "*.sqlite3",
|
||||
"*.log", "*.zip", "*.gz", "*.tar", "*.rar", "*.7z", "*.pdf",
|
||||
"*.jpg", "*.jpeg", "*.png", "*.gif", "*.svg", "cookbooks",
|
||||
"assets", "__pycache__", "dist", "build", "node_modules", "venv"
|
||||
]
|
||||
logger.debug(f"Using default ignore patterns: {ignore_patterns}")
|
||||
|
||||
# Modify patterns to match directories and add leading '*' if necessary
|
||||
modified_ignore_patterns = [
|
||||
'*' + pattern if not pattern.startswith('.') and not pattern.startswith('*') else pattern
|
||||
for pattern in ignore_patterns
|
||||
]
|
||||
logger.debug(f"Final ignore patterns: {modified_ignore_patterns}")
|
||||
return modified_ignore_patterns
|
||||
|
||||
def get_include_paths(self):
|
||||
"""
|
||||
Loads include paths from:
|
||||
1. .praisoninclude (includes ONLY files/directories listed)
|
||||
2. .praisoncontext (if .praisoninclude doesn't exist, this is used
|
||||
to include all other relevant files, excluding ignore patterns)
|
||||
"""
|
||||
include_paths = []
|
||||
include_all = False # Flag to indicate if we need to include all files
|
||||
|
||||
include_file = os.path.join(self.directory, '.praisoncontext')
|
||||
if os.path.exists(include_file):
|
||||
with open(include_file, 'r') as f:
|
||||
include_paths.extend(
|
||||
line.strip() for line in f
|
||||
if line.strip() and not line.startswith('#')
|
||||
)
|
||||
|
||||
# If .praisoncontext doesn't exist, fall back to .praisoninclude
|
||||
# for including all relevant files
|
||||
if not include_paths:
|
||||
include_file = os.path.join(self.directory, '.praisoninclude')
|
||||
if os.path.exists(include_file):
|
||||
with open(include_file, 'r') as f:
|
||||
include_paths.extend(
|
||||
line.strip() for line in f
|
||||
if line.strip() and not line.startswith('#')
|
||||
)
|
||||
include_all = True # Include all files along with specified paths
|
||||
|
||||
return include_paths, include_all
|
||||
|
||||
def should_ignore(self, file_path):
|
||||
"""
|
||||
Check if a file or directory should be ignored based on patterns.
|
||||
Handles both file names and directory names for more comprehensive filtering.
|
||||
"""
|
||||
relative_path = os.path.relpath(file_path, self.directory)
|
||||
if relative_path.startswith('.'):
|
||||
return True
|
||||
for pattern in self.ignore_patterns:
|
||||
if fnmatch.fnmatch(relative_path, pattern) or \
|
||||
fnmatch.fnmatch(os.path.basename(file_path), pattern):
|
||||
return True
|
||||
return False
|
||||
|
||||
def is_relevant_file(self, file_path):
|
||||
"""Determine if a file is relevant for the context."""
|
||||
return os.path.isfile(file_path) and \
|
||||
os.path.getsize(file_path) <= self.max_file_size and \
|
||||
any(file_path.endswith(ext) for ext in self.relevant_extensions)
|
||||
|
||||
def gather_context(self):
|
||||
"""
|
||||
Gather context from relevant files, respecting ignore patterns
|
||||
and include options from .praisoninclude and .praisoncontext.
|
||||
"""
|
||||
context = []
|
||||
total_files = 0
|
||||
processed_files = 0
|
||||
self.include_paths, include_all = self.get_include_paths()
|
||||
|
||||
def add_file_content(file_path):
|
||||
"""Helper function to add file content to context."""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
context.append(
|
||||
f"File: {file_path}\n\n{content}\n\n{'=' * 50}\n"
|
||||
)
|
||||
self.included_files.append(
|
||||
Path(file_path).relative_to(self.directory)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error reading {file_path}: {e}")
|
||||
|
||||
def process_path(path):
|
||||
"""Helper function to process a single path (file or directory)."""
|
||||
nonlocal total_files, processed_files
|
||||
if os.path.isdir(path):
|
||||
for root, dirs, files in os.walk(path):
|
||||
total_files += len(files)
|
||||
dirs[:] = [
|
||||
d
|
||||
for d in dirs
|
||||
if not self.should_ignore(os.path.join(root, d))
|
||||
]
|
||||
for file in files:
|
||||
file_path = os.path.join(root, file)
|
||||
if not self.should_ignore(file_path) and self.is_relevant_file(file_path):
|
||||
add_file_content(file_path)
|
||||
processed_files += 1
|
||||
print(
|
||||
f"\rProcessed {processed_files}/{total_files} files",
|
||||
end="",
|
||||
flush=True,
|
||||
)
|
||||
elif os.path.isfile(path) and self.is_relevant_file(path):
|
||||
add_file_content(path)
|
||||
processed_files += 1
|
||||
print(
|
||||
f"\rProcessed {processed_files}/1 files",
|
||||
end="",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
if include_all:
|
||||
# Include ALL relevant files from the entire directory
|
||||
process_path(self.directory)
|
||||
|
||||
# Include files from .praisoninclude specifically
|
||||
for include_path in self.include_paths:
|
||||
full_path = os.path.join(self.directory, include_path)
|
||||
process_path(full_path)
|
||||
elif self.include_paths:
|
||||
# Include only files specified in .praisoncontext
|
||||
for include_path in self.include_paths:
|
||||
full_path = os.path.join(self.directory, include_path)
|
||||
process_path(full_path)
|
||||
else:
|
||||
# No include options, process the entire directory
|
||||
process_path(self.directory)
|
||||
|
||||
print() # New line after progress indicator
|
||||
return "\n".join(context)
|
||||
|
||||
def count_tokens(self, text):
|
||||
"""Count tokens using a simple whitespace-based tokenizer."""
|
||||
return len(text.split())
|
||||
|
||||
def truncate_context(self, context):
|
||||
"""Truncate context to stay within the token limit."""
|
||||
tokens = context.split()
|
||||
if len(tokens) > self.max_tokens:
|
||||
truncated_context = ' '.join(tokens[:self.max_tokens])
|
||||
logger.warning("Context truncated due to token limit.")
|
||||
return truncated_context
|
||||
return context
|
||||
|
||||
def save_context(self, context):
|
||||
"""Save the gathered context to a file."""
|
||||
with open(self.output_file, 'w', encoding='utf-8') as f:
|
||||
f.write(context)
|
||||
|
||||
def get_context_tree(self):
|
||||
"""Generate a formatted tree structure of included files and folders."""
|
||||
tree = []
|
||||
start_dir = Path(self.directory)
|
||||
|
||||
def add_to_tree(path, prefix=''):
|
||||
contents = sorted(path.iterdir())
|
||||
pointers = [('└── ' if i == len(contents) - 1 else '├── ') for i in range(len(contents))]
|
||||
for pointer, item in zip(pointers, contents):
|
||||
rel_path = item.relative_to(start_dir)
|
||||
if rel_path in self.included_files:
|
||||
tree.append(f"{prefix}{pointer}{rel_path}")
|
||||
|
||||
if item.is_dir():
|
||||
add_to_tree(item, prefix + (' ' if pointer == '└── ' else '│ '))
|
||||
|
||||
add_to_tree(start_dir)
|
||||
return '\n'.join(tree)
|
||||
|
||||
def run(self):
|
||||
"""Execute the context gathering, truncation, and reporting."""
|
||||
context = self.gather_context()
|
||||
context = self.truncate_context(context)
|
||||
token_count = self.count_tokens(context)
|
||||
print(f"Context gathered successfully.")
|
||||
print(f"Total number of tokens (estimated): {token_count}")
|
||||
# self.save_context(context)
|
||||
context_tree = self.get_context_tree()
|
||||
logger.debug(f"Context tree:\n{context_tree}")
|
||||
return context, token_count, context_tree</code></pre>
|
||||
</details>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.count_tokens"><code class="name flex">
|
||||
<span>def <span class="ident">count_tokens</span></span>(<span>self, text)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Count tokens using a simple whitespace-based tokenizer.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.gather_context"><code class="name flex">
|
||||
<span>def <span class="ident">gather_context</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Gather context from relevant files, respecting ignore patterns
|
||||
and include options from .praisoninclude and .praisoncontext.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.get_context_tree"><code class="name flex">
|
||||
<span>def <span class="ident">get_context_tree</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Generate a formatted tree structure of included files and folders.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.get_ignore_patterns"><code class="name flex">
|
||||
<span>def <span class="ident">get_ignore_patterns</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Loads ignore patterns from various sources, prioritizing them in
|
||||
the following order:
|
||||
1. .praisonignore
|
||||
2. settings.yaml (under code.ignore_files)
|
||||
3. PRAISONAI_IGNORE_FILES environment variable
|
||||
4. .gitignore
|
||||
5. Default patterns</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.get_include_paths"><code class="name flex">
|
||||
<span>def <span class="ident">get_include_paths</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Loads include paths from:
|
||||
1. .praisoninclude (includes ONLY files/directories listed)
|
||||
2. .praisoncontext (if .praisoninclude doesn't exist, this is used
|
||||
to include all other relevant files, excluding ignore patterns)</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.is_relevant_file"><code class="name flex">
|
||||
<span>def <span class="ident">is_relevant_file</span></span>(<span>self, file_path)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Determine if a file is relevant for the context.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.run"><code class="name flex">
|
||||
<span>def <span class="ident">run</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Execute the context gathering, truncation, and reporting.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.save_context"><code class="name flex">
|
||||
<span>def <span class="ident">save_context</span></span>(<span>self, context)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Save the gathered context to a file.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.should_ignore"><code class="name flex">
|
||||
<span>def <span class="ident">should_ignore</span></span>(<span>self, file_path)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Check if a file or directory should be ignored based on patterns.
|
||||
Handles both file names and directory names for more comprehensive filtering.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.context.ContextGatherer.truncate_context"><code class="name flex">
|
||||
<span>def <span class="ident">truncate_context</span></span>(<span>self, context)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Truncate context to stay within the token limit.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.ui" href="index.html">praisonai.ui</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.ui.context.main" href="#praisonai.ui.context.main">main</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.ui.context.ContextGatherer" href="#praisonai.ui.context.ContextGatherer">ContextGatherer</a></code></h4>
|
||||
<ul class="two-column">
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.count_tokens" href="#praisonai.ui.context.ContextGatherer.count_tokens">count_tokens</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.gather_context" href="#praisonai.ui.context.ContextGatherer.gather_context">gather_context</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.get_context_tree" href="#praisonai.ui.context.ContextGatherer.get_context_tree">get_context_tree</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.get_ignore_patterns" href="#praisonai.ui.context.ContextGatherer.get_ignore_patterns">get_ignore_patterns</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.get_include_paths" href="#praisonai.ui.context.ContextGatherer.get_include_paths">get_include_paths</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.is_relevant_file" href="#praisonai.ui.context.ContextGatherer.is_relevant_file">is_relevant_file</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.run" href="#praisonai.ui.context.ContextGatherer.run">run</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.save_context" href="#praisonai.ui.context.ContextGatherer.save_context">save_context</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.should_ignore" href="#praisonai.ui.context.ContextGatherer.should_ignore">should_ignore</a></code></li>
|
||||
<li><code><a title="praisonai.ui.context.ContextGatherer.truncate_context" href="#praisonai.ui.context.ContextGatherer.truncate_context">truncate_context</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,77 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.ui API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Namespace <code>praisonai.ui</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
|
||||
<dl>
|
||||
<dt><code class="name"><a title="praisonai.ui.context" href="context.html">praisonai.ui.context</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.ui.realtimeclient" href="realtimeclient/index.html">praisonai.ui.realtimeclient</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="praisonai.ui.sql_alchemy" href="sql_alchemy.html">praisonai.ui.sql_alchemy</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.ui.context" href="context.html">praisonai.ui.context</a></code></li>
|
||||
<li><code><a title="praisonai.ui.realtimeclient" href="realtimeclient/index.html">praisonai.ui.realtimeclient</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy" href="sql_alchemy.html">praisonai.ui.sql_alchemy</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,898 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.ui.sql_alchemy API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.ui.sql_alchemy</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer"><code class="flex name class">
|
||||
<span>class <span class="ident">SQLAlchemyDataLayer</span></span>
|
||||
<span>(</span><span>conninfo: str, ssl_require: bool = False, storage_provider: Optional[chainlit.data.base.BaseStorageClient] = None, user_thread_limit: Optional[int] = 1000, show_logger: Optional[bool] = False)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Base class for data persistence.</p></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class SQLAlchemyDataLayer(BaseDataLayer):
|
||||
def __init__(
|
||||
self,
|
||||
conninfo: str,
|
||||
ssl_require: bool = False,
|
||||
storage_provider: Optional[BaseStorageClient] = None,
|
||||
user_thread_limit: Optional[int] = 1000,
|
||||
show_logger: Optional[bool] = False,
|
||||
):
|
||||
self._conninfo = conninfo
|
||||
self.user_thread_limit = user_thread_limit
|
||||
self.show_logger = show_logger
|
||||
ssl_args = {}
|
||||
if ssl_require:
|
||||
# Create an SSL context to require an SSL connection
|
||||
ssl_context = ssl.create_default_context()
|
||||
ssl_context.check_hostname = False
|
||||
ssl_context.verify_mode = ssl.CERT_NONE
|
||||
ssl_args["ssl"] = ssl_context
|
||||
self.engine: AsyncEngine = create_async_engine(
|
||||
self._conninfo, connect_args=ssl_args
|
||||
)
|
||||
self.async_session = sessionmaker(
|
||||
bind=self.engine, expire_on_commit=False, class_=AsyncSession
|
||||
) # type: ignore
|
||||
if storage_provider:
|
||||
self.storage_provider: Optional[BaseStorageClient] = storage_provider
|
||||
if self.show_logger:
|
||||
logger.info("SQLAlchemyDataLayer storage client initialized")
|
||||
else:
|
||||
self.storage_provider = None
|
||||
logger.warn(
|
||||
"SQLAlchemyDataLayer storage client is not initialized and elements will not be persisted!"
|
||||
)
|
||||
|
||||
async def build_debug_url(self) -> str:
|
||||
return ""
|
||||
|
||||
###### SQL Helpers ######
|
||||
async def execute_sql(
|
||||
self, query: str, parameters: dict
|
||||
) -> Union[List[Dict[str, Any]], int, None]:
|
||||
parameterized_query = text(query)
|
||||
async with self.async_session() as session:
|
||||
try:
|
||||
await session.begin()
|
||||
result = await session.execute(parameterized_query, parameters)
|
||||
await session.commit()
|
||||
if result.returns_rows:
|
||||
json_result = [dict(row._mapping) for row in result.fetchall()]
|
||||
clean_json_result = self.clean_result(json_result)
|
||||
assert isinstance(clean_json_result, list) or isinstance(
|
||||
clean_json_result, int
|
||||
)
|
||||
return clean_json_result
|
||||
else:
|
||||
return result.rowcount
|
||||
except SQLAlchemyError as e:
|
||||
await session.rollback()
|
||||
logger.warn(f"An error occurred: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
logger.warn(f"An unexpected error occurred: {e}")
|
||||
return None
|
||||
|
||||
async def get_current_timestamp(self) -> str:
|
||||
return datetime.now().isoformat() + "Z"
|
||||
|
||||
def clean_result(self, obj):
|
||||
"""Recursively change UUID -> str and serialize dictionaries"""
|
||||
if isinstance(obj, dict):
|
||||
return {k: self.clean_result(v) for k, v in obj.items()}
|
||||
elif isinstance(obj, list):
|
||||
return [self.clean_result(item) for item in obj]
|
||||
elif isinstance(obj, uuid.UUID):
|
||||
return str(obj)
|
||||
return obj
|
||||
|
||||
###### User ######
|
||||
async def get_user(self, identifier: str) -> Optional[PersistedUser]:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: get_user, identifier={identifier}")
|
||||
query = "SELECT * FROM users WHERE identifier = :identifier"
|
||||
parameters = {"identifier": identifier}
|
||||
result = await self.execute_sql(query=query, parameters=parameters)
|
||||
if result and isinstance(result, list):
|
||||
user_data = result[0]
|
||||
|
||||
# SQLite returns JSON as string, we most convert it. (#1137)
|
||||
metadata = user_data.get("metadata", {})
|
||||
if isinstance(metadata, str):
|
||||
metadata = json.loads(metadata)
|
||||
|
||||
assert isinstance(metadata, dict)
|
||||
assert isinstance(user_data["id"], str)
|
||||
assert isinstance(user_data["identifier"], str)
|
||||
assert isinstance(user_data["createdAt"], str)
|
||||
|
||||
return PersistedUser(
|
||||
id=user_data["id"],
|
||||
identifier=user_data["identifier"],
|
||||
createdAt=user_data["createdAt"],
|
||||
metadata=metadata,
|
||||
)
|
||||
return None
|
||||
|
||||
async def _get_user_identifer_by_id(self, user_id: str) -> str:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: _get_user_identifer_by_id, user_id={user_id}")
|
||||
query = "SELECT identifier FROM users WHERE id = :user_id"
|
||||
parameters = {"user_id": user_id}
|
||||
result = await self.execute_sql(query=query, parameters=parameters)
|
||||
|
||||
assert result
|
||||
assert isinstance(result, list)
|
||||
|
||||
return result[0]["identifier"]
|
||||
|
||||
async def _get_user_id_by_thread(self, thread_id: str) -> Optional[str]:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: _get_user_id_by_thread, thread_id={thread_id}")
|
||||
query = "SELECT userId FROM threads WHERE id = :thread_id"
|
||||
parameters = {"thread_id": thread_id}
|
||||
result = await self.execute_sql(query=query, parameters=parameters)
|
||||
if result:
|
||||
assert isinstance(result, list)
|
||||
return result[0]["userId"]
|
||||
|
||||
return None
|
||||
|
||||
async def create_user(self, user: User) -> Optional[PersistedUser]:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: create_user, user_identifier={user.identifier}")
|
||||
existing_user: Optional["PersistedUser"] = await self.get_user(user.identifier)
|
||||
user_dict: Dict[str, Any] = {
|
||||
"identifier": str(user.identifier),
|
||||
"metadata": json.dumps(user.metadata) or {},
|
||||
}
|
||||
if not existing_user: # create the user
|
||||
if self.show_logger:
|
||||
logger.info("SQLAlchemy: create_user, creating the user")
|
||||
user_dict["id"] = str(uuid.uuid4())
|
||||
user_dict["createdAt"] = await self.get_current_timestamp()
|
||||
query = """INSERT INTO users ("id", "identifier", "createdAt", "metadata") VALUES (:id, :identifier, :createdAt, :metadata)"""
|
||||
await self.execute_sql(query=query, parameters=user_dict)
|
||||
else: # update the user
|
||||
if self.show_logger:
|
||||
logger.info("SQLAlchemy: update user metadata")
|
||||
query = """UPDATE users SET "metadata" = :metadata WHERE "identifier" = :identifier"""
|
||||
await self.execute_sql(
|
||||
query=query, parameters=user_dict
|
||||
) # We want to update the metadata
|
||||
return await self.get_user(user.identifier)
|
||||
|
||||
###### Threads ######
|
||||
async def get_thread_author(self, thread_id: str) -> str:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: get_thread_author, thread_id={thread_id}")
|
||||
query = """SELECT "userIdentifier" FROM threads WHERE "id" = :id"""
|
||||
parameters = {"id": thread_id}
|
||||
result = await self.execute_sql(query=query, parameters=parameters)
|
||||
if isinstance(result, list) and result:
|
||||
author_identifier = result[0].get("userIdentifier")
|
||||
if author_identifier is not None:
|
||||
return author_identifier
|
||||
raise ValueError(f"Author not found for thread_id {thread_id}")
|
||||
|
||||
async def get_thread(self, thread_id: str) -> Optional[ThreadDict]:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: get_thread, thread_id={thread_id}")
|
||||
user_threads: Optional[List[ThreadDict]] = await self.get_all_user_threads(
|
||||
thread_id=thread_id
|
||||
)
|
||||
if user_threads:
|
||||
return user_threads[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
async def update_thread(
|
||||
self,
|
||||
thread_id: str,
|
||||
name: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
metadata: Optional[Dict] = None,
|
||||
tags: Optional[List[str]] = None,
|
||||
):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: update_thread, thread_id={thread_id}")
|
||||
|
||||
user_identifier = None
|
||||
if user_id:
|
||||
user_identifier = await self._get_user_identifer_by_id(user_id)
|
||||
|
||||
data = {
|
||||
"id": thread_id,
|
||||
"createdAt": (
|
||||
await self.get_current_timestamp() if metadata is None else None
|
||||
),
|
||||
"name": (
|
||||
name
|
||||
if name is not None
|
||||
else (metadata.get("name") if metadata and "name" in metadata else None)
|
||||
),
|
||||
"userId": user_id,
|
||||
"userIdentifier": user_identifier,
|
||||
"tags": tags,
|
||||
"metadata": json.dumps(metadata) if metadata else None,
|
||||
}
|
||||
parameters = {
|
||||
key: value for key, value in data.items() if value is not None
|
||||
} # Remove keys with None values
|
||||
columns = ", ".join(f'"{key}"' for key in parameters.keys())
|
||||
values = ", ".join(f":{key}" for key in parameters.keys())
|
||||
updates = ", ".join(
|
||||
f'"{key}" = EXCLUDED."{key}"' for key in parameters.keys() if key != "id"
|
||||
)
|
||||
query = f"""
|
||||
INSERT INTO threads ({columns})
|
||||
VALUES ({values})
|
||||
ON CONFLICT ("id") DO UPDATE
|
||||
SET {updates};
|
||||
"""
|
||||
await self.execute_sql(query=query, parameters=parameters)
|
||||
|
||||
async def delete_thread(self, thread_id: str):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: delete_thread, thread_id={thread_id}")
|
||||
# Delete feedbacks/elements/steps/thread
|
||||
feedbacks_query = """DELETE FROM feedbacks WHERE "forId" IN (SELECT "id" FROM steps WHERE "threadId" = :id)"""
|
||||
elements_query = """DELETE FROM elements WHERE "threadId" = :id"""
|
||||
steps_query = """DELETE FROM steps WHERE "threadId" = :id"""
|
||||
thread_query = """DELETE FROM threads WHERE "id" = :id"""
|
||||
parameters = {"id": thread_id}
|
||||
await self.execute_sql(query=feedbacks_query, parameters=parameters)
|
||||
await self.execute_sql(query=elements_query, parameters=parameters)
|
||||
await self.execute_sql(query=steps_query, parameters=parameters)
|
||||
await self.execute_sql(query=thread_query, parameters=parameters)
|
||||
|
||||
async def list_threads(
|
||||
self, pagination: Pagination, filters: ThreadFilter
|
||||
) -> PaginatedResponse:
|
||||
if self.show_logger:
|
||||
logger.info(
|
||||
f"SQLAlchemy: list_threads, pagination={pagination}, filters={filters}"
|
||||
)
|
||||
if not filters.userId:
|
||||
raise ValueError("userId is required")
|
||||
all_user_threads: List[ThreadDict] = (
|
||||
await self.get_all_user_threads(user_id=filters.userId) or []
|
||||
)
|
||||
|
||||
search_keyword = filters.search.lower() if filters.search else None
|
||||
feedback_value = int(filters.feedback) if filters.feedback else None
|
||||
|
||||
filtered_threads = []
|
||||
for thread in all_user_threads:
|
||||
keyword_match = True
|
||||
feedback_match = True
|
||||
if search_keyword or feedback_value is not None:
|
||||
if search_keyword:
|
||||
keyword_match = any(
|
||||
search_keyword in step["output"].lower()
|
||||
for step in thread["steps"]
|
||||
if "output" in step
|
||||
)
|
||||
if feedback_value is not None:
|
||||
feedback_match = False # Assume no match until found
|
||||
for step in thread["steps"]:
|
||||
feedback = step.get("feedback")
|
||||
if feedback and feedback.get("value") == feedback_value:
|
||||
feedback_match = True
|
||||
break
|
||||
if keyword_match and feedback_match:
|
||||
filtered_threads.append(thread)
|
||||
|
||||
start = 0
|
||||
if pagination.cursor:
|
||||
for i, thread in enumerate(filtered_threads):
|
||||
if (
|
||||
thread["id"] == pagination.cursor
|
||||
): # Find the start index using pagination.cursor
|
||||
start = i + 1
|
||||
break
|
||||
end = start + pagination.first
|
||||
paginated_threads = filtered_threads[start:end] or []
|
||||
|
||||
has_next_page = len(filtered_threads) > end
|
||||
start_cursor = paginated_threads[0]["id"] if paginated_threads else None
|
||||
end_cursor = paginated_threads[-1]["id"] if paginated_threads else None
|
||||
|
||||
return PaginatedResponse(
|
||||
pageInfo=PageInfo(
|
||||
hasNextPage=has_next_page,
|
||||
startCursor=start_cursor,
|
||||
endCursor=end_cursor,
|
||||
),
|
||||
data=paginated_threads,
|
||||
)
|
||||
|
||||
###### Steps ######
|
||||
@queue_until_user_message()
|
||||
async def create_step(self, step_dict: "StepDict"):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: create_step, step_id={step_dict.get('id')}")
|
||||
|
||||
step_dict["showInput"] = (
|
||||
str(step_dict.get("showInput", "")).lower()
|
||||
if "showInput" in step_dict
|
||||
else None
|
||||
)
|
||||
parameters = {
|
||||
key: value
|
||||
for key, value in step_dict.items()
|
||||
if value is not None and not (isinstance(value, dict) and not value)
|
||||
}
|
||||
parameters["metadata"] = json.dumps(step_dict.get("metadata", {}))
|
||||
parameters["generation"] = json.dumps(step_dict.get("generation", {}))
|
||||
columns = ", ".join(f'"{key}"' for key in parameters.keys())
|
||||
values = ", ".join(f":{key}" for key in parameters.keys())
|
||||
updates = ", ".join(
|
||||
f'"{key}" = :{key}' for key in parameters.keys() if key != "id"
|
||||
)
|
||||
query = f"""
|
||||
INSERT INTO steps ({columns})
|
||||
VALUES ({values})
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET {updates};
|
||||
"""
|
||||
await self.execute_sql(query=query, parameters=parameters)
|
||||
|
||||
@queue_until_user_message()
|
||||
async def update_step(self, step_dict: "StepDict"):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: update_step, step_id={step_dict.get('id')}")
|
||||
await self.create_step(step_dict)
|
||||
|
||||
@queue_until_user_message()
|
||||
async def delete_step(self, step_id: str):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: delete_step, step_id={step_id}")
|
||||
# Delete feedbacks/elements/steps
|
||||
feedbacks_query = """DELETE FROM feedbacks WHERE "forId" = :id"""
|
||||
elements_query = """DELETE FROM elements WHERE "forId" = :id"""
|
||||
steps_query = """DELETE FROM steps WHERE "id" = :id"""
|
||||
parameters = {"id": step_id}
|
||||
await self.execute_sql(query=feedbacks_query, parameters=parameters)
|
||||
await self.execute_sql(query=elements_query, parameters=parameters)
|
||||
await self.execute_sql(query=steps_query, parameters=parameters)
|
||||
|
||||
###### Feedback ######
|
||||
async def upsert_feedback(self, feedback: Feedback) -> str:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: upsert_feedback, feedback_id={feedback.id}")
|
||||
feedback.id = feedback.id or str(uuid.uuid4())
|
||||
feedback_dict = asdict(feedback)
|
||||
parameters = {
|
||||
key: value for key, value in feedback_dict.items() if value is not None
|
||||
}
|
||||
|
||||
columns = ", ".join(f'"{key}"' for key in parameters.keys())
|
||||
values = ", ".join(f":{key}" for key in parameters.keys())
|
||||
updates = ", ".join(
|
||||
f'"{key}" = :{key}' for key in parameters.keys() if key != "id"
|
||||
)
|
||||
query = f"""
|
||||
INSERT INTO feedbacks ({columns})
|
||||
VALUES ({values})
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET {updates};
|
||||
"""
|
||||
await self.execute_sql(query=query, parameters=parameters)
|
||||
return feedback.id
|
||||
|
||||
async def delete_feedback(self, feedback_id: str) -> bool:
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: delete_feedback, feedback_id={feedback_id}")
|
||||
query = """DELETE FROM feedbacks WHERE "id" = :feedback_id"""
|
||||
parameters = {"feedback_id": feedback_id}
|
||||
await self.execute_sql(query=query, parameters=parameters)
|
||||
return True
|
||||
|
||||
###### Elements ######
|
||||
async def get_element(
|
||||
self, thread_id: str, element_id: str
|
||||
) -> Optional["ElementDict"]:
|
||||
if self.show_logger:
|
||||
logger.info(
|
||||
f"SQLAlchemy: get_element, thread_id={thread_id}, element_id={element_id}"
|
||||
)
|
||||
query = """SELECT * FROM elements WHERE "threadId" = :thread_id AND "id" = :element_id"""
|
||||
parameters = {"thread_id": thread_id, "element_id": element_id}
|
||||
element: Union[List[Dict[str, Any]], int, None] = await self.execute_sql(
|
||||
query=query, parameters=parameters
|
||||
)
|
||||
if isinstance(element, list) and element:
|
||||
element_dict: Dict[str, Any] = element[0]
|
||||
return ElementDict(
|
||||
id=element_dict["id"],
|
||||
threadId=element_dict.get("threadId"),
|
||||
type=element_dict["type"],
|
||||
chainlitKey=element_dict.get("chainlitKey"),
|
||||
url=element_dict.get("url"),
|
||||
objectKey=element_dict.get("objectKey"),
|
||||
name=element_dict["name"],
|
||||
display=element_dict["display"],
|
||||
size=element_dict.get("size"),
|
||||
language=element_dict.get("language"),
|
||||
page=element_dict.get("page"),
|
||||
autoPlay=element_dict.get("autoPlay"),
|
||||
playerConfig=element_dict.get("playerConfig"),
|
||||
forId=element_dict.get("forId"),
|
||||
mime=element_dict.get("mime"),
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
@queue_until_user_message()
|
||||
async def create_element(self, element: "Element"):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: create_element, element_id = {element.id}")
|
||||
|
||||
if not self.storage_provider:
|
||||
logger.warn(
|
||||
"SQLAlchemy: create_element error. No blob_storage_client is configured!"
|
||||
)
|
||||
return
|
||||
if not element.for_id:
|
||||
return
|
||||
|
||||
content: Optional[Union[bytes, str]] = None
|
||||
|
||||
if element.path:
|
||||
async with aiofiles.open(element.path, "rb") as f:
|
||||
content = await f.read()
|
||||
elif element.url:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(element.url) as response:
|
||||
if response.status == 200:
|
||||
content = await response.read()
|
||||
else:
|
||||
content = None
|
||||
elif element.content:
|
||||
content = element.content
|
||||
else:
|
||||
raise ValueError("Element url, path or content must be provided")
|
||||
if content is None:
|
||||
raise ValueError("Content is None, cannot upload file")
|
||||
|
||||
user_id: str = await self._get_user_id_by_thread(element.thread_id) or "unknown"
|
||||
file_object_key = f"{user_id}/{element.id}" + (
|
||||
f"/{element.name}" if element.name else ""
|
||||
)
|
||||
|
||||
if not element.mime:
|
||||
element.mime = "application/octet-stream"
|
||||
|
||||
uploaded_file = await self.storage_provider.upload_file(
|
||||
object_key=file_object_key, data=content, mime=element.mime, overwrite=True
|
||||
)
|
||||
if not uploaded_file:
|
||||
raise ValueError(
|
||||
"SQLAlchemy Error: create_element, Failed to persist data in storage_provider"
|
||||
)
|
||||
|
||||
element_dict: ElementDict = element.to_dict()
|
||||
|
||||
element_dict["url"] = uploaded_file.get("url")
|
||||
element_dict["objectKey"] = uploaded_file.get("object_key")
|
||||
element_dict_cleaned = {k: v for k, v in element_dict.items() if v is not None}
|
||||
|
||||
columns = ", ".join(f'"{column}"' for column in element_dict_cleaned.keys())
|
||||
placeholders = ", ".join(f":{column}" for column in element_dict_cleaned.keys())
|
||||
query = f"INSERT INTO elements ({columns}) VALUES ({placeholders})"
|
||||
await self.execute_sql(query=query, parameters=element_dict_cleaned)
|
||||
|
||||
@queue_until_user_message()
|
||||
async def delete_element(self, element_id: str, thread_id: Optional[str] = None):
|
||||
if self.show_logger:
|
||||
logger.info(f"SQLAlchemy: delete_element, element_id={element_id}")
|
||||
query = """DELETE FROM elements WHERE "id" = :id"""
|
||||
parameters = {"id": element_id}
|
||||
await self.execute_sql(query=query, parameters=parameters)
|
||||
|
||||
async def get_all_user_threads(
|
||||
self, user_id: Optional[str] = None, thread_id: Optional[str] = None
|
||||
) -> Optional[List[ThreadDict]]:
|
||||
"""Fetch all user threads up to self.user_thread_limit, or one thread by id if thread_id is provided."""
|
||||
if self.show_logger:
|
||||
logger.info("SQLAlchemy: get_all_user_threads")
|
||||
user_threads_query = """
|
||||
SELECT
|
||||
"id" AS thread_id,
|
||||
"createdAt" AS thread_createdat,
|
||||
"name" AS thread_name,
|
||||
"userId" AS user_id,
|
||||
"userIdentifier" AS user_identifier,
|
||||
"tags" AS thread_tags,
|
||||
"metadata" AS thread_metadata
|
||||
FROM threads
|
||||
WHERE "userId" = :user_id OR "id" = :thread_id
|
||||
ORDER BY "createdAt" DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
user_threads = await self.execute_sql(
|
||||
query=user_threads_query,
|
||||
parameters={
|
||||
"user_id": user_id,
|
||||
"limit": self.user_thread_limit,
|
||||
"thread_id": thread_id,
|
||||
},
|
||||
)
|
||||
if not isinstance(user_threads, list):
|
||||
return None
|
||||
if not user_threads:
|
||||
return []
|
||||
else:
|
||||
thread_ids = (
|
||||
"('"
|
||||
+ "','".join(map(str, [thread["thread_id"] for thread in user_threads]))
|
||||
+ "')"
|
||||
)
|
||||
|
||||
steps_feedbacks_query = f"""
|
||||
SELECT
|
||||
s."id" AS step_id,
|
||||
s."name" AS step_name,
|
||||
s."type" AS step_type,
|
||||
s."threadId" AS step_threadid,
|
||||
s."parentId" AS step_parentid,
|
||||
s."streaming" AS step_streaming,
|
||||
s."waitForAnswer" AS step_waitforanswer,
|
||||
s."isError" AS step_iserror,
|
||||
s."metadata" AS step_metadata,
|
||||
s."tags" AS step_tags,
|
||||
s."input" AS step_input,
|
||||
s."output" AS step_output,
|
||||
s."createdAt" AS step_createdat,
|
||||
s."start" AS step_start,
|
||||
s."end" AS step_end,
|
||||
s."generation" AS step_generation,
|
||||
s."showInput" AS step_showinput,
|
||||
s."language" AS step_language,
|
||||
s."indent" AS step_indent,
|
||||
f."value" AS feedback_value,
|
||||
f."comment" AS feedback_comment,
|
||||
f."id" AS feedback_id
|
||||
FROM steps s LEFT JOIN feedbacks f ON s."id" = f."forId"
|
||||
WHERE s."threadId" IN {thread_ids}
|
||||
ORDER BY s."createdAt" ASC
|
||||
"""
|
||||
steps_feedbacks = await self.execute_sql(
|
||||
query=steps_feedbacks_query, parameters={}
|
||||
)
|
||||
|
||||
elements_query = f"""
|
||||
SELECT
|
||||
e."id" AS element_id,
|
||||
e."threadId" as element_threadid,
|
||||
e."type" AS element_type,
|
||||
e."chainlitKey" AS element_chainlitkey,
|
||||
e."url" AS element_url,
|
||||
e."objectKey" as element_objectkey,
|
||||
e."name" AS element_name,
|
||||
e."display" AS element_display,
|
||||
e."size" AS element_size,
|
||||
e."language" AS element_language,
|
||||
e."page" AS element_page,
|
||||
e."forId" AS element_forid,
|
||||
e."mime" AS element_mime
|
||||
FROM elements e
|
||||
WHERE e."threadId" IN {thread_ids}
|
||||
"""
|
||||
elements = await self.execute_sql(query=elements_query, parameters={})
|
||||
|
||||
thread_dicts = {}
|
||||
for thread in user_threads:
|
||||
thread_id = thread["thread_id"]
|
||||
if thread_id is not None:
|
||||
# Ensure metadata is a dictionary
|
||||
metadata = thread["thread_metadata"]
|
||||
if isinstance(metadata, str):
|
||||
try:
|
||||
metadata = json.loads(metadata)
|
||||
except json.JSONDecodeError:
|
||||
metadata = {}
|
||||
elif metadata is None:
|
||||
metadata = {}
|
||||
|
||||
thread_dicts[thread_id] = ThreadDict(
|
||||
id=thread_id,
|
||||
createdAt=thread["thread_createdat"],
|
||||
name=thread["thread_name"],
|
||||
userId=thread["user_id"],
|
||||
userIdentifier=thread["user_identifier"],
|
||||
tags=thread["thread_tags"],
|
||||
metadata=metadata,
|
||||
steps=[],
|
||||
elements=[],
|
||||
)
|
||||
# Process steps_feedbacks to populate the steps in the corresponding ThreadDict
|
||||
if isinstance(steps_feedbacks, list):
|
||||
for step_feedback in steps_feedbacks:
|
||||
thread_id = step_feedback["step_threadid"]
|
||||
if thread_id is not None:
|
||||
feedback = None
|
||||
if step_feedback["feedback_value"] is not None:
|
||||
feedback = FeedbackDict(
|
||||
forId=step_feedback["step_id"],
|
||||
id=step_feedback.get("feedback_id"),
|
||||
value=step_feedback["feedback_value"],
|
||||
comment=step_feedback.get("feedback_comment"),
|
||||
)
|
||||
step_dict = StepDict(
|
||||
id=step_feedback["step_id"],
|
||||
name=step_feedback["step_name"],
|
||||
type=step_feedback["step_type"],
|
||||
threadId=thread_id,
|
||||
parentId=step_feedback.get("step_parentid"),
|
||||
streaming=step_feedback.get("step_streaming", False),
|
||||
waitForAnswer=step_feedback.get("step_waitforanswer"),
|
||||
isError=step_feedback.get("step_iserror"),
|
||||
metadata=(
|
||||
step_feedback["step_metadata"]
|
||||
if step_feedback.get("step_metadata") is not None
|
||||
else {}
|
||||
),
|
||||
tags=step_feedback.get("step_tags"),
|
||||
input=(
|
||||
step_feedback.get("step_input", "")
|
||||
if step_feedback.get("step_showinput")
|
||||
not in [None, "false"]
|
||||
else ""
|
||||
),
|
||||
output=step_feedback.get("step_output", ""),
|
||||
createdAt=step_feedback.get("step_createdat"),
|
||||
start=step_feedback.get("step_start"),
|
||||
end=step_feedback.get("step_end"),
|
||||
generation=step_feedback.get("step_generation"),
|
||||
showInput=step_feedback.get("step_showinput"),
|
||||
language=step_feedback.get("step_language"),
|
||||
indent=step_feedback.get("step_indent"),
|
||||
feedback=feedback,
|
||||
)
|
||||
# Append the step to the steps list of the corresponding ThreadDict
|
||||
thread_dicts[thread_id]["steps"].append(step_dict)
|
||||
|
||||
if isinstance(elements, list):
|
||||
for element in elements:
|
||||
thread_id = element["element_threadid"]
|
||||
if thread_id is not None:
|
||||
element_dict = ElementDict(
|
||||
id=element["element_id"],
|
||||
threadId=thread_id,
|
||||
type=element["element_type"],
|
||||
chainlitKey=element.get("element_chainlitkey"),
|
||||
url=element.get("element_url"),
|
||||
objectKey=element.get("element_objectkey"),
|
||||
name=element["element_name"],
|
||||
display=element["element_display"],
|
||||
size=element.get("element_size"),
|
||||
language=element.get("element_language"),
|
||||
autoPlay=element.get("element_autoPlay"),
|
||||
playerConfig=element.get("element_playerconfig"),
|
||||
page=element.get("element_page"),
|
||||
forId=element.get("element_forid"),
|
||||
mime=element.get("element_mime"),
|
||||
)
|
||||
thread_dicts[thread_id]["elements"].append(element_dict) # type: ignore
|
||||
|
||||
return list(thread_dicts.values())</code></pre>
|
||||
</details>
|
||||
<h3>Ancestors</h3>
|
||||
<ul class="hlist">
|
||||
<li>chainlit.data.base.BaseDataLayer</li>
|
||||
<li>abc.ABC</li>
|
||||
</ul>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.build_debug_url"><code class="name flex">
|
||||
<span>async def <span class="ident">build_debug_url</span></span>(<span>self) ‑> str</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.clean_result"><code class="name flex">
|
||||
<span>def <span class="ident">clean_result</span></span>(<span>self, obj)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Recursively change UUID -> str and serialize dictionaries</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_element"><code class="name flex">
|
||||
<span>async def <span class="ident">create_element</span></span>(<span>self, element: Element)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_step"><code class="name flex">
|
||||
<span>async def <span class="ident">create_step</span></span>(<span>self, step_dict: StepDict)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_user"><code class="name flex">
|
||||
<span>async def <span class="ident">create_user</span></span>(<span>self, user: chainlit.user.User) ‑> Optional[chainlit.user.PersistedUser]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_element"><code class="name flex">
|
||||
<span>async def <span class="ident">delete_element</span></span>(<span>self, element_id: str, thread_id: Optional[str] = None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_feedback"><code class="name flex">
|
||||
<span>async def <span class="ident">delete_feedback</span></span>(<span>self, feedback_id: str) ‑> bool</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_step"><code class="name flex">
|
||||
<span>async def <span class="ident">delete_step</span></span>(<span>self, step_id: str)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_thread"><code class="name flex">
|
||||
<span>async def <span class="ident">delete_thread</span></span>(<span>self, thread_id: str)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.execute_sql"><code class="name flex">
|
||||
<span>async def <span class="ident">execute_sql</span></span>(<span>self, query: str, parameters: dict) ‑> Union[List[Dict[str, Any]], int, ForwardRef(None)]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_all_user_threads"><code class="name flex">
|
||||
<span>async def <span class="ident">get_all_user_threads</span></span>(<span>self, user_id: Optional[str] = None, thread_id: Optional[str] = None) ‑> Optional[List[chainlit.types.ThreadDict]]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Fetch all user threads up to self.user_thread_limit, or one thread by id if thread_id is provided.</p></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_current_timestamp"><code class="name flex">
|
||||
<span>async def <span class="ident">get_current_timestamp</span></span>(<span>self) ‑> str</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_element"><code class="name flex">
|
||||
<span>async def <span class="ident">get_element</span></span>(<span>self, thread_id: str, element_id: str) ‑> Optional[chainlit.element.ElementDict]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread"><code class="name flex">
|
||||
<span>async def <span class="ident">get_thread</span></span>(<span>self, thread_id: str) ‑> Optional[chainlit.types.ThreadDict]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread_author"><code class="name flex">
|
||||
<span>async def <span class="ident">get_thread_author</span></span>(<span>self, thread_id: str) ‑> str</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_user"><code class="name flex">
|
||||
<span>async def <span class="ident">get_user</span></span>(<span>self, identifier: str) ‑> Optional[chainlit.user.PersistedUser]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.list_threads"><code class="name flex">
|
||||
<span>async def <span class="ident">list_threads</span></span>(<span>self, pagination: chainlit.types.Pagination, filters: chainlit.types.ThreadFilter) ‑> chainlit.types.PaginatedResponse</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_step"><code class="name flex">
|
||||
<span>async def <span class="ident">update_step</span></span>(<span>self, step_dict: StepDict)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_thread"><code class="name flex">
|
||||
<span>async def <span class="ident">update_thread</span></span>(<span>self, thread_id: str, name: Optional[str] = None, user_id: Optional[str] = None, metadata: Optional[Dict] = None, tags: Optional[List[str]] = None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.upsert_feedback"><code class="name flex">
|
||||
<span>async def <span class="ident">upsert_feedback</span></span>(<span>self, feedback: chainlit.types.Feedback) ‑> str</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai.ui" href="index.html">praisonai.ui</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer">SQLAlchemyDataLayer</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.build_debug_url" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.build_debug_url">build_debug_url</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.clean_result" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.clean_result">clean_result</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_element" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_element">create_element</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_step" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_step">create_step</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_user" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_user">create_user</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_element" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_element">delete_element</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_feedback" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_feedback">delete_feedback</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_step" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_step">delete_step</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_thread" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_thread">delete_thread</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.execute_sql" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.execute_sql">execute_sql</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_all_user_threads" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_all_user_threads">get_all_user_threads</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_current_timestamp" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_current_timestamp">get_current_timestamp</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_element" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_element">get_element</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread">get_thread</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread_author" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread_author">get_thread_author</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_user" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_user">get_user</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.list_threads" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.list_threads">list_threads</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_step" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_step">update_step</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_thread" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_thread">update_thread</a></code></li>
|
||||
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.upsert_feedback" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.upsert_feedback">upsert_feedback</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,55 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta name="generator" content="pdoc3 0.11.1">
|
||||
<title>praisonai.version API documentation</title>
|
||||
<meta name="description" content="">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||||
hljs.highlightAll();
|
||||
})</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>praisonai.version</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
</article>
|
||||
<nav id="sidebar">
|
||||
<div class="toc">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<ul id="index">
|
||||
<li><h3>Super-module</h3>
|
||||
<ul>
|
||||
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,79 +0,0 @@
|
||||
---
|
||||
title: "Agent Module"
|
||||
description: "Documentation for the praisonaiagents.agent.agent module"
|
||||
icon: "user"
|
||||
---
|
||||
|
||||
# Module praisonaiagents.agent.agent
|
||||
|
||||
## Classes
|
||||
|
||||
### Agent
|
||||
The main class representing an AI agent with specific role, goal, and capabilities.
|
||||
|
||||
#### Parameters
|
||||
- `name: str` - Name of the agent
|
||||
- `role: str` - Role of the agent
|
||||
- `goal: str` - Goal the agent aims to achieve
|
||||
- `backstory: str` - Background story of the agent
|
||||
- `llm: str | Any | None = 'gpt-4o'` - Language model to use
|
||||
- `tools: List[Any] | None = None` - List of tools available to the agent
|
||||
- `function_calling_llm: Any | None = None` - LLM for function calling
|
||||
- `max_iter: int = 20` - Maximum iterations
|
||||
- `max_rpm: int | None = None` - Maximum requests per minute
|
||||
- `max_execution_time: int | None = None` - Maximum execution time
|
||||
- `memory: bool = True` - Enable memory
|
||||
- `verbose: bool = True` - Enable verbose output
|
||||
- `allow_delegation: bool = False` - Allow task delegation
|
||||
- `step_callback: Any | None = None` - Callback for each step
|
||||
- `cache: bool = True` - Enable caching
|
||||
- `system_template: str | None = None` - System prompt template
|
||||
- `prompt_template: str | None = None` - Prompt template
|
||||
- `response_template: str | None = None` - Response template
|
||||
- `allow_code_execution: bool | None = False` - Allow code execution
|
||||
- `max_retry_limit: int = 2` - Maximum retry attempts
|
||||
- `respect_context_window: bool = True` - Respect context window size
|
||||
- `code_execution_mode: Literal['safe', 'unsafe'] = 'safe'` - Code execution mode
|
||||
- `embedder_config: Dict[str, Any] | None = None` - Embedder configuration
|
||||
- `knowledge_sources: List[Any] | None = None` - Knowledge sources
|
||||
- `use_system_prompt: bool | None = True` - Use system prompt
|
||||
- `markdown: bool = True` - Enable markdown
|
||||
- `self_reflect: bool = True` - Enable self reflection
|
||||
- `max_reflect: int = 3` - Maximum reflections
|
||||
- `min_reflect: int = 1` - Minimum reflections
|
||||
- `reflect_llm: str | None = None` - LLM for reflection
|
||||
|
||||
#### Methods
|
||||
- `chat(self, prompt, temperature=0.2, tools=None, output_json=None)` - Chat with the agent
|
||||
- `achat(self, prompt, temperature=0.2, tools=None, output_json=None)` - Async version of chat method
|
||||
- `clean_json_output(self, output: str) → str` - Clean and extract JSON from response text
|
||||
- `clear_history(self)` - Clear chat history
|
||||
- `execute_tool(self, function_name, arguments)` - Execute a tool dynamically based on the function name and arguments
|
||||
- `_achat_completion(self, response, tools)` - Async version of _chat_completion method
|
||||
|
||||
#### Async Support
|
||||
The Agent class provides async support through the following methods:
|
||||
|
||||
- `achat`: Async version of the chat method for non-blocking communication
|
||||
- `_achat_completion`: Internal async method for handling chat completions
|
||||
|
||||
Example usage:
|
||||
```python
|
||||
async def main():
|
||||
agent = Agent(
|
||||
name="AsyncAgent",
|
||||
role="Async Specialist",
|
||||
goal="Handle async operations",
|
||||
backstory="Expert in async processing"
|
||||
)
|
||||
|
||||
# Use async chat
|
||||
result = await agent.achat(
|
||||
prompt="Your prompt here",
|
||||
tools=your_tools,
|
||||
output_json=your_schema
|
||||
)
|
||||
print(result)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
@@ -1,113 +0,0 @@
|
||||
---
|
||||
title: "Agents Module"
|
||||
description: "Documentation for the praisonaiagents.agents.agents module"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
# Module praisonaiagents.agents.agents
|
||||
|
||||
## Functions
|
||||
|
||||
### encode_file_to_base64(file_path: str) → str
|
||||
Base64-encode a file.
|
||||
|
||||
### process_video(video_path: str, seconds_per_frame=2)
|
||||
Split video into frames (base64-encoded).
|
||||
|
||||
## Classes
|
||||
|
||||
### LoopItems
|
||||
A Pydantic model for handling loop items.
|
||||
|
||||
#### Class Variables
|
||||
- `items: List[Any]` - List of items to loop through
|
||||
- `model_config` - Model configuration
|
||||
|
||||
### PraisonAIAgents
|
||||
The main class for managing agents and tasks execution.
|
||||
|
||||
#### Parameters
|
||||
- `agents: List[Agent]` - List of agents
|
||||
- `tasks: List[Task]` - List of tasks
|
||||
- `verbose: int = 0` - Verbosity level
|
||||
- `completion_checker: Optional[Callable] = None` - Custom completion checker
|
||||
- `max_retries: int = 5` - Maximum retry attempts
|
||||
- `process: str = "sequential"` - Process type (sequential, workflow, hierarchical)
|
||||
- `manager_llm: Optional[str] = None` - Language model for manager agent
|
||||
|
||||
#### Methods
|
||||
- `add_task(self, task)` - Add a task to the crew
|
||||
- `clean_json_output(self, output: str) → str` - Clean JSON output
|
||||
- `clear_state(self) → None` - Clear all state values
|
||||
- `default_completion_checker(self, task, agent_output)` - Default completion checker
|
||||
- `execute_task(self, task_id)` - Execute a specific task
|
||||
- `get_agent_details(self, agent_name)` - Get agent details
|
||||
- `get_all_tasks_status(self)` - Get status of all tasks
|
||||
- `get_state(self, key: str, default: Any = None) → Any` - Get a state value
|
||||
- `get_task_details(self, task_id)` - Get task details
|
||||
- `get_task_result(self, task_id)` - Get task result
|
||||
- `get_task_status(self, task_id)` - Get task status
|
||||
- `run_all_tasks(self)` - Execute tasks based on execution mode
|
||||
- `run_task(self, task_id)` - Run a specific task
|
||||
- `save_output_to_file(self, task, task_output)` - Save task output to file
|
||||
- `set_state(self, key: str, value: Any) → None` - Set a state value
|
||||
- `start(self)` - Start the crew execution
|
||||
- `update_state(self, updates: Dict) → None` - Update multiple state values
|
||||
|
||||
#### Async Methods
|
||||
- `astart(self)` - Async version of start method
|
||||
- `aexecute_task(self, task_id)` - Async version of execute_task
|
||||
- `arun_task(self, task_id)` - Async version of run_task
|
||||
- `arun_all_tasks(self)` - Async version of run_all_tasks
|
||||
|
||||
#### Async Support
|
||||
The PraisonAIAgents class provides comprehensive async support through the following methods:
|
||||
|
||||
```python
|
||||
class PraisonAIAgents:
|
||||
async def astart(self):
|
||||
"""Async version of start method"""
|
||||
await self.arun_all_tasks()
|
||||
return {
|
||||
"task_status": self.get_all_tasks_status(),
|
||||
"task_results": self.get_task_results()
|
||||
}
|
||||
|
||||
async def aexecute_task(self, task_id):
|
||||
"""Async version of execute_task method"""
|
||||
# Async task execution implementation
|
||||
|
||||
async def arun_task(self, task_id):
|
||||
"""Async version of run_task method"""
|
||||
# Async task running with retries
|
||||
|
||||
async def arun_all_tasks(self):
|
||||
"""Async version of run_all_tasks method"""
|
||||
# Async execution of all tasks
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python
|
||||
async def main():
|
||||
# Initialize agents and tasks
|
||||
agents = PraisonAIAgents(
|
||||
agents=[async_agent1, async_agent2],
|
||||
tasks=[async_task1, async_task2],
|
||||
process="workflow"
|
||||
)
|
||||
|
||||
# Start async execution
|
||||
result = await agents.astart()
|
||||
print(result)
|
||||
|
||||
# Run the async workflow
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
#### Async Features
|
||||
- Full async/await support
|
||||
- Parallel task execution
|
||||
- Non-blocking operations
|
||||
- Efficient resource utilization
|
||||
- Mixed sync/async task handling
|
||||
- Async process management
|
||||
@@ -1,187 +0,0 @@
|
||||
---
|
||||
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,52 +0,0 @@
|
||||
---
|
||||
title: "API Reference"
|
||||
description: "Praison AI Agents - SDK Documentation"
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent" icon="user" href="/api/praisonaiagents/agent/agent">
|
||||
Documentation for individual AI agents and their capabilities
|
||||
</Card>
|
||||
<Card title="Agents" icon="users" href="/api/praisonaiagents/agents/agents">
|
||||
Documentation for managing multiple agents and their interactions
|
||||
</Card>
|
||||
<Card title="Task" icon="list-check" href="/api/praisonaiagents/task/task">
|
||||
Documentation for defining and managing tasks
|
||||
</Card>
|
||||
<Card title="Process" icon="diagram-project" href="/api/praisonaiagents/process/process">
|
||||
Documentation for handling task execution flows
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
# Module praisonaiagents
|
||||
|
||||
## Sub-modules
|
||||
* praisonaiagents.agent - Agent module for defining individual AI agents
|
||||
* praisonaiagents.agents - Agents module for managing multiple agents
|
||||
* praisonaiagents.task - Task module for defining and managing tasks
|
||||
* praisonaiagents.process - Process module for handling task execution flows
|
||||
* praisonaiagents.main - Main module containing utility functions
|
||||
|
||||
## Functions
|
||||
|
||||
### clean_triple_backticks(text: str) → str
|
||||
Clean triple backticks from text output.
|
||||
|
||||
### display_error(message: str, console=None)
|
||||
Display error messages in the console.
|
||||
|
||||
### display_generating(content: str = '', start_time: float | None = None)
|
||||
Display generation status with optional timing information.
|
||||
|
||||
### display_instruction(message: str, console=None)
|
||||
Display instruction messages in the console.
|
||||
|
||||
### display_interaction(message, response, markdown=True, generation_time=None, console=None)
|
||||
Display interaction between user and agent.
|
||||
|
||||
### display_self_reflection(message: str, console=None)
|
||||
Display agent self-reflection messages.
|
||||
|
||||
### display_tool_call(message: str, console=None)
|
||||
Display tool call messages.
|
||||
@@ -1,98 +0,0 @@
|
||||
---
|
||||
title: "Process Module"
|
||||
description: "Documentation for the praisonaiagents.process.process module"
|
||||
icon: "diagram-project"
|
||||
---
|
||||
|
||||
# Module praisonaiagents.process.process
|
||||
|
||||
## Classes
|
||||
|
||||
### Process
|
||||
The main class for handling task execution processes in different modes (sequential, hierarchical, workflow).
|
||||
|
||||
#### Parameters
|
||||
- `tasks: Dict[str, Task]` - Dictionary of tasks to be executed
|
||||
- `agents: List[Agent]` - List of available agents
|
||||
- `manager_llm: Optional[str] = None` - Language model for manager agent in hierarchical process
|
||||
- `verbose: bool = False` - Enable verbose logging
|
||||
|
||||
#### Methods
|
||||
- `workflow(self)` - Execute tasks in a workflow pattern with support for loops and conditions
|
||||
- `sequential(self)` - Execute tasks in sequential order
|
||||
- `hierarchical(self)` - Execute tasks in hierarchical order with a manager agent
|
||||
|
||||
#### Async Methods
|
||||
- `aworkflow(self) -> AsyncGenerator[str, None]` - Async version of workflow process
|
||||
- `asequential(self) -> AsyncGenerator[str, None]` - Async version of sequential process
|
||||
- `ahierarchical(self) -> AsyncGenerator[str, None]` - Async version of hierarchical process
|
||||
|
||||
#### Async Process Support
|
||||
Each process type has an async counterpart that supports non-blocking execution:
|
||||
|
||||
```python
|
||||
class Process:
|
||||
async def aworkflow(self):
|
||||
"""Async workflow process execution"""
|
||||
# Async workflow implementation
|
||||
|
||||
async def asequential(self):
|
||||
"""Async sequential process execution"""
|
||||
# Async sequential implementation
|
||||
|
||||
async def ahierarchical(self):
|
||||
"""Async hierarchical process execution"""
|
||||
# Async hierarchical implementation
|
||||
```
|
||||
|
||||
Example usage:
|
||||
```python
|
||||
# Create process instance
|
||||
process = Process(tasks=tasks, agents=agents)
|
||||
|
||||
# Use async workflow
|
||||
async for task_id in process.aworkflow():
|
||||
# Handle task execution
|
||||
if tasks[task_id].async_execution:
|
||||
await handle_async_task(task_id)
|
||||
else:
|
||||
handle_sync_task(task_id)
|
||||
```
|
||||
|
||||
#### Async Process Features
|
||||
- Non-blocking task execution
|
||||
- Parallel task processing
|
||||
- Mixed sync/async task support
|
||||
- Efficient resource utilization
|
||||
- Async manager coordination (hierarchical)
|
||||
- Dynamic task scheduling (workflow)
|
||||
|
||||
### LoopItems
|
||||
A Pydantic model for handling loop data in workflow process.
|
||||
|
||||
#### Parameters
|
||||
- `items: List[Any]` - List of items to be processed in a loop
|
||||
|
||||
## Process Types
|
||||
|
||||
### Sequential Process
|
||||
- Tasks are executed one after another in a linear fashion
|
||||
- Each task is completed before moving to the next one
|
||||
- Simplest form of task execution
|
||||
|
||||
### Hierarchical Process
|
||||
- Uses a manager agent to coordinate task execution
|
||||
- Manager decides task order and agent assignments
|
||||
- Provides more complex task orchestration
|
||||
- Requires manager_llm parameter
|
||||
- Supports dynamic agent assignment
|
||||
|
||||
### Workflow Process
|
||||
- Supports complex task relationships
|
||||
- Features:
|
||||
- Task dependencies
|
||||
- Conditional execution
|
||||
- Loops
|
||||
- Context sharing between tasks
|
||||
- Maintains task state and relationships
|
||||
- Handles data flow between tasks
|
||||
@@ -1,78 +0,0 @@
|
||||
---
|
||||
title: "Task Module"
|
||||
description: "Documentation for the praisonaiagents.task.task module"
|
||||
icon: "list-check"
|
||||
---
|
||||
|
||||
# Module praisonaiagents.task.task
|
||||
|
||||
## Classes
|
||||
|
||||
### Task
|
||||
Represents a task to be executed by an agent.
|
||||
|
||||
#### Parameters
|
||||
- `description: str` - Task description
|
||||
- `expected_output: str` - Expected output description
|
||||
- `agent: Agent | None = None` - Agent assigned to the task
|
||||
- `name: str | None = None` - Task name
|
||||
- `tools: List[Any] | None = None` - Tools available for the task
|
||||
- `context: List[Task] | None = None` - Context from other tasks
|
||||
- `async_execution: bool | None = False` - Enable async execution
|
||||
- `config: Dict[str, Any] | None = None` - Task configuration
|
||||
- `output_file: str | None = None` - Output file path
|
||||
- `output_json: Type[BaseModel] | None = None` - JSON output schema
|
||||
- `output_pydantic: Type[BaseModel] | None = None` - Pydantic output schema
|
||||
- `callback: Any | None = None` - Task callback
|
||||
- `status: str = 'not started'` - Task status
|
||||
- `result: TaskOutput | None = None` - Task result
|
||||
- `create_directory: bool | None = False` - Create output directory
|
||||
- `id: int | None = None` - Task ID
|
||||
- `images: List[str] | None = None` - Task images
|
||||
- `next_tasks: List[str] | None = None` - Next tasks
|
||||
- `task_type: str = 'task'` - Task type
|
||||
- `condition: Dict[str, List[str]] | None = None` - Task conditions
|
||||
- `is_start: bool = False` - Is start task
|
||||
- `loop_state: Dict[str, str | int] | None = None` - Loop state
|
||||
|
||||
#### Async Support
|
||||
The Task class supports asynchronous execution through the following features:
|
||||
|
||||
- `async_execution`: Boolean flag to enable async execution
|
||||
- `callback`: Supports both sync and async callback functions
|
||||
- `execute_callback`: Internal async method for handling callbacks
|
||||
|
||||
Example usage:
|
||||
```python
|
||||
from typing import Coroutine
|
||||
from praisonaiagents import Task, TaskOutput
|
||||
|
||||
# Define an async callback
|
||||
async def async_callback(output: TaskOutput):
|
||||
await some_async_operation()
|
||||
print(f"Processed: {output.raw}")
|
||||
|
||||
# Create task with async execution
|
||||
task = Task(
|
||||
description="Async task example",
|
||||
expected_output="Async result",
|
||||
async_execution=True, # Enable async execution
|
||||
callback=async_callback # Async callback
|
||||
)
|
||||
```
|
||||
|
||||
#### Callback Types
|
||||
The Task class supports both synchronous and asynchronous callbacks:
|
||||
```python
|
||||
# Type definition
|
||||
callback: Optional[Union[
|
||||
Callable[[TaskOutput], Any], # Sync callback
|
||||
Callable[[TaskOutput], Coroutine[Any, Any, Any]] # Async callback
|
||||
]]
|
||||
```
|
||||
|
||||
#### Async Task States
|
||||
- `not started`: Initial state
|
||||
- `in progress`: Task is being executed
|
||||
- `completed`: Task finished successfully
|
||||
- `failed`: Task execution failed
|
||||
-126
@@ -1,126 +0,0 @@
|
||||
---
|
||||
title: "PraisonAI Call"
|
||||
description: "Guide to PraisonAI's voice-based interaction feature enabling AI customer service through phone calls, including setup and tool integration"
|
||||
icon: "phone"
|
||||
---
|
||||
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/m1cwrUG2iAk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
|
||||
## AI Customer Service
|
||||
|
||||
PraisonAI Call is a feature that enables voice-based interaction with AI models through phone calls. This functionality allows users to have natural conversations with AI agents over traditional phone lines.
|
||||
|
||||
## Installation
|
||||
|
||||
### Step 1
|
||||
|
||||
```bash
|
||||
pip install "praisonai[call]"
|
||||
export OPENAI_API_KEY="enter your openai api key here"
|
||||
export NGROK_AUTH_TOKEN="enter your ngrok auth token here"
|
||||
praisonai call --public
|
||||
```
|
||||
|
||||
### Step 2
|
||||
|
||||
Buy a number at [PraisonAI Dashboard](https://dashboard.praison.ai/)
|
||||
|
||||
### Step 3
|
||||
|
||||
Enter the Public URL in the PraisonAI Dashboard phone number field
|
||||
|
||||
## Features
|
||||
|
||||
- Make and receive phone calls with AI agents
|
||||
- Natural language processing for voice interactions
|
||||
- Support for multiple phone carriers and providers
|
||||
- Call recording and transcription capabilities
|
||||
- Integration with other PraisonAI features
|
||||
|
||||
## Adding Tools
|
||||
|
||||
1. Create a file called `tools.py`
|
||||
2. Add the following code:
|
||||
```python
|
||||
import yfinance as yf
|
||||
|
||||
# Get Stock Price definition
|
||||
get_stock_price_def = {
|
||||
"name": "get_stock_price",
|
||||
"description": "Get the current stock price for a given ticker symbol",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ticker_symbol": {
|
||||
"type": "string",
|
||||
"description": "The ticker symbol of the stock (e.g., AAPL, GOOGL)"
|
||||
}
|
||||
},
|
||||
"required": ["ticker_symbol"]
|
||||
}
|
||||
}
|
||||
|
||||
# Get Stock Price function / Tool
|
||||
async def get_stock_price_handler(ticker_symbol):
|
||||
try:
|
||||
stock = yf.Ticker(ticker_symbol)
|
||||
hist = stock.history(period="1d")
|
||||
if hist.empty:
|
||||
return {"error": f"No data found for ticker {ticker_symbol}"}
|
||||
current_price = hist['Close'].iloc[-1] # Using -1 is safer than 0
|
||||
return {"price": str(current_price)}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
|
||||
get_stock_price = (get_stock_price_def, get_stock_price_handler)
|
||||
tools = [
|
||||
get_stock_price
|
||||
]
|
||||
```
|
||||
|
||||
3. ```bash
|
||||
pip install yfinance
|
||||
```
|
||||
|
||||
4. ```bash
|
||||
export OPENAI_API_KEY="enter your openai api key here"
|
||||
export NGROK_AUTH_TOKEN="enter your ngrok auth token here"
|
||||
praisonai call --public
|
||||
```
|
||||
|
||||
## Manage Google Calendar Events
|
||||
|
||||
See [Google Calendar Tools](tools/googlecalendar.md)
|
||||
|
||||
|
||||
## Deploy
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
```dockerfile
|
||||
# Use an official Python runtime as a parent image
|
||||
FROM python:3.11-slim
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
|
||||
# Set work directory
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install PraisonAI with the 'call' extra and ensure it's the latest version
|
||||
RUN pip install --no-cache-dir --upgrade "praisonai[call]"
|
||||
|
||||
# Expose the port the app runs on
|
||||
EXPOSE 8090
|
||||
|
||||
# Run the application
|
||||
CMD ["praisonai", "call"]
|
||||
```
|
||||
@@ -1,446 +0,0 @@
|
||||
---
|
||||
title: "Agents"
|
||||
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
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Role & Goal" icon="target">
|
||||
Defines the agent's purpose and objectives through role definition and specific goals
|
||||
</Card>
|
||||
<Card title="Capabilities" icon="toolbox">
|
||||
Tools and functions available to the agent for task execution
|
||||
</Card>
|
||||
<Card title="Memory" icon="brain">
|
||||
Context retention and learning capabilities across interactions
|
||||
</Card>
|
||||
<Card title="Language Model" icon="microchip">
|
||||
The underlying AI model powering the agent's intelligence
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Component Details
|
||||
|
||||
### Role and Goal
|
||||
<Tip>
|
||||
Clear role and goal definitions are crucial for optimal agent performance.
|
||||
</Tip>
|
||||
|
||||
| Component | Description | Example |
|
||||
|:----------|:------------|:--------|
|
||||
| **Role** | Agent's function and expertise | Research Analyst, Code Developer |
|
||||
| **Goal** | Specific objectives to achieve | Analyze market trends, Generate reports |
|
||||
| **Backstory** | Contextual background | Expert with 10 years of experience |
|
||||
|
||||
### Capabilities
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
agent = 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
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
<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>
|
||||
|
||||
<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
|
||||
|
||||
<Note>
|
||||
Always implement proper error handling and resource management in your agent configurations.
|
||||
</Note>
|
||||
|
||||
<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>
|
||||
|
||||
<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
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Memory Management" icon="brain">
|
||||
- Short-term conversation memory
|
||||
- Long-term knowledge retention
|
||||
- Context preservation
|
||||
</Card>
|
||||
<Card title="Tool Integration" icon="plug">
|
||||
- Custom tool development
|
||||
- External API integration
|
||||
- Resource access control
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Async Support
|
||||
Agents now support asynchronous operations through the following methods:
|
||||
|
||||
- `achat`: Async version of the chat method
|
||||
- `astart`: Async version of start method
|
||||
- `aexecute_task`: Async version of execute_task method
|
||||
- `arun_task`: Async version of run_task method
|
||||
- `arun_all_tasks`: Async version of run_all_tasks method
|
||||
|
||||
### Example Usage:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
async def main():
|
||||
# Create an async agent
|
||||
async_agent = Agent(
|
||||
name="AsyncAgent",
|
||||
role="Async Task Specialist",
|
||||
goal="Perform async operations",
|
||||
backstory="Expert in async operations",
|
||||
tools=[async_search_tool], # Your async tool
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create an async task
|
||||
async_task = Task(
|
||||
description="Perform async operation",
|
||||
expected_output="Async result",
|
||||
agent=async_agent,
|
||||
async_execution=True # Enable async execution
|
||||
)
|
||||
|
||||
# Create and start agents with async support
|
||||
agents = PraisonAIAgents(
|
||||
agents=[async_agent],
|
||||
tasks=[async_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Start async execution
|
||||
result = await agents.astart()
|
||||
print(result)
|
||||
|
||||
# Run the async main function
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### Key Features:
|
||||
- Full async/await support
|
||||
- Parallel task execution
|
||||
- Async tool integration
|
||||
- Async callback support
|
||||
- Mixed sync/async operations
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Create Your First Agent"
|
||||
icon="code"
|
||||
href="/code/quickstart"
|
||||
>
|
||||
Follow our quickstart guide to create your first agent
|
||||
</Card>
|
||||
<Card
|
||||
title="API Reference"
|
||||
icon="book"
|
||||
href="/api/praisonaiagents/agent/agent"
|
||||
>
|
||||
Explore the complete Agent API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -1,441 +0,0 @@
|
||||
---
|
||||
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"
|
||||
---
|
||||
|
||||
## 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>
|
||||
<Card title="Entity Memory" icon="diagram-project">
|
||||
- Store information about specific entities
|
||||
- Track relationships and attributes
|
||||
- Specialized search for entity information
|
||||
</Card>
|
||||
<Card title="User Memory" icon="user">
|
||||
- Store user-specific information
|
||||
- Personalized context for each user
|
||||
- Persistent across sessions
|
||||
</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
|
||||
)
|
||||
```
|
||||
@@ -1,375 +0,0 @@
|
||||
---
|
||||
title: "Process"
|
||||
description: "Understanding Process Types in PraisonAI"
|
||||
icon: "diagram-project"
|
||||
---
|
||||
|
||||
# Understanding Process Types
|
||||
|
||||
Process types in PraisonAI define how tasks are executed and how agents collaborate. Each process type offers different patterns for task execution and agent coordination.
|
||||
|
||||
## Process Types Overview
|
||||
|
||||
<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>
|
||||
|
||||
## Sequential Process
|
||||
|
||||
The simplest form of task execution where tasks are performed one after another.
|
||||
|
||||
<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"
|
||||
)
|
||||
```
|
||||
</Card>
|
||||
|
||||
## Hierarchical Process
|
||||
|
||||
Uses a manager agent to coordinate task execution and agent assignments.
|
||||
|
||||
<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"
|
||||
)
|
||||
```
|
||||
</Card>
|
||||
|
||||
## 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"
|
||||
src="https://www.youtube.com/embed/yWTH44QPl2A"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
<br />
|
||||
|
||||
## Advanced Features
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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 Processing
|
||||
|
||||
<Note>
|
||||
All process types support asynchronous execution through async generators, enabling efficient parallel processing and non-blocking operations.
|
||||
</Note>
|
||||
|
||||
### Core Async Methods
|
||||
|
||||
<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>
|
||||
|
||||
### Process-Specific Features
|
||||
|
||||
<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>
|
||||
|
||||
### Key Benefits
|
||||
|
||||
<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>
|
||||
@@ -1,503 +0,0 @@
|
||||
---
|
||||
title: "Tasks"
|
||||
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>
|
||||
|
||||
## Core Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Task Definition" icon="file-lines">
|
||||
Clear description of work to be done and expected outputs
|
||||
</Card>
|
||||
<Card title="Agent Assignment" icon="user-check">
|
||||
Matching tasks with capable agents
|
||||
</Card>
|
||||
<Card title="Tool Access" icon="toolbox">
|
||||
Resources available for task completion
|
||||
</Card>
|
||||
<Card title="Output Handling" icon="file-export">
|
||||
Managing and formatting task results
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## 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 Dependencies
|
||||
|
||||
| Relationship | Description | Example |
|
||||
|:-------------|:------------|:--------|
|
||||
| **Sequential** | Tasks run one after another | Research → Analysis → Report |
|
||||
| **Parallel** | Independent tasks run simultaneously | Data Collection + Processing |
|
||||
| **Conditional** | Tasks depend on previous results | Success → Next Task, Failure → Retry |
|
||||
|
||||
## Advanced Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Output Handling" icon="file-code">
|
||||
- Multiple output formats
|
||||
- Structured data validation
|
||||
- File system integration
|
||||
</Card>
|
||||
<Card title="Task Control" icon="sliders">
|
||||
- Execution flow control
|
||||
- Error recovery
|
||||
- Progress tracking
|
||||
</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
|
||||
|
||||
<Note>
|
||||
Design tasks to be atomic and focused. Each task should have a single, clear responsibility.
|
||||
</Note>
|
||||
|
||||
<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
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Create Tasks"
|
||||
icon="plus"
|
||||
href="/code/quickstart"
|
||||
>
|
||||
Learn how to create and configure tasks
|
||||
</Card>
|
||||
<Card
|
||||
title="Task API"
|
||||
icon="code"
|
||||
href="/api/praisonaiagents/task/task"
|
||||
>
|
||||
Explore the complete Task API documentation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -1,610 +0,0 @@
|
||||
---
|
||||
title: "Tools"
|
||||
description: "Understanding Tools in PraisonAI"
|
||||
icon: "screwdriver-wrench"
|
||||
---
|
||||
|
||||
# Understanding Tools
|
||||
|
||||
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.
|
||||
|
||||
## 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
|
||||
from typing import List, Dict
|
||||
|
||||
# Tool Implementation
|
||||
def internet_search_tool(query: str) -> List[Dict]:
|
||||
"""
|
||||
Perform Internet Search using DuckDuckGo
|
||||
|
||||
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
|
||||
```
|
||||
</Step>
|
||||
<Step>
|
||||
Assign the tool to an agent
|
||||
```python
|
||||
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], ## Add the tool to the agent i.e the function name
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Card title="That's it!">
|
||||
<Check>You have created a custom tool and assigned it to an agent.</Check>
|
||||
</Card>
|
||||
|
||||
## Implementing Tools Full Code Example
|
||||
<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`
|
||||
```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
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
# 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"
|
||||
)
|
||||
|
||||
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>
|
||||
```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
|
||||
|
||||
Returns:
|
||||
List[Dict]: Search results
|
||||
"""
|
||||
# Tool implementation
|
||||
pass
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Chaining
|
||||
<Frame>
|
||||
```python
|
||||
def chain_tools(input_data: str) -> Dict:
|
||||
"""
|
||||
Example of chaining multiple tools
|
||||
|
||||
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)
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Categories
|
||||
|
||||
<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>
|
||||
```python
|
||||
# Multiple tools
|
||||
agent = Agent(
|
||||
name="MultiTool Agent",
|
||||
tools=[
|
||||
internet_search_tool,
|
||||
file_processing_tool,
|
||||
api_integration_tool
|
||||
]
|
||||
)
|
||||
```
|
||||
</Frame>
|
||||
|
||||
### Tool Dependencies
|
||||
<Frame>
|
||||
```python
|
||||
# Tool with dependencies
|
||||
def advanced_tool(data: Dict) -> Dict:
|
||||
"""
|
||||
Tool that depends on external libraries
|
||||
|
||||
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")
|
||||
```
|
||||
</Frame>
|
||||
|
||||
## Tool Guidelines
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Best Practices">
|
||||
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
|
||||
|
||||
3. **Error Handling**
|
||||
- Handle exceptions gracefully
|
||||
- Return meaningful errors
|
||||
- Validate inputs
|
||||
</Card>
|
||||
|
||||
<Card title="Tool Types">
|
||||
1. **Search Tools**
|
||||
- Web search
|
||||
- Database queries
|
||||
- Document search
|
||||
|
||||
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
|
||||
|
||||
<Note>
|
||||
Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.
|
||||
</Note>
|
||||
|
||||
<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
|
||||
|
||||
# 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>
|
||||
@@ -1,28 +0,0 @@
|
||||
# Configuration file for the Sphinx documentation builder.
|
||||
#
|
||||
# For the full list of built-in configuration values, see the documentation:
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html
|
||||
|
||||
# -- Project information -----------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
|
||||
|
||||
project = 'PraisonAI'
|
||||
copyright = '2024, Mervin Praison'
|
||||
author = 'Mervin Praison'
|
||||
release = '7'
|
||||
|
||||
# -- General configuration ---------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
|
||||
|
||||
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx_rtd_theme']
|
||||
|
||||
templates_path = ['_templates']
|
||||
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
|
||||
|
||||
|
||||
|
||||
# -- Options for HTML output -------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
|
||||
|
||||
html_theme = 'sphinx_rtd_theme'
|
||||
html_static_path = ['_static']
|
||||
@@ -1,14 +0,0 @@
|
||||
---
|
||||
title: "Contributing"
|
||||
description: "Guide for contributing to PraisonAI through GitHub, including forking, cloning, and submitting pull requests"
|
||||
icon: "code-branch"
|
||||
---
|
||||
|
||||
- Fork on GitHub: Use the "Fork" button on the repository page.
|
||||
- Clone your fork: `git clone https://github.com/yourusername/praisonAI.git`
|
||||
- Create a branch: `git checkout -b new-feature`
|
||||
- Make changes and commit: `git commit -am "Add some feature"`
|
||||
- Push to your fork: `git push origin new-feature`
|
||||
- Submit a pull request via GitHub's web interface.
|
||||
- Await feedback from project maintainers.
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
title: "Deploy"
|
||||
description: "Guide for deploying PraisonAI to cloud platforms, with detailed instructions for Google Cloud deployment"
|
||||
icon: "cloud"
|
||||
---
|
||||
|
||||
## Google Cloud
|
||||
|
||||
```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}
|
||||
```
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
---
|
||||
title: "Agents Playbook"
|
||||
description: "Examples and templates for creating PraisonAI agent playbooks, from simple to detailed configurations with multiple roles and tasks"
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
# Agents Playbook
|
||||
|
||||
## Simple Playbook Example
|
||||
|
||||
```yaml
|
||||
framework: crewai
|
||||
topic: Artificial Intelligence
|
||||
roles:
|
||||
screenwriter:
|
||||
backstory: 'Skilled in crafting scripts with engaging dialogue about {topic}.'
|
||||
goal: Create scripts from concepts.
|
||||
role: Screenwriter
|
||||
tasks:
|
||||
scriptwriting_task:
|
||||
description: 'Develop scripts with compelling characters and dialogue about {topic}.'
|
||||
expected_output: 'Complete script ready for production.'
|
||||
```
|
||||
|
||||
## Detailed Playbook Example
|
||||
|
||||
```yaml
|
||||
framework: crewai
|
||||
topic: Artificial Intelligence
|
||||
roles:
|
||||
movie_concept_creator:
|
||||
backstory: 'Creative thinker with a deep understanding of cinematic storytelling,
|
||||
capable of using AI-generated storylines to create unique and compelling movie
|
||||
ideas.'
|
||||
goal: Generate engaging movie concepts using AI storylines
|
||||
role: Movie Concept Creator
|
||||
tasks:
|
||||
movie_concept_development:
|
||||
description: 'Develop movie concepts from AI-generated storylines, ensuring
|
||||
they are engaging and have strong narrative arcs.'
|
||||
expected_output: 'Well-structured movie concept document with character
|
||||
bios, settings, and plot outlines.'
|
||||
screenwriter:
|
||||
backstory: 'Expert in writing engaging dialogue and script structure, able to
|
||||
turn movie concepts into production-ready scripts.'
|
||||
goal: Write compelling scripts based on movie concepts
|
||||
role: Screenwriter
|
||||
tasks:
|
||||
scriptwriting_task:
|
||||
description: 'Turn movie concepts into polished scripts with well-developed
|
||||
characters, strong dialogue, and effective scene transitions.'
|
||||
expected_output: 'Production-ready script with a beginning, middle, and
|
||||
end, along with character development and engaging dialogues.'
|
||||
editor:
|
||||
backstory: 'Adept at identifying inconsistencies, improving language usage,
|
||||
and maintaining the overall flow of the script.'
|
||||
goal: Refine the scripts and ensure continuity of the movie storyline
|
||||
role: Editor
|
||||
tasks:
|
||||
editing_task:
|
||||
description: 'Review, edit, and refine the scripts to ensure they are cohesive
|
||||
and follow a well-structured narrative.'
|
||||
expected_output: 'A polished final draft of the script with no inconsistencies,
|
||||
strong character development, and effective dialogue.'
|
||||
dependencies: []
|
||||
```
|
||||
@@ -1,214 +0,0 @@
|
||||
---
|
||||
title: "Google Colab Tools"
|
||||
description: "Guide for implementing and using custom tools in PraisonAI with Google Colab, including examples of internet search and data processing tools"
|
||||
icon: "wrench"
|
||||
---
|
||||
|
||||
```
|
||||
jupyter:
|
||||
accelerator: GPU
|
||||
colab:
|
||||
gpuType: T4
|
||||
kernelspec:
|
||||
display_name: Python 3
|
||||
name: python3
|
||||
language_info:
|
||||
name: python
|
||||
nbformat: 4
|
||||
nbformat_minor: 0
|
||||
```
|
||||
|
||||
``` python
|
||||
!pip install -Uq praisonai duckduckgo_search
|
||||
```
|
||||
|
||||
``` python
|
||||
from duckduckgo_search import DDGS
|
||||
from praisonai_tools import BaseTool
|
||||
|
||||
class InternetSearchTool(BaseTool):
|
||||
name: str = "InternetSearchTool"
|
||||
description: str = "Search Internet for relevant information based on a query or latest news"
|
||||
|
||||
def _run(self, query: str):
|
||||
ddgs = DDGS()
|
||||
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
|
||||
return results
|
||||
```
|
||||
|
||||
``` python
|
||||
import os
|
||||
import yaml
|
||||
from praisonai import PraisonAI
|
||||
from google.colab import userdata
|
||||
|
||||
# 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."
|
||||
tools:
|
||||
- "InternetSearchTool"
|
||||
"""
|
||||
|
||||
# Create a PraisonAI instance with the agent_yaml content
|
||||
praisonai = PraisonAI(agent_yaml=agent_yaml)
|
||||
|
||||
# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below
|
||||
os.environ["OPENAI_API_KEY"] = userdata.get('OPENAI_API_KEY') or "ENTER OPENAI_API_KEY HERE"
|
||||
|
||||
# Run PraisonAI
|
||||
result = praisonai.run()
|
||||
|
||||
# Print the result
|
||||
print(result)
|
||||
```
|
||||
|
||||
|
||||
[2024-07-03 04:53:48][DEBUG]: == Working Agent: Space Researcher
|
||||
[2024-07-03 04:53:48][INFO]: == Starting Task: Research and compile information about exoplanets discovered in the last decade.
|
||||
|
||||
|
||||
> Entering new CrewAgentExecutor chain...
|
||||
I now can give a great answer.
|
||||
|
||||
Final Answer:
|
||||
|
||||
Over the last decade, the field of exoplanet research has experienced significant advancements, leading to the discovery of thousands of exoplanets. These discoveries have been made possible through missions like NASA's Kepler and TESS (Transiting Exoplanet Survey Satellite), as well as ground-based observatories. Here is a summarized report on some of the notable exoplanet discoveries, including their size, potential habitability, and distance from Earth:
|
||||
|
||||
1. **Kepler-452b**
|
||||
- **Size**: Approximately 1.6 times the radius of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, where liquid water could exist. It is often referred to as Earth's "cousin."
|
||||
- **Distance from Earth**: About 1,400 light-years
|
||||
|
||||
2. **Proxima Centauri b**
|
||||
- **Size**: About 1.17 times the mass of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of Proxima Centauri, the closest star to the Sun. It has the potential to have liquid water.
|
||||
- **Distance from Earth**: 4.24 light-years
|
||||
|
||||
3. **TRAPPIST-1 System**
|
||||
- **Size**: The system includes seven Earth-sized planets
|
||||
- **Potential Habitability**: Three of the planets (TRAPPIST-1e, TRAPPIST-1f, and TRAPPIST-1g) are located in the habitable zone and could potentially support liquid water.
|
||||
- **Distance from Earth**: Approximately 39 light-years
|
||||
|
||||
4. **LHS 1140b**
|
||||
- **Size**: About 1.4 times the size of Earth and 6.6 times its mass
|
||||
- **Potential Habitability**: Located in the habitable zone of its star. It has a thick atmosphere and conditions that could support life.
|
||||
- **Distance from Earth**: About 40 light-years
|
||||
|
||||
5. **Kepler-186f**
|
||||
- **Size**: Similar to Earth in size
|
||||
- **Potential Habitability**: The first Earth-sized planet discovered in the habitable zone of another star. It has potential for liquid water on its surface.
|
||||
- **Distance from Earth**: About 500 light-years
|
||||
|
||||
6. **K2-18b**
|
||||
- **Size**: Approximately 2.6 times the radius of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, with evidence of water vapor in its atmosphere.
|
||||
- **Distance from Earth**: About 124 light-years
|
||||
|
||||
7. **GJ 357 d**
|
||||
- **Size**: About 6.1 times the mass of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, with the potential to have liquid water on its surface.
|
||||
- **Distance from Earth**: About 31 light-years
|
||||
|
||||
These discoveries highlight the diversity of exoplanets in terms of size, composition, and potential habitability. The search for exoplanets is crucial for understanding the potential for life beyond Earth and the formation and evolution of planetary systems. Ongoing and future missions, such as the James Webb Space Telescope, are expected to provide even more detailed information about these distant worlds.
|
||||
|
||||
The continuous exploration and study of exoplanets will undoubtedly lead to new insights and perhaps even the discovery of life beyond our solar system.
|
||||
|
||||
|
||||
|
||||
> Finished chain.
|
||||
[2024-07-03 04:53:58][DEBUG]: == [Space Researcher] Task output: Over the last decade, the field of exoplanet research has experienced significant advancements, leading to the discovery of thousands of exoplanets. These discoveries have been made possible through missions like NASA's Kepler and TESS (Transiting Exoplanet Survey Satellite), as well as ground-based observatories. Here is a summarized report on some of the notable exoplanet discoveries, including their size, potential habitability, and distance from Earth:
|
||||
|
||||
1. **Kepler-452b**
|
||||
- **Size**: Approximately 1.6 times the radius of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, where liquid water could exist. It is often referred to as Earth's "cousin."
|
||||
- **Distance from Earth**: About 1,400 light-years
|
||||
|
||||
2. **Proxima Centauri b**
|
||||
- **Size**: About 1.17 times the mass of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of Proxima Centauri, the closest star to the Sun. It has the potential to have liquid water.
|
||||
- **Distance from Earth**: 4.24 light-years
|
||||
|
||||
3. **TRAPPIST-1 System**
|
||||
- **Size**: The system includes seven Earth-sized planets
|
||||
- **Potential Habitability**: Three of the planets (TRAPPIST-1e, TRAPPIST-1f, and TRAPPIST-1g) are located in the habitable zone and could potentially support liquid water.
|
||||
- **Distance from Earth**: Approximately 39 light-years
|
||||
|
||||
4. **LHS 1140b**
|
||||
- **Size**: About 1.4 times the size of Earth and 6.6 times its mass
|
||||
- **Potential Habitability**: Located in the habitable zone of its star. It has a thick atmosphere and conditions that could support life.
|
||||
- **Distance from Earth**: About 40 light-years
|
||||
|
||||
5. **Kepler-186f**
|
||||
- **Size**: Similar to Earth in size
|
||||
- **Potential Habitability**: The first Earth-sized planet discovered in the habitable zone of another star. It has potential for liquid water on its surface.
|
||||
- **Distance from Earth**: About 500 light-years
|
||||
|
||||
6. **K2-18b**
|
||||
- **Size**: Approximately 2.6 times the radius of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, with evidence of water vapor in its atmosphere.
|
||||
- **Distance from Earth**: About 124 light-years
|
||||
|
||||
7. **GJ 357 d**
|
||||
- **Size**: About 6.1 times the mass of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, with the potential to have liquid water on its surface.
|
||||
- **Distance from Earth**: About 31 light-years
|
||||
|
||||
These discoveries highlight the diversity of exoplanets in terms of size, composition, and potential habitability. The search for exoplanets is crucial for understanding the potential for life beyond Earth and the formation and evolution of planetary systems. Ongoing and future missions, such as the James Webb Space Telescope, are expected to provide even more detailed information about these distant worlds.
|
||||
|
||||
The continuous exploration and study of exoplanets will undoubtedly lead to new insights and perhaps even the discovery of life beyond our solar system.
|
||||
|
||||
|
||||
### Task Output ###
|
||||
Over the last decade, the field of exoplanet research has experienced significant advancements, leading to the discovery of thousands of exoplanets. These discoveries have been made possible through missions like NASA's Kepler and TESS (Transiting Exoplanet Survey Satellite), as well as ground-based observatories. Here is a summarized report on some of the notable exoplanet discoveries, including their size, potential habitability, and distance from Earth:
|
||||
|
||||
1. **Kepler-452b**
|
||||
- **Size**: Approximately 1.6 times the radius of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, where liquid water could exist. It is often referred to as Earth's "cousin."
|
||||
- **Distance from Earth**: About 1,400 light-years
|
||||
|
||||
2. **Proxima Centauri b**
|
||||
- **Size**: About 1.17 times the mass of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of Proxima Centauri, the closest star to the Sun. It has the potential to have liquid water.
|
||||
- **Distance from Earth**: 4.24 light-years
|
||||
|
||||
3. **TRAPPIST-1 System**
|
||||
- **Size**: The system includes seven Earth-sized planets
|
||||
- **Potential Habitability**: Three of the planets (TRAPPIST-1e, TRAPPIST-1f, and TRAPPIST-1g) are located in the habitable zone and could potentially support liquid water.
|
||||
- **Distance from Earth**: Approximately 39 light-years
|
||||
|
||||
4. **LHS 1140b**
|
||||
- **Size**: About 1.4 times the size of Earth and 6.6 times its mass
|
||||
- **Potential Habitability**: Located in the habitable zone of its star. It has a thick atmosphere and conditions that could support life.
|
||||
- **Distance from Earth**: About 40 light-years
|
||||
|
||||
5. **Kepler-186f**
|
||||
- **Size**: Similar to Earth in size
|
||||
- **Potential Habitability**: The first Earth-sized planet discovered in the habitable zone of another star. It has potential for liquid water on its surface.
|
||||
- **Distance from Earth**: About 500 light-years
|
||||
|
||||
6. **K2-18b**
|
||||
- **Size**: Approximately 2.6 times the radius of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, with evidence of water vapor in its atmosphere.
|
||||
- **Distance from Earth**: About 124 light-years
|
||||
|
||||
7. **GJ 357 d**
|
||||
- **Size**: About 6.1 times the mass of Earth
|
||||
- **Potential Habitability**: Located in the habitable zone of its star, with the potential to have liquid water on its surface.
|
||||
- **Distance from Earth**: About 31 light-years
|
||||
|
||||
These discoveries highlight the diversity of exoplanets in terms of size, composition, and potential habitability. The search for exoplanets is crucial for understanding the potential for life beyond Earth and the formation and evolution of planetary systems. Ongoing and future missions, such as the James Webb Space Telescope, are expected to provide even more detailed information about these distant worlds.
|
||||
|
||||
The continuous exploration and study of exoplanets will undoubtedly lead to new insights and perhaps even the discovery of life beyond our solar system.
|
||||
:::
|
||||
:::
|
||||
@@ -1,247 +0,0 @@
|
||||
---
|
||||
title: "Google Colab Integration"
|
||||
description: "Guide for using PraisonAI in Google Colab environments, with example code and configurations for agent-based tasks"
|
||||
icon: "google"
|
||||
---
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Basic PraisonAI" icon="book">
|
||||
<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>
|
||||
</Card>
|
||||
<Card title="PraisonAI with Tools" icon="screwdriver-wrench">
|
||||
<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>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
```
|
||||
jupyter:
|
||||
accelerator: GPU
|
||||
colab:
|
||||
gpuType: T4
|
||||
kernelspec:
|
||||
display_name: Python 3
|
||||
name: python3
|
||||
language_info:
|
||||
name: python
|
||||
nbformat: 4
|
||||
nbformat_minor: 0
|
||||
```
|
||||
|
||||
|
||||
``` python
|
||||
!pip install -Uq praisonai
|
||||
```
|
||||
|
||||
``` python
|
||||
import os
|
||||
import yaml
|
||||
from praisonai import PraisonAI
|
||||
from google.colab import userdata
|
||||
|
||||
# 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)
|
||||
|
||||
# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below
|
||||
os.environ["OPENAI_API_KEY"] = userdata.get('OPENAI_API_KEY') or "ENTER OPENAI_API_KEY HERE"
|
||||
|
||||
# Run PraisonAI
|
||||
result = praisonai.run()
|
||||
|
||||
# Print the result
|
||||
print(result)
|
||||
```
|
||||
|
||||
|
||||
[2024-07-03 04:39:09][DEBUG]: == Working Agent: Space Researcher
|
||||
[2024-07-03 04:39:09][INFO]: == Starting Task: Research and compile information about exoplanets discovered in the last decade.
|
||||
|
||||
|
||||
> Entering new CrewAgentExecutor chain...
|
||||
I now can give a great answer.
|
||||
|
||||
Final Answer:
|
||||
|
||||
In the last decade, the field of exoplanet research has experienced a remarkable surge in discoveries, thanks to advancements in technology and dedicated space missions such as Kepler, TESS (Transiting Exoplanet Survey Satellite), and various ground-based observatories. Here is a summarized report on some of the notable exoplanet discoveries, highlighting their size, potential habitability, and distance from Earth:
|
||||
|
||||
1. **Kepler-452b**
|
||||
- **Size:** Approximately 60% larger in diameter than Earth.
|
||||
- **Potential Habitability:** Often referred to as "Earth's Cousin," Kepler-452b orbits within the habitable zone of its star, where liquid water could exist. The planet receives a similar amount of energy from its star as Earth does from the Sun.
|
||||
- **Distance from Earth:** About 1,402 light-years.
|
||||
|
||||
2. **Proxima Centauri b**
|
||||
- **Size:** Slightly larger than Earth, with a minimum mass of 1.17 Earth masses.
|
||||
- **Potential Habitability:** Located in the habitable zone of Proxima Centauri, the closest known star to the Sun. Potential for liquid water exists, but its habitability is uncertain due to stellar flare activity.
|
||||
- **Distance from Earth:** 4.24 light-years.
|
||||
|
||||
3. **TRAPPIST-1 System**
|
||||
- **Size:** The system contains seven Earth-sized planets. TRAPPIST-1e, f, and g are within the star's habitable zone.
|
||||
- **Potential Habitability:** TRAPPIST-1e is considered the most promising candidate for habitability, as it has a rocky composition and is located in the middle of the habitable zone.
|
||||
- **Distance from Earth:** About 39 light-years.
|
||||
|
||||
4. **LHS 1140 b**
|
||||
- **Size:** About 1.4 times the size of Earth with a mass of around 6.6 Earth masses.
|
||||
- **Potential Habitability:** Resides in the habitable zone of its red dwarf star. The planet is likely rocky and has an atmosphere that could support life.
|
||||
- **Distance from Earth:** Approximately 40 light-years.
|
||||
|
||||
5. **K2-18b**
|
||||
- **Size:** About 2.6 times the size of Earth with a mass of 8.6 Earth masses.
|
||||
- **Potential Habitability:** This exoplanet lies within the habitable zone and has been detected to have water vapor in its atmosphere. It is considered one of the most promising candidates for habitability outside our solar system.
|
||||
- **Distance from Earth:** Roughly 124 light-years.
|
||||
|
||||
6. **Gliese 667 Cc**
|
||||
- **Size:** At least 4.5 times the mass of Earth.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of its host star, Gliese 667 C. Its orbit allows for the possibility of liquid water on its surface.
|
||||
- **Distance from Earth:** About 23.62 light-years.
|
||||
|
||||
7. **HD 40307 g**
|
||||
- **Size:** A super-Earth with at least 7 Earth masses.
|
||||
- **Potential Habitability:** Located in the habitable zone of its star, this planet could potentially support liquid water and therefore life.
|
||||
- **Distance from Earth:** Approximately 42 light-years.
|
||||
|
||||
8. **Ross 128 b**
|
||||
- **Size:** Similar to Earth, with a minimum mass of 1.35 Earth masses.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of the relatively quiet red dwarf star Ross 128. The planet has mild temperatures that could allow for liquid water.
|
||||
- **Distance from Earth:** About 11 light-years.
|
||||
|
||||
9. **Teegarden's Star b**
|
||||
- **Size:** Comparable to Earth.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of Teegarden's Star, a cool red dwarf. Conditions could be suitable for liquid water.
|
||||
- **Distance from Earth:** Approximately 12 light-years.
|
||||
|
||||
10. **Barnard's Star b**
|
||||
- **Size:** A super-Earth with a mass of about 3.2 Earth masses.
|
||||
- **Potential Habitability:** Located just outside the traditional habitable zone, but still within a range where liquid water could exist under certain conditions.
|
||||
- **Distance from Earth:** About 6 light-years.
|
||||
|
||||
These discoveries highlight the diverse and intriguing nature of exoplanets found in the last decade. Each of these planets adds valuable information to our understanding of planetary formation, potential habitability, and the search for extraterrestrial life. Continued advancements in detection methods and technologies promise to further expand our knowledge in the years to come.
|
||||
|
||||
> Finished chain.
|
||||
[2024-07-03 04:39:25][DEBUG]: == [Space Researcher] Task output: In the last decade, the field of exoplanet research has experienced a remarkable surge in discoveries, thanks to advancements in technology and dedicated space missions such as Kepler, TESS (Transiting Exoplanet Survey Satellite), and various ground-based observatories. Here is a summarized report on some of the notable exoplanet discoveries, highlighting their size, potential habitability, and distance from Earth:
|
||||
|
||||
1. **Kepler-452b**
|
||||
- **Size:** Approximately 60% larger in diameter than Earth.
|
||||
- **Potential Habitability:** Often referred to as "Earth's Cousin," Kepler-452b orbits within the habitable zone of its star, where liquid water could exist. The planet receives a similar amount of energy from its star as Earth does from the Sun.
|
||||
- **Distance from Earth:** About 1,402 light-years.
|
||||
|
||||
2. **Proxima Centauri b**
|
||||
- **Size:** Slightly larger than Earth, with a minimum mass of 1.17 Earth masses.
|
||||
- **Potential Habitability:** Located in the habitable zone of Proxima Centauri, the closest known star to the Sun. Potential for liquid water exists, but its habitability is uncertain due to stellar flare activity.
|
||||
- **Distance from Earth:** 4.24 light-years.
|
||||
|
||||
3. **TRAPPIST-1 System**
|
||||
- **Size:** The system contains seven Earth-sized planets. TRAPPIST-1e, f, and g are within the star's habitable zone.
|
||||
- **Potential Habitability:** TRAPPIST-1e is considered the most promising candidate for habitability, as it has a rocky composition and is located in the middle of the habitable zone.
|
||||
- **Distance from Earth:** About 39 light-years.
|
||||
|
||||
4. **LHS 1140 b**
|
||||
- **Size:** About 1.4 times the size of Earth with a mass of around 6.6 Earth masses.
|
||||
- **Potential Habitability:** Resides in the habitable zone of its red dwarf star. The planet is likely rocky and has an atmosphere that could support life.
|
||||
- **Distance from Earth:** Approximately 40 light-years.
|
||||
|
||||
5. **K2-18b**
|
||||
- **Size:** About 2.6 times the size of Earth with a mass of 8.6 Earth masses.
|
||||
- **Potential Habitability:** This exoplanet lies within the habitable zone and has been detected to have water vapor in its atmosphere. It is considered one of the most promising candidates for habitability outside our solar system.
|
||||
- **Distance from Earth:** Roughly 124 light-years.
|
||||
|
||||
6. **Gliese 667 Cc**
|
||||
- **Size:** At least 4.5 times the mass of Earth.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of its host star, Gliese 667 C. Its orbit allows for the possibility of liquid water on its surface.
|
||||
- **Distance from Earth:** About 23.62 light-years.
|
||||
|
||||
7. **HD 40307 g**
|
||||
- **Size:** A super-Earth with at least 7 Earth masses.
|
||||
- **Potential Habitability:** Located in the habitable zone of its star, this planet could potentially support liquid water and therefore life.
|
||||
- **Distance from Earth:** Approximately 42 light-years.
|
||||
|
||||
8. **Ross 128 b**
|
||||
- **Size:** Similar to Earth, with a minimum mass of 1.35 Earth masses.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of the relatively quiet red dwarf star Ross 128. The planet has mild temperatures that could allow for liquid water.
|
||||
- **Distance from Earth:** About 11 light-years.
|
||||
|
||||
9. **Teegarden's Star b**
|
||||
- **Size:** Comparable to Earth.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of Teegarden's Star, a cool red dwarf. Conditions could be suitable for liquid water.
|
||||
- **Distance from Earth:** Approximately 12 light-years.
|
||||
|
||||
10. **Barnard's Star b**
|
||||
- **Size:** A super-Earth with a mass of about 3.2 Earth masses.
|
||||
- **Potential Habitability:** Located just outside the traditional habitable zone, but still within a range where liquid water could exist under certain conditions.
|
||||
- **Distance from Earth:** About 6 light-years.
|
||||
|
||||
These discoveries highlight the diverse and intriguing nature of exoplanets found in the last decade. Each of these planets adds valuable information to our understanding of planetary formation, potential habitability, and the search for extraterrestrial life. Continued advancements in detection methods and technologies promise to further expand our knowledge in the years to come.
|
||||
|
||||
|
||||
### Task Output ###
|
||||
In the last decade, the field of exoplanet research has experienced a remarkable surge in discoveries, thanks to advancements in technology and dedicated space missions such as Kepler, TESS (Transiting Exoplanet Survey Satellite), and various ground-based observatories. Here is a summarized report on some of the notable exoplanet discoveries, highlighting their size, potential habitability, and distance from Earth:
|
||||
|
||||
1. **Kepler-452b**
|
||||
- **Size:** Approximately 60% larger in diameter than Earth.
|
||||
- **Potential Habitability:** Often referred to as "Earth's Cousin," Kepler-452b orbits within the habitable zone of its star, where liquid water could exist. The planet receives a similar amount of energy from its star as Earth does from the Sun.
|
||||
- **Distance from Earth:** About 1,402 light-years.
|
||||
|
||||
2. **Proxima Centauri b**
|
||||
- **Size:** Slightly larger than Earth, with a minimum mass of 1.17 Earth masses.
|
||||
- **Potential Habitability:** Located in the habitable zone of Proxima Centauri, the closest known star to the Sun. Potential for liquid water exists, but its habitability is uncertain due to stellar flare activity.
|
||||
- **Distance from Earth:** 4.24 light-years.
|
||||
|
||||
3. **TRAPPIST-1 System**
|
||||
- **Size:** The system contains seven Earth-sized planets. TRAPPIST-1e, f, and g are within the star's habitable zone.
|
||||
- **Potential Habitability:** TRAPPIST-1e is considered the most promising candidate for habitability, as it has a rocky composition and is located in the middle of the habitable zone.
|
||||
- **Distance from Earth:** About 39 light-years.
|
||||
|
||||
4. **LHS 1140 b**
|
||||
- **Size:** About 1.4 times the size of Earth with a mass of around 6.6 Earth masses.
|
||||
- **Potential Habitability:** Resides in the habitable zone of its red dwarf star. The planet is likely rocky and has an atmosphere that could support life.
|
||||
- **Distance from Earth:** Approximately 40 light-years.
|
||||
|
||||
5. **K2-18b**
|
||||
- **Size:** About 2.6 times the size of Earth with a mass of 8.6 Earth masses.
|
||||
- **Potential Habitability:** This exoplanet lies within the habitable zone and has been detected to have water vapor in its atmosphere. It is considered one of the most promising candidates for habitability outside our solar system.
|
||||
- **Distance from Earth:** Roughly 124 light-years.
|
||||
|
||||
6. **Gliese 667 Cc**
|
||||
- **Size:** At least 4.5 times the mass of Earth.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of its host star, Gliese 667 C. Its orbit allows for the possibility of liquid water on its surface.
|
||||
- **Distance from Earth:** About 23.62 light-years.
|
||||
|
||||
7. **HD 40307 g**
|
||||
- **Size:** A super-Earth with at least 7 Earth masses.
|
||||
- **Potential Habitability:** Located in the habitable zone of its star, this planet could potentially support liquid water and therefore life.
|
||||
- **Distance from Earth:** Approximately 42 light-years.
|
||||
|
||||
8. **Ross 128 b**
|
||||
- **Size:** Similar to Earth, with a minimum mass of 1.35 Earth masses.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of the relatively quiet red dwarf star Ross 128. The planet has mild temperatures that could allow for liquid water.
|
||||
- **Distance from Earth:** About 11 light-years.
|
||||
|
||||
9. **Teegarden's Star b**
|
||||
- **Size:** Comparable to Earth.
|
||||
- **Potential Habitability:** Orbits within the habitable zone of Teegarden's Star, a cool red dwarf. Conditions could be suitable for liquid water.
|
||||
- **Distance from Earth:** Approximately 12 light-years.
|
||||
|
||||
10. **Barnard's Star b**
|
||||
- **Size:** A super-Earth with a mass of about 3.2 Earth masses.
|
||||
- **Potential Habitability:** Located just outside the traditional habitable zone, but still within a range where liquid water could exist under certain conditions.
|
||||
- **Distance from Earth:** About 6 light-years.
|
||||
|
||||
These discoveries highlight the diverse and intriguing nature of exoplanets found in the last decade. Each of these planets adds valuable information to our understanding of planetary formation, potential habitability, and the search for extraterrestrial life. Continued advancements in detection methods and technologies promise to further expand our knowledge in the years to come.
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
title: "Test"
|
||||
description: "Instructions for running and writing tests for PraisonAI components, including unit tests and test automation"
|
||||
icon: "vial"
|
||||
---
|
||||
|
||||
# Test
|
||||
|
||||
```bash
|
||||
python -m unittest tests.test
|
||||
```
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
title: "Integrate with Tools"
|
||||
description: "Guide for integrating external tools and APIs with PraisonAI, including examples of custom tool creation and implementation"
|
||||
icon: "plug"
|
||||
---
|
||||
|
||||
# Integrate with Tools
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
from duckduckgo_search import DDGS
|
||||
from praisonai_tools import BaseTool
|
||||
|
||||
class InternetSearchTool(BaseTool):
|
||||
name: str = "InternetSearchTool"
|
||||
description: str = "Search Internet for relevant information based on a query or latest news"
|
||||
|
||||
def _run(self, query: str):
|
||||
ddgs = DDGS()
|
||||
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
|
||||
return results
|
||||
|
||||
# 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."
|
||||
tools:
|
||||
- "InternetSearchTool"
|
||||
"""
|
||||
|
||||
# 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)
|
||||
```
|
||||
@@ -1,85 +0,0 @@
|
||||
---
|
||||
title: "PraisonAI Package Integration"
|
||||
description: "Guide for integrating the PraisonAI package into your Python projects, including YAML configuration and different execution modes"
|
||||
icon: "box"
|
||||
---
|
||||
|
||||
# Include praisonai package in your project
|
||||
|
||||
## 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()
|
||||
```
|
||||
|
||||
## Other options
|
||||
|
||||
```python
|
||||
from praisonai import PraisonAI
|
||||
|
||||
def basic(): # Basic Mode
|
||||
praisonai = PraisonAI(agent_file="agents.yaml")
|
||||
praisonai.run()
|
||||
|
||||
def advanced(): # Advanced Mode with options
|
||||
praisonai = PraisonAI(
|
||||
agent_file="agents.yaml",
|
||||
framework="autogen",
|
||||
)
|
||||
praisonai.run()
|
||||
|
||||
def auto(): # Full Automatic Mode
|
||||
praisonai = PraisonAI(
|
||||
auto="Create a movie script about car in mars",
|
||||
framework="autogen"
|
||||
)
|
||||
print(praisonai.framework)
|
||||
praisonai.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
basic()
|
||||
advanced()
|
||||
auto()
|
||||
```
|
||||
|
||||
@@ -1,561 +0,0 @@
|
||||
---
|
||||
title: "Async Agents"
|
||||
description: "Async AI Agents allow you to run AI tasks asynchronously, improving performance and efficiency in your applications."
|
||||
icon: "clock"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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 Project">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create an agent
|
||||
agent = Agent(
|
||||
name="AsyncAgent",
|
||||
role="Assistant",
|
||||
goal="Help with tasks",
|
||||
backstory="Expert in async operations"
|
||||
)
|
||||
|
||||
# Create a task
|
||||
task = Task(
|
||||
name="hello_task",
|
||||
description="Say hello and introduce yourself",
|
||||
agent=agent,
|
||||
async_execution=True,
|
||||
expected_output="Answer to the question"
|
||||
)
|
||||
|
||||
# Create agents manager
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Main async function
|
||||
async def main():
|
||||
result = await agents.astart()
|
||||
print(result)
|
||||
|
||||
# Run the program
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Program">
|
||||
Run your async AI agent:
|
||||
```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:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create Project">
|
||||
Create a new file `agents.yaml` with the basic setup:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: async operations
|
||||
roles:
|
||||
assistant:
|
||||
name: AsyncAgent
|
||||
role: Assistant
|
||||
goal: Help with tasks
|
||||
backstory: Expert in async operations
|
||||
tasks:
|
||||
hello_task:
|
||||
description: Say hello and introduce yourself
|
||||
expected_output: Answer to the question
|
||||
async_execution: true
|
||||
```
|
||||
</Step>
|
||||
<Step title="Run the Program">
|
||||
Run your async AI agent:
|
||||
```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 async/await in Python
|
||||
</Note>
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/VhVQfgo00LE"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Understanding Async Execution
|
||||
|
||||
<Card title="What is Asynchronous Execution?" icon="question">
|
||||
Async execution lets your program continue running while waiting for operations to complete. This is ideal for:
|
||||
- Making multiple AI API calls
|
||||
- Processing large datasets
|
||||
- Handling multiple tasks simultaneously
|
||||
- Maintaining responsive applications
|
||||
</Card>
|
||||
|
||||
<CodeGroup>
|
||||
```python Sync
|
||||
# Synchronous execution (blocks until complete)
|
||||
result = agent.chat("Hello")
|
||||
```
|
||||
|
||||
```python Async
|
||||
# Asynchronous execution (non-blocking)
|
||||
result = await agent.achat("Hello")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Async Tasks" icon="tasks">
|
||||
Create tasks that run asynchronously with built-in error handling and retries.
|
||||
</Card>
|
||||
<Card title="Parallel Processing" icon="arrows-split-up-and-left">
|
||||
Run multiple tasks in parallel using asyncio.gather().
|
||||
</Card>
|
||||
<Card title="Mixed Mode" icon="shuffle">
|
||||
Mix sync and async tasks in the same workflow seamlessly.
|
||||
</Card>
|
||||
<Card title="Resource Management" icon="gear">
|
||||
Built-in resource management and performance optimization.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
### Async Tasks with Callbacks and Tools Example Code
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
import time
|
||||
from typing import List, Dict
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents, TaskOutput
|
||||
from duckduckgo_search import DDGS
|
||||
from pydantic import BaseModel
|
||||
|
||||
# 1. Define async tool
|
||||
class SearchResult(BaseModel):
|
||||
query: str
|
||||
results: List[Dict[str, str]]
|
||||
total_results: int
|
||||
|
||||
async def async_search_tool(query: str) -> Dict:
|
||||
"""
|
||||
Asynchronous search using DuckDuckGo.
|
||||
Args:
|
||||
query (str): The search query.
|
||||
Returns:
|
||||
dict: Search results in SearchResult model format
|
||||
"""
|
||||
await asyncio.sleep(1) # Simulate network delay
|
||||
try:
|
||||
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", "")
|
||||
})
|
||||
|
||||
# Format response to match SearchResult model
|
||||
return {
|
||||
"query": query,
|
||||
"results": results,
|
||||
"total_results": len(results)
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"Error during async search: {e}")
|
||||
return {
|
||||
"query": query,
|
||||
"results": [],
|
||||
"total_results": 0
|
||||
}
|
||||
|
||||
# 2. Define async callback
|
||||
async def async_callback(output: TaskOutput):
|
||||
await asyncio.sleep(1) # Simulate processing
|
||||
if output.output_format == "JSON":
|
||||
print(f"Processed JSON result: {output.json_dict}")
|
||||
elif output.output_format == "Pydantic":
|
||||
print(f"Processed Pydantic result: {output.pydantic}")
|
||||
|
||||
# 3. Create specialized agents
|
||||
async_agent = Agent(
|
||||
name="AsyncSearchAgent",
|
||||
role="Asynchronous Search Specialist",
|
||||
goal="Perform fast and efficient asynchronous searches with structured results",
|
||||
backstory="Expert in parallel search operations and data retrieval",
|
||||
tools=[async_search_tool],
|
||||
self_reflect=False,
|
||||
verbose=True,
|
||||
markdown=True
|
||||
)
|
||||
|
||||
summary_agent = Agent(
|
||||
name="SummaryAgent",
|
||||
role="Research Synthesizer",
|
||||
goal="Create comprehensive summaries and identify patterns across multiple search results",
|
||||
backstory="""Expert in analyzing and synthesizing information from multiple sources.
|
||||
Skilled at identifying patterns, trends, and connections between different topics.
|
||||
Specializes in creating clear, structured summaries that highlight key insights.""",
|
||||
self_reflect=True, # Enable self-reflection for better summary quality
|
||||
verbose=True,
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# 4. Create async tasks
|
||||
async_task = Task(
|
||||
name="async_search",
|
||||
description="""Search for 'Async programming' and return results in the following JSON format:
|
||||
{
|
||||
"query": "the search query",
|
||||
"results": [
|
||||
{
|
||||
"title": "result title",
|
||||
"url": "result url",
|
||||
"snippet": "result snippet"
|
||||
}
|
||||
],
|
||||
"total_results": number of results
|
||||
}""",
|
||||
expected_output="SearchResult model with query details and results",
|
||||
agent=async_agent,
|
||||
async_execution=True,
|
||||
callback=async_callback,
|
||||
output_pydantic=SearchResult
|
||||
)
|
||||
|
||||
# 5. Example usage functions
|
||||
async def run_single_task():
|
||||
"""Run single async task"""
|
||||
print("\nRunning Single Async Task...")
|
||||
agents = PraisonAIAgents(
|
||||
agents=[async_agent],
|
||||
tasks=[async_task],
|
||||
verbose=1,
|
||||
process="sequential"
|
||||
)
|
||||
result = await agents.astart()
|
||||
print(f"Single Task Result: {result}")
|
||||
|
||||
async def run_parallel_tasks():
|
||||
"""Run multiple async tasks in parallel"""
|
||||
print("\nRunning Parallel Async Tasks...")
|
||||
|
||||
# Define different search topics
|
||||
search_topics = [
|
||||
"Latest AI Developments 2024",
|
||||
"Machine Learning Best Practices",
|
||||
"Neural Networks Architecture"
|
||||
]
|
||||
|
||||
# Create tasks for different topics
|
||||
parallel_tasks = [
|
||||
Task(
|
||||
name=f"search_task_{i}",
|
||||
description=f"""Search for '{topic}' and return results in the following JSON format:
|
||||
{{
|
||||
"query": "{topic}",
|
||||
"results": [
|
||||
{{
|
||||
"title": "result title",
|
||||
"url": "result url",
|
||||
"snippet": "result snippet"
|
||||
}}
|
||||
],
|
||||
"total_results": number of results
|
||||
}}""",
|
||||
expected_output="SearchResult model with detailed information",
|
||||
agent=async_agent,
|
||||
async_execution=True,
|
||||
callback=async_callback,
|
||||
output_pydantic=SearchResult
|
||||
) for i, topic in enumerate(search_topics)
|
||||
]
|
||||
|
||||
# Create summarization task with the specialized summary agent
|
||||
summary_task = Task(
|
||||
name="summary_task",
|
||||
description="""As a Research Synthesizer, analyze the search results and create a comprehensive summary. Your task:
|
||||
|
||||
1. Analyze Results:
|
||||
- Review all search results thoroughly
|
||||
- Extract key findings from each topic
|
||||
- Identify main themes and concepts
|
||||
|
||||
2. Find Connections:
|
||||
- Identify relationships between topics
|
||||
- Spot common patterns or contradictions
|
||||
- Note emerging trends across sources
|
||||
|
||||
3. Create Structured Summary:
|
||||
- Main findings per topic
|
||||
- Cross-cutting themes
|
||||
- Emerging trends
|
||||
- Practical implications
|
||||
- Future directions
|
||||
|
||||
4. Quality Checks:
|
||||
- Ensure all topics are covered
|
||||
- Verify accuracy of connections
|
||||
- Confirm clarity of insights
|
||||
- Validate practical relevance
|
||||
|
||||
Present the summary in a clear, structured format with sections for findings, patterns, trends, and implications.""",
|
||||
expected_output="""A comprehensive research synthesis containing:
|
||||
- Detailed findings from each search topic
|
||||
- Cross-topic patterns and relationships
|
||||
- Emerging trends and their implications
|
||||
- Practical applications and future directions""",
|
||||
agent=summary_agent, # Use the specialized summary agent
|
||||
async_execution=False, # Run synchronously after search tasks
|
||||
callback=async_callback
|
||||
)
|
||||
|
||||
# Create a single PraisonAIAgents instance with both agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[async_agent, summary_agent], # Include both agents
|
||||
tasks=parallel_tasks + [summary_task], # Include all tasks
|
||||
verbose=1,
|
||||
process="sequential" # Tasks will run in sequence, with parallel tasks running first
|
||||
)
|
||||
|
||||
# Run all tasks
|
||||
results = await agents.astart()
|
||||
print(f"Tasks Results: {results}")
|
||||
|
||||
# Return results in a serializable format
|
||||
return {
|
||||
"search_results": {
|
||||
"task_status": {k: v for k, v in results["task_status"].items() if k != summary_task.id},
|
||||
"task_results": [str(results["task_results"][i]) if results["task_results"][i] else None
|
||||
for i in range(len(parallel_tasks))]
|
||||
},
|
||||
"summary": str(results["task_results"][summary_task.id]) if results["task_results"].get(summary_task.id) else None,
|
||||
"topics": search_topics
|
||||
}
|
||||
|
||||
# 6. Main execution
|
||||
async def main():
|
||||
"""Main execution function"""
|
||||
print("Starting Async AI Agents Examples...")
|
||||
|
||||
try:
|
||||
# Run different async patterns
|
||||
await run_single_task()
|
||||
await run_parallel_tasks()
|
||||
except Exception as e:
|
||||
print(f"Error in main execution: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the main function
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### 1. Async Tasks with Callbacks
|
||||
|
||||
<CodeGroup>
|
||||
```python Task
|
||||
# Create an async task with callback
|
||||
async_task = Task(
|
||||
name="weather_task",
|
||||
description="Check weather conditions",
|
||||
agent=agent,
|
||||
async_execution=True,
|
||||
callback=async_callback
|
||||
)
|
||||
```
|
||||
|
||||
```python Callback
|
||||
async def async_callback(output):
|
||||
await process_result(output)
|
||||
await save_to_database(output)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 2. Parallel Task Processing
|
||||
|
||||
<Warning>
|
||||
Be mindful of rate limits and resource usage when processing tasks in parallel.
|
||||
</Warning>
|
||||
|
||||
```python
|
||||
async def process_multiple_tasks():
|
||||
tasks = [
|
||||
Task(
|
||||
name=f"task_{i}",
|
||||
description=f"Process item {i}",
|
||||
async_execution=True
|
||||
) for i in range(5)
|
||||
]
|
||||
|
||||
results = await asyncio.gather(
|
||||
*[agent.achat(task.description) for task in tasks]
|
||||
)
|
||||
return results
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: async operations
|
||||
roles:
|
||||
async_agent:
|
||||
name: AsyncSearchAgent
|
||||
role: Asynchronous Search Specialist
|
||||
goal: Perform fast and efficient asynchronous searches
|
||||
backstory: Expert in parallel search operations
|
||||
tools:
|
||||
- async_search_tool
|
||||
tasks:
|
||||
search_task:
|
||||
description: Perform async search operations
|
||||
expected_output: Structured search results
|
||||
async_execution: true
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Error Handling">
|
||||
```python
|
||||
async def safe_async_operation():
|
||||
try:
|
||||
result = await agent.achat("Process this")
|
||||
return result
|
||||
except Exception as e:
|
||||
logging.error(f"Error: {e}")
|
||||
return None
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Resource Management">
|
||||
```python
|
||||
async def efficient_processing():
|
||||
semaphore = asyncio.Semaphore(5)
|
||||
async with semaphore:
|
||||
result = await agent.achat("Process within limits")
|
||||
return result
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Performance Tips">
|
||||
- Use `asyncio.gather()` for parallel operations
|
||||
- Implement proper error handling
|
||||
- Monitor memory usage
|
||||
- Use timeouts for long-running operations
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="ChatCompletion Error" icon="triangle-exclamation">
|
||||
If you see "ChatCompletion can't be used in await expression":
|
||||
- Use AsyncOpenAI() client
|
||||
- Ensure proper async context
|
||||
</Card>
|
||||
|
||||
<Card title="Event Loop Error" icon="circle-exclamation">
|
||||
If you get "Event loop is closed":
|
||||
- Use asyncio.run() for main entry
|
||||
- Check async context
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## API Reference
|
||||
|
||||
### Async Methods
|
||||
|
||||
<ResponseField name="achat()" type="async">
|
||||
Async version of chat method
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="aexecute_tool()" type="async">
|
||||
Async tool execution method
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="astart()" type="async">
|
||||
Async task execution starter
|
||||
</ResponseField>
|
||||
|
||||
### Task Properties
|
||||
|
||||
<ResponseField name="async_execution" type="boolean">
|
||||
Enable/disable async mode for tasks
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="callback" type="function">
|
||||
Set sync or async callback function
|
||||
</ResponseField>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
Remember to handle errors properly, manage resources efficiently, and test thoroughly in async contexts.
|
||||
</Note>
|
||||
@@ -1,308 +0,0 @@
|
||||
---
|
||||
title: "AutoAgents"
|
||||
description: "AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions."
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents duckduckgo_search
|
||||
```
|
||||
</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 AutoAgents
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Create AutoAgents instance
|
||||
agents = AutoAgents(
|
||||
instructions="Search for information about AI Agents",
|
||||
tools=[duckduckgo],
|
||||
process="sequential",
|
||||
verbose=True,
|
||||
max_agents=3 # Maximum number of agents to create
|
||||
)
|
||||
|
||||
# Start the agents
|
||||
result = agents.start()
|
||||
print(result)
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Start AutoAgents">
|
||||
Run your AutoAgents:
|
||||
```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>
|
||||
|
||||
</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="Start AutoAgents">
|
||||
Run your AutoAgents:
|
||||
```bash
|
||||
praisonai --auto "Create a movie script about a robot in Mars"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Understanding AutoAgents
|
||||
|
||||
<Card title="What are AutoAgents?" icon="question">
|
||||
AutoAgents automatically:
|
||||
- Creates appropriate AI agents based on your instructions
|
||||
- Assigns relevant tools to each agent
|
||||
- Breaks down tasks into manageable steps
|
||||
- Manages execution flow between agents
|
||||
- Handles agent coordination and task delegation
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Automatic Agent Creation" icon="wand-magic-sparkles">
|
||||
Creates specialized agents based on task requirements.
|
||||
</Card>
|
||||
<Card title="Smart Tool Assignment" icon="toolbox">
|
||||
Automatically assigns relevant tools to each agent.
|
||||
</Card>
|
||||
<Card title="Task Management" icon="list-check">
|
||||
Breaks down complex tasks into manageable steps.
|
||||
</Card>
|
||||
<Card title="Process Optimization" icon="gauge-high">
|
||||
Chooses optimal execution process (sequential/hierarchical).
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
# Basic usage with default settings
|
||||
agents = AutoAgents(
|
||||
instructions="Your high-level task description",
|
||||
tools=[tool1, tool2]
|
||||
)
|
||||
```
|
||||
|
||||
```python Advanced
|
||||
# Advanced usage with custom settings
|
||||
agents = AutoAgents(
|
||||
instructions="Your task description",
|
||||
tools=[tool1, tool2],
|
||||
max_agents=3,
|
||||
process="hierarchical",
|
||||
verbose=True,
|
||||
memory=True,
|
||||
allow_delegation=True
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
|
||||
# Create AutoAgents with advanced configuration
|
||||
agents = AutoAgents(
|
||||
instructions="Research and summarize recent AI developments",
|
||||
tools=[SerperDevTool, WikipediaTools],
|
||||
max_agents=3, # Maximum number of agents to create
|
||||
verbose=True, # Enable detailed logging
|
||||
process="hierarchical", # Use hierarchical process
|
||||
memory=True, # Enable memory for agents
|
||||
allow_delegation=True, # Allow task delegation
|
||||
max_rpm=60, # Maximum requests per minute
|
||||
max_execution_time=300, # Maximum execution time in seconds
|
||||
allow_code_execution=True, # Allow code execution
|
||||
code_execution_mode="safe", # Use safe mode for code execution
|
||||
self_reflect=True, # Enable agent self-reflection
|
||||
markdown=True # Enable markdown formatting
|
||||
)
|
||||
```
|
||||
|
||||
### Process Types
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Sequential Process">
|
||||
```python
|
||||
# Tasks are executed in sequence
|
||||
agents = AutoAgents(
|
||||
instructions="Your task",
|
||||
process="sequential"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Hierarchical Process">
|
||||
```python
|
||||
# Manager agent coordinates other agents
|
||||
agents = AutoAgents(
|
||||
instructions="Your task",
|
||||
process="hierarchical",
|
||||
manager_llm="gpt-4o" # Specify LLM for manager
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Clear Instructions">
|
||||
```python
|
||||
# Good instruction example
|
||||
agents = AutoAgents(
|
||||
instructions="""
|
||||
Research the latest developments in AI for 2024:
|
||||
1. Focus on breakthrough technologies
|
||||
2. Include real-world applications
|
||||
3. Consider future implications
|
||||
"""
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Tool Selection">
|
||||
```python
|
||||
# Provide relevant tools for the task
|
||||
|
||||
agents = AutoAgents(
|
||||
instructions="Research task",
|
||||
tools=[
|
||||
SerperDevTool, # For web search
|
||||
WikipediaTools, # For background info
|
||||
CustomTool # Your custom tool
|
||||
]
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Resource Management">
|
||||
|
||||
```python
|
||||
# Configure resource limits
|
||||
agents = AutoAgents(
|
||||
instructions="Your task",
|
||||
max_rpm=60, # Rate limiting
|
||||
max_execution_time=300, # Timeout
|
||||
max_agents=3 # Agent limit
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Tool Assignment Issues" icon="triangle-exclamation">
|
||||
If tools aren't being assigned correctly:
|
||||
- Check tool compatibility
|
||||
- Verify tool names
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Performance Issues" icon="gauge">
|
||||
If execution is slow:
|
||||
- Reduce max_agents
|
||||
- Adjust max_rpm
|
||||
- Consider process type
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## API Reference
|
||||
|
||||
### Main Parameters
|
||||
|
||||
<ResponseField name="instructions" type="str" required>
|
||||
High-level task description for the agents
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="tools" type="List[Any]">
|
||||
List of tools available to the agents
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="max_agents" type="int" default="3">
|
||||
Maximum number of agents to create
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="process" type="str" default="sequential">
|
||||
Process type: "sequential" or "hierarchical"
|
||||
</ResponseField>
|
||||
|
||||
### Optional Parameters
|
||||
|
||||
<ResponseField name="verbose" type="bool" default="False">
|
||||
Enable detailed logging
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="memory" type="bool" default="True">
|
||||
Enable agent memory
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="allow_delegation" type="bool" default="False">
|
||||
Allow agents to delegate tasks
|
||||
</ResponseField>
|
||||
|
||||
### Methods
|
||||
|
||||
<ResponseField name="start()" type="method">
|
||||
Start the agents synchronously
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="astart()" type="method">
|
||||
Start the agents asynchronously
|
||||
</ResponseField>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Examples" icon="code" href="./examples">
|
||||
Explore more examples in our examples directory
|
||||
</Card>
|
||||
<Card title="Custom Tools" icon="screwdriver-wrench" href="./tools">
|
||||
Learn how to create custom tools for your agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, provide clear instructions and appropriate tools for your use case.
|
||||
</Note>
|
||||
@@ -1,976 +0,0 @@
|
||||
---
|
||||
title: "AI Agents with Callbacks"
|
||||
sidebarTitle: "Callbacks Agent"
|
||||
description: "Learn how to implement callbacks to monitor and log AI agent interactions, errors, and task completions."
|
||||
icon: "bell"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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 (
|
||||
register_display_callback,
|
||||
Agent,
|
||||
Task,
|
||||
PraisonAIAgents
|
||||
)
|
||||
|
||||
def simple_callback(message=None, response=None, **kwargs):
|
||||
print(f"Received message: {message}")
|
||||
print(f"Got response: {response}")
|
||||
|
||||
# Register as synchronous callback
|
||||
register_display_callback('interaction', simple_callback, is_async=False)
|
||||
|
||||
# For async callbacks
|
||||
async def async_simple_callback(message=None, response=None, **kwargs):
|
||||
await asyncio.sleep(0) # Non-blocking pause
|
||||
print(f"Received message: {message}")
|
||||
print(f"Got response: {response}")
|
||||
|
||||
# Register as async callback
|
||||
register_display_callback('interaction', async_simple_callback, is_async=True)
|
||||
|
||||
# Create an agent
|
||||
agent = Agent(
|
||||
name="MyAgent",
|
||||
role="Assistant",
|
||||
goal="Help with tasks",
|
||||
backstory="I am a helpful assistant",
|
||||
verbose=True # Enable verbose mode to see callbacks in action
|
||||
)
|
||||
|
||||
# Create a task
|
||||
task = Task(
|
||||
name="simple_task",
|
||||
description="Say hello",
|
||||
agent=agent,
|
||||
expected_output="A greeting"
|
||||
)
|
||||
|
||||
# Run the agent
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task]
|
||||
)
|
||||
agents.start()
|
||||
```
|
||||
</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
|
||||
topic: demonstrate basic callbacks
|
||||
roles:
|
||||
assistant:
|
||||
backstory: I am a helpful assistant focused on demonstrating callback functionality
|
||||
goal: Help demonstrate callback functionality
|
||||
role: Assistant
|
||||
tasks:
|
||||
simple_task:
|
||||
description: Say hello and demonstrate basic callbacks
|
||||
expected_output: A greeting with callback logs
|
||||
tools:
|
||||
- basic_tool
|
||||
callbacks:
|
||||
interaction:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: interactions.log
|
||||
```
|
||||
</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 functions
|
||||
</Note>
|
||||
|
||||
## Understanding Callbacks
|
||||
|
||||
<Card title="What are Callbacks?" icon="question">
|
||||
Callbacks are functions that get called automatically when specific events occur in your AI agents:
|
||||
- Interactions between user and agent
|
||||
- Error messages
|
||||
- Tool calls
|
||||
- Self-reflection moments
|
||||
- Task completion
|
||||
- Generation progress
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Interaction Callback" icon="comments">
|
||||
Triggered when the agent interacts with users
|
||||
</Card>
|
||||
<Card title="Error Callback" icon="triangle-exclamation">
|
||||
Called when errors occur
|
||||
</Card>
|
||||
<Card title="Tool Call Callback" icon="wrench">
|
||||
Activated when tools are used
|
||||
</Card>
|
||||
<Card title="Self Reflection Callback" icon="brain">
|
||||
Triggered during agent self-reflection
|
||||
</Card>
|
||||
<Card title="Instruction Callback" icon="list-check">
|
||||
Called when instructions are processed
|
||||
</Card>
|
||||
<Card title="Generating Callback" icon="spinner">
|
||||
Activated during content generation
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Basic Implementation
|
||||
|
||||
### 1. Simple Logging Callback
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
import logging
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
def log_callback(message=None, **kwargs):
|
||||
logging.info(f"Agent message: {message}")
|
||||
|
||||
# Register synchronous callback
|
||||
register_display_callback('interaction', log_callback, is_async=False)
|
||||
|
||||
# Register asynchronous callback
|
||||
async def async_log_callback(message=None, **kwargs):
|
||||
await asyncio.sleep(0)
|
||||
logging.info(f"Agent message: {message}")
|
||||
|
||||
# Register as async callback
|
||||
register_display_callback('interaction', async_log_callback, is_async=True)
|
||||
```
|
||||
|
||||
```python Advanced
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# Setup logging with file output
|
||||
logging.basicConfig(
|
||||
filename='ai_interactions.log',
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
def detailed_callback(message=None, response=None, **kwargs):
|
||||
logging.info(f"""
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
Response: {response}
|
||||
Additional Info: {kwargs}
|
||||
""")
|
||||
|
||||
register_display_callback('interaction', detailed_callback)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: demonstrate logging callbacks
|
||||
roles:
|
||||
logger:
|
||||
backstory: Expert in logging and monitoring system interactions
|
||||
goal: Demonstrate comprehensive logging capabilities
|
||||
role: Logging Specialist
|
||||
tasks:
|
||||
logging_task:
|
||||
description: Perform actions that trigger various log events
|
||||
expected_output: Comprehensive log entries for different events
|
||||
tools:
|
||||
- logging_tool
|
||||
callbacks:
|
||||
logging:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: ai_interactions.log
|
||||
format: "%(asctime)s - %(levelname)s - %(message)s"
|
||||
level: INFO
|
||||
handlers:
|
||||
- type: file
|
||||
filename: ai_interactions.log
|
||||
- type: console
|
||||
events:
|
||||
- interaction
|
||||
- error
|
||||
- tool_call
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### 2. Multiple Callback Types
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
# Error callback
|
||||
def error_callback(message=None):
|
||||
logging.error(f"Error occurred: {message}")
|
||||
|
||||
# Tool call callback
|
||||
def tool_callback(message=None):
|
||||
logging.info(f"Tool called: {message}")
|
||||
|
||||
# Register multiple callbacks
|
||||
register_display_callback('error', error_callback)
|
||||
register_display_callback('tool_call', tool_callback)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: demonstrate multiple callback types
|
||||
roles:
|
||||
multi_agent:
|
||||
backstory: Specialized in demonstrating various callback functionalities
|
||||
goal: Show different types of callbacks in action
|
||||
role: Callback Specialist
|
||||
tasks:
|
||||
multi_callback_task:
|
||||
description: Trigger different types of callbacks
|
||||
expected_output: Logs showing various callback types in action
|
||||
tools:
|
||||
- error_tool
|
||||
- callback_tool
|
||||
callbacks:
|
||||
error:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: ai_interactions.log
|
||||
level: ERROR
|
||||
tool_call:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: ai_interactions.log
|
||||
level: INFO
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a full implementation showing all callback types and proper logging:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents, register_display_callback
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
filename='ai_interactions.log',
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
# Interaction callback
|
||||
def interaction_callback(message=None, response=None, markdown=None, generation_time=None):
|
||||
logging.info(f"""
|
||||
=== INTERACTION ===
|
||||
Time: {datetime.now()}
|
||||
Generation Time: {generation_time}s
|
||||
Message: {message}
|
||||
Response: {response}
|
||||
Markdown: {markdown}
|
||||
""")
|
||||
|
||||
# Error callback
|
||||
def error_callback(message=None):
|
||||
logging.error(f"""
|
||||
=== ERROR ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
# Tool call callback
|
||||
def tool_call_callback(message=None):
|
||||
logging.info(f"""
|
||||
=== TOOL CALL ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
# Register callbacks
|
||||
register_display_callback('interaction', interaction_callback)
|
||||
register_display_callback('error', error_callback)
|
||||
register_display_callback('tool_call', tool_call_callback)
|
||||
|
||||
agent = Agent(
|
||||
name="CallbackAgent",
|
||||
role="Assistant",
|
||||
goal="Demonstrate callbacks",
|
||||
backstory="I am a helpful assistant",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
task = Task(
|
||||
name="callback_task",
|
||||
description="Show how callbacks work",
|
||||
agent=agent,
|
||||
expected_output="Demonstration complete"
|
||||
)
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: demonstrate complete callback system
|
||||
roles:
|
||||
callback_agent:
|
||||
backstory: Expert in comprehensive callback implementation
|
||||
goal: Demonstrate a complete callback system
|
||||
role: Callback Expert
|
||||
tasks:
|
||||
callback_demo:
|
||||
description: Show how callbacks work in a complete system
|
||||
expected_output: Demonstration of all callback types
|
||||
tools:
|
||||
- callback_tool
|
||||
callbacks:
|
||||
interaction:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: ai_interactions.log
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
level: INFO
|
||||
error:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: ai_interactions.log
|
||||
level: ERROR
|
||||
tool_call:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: ai_interactions.log
|
||||
level: INFO
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Advanced Examples
|
||||
|
||||
- All callback types
|
||||
- Comprehensive logging
|
||||
- Task callbacks
|
||||
- Tool integration
|
||||
- Multiple agents
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents, error_logs, register_display_callback
|
||||
from duckduckgo_search import DDGS
|
||||
from rich.console import Console
|
||||
import json
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
filename='ai_interactions.log',
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
# Callback functions for different display types
|
||||
def interaction_callback(message=None, response=None, markdown=None, generation_time=None):
|
||||
"""Callback for display_interaction"""
|
||||
logging.info(f"""
|
||||
=== INTERACTION ===
|
||||
Time: {datetime.now()}
|
||||
Generation Time: {generation_time}s
|
||||
Message: {message}
|
||||
Response: {response}
|
||||
Markdown: {markdown}
|
||||
""")
|
||||
|
||||
def error_callback(message=None):
|
||||
"""Callback for display_error"""
|
||||
logging.error(f"""
|
||||
=== ERROR ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
def tool_call_callback(message=None):
|
||||
"""Callback for display_tool_call"""
|
||||
logging.info(f"""
|
||||
=== TOOL CALL ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
def instruction_callback(message=None):
|
||||
"""Callback for display_instruction"""
|
||||
logging.info(f"""
|
||||
=== INSTRUCTION ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
def self_reflection_callback(message=None):
|
||||
"""Callback for display_self_reflection"""
|
||||
logging.info(f"""
|
||||
=== SELF REFLECTION ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
def generating_callback(content=None, elapsed_time=None):
|
||||
"""Callback for display_generating"""
|
||||
logging.info(f"""
|
||||
=== GENERATING ===
|
||||
Time: {datetime.now()}
|
||||
Content: {content}
|
||||
Elapsed Time: {elapsed_time}
|
||||
""")
|
||||
|
||||
# Register all callbacks
|
||||
register_display_callback('interaction', interaction_callback)
|
||||
register_display_callback('error', error_callback)
|
||||
register_display_callback('tool_call', tool_call_callback)
|
||||
register_display_callback('instruction', instruction_callback)
|
||||
register_display_callback('self_reflection', self_reflection_callback)
|
||||
# register_display_callback('generating', generating_callback)
|
||||
|
||||
def task_callback(output):
|
||||
"""Callback for task completion"""
|
||||
logging.info(f"""
|
||||
=== TASK COMPLETED ===
|
||||
Time: {datetime.now()}
|
||||
Description: {output.description}
|
||||
Agent: {output.agent}
|
||||
Output: {output.raw[:200]}...
|
||||
""")
|
||||
|
||||
def internet_search_tool(query) -> list:
|
||||
"""
|
||||
Perform a search using DuckDuckGo.
|
||||
|
||||
Args:
|
||||
query (str): The search query.
|
||||
|
||||
Returns:
|
||||
list: A list of search result titles and URLs.
|
||||
"""
|
||||
try:
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=10):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", "")
|
||||
})
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during DuckDuckGo search: {e}")
|
||||
return []
|
||||
|
||||
def main():
|
||||
# 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,
|
||||
allow_delegation=False,
|
||||
tools=[internet_search_tool],
|
||||
llm="gpt-4o",
|
||||
markdown=True,
|
||||
reflect_llm="gpt-4o",
|
||||
min_reflect=2,
|
||||
max_reflect=4
|
||||
)
|
||||
|
||||
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.""",
|
||||
verbose=True,
|
||||
allow_delegation=True,
|
||||
llm="gpt-4o",
|
||||
tools=[],
|
||||
markdown=True
|
||||
)
|
||||
|
||||
# Create tasks with callbacks
|
||||
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,
|
||||
tools=[internet_search_tool],
|
||||
callback=task_callback
|
||||
)
|
||||
|
||||
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,
|
||||
context=[task1],
|
||||
callback=task_callback,
|
||||
tools=[]
|
||||
)
|
||||
|
||||
task3 = Task(
|
||||
name="json_task",
|
||||
description="""Create a json object with a title of "My Task" and content of "My content".""",
|
||||
expected_output="""JSON output with title and content""",
|
||||
agent=researcher,
|
||||
callback=task_callback
|
||||
)
|
||||
|
||||
task4 = Task(
|
||||
name="save_output_task",
|
||||
description="""Save the AI blog post to a file""",
|
||||
expected_output="""File saved successfully""",
|
||||
agent=writer,
|
||||
context=[task2],
|
||||
output_file='test.txt',
|
||||
create_directory=True,
|
||||
callback=task_callback
|
||||
)
|
||||
|
||||
# Create and run agents manager
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2, task3, task4],
|
||||
verbose=True,
|
||||
process="sequential",
|
||||
manager_llm="gpt-4o"
|
||||
)
|
||||
|
||||
agents.start()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: demonstrate advanced callback features
|
||||
roles:
|
||||
researcher:
|
||||
backstory: Expert at a technology research group specializing in AI trends
|
||||
goal: Uncover cutting-edge developments in AI and data science
|
||||
role: Senior Research Analyst
|
||||
tasks:
|
||||
research_task:
|
||||
description: Analyze 2024's AI advancements
|
||||
expected_output: A detailed report on 2024 AI advancements
|
||||
tools:
|
||||
- internet_search_tool
|
||||
writer:
|
||||
backstory: Content strategist skilled in technical communication
|
||||
goal: Craft compelling content on tech advancements
|
||||
role: Tech Content Strategist
|
||||
tasks:
|
||||
writing_task:
|
||||
description: Create a blog post about major AI advancements
|
||||
expected_output: A blog post of at least 4 paragraphs
|
||||
save_output_task:
|
||||
description: Save the AI blog post to a file
|
||||
expected_output: File saved successfully
|
||||
tools:
|
||||
- file_tool
|
||||
callbacks:
|
||||
interaction:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: advanced_interactions.log
|
||||
error:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: advanced_errors.log
|
||||
tool_call:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: advanced_tools.log
|
||||
instruction:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: advanced_instructions.log
|
||||
self_reflection:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: advanced_reflections.log
|
||||
generating:
|
||||
type: sync
|
||||
enabled: true
|
||||
log_file: advanced_generating.log
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Async Callbacks
|
||||
|
||||
Async callbacks allow you to handle events asynchronously, which is particularly useful for long-running operations or when dealing with multiple agents simultaneously.
|
||||
|
||||
### Basic Async Callback Implementation
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import register_display_callback
|
||||
|
||||
async def async_interaction_callback(message=None, response=None, **kwargs):
|
||||
"""Async callback for handling interactions"""
|
||||
await asyncio.sleep(0) # Non-blocking pause
|
||||
print(f"Async processing - Message: {message}")
|
||||
print(f"Response: {response}")
|
||||
|
||||
# Register the async callback
|
||||
register_display_callback('interaction', async_interaction_callback)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: demonstrate basic async callbacks
|
||||
roles:
|
||||
async_handler:
|
||||
backstory: Specialized in asynchronous operations and callbacks
|
||||
goal: Demonstrate basic async callback functionality
|
||||
role: Async Specialist
|
||||
tasks:
|
||||
async_demo:
|
||||
description: Show basic async callback functionality
|
||||
expected_output: Demonstration of async callbacks
|
||||
tools:
|
||||
- async_tool
|
||||
callbacks:
|
||||
interaction:
|
||||
type: async
|
||||
enabled: true
|
||||
log_file: async_interactions.log
|
||||
format: "%(asctime)s - %(levelname)s - %(message)s"
|
||||
level: INFO
|
||||
non_blocking: true
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Complete Async Example
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents, register_display_callback
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# Setup async logging
|
||||
async def setup_async_logging():
|
||||
logging.basicConfig(
|
||||
filename='async_ai_interactions.log',
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
|
||||
# Async callbacks
|
||||
async def async_interaction_callback(message=None, response=None, markdown=None, generation_time=None):
|
||||
await asyncio.sleep(0)
|
||||
logging.info(f"""
|
||||
=== ASYNC INTERACTION ===
|
||||
Time: {datetime.now()}
|
||||
Generation Time: {generation_time}s
|
||||
Message: {message}
|
||||
Response: {response}
|
||||
""")
|
||||
|
||||
async def async_error_callback(message=None):
|
||||
await asyncio.sleep(0)
|
||||
logging.error(f"""
|
||||
=== ASYNC ERROR ===
|
||||
Time: {datetime.now()}
|
||||
Message: {message}
|
||||
""")
|
||||
|
||||
# Register async callbacks
|
||||
register_display_callback('interaction', async_interaction_callback, is_async=True)
|
||||
register_display_callback('error', async_error_callback, is_async=True)
|
||||
|
||||
# Create async task callback
|
||||
async def async_task_callback(output):
|
||||
await asyncio.sleep(0)
|
||||
logging.info(f"""
|
||||
=== ASYNC TASK COMPLETED ===
|
||||
Time: {datetime.now()}
|
||||
Description: {output.description}
|
||||
Agent: {output.agent}
|
||||
Output: {output.raw[:200]}...
|
||||
""")
|
||||
|
||||
async def main():
|
||||
await setup_async_logging()
|
||||
|
||||
# Create agent with async capabilities
|
||||
agent = Agent(
|
||||
name="AsyncAgent",
|
||||
role="Assistant",
|
||||
goal="Demonstrate async callbacks",
|
||||
backstory="I am an async-capable assistant",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create task with async callback
|
||||
task = Task(
|
||||
name="async_task",
|
||||
description="Demonstrate async callbacks",
|
||||
agent=agent,
|
||||
expected_output="Async demonstration complete",
|
||||
callback=async_task_callback
|
||||
)
|
||||
|
||||
# Create and run agents with async support
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
await agents.start_async()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: demonstrate complete async system
|
||||
roles:
|
||||
async_agent:
|
||||
backstory: Expert in asynchronous operations and comprehensive logging
|
||||
goal: Demonstrate complete async callback system
|
||||
role: Async Expert
|
||||
tasks:
|
||||
async_task:
|
||||
description: Demonstrate comprehensive async callbacks
|
||||
expected_output: Complete async callback demonstration
|
||||
tools:
|
||||
- async_tool
|
||||
callbacks:
|
||||
interaction:
|
||||
type: async
|
||||
enabled: true
|
||||
log_file: async_interactions.log
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
level: INFO
|
||||
non_blocking: true
|
||||
error:
|
||||
type: async
|
||||
enabled: true
|
||||
log_file: async_errors.log
|
||||
level: ERROR
|
||||
non_blocking: true
|
||||
task:
|
||||
type: async
|
||||
enabled: true
|
||||
log_file: async_tasks.log
|
||||
level: INFO
|
||||
non_blocking: true
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Async Display Functions
|
||||
|
||||
PraisonAI Agents provides several async versions of display functions, prefixed with 'a'. Here's the complete list:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="adisplay_instruction" icon="list-check">
|
||||
```python
|
||||
async def adisplay_instruction(
|
||||
message: str,
|
||||
console=None
|
||||
)
|
||||
```
|
||||
Async version for showing instructions.
|
||||
</Card>
|
||||
|
||||
<Card title="adisplay_tool_call" icon="wrench">
|
||||
```python
|
||||
async def adisplay_tool_call(
|
||||
message: str,
|
||||
console=None
|
||||
)
|
||||
```
|
||||
Async version for displaying tool calls.
|
||||
</Card>
|
||||
|
||||
<Card title="adisplay_error" icon="triangle-exclamation">
|
||||
```python
|
||||
async def adisplay_error(
|
||||
message: str,
|
||||
console=None
|
||||
)
|
||||
```
|
||||
Async version for error messages.
|
||||
</Card>
|
||||
|
||||
<Card title="adisplay_generating" icon="spinner">
|
||||
```python
|
||||
async def adisplay_generating(
|
||||
content: str = "",
|
||||
start_time: Optional[float] = None
|
||||
)
|
||||
```
|
||||
Async version for showing generation progress.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from praisonaiagents import (
|
||||
adisplay_interaction,
|
||||
adisplay_error,
|
||||
adisplay_tool_call
|
||||
)
|
||||
|
||||
async def main():
|
||||
# Display an interaction
|
||||
await adisplay_interaction(
|
||||
message="What's the weather?",
|
||||
response="Let me check that for you.",
|
||||
generation_time=0.5
|
||||
)
|
||||
|
||||
# Display a tool call
|
||||
await adisplay_tool_call(
|
||||
"Calling weather API for location data..."
|
||||
)
|
||||
|
||||
# Handle an error
|
||||
try:
|
||||
raise Exception("API connection failed")
|
||||
except Exception as e:
|
||||
await adisplay_error(str(e))
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Error Handling" icon="shield-check">
|
||||
- Implement proper error handling
|
||||
- Use try-catch blocks
|
||||
- Log errors appropriately
|
||||
- Handle edge cases
|
||||
</Card>
|
||||
<Card title="Performance" icon="gauge-high">
|
||||
- Keep callbacks lightweight
|
||||
- Avoid blocking operations
|
||||
- Use async when appropriate
|
||||
- Monitor resource usage
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
Remember to handle callbacks efficiently and implement proper error handling to ensure smooth agent operations.
|
||||
</Note>
|
||||
@@ -1,353 +0,0 @@
|
||||
---
|
||||
title: "Code Execution AI Agent"
|
||||
sidebarTitle: "Code Agent"
|
||||
description: "Learn how to create AI agents that can write and execute Python code safely using e2b code interpreter."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the required packages:
|
||||
```bash
|
||||
pip install praisonaiagents e2b_code_interpreter
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Set API Key">
|
||||
Set your OpenAI API key and E2B API key as an environment variable in your terminal:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
export E2B_API_KEY=your_e2b_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
|
||||
from e2b_code_interpreter import Sandbox
|
||||
|
||||
def code_interpreter(code: str):
|
||||
print(f"\n{'='*50}\n> Running following AI-generated code:\n{code}\n{'='*50}")
|
||||
exec_result = Sandbox().run_code(code)
|
||||
if exec_result.error:
|
||||
print("[Code Interpreter error]", exec_result.error)
|
||||
return {"error": str(exec_result.error)}
|
||||
else:
|
||||
results = []
|
||||
for result in exec_result.results:
|
||||
if hasattr(result, '__iter__'):
|
||||
results.extend(list(result))
|
||||
else:
|
||||
results.append(str(result))
|
||||
logs = {"stdout": list(exec_result.logs.stdout), "stderr": list(exec_result.logs.stderr)}
|
||||
return json.dumps({"results": results, "logs": logs})
|
||||
|
||||
# Create code agent
|
||||
code_agent = Agent(
|
||||
role="Code Developer",
|
||||
goal="Write and execute Python code",
|
||||
backstory="Expert Python developer with strong coding skills",
|
||||
tools=[code_interpreter],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create a task
|
||||
task = Task(
|
||||
description="Write and execute a Python script to analyze data",
|
||||
expected_output="Working Python script with execution results",
|
||||
agent=code_agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[code_agent],
|
||||
tasks=[task],
|
||||
process="sequential",
|
||||
verbose=2
|
||||
)
|
||||
|
||||
# Start execution
|
||||
agents.start()
|
||||
```
|
||||
</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 e2b_code_interpreter
|
||||
```
|
||||
</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
|
||||
topic: write and execute Python code
|
||||
roles:
|
||||
developer:
|
||||
backstory: Expert Python developer with strong coding skills.
|
||||
goal: Write and execute Python code safely
|
||||
role: Code Developer
|
||||
tools:
|
||||
- code_interpreter
|
||||
tasks:
|
||||
coding_task:
|
||||
description: Write and execute a Python script to analyze data.
|
||||
expected_output: Working Python script with execution results.
|
||||
```
|
||||
</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).
|
||||
- e2b_code_interpreter package installed
|
||||
</Note>
|
||||
|
||||
## Understanding Code Agents
|
||||
|
||||
<Card title="What are Code Agents?" icon="question">
|
||||
Code agents are specialized AI agents that can:
|
||||
- Write Python code based on requirements
|
||||
- Execute code safely in a sandboxed environment
|
||||
- Handle code execution results and errors
|
||||
- Work together in a pipeline (writer → executor)
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Code Writer" icon="pencil">
|
||||
Writes Python code based on requirements.
|
||||
</Card>
|
||||
<Card title="Safe Execution" icon="shield">
|
||||
Executes code in a sandboxed environment.
|
||||
</Card>
|
||||
<Card title="Error Handling" icon="bug">
|
||||
Manages code execution errors and debugging.
|
||||
</Card>
|
||||
<Card title="Results Processing" icon="output">
|
||||
Processes and formats execution results.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent Code Development
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the required packages:
|
||||
```bash
|
||||
pip install praisonaiagents e2b_code_interpreter
|
||||
```
|
||||
</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
|
||||
from e2b_code_interpreter import Sandbox
|
||||
|
||||
def code_interpreter(code: str):
|
||||
print(f"\n{'='*50}\n> Running following AI-generated code:\n{code}\n{'='*50}")
|
||||
exec_result = Sandbox().run_code(code)
|
||||
if exec_result.error:
|
||||
print("[Code Interpreter error]", exec_result.error)
|
||||
return {"error": str(exec_result.error)}
|
||||
else:
|
||||
results = []
|
||||
for result in exec_result.results:
|
||||
if hasattr(result, '__iter__'):
|
||||
results.extend(list(result))
|
||||
else:
|
||||
results.append(str(result))
|
||||
logs = {"stdout": list(exec_result.logs.stdout), "stderr": list(exec_result.logs.stderr)}
|
||||
return json.dumps({"results": results, "logs": logs})
|
||||
|
||||
# Create first agent for writing code
|
||||
code_writer = Agent(
|
||||
role="Code Writer",
|
||||
goal="Write efficient Python code",
|
||||
backstory="Expert Python developer specializing in code writing",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create second agent for code execution
|
||||
code_executor = Agent(
|
||||
role="Code Executor",
|
||||
goal="Execute and validate Python code",
|
||||
backstory="Expert in code execution and testing",
|
||||
tools=[code_interpreter],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create first task
|
||||
writing_task = Task(
|
||||
description="Write a Python script for data analysis",
|
||||
expected_output="Complete Python script",
|
||||
agent=code_writer
|
||||
)
|
||||
|
||||
# Create second task
|
||||
execution_task = Task(
|
||||
description="Execute and validate the Python script",
|
||||
expected_output="Execution results and validation",
|
||||
agent=code_executor
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[code_writer, code_executor],
|
||||
tasks=[writing_task, execution_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
agents.start()
|
||||
```
|
||||
</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 e2b_code_interpreter
|
||||
```
|
||||
</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
|
||||
topic: develop and execute Python code
|
||||
roles:
|
||||
writer:
|
||||
backstory: Expert Python developer specializing in code writing.
|
||||
goal: Write efficient Python code
|
||||
role: Code Writer
|
||||
tasks:
|
||||
writing_task:
|
||||
description: Write a Python script for data analysis.
|
||||
expected_output: Complete Python script.
|
||||
|
||||
executor:
|
||||
backstory: Expert in code execution and testing.
|
||||
goal: Execute and validate Python code
|
||||
role: Code Executor
|
||||
tools:
|
||||
- code_interpreter
|
||||
tasks:
|
||||
execution_task:
|
||||
description: Execute and validate the Python script.
|
||||
expected_output: Execution results and validation.
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with advanced code execution configuration
|
||||
agent = Agent(
|
||||
role="Code Developer",
|
||||
goal="Write and execute Python code",
|
||||
backstory="Expert in Python development",
|
||||
tools=[code_interpreter],
|
||||
verbose=True, # Enable detailed logging
|
||||
llm="gpt-4o" # Language model to use
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Code Errors" icon="triangle-exclamation">
|
||||
If code execution fails:
|
||||
- Check syntax errors
|
||||
- Verify package imports
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Sandbox Issues" icon="box">
|
||||
If sandbox execution fails:
|
||||
- Check environment setup
|
||||
- Verify permissions
|
||||
- Review resource limits
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure code is properly formatted and tested in the sandbox environment before production use.
|
||||
</Note>
|
||||
@@ -1,347 +0,0 @@
|
||||
---
|
||||
title: "Math AI Agent"
|
||||
sidebarTitle: "Math Agent"
|
||||
description: "Learn how to create AI agents that can perform complex mathematical calculations, unit conversions, and financial computations."
|
||||
icon: "calculator"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents sympy pint
|
||||
```
|
||||
</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
|
||||
from praisonaiagents.tools import (
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
)
|
||||
|
||||
# Create math agent
|
||||
math_agent = Agent(
|
||||
role="Math Expert",
|
||||
goal="Perform complex mathematical calculations",
|
||||
backstory="Expert in mathematical computations and analysis",
|
||||
tools=[
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create a task
|
||||
task = Task(
|
||||
description="Calculate compound interest and statistical analysis",
|
||||
expected_output="Detailed mathematical analysis",
|
||||
agent=math_agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[math_agent],
|
||||
tasks=[task],
|
||||
process="sequential",
|
||||
verbose=2
|
||||
)
|
||||
|
||||
# Start execution
|
||||
agents.start()
|
||||
```
|
||||
</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 sympy pint
|
||||
```
|
||||
</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
|
||||
topic: perform mathematical analysis
|
||||
roles:
|
||||
mathematician:
|
||||
backstory: Expert in mathematical computations and analysis.
|
||||
goal: Perform complex mathematical calculations
|
||||
role: Math Expert
|
||||
tools:
|
||||
- evaluate
|
||||
- solve_equation
|
||||
- convert_units
|
||||
- calculate_statistics
|
||||
- calculate_financial
|
||||
tasks:
|
||||
math_task:
|
||||
description: Calculate compound interest and perform statistical analysis.
|
||||
expected_output: Detailed mathematical analysis with results.
|
||||
```
|
||||
</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).
|
||||
- sympy and pint packages (automatically installed when needed)
|
||||
</Note>
|
||||
|
||||
## Understanding Math Agents
|
||||
|
||||
<Card title="What are Math Agents?" icon="question">
|
||||
Math agents are specialized AI agents that can:
|
||||
- Evaluate mathematical expressions
|
||||
- Solve equations and systems of equations
|
||||
- Perform unit conversions
|
||||
- Calculate statistical metrics
|
||||
- Handle financial calculations
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Expression Evaluator" icon="function">
|
||||
Evaluates mathematical expressions and formulas.
|
||||
</Card>
|
||||
<Card title="Equation Solver" icon="equals">
|
||||
Solves mathematical equations and systems.
|
||||
</Card>
|
||||
<Card title="Unit Converter" icon="arrows-rotate">
|
||||
Converts between different units of measurement.
|
||||
</Card>
|
||||
<Card title="Statistical Calculator" icon="chart-simple">
|
||||
Calculates statistical metrics and analysis.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent AI Math Analysis
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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
|
||||
from praisonaiagents.tools import (
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
)
|
||||
|
||||
# Create first agent for calculations
|
||||
calculator = Agent(
|
||||
role="Mathematical Calculator",
|
||||
goal="Perform complex calculations and analysis",
|
||||
backstory="Expert in mathematical computations",
|
||||
tools=[evaluate, solve_equation, convert_units],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create second agent for statistics
|
||||
statistician = Agent(
|
||||
role="Statistical Analyst",
|
||||
goal="Perform statistical analysis and interpretation",
|
||||
backstory="Expert in statistical analysis",
|
||||
tools=[calculate_statistics, calculate_financial],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create first task
|
||||
calc_task = Task(
|
||||
description="Calculate compound interest for $10000 at 5% for 3 years",
|
||||
expected_output="Detailed interest calculation",
|
||||
agent=calculator
|
||||
)
|
||||
|
||||
# Create second task
|
||||
stats_task = Task(
|
||||
description="Analyze the monthly interest distribution",
|
||||
expected_output="Statistical analysis of interest data",
|
||||
agent=statistician
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[calculator, statistician],
|
||||
tasks=[calc_task, stats_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
agents.start()
|
||||
```
|
||||
</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
|
||||
topic: perform financial and statistical analysis
|
||||
roles:
|
||||
calculator:
|
||||
backstory: Expert in mathematical computations and analysis.
|
||||
goal: Perform complex calculations
|
||||
role: Mathematical Calculator
|
||||
tools:
|
||||
- evaluate
|
||||
- solve_equation
|
||||
- convert_units
|
||||
tasks:
|
||||
calc_task:
|
||||
description: Calculate compound interest for investment scenario.
|
||||
expected_output: Detailed interest calculations.
|
||||
|
||||
statistician:
|
||||
backstory: Expert in statistical analysis and interpretation.
|
||||
goal: Analyze numerical data and patterns
|
||||
role: Statistical Analyst
|
||||
tools:
|
||||
- calculate_statistics
|
||||
- calculate_financial
|
||||
tasks:
|
||||
stats_task:
|
||||
description: Analyze the monthly interest distribution.
|
||||
expected_output: Statistical analysis report.
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with advanced math configuration
|
||||
agent = Agent(
|
||||
role="Math Expert",
|
||||
goal="Perform complex mathematical analysis",
|
||||
backstory="Expert in mathematical computations",
|
||||
tools=[
|
||||
evaluate,
|
||||
solve_equation,
|
||||
convert_units,
|
||||
calculate_statistics,
|
||||
calculate_financial
|
||||
],
|
||||
verbose=True, # Enable detailed logging
|
||||
llm="gpt-4o" # Language model to use
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Expression Errors" icon="triangle-exclamation">
|
||||
If expressions are not evaluating:
|
||||
- Check syntax and formatting
|
||||
- Verify variable definitions
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Calculation Issues" icon="calculator">
|
||||
If calculations are incorrect:
|
||||
- Review input formats
|
||||
- Check unit compatibility
|
||||
- Verify formula structure
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure mathematical expressions and units are properly formatted for your specific use case.
|
||||
</Note>
|
||||
@@ -1,286 +0,0 @@
|
||||
---
|
||||
title: "Mini AI Agents"
|
||||
description: "Learn how to create simple yet powerful AI agents in just a few lines of code."
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
Create multiple AI agents that can work together in just a few lines of code!
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents duckduckgo_search
|
||||
```
|
||||
</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 Your Agents">
|
||||
<CodeGroup>
|
||||
```python Single Agent
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
summarise_agent = Agent(instructions="Summarise Photosynthesis")
|
||||
agents = PraisonAIAgents(agents=[summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
```python Multiple Agents
|
||||
# Agent with Internet Search Tool
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
research_agent = Agent(instructions="Research about AI 2024", tools=[Tools.internet_search])
|
||||
summarise_agent = Agent(instructions="Summarise research agent's findings")
|
||||
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
|
||||
agents.start()
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Your Agents">
|
||||
Execute your agents by running:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
<Steps>
|
||||
<Step title="Install Package">
|
||||
First, install the PraisonAI Agents package:
|
||||
```bash
|
||||
pip install praisonaiagents duckduckgo_search
|
||||
```
|
||||
</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 Your Agents">
|
||||
<CodeGroup>
|
||||
```yaml Single Agent
|
||||
# Create a new file `agents.yaml` with the following content:
|
||||
roles:
|
||||
summarise_agent
|
||||
instructions: Summarise Photosynthesis
|
||||
```
|
||||
```yaml Multiple Agents
|
||||
# Create a new file `agents.yaml` with the following content:
|
||||
# Agent with Internet Search Tool
|
||||
roles:
|
||||
research_agent
|
||||
instructions: Research about AI 2024
|
||||
tools:
|
||||
- internet_search
|
||||
summarise_agent
|
||||
instructions: Summarise research agent's findings
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
<Step title="Run Your Agents">
|
||||
Execute your agents by running:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Note>
|
||||
**Prerequisites**
|
||||
- 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>
|
||||
<br />
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/OkvYp5aAGSg"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
<br />
|
||||
|
||||
## Understanding Mini AI Agents
|
||||
|
||||
<Card title="What are Mini AI Agents?" icon="question">
|
||||
Mini AI Agents are simplified yet powerful AI agents that can:
|
||||
- Work together to accomplish tasks
|
||||
- Use tools like internet search
|
||||
- Process and summarize information
|
||||
- Execute tasks sequentially
|
||||
</Card>
|
||||
|
||||
## Key Components
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent" icon="user-robot">
|
||||
Individual AI agents with specific roles and capabilities
|
||||
```python
|
||||
Agent(instructions="Your agent's role description")
|
||||
```
|
||||
</Card>
|
||||
<Card title="Tools" icon="wrench">
|
||||
Built-in tools that agents can use
|
||||
```python
|
||||
tools=[Tools.internet_search]
|
||||
```
|
||||
</Card>
|
||||
<Card title="Agents Manager" icon="users">
|
||||
Coordinates multiple agents
|
||||
```python
|
||||
Agents(agents=[agent1, agent2])
|
||||
```
|
||||
</Card>
|
||||
<Card title="Sequential Flow" icon="arrow-right">
|
||||
Agents work in sequence, passing results to each other
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Available Tools
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Internet Search" icon="search">
|
||||
```python
|
||||
Tools.internet_search
|
||||
```
|
||||
Search the internet using DuckDuckGo
|
||||
<Note>
|
||||
Requires: `pip install duckduckgo_search`
|
||||
</Note>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Custom Instructions
|
||||
|
||||
<CodeGroup>
|
||||
```python Basic
|
||||
# Simple instructions
|
||||
research_agent = Agent(
|
||||
instructions="Research about climate change"
|
||||
)
|
||||
```
|
||||
|
||||
```python Advanced
|
||||
# Detailed instructions
|
||||
research_agent = Agent(
|
||||
instructions="""
|
||||
You are a research agent focused on gathering information about:
|
||||
1. Latest AI developments in 2024
|
||||
2. Major breakthroughs in machine learning
|
||||
3. New AI applications in industry
|
||||
|
||||
Provide detailed and accurate information from reliable sources.
|
||||
"""
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Agent Instructions">
|
||||
Write clear and specific instructions:
|
||||
```python
|
||||
# Good
|
||||
Agent(instructions="Research and analyze the latest AI developments in 2024")
|
||||
|
||||
# Too vague
|
||||
Agent(instructions="Research AI")
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Tool Usage">
|
||||
Provide tools only to agents that need them:
|
||||
```python
|
||||
# Research agent needs search
|
||||
research_agent = Agent(
|
||||
instructions="Research AI",
|
||||
tools=[Tools.internet_search]
|
||||
)
|
||||
|
||||
# Summary agent doesn't need search
|
||||
summary_agent = Agent(
|
||||
instructions="Summarize findings"
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Research and Analysis
|
||||
```python
|
||||
# Research agent
|
||||
researcher = Agent(
|
||||
instructions="Research latest developments in quantum computing",
|
||||
tools=[Tools.internet_search]
|
||||
)
|
||||
|
||||
# Analysis agent
|
||||
analyst = Agent(
|
||||
instructions="Analyze and explain the research findings in simple terms"
|
||||
)
|
||||
|
||||
agents = Agents(agents=[researcher, analyst])
|
||||
```
|
||||
|
||||
### Information Processing
|
||||
```python
|
||||
# Data collector
|
||||
collector = Agent(
|
||||
instructions="Collect information about renewable energy",
|
||||
tools=[Tools.internet_search]
|
||||
)
|
||||
|
||||
# Summarizer
|
||||
summarizer = Agent(
|
||||
instructions="Create a concise summary of the collected information"
|
||||
)
|
||||
|
||||
# Report writer
|
||||
writer = Agent(
|
||||
instructions="Write a detailed report based on the summary"
|
||||
)
|
||||
|
||||
agents = Agents(agents=[collector, summarizer, writer])
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Tool Not Available" icon="triangle-exclamation">
|
||||
If using `Tools.internet_search`, install required package:
|
||||
```bash
|
||||
pip install duckduckgo_search
|
||||
```
|
||||
</Card>
|
||||
<Card title="Agent Communication" icon="comments">
|
||||
Ensure agent instructions are clear and complementary
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Advanced Agents" icon="graduation-cap" href="./advanced">
|
||||
Learn about advanced agent configurations
|
||||
</Card>
|
||||
<Card title="Custom Tools" icon="screwdriver-wrench" href="./tools">
|
||||
Create your own agent tools
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
Mini AI Agents are designed to be simple yet powerful. They're perfect for quick prototypes and straightforward automation tasks.
|
||||
</Note>
|
||||
@@ -1,314 +0,0 @@
|
||||
---
|
||||
title: "Multimodal Agents"
|
||||
description: "Guide for creating and using multimodal AI agents in PraisonAI for processing images, videos, and other media types"
|
||||
icon: "images"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create a file">
|
||||
Create a new file `app.py` with the basic setup:
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create Vision Analysis Agent
|
||||
vision_agent = Agent(
|
||||
name="VisionAnalyst",
|
||||
role="Computer Vision 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 with different media types
|
||||
task = 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=vision_agent,
|
||||
images=["https://upload.wikimedia.org/wikipedia/commons/b/bf/Krakow_-_Kosciol_Mariacki.jpg"]
|
||||
)
|
||||
|
||||
# Run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[vision_agent],
|
||||
tasks=[task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
agents.start()
|
||||
```
|
||||
</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=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
</Step>
|
||||
<Step title="Create a file">
|
||||
Create a new file `agents.yaml` with the basic setup:
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: analyze landmark image
|
||||
roles:
|
||||
vision_analyst:
|
||||
name: VisionAnalyst
|
||||
role: Computer Vision 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
|
||||
tasks:
|
||||
analyze_landmark:
|
||||
description: Describe this famous landmark and its architectural features.
|
||||
expected_output: Detailed description of the landmark's architecture and significance
|
||||
images:
|
||||
- https://upload.wikimedia.org/wikipedia/commons/b/bf/Krakow_-_Kosciol_Mariacki.jpg
|
||||
```
|
||||
</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 with vision model access
|
||||
- Basic understanding of Python and media handling
|
||||
</Note>
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/hjAWmUT1qqY"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Understanding Multimodal Agents
|
||||
|
||||
<Card title="What are Multimodal Agents?" icon="question">
|
||||
Multimodal agents are designed to:
|
||||
- Process multiple types of data (text, images, videos)
|
||||
- Understand context across different modalities
|
||||
- Generate insights from diverse media sources
|
||||
- Handle complex multimedia tasks
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Vision Processing" icon="eye">
|
||||
Analyze images, detect objects, and understand visual content.
|
||||
</Card>
|
||||
<Card title="Video Analysis" icon="video">
|
||||
Process video content for events and actions.
|
||||
</Card>
|
||||
<Card title="Text Extraction" icon="font">
|
||||
Extract and analyze text from images and documents.
|
||||
</Card>
|
||||
<Card title="Cross-Modal Understanding" icon="arrows-repeat">
|
||||
Integrate insights across different media types.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent Media Processing
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Create first agent for image analysis
|
||||
vision_agent = Agent(
|
||||
role="Image Analyst",
|
||||
goal="Analyze visual content and extract key information",
|
||||
backstory="Expert in visual analysis and image understanding",
|
||||
llm="gpt-4o-mini",
|
||||
self_reflect=False
|
||||
)
|
||||
|
||||
# Create second agent for content writing
|
||||
writer_agent = Agent(
|
||||
role="Content Writer",
|
||||
goal="Create engaging content based on image analysis",
|
||||
backstory="Expert in creating compelling content from visual insights",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create tasks for different media types
|
||||
document_task = Task(
|
||||
description="Extract and summarize text from this document image",
|
||||
expected_output="Structured text content with key information highlighted",
|
||||
agent=vision_agent,
|
||||
images=["document.jpg"]
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description="Create engaging content based on image analysis",
|
||||
expected_output="Compelling article incorporating visual insights",
|
||||
agent=writer_agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[vision_agent, writer_agent],
|
||||
tasks=[document_task, writing_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="No Code">
|
||||
```yaml
|
||||
framework: praisonai
|
||||
process: sequential
|
||||
topic: document analysis and content creation
|
||||
roles:
|
||||
vision_analyst:
|
||||
role: Image Analyst
|
||||
goal: Analyze visual content and extract key information
|
||||
backstory: Expert in visual analysis and image understanding
|
||||
llm: gpt-4o-mini
|
||||
self_reflect: false
|
||||
tasks:
|
||||
document_task:
|
||||
description: Extract and summarize text from this document image
|
||||
expected_output: Structured text content with key information highlighted
|
||||
images:
|
||||
- document.jpg
|
||||
|
||||
content_writer:
|
||||
role: Content Writer
|
||||
goal: Create engaging content based on image analysis
|
||||
backstory: Expert in creating compelling content from visual insights
|
||||
llm: gpt-4o-mini
|
||||
tasks:
|
||||
writing_task:
|
||||
description: Create engaging content based on image analysis
|
||||
expected_output: Compelling article incorporating visual insights
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with multimodal configuration
|
||||
agent = Agent(
|
||||
role="Media Analyst",
|
||||
goal="Process multiple types of media",
|
||||
backstory="Expert in multimedia analysis",
|
||||
llm="gpt-4o-mini", # Must support vision capabilities
|
||||
verbose=True, # Enable detailed logging
|
||||
self_reflect=False # Optional: disable self-reflection
|
||||
)
|
||||
|
||||
# Task with media requirements
|
||||
task = Task(
|
||||
description="Analyze media content",
|
||||
expected_output="Comprehensive analysis",
|
||||
agent=agent,
|
||||
images=[ # Support multiple media sources
|
||||
"https://example.com/image1.jpg",
|
||||
"path/to/local/image.jpg",
|
||||
"path/to/video.mp4"
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Media Handling" icon="image">
|
||||
- Use supported formats (JPEG, PNG)
|
||||
- Keep reasonable file sizes
|
||||
- Provide high-quality media
|
||||
- Validate files before processing
|
||||
</Card>
|
||||
<Card title="Task Design" icon="list-check">
|
||||
- Write clear descriptions
|
||||
- Break down complex analyses
|
||||
- Specify expected outputs
|
||||
- Handle errors gracefully
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Example Use Cases
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Document Analysis" icon="file-lines">
|
||||
Extract and analyze text from document images.
|
||||
</Card>
|
||||
<Card title="Security Monitoring" icon="camera-cctv">
|
||||
Monitor security feeds for suspicious activity.
|
||||
</Card>
|
||||
<Card title="Medical Imaging" icon="microscope">
|
||||
Analyze medical scans for abnormalities.
|
||||
</Card>
|
||||
<Card title="Architectural Analysis" icon="building">
|
||||
Study architectural features and designs.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure your media files are in supported formats and sizes for processing.
|
||||
</Note>
|
||||
@@ -1,335 +0,0 @@
|
||||
---
|
||||
title: "Reasoning Agents"
|
||||
description: "Learn how to create AI agents with advanced reasoning capabilities for complex problem-solving."
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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, Tools
|
||||
|
||||
# Create reasoning agent
|
||||
reasoner = Agent(
|
||||
role="Problem Solver",
|
||||
goal="Solve complex problems using logical reasoning",
|
||||
backstory="Expert in logical analysis and problem-solving",
|
||||
tools=[Tools.internet_search],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create task
|
||||
task = Task(
|
||||
description="Analyze and solve a complex business problem",
|
||||
expected_output="Detailed solution with reasoning steps",
|
||||
agent=reasoner
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[reasoner],
|
||||
tasks=[task],
|
||||
process="sequential",
|
||||
verbose=2
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
print(result)
|
||||
```
|
||||
</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
|
||||
topic: solve complex business problem
|
||||
roles:
|
||||
reasoner:
|
||||
backstory: Expert in logical analysis and problem-solving.
|
||||
goal: Solve complex problems using logical reasoning
|
||||
role: Problem Solver
|
||||
tools:
|
||||
- internet_search
|
||||
tasks:
|
||||
analysis_task:
|
||||
description: Analyze and solve a complex business problem.
|
||||
expected_output: Detailed solution with reasoning steps.
|
||||
```
|
||||
</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>
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/KNDVWGN3TpM"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Understanding Reasoning
|
||||
|
||||
<Card title="What is Reasoning?" icon="question">
|
||||
Reasoning agents are designed to:
|
||||
- Break down complex problems into manageable steps
|
||||
- Apply logical analysis to find solutions
|
||||
- Explain their thought process and decisions
|
||||
- Handle uncertainty and incomplete information
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Problem Decomposition" icon="puzzle-piece">
|
||||
Break complex problems into smaller, manageable parts.
|
||||
</Card>
|
||||
<Card title="Logical Analysis" icon="brain">
|
||||
Apply structured thinking to solve problems.
|
||||
</Card>
|
||||
<Card title="Error Recovery" icon="shield-check">
|
||||
Handle edge cases and recover from errors.
|
||||
</Card>
|
||||
<Card title="Explanation" icon="comment">
|
||||
Provide detailed reasoning for decisions.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent Reasoning
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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, Tools
|
||||
|
||||
# Create first agent for analysis
|
||||
analyst = Agent(
|
||||
role="Business Analyst",
|
||||
goal="Analyze business problems and identify key issues",
|
||||
backstory="Expert in business analysis and problem identification",
|
||||
tools=[Tools.internet_search],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create second agent for solution development
|
||||
solver = Agent(
|
||||
role="Solution Architect",
|
||||
goal="Develop comprehensive solutions to business problems",
|
||||
backstory="Expert in solution design and implementation",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create first task
|
||||
analysis_task = Task(
|
||||
description="Analyze the current market challenges",
|
||||
expected_output="Detailed analysis of key issues",
|
||||
agent=analyst
|
||||
)
|
||||
|
||||
# Create second task
|
||||
solution_task = Task(
|
||||
description="Develop solutions for identified challenges",
|
||||
expected_output="Comprehensive solution strategy",
|
||||
agent=solver
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[analyst, solver],
|
||||
tasks=[analysis_task, solution_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
```
|
||||
</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
|
||||
topic: solve market challenges
|
||||
roles:
|
||||
analyst:
|
||||
backstory: Expert in business analysis and problem identification.
|
||||
goal: Analyze business problems and identify key issues
|
||||
role: Business Analyst
|
||||
tools:
|
||||
- internet_search
|
||||
tasks:
|
||||
analysis_task:
|
||||
description: Analyze the current market challenges.
|
||||
expected_output: Detailed analysis of key issues.
|
||||
|
||||
solver:
|
||||
backstory: Expert in solution design and implementation.
|
||||
goal: Develop comprehensive solutions to business problems
|
||||
role: Solution Architect
|
||||
tasks:
|
||||
solution_task:
|
||||
description: Develop solutions for identified challenges.
|
||||
expected_output: Comprehensive solution strategy.
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with reasoning configuration
|
||||
agent = Agent(
|
||||
role="Problem Solver",
|
||||
goal="Solve complex problems",
|
||||
backstory="Expert in problem-solving",
|
||||
tools=[Tools.internet_search],
|
||||
verbose=True, # Enable detailed logging
|
||||
llm="gpt-4o" # Language model to use
|
||||
)
|
||||
|
||||
# Task with reasoning requirements
|
||||
task = Task(
|
||||
description="Solve complex problem",
|
||||
expected_output="Detailed solution",
|
||||
agent=agent
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Reasoning Errors" icon="triangle-exclamation">
|
||||
If reasoning seems incorrect:
|
||||
- Check problem description clarity
|
||||
- Enable verbose mode for debugging
|
||||
- Review agent configuration
|
||||
</Card>
|
||||
|
||||
<Card title="Process Flow" icon="code">
|
||||
If process flow is unclear:
|
||||
- Verify task dependencies
|
||||
- Check agent roles and goals
|
||||
- Review task descriptions
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure your problem descriptions are clear and provide sufficient context for the reasoning agents.
|
||||
</Note>
|
||||
@@ -1,338 +0,0 @@
|
||||
---
|
||||
title: "Self Reflection AI Agents"
|
||||
sidebarTitle: "Self Reflection Agents"
|
||||
description: "Self-reflection enables agents to evaluate and improve their own responses before delivering them."
|
||||
icon: "brain"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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
|
||||
|
||||
# Create an agent with self-reflection
|
||||
agent = Agent(
|
||||
role="Senior Research Analyst",
|
||||
goal="Analyze and provide insights on given topics",
|
||||
backstory="You are an expert analyst with strong critical thinking skills",
|
||||
self_reflect=True # Enable self-reflection
|
||||
)
|
||||
|
||||
# Create a task
|
||||
task = Task(
|
||||
description="Analyze recent developments in AI",
|
||||
expected_output="A detailed analysis report",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process="sequential",
|
||||
verbose=2
|
||||
)
|
||||
|
||||
# Start execution
|
||||
agents.start()
|
||||
```
|
||||
</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
|
||||
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
|
||||
self_reflect: true
|
||||
min_reflect: 1
|
||||
max_reflect: 2
|
||||
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.
|
||||
tools:
|
||||
- search_tool
|
||||
```
|
||||
</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).
|
||||
</Note>
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/vLXobEN2Vc8"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Understanding Self-Reflection
|
||||
|
||||
<Card title="What is Self-Reflection?" icon="question">
|
||||
Self-reflection enables agents to:
|
||||
- Evaluate their own responses before delivery
|
||||
- Check for completeness and accuracy
|
||||
- Improve output quality through iteration
|
||||
- Ensure task requirements are met
|
||||
- Make conscious decisions about their responses
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quality Assurance" icon="check-double">
|
||||
Evaluates and improves response quality through self-review.
|
||||
</Card>
|
||||
<Card title="Iterative Improvement" icon="rotate">
|
||||
Refines responses through multiple reflection cycles.
|
||||
</Card>
|
||||
<Card title="Task Validation" icon="list-check">
|
||||
Ensures all aspects of the task are properly addressed.
|
||||
</Card>
|
||||
<Card title="Conscious Decision Making" icon="brain">
|
||||
Enables thoughtful evaluation of responses.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent Self-Reflection
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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
|
||||
|
||||
# Create first agent with self-reflection
|
||||
researcher = Agent(
|
||||
role="Senior Research Analyst",
|
||||
goal="Research and analyze AI developments",
|
||||
backstory="Expert analyst specializing in AI trends and impacts",
|
||||
self_reflect=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create second agent with self-reflection
|
||||
writer = Agent(
|
||||
role="Technical Writer",
|
||||
goal="Transform research into clear documentation",
|
||||
backstory="Experienced in creating technical content and documentation",
|
||||
self_reflect=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create first task
|
||||
research_task = Task(
|
||||
description="Research and analyze recent AI developments",
|
||||
expected_output="Comprehensive analysis of AI trends",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Create second task
|
||||
documentation_task = Task(
|
||||
description="Create technical documentation from research findings",
|
||||
expected_output="Well-structured technical documentation",
|
||||
agent=writer
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, documentation_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
agents.start()
|
||||
```
|
||||
</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 duckduckgo_search
|
||||
```
|
||||
</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
|
||||
topic: create technical documentation about AI trends
|
||||
roles:
|
||||
researcher:
|
||||
backstory: Expert analyst specializing in AI trends and their implications.
|
||||
goal: Research and analyze current AI developments
|
||||
role: Senior Research Analyst
|
||||
self_reflect: true
|
||||
min_reflect: 1
|
||||
max_reflect: 2
|
||||
tasks:
|
||||
research_task:
|
||||
description: Research and analyze recent developments in AI technology.
|
||||
expected_output: Comprehensive analysis of current AI trends.
|
||||
tools:
|
||||
- duckduckgo
|
||||
|
||||
writer:
|
||||
backstory: Experienced technical writer skilled in creating clear documentation.
|
||||
goal: Transform research into accessible documentation
|
||||
role: Technical Writer
|
||||
tasks:
|
||||
documentation_task:
|
||||
description: Create technical documentation from research findings.
|
||||
expected_output: Well-structured technical documentation.
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with advanced self-reflection configuration
|
||||
agent = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Provide comprehensive analysis",
|
||||
backstory="Expert analyst with critical thinking skills",
|
||||
self_reflect=True, # Enable self-reflection
|
||||
verbose=True, # Enable detailed logging
|
||||
llm="gpt-4o", # Language model to use
|
||||
allow_delegation=True # Allow task delegation
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Response Issues" icon="rotate">
|
||||
If responses are not meeting expectations:
|
||||
- Enable verbose mode for debugging
|
||||
- Review agent configuration
|
||||
- Check task description clarity
|
||||
</Card>
|
||||
|
||||
<Card title="Quality Issues" icon="triangle-exclamation">
|
||||
If output quality is insufficient:
|
||||
- Enable verbose mode
|
||||
- Review agent role and goal
|
||||
- Clarify expected output
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, configure reflection parameters based on your specific use case requirements.
|
||||
</Note>
|
||||
@@ -1,369 +0,0 @@
|
||||
---
|
||||
title: "Structured AI Agents"
|
||||
description: "Learn how to create AI agents that return structured, type-safe outputs using Pydantic models and JSON."
|
||||
icon: "cube"
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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, Tools
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Define your data structure
|
||||
class AnalysisReport(BaseModel):
|
||||
title: str
|
||||
findings: str
|
||||
summary: str
|
||||
|
||||
# Create agent
|
||||
analyst = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze data and provide structured insights",
|
||||
backstory="Expert in data analysis and insights generation",
|
||||
tools=[Tools.internet_search],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create task with structured output
|
||||
task = Task(
|
||||
description="Analyze recent AI developments",
|
||||
expected_output="Structured analysis report",
|
||||
agent=analyst,
|
||||
output_pydantic=AnalysisReport
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[analyst],
|
||||
tasks=[task],
|
||||
process="sequential",
|
||||
verbose=2
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
print(result.pydantic.title)
|
||||
print(result.pydantic.findings)
|
||||
print(result.pydantic.summary)
|
||||
```
|
||||
</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
|
||||
topic: analyze AI developments with structured output
|
||||
roles:
|
||||
analyst:
|
||||
backstory: Expert in data analysis and insights generation.
|
||||
goal: Analyze data and provide structured insights
|
||||
role: Data Analyst
|
||||
tools:
|
||||
- internet_search
|
||||
tasks:
|
||||
analysis_task:
|
||||
description: Analyze recent AI developments.
|
||||
expected_output: Structured analysis report.
|
||||
output_structure:
|
||||
type: pydantic
|
||||
model:
|
||||
title: str
|
||||
findings: str
|
||||
summary: str
|
||||
```
|
||||
</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 and Pydantic
|
||||
</Note>
|
||||
|
||||
## Understanding Structured Outputs
|
||||
|
||||
<Card title="What are Structured Outputs?" icon="question">
|
||||
Structured outputs allow you to:
|
||||
- Define exact shape of data using Pydantic models
|
||||
- Get type-safe, validated responses
|
||||
- Choose between Pydantic objects or JSON
|
||||
- Ensure consistent output format across agent responses
|
||||
</Card>
|
||||
|
||||
## Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Pydantic Models" icon="cube">
|
||||
Define exact data structures with validation.
|
||||
</Card>
|
||||
<Card title="JSON Output" icon="brackets-curly">
|
||||
Get structured JSON responses.
|
||||
</Card>
|
||||
<Card title="Type Safety" icon="shield-check">
|
||||
Ensure type-safe, validated outputs.
|
||||
</Card>
|
||||
<Card title="Format Options" icon="code">
|
||||
Choose between Pydantic or JSON.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Multi-Agent Structured Analysis
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Code">
|
||||
<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, Tools
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Define output structures
|
||||
class ResearchReport(BaseModel):
|
||||
topic: str
|
||||
findings: str
|
||||
sources: list[str]
|
||||
|
||||
class Analysis(BaseModel):
|
||||
key_points: list[str]
|
||||
implications: str
|
||||
recommendations: str
|
||||
|
||||
# Create first agent for research
|
||||
researcher = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Gather and structure research data",
|
||||
backstory="Expert in research and data collection",
|
||||
tools=[Tools.internet_search],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create second agent for analysis
|
||||
analyst = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze research and provide structured insights",
|
||||
backstory="Expert in data analysis and insights generation",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create first task
|
||||
research_task = Task(
|
||||
description="Research quantum computing developments",
|
||||
expected_output="Structured research findings",
|
||||
agent=researcher,
|
||||
output_pydantic=ResearchReport
|
||||
)
|
||||
|
||||
# Create second task
|
||||
analysis_task = Task(
|
||||
description="Analyze research implications",
|
||||
expected_output="Structured analysis report",
|
||||
agent=analyst,
|
||||
output_pydantic=Analysis
|
||||
)
|
||||
|
||||
# Create and start the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, analyst],
|
||||
tasks=[research_task, analysis_task],
|
||||
process="sequential"
|
||||
)
|
||||
|
||||
# Start execution
|
||||
result = agents.start()
|
||||
```
|
||||
</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
|
||||
topic: research and analyze quantum computing
|
||||
roles:
|
||||
researcher:
|
||||
backstory: Expert in research and data collection.
|
||||
goal: Gather and structure research data
|
||||
role: Research Analyst
|
||||
tools:
|
||||
- internet_search
|
||||
tasks:
|
||||
research_task:
|
||||
description: Research quantum computing developments.
|
||||
expected_output: Structured research findings.
|
||||
output_structure:
|
||||
type: pydantic
|
||||
model:
|
||||
topic: str
|
||||
findings: str
|
||||
sources: list[str]
|
||||
|
||||
analyst:
|
||||
backstory: Expert in data analysis and insights generation.
|
||||
goal: Analyze research and provide structured insights
|
||||
role: Data Analyst
|
||||
tasks:
|
||||
analysis_task:
|
||||
description: Analyze research implications.
|
||||
expected_output: Structured analysis report.
|
||||
output_structure:
|
||||
type: pydantic
|
||||
model:
|
||||
key_points: list[str]
|
||||
implications: str
|
||||
recommendations: str
|
||||
```
|
||||
</Step>
|
||||
<Step title="Start Agents">
|
||||
Type this in your terminal to run your agents:
|
||||
```bash
|
||||
praisonai agents.yaml
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```python
|
||||
# Create an agent with structured output configuration
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Provide structured analysis",
|
||||
backstory="Expert in data analysis",
|
||||
tools=[Tools.internet_search],
|
||||
verbose=True, # Enable detailed logging
|
||||
llm="gpt-4o" # Language model to use
|
||||
)
|
||||
|
||||
# Task with Pydantic output
|
||||
task = Task(
|
||||
description="Analyze data",
|
||||
expected_output="Structured report",
|
||||
agent=agent,
|
||||
output_pydantic=AnalysisReport # Use Pydantic model
|
||||
# or output_json=AnalysisReport # Use JSON output
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Validation Errors" icon="triangle-exclamation">
|
||||
If model validation fails:
|
||||
- Check data types match model
|
||||
- Verify required fields
|
||||
- Enable verbose mode for debugging
|
||||
</Card>
|
||||
|
||||
<Card title="Output Format" icon="code">
|
||||
If output format is incorrect:
|
||||
- Verify model definition
|
||||
- Check output_pydantic vs output_json
|
||||
- Review field specifications
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AutoAgents" icon="robot" href="./autoagents">
|
||||
Learn about automatically created and managed AI agents
|
||||
</Card>
|
||||
<Card title="Mini Agents" icon="microchip" href="./mini">
|
||||
Explore lightweight, focused AI agents
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
For optimal results, ensure your Pydantic models accurately represent your desired output structure.
|
||||
</Note>
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
title: "Firecrawl PraisonAI Integration"
|
||||
description: "Guide for integrating Firecrawl web scraping capabilities with PraisonAI, including custom tool implementation for web page content extraction"
|
||||
icon: "spider"
|
||||
---
|
||||
|
||||
# Firecrawl PraisonAI Integration
|
||||
|
||||
<div className="relative w-full aspect-video">
|
||||
<iframe
|
||||
className="absolute top-0 left-0 w-full h-full"
|
||||
src="https://www.youtube.com/embed/UoqUDcLcOYo"
|
||||
title="YouTube video player"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
## Firecrawl running in Localhost:3002
|
||||
|
||||
```python
|
||||
from firecrawl import FirecrawlApp
|
||||
from praisonai_tools import BaseTool
|
||||
import re
|
||||
|
||||
class WebPageScraperTool(BaseTool):
|
||||
name: str = "Web Page Scraper Tool"
|
||||
description: str = "Scrape and extract information from a given web page URL."
|
||||
|
||||
def _run(self, url: str) -> str:
|
||||
app = FirecrawlApp(api_url='http://localhost:3002')
|
||||
response = app.scrape_url(url=url)
|
||||
content = response["content"]
|
||||
# Remove all content above the line "========================================================"
|
||||
if "========================================================" in content:
|
||||
content = content.split("========================================================", 1)[1]
|
||||
|
||||
# Remove all menu items and similar patterns
|
||||
content = re.sub(r'\*\s+\[.*?\]\(.*?\)', '', content)
|
||||
content = re.sub(r'\[Skip to the content\]\(.*?\)', '', content)
|
||||
content = re.sub(r'\[.*?\]\(.*?\)', '', content)
|
||||
content = re.sub(r'\s*Menu\s*', '', content)
|
||||
content = re.sub(r'\s*Search\s*', '', content)
|
||||
content = re.sub(r'Categories\s*', '', content)
|
||||
|
||||
# Remove all URLs
|
||||
content = re.sub(r'http\S+', '', content)
|
||||
|
||||
# Remove empty lines or lines with only whitespace
|
||||
content = '\n'.join([line for line in content.split('\n') if line.strip()])
|
||||
|
||||
# Limit to the first 1000 words
|
||||
words = content.split()
|
||||
if len(words) > 1000:
|
||||
content = ' '.join(words[:1000])
|
||||
|
||||
return content
|
||||
```
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: "AutoGen with PraisonAI"
|
||||
description: "Guide for using AutoGen framework with PraisonAI, including installation, setup, and multi-agent conversation capabilities"
|
||||
icon: "robot"
|
||||
---
|
||||
|
||||
# AutoGen with PraisonAI
|
||||
|
||||
Low-code solution to run AutoGen with integrated tools and features.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Install with AutoGen support
|
||||
pip install "praisonai[autogen]"
|
||||
```
|
||||
|
||||
This installation includes:
|
||||
- AutoGen framework
|
||||
- PraisonAI tools integration
|
||||
- Multi-agent conversation capabilities
|
||||
- Code execution environment
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Set your OpenAI API key
|
||||
export OPENAI_API_KEY=xxxxxxxxxx
|
||||
|
||||
# Initialize with AutoGen
|
||||
praisonai --framework autogen --init "Create a Movie Script About Cat in Mars"
|
||||
|
||||
# Run the agents
|
||||
praisonai --framework autogen
|
||||
```
|
||||
|
||||
## Auto Mode
|
||||
```bash
|
||||
praisonai --framework autogen --auto "Create a Movie Script About Cat in Mars"
|
||||
```
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: "CrewAI with PraisonAI"
|
||||
description: "Guide for using CrewAI framework with PraisonAI, including installation, setup, and execution of agent-based tasks"
|
||||
icon: "users"
|
||||
---
|
||||
|
||||
# CrewAI with PraisonAI
|
||||
|
||||
Low-code solution to run CrewAI with integrated tools and features.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Install with CrewAI support
|
||||
pip install "praisonai[crewai]"
|
||||
```
|
||||
|
||||
This installation includes:
|
||||
- CrewAI framework
|
||||
- PraisonAI tools integration
|
||||
- Task delegation capabilities
|
||||
- Sequential and parallel task execution
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Set your OpenAI API key
|
||||
export OPENAI_API_KEY=xxxxxxxxxx
|
||||
|
||||
# Initialize with CrewAI
|
||||
praisonai --framework crewai --init "Create a Movie Script About Cat in Mars"
|
||||
|
||||
# Run the agents
|
||||
praisonai --framework crewai
|
||||
```
|
||||
|
||||
## Auto Mode
|
||||
```bash
|
||||
praisonai --framework crewai --auto "Create a Movie Script About Cat in Mars"
|
||||
```
|
||||
@@ -1,207 +0,0 @@
|
||||
---
|
||||
title: "PraisonAI Agents"
|
||||
description: "Guide for using PraisonAI Agents framework, a lightweight package for creating and managing AI agents with advanced capabilities"
|
||||
icon: "users-gear"
|
||||
---
|
||||
|
||||
A lightweight package dedicated to creating and managing AI agents with advanced capabilities.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
Create `app.py` and add the following code:
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# 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
|
||||
)
|
||||
|
||||
# Create tasks
|
||||
research_task = Task(
|
||||
description="Research the latest developments in AI and data science",
|
||||
expected_output="A comprehensive report on recent AI trends and breakthroughs",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description="Create an engaging blog post about the research findings",
|
||||
expected_output="A well-structured blog post explaining AI developments",
|
||||
agent=writer,
|
||||
context=[research_task] # This task depends on research_task output
|
||||
)
|
||||
|
||||
# Create and run the agents
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, writing_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = agents.start()
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Agent Configuration
|
||||
|
||||
### Core Attributes
|
||||
- `name`: Agent's identifier
|
||||
- `role`: Agent's function/expertise
|
||||
- `goal`: Individual objective
|
||||
- `backstory`: Context and personality
|
||||
- `llm`: Language model (default: OpenAI's GPT-4)
|
||||
- `verbose`: Enable detailed logs (default: False)
|
||||
- `markdown`: Enable markdown formatting (default: True)
|
||||
|
||||
### Optional Attributes
|
||||
- `tools`: List of available tools
|
||||
- `memory`: Enable conversation history (default: True)
|
||||
- `max_iter`: Maximum iterations (default: 20)
|
||||
- `max_rpm`: Rate limit for API calls
|
||||
- `allow_delegation`: Enable task delegation (default: False)
|
||||
|
||||
## Task Configuration
|
||||
|
||||
### Core Attributes
|
||||
- `description`: Task details
|
||||
- `expected_output`: Desired outcome
|
||||
- `agent`: Assigned agent
|
||||
|
||||
### Optional Attributes
|
||||
- `context`: Dependencies on other tasks
|
||||
- `tools`: Task-specific tools
|
||||
- `async_execution`: Run asynchronously (default: False)
|
||||
- `output_file`: Save output to file
|
||||
- `callback`: Post-task function
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Tool Integration
|
||||
```python
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
def search_tool(query: str) -> list:
|
||||
"""
|
||||
Perform a web search using DuckDuckGo and return relevant results.
|
||||
|
||||
Args:
|
||||
query (str): The search query string to look up information about.
|
||||
|
||||
Returns:
|
||||
list: A list of dictionaries containing search results with the following keys:
|
||||
- title (str): The title of the search result
|
||||
- url (str): The URL of the search result
|
||||
- snippet (str): A brief excerpt or description of the search result
|
||||
"""
|
||||
results = []
|
||||
ddgs = DDGS()
|
||||
for result in ddgs.text(keywords=query, max_results=10):
|
||||
results.append({
|
||||
"title": result.get("title", ""),
|
||||
"url": result.get("href", ""),
|
||||
"snippet": result.get("body", ""),
|
||||
})
|
||||
return results
|
||||
|
||||
agent = Agent(
|
||||
name="Researcher",
|
||||
tools=[search_tool]
|
||||
)
|
||||
```
|
||||
|
||||
### Custom Callbacks
|
||||
```python
|
||||
def task_completed(output):
|
||||
print(f"Task completed: {output.description}")
|
||||
print(f"Output: {output.raw}")
|
||||
|
||||
task = Task(
|
||||
description="Analysis task",
|
||||
callback=task_completed
|
||||
)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The framework includes built-in error handling for:
|
||||
- API rate limits
|
||||
- Token limits
|
||||
- Task timeouts
|
||||
- Tool execution failures
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Agent Design**
|
||||
- Give clear, specific roles and goals
|
||||
- Provide detailed backstories
|
||||
- Use appropriate tools for tasks
|
||||
|
||||
2. **Task Management**
|
||||
- Break complex tasks into subtasks
|
||||
- Set clear dependencies
|
||||
- Use async execution for independent tasks
|
||||
|
||||
3. **Resource Optimization**
|
||||
- Enable caching when appropriate
|
||||
- Set reasonable max_iter limits
|
||||
- Use rate limiting for API calls
|
||||
|
||||
4. **Error Handling**
|
||||
- Implement task callbacks
|
||||
- Set appropriate timeouts
|
||||
- Monitor execution logs
|
||||
|
||||
### Parallel Execution (Upcoming)
|
||||
```python
|
||||
task1 = Task(
|
||||
description="Research task 1",
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
description="Research task 2",
|
||||
async_execution=True
|
||||
)
|
||||
|
||||
final_task = Task(
|
||||
description="Compile results",
|
||||
context=[task1, task2] # Waits for both tasks
|
||||
)
|
||||
```
|
||||
|
||||
### Memory Management (Upcoming)
|
||||
```python
|
||||
agent = Agent(
|
||||
name="Analyst",
|
||||
memory=True, # Enable memory
|
||||
memory_config={
|
||||
"type": "short_term",
|
||||
"max_tokens": 4000
|
||||
}
|
||||
)
|
||||
```
|
||||
@@ -1,11 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e # Exit if any command fails
|
||||
|
||||
# Install necessary packages
|
||||
pip install pdoc3 mkdocs mkdocs-material duckduckgo_search
|
||||
|
||||
# Generate HTML documentation with pdoc
|
||||
pdoc --html --skip-errors -o docs/api praisonai --force
|
||||
|
||||
# Build the MkDocs site
|
||||
mkdocs build
|
||||
Loaded 100 of 981 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user