Spaces:
Paused
Paused
File size: 250,509 Bytes
f6686e1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 | <!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="pdoc 0.10.0" />
<title>tinytroupe.agent.tiny_person API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;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:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 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 .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#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-weight:bold;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 .5em;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}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.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/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>tinytroupe.agent.tiny_person</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">from tinytroupe.agent import logger, default, Self, AgentOrWorld, CognitiveActionModel
from tinytroupe.agent.memory import EpisodicMemory, SemanticMemory, EpisodicConsolidator
import tinytroupe.openai_utils as openai_utils
from tinytroupe.utils import JsonSerializableRegistry, repeat_on_error, name_or_empty
import tinytroupe.utils as utils
from tinytroupe.control import transactional, current_simulation
from tinytroupe import config_manager
import os
import json
import copy
import textwrap # to dedent strings
import chevron # to parse Mustache templates
from typing import Any
from rich import print
import threading
from tinytroupe.utils import LLMChat # Import LLMChat from the appropriate module
import tinytroupe.utils.llm
# to protect from race conditions when running agents in parallel
concurrent_agent_action_lock = threading.Lock()
#######################################################################################################################
# TinyPerson itself
#######################################################################################################################
@utils.post_init
class TinyPerson(JsonSerializableRegistry):
"""A simulated person in the TinyTroupe universe."""
# The maximum number of actions that an agent is allowed to perform before DONE.
# This prevents the agent from acting without ever stopping.
MAX_ACTIONS_BEFORE_DONE = 15
# The maximum similarity between consecutive actions. If the similarity is too high, the action is discarded and replaced by a DONE.
# Set this to None to disable the check.
MAX_ACTION_SIMILARITY = 0.85
MIN_EPISODE_LENGTH = config_manager.get("min_episode_length", 15) # The minimum number of messages in an episode before it is considered valid.
MAX_EPISODE_LENGTH = config_manager.get("max_episode_length", 50) # The maximum number of messages in an episode before it is considered valid.
PP_TEXT_WIDTH = 100
serializable_attributes = ["_persona", "_mental_state", "_mental_faculties", "_current_episode_event_count", "episodic_memory", "semantic_memory"]
serializable_attributes_renaming = {"_mental_faculties": "mental_faculties", "_persona": "persona", "_mental_state": "mental_state", "_current_episode_event_count": "current_episode_event_count"}
# A dict of all agents instantiated so far.
all_agents = {} # name -> agent
# Whether to display the communication or not. True is for interactive applications, when we want to see simulation
# outputs as they are produced.
communication_display:bool=True
def __init__(self, name:str=None,
action_generator=None,
episodic_memory=None,
semantic_memory=None,
mental_faculties:list=None,
enable_basic_action_repetition_prevention:bool=True):
"""
Creates a TinyPerson.
Args:
name (str): The name of the TinyPerson. Either this or spec_path must be specified.
action_generator (ActionGenerator, optional): The action generator to use. Defaults to ActionGenerator().
episodic_memory (EpisodicMemory, optional): The memory implementation to use. Defaults to EpisodicMemory().
semantic_memory (SemanticMemory, optional): The memory implementation to use. Defaults to SemanticMemory().
mental_faculties (list, optional): A list of mental faculties to add to the agent. Defaults to None.
enable_basic_action_repetition_prevention (bool, optional): Whether to enable basic action repetition prevention. Defaults to True.
"""
# NOTE: default values will be given in the _post_init method, as that's shared by
# direct initialization as well as via deserialization.
if action_generator is not None:
self.action_generator = action_generator
if episodic_memory is not None:
self.episodic_memory = episodic_memory
if semantic_memory is not None:
self.semantic_memory = semantic_memory
# Mental faculties
if mental_faculties is not None:
self._mental_faculties = mental_faculties
if enable_basic_action_repetition_prevention:
self.enable_basic_action_repetition_prevention = enable_basic_action_repetition_prevention
assert name is not None, "A TinyPerson must have a name."
self.name = name
# @post_init makes sure that _post_init is called after __init__
def _post_init(self, **kwargs):
"""
This will run after __init__, since the class has the @post_init decorator.
It is convenient to separate some of the initialization processes to make deserialize easier.
"""
from tinytroupe.agent.action_generator import ActionGenerator # import here to avoid circular import issues
############################################################
# Default values
############################################################
self.current_messages = []
# the current environment in which the agent is acting
self.environment = None
# The list of actions that this agent has performed so far, but which have not been
# consumed by the environment yet.
self._actions_buffer = []
# The list of agents that this agent can currently interact with.
# This can change over time, as agents move around the world.
self._accessible_agents = []
# the buffer of communications that have been displayed so far, used for
# saving these communications to another output form later (e.g., caching)
self._displayed_communications_buffer = []
if not hasattr(self, '_current_episode_event_count'):
self._current_episode_event_count = 0 # the number of events in the current episode, used to limit the episode length
if not hasattr(self, 'action_generator'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self.action_generator = ActionGenerator(max_attempts=config_manager.get("action_generator_max_attempts"),
enable_quality_checks=config_manager.get("action_generator_enable_quality_checks"),
enable_regeneration=config_manager.get("action_generator_enable_regeneration"),
enable_direct_correction=config_manager.get("action_generator_enable_direct_correction"),
enable_quality_check_for_persona_adherence=config_manager.get("action_generator_enable_quality_check_for_persona_adherence"),
enable_quality_check_for_selfconsistency=config_manager.get("action_generator_enable_quality_check_for_selfconsistency"),
enable_quality_check_for_fluency=config_manager.get("action_generator_enable_quality_check_for_fluency"),
enable_quality_check_for_suitability=config_manager.get("action_generator_enable_quality_check_for_suitability"),
enable_quality_check_for_similarity=config_manager.get("action_generator_enable_quality_check_for_similarity"),
continue_on_failure=config_manager.get("action_generator_continue_on_failure"),
quality_threshold=config_manager.get("action_generator_quality_threshold"))
if not hasattr(self, 'episodic_memory'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self.episodic_memory = EpisodicMemory(fixed_prefix_length= config_manager.get("episodic_memory_fixed_prefix_length"),
lookback_length=config_manager.get("episodic_memory_lookback_length"))
if not hasattr(self, 'semantic_memory'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self.semantic_memory = SemanticMemory()
# _mental_faculties
if not hasattr(self, '_mental_faculties'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self._mental_faculties = []
# basic action repetition prevention
if not hasattr(self, 'enable_basic_action_repetition_prevention'):
self.enable_basic_action_repetition_prevention = True
# create the persona configuration dictionary
if not hasattr(self, '_persona'):
self._persona = {
"name": self.name,
"age": None,
"nationality": None,
"country_of_residence": None,
"occupation": None
}
if not hasattr(self, 'name'):
self.name = self._persona["name"]
# create the mental state dictionary
if not hasattr(self, '_mental_state'):
self._mental_state = {
"datetime": None,
"location": None,
"context": [],
"goals": [],
"attention": None,
"emotions": "Feeling nothing in particular, just calm.",
"memory_context": None,
"accessible_agents": [] # [{"agent": agent_1, "relation": "My friend"}, {"agent": agent_2, "relation": "My colleague"}, ...]
}
if not hasattr(self, '_extended_agent_summary'):
self._extended_agent_summary = None
if not hasattr(self, 'actions_count'):
self.actions_count = 0
if not hasattr(self, 'stimuli_count'):
self.stimuli_count = 0
self._prompt_template_path = os.path.join(
os.path.dirname(__file__), "prompts/tiny_person.mustache"
)
self._init_system_message = None # initialized later
############################################################
# Special mechanisms used during deserialization
############################################################
# rename agent to some specific name?
if kwargs.get("new_agent_name") is not None:
self._rename(kwargs.get("new_agent_name"))
# If auto-rename, use the given name plus some new number ...
if kwargs.get("auto_rename") is True:
new_name = self.name # start with the current name
rename_succeeded = False
while not rename_succeeded:
try:
self._rename(new_name)
TinyPerson.add_agent(self)
rename_succeeded = True
except ValueError:
new_id = utils.fresh_id(self.__class__.__name__)
new_name = f"{self.name}_{new_id}"
# ... otherwise, just register the agent
else:
# register the agent in the global list of agents
TinyPerson.add_agent(self)
# start with a clean slate
self.reset_prompt()
# it could be the case that the agent is being created within a simulation scope, in which case
# the simulation_id must be set accordingly
if current_simulation() is not None:
current_simulation().add_agent(self)
else:
self.simulation_id = None
def _rename(self, new_name:str):
self.name = new_name
self._persona["name"] = self.name
def generate_agent_system_prompt(self):
with open(self._prompt_template_path, "r") as f:
agent_prompt_template = f.read()
# let's operate on top of a copy of the configuration, because we'll need to add more variables, etc.
template_variables = self._persona.copy()
template_variables["persona"] = json.dumps(self._persona.copy(), indent=4)
# add mental state to the template variables
template_variables["mental_state"] = json.dumps(self._mental_state, indent=4)
# Prepare additional action definitions and constraints
actions_definitions_prompt = ""
actions_constraints_prompt = ""
for faculty in self._mental_faculties:
actions_definitions_prompt += f"{faculty.actions_definitions_prompt()}\n"
actions_constraints_prompt += f"{faculty.actions_constraints_prompt()}\n"
# Make the additional prompt pieces available to the template.
# Identation here is to align with the text structure in the template.
template_variables['actions_definitions_prompt'] = textwrap.indent(actions_definitions_prompt.strip(), " ")
template_variables['actions_constraints_prompt'] = textwrap.indent(actions_constraints_prompt.strip(), " ")
# RAI prompt components, if requested
template_variables = utils.add_rai_template_variables_if_enabled(template_variables)
return chevron.render(agent_prompt_template, template_variables)
def reset_prompt(self):
# render the template with the current configuration
self._init_system_message = self.generate_agent_system_prompt()
# - reset system message
# - make it clear that the provided events are past events and have already had their effects
self.current_messages = [
{"role": "system", "content": self._init_system_message},
{"role": "system", "content": "The next messages refer to past interactions you had recently and are meant to help you contextualize your next actions. "\
+ "They are the most recent episodic memories you have, including stimuli and actions. "\
+ "Their effects already took place and led to your present cognitive state (described above), so you can use them in conjunction "\
+ "with your cognitive state to inform your next actions and perceptions. Please consider them and then proceed with your next actions right after. "}
]
# sets up the actual interaction messages to use for prompting
self.current_messages += self.retrieve_recent_memories()
#########################################################################
# Persona definitions
#########################################################################
#
# Conveniences to access the persona configuration via dictionary-like syntax using
# the [] operator. e.g., agent["nationality"] = "American"
#
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
self.define(key, value)
#
# Conveniences to import persona definitions via the '+' operator,
# e.g., agent + {"nationality": "American", ...}
#
# e.g., agent + "path/to/fragment.json"
#
def __add__(self, other):
"""
Allows using the '+' operator to add persona definitions or import a fragment.
If 'other' is a dict, calls include_persona_definitions().
If 'other' is a string, calls import_fragment().
"""
if isinstance(other, dict):
self.include_persona_definitions(other)
elif isinstance(other, str):
self.import_fragment(other)
else:
raise TypeError("Unsupported operand type for +. Must be a dict or a string path to fragment.")
return self
#
# Various other conveniences to manipulate the persona configuration
#
def get(self, key):
"""
Returns the value of a key in the TinyPerson's persona configuration.
Supports dot notation for nested keys (e.g., "address.city").
"""
keys = key.split(".")
value = self._persona
for k in keys:
if isinstance(value, dict):
value = value.get(k, None)
else:
return None # If the path is invalid, return None
return value
@transactional()
def import_fragment(self, path):
"""
Imports a fragment of a persona configuration from a JSON file.
"""
with open(path, "r") as f:
fragment = json.load(f)
# check the type is "Fragment" and that there's also a "persona" key
if fragment.get("type", None) == "Fragment" and fragment.get("persona", None) is not None:
self.include_persona_definitions(fragment["persona"])
else:
raise ValueError("The imported JSON file must be a valid fragment of a persona configuration.")
# must reset prompt after adding to configuration
self.reset_prompt()
@transactional()
def include_persona_definitions(self, additional_definitions: dict):
"""
Imports a set of definitions into the TinyPerson. They will be merged with the current configuration.
It is also a convenient way to include multiple bundled definitions into the agent.
Args:
additional_definitions (dict): The additional definitions to import.
"""
self._persona = utils.merge_dicts(self._persona, additional_definitions)
# must reset prompt after adding to configuration
self.reset_prompt()
@transactional()
def define(self, key, value, merge=False, overwrite_scalars=True):
"""
Define a value to the TinyPerson's persona configuration. Value can either be a scalar or a dictionary.
If the value is a dictionary or list, you can choose to merge it with the existing value or replace it.
If the value is a scalar, you can choose to overwrite the existing value or not.
Args:
key (str): The key to define.
value (Any): The value to define.
merge (bool, optional): Whether to merge the dict/list values with the existing values or replace them. Defaults to False.
overwrite_scalars (bool, optional): Whether to overwrite scalar values or not. Defaults to True.
"""
# dedent value if it is a string
if isinstance(value, str):
value = textwrap.dedent(value)
# if the value is a dictionary, we can choose to merge it with the existing value or replace it
if isinstance(value, dict) or isinstance(value, list):
if merge:
self._persona = utils.merge_dicts(self._persona, {key: value})
else:
self._persona[key] = value
# if the value is a scalar, we can choose to overwrite it or not
elif overwrite_scalars or (key not in self._persona):
self._persona[key] = value
else:
raise ValueError(f"The key '{key}' already exists in the persona configuration and overwrite_scalars is set to False.")
# must reset prompt after adding to configuration
self.reset_prompt()
@transactional()
def define_relationships(self, relationships, replace=True):
"""
Defines or updates the TinyPerson's relationships.
Args:
relationships (list or dict): The relationships to add or replace. Either a list of dicts mapping agent names to relationship descriptions,
or a single dict mapping one agent name to its relationship description.
replace (bool, optional): Whether to replace the current relationships or just add to them. Defaults to True.
"""
if (replace == True) and (isinstance(relationships, list)):
self._persona['relationships'] = relationships
elif replace == False:
current_relationships = self._persona['relationships']
if isinstance(relationships, list):
for r in relationships:
current_relationships.append(r)
elif isinstance(relationships, dict) and len(relationships) == 2: #{"Name": ..., "Description": ...}
current_relationships.append(relationships)
else:
raise Exception("Only one key-value pair is allowed in the relationships dict.")
else:
raise Exception("Invalid arguments for define_relationships.")
##############################################################################
# Relationships
##############################################################################
@transactional()
def clear_relationships(self):
"""
Clears the TinyPerson's relationships.
"""
self._persona['relationships'] = []
return self
@transactional()
def related_to(self, other_agent, description, symmetric_description=None):
"""
Defines a relationship between this agent and another agent.
Args:
other_agent (TinyPerson): The other agent.
description (str): The description of the relationship.
symmetric (bool): Whether the relationship is symmetric or not. That is,
if the relationship is defined for both agents.
Returns:
TinyPerson: The agent itself, to facilitate chaining.
"""
self.define_relationships([{"Name": other_agent.name, "Description": description}], replace=False)
if symmetric_description is not None:
other_agent.define_relationships([{"Name": self.name, "Description": symmetric_description}], replace=False)
return self
############################################################################
def add_mental_faculties(self, mental_faculties):
"""
Adds a list of mental faculties to the agent.
"""
for faculty in mental_faculties:
self.add_mental_faculty(faculty)
return self
def add_mental_faculty(self, faculty):
"""
Adds a mental faculty to the agent.
"""
# check if the faculty is already there or not
if faculty not in self._mental_faculties:
self._mental_faculties.append(faculty)
else:
raise Exception(f"The mental faculty {faculty} is already present in the agent.")
return self
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def act(
self,
until_done=True,
n=None,
return_actions=False,
max_content_length=None,
):
"""
Acts in the environment and updates its internal cognitive state.
Either acts until the agent is done and needs additional stimuli, or acts a fixed number of times,
but not both.
Args:
until_done (bool): Whether to keep acting until the agent is done and needs additional stimuli.
n (int): The number of actions to perform. Defaults to None.
return_actions (bool): Whether to return the actions or not. Defaults to False.
"""
# either act until done or act a fixed number of times, but not both
assert not (until_done and n is not None)
if n is not None:
assert n < TinyPerson.MAX_ACTIONS_BEFORE_DONE
contents = []
# A separate function to run before each action, which is not meant to be repeated in case of errors.
def aux_pre_act():
# TODO maybe we don't need this at all anymore?
#
# A quick thought before the action. This seems to help with better model responses, perhaps because
# it interleaves user with assistant messages.
pass # self.think("I will now think, reflect and act a bit, and then issue DONE.")
# Aux function to perform exactly one action.
# Occasionally, the model will return JSON missing important keys, so we just ask it to try again
# Sometimes `content` contains EpisodicMemory's MEMORY_BLOCK_OMISSION_INFO message, which raises a TypeError on line 443
@repeat_on_error(retries=5, exceptions=[KeyError, TypeError])
def aux_act_once():
# ensure we have the latest prompt (initial system message + selected messages from memory)
self.reset_prompt()
action, role, content, all_negative_feedbacks = self.action_generator.generate_next_action(self, self.current_messages)
logger.debug(f"{self.name}'s action: {action}")
# check the next action similarity, and if it is too similar, put a system warning instruction in memory too
next_action_similarity = utils.next_action_jaccard_similarity(self, action)
# we have a redundant repetition check here, because this an be computed quickly and is often very useful.
if self.enable_basic_action_repetition_prevention and \
(TinyPerson.MAX_ACTION_SIMILARITY is not None) and (next_action_similarity > TinyPerson.MAX_ACTION_SIMILARITY):
logger.warning(f"[{self.name}] Action similarity is too high ({next_action_similarity}), replacing it with DONE.")
# replace the action with a DONE
action = {"type": "DONE", "content": "", "target": ""}
content["action"] = action
content["cognitive_state"] = {}
self.store_in_memory({'role': 'system',
'content': \
f"""
# EXCESSIVE ACTION SIMILARITY WARNING
You were about to generate a repetitive action (jaccard similarity = {next_action_similarity}).
Thus, the action was discarded and replaced by an artificial DONE.
DO NOT BE REPETITIVE. This is not a human-like behavior, therefore you **must** avoid this in the future.
Your alternatives are:
- produce more diverse actions.
- aggregate similar actions into a single, larger, action and produce it all at once.
- as a **last resort only**, you may simply not acting at all by issuing a DONE.
""",
'type': 'feedback',
'simulation_timestamp': self.iso_datetime()})
# All checks done, we can commit the action to memory.
self.store_in_memory({'role': role, 'content': content,
'type': 'action',
'simulation_timestamp': self.iso_datetime()})
self._actions_buffer.append(action)
if "cognitive_state" in content:
cognitive_state = content["cognitive_state"]
logger.debug(f"[{self.name}] Cognitive state: {cognitive_state}")
self._update_cognitive_state(goals=cognitive_state.get("goals", None),
context=cognitive_state.get("context", None),
attention=cognitive_state.get("emotions", None),
emotions=cognitive_state.get("emotions", None))
contents.append(content)
if TinyPerson.communication_display:
self._display_communication(role=role, content=content, kind='action', simplified=True, max_content_length=max_content_length)
#
# Some actions induce an immediate stimulus or other side-effects. We need to process them here, by means of the mental faculties.
#
for faculty in self._mental_faculties:
faculty.process_action(self, action)
#
# turns all_negative_feedbacks list into a system message
#
# TODO improve this?
#
##if len(all_negative_feedbacks) > 0:
## feedback = """
## # QUALITY FEEDBACK
##
## Up to the present moment, we monitored actions and tentative aborted actions (i.e., that were not actually executed),
## and some of them were not of good quality.
## Some of those were replaced by regenerated actions of better quality. In the process of doing so, some
## important quality feedback was produced, which is now given below.
##
## To improve your performance, and prevent future similar quality issues, you **MUST** take into account the following feedback
## whenever computing your future actions. Note that the feedback might also include the actual action or tentative action
## that was of low quality, so that you can understand what was wrong with it and avoid similar mistakes in the future.
##
## """
## for i, feedback_item in enumerate(all_negative_feedbacks):
## feedback += f"{feedback_item}\n\n"
## feedback += f"\n\n *** \n\n"
##
## self.store_in_memory({'role': 'system', 'content': feedback,
## 'type': 'feedback',
## 'simulation_timestamp': self.iso_datetime()})
##
# count the actions as this can be useful for taking decisions later
self.actions_count += 1
#
# How to proceed with a sequence of actions.
#
##### Option 1: run N actions ######
if n is not None:
for i in range(n):
aux_pre_act()
aux_act_once()
##### Option 2: run until DONE ######
elif until_done:
while (len(contents) == 0) or (
not contents[-1]["action"]["type"] == "DONE"
):
# check if the agent is acting without ever stopping
if len(contents) > TinyPerson.MAX_ACTIONS_BEFORE_DONE:
logger.warning(f"[{self.name}] Agent {self.name} is acting without ever stopping. This may be a bug. Let's stop it here anyway.")
break
if len(contents) > 4: # just some minimum number of actions to check for repetition, could be anything >= 3
# if the last three actions were the same, then we are probably in a loop
if contents[-1]['action'] == contents[-2]['action'] == contents[-3]['action']:
logger.warning(f"[{self.name}] Agent {self.name} is acting in a loop. This may be a bug. Let's stop it here anyway.")
break
aux_pre_act()
aux_act_once()
# The end of a sequence of actions is always considered to mark the end of an episode.
self.consolidate_episode_memories()
if return_actions:
return contents
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def listen(
self,
speech,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Listens to another agent (artificial or human) and updates its internal cognitive state.
Args:
speech (str): The speech to listen to.
source (AgentOrWorld, optional): The source of the speech. Defaults to None.
"""
return self._observe(
stimulus={
"type": "CONVERSATION",
"content": speech,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def socialize(
self,
social_description: str,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Perceives a social stimulus through a description and updates its internal cognitive state.
Args:
social_description (str): The description of the social stimulus.
source (AgentOrWorld, optional): The source of the social stimulus. Defaults to None.
"""
return self._observe(
stimulus={
"type": "SOCIAL",
"content": social_description,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def see(
self,
visual_description,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Perceives a visual stimulus through a description and updates its internal cognitive state.
Args:
visual_description (str): The description of the visual stimulus.
source (AgentOrWorld, optional): The source of the visual stimulus. Defaults to None.
"""
return self._observe(
stimulus={
"type": "VISUAL",
"content": visual_description,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def think(self, thought, max_content_length=None):
"""
Forces the agent to think about something and updates its internal cognitive state.
"""
return self._observe(
stimulus={
"type": "THOUGHT",
"content": thought,
"source": name_or_empty(self),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def internalize_goal(
self, goal, max_content_length=None
):
"""
Internalizes a goal and updates its internal cognitive state.
"""
return self._observe(
stimulus={
"type": "INTERNAL_GOAL_FORMULATION",
"content": goal,
"source": name_or_empty(self),
},
max_content_length=max_content_length,
)
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def _observe(self, stimulus, max_content_length=None):
stimuli = [stimulus]
content = {"stimuli": stimuli}
logger.debug(f"[{self.name}] Observing stimuli: {content}")
# whatever comes from the outside will be interpreted as coming from 'user', simply because
# this is the counterpart of 'assistant'
self.store_in_memory({'role': 'user', 'content': content,
'type': 'stimulus',
'simulation_timestamp': self.iso_datetime()})
if TinyPerson.communication_display:
self._display_communication(
role="user",
content=content,
kind="stimuli",
simplified=True,
max_content_length=max_content_length,
)
# count the stimuli as this can be useful for taking decisions later
self.stimuli_count += 1
return self # allows easier chaining of methods
@transactional()
def listen_and_act(
self,
speech,
return_actions=False,
max_content_length=None,
):
"""
Convenience method that combines the `listen` and `act` methods.
"""
self.listen(speech, max_content_length=max_content_length)
return self.act(
return_actions=return_actions, max_content_length=max_content_length
)
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def see_and_act(
self,
visual_description,
return_actions=False,
max_content_length=None,
):
"""
Convenience method that combines the `see` and `act` methods.
"""
self.see(visual_description, max_content_length=max_content_length)
return self.act(
return_actions=return_actions, max_content_length=max_content_length
)
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def think_and_act(
self,
thought,
return_actions=False,
max_content_length=None,
):
"""
Convenience method that combines the `think` and `act` methods.
"""
self.think(thought, max_content_length=max_content_length)
return self.act(return_actions=return_actions, max_content_length=max_content_length)
def read_documents_from_folder(self, documents_path:str):
"""
Reads documents from a directory and loads them into the semantic memory.
"""
logger.info(f"Setting documents path to {documents_path} and loading documents.")
self.semantic_memory.add_documents_path(documents_path)
def read_document_from_file(self, file_path:str):
"""
Reads a document from a file and loads it into the semantic memory.
"""
logger.info(f"Reading document from file: {file_path}")
self.semantic_memory.add_document_path(file_path)
def read_documents_from_web(self, web_urls:list):
"""
Reads documents from web URLs and loads them into the semantic memory.
"""
logger.info(f"Reading documents from the following web URLs: {web_urls}")
self.semantic_memory.add_web_urls(web_urls)
def read_document_from_web(self, web_url:str):
"""
Reads a document from a web URL and loads it into the semantic memory.
"""
logger.info(f"Reading document from web URL: {web_url}")
self.semantic_memory.add_web_url(web_url)
@transactional()
def move_to(self, location, context=[]):
"""
Moves to a new location and updates its internal cognitive state.
"""
self._mental_state["location"] = location
# context must also be updated when moved, since we assume that context is dictated partly by location.
self.change_context(context)
@transactional()
def change_context(self, context: list):
"""
Changes the context and updates its internal cognitive state.
"""
self._mental_state["context"] = {
"description": item for item in context
}
self._update_cognitive_state(context=context)
@transactional()
def make_agent_accessible(
self,
agent: Self,
relation_description: str = "An agent I can currently interact with.",
):
"""
Makes an agent accessible to this agent.
"""
if agent not in self._accessible_agents:
self._accessible_agents.append(agent)
self._mental_state["accessible_agents"].append(
{"name": agent.name, "relation_description": relation_description}
)
else:
logger.warning(
f"[{self.name}] Agent {agent.name} is already accessible to {self.name}."
)
@transactional()
def make_agents_accessible(self, agents: list, relation_description: str = "An agent I can currently interact with."):
"""
Makes a list of agents accessible to this agent.
"""
for agent in agents:
self.make_agent_accessible(agent, relation_description)
@transactional()
def make_agent_inaccessible(self, agent: Self):
"""
Makes an agent inaccessible to this agent.
"""
if agent in self._accessible_agents:
self._accessible_agents.remove(agent)
else:
logger.warning(
f"[{self.name}] Agent {agent.name} is already inaccessible to {self.name}."
)
@transactional()
def make_all_agents_inaccessible(self):
"""
Makes all agents inaccessible to this agent.
"""
self._accessible_agents = []
self._mental_state["accessible_agents"] = []
@property
def accessible_agents(self):
"""
Property to access the list of accessible agents.
"""
return self._accessible_agents
###########################################################
# Internal cognitive state changes
###########################################################
@transactional()
def _update_cognitive_state(
self, goals=None, context=None, attention=None, emotions=None
):
"""
Update the TinyPerson's cognitive state.
"""
# Update current datetime. The passage of time is controlled by the environment, if any.
if self.environment is not None and self.environment.current_datetime is not None:
self._mental_state["datetime"] = utils.pretty_datetime(self.environment.current_datetime)
# update current goals
if goals is not None:
self._mental_state["goals"] = goals
# update current context
if context is not None:
self._mental_state["context"] = context
# update current attention
if attention is not None:
self._mental_state["attention"] = attention
# update current emotions
if emotions is not None:
self._mental_state["emotions"] = emotions
# update relevant memories for the current situation. These are memories that come to mind "spontaneously" when the agent is in a given context,
# so avoiding the need to actively trying to remember them.
current_memory_context = self.retrieve_relevant_memories_for_current_context()
self._mental_state["memory_context"] = current_memory_context
self.reset_prompt()
###########################################################
# Memory management
###########################################################
def store_in_memory(self, value: Any) -> list:
self.episodic_memory.store(value)
self._current_episode_event_count += 1
logger.debug(f"[{self.name}] Current episode event count: {self._current_episode_event_count}.")
if self._current_episode_event_count >= self.MAX_EPISODE_LENGTH:
# commit the current episode to memory, if it is long enough
logger.warning(f"[{self.name}] Episode length exceeded {self.MAX_EPISODE_LENGTH} events. Committing episode to memory. Please check whether this was expected or not.")
self.consolidate_episode_memories()
def consolidate_episode_memories(self):
"""
Applies all memory consolidation or transformation processes appropriate to the conclusion of one simulation episode.
"""
# a minimum length of the episode is required to consolidate it, to avoid excessive fragments in the semantic memory
if self._current_episode_event_count > self.MIN_EPISODE_LENGTH:
logger.debug(f"[{self.name}] ***** Consolidating current episode memories into semantic memory *****")
# Consolidate latest episodic memories into semantic memory
if config_manager.get("enable_memory_consolidation"):
episodic_consolidator = EpisodicConsolidator()
episode = self.episodic_memory.get_current_episode(item_types=["action", "stimulus"],)
logger.debug(f"[{self.name}] Current episode: {episode}")
consolidated_memories = episodic_consolidator.process(episode, timestamp=self._mental_state["datetime"], context=self._mental_state, persona=self.minibio())["consolidation"]
if consolidated_memories is not None:
logger.info(f"[{self.name}] Consolidating current {len(episode)} episodic events as consolidated semantic memories.")
logger.debug(f"[{self.name}] Consolidated memories: {consolidated_memories}")
self.semantic_memory.store_all(consolidated_memories)
else:
logger.debug(f"[{self.name}] No memories to consolidate from the current episode.")
else:
logger.warning(f"[{self.name}] Memory consolidation is disabled. Not consolidating current episode memories into semantic memory.")
# commit the current episode to episodic memory
self.episodic_memory.commit_episode()
self._current_episode_event_count = 0
logger.debug(f"[{self.name}] Current episode event count reset to 0 after consolidation.")
# TODO reflections, optimizations, etc.
def optimize_memory(self):
pass #TODO
def clear_episodic_memory(self, max_prefix_to_clear=None, max_suffix_to_clear=None):
"""
Clears the episodic memory, causing a permanent "episodic amnesia". Note that this does not
change other memories, such as semantic memory.
"""
self.episodic_memory.clear(max_prefix_to_clear=max_prefix_to_clear, max_suffix_to_clear=max_suffix_to_clear)
def retrieve_memories(self, first_n: int, last_n: int, include_omission_info:bool=True, max_content_length:int=None) -> list:
episodes = self.episodic_memory.retrieve(first_n=first_n, last_n=last_n, include_omission_info=include_omission_info)
if max_content_length is not None:
episodes = utils.truncate_actions_or_stimuli(episodes, max_content_length)
return episodes
def retrieve_recent_memories(self, max_content_length:int=None) -> list:
episodes = self.episodic_memory.retrieve_recent()
if max_content_length is not None:
episodes = utils.truncate_actions_or_stimuli(episodes, max_content_length)
return episodes
def retrieve_relevant_memories(self, relevance_target:str, top_k=20) -> list:
relevant = self.semantic_memory.retrieve_relevant(relevance_target, top_k=top_k)
return relevant
def retrieve_relevant_memories_for_current_context(self, top_k=7) -> list:
# current context is composed of th recent memories, plus context, goals, attention, and emotions
context = self._mental_state["context"]
goals = self._mental_state["goals"]
attention = self._mental_state["attention"]
emotions = self._mental_state["emotions"]
recent_memories = "\n".join([f" - {m['content']}" for m in self.retrieve_memories(first_n=10, last_n=20, max_content_length=500)])
# put everything together in a nice markdown string to fetch relevant memories
target = f"""
Current Context: {context}
Current Goals: {goals}
Current Attention: {attention}
Current Emotions: {emotions}
Selected Episodic Memories (from oldest to newest):
{recent_memories}
"""
logger.debug(f"Retrieving relevant memories for contextual target: {target}")
return self.retrieve_relevant_memories(target, top_k=top_k)
def summarize_relevant_memories_via_full_scan(self, relevance_target:str, item_type: str = None) -> str:
"""
Summarizes relevant memories for a given target by scanning the entire semantic memory.
Args:
relevance_target (str): The target to retrieve relevant memories for.
item_type (str, optional): The type of items to summarize. Defaults to None.
max_summary_length (int, optional): The maximum length of the summary. Defaults to 1000.
Returns:
str: The summary of relevant memories.
"""
return self.semantic_memory.summarize_relevant_via_full_scan(relevance_target, item_type=item_type)
###########################################################
# Inspection conveniences
###########################################################
def last_remembered_action(self, ignore_done:bool=True):
"""
Returns the last remembered action.
Args:
ignore_done (bool): Whether to ignore the "DONE" action or not. Defaults to True.
"""
action = None
memory_items_list = self.episodic_memory.retrieve_last(include_omission_info=False, item_type="action")
if len(memory_items_list) > 0:
# iterate from last to first while the action type is not "DONE"
for candidate_item in memory_items_list[::-1]:
if candidate_item["content"]["action"]["type"] != "DONE":
action = candidate_item["content"]["action"]
break
else:
if ignore_done:
continue
else:
action = candidate_item["content"]["action"]
break
return action
###########################################################
# Communication display and action execution
###########################################################
def _display_communication(
self,
role,
content,
kind,
simplified=True,
max_content_length=default["max_content_display_length"],
):
"""
Displays the current communication and stores it in a buffer for later use.
"""
# CONCURRENT PROTECTION, as we'll access shared display buffers
with concurrent_agent_action_lock:
if kind == "stimuli":
rendering = self._pretty_stimuli(
role=role,
content=content,
simplified=simplified,
max_content_length=max_content_length,
)
source = content["stimuli"][0].get("source", None)
target = self.name
elif kind == "action":
rendering = self._pretty_action(
role=role,
content=content,
simplified=simplified,
max_content_length=max_content_length,
)
source = self.name
target = content["action"].get("target", None)
else:
raise ValueError(f"Unknown communication kind: {kind}")
# if the agent has no parent environment, then it is a free agent and we can display the communication.
# otherwise, the environment will display the communication instead. This is important to make sure that
# the communication is displayed in the correct order, since environments control the flow of their underlying
# agents.
if self.environment is None:
self._push_and_display_latest_communication({"kind": kind, "rendering":rendering, "content": content, "source":source, "target": target})
else:
self.environment._push_and_display_latest_communication({"kind": kind, "rendering":rendering, "content": content, "source":source, "target": target})
def _push_and_display_latest_communication(self, communication):
"""
Pushes the latest communications to the agent's buffer.
"""
self._displayed_communications_buffer.append(communication)
print(communication["rendering"])
def pop_and_display_latest_communications(self):
"""
Pops the latest communications and displays them.
"""
communications = self._displayed_communications_buffer
self._displayed_communications_buffer = []
for communication in communications:
print(communication["rendering"])
return communications
def clear_communications_buffer(self):
"""
Cleans the communications buffer.
"""
self._displayed_communications_buffer = []
@transactional()
def pop_latest_actions(self) -> list:
"""
Returns the latest actions performed by this agent. Typically used
by an environment to consume the actions and provide the appropriate
environmental semantics to them (i.e., effects on other agents).
"""
actions = self._actions_buffer
self._actions_buffer = []
return actions
@transactional()
def pop_actions_and_get_contents_for(
self, action_type: str, only_last_action: bool = True
) -> list:
"""
Returns the contents of actions of a given type performed by this agent.
Typically used to perform inspections and tests.
Args:
action_type (str): The type of action to look for.
only_last_action (bool, optional): Whether to only return the contents of the last action. Defaults to False.
"""
actions = self.pop_latest_actions()
# Filter the actions by type
actions = [action for action in actions if action["type"] == action_type]
# If interested only in the last action, return the latest one
if only_last_action:
return actions[-1].get("content", "")
# Otherwise, return all contents from the filtered actions
return "\n".join([action.get("content", "") for action in actions])
#############################################################################################
# Formatting conveniences
#
# For rich colors,
# see: https://rich.readthedocs.io/en/latest/appendix/colors.html#appendix-colors
#############################################################################################
def __repr__(self):
return f"TinyPerson(name='{self.name}')"
@transactional()
def minibio(self, extended=True, requirements=None):
"""
Returns a mini-biography of the TinyPerson.
Args:
extended (bool): Whether to include extended information or not.
requirements (str): Additional requirements for the biography (e.g., focus on a specific aspect relevant for the scenario).
Returns:
str: The mini-biography.
"""
# if occupation is a dict and has a "title" key, use that as the occupation
if isinstance(self._persona['occupation'], dict) and 'title' in self._persona['occupation']:
occupation = self._persona['occupation']['title']
else:
occupation = self._persona['occupation']
base_biography = f"{self.name} is a {self._persona['age']} year old {occupation}, {self._persona['nationality']}, currently living in {self._persona['residence']}."
if self._extended_agent_summary is None and extended:
logger.debug(f"Generating extended agent summary for {self.name}.")
self._extended_agent_summary = LLMChat(
system_prompt=f"""
You are given a short biography of an agent, as well as a detailed specification of his or her other characteristics
You must then produce a short paragraph (3 or 4 sentences) that **complements** the short biography, adding details about
personality, interests, opinions, skills, etc. Do not repeat the information already given in the short biography.
repeating the information already given. The paragraph should be coherent, consistent and comprehensive. All information
must be grounded on the specification, **do not** create anything new.
{"Additional constraints: "+ requirements if requirements is not None else ""}
""",
user_prompt=f"""
**Short biography:** {base_biography}
**Detailed specification:** {self._persona}
""").call()
if extended:
biography = f"{base_biography} {self._extended_agent_summary}"
else:
biography = base_biography
return biography
def pp_current_interactions(
self,
simplified=True,
skip_system=True,
max_content_length=default["max_content_display_length"],
first_n=None,
last_n=None,
include_omission_info:bool=True
):
"""
Pretty prints the current messages.
"""
print(
self.pretty_current_interactions(
simplified=simplified,
skip_system=skip_system,
max_content_length=max_content_length,
first_n=first_n,
last_n=last_n,
include_omission_info=include_omission_info
)
)
def pp_last_interactions(
self,
n=3,
simplified=True,
skip_system=True,
max_content_length=default["max_content_display_length"],
include_omission_info:bool=True
):
"""
Pretty prints the last n messages. Useful to examine the conclusion of an experiment.
"""
print(
self.pretty_current_interactions(
simplified=simplified,
skip_system=skip_system,
max_content_length=max_content_length,
first_n=None,
last_n=n,
include_omission_info=include_omission_info
)
)
def pretty_current_interactions(self, simplified=True, skip_system=True, max_content_length=default["max_content_display_length"], first_n=None, last_n=None, include_omission_info:bool=True):
"""
Returns a pretty, readable, string with the current messages.
"""
lines = [f"**** BEGIN SIMULATION TRAJECTORY FOR {self.name} ****"]
last_step = 0
for i, message in enumerate(self.episodic_memory.retrieve(first_n=first_n, last_n=last_n, include_omission_info=include_omission_info)):
try:
if not (skip_system and message['role'] == 'system'):
msg_simplified_type = ""
msg_simplified_content = ""
msg_simplified_actor = ""
last_step = i
lines.append(f"Agent simulation trajectory event #{i}:")
lines.append(self._pretty_timestamp(message['role'], message['simulation_timestamp']))
if message["role"] == "system":
msg_simplified_actor = "SYSTEM"
msg_simplified_type = message["role"]
msg_simplified_content = message["content"]
lines.append(
f"[dim] {msg_simplified_type}: {msg_simplified_content}[/]"
)
elif message["role"] == "user":
lines.append(
self._pretty_stimuli(
role=message["role"],
content=message["content"],
simplified=simplified,
max_content_length=max_content_length,
)
)
elif message["role"] == "assistant":
lines.append(
self._pretty_action(
role=message["role"],
content=message["content"],
simplified=simplified,
max_content_length=max_content_length,
)
)
else:
lines.append(f"{message['role']}: {message['content']}")
except:
# print(f"ERROR: {message}")
continue
lines.append(f"The last agent simulation trajectory event number was {last_step}, thus the current number of the NEXT POTENTIAL TRAJECTORY EVENT is {last_step + 1}.")
lines.append(f"**** END SIMULATION TRAJECTORY FOR {self.name} ****\n\n")
return "\n".join(lines)
def _pretty_stimuli(
self,
role,
content,
simplified=True,
max_content_length=default["max_content_display_length"],
) -> list:
"""
Pretty prints stimuli.
"""
lines = []
msg_simplified_actor = "USER"
for stimus in content["stimuli"]:
if simplified:
if stimus["source"] != "":
msg_simplified_actor = stimus["source"]
else:
msg_simplified_actor = "USER"
msg_simplified_type = stimus["type"]
msg_simplified_content = utils.break_text_at_length(
stimus["content"], max_length=max_content_length
)
indent = " " * len(msg_simplified_actor) + " > "
msg_simplified_content = textwrap.fill(
msg_simplified_content,
width=TinyPerson.PP_TEXT_WIDTH,
initial_indent=indent,
subsequent_indent=indent,
)
#
# Using rich for formatting. Let's make things as readable as possible!
#
rich_style = utils.RichTextStyle.get_style_for("stimulus", msg_simplified_type)
lines.append(
f"[{rich_style}][underline]{msg_simplified_actor}[/] --> [{rich_style}][underline]{self.name}[/]: [{msg_simplified_type}] \n{msg_simplified_content}[/]"
)
else:
lines.append(f"{role}: {content}")
return "\n".join(lines)
def _pretty_action(
self,
role,
content,
simplified=True,
max_content_length=default["max_content_display_length"],
) -> str:
"""
Pretty prints an action.
"""
if simplified:
msg_simplified_actor = self.name
msg_simplified_type = content["action"]["type"]
msg_simplified_content = utils.break_text_at_length(
content["action"].get("content", ""), max_length=max_content_length
)
indent = " " * len(msg_simplified_actor) + " > "
msg_simplified_content = textwrap.fill(
msg_simplified_content,
width=TinyPerson.PP_TEXT_WIDTH,
initial_indent=indent,
subsequent_indent=indent,
)
#
# Using rich for formatting. Let's make things as readable as possible!
#
rich_style = utils.RichTextStyle.get_style_for("action", msg_simplified_type)
return f"[{rich_style}][underline]{msg_simplified_actor}[/] acts: [{msg_simplified_type}] \n{msg_simplified_content}[/]"
else:
return f"{role}: {content}"
def _pretty_timestamp(
self,
role,
timestamp,
) -> str:
"""
Pretty prints a timestamp.
"""
return f">>>>>>>>> Date and time of events: {timestamp}"
def iso_datetime(self) -> str:
"""
Returns the current datetime of the environment, if any.
Returns:
datetime: The current datetime of the environment in ISO forat.
"""
if self.environment is not None and self.environment.current_datetime is not None:
return self.environment.current_datetime.isoformat()
else:
return None
###########################################################
# IO
###########################################################
def save_specification(self, path, include_mental_faculties=True, include_memory=False, include_mental_state=False):
"""
Saves the current configuration to a JSON file.
"""
suppress_attributes = []
# should we include the mental faculties?
if not include_mental_faculties:
suppress_attributes.append("_mental_faculties")
# should we include the memory?
if not include_memory:
suppress_attributes.append("episodic_memory")
suppress_attributes.append("semantic_memory")
# should we include the mental state?
if not include_mental_state:
suppress_attributes.append("_mental_state")
self.to_json(suppress=suppress_attributes, file_path=path,
serialization_type_field_name="type")
@staticmethod
def load_specification(path_or_dict, suppress_mental_faculties=False, suppress_memory=False, suppress_mental_state=False,
auto_rename_agent=False, new_agent_name=None):
"""
Loads a JSON agent specification.
Args:
path_or_dict (str or dict): The path to the JSON file or the dictionary itself.
suppress_mental_faculties (bool, optional): Whether to suppress loading the mental faculties. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_mental_state (bool, optional): Whether to suppress loading the mental state. Defaults to False.
auto_rename_agent (bool, optional): Whether to auto rename the agent. Defaults to False.
new_agent_name (str, optional): The new name for the agent. Defaults to None.
"""
suppress_attributes = []
# should we suppress the mental faculties?
if suppress_mental_faculties:
suppress_attributes.append("_mental_faculties")
# should we suppress the memory?
if suppress_memory:
suppress_attributes.append("episodic_memory")
suppress_attributes.append("semantic_memory")
# should we suppress the mental state?
if suppress_mental_state:
suppress_attributes.append("_mental_state")
return TinyPerson.from_json(json_dict_or_path=path_or_dict, suppress=suppress_attributes,
serialization_type_field_name="type",
post_init_params={"auto_rename_agent": auto_rename_agent, "new_agent_name": new_agent_name})
@staticmethod
def load_specifications_from_folder(folder_path:str, file_suffix=".agent.json", suppress_mental_faculties=False,
suppress_memory=False, suppress_mental_state=False, auto_rename_agent=False,
new_agent_name=None) -> list:
"""
Loads all JSON agent specifications from a folder.
Args:
folder_path (str): The path to the folder containing the JSON files.
file_suffix (str, optional): The suffix of the JSON files. Defaults to ".agent.json".
suppress_mental_faculties (bool, optional): Whether to suppress loading the mental faculties. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_mental_state (bool, optional): Whether to suppress loading the mental state. Defaults to False.
auto_rename_agent (bool, optional): Whether to auto rename the agent. Defaults to False.
new_agent_name (str, optional): The new name for the agent. Defaults to None.
"""
agents = []
for file in os.listdir(folder_path):
if file.endswith(file_suffix):
file_path = os.path.join(folder_path, file)
agent = TinyPerson.load_specification(file_path, suppress_mental_faculties=suppress_mental_faculties,
suppress_memory=suppress_memory, suppress_mental_state=suppress_mental_state,
auto_rename_agent=auto_rename_agent, new_agent_name=new_agent_name)
agents.append(agent)
return agents
def encode_complete_state(self) -> dict:
"""
Encodes the complete state of the TinyPerson, including the current messages, accessible agents, etc.
This is meant for serialization and caching purposes, not for exporting the state to the user.
"""
to_copy = copy.copy(self.__dict__)
# delete the logger and other attributes that cannot be serialized
del to_copy["environment"]
del to_copy["_mental_faculties"]
del to_copy["action_generator"]
to_copy["_accessible_agents"] = [agent.name for agent in self._accessible_agents]
to_copy['episodic_memory'] = self.episodic_memory.to_json()
to_copy['semantic_memory'] = self.semantic_memory.to_json()
to_copy["_mental_faculties"] = [faculty.to_json() for faculty in self._mental_faculties]
state = copy.deepcopy(to_copy)
return state
def decode_complete_state(self, state: dict) -> Self:
"""
Loads the complete state of the TinyPerson, including the current messages,
and produces a new TinyPerson instance.
"""
state = copy.deepcopy(state)
self._accessible_agents = [TinyPerson.get_agent_by_name(name) for name in state["_accessible_agents"]]
self.episodic_memory = EpisodicMemory.from_json(state['episodic_memory'])
self.semantic_memory = SemanticMemory.from_json(state['semantic_memory'])
for i, faculty in enumerate(self._mental_faculties):
faculty = faculty.from_json(state['_mental_faculties'][i])
# delete fields already present in the state
del state["_accessible_agents"]
del state['episodic_memory']
del state['semantic_memory']
del state['_mental_faculties']
# restore other fields
self.__dict__.update(state)
return self
def create_new_agent_from_current_spec(self, new_name:str) -> Self:
"""
Creates a new agent from the current agent's specification.
Args:
new_name (str): The name of the new agent. Agent names must be unique in the simulation,
this is why we need to provide a new name.
"""
new_agent = TinyPerson(name=new_name, spec_path=None)
new_persona = copy.deepcopy(self._persona)
new_persona['name'] = new_name
new_agent._persona = new_persona
return new_agent
@staticmethod
def add_agent(agent):
"""
Adds an agent to the global list of agents. Agent names must be unique,
so this method will raise an exception if the name is already in use.
"""
if agent.name in TinyPerson.all_agents:
raise ValueError(f"Agent name {agent.name} is already in use.")
else:
TinyPerson.all_agents[agent.name] = agent
@staticmethod
def has_agent(agent_name: str):
"""
Checks if an agent is already registered.
"""
return agent_name in TinyPerson.all_agents
@staticmethod
def set_simulation_for_free_agents(simulation):
"""
Sets the simulation if it is None. This allows free agents to be captured by specific simulation scopes
if desired.
"""
for agent in TinyPerson.all_agents.values():
if agent.simulation_id is None:
simulation.add_agent(agent)
@staticmethod
def get_agent_by_name(name):
"""
Gets an agent by name.
"""
if name in TinyPerson.all_agents:
return TinyPerson.all_agents[name]
else:
return None
@staticmethod
def all_agents_names():
"""
Returns the names of all agents.
"""
return list(TinyPerson.all_agents.keys())
@staticmethod
def clear_agents():
"""
Clears the global list of agents.
"""
TinyPerson.all_agents = {}</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="tinytroupe.agent.tiny_person.TinyPerson"><code class="flex name class">
<span>class <span class="ident">TinyPerson</span></span>
<span>(</span><span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"><p>A simulated person in the TinyTroupe universe.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@utils.post_init
class TinyPerson(JsonSerializableRegistry):
"""A simulated person in the TinyTroupe universe."""
# The maximum number of actions that an agent is allowed to perform before DONE.
# This prevents the agent from acting without ever stopping.
MAX_ACTIONS_BEFORE_DONE = 15
# The maximum similarity between consecutive actions. If the similarity is too high, the action is discarded and replaced by a DONE.
# Set this to None to disable the check.
MAX_ACTION_SIMILARITY = 0.85
MIN_EPISODE_LENGTH = config_manager.get("min_episode_length", 15) # The minimum number of messages in an episode before it is considered valid.
MAX_EPISODE_LENGTH = config_manager.get("max_episode_length", 50) # The maximum number of messages in an episode before it is considered valid.
PP_TEXT_WIDTH = 100
serializable_attributes = ["_persona", "_mental_state", "_mental_faculties", "_current_episode_event_count", "episodic_memory", "semantic_memory"]
serializable_attributes_renaming = {"_mental_faculties": "mental_faculties", "_persona": "persona", "_mental_state": "mental_state", "_current_episode_event_count": "current_episode_event_count"}
# A dict of all agents instantiated so far.
all_agents = {} # name -> agent
# Whether to display the communication or not. True is for interactive applications, when we want to see simulation
# outputs as they are produced.
communication_display:bool=True
def __init__(self, name:str=None,
action_generator=None,
episodic_memory=None,
semantic_memory=None,
mental_faculties:list=None,
enable_basic_action_repetition_prevention:bool=True):
"""
Creates a TinyPerson.
Args:
name (str): The name of the TinyPerson. Either this or spec_path must be specified.
action_generator (ActionGenerator, optional): The action generator to use. Defaults to ActionGenerator().
episodic_memory (EpisodicMemory, optional): The memory implementation to use. Defaults to EpisodicMemory().
semantic_memory (SemanticMemory, optional): The memory implementation to use. Defaults to SemanticMemory().
mental_faculties (list, optional): A list of mental faculties to add to the agent. Defaults to None.
enable_basic_action_repetition_prevention (bool, optional): Whether to enable basic action repetition prevention. Defaults to True.
"""
# NOTE: default values will be given in the _post_init method, as that's shared by
# direct initialization as well as via deserialization.
if action_generator is not None:
self.action_generator = action_generator
if episodic_memory is not None:
self.episodic_memory = episodic_memory
if semantic_memory is not None:
self.semantic_memory = semantic_memory
# Mental faculties
if mental_faculties is not None:
self._mental_faculties = mental_faculties
if enable_basic_action_repetition_prevention:
self.enable_basic_action_repetition_prevention = enable_basic_action_repetition_prevention
assert name is not None, "A TinyPerson must have a name."
self.name = name
# @post_init makes sure that _post_init is called after __init__
def _post_init(self, **kwargs):
"""
This will run after __init__, since the class has the @post_init decorator.
It is convenient to separate some of the initialization processes to make deserialize easier.
"""
from tinytroupe.agent.action_generator import ActionGenerator # import here to avoid circular import issues
############################################################
# Default values
############################################################
self.current_messages = []
# the current environment in which the agent is acting
self.environment = None
# The list of actions that this agent has performed so far, but which have not been
# consumed by the environment yet.
self._actions_buffer = []
# The list of agents that this agent can currently interact with.
# This can change over time, as agents move around the world.
self._accessible_agents = []
# the buffer of communications that have been displayed so far, used for
# saving these communications to another output form later (e.g., caching)
self._displayed_communications_buffer = []
if not hasattr(self, '_current_episode_event_count'):
self._current_episode_event_count = 0 # the number of events in the current episode, used to limit the episode length
if not hasattr(self, 'action_generator'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self.action_generator = ActionGenerator(max_attempts=config_manager.get("action_generator_max_attempts"),
enable_quality_checks=config_manager.get("action_generator_enable_quality_checks"),
enable_regeneration=config_manager.get("action_generator_enable_regeneration"),
enable_direct_correction=config_manager.get("action_generator_enable_direct_correction"),
enable_quality_check_for_persona_adherence=config_manager.get("action_generator_enable_quality_check_for_persona_adherence"),
enable_quality_check_for_selfconsistency=config_manager.get("action_generator_enable_quality_check_for_selfconsistency"),
enable_quality_check_for_fluency=config_manager.get("action_generator_enable_quality_check_for_fluency"),
enable_quality_check_for_suitability=config_manager.get("action_generator_enable_quality_check_for_suitability"),
enable_quality_check_for_similarity=config_manager.get("action_generator_enable_quality_check_for_similarity"),
continue_on_failure=config_manager.get("action_generator_continue_on_failure"),
quality_threshold=config_manager.get("action_generator_quality_threshold"))
if not hasattr(self, 'episodic_memory'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self.episodic_memory = EpisodicMemory(fixed_prefix_length= config_manager.get("episodic_memory_fixed_prefix_length"),
lookback_length=config_manager.get("episodic_memory_lookback_length"))
if not hasattr(self, 'semantic_memory'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self.semantic_memory = SemanticMemory()
# _mental_faculties
if not hasattr(self, '_mental_faculties'):
# This default value MUST NOT be in the method signature, otherwise it will be shared across all instances.
self._mental_faculties = []
# basic action repetition prevention
if not hasattr(self, 'enable_basic_action_repetition_prevention'):
self.enable_basic_action_repetition_prevention = True
# create the persona configuration dictionary
if not hasattr(self, '_persona'):
self._persona = {
"name": self.name,
"age": None,
"nationality": None,
"country_of_residence": None,
"occupation": None
}
if not hasattr(self, 'name'):
self.name = self._persona["name"]
# create the mental state dictionary
if not hasattr(self, '_mental_state'):
self._mental_state = {
"datetime": None,
"location": None,
"context": [],
"goals": [],
"attention": None,
"emotions": "Feeling nothing in particular, just calm.",
"memory_context": None,
"accessible_agents": [] # [{"agent": agent_1, "relation": "My friend"}, {"agent": agent_2, "relation": "My colleague"}, ...]
}
if not hasattr(self, '_extended_agent_summary'):
self._extended_agent_summary = None
if not hasattr(self, 'actions_count'):
self.actions_count = 0
if not hasattr(self, 'stimuli_count'):
self.stimuli_count = 0
self._prompt_template_path = os.path.join(
os.path.dirname(__file__), "prompts/tiny_person.mustache"
)
self._init_system_message = None # initialized later
############################################################
# Special mechanisms used during deserialization
############################################################
# rename agent to some specific name?
if kwargs.get("new_agent_name") is not None:
self._rename(kwargs.get("new_agent_name"))
# If auto-rename, use the given name plus some new number ...
if kwargs.get("auto_rename") is True:
new_name = self.name # start with the current name
rename_succeeded = False
while not rename_succeeded:
try:
self._rename(new_name)
TinyPerson.add_agent(self)
rename_succeeded = True
except ValueError:
new_id = utils.fresh_id(self.__class__.__name__)
new_name = f"{self.name}_{new_id}"
# ... otherwise, just register the agent
else:
# register the agent in the global list of agents
TinyPerson.add_agent(self)
# start with a clean slate
self.reset_prompt()
# it could be the case that the agent is being created within a simulation scope, in which case
# the simulation_id must be set accordingly
if current_simulation() is not None:
current_simulation().add_agent(self)
else:
self.simulation_id = None
def _rename(self, new_name:str):
self.name = new_name
self._persona["name"] = self.name
def generate_agent_system_prompt(self):
with open(self._prompt_template_path, "r") as f:
agent_prompt_template = f.read()
# let's operate on top of a copy of the configuration, because we'll need to add more variables, etc.
template_variables = self._persona.copy()
template_variables["persona"] = json.dumps(self._persona.copy(), indent=4)
# add mental state to the template variables
template_variables["mental_state"] = json.dumps(self._mental_state, indent=4)
# Prepare additional action definitions and constraints
actions_definitions_prompt = ""
actions_constraints_prompt = ""
for faculty in self._mental_faculties:
actions_definitions_prompt += f"{faculty.actions_definitions_prompt()}\n"
actions_constraints_prompt += f"{faculty.actions_constraints_prompt()}\n"
# Make the additional prompt pieces available to the template.
# Identation here is to align with the text structure in the template.
template_variables['actions_definitions_prompt'] = textwrap.indent(actions_definitions_prompt.strip(), " ")
template_variables['actions_constraints_prompt'] = textwrap.indent(actions_constraints_prompt.strip(), " ")
# RAI prompt components, if requested
template_variables = utils.add_rai_template_variables_if_enabled(template_variables)
return chevron.render(agent_prompt_template, template_variables)
def reset_prompt(self):
# render the template with the current configuration
self._init_system_message = self.generate_agent_system_prompt()
# - reset system message
# - make it clear that the provided events are past events and have already had their effects
self.current_messages = [
{"role": "system", "content": self._init_system_message},
{"role": "system", "content": "The next messages refer to past interactions you had recently and are meant to help you contextualize your next actions. "\
+ "They are the most recent episodic memories you have, including stimuli and actions. "\
+ "Their effects already took place and led to your present cognitive state (described above), so you can use them in conjunction "\
+ "with your cognitive state to inform your next actions and perceptions. Please consider them and then proceed with your next actions right after. "}
]
# sets up the actual interaction messages to use for prompting
self.current_messages += self.retrieve_recent_memories()
#########################################################################
# Persona definitions
#########################################################################
#
# Conveniences to access the persona configuration via dictionary-like syntax using
# the [] operator. e.g., agent["nationality"] = "American"
#
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
self.define(key, value)
#
# Conveniences to import persona definitions via the '+' operator,
# e.g., agent + {"nationality": "American", ...}
#
# e.g., agent + "path/to/fragment.json"
#
def __add__(self, other):
"""
Allows using the '+' operator to add persona definitions or import a fragment.
If 'other' is a dict, calls include_persona_definitions().
If 'other' is a string, calls import_fragment().
"""
if isinstance(other, dict):
self.include_persona_definitions(other)
elif isinstance(other, str):
self.import_fragment(other)
else:
raise TypeError("Unsupported operand type for +. Must be a dict or a string path to fragment.")
return self
#
# Various other conveniences to manipulate the persona configuration
#
def get(self, key):
"""
Returns the value of a key in the TinyPerson's persona configuration.
Supports dot notation for nested keys (e.g., "address.city").
"""
keys = key.split(".")
value = self._persona
for k in keys:
if isinstance(value, dict):
value = value.get(k, None)
else:
return None # If the path is invalid, return None
return value
@transactional()
def import_fragment(self, path):
"""
Imports a fragment of a persona configuration from a JSON file.
"""
with open(path, "r") as f:
fragment = json.load(f)
# check the type is "Fragment" and that there's also a "persona" key
if fragment.get("type", None) == "Fragment" and fragment.get("persona", None) is not None:
self.include_persona_definitions(fragment["persona"])
else:
raise ValueError("The imported JSON file must be a valid fragment of a persona configuration.")
# must reset prompt after adding to configuration
self.reset_prompt()
@transactional()
def include_persona_definitions(self, additional_definitions: dict):
"""
Imports a set of definitions into the TinyPerson. They will be merged with the current configuration.
It is also a convenient way to include multiple bundled definitions into the agent.
Args:
additional_definitions (dict): The additional definitions to import.
"""
self._persona = utils.merge_dicts(self._persona, additional_definitions)
# must reset prompt after adding to configuration
self.reset_prompt()
@transactional()
def define(self, key, value, merge=False, overwrite_scalars=True):
"""
Define a value to the TinyPerson's persona configuration. Value can either be a scalar or a dictionary.
If the value is a dictionary or list, you can choose to merge it with the existing value or replace it.
If the value is a scalar, you can choose to overwrite the existing value or not.
Args:
key (str): The key to define.
value (Any): The value to define.
merge (bool, optional): Whether to merge the dict/list values with the existing values or replace them. Defaults to False.
overwrite_scalars (bool, optional): Whether to overwrite scalar values or not. Defaults to True.
"""
# dedent value if it is a string
if isinstance(value, str):
value = textwrap.dedent(value)
# if the value is a dictionary, we can choose to merge it with the existing value or replace it
if isinstance(value, dict) or isinstance(value, list):
if merge:
self._persona = utils.merge_dicts(self._persona, {key: value})
else:
self._persona[key] = value
# if the value is a scalar, we can choose to overwrite it or not
elif overwrite_scalars or (key not in self._persona):
self._persona[key] = value
else:
raise ValueError(f"The key '{key}' already exists in the persona configuration and overwrite_scalars is set to False.")
# must reset prompt after adding to configuration
self.reset_prompt()
@transactional()
def define_relationships(self, relationships, replace=True):
"""
Defines or updates the TinyPerson's relationships.
Args:
relationships (list or dict): The relationships to add or replace. Either a list of dicts mapping agent names to relationship descriptions,
or a single dict mapping one agent name to its relationship description.
replace (bool, optional): Whether to replace the current relationships or just add to them. Defaults to True.
"""
if (replace == True) and (isinstance(relationships, list)):
self._persona['relationships'] = relationships
elif replace == False:
current_relationships = self._persona['relationships']
if isinstance(relationships, list):
for r in relationships:
current_relationships.append(r)
elif isinstance(relationships, dict) and len(relationships) == 2: #{"Name": ..., "Description": ...}
current_relationships.append(relationships)
else:
raise Exception("Only one key-value pair is allowed in the relationships dict.")
else:
raise Exception("Invalid arguments for define_relationships.")
##############################################################################
# Relationships
##############################################################################
@transactional()
def clear_relationships(self):
"""
Clears the TinyPerson's relationships.
"""
self._persona['relationships'] = []
return self
@transactional()
def related_to(self, other_agent, description, symmetric_description=None):
"""
Defines a relationship between this agent and another agent.
Args:
other_agent (TinyPerson): The other agent.
description (str): The description of the relationship.
symmetric (bool): Whether the relationship is symmetric or not. That is,
if the relationship is defined for both agents.
Returns:
TinyPerson: The agent itself, to facilitate chaining.
"""
self.define_relationships([{"Name": other_agent.name, "Description": description}], replace=False)
if symmetric_description is not None:
other_agent.define_relationships([{"Name": self.name, "Description": symmetric_description}], replace=False)
return self
############################################################################
def add_mental_faculties(self, mental_faculties):
"""
Adds a list of mental faculties to the agent.
"""
for faculty in mental_faculties:
self.add_mental_faculty(faculty)
return self
def add_mental_faculty(self, faculty):
"""
Adds a mental faculty to the agent.
"""
# check if the faculty is already there or not
if faculty not in self._mental_faculties:
self._mental_faculties.append(faculty)
else:
raise Exception(f"The mental faculty {faculty} is already present in the agent.")
return self
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def act(
self,
until_done=True,
n=None,
return_actions=False,
max_content_length=None,
):
"""
Acts in the environment and updates its internal cognitive state.
Either acts until the agent is done and needs additional stimuli, or acts a fixed number of times,
but not both.
Args:
until_done (bool): Whether to keep acting until the agent is done and needs additional stimuli.
n (int): The number of actions to perform. Defaults to None.
return_actions (bool): Whether to return the actions or not. Defaults to False.
"""
# either act until done or act a fixed number of times, but not both
assert not (until_done and n is not None)
if n is not None:
assert n < TinyPerson.MAX_ACTIONS_BEFORE_DONE
contents = []
# A separate function to run before each action, which is not meant to be repeated in case of errors.
def aux_pre_act():
# TODO maybe we don't need this at all anymore?
#
# A quick thought before the action. This seems to help with better model responses, perhaps because
# it interleaves user with assistant messages.
pass # self.think("I will now think, reflect and act a bit, and then issue DONE.")
# Aux function to perform exactly one action.
# Occasionally, the model will return JSON missing important keys, so we just ask it to try again
# Sometimes `content` contains EpisodicMemory's MEMORY_BLOCK_OMISSION_INFO message, which raises a TypeError on line 443
@repeat_on_error(retries=5, exceptions=[KeyError, TypeError])
def aux_act_once():
# ensure we have the latest prompt (initial system message + selected messages from memory)
self.reset_prompt()
action, role, content, all_negative_feedbacks = self.action_generator.generate_next_action(self, self.current_messages)
logger.debug(f"{self.name}'s action: {action}")
# check the next action similarity, and if it is too similar, put a system warning instruction in memory too
next_action_similarity = utils.next_action_jaccard_similarity(self, action)
# we have a redundant repetition check here, because this an be computed quickly and is often very useful.
if self.enable_basic_action_repetition_prevention and \
(TinyPerson.MAX_ACTION_SIMILARITY is not None) and (next_action_similarity > TinyPerson.MAX_ACTION_SIMILARITY):
logger.warning(f"[{self.name}] Action similarity is too high ({next_action_similarity}), replacing it with DONE.")
# replace the action with a DONE
action = {"type": "DONE", "content": "", "target": ""}
content["action"] = action
content["cognitive_state"] = {}
self.store_in_memory({'role': 'system',
'content': \
f"""
# EXCESSIVE ACTION SIMILARITY WARNING
You were about to generate a repetitive action (jaccard similarity = {next_action_similarity}).
Thus, the action was discarded and replaced by an artificial DONE.
DO NOT BE REPETITIVE. This is not a human-like behavior, therefore you **must** avoid this in the future.
Your alternatives are:
- produce more diverse actions.
- aggregate similar actions into a single, larger, action and produce it all at once.
- as a **last resort only**, you may simply not acting at all by issuing a DONE.
""",
'type': 'feedback',
'simulation_timestamp': self.iso_datetime()})
# All checks done, we can commit the action to memory.
self.store_in_memory({'role': role, 'content': content,
'type': 'action',
'simulation_timestamp': self.iso_datetime()})
self._actions_buffer.append(action)
if "cognitive_state" in content:
cognitive_state = content["cognitive_state"]
logger.debug(f"[{self.name}] Cognitive state: {cognitive_state}")
self._update_cognitive_state(goals=cognitive_state.get("goals", None),
context=cognitive_state.get("context", None),
attention=cognitive_state.get("emotions", None),
emotions=cognitive_state.get("emotions", None))
contents.append(content)
if TinyPerson.communication_display:
self._display_communication(role=role, content=content, kind='action', simplified=True, max_content_length=max_content_length)
#
# Some actions induce an immediate stimulus or other side-effects. We need to process them here, by means of the mental faculties.
#
for faculty in self._mental_faculties:
faculty.process_action(self, action)
#
# turns all_negative_feedbacks list into a system message
#
# TODO improve this?
#
##if len(all_negative_feedbacks) > 0:
## feedback = """
## # QUALITY FEEDBACK
##
## Up to the present moment, we monitored actions and tentative aborted actions (i.e., that were not actually executed),
## and some of them were not of good quality.
## Some of those were replaced by regenerated actions of better quality. In the process of doing so, some
## important quality feedback was produced, which is now given below.
##
## To improve your performance, and prevent future similar quality issues, you **MUST** take into account the following feedback
## whenever computing your future actions. Note that the feedback might also include the actual action or tentative action
## that was of low quality, so that you can understand what was wrong with it and avoid similar mistakes in the future.
##
## """
## for i, feedback_item in enumerate(all_negative_feedbacks):
## feedback += f"{feedback_item}\n\n"
## feedback += f"\n\n *** \n\n"
##
## self.store_in_memory({'role': 'system', 'content': feedback,
## 'type': 'feedback',
## 'simulation_timestamp': self.iso_datetime()})
##
# count the actions as this can be useful for taking decisions later
self.actions_count += 1
#
# How to proceed with a sequence of actions.
#
##### Option 1: run N actions ######
if n is not None:
for i in range(n):
aux_pre_act()
aux_act_once()
##### Option 2: run until DONE ######
elif until_done:
while (len(contents) == 0) or (
not contents[-1]["action"]["type"] == "DONE"
):
# check if the agent is acting without ever stopping
if len(contents) > TinyPerson.MAX_ACTIONS_BEFORE_DONE:
logger.warning(f"[{self.name}] Agent {self.name} is acting without ever stopping. This may be a bug. Let's stop it here anyway.")
break
if len(contents) > 4: # just some minimum number of actions to check for repetition, could be anything >= 3
# if the last three actions were the same, then we are probably in a loop
if contents[-1]['action'] == contents[-2]['action'] == contents[-3]['action']:
logger.warning(f"[{self.name}] Agent {self.name} is acting in a loop. This may be a bug. Let's stop it here anyway.")
break
aux_pre_act()
aux_act_once()
# The end of a sequence of actions is always considered to mark the end of an episode.
self.consolidate_episode_memories()
if return_actions:
return contents
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def listen(
self,
speech,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Listens to another agent (artificial or human) and updates its internal cognitive state.
Args:
speech (str): The speech to listen to.
source (AgentOrWorld, optional): The source of the speech. Defaults to None.
"""
return self._observe(
stimulus={
"type": "CONVERSATION",
"content": speech,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def socialize(
self,
social_description: str,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Perceives a social stimulus through a description and updates its internal cognitive state.
Args:
social_description (str): The description of the social stimulus.
source (AgentOrWorld, optional): The source of the social stimulus. Defaults to None.
"""
return self._observe(
stimulus={
"type": "SOCIAL",
"content": social_description,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def see(
self,
visual_description,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Perceives a visual stimulus through a description and updates its internal cognitive state.
Args:
visual_description (str): The description of the visual stimulus.
source (AgentOrWorld, optional): The source of the visual stimulus. Defaults to None.
"""
return self._observe(
stimulus={
"type": "VISUAL",
"content": visual_description,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def think(self, thought, max_content_length=None):
"""
Forces the agent to think about something and updates its internal cognitive state.
"""
return self._observe(
stimulus={
"type": "THOUGHT",
"content": thought,
"source": name_or_empty(self),
},
max_content_length=max_content_length,
)
@config_manager.config_defaults(max_content_length="max_content_display_length")
def internalize_goal(
self, goal, max_content_length=None
):
"""
Internalizes a goal and updates its internal cognitive state.
"""
return self._observe(
stimulus={
"type": "INTERNAL_GOAL_FORMULATION",
"content": goal,
"source": name_or_empty(self),
},
max_content_length=max_content_length,
)
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def _observe(self, stimulus, max_content_length=None):
stimuli = [stimulus]
content = {"stimuli": stimuli}
logger.debug(f"[{self.name}] Observing stimuli: {content}")
# whatever comes from the outside will be interpreted as coming from 'user', simply because
# this is the counterpart of 'assistant'
self.store_in_memory({'role': 'user', 'content': content,
'type': 'stimulus',
'simulation_timestamp': self.iso_datetime()})
if TinyPerson.communication_display:
self._display_communication(
role="user",
content=content,
kind="stimuli",
simplified=True,
max_content_length=max_content_length,
)
# count the stimuli as this can be useful for taking decisions later
self.stimuli_count += 1
return self # allows easier chaining of methods
@transactional()
def listen_and_act(
self,
speech,
return_actions=False,
max_content_length=None,
):
"""
Convenience method that combines the `listen` and `act` methods.
"""
self.listen(speech, max_content_length=max_content_length)
return self.act(
return_actions=return_actions, max_content_length=max_content_length
)
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def see_and_act(
self,
visual_description,
return_actions=False,
max_content_length=None,
):
"""
Convenience method that combines the `see` and `act` methods.
"""
self.see(visual_description, max_content_length=max_content_length)
return self.act(
return_actions=return_actions, max_content_length=max_content_length
)
@transactional()
@config_manager.config_defaults(max_content_length="max_content_display_length")
def think_and_act(
self,
thought,
return_actions=False,
max_content_length=None,
):
"""
Convenience method that combines the `think` and `act` methods.
"""
self.think(thought, max_content_length=max_content_length)
return self.act(return_actions=return_actions, max_content_length=max_content_length)
def read_documents_from_folder(self, documents_path:str):
"""
Reads documents from a directory and loads them into the semantic memory.
"""
logger.info(f"Setting documents path to {documents_path} and loading documents.")
self.semantic_memory.add_documents_path(documents_path)
def read_document_from_file(self, file_path:str):
"""
Reads a document from a file and loads it into the semantic memory.
"""
logger.info(f"Reading document from file: {file_path}")
self.semantic_memory.add_document_path(file_path)
def read_documents_from_web(self, web_urls:list):
"""
Reads documents from web URLs and loads them into the semantic memory.
"""
logger.info(f"Reading documents from the following web URLs: {web_urls}")
self.semantic_memory.add_web_urls(web_urls)
def read_document_from_web(self, web_url:str):
"""
Reads a document from a web URL and loads it into the semantic memory.
"""
logger.info(f"Reading document from web URL: {web_url}")
self.semantic_memory.add_web_url(web_url)
@transactional()
def move_to(self, location, context=[]):
"""
Moves to a new location and updates its internal cognitive state.
"""
self._mental_state["location"] = location
# context must also be updated when moved, since we assume that context is dictated partly by location.
self.change_context(context)
@transactional()
def change_context(self, context: list):
"""
Changes the context and updates its internal cognitive state.
"""
self._mental_state["context"] = {
"description": item for item in context
}
self._update_cognitive_state(context=context)
@transactional()
def make_agent_accessible(
self,
agent: Self,
relation_description: str = "An agent I can currently interact with.",
):
"""
Makes an agent accessible to this agent.
"""
if agent not in self._accessible_agents:
self._accessible_agents.append(agent)
self._mental_state["accessible_agents"].append(
{"name": agent.name, "relation_description": relation_description}
)
else:
logger.warning(
f"[{self.name}] Agent {agent.name} is already accessible to {self.name}."
)
@transactional()
def make_agents_accessible(self, agents: list, relation_description: str = "An agent I can currently interact with."):
"""
Makes a list of agents accessible to this agent.
"""
for agent in agents:
self.make_agent_accessible(agent, relation_description)
@transactional()
def make_agent_inaccessible(self, agent: Self):
"""
Makes an agent inaccessible to this agent.
"""
if agent in self._accessible_agents:
self._accessible_agents.remove(agent)
else:
logger.warning(
f"[{self.name}] Agent {agent.name} is already inaccessible to {self.name}."
)
@transactional()
def make_all_agents_inaccessible(self):
"""
Makes all agents inaccessible to this agent.
"""
self._accessible_agents = []
self._mental_state["accessible_agents"] = []
@property
def accessible_agents(self):
"""
Property to access the list of accessible agents.
"""
return self._accessible_agents
###########################################################
# Internal cognitive state changes
###########################################################
@transactional()
def _update_cognitive_state(
self, goals=None, context=None, attention=None, emotions=None
):
"""
Update the TinyPerson's cognitive state.
"""
# Update current datetime. The passage of time is controlled by the environment, if any.
if self.environment is not None and self.environment.current_datetime is not None:
self._mental_state["datetime"] = utils.pretty_datetime(self.environment.current_datetime)
# update current goals
if goals is not None:
self._mental_state["goals"] = goals
# update current context
if context is not None:
self._mental_state["context"] = context
# update current attention
if attention is not None:
self._mental_state["attention"] = attention
# update current emotions
if emotions is not None:
self._mental_state["emotions"] = emotions
# update relevant memories for the current situation. These are memories that come to mind "spontaneously" when the agent is in a given context,
# so avoiding the need to actively trying to remember them.
current_memory_context = self.retrieve_relevant_memories_for_current_context()
self._mental_state["memory_context"] = current_memory_context
self.reset_prompt()
###########################################################
# Memory management
###########################################################
def store_in_memory(self, value: Any) -> list:
self.episodic_memory.store(value)
self._current_episode_event_count += 1
logger.debug(f"[{self.name}] Current episode event count: {self._current_episode_event_count}.")
if self._current_episode_event_count >= self.MAX_EPISODE_LENGTH:
# commit the current episode to memory, if it is long enough
logger.warning(f"[{self.name}] Episode length exceeded {self.MAX_EPISODE_LENGTH} events. Committing episode to memory. Please check whether this was expected or not.")
self.consolidate_episode_memories()
def consolidate_episode_memories(self):
"""
Applies all memory consolidation or transformation processes appropriate to the conclusion of one simulation episode.
"""
# a minimum length of the episode is required to consolidate it, to avoid excessive fragments in the semantic memory
if self._current_episode_event_count > self.MIN_EPISODE_LENGTH:
logger.debug(f"[{self.name}] ***** Consolidating current episode memories into semantic memory *****")
# Consolidate latest episodic memories into semantic memory
if config_manager.get("enable_memory_consolidation"):
episodic_consolidator = EpisodicConsolidator()
episode = self.episodic_memory.get_current_episode(item_types=["action", "stimulus"],)
logger.debug(f"[{self.name}] Current episode: {episode}")
consolidated_memories = episodic_consolidator.process(episode, timestamp=self._mental_state["datetime"], context=self._mental_state, persona=self.minibio())["consolidation"]
if consolidated_memories is not None:
logger.info(f"[{self.name}] Consolidating current {len(episode)} episodic events as consolidated semantic memories.")
logger.debug(f"[{self.name}] Consolidated memories: {consolidated_memories}")
self.semantic_memory.store_all(consolidated_memories)
else:
logger.debug(f"[{self.name}] No memories to consolidate from the current episode.")
else:
logger.warning(f"[{self.name}] Memory consolidation is disabled. Not consolidating current episode memories into semantic memory.")
# commit the current episode to episodic memory
self.episodic_memory.commit_episode()
self._current_episode_event_count = 0
logger.debug(f"[{self.name}] Current episode event count reset to 0 after consolidation.")
# TODO reflections, optimizations, etc.
def optimize_memory(self):
pass #TODO
def clear_episodic_memory(self, max_prefix_to_clear=None, max_suffix_to_clear=None):
"""
Clears the episodic memory, causing a permanent "episodic amnesia". Note that this does not
change other memories, such as semantic memory.
"""
self.episodic_memory.clear(max_prefix_to_clear=max_prefix_to_clear, max_suffix_to_clear=max_suffix_to_clear)
def retrieve_memories(self, first_n: int, last_n: int, include_omission_info:bool=True, max_content_length:int=None) -> list:
episodes = self.episodic_memory.retrieve(first_n=first_n, last_n=last_n, include_omission_info=include_omission_info)
if max_content_length is not None:
episodes = utils.truncate_actions_or_stimuli(episodes, max_content_length)
return episodes
def retrieve_recent_memories(self, max_content_length:int=None) -> list:
episodes = self.episodic_memory.retrieve_recent()
if max_content_length is not None:
episodes = utils.truncate_actions_or_stimuli(episodes, max_content_length)
return episodes
def retrieve_relevant_memories(self, relevance_target:str, top_k=20) -> list:
relevant = self.semantic_memory.retrieve_relevant(relevance_target, top_k=top_k)
return relevant
def retrieve_relevant_memories_for_current_context(self, top_k=7) -> list:
# current context is composed of th recent memories, plus context, goals, attention, and emotions
context = self._mental_state["context"]
goals = self._mental_state["goals"]
attention = self._mental_state["attention"]
emotions = self._mental_state["emotions"]
recent_memories = "\n".join([f" - {m['content']}" for m in self.retrieve_memories(first_n=10, last_n=20, max_content_length=500)])
# put everything together in a nice markdown string to fetch relevant memories
target = f"""
Current Context: {context}
Current Goals: {goals}
Current Attention: {attention}
Current Emotions: {emotions}
Selected Episodic Memories (from oldest to newest):
{recent_memories}
"""
logger.debug(f"Retrieving relevant memories for contextual target: {target}")
return self.retrieve_relevant_memories(target, top_k=top_k)
def summarize_relevant_memories_via_full_scan(self, relevance_target:str, item_type: str = None) -> str:
"""
Summarizes relevant memories for a given target by scanning the entire semantic memory.
Args:
relevance_target (str): The target to retrieve relevant memories for.
item_type (str, optional): The type of items to summarize. Defaults to None.
max_summary_length (int, optional): The maximum length of the summary. Defaults to 1000.
Returns:
str: The summary of relevant memories.
"""
return self.semantic_memory.summarize_relevant_via_full_scan(relevance_target, item_type=item_type)
###########################################################
# Inspection conveniences
###########################################################
def last_remembered_action(self, ignore_done:bool=True):
"""
Returns the last remembered action.
Args:
ignore_done (bool): Whether to ignore the "DONE" action or not. Defaults to True.
"""
action = None
memory_items_list = self.episodic_memory.retrieve_last(include_omission_info=False, item_type="action")
if len(memory_items_list) > 0:
# iterate from last to first while the action type is not "DONE"
for candidate_item in memory_items_list[::-1]:
if candidate_item["content"]["action"]["type"] != "DONE":
action = candidate_item["content"]["action"]
break
else:
if ignore_done:
continue
else:
action = candidate_item["content"]["action"]
break
return action
###########################################################
# Communication display and action execution
###########################################################
def _display_communication(
self,
role,
content,
kind,
simplified=True,
max_content_length=default["max_content_display_length"],
):
"""
Displays the current communication and stores it in a buffer for later use.
"""
# CONCURRENT PROTECTION, as we'll access shared display buffers
with concurrent_agent_action_lock:
if kind == "stimuli":
rendering = self._pretty_stimuli(
role=role,
content=content,
simplified=simplified,
max_content_length=max_content_length,
)
source = content["stimuli"][0].get("source", None)
target = self.name
elif kind == "action":
rendering = self._pretty_action(
role=role,
content=content,
simplified=simplified,
max_content_length=max_content_length,
)
source = self.name
target = content["action"].get("target", None)
else:
raise ValueError(f"Unknown communication kind: {kind}")
# if the agent has no parent environment, then it is a free agent and we can display the communication.
# otherwise, the environment will display the communication instead. This is important to make sure that
# the communication is displayed in the correct order, since environments control the flow of their underlying
# agents.
if self.environment is None:
self._push_and_display_latest_communication({"kind": kind, "rendering":rendering, "content": content, "source":source, "target": target})
else:
self.environment._push_and_display_latest_communication({"kind": kind, "rendering":rendering, "content": content, "source":source, "target": target})
def _push_and_display_latest_communication(self, communication):
"""
Pushes the latest communications to the agent's buffer.
"""
self._displayed_communications_buffer.append(communication)
print(communication["rendering"])
def pop_and_display_latest_communications(self):
"""
Pops the latest communications and displays them.
"""
communications = self._displayed_communications_buffer
self._displayed_communications_buffer = []
for communication in communications:
print(communication["rendering"])
return communications
def clear_communications_buffer(self):
"""
Cleans the communications buffer.
"""
self._displayed_communications_buffer = []
@transactional()
def pop_latest_actions(self) -> list:
"""
Returns the latest actions performed by this agent. Typically used
by an environment to consume the actions and provide the appropriate
environmental semantics to them (i.e., effects on other agents).
"""
actions = self._actions_buffer
self._actions_buffer = []
return actions
@transactional()
def pop_actions_and_get_contents_for(
self, action_type: str, only_last_action: bool = True
) -> list:
"""
Returns the contents of actions of a given type performed by this agent.
Typically used to perform inspections and tests.
Args:
action_type (str): The type of action to look for.
only_last_action (bool, optional): Whether to only return the contents of the last action. Defaults to False.
"""
actions = self.pop_latest_actions()
# Filter the actions by type
actions = [action for action in actions if action["type"] == action_type]
# If interested only in the last action, return the latest one
if only_last_action:
return actions[-1].get("content", "")
# Otherwise, return all contents from the filtered actions
return "\n".join([action.get("content", "") for action in actions])
#############################################################################################
# Formatting conveniences
#
# For rich colors,
# see: https://rich.readthedocs.io/en/latest/appendix/colors.html#appendix-colors
#############################################################################################
def __repr__(self):
return f"TinyPerson(name='{self.name}')"
@transactional()
def minibio(self, extended=True, requirements=None):
"""
Returns a mini-biography of the TinyPerson.
Args:
extended (bool): Whether to include extended information or not.
requirements (str): Additional requirements for the biography (e.g., focus on a specific aspect relevant for the scenario).
Returns:
str: The mini-biography.
"""
# if occupation is a dict and has a "title" key, use that as the occupation
if isinstance(self._persona['occupation'], dict) and 'title' in self._persona['occupation']:
occupation = self._persona['occupation']['title']
else:
occupation = self._persona['occupation']
base_biography = f"{self.name} is a {self._persona['age']} year old {occupation}, {self._persona['nationality']}, currently living in {self._persona['residence']}."
if self._extended_agent_summary is None and extended:
logger.debug(f"Generating extended agent summary for {self.name}.")
self._extended_agent_summary = LLMChat(
system_prompt=f"""
You are given a short biography of an agent, as well as a detailed specification of his or her other characteristics
You must then produce a short paragraph (3 or 4 sentences) that **complements** the short biography, adding details about
personality, interests, opinions, skills, etc. Do not repeat the information already given in the short biography.
repeating the information already given. The paragraph should be coherent, consistent and comprehensive. All information
must be grounded on the specification, **do not** create anything new.
{"Additional constraints: "+ requirements if requirements is not None else ""}
""",
user_prompt=f"""
**Short biography:** {base_biography}
**Detailed specification:** {self._persona}
""").call()
if extended:
biography = f"{base_biography} {self._extended_agent_summary}"
else:
biography = base_biography
return biography
def pp_current_interactions(
self,
simplified=True,
skip_system=True,
max_content_length=default["max_content_display_length"],
first_n=None,
last_n=None,
include_omission_info:bool=True
):
"""
Pretty prints the current messages.
"""
print(
self.pretty_current_interactions(
simplified=simplified,
skip_system=skip_system,
max_content_length=max_content_length,
first_n=first_n,
last_n=last_n,
include_omission_info=include_omission_info
)
)
def pp_last_interactions(
self,
n=3,
simplified=True,
skip_system=True,
max_content_length=default["max_content_display_length"],
include_omission_info:bool=True
):
"""
Pretty prints the last n messages. Useful to examine the conclusion of an experiment.
"""
print(
self.pretty_current_interactions(
simplified=simplified,
skip_system=skip_system,
max_content_length=max_content_length,
first_n=None,
last_n=n,
include_omission_info=include_omission_info
)
)
def pretty_current_interactions(self, simplified=True, skip_system=True, max_content_length=default["max_content_display_length"], first_n=None, last_n=None, include_omission_info:bool=True):
"""
Returns a pretty, readable, string with the current messages.
"""
lines = [f"**** BEGIN SIMULATION TRAJECTORY FOR {self.name} ****"]
last_step = 0
for i, message in enumerate(self.episodic_memory.retrieve(first_n=first_n, last_n=last_n, include_omission_info=include_omission_info)):
try:
if not (skip_system and message['role'] == 'system'):
msg_simplified_type = ""
msg_simplified_content = ""
msg_simplified_actor = ""
last_step = i
lines.append(f"Agent simulation trajectory event #{i}:")
lines.append(self._pretty_timestamp(message['role'], message['simulation_timestamp']))
if message["role"] == "system":
msg_simplified_actor = "SYSTEM"
msg_simplified_type = message["role"]
msg_simplified_content = message["content"]
lines.append(
f"[dim] {msg_simplified_type}: {msg_simplified_content}[/]"
)
elif message["role"] == "user":
lines.append(
self._pretty_stimuli(
role=message["role"],
content=message["content"],
simplified=simplified,
max_content_length=max_content_length,
)
)
elif message["role"] == "assistant":
lines.append(
self._pretty_action(
role=message["role"],
content=message["content"],
simplified=simplified,
max_content_length=max_content_length,
)
)
else:
lines.append(f"{message['role']}: {message['content']}")
except:
# print(f"ERROR: {message}")
continue
lines.append(f"The last agent simulation trajectory event number was {last_step}, thus the current number of the NEXT POTENTIAL TRAJECTORY EVENT is {last_step + 1}.")
lines.append(f"**** END SIMULATION TRAJECTORY FOR {self.name} ****\n\n")
return "\n".join(lines)
def _pretty_stimuli(
self,
role,
content,
simplified=True,
max_content_length=default["max_content_display_length"],
) -> list:
"""
Pretty prints stimuli.
"""
lines = []
msg_simplified_actor = "USER"
for stimus in content["stimuli"]:
if simplified:
if stimus["source"] != "":
msg_simplified_actor = stimus["source"]
else:
msg_simplified_actor = "USER"
msg_simplified_type = stimus["type"]
msg_simplified_content = utils.break_text_at_length(
stimus["content"], max_length=max_content_length
)
indent = " " * len(msg_simplified_actor) + " > "
msg_simplified_content = textwrap.fill(
msg_simplified_content,
width=TinyPerson.PP_TEXT_WIDTH,
initial_indent=indent,
subsequent_indent=indent,
)
#
# Using rich for formatting. Let's make things as readable as possible!
#
rich_style = utils.RichTextStyle.get_style_for("stimulus", msg_simplified_type)
lines.append(
f"[{rich_style}][underline]{msg_simplified_actor}[/] --> [{rich_style}][underline]{self.name}[/]: [{msg_simplified_type}] \n{msg_simplified_content}[/]"
)
else:
lines.append(f"{role}: {content}")
return "\n".join(lines)
def _pretty_action(
self,
role,
content,
simplified=True,
max_content_length=default["max_content_display_length"],
) -> str:
"""
Pretty prints an action.
"""
if simplified:
msg_simplified_actor = self.name
msg_simplified_type = content["action"]["type"]
msg_simplified_content = utils.break_text_at_length(
content["action"].get("content", ""), max_length=max_content_length
)
indent = " " * len(msg_simplified_actor) + " > "
msg_simplified_content = textwrap.fill(
msg_simplified_content,
width=TinyPerson.PP_TEXT_WIDTH,
initial_indent=indent,
subsequent_indent=indent,
)
#
# Using rich for formatting. Let's make things as readable as possible!
#
rich_style = utils.RichTextStyle.get_style_for("action", msg_simplified_type)
return f"[{rich_style}][underline]{msg_simplified_actor}[/] acts: [{msg_simplified_type}] \n{msg_simplified_content}[/]"
else:
return f"{role}: {content}"
def _pretty_timestamp(
self,
role,
timestamp,
) -> str:
"""
Pretty prints a timestamp.
"""
return f">>>>>>>>> Date and time of events: {timestamp}"
def iso_datetime(self) -> str:
"""
Returns the current datetime of the environment, if any.
Returns:
datetime: The current datetime of the environment in ISO forat.
"""
if self.environment is not None and self.environment.current_datetime is not None:
return self.environment.current_datetime.isoformat()
else:
return None
###########################################################
# IO
###########################################################
def save_specification(self, path, include_mental_faculties=True, include_memory=False, include_mental_state=False):
"""
Saves the current configuration to a JSON file.
"""
suppress_attributes = []
# should we include the mental faculties?
if not include_mental_faculties:
suppress_attributes.append("_mental_faculties")
# should we include the memory?
if not include_memory:
suppress_attributes.append("episodic_memory")
suppress_attributes.append("semantic_memory")
# should we include the mental state?
if not include_mental_state:
suppress_attributes.append("_mental_state")
self.to_json(suppress=suppress_attributes, file_path=path,
serialization_type_field_name="type")
@staticmethod
def load_specification(path_or_dict, suppress_mental_faculties=False, suppress_memory=False, suppress_mental_state=False,
auto_rename_agent=False, new_agent_name=None):
"""
Loads a JSON agent specification.
Args:
path_or_dict (str or dict): The path to the JSON file or the dictionary itself.
suppress_mental_faculties (bool, optional): Whether to suppress loading the mental faculties. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_mental_state (bool, optional): Whether to suppress loading the mental state. Defaults to False.
auto_rename_agent (bool, optional): Whether to auto rename the agent. Defaults to False.
new_agent_name (str, optional): The new name for the agent. Defaults to None.
"""
suppress_attributes = []
# should we suppress the mental faculties?
if suppress_mental_faculties:
suppress_attributes.append("_mental_faculties")
# should we suppress the memory?
if suppress_memory:
suppress_attributes.append("episodic_memory")
suppress_attributes.append("semantic_memory")
# should we suppress the mental state?
if suppress_mental_state:
suppress_attributes.append("_mental_state")
return TinyPerson.from_json(json_dict_or_path=path_or_dict, suppress=suppress_attributes,
serialization_type_field_name="type",
post_init_params={"auto_rename_agent": auto_rename_agent, "new_agent_name": new_agent_name})
@staticmethod
def load_specifications_from_folder(folder_path:str, file_suffix=".agent.json", suppress_mental_faculties=False,
suppress_memory=False, suppress_mental_state=False, auto_rename_agent=False,
new_agent_name=None) -> list:
"""
Loads all JSON agent specifications from a folder.
Args:
folder_path (str): The path to the folder containing the JSON files.
file_suffix (str, optional): The suffix of the JSON files. Defaults to ".agent.json".
suppress_mental_faculties (bool, optional): Whether to suppress loading the mental faculties. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_mental_state (bool, optional): Whether to suppress loading the mental state. Defaults to False.
auto_rename_agent (bool, optional): Whether to auto rename the agent. Defaults to False.
new_agent_name (str, optional): The new name for the agent. Defaults to None.
"""
agents = []
for file in os.listdir(folder_path):
if file.endswith(file_suffix):
file_path = os.path.join(folder_path, file)
agent = TinyPerson.load_specification(file_path, suppress_mental_faculties=suppress_mental_faculties,
suppress_memory=suppress_memory, suppress_mental_state=suppress_mental_state,
auto_rename_agent=auto_rename_agent, new_agent_name=new_agent_name)
agents.append(agent)
return agents
def encode_complete_state(self) -> dict:
"""
Encodes the complete state of the TinyPerson, including the current messages, accessible agents, etc.
This is meant for serialization and caching purposes, not for exporting the state to the user.
"""
to_copy = copy.copy(self.__dict__)
# delete the logger and other attributes that cannot be serialized
del to_copy["environment"]
del to_copy["_mental_faculties"]
del to_copy["action_generator"]
to_copy["_accessible_agents"] = [agent.name for agent in self._accessible_agents]
to_copy['episodic_memory'] = self.episodic_memory.to_json()
to_copy['semantic_memory'] = self.semantic_memory.to_json()
to_copy["_mental_faculties"] = [faculty.to_json() for faculty in self._mental_faculties]
state = copy.deepcopy(to_copy)
return state
def decode_complete_state(self, state: dict) -> Self:
"""
Loads the complete state of the TinyPerson, including the current messages,
and produces a new TinyPerson instance.
"""
state = copy.deepcopy(state)
self._accessible_agents = [TinyPerson.get_agent_by_name(name) for name in state["_accessible_agents"]]
self.episodic_memory = EpisodicMemory.from_json(state['episodic_memory'])
self.semantic_memory = SemanticMemory.from_json(state['semantic_memory'])
for i, faculty in enumerate(self._mental_faculties):
faculty = faculty.from_json(state['_mental_faculties'][i])
# delete fields already present in the state
del state["_accessible_agents"]
del state['episodic_memory']
del state['semantic_memory']
del state['_mental_faculties']
# restore other fields
self.__dict__.update(state)
return self
def create_new_agent_from_current_spec(self, new_name:str) -> Self:
"""
Creates a new agent from the current agent's specification.
Args:
new_name (str): The name of the new agent. Agent names must be unique in the simulation,
this is why we need to provide a new name.
"""
new_agent = TinyPerson(name=new_name, spec_path=None)
new_persona = copy.deepcopy(self._persona)
new_persona['name'] = new_name
new_agent._persona = new_persona
return new_agent
@staticmethod
def add_agent(agent):
"""
Adds an agent to the global list of agents. Agent names must be unique,
so this method will raise an exception if the name is already in use.
"""
if agent.name in TinyPerson.all_agents:
raise ValueError(f"Agent name {agent.name} is already in use.")
else:
TinyPerson.all_agents[agent.name] = agent
@staticmethod
def has_agent(agent_name: str):
"""
Checks if an agent is already registered.
"""
return agent_name in TinyPerson.all_agents
@staticmethod
def set_simulation_for_free_agents(simulation):
"""
Sets the simulation if it is None. This allows free agents to be captured by specific simulation scopes
if desired.
"""
for agent in TinyPerson.all_agents.values():
if agent.simulation_id is None:
simulation.add_agent(agent)
@staticmethod
def get_agent_by_name(name):
"""
Gets an agent by name.
"""
if name in TinyPerson.all_agents:
return TinyPerson.all_agents[name]
else:
return None
@staticmethod
def all_agents_names():
"""
Returns the names of all agents.
"""
return list(TinyPerson.all_agents.keys())
@staticmethod
def clear_agents():
"""
Clears the global list of agents.
"""
TinyPerson.all_agents = {}</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="tinytroupe.utils.json.JsonSerializableRegistry" href="../utils/json.html#tinytroupe.utils.json.JsonSerializableRegistry">JsonSerializableRegistry</a></li>
</ul>
<h3>Class variables</h3>
<dl>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.MAX_ACTIONS_BEFORE_DONE"><code class="name">var <span class="ident">MAX_ACTIONS_BEFORE_DONE</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.MAX_ACTION_SIMILARITY"><code class="name">var <span class="ident">MAX_ACTION_SIMILARITY</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.MAX_EPISODE_LENGTH"><code class="name">var <span class="ident">MAX_EPISODE_LENGTH</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.MIN_EPISODE_LENGTH"><code class="name">var <span class="ident">MIN_EPISODE_LENGTH</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.PP_TEXT_WIDTH"><code class="name">var <span class="ident">PP_TEXT_WIDTH</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.all_agents"><code class="name">var <span class="ident">all_agents</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.communication_display"><code class="name">var <span class="ident">communication_display</span> : bool</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.serializable_attributes"><code class="name">var <span class="ident">serializable_attributes</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.serializable_attributes_renaming"><code class="name">var <span class="ident">serializable_attributes_renaming</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
<h3>Static methods</h3>
<dl>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.add_agent"><code class="name flex">
<span>def <span class="ident">add_agent</span></span>(<span>agent)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds an agent to the global list of agents. Agent names must be unique,
so this method will raise an exception if the name is already in use.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def add_agent(agent):
"""
Adds an agent to the global list of agents. Agent names must be unique,
so this method will raise an exception if the name is already in use.
"""
if agent.name in TinyPerson.all_agents:
raise ValueError(f"Agent name {agent.name} is already in use.")
else:
TinyPerson.all_agents[agent.name] = agent</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.all_agents_names"><code class="name flex">
<span>def <span class="ident">all_agents_names</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the names of all agents.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def all_agents_names():
"""
Returns the names of all agents.
"""
return list(TinyPerson.all_agents.keys())</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.clear_agents"><code class="name flex">
<span>def <span class="ident">clear_agents</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Clears the global list of agents.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def clear_agents():
"""
Clears the global list of agents.
"""
TinyPerson.all_agents = {}</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.get_agent_by_name"><code class="name flex">
<span>def <span class="ident">get_agent_by_name</span></span>(<span>name)</span>
</code></dt>
<dd>
<div class="desc"><p>Gets an agent by name.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def get_agent_by_name(name):
"""
Gets an agent by name.
"""
if name in TinyPerson.all_agents:
return TinyPerson.all_agents[name]
else:
return None</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.has_agent"><code class="name flex">
<span>def <span class="ident">has_agent</span></span>(<span>agent_name: str)</span>
</code></dt>
<dd>
<div class="desc"><p>Checks if an agent is already registered.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def has_agent(agent_name: str):
"""
Checks if an agent is already registered.
"""
return agent_name in TinyPerson.all_agents</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.load_specification"><code class="name flex">
<span>def <span class="ident">load_specification</span></span>(<span>path_or_dict, suppress_mental_faculties=False, suppress_memory=False, suppress_mental_state=False, auto_rename_agent=False, new_agent_name=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Loads a JSON agent specification.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>path_or_dict</code></strong> : <code>str</code> or <code>dict</code></dt>
<dd>The path to the JSON file or the dictionary itself.</dd>
<dt><strong><code>suppress_mental_faculties</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the mental faculties. Defaults to False.</dd>
<dt><strong><code>suppress_memory</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the memory. Defaults to False.</dd>
<dt><strong><code>suppress_memory</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the memory. Defaults to False.</dd>
<dt><strong><code>suppress_mental_state</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the mental state. Defaults to False.</dd>
<dt><strong><code>auto_rename_agent</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to auto rename the agent. Defaults to False.</dd>
<dt><strong><code>new_agent_name</code></strong> : <code>str</code>, optional</dt>
<dd>The new name for the agent. Defaults to None.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def load_specification(path_or_dict, suppress_mental_faculties=False, suppress_memory=False, suppress_mental_state=False,
auto_rename_agent=False, new_agent_name=None):
"""
Loads a JSON agent specification.
Args:
path_or_dict (str or dict): The path to the JSON file or the dictionary itself.
suppress_mental_faculties (bool, optional): Whether to suppress loading the mental faculties. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_mental_state (bool, optional): Whether to suppress loading the mental state. Defaults to False.
auto_rename_agent (bool, optional): Whether to auto rename the agent. Defaults to False.
new_agent_name (str, optional): The new name for the agent. Defaults to None.
"""
suppress_attributes = []
# should we suppress the mental faculties?
if suppress_mental_faculties:
suppress_attributes.append("_mental_faculties")
# should we suppress the memory?
if suppress_memory:
suppress_attributes.append("episodic_memory")
suppress_attributes.append("semantic_memory")
# should we suppress the mental state?
if suppress_mental_state:
suppress_attributes.append("_mental_state")
return TinyPerson.from_json(json_dict_or_path=path_or_dict, suppress=suppress_attributes,
serialization_type_field_name="type",
post_init_params={"auto_rename_agent": auto_rename_agent, "new_agent_name": new_agent_name})</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.load_specifications_from_folder"><code class="name flex">
<span>def <span class="ident">load_specifications_from_folder</span></span>(<span>folder_path: str, file_suffix='.agent.json', suppress_mental_faculties=False, suppress_memory=False, suppress_mental_state=False, auto_rename_agent=False, new_agent_name=None) ‑> list</span>
</code></dt>
<dd>
<div class="desc"><p>Loads all JSON agent specifications from a folder.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>folder_path</code></strong> : <code>str</code></dt>
<dd>The path to the folder containing the JSON files.</dd>
<dt><strong><code>file_suffix</code></strong> : <code>str</code>, optional</dt>
<dd>The suffix of the JSON files. Defaults to ".agent.json".</dd>
<dt><strong><code>suppress_mental_faculties</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the mental faculties. Defaults to False.</dd>
<dt><strong><code>suppress_memory</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the memory. Defaults to False.</dd>
<dt><strong><code>suppress_mental_state</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to suppress loading the mental state. Defaults to False.</dd>
<dt><strong><code>auto_rename_agent</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to auto rename the agent. Defaults to False.</dd>
<dt><strong><code>new_agent_name</code></strong> : <code>str</code>, optional</dt>
<dd>The new name for the agent. Defaults to None.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def load_specifications_from_folder(folder_path:str, file_suffix=".agent.json", suppress_mental_faculties=False,
suppress_memory=False, suppress_mental_state=False, auto_rename_agent=False,
new_agent_name=None) -> list:
"""
Loads all JSON agent specifications from a folder.
Args:
folder_path (str): The path to the folder containing the JSON files.
file_suffix (str, optional): The suffix of the JSON files. Defaults to ".agent.json".
suppress_mental_faculties (bool, optional): Whether to suppress loading the mental faculties. Defaults to False.
suppress_memory (bool, optional): Whether to suppress loading the memory. Defaults to False.
suppress_mental_state (bool, optional): Whether to suppress loading the mental state. Defaults to False.
auto_rename_agent (bool, optional): Whether to auto rename the agent. Defaults to False.
new_agent_name (str, optional): The new name for the agent. Defaults to None.
"""
agents = []
for file in os.listdir(folder_path):
if file.endswith(file_suffix):
file_path = os.path.join(folder_path, file)
agent = TinyPerson.load_specification(file_path, suppress_mental_faculties=suppress_mental_faculties,
suppress_memory=suppress_memory, suppress_mental_state=suppress_mental_state,
auto_rename_agent=auto_rename_agent, new_agent_name=new_agent_name)
agents.append(agent)
return agents</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.set_simulation_for_free_agents"><code class="name flex">
<span>def <span class="ident">set_simulation_for_free_agents</span></span>(<span>simulation)</span>
</code></dt>
<dd>
<div class="desc"><p>Sets the simulation if it is None. This allows free agents to be captured by specific simulation scopes
if desired.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def set_simulation_for_free_agents(simulation):
"""
Sets the simulation if it is None. This allows free agents to be captured by specific simulation scopes
if desired.
"""
for agent in TinyPerson.all_agents.values():
if agent.simulation_id is None:
simulation.add_agent(agent)</code></pre>
</details>
</dd>
</dl>
<h3>Instance variables</h3>
<dl>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.accessible_agents"><code class="name">var <span class="ident">accessible_agents</span></code></dt>
<dd>
<div class="desc"><p>Property to access the list of accessible agents.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def accessible_agents(self):
"""
Property to access the list of accessible agents.
"""
return self._accessible_agents</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.act"><code class="name flex">
<span>def <span class="ident">act</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.add_mental_faculties"><code class="name flex">
<span>def <span class="ident">add_mental_faculties</span></span>(<span>self, mental_faculties)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds a list of mental faculties to the agent.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_mental_faculties(self, mental_faculties):
"""
Adds a list of mental faculties to the agent.
"""
for faculty in mental_faculties:
self.add_mental_faculty(faculty)
return self</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.add_mental_faculty"><code class="name flex">
<span>def <span class="ident">add_mental_faculty</span></span>(<span>self, faculty)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds a mental faculty to the agent.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_mental_faculty(self, faculty):
"""
Adds a mental faculty to the agent.
"""
# check if the faculty is already there or not
if faculty not in self._mental_faculties:
self._mental_faculties.append(faculty)
else:
raise Exception(f"The mental faculty {faculty} is already present in the agent.")
return self</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.change_context"><code class="name flex">
<span>def <span class="ident">change_context</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.clear_communications_buffer"><code class="name flex">
<span>def <span class="ident">clear_communications_buffer</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Cleans the communications buffer.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def clear_communications_buffer(self):
"""
Cleans the communications buffer.
"""
self._displayed_communications_buffer = []</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.clear_episodic_memory"><code class="name flex">
<span>def <span class="ident">clear_episodic_memory</span></span>(<span>self, max_prefix_to_clear=None, max_suffix_to_clear=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Clears the episodic memory, causing a permanent "episodic amnesia". Note that this does not
change other memories, such as semantic memory.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def clear_episodic_memory(self, max_prefix_to_clear=None, max_suffix_to_clear=None):
"""
Clears the episodic memory, causing a permanent "episodic amnesia". Note that this does not
change other memories, such as semantic memory.
"""
self.episodic_memory.clear(max_prefix_to_clear=max_prefix_to_clear, max_suffix_to_clear=max_suffix_to_clear)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.clear_relationships"><code class="name flex">
<span>def <span class="ident">clear_relationships</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.consolidate_episode_memories"><code class="name flex">
<span>def <span class="ident">consolidate_episode_memories</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Applies all memory consolidation or transformation processes appropriate to the conclusion of one simulation episode.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def consolidate_episode_memories(self):
"""
Applies all memory consolidation or transformation processes appropriate to the conclusion of one simulation episode.
"""
# a minimum length of the episode is required to consolidate it, to avoid excessive fragments in the semantic memory
if self._current_episode_event_count > self.MIN_EPISODE_LENGTH:
logger.debug(f"[{self.name}] ***** Consolidating current episode memories into semantic memory *****")
# Consolidate latest episodic memories into semantic memory
if config_manager.get("enable_memory_consolidation"):
episodic_consolidator = EpisodicConsolidator()
episode = self.episodic_memory.get_current_episode(item_types=["action", "stimulus"],)
logger.debug(f"[{self.name}] Current episode: {episode}")
consolidated_memories = episodic_consolidator.process(episode, timestamp=self._mental_state["datetime"], context=self._mental_state, persona=self.minibio())["consolidation"]
if consolidated_memories is not None:
logger.info(f"[{self.name}] Consolidating current {len(episode)} episodic events as consolidated semantic memories.")
logger.debug(f"[{self.name}] Consolidated memories: {consolidated_memories}")
self.semantic_memory.store_all(consolidated_memories)
else:
logger.debug(f"[{self.name}] No memories to consolidate from the current episode.")
else:
logger.warning(f"[{self.name}] Memory consolidation is disabled. Not consolidating current episode memories into semantic memory.")
# commit the current episode to episodic memory
self.episodic_memory.commit_episode()
self._current_episode_event_count = 0
logger.debug(f"[{self.name}] Current episode event count reset to 0 after consolidation.")
# TODO reflections, optimizations, etc.</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.create_new_agent_from_current_spec"><code class="name flex">
<span>def <span class="ident">create_new_agent_from_current_spec</span></span>(<span>self, new_name: str) ‑> ~Self</span>
</code></dt>
<dd>
<div class="desc"><p>Creates a new agent from the current agent's specification. </p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>new_name</code></strong> : <code>str</code></dt>
<dd>The name of the new agent. Agent names must be unique in the simulation,
this is why we need to provide a new name.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def create_new_agent_from_current_spec(self, new_name:str) -> Self:
"""
Creates a new agent from the current agent's specification.
Args:
new_name (str): The name of the new agent. Agent names must be unique in the simulation,
this is why we need to provide a new name.
"""
new_agent = TinyPerson(name=new_name, spec_path=None)
new_persona = copy.deepcopy(self._persona)
new_persona['name'] = new_name
new_agent._persona = new_persona
return new_agent</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.decode_complete_state"><code class="name flex">
<span>def <span class="ident">decode_complete_state</span></span>(<span>self, state: dict) ‑> ~Self</span>
</code></dt>
<dd>
<div class="desc"><p>Loads the complete state of the TinyPerson, including the current messages,
and produces a new TinyPerson instance.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def decode_complete_state(self, state: dict) -> Self:
"""
Loads the complete state of the TinyPerson, including the current messages,
and produces a new TinyPerson instance.
"""
state = copy.deepcopy(state)
self._accessible_agents = [TinyPerson.get_agent_by_name(name) for name in state["_accessible_agents"]]
self.episodic_memory = EpisodicMemory.from_json(state['episodic_memory'])
self.semantic_memory = SemanticMemory.from_json(state['semantic_memory'])
for i, faculty in enumerate(self._mental_faculties):
faculty = faculty.from_json(state['_mental_faculties'][i])
# delete fields already present in the state
del state["_accessible_agents"]
del state['episodic_memory']
del state['semantic_memory']
del state['_mental_faculties']
# restore other fields
self.__dict__.update(state)
return self</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.define"><code class="name flex">
<span>def <span class="ident">define</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.define_relationships"><code class="name flex">
<span>def <span class="ident">define_relationships</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.encode_complete_state"><code class="name flex">
<span>def <span class="ident">encode_complete_state</span></span>(<span>self) ‑> dict</span>
</code></dt>
<dd>
<div class="desc"><p>Encodes the complete state of the TinyPerson, including the current messages, accessible agents, etc.
This is meant for serialization and caching purposes, not for exporting the state to the user.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def encode_complete_state(self) -> dict:
"""
Encodes the complete state of the TinyPerson, including the current messages, accessible agents, etc.
This is meant for serialization and caching purposes, not for exporting the state to the user.
"""
to_copy = copy.copy(self.__dict__)
# delete the logger and other attributes that cannot be serialized
del to_copy["environment"]
del to_copy["_mental_faculties"]
del to_copy["action_generator"]
to_copy["_accessible_agents"] = [agent.name for agent in self._accessible_agents]
to_copy['episodic_memory'] = self.episodic_memory.to_json()
to_copy['semantic_memory'] = self.semantic_memory.to_json()
to_copy["_mental_faculties"] = [faculty.to_json() for faculty in self._mental_faculties]
state = copy.deepcopy(to_copy)
return state</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.generate_agent_system_prompt"><code class="name flex">
<span>def <span class="ident">generate_agent_system_prompt</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def generate_agent_system_prompt(self):
with open(self._prompt_template_path, "r") as f:
agent_prompt_template = f.read()
# let's operate on top of a copy of the configuration, because we'll need to add more variables, etc.
template_variables = self._persona.copy()
template_variables["persona"] = json.dumps(self._persona.copy(), indent=4)
# add mental state to the template variables
template_variables["mental_state"] = json.dumps(self._mental_state, indent=4)
# Prepare additional action definitions and constraints
actions_definitions_prompt = ""
actions_constraints_prompt = ""
for faculty in self._mental_faculties:
actions_definitions_prompt += f"{faculty.actions_definitions_prompt()}\n"
actions_constraints_prompt += f"{faculty.actions_constraints_prompt()}\n"
# Make the additional prompt pieces available to the template.
# Identation here is to align with the text structure in the template.
template_variables['actions_definitions_prompt'] = textwrap.indent(actions_definitions_prompt.strip(), " ")
template_variables['actions_constraints_prompt'] = textwrap.indent(actions_constraints_prompt.strip(), " ")
# RAI prompt components, if requested
template_variables = utils.add_rai_template_variables_if_enabled(template_variables)
return chevron.render(agent_prompt_template, template_variables)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.get"><code class="name flex">
<span>def <span class="ident">get</span></span>(<span>self, key)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the value of a key in the TinyPerson's persona configuration.
Supports dot notation for nested keys (e.g., "address.city").</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get(self, key):
"""
Returns the value of a key in the TinyPerson's persona configuration.
Supports dot notation for nested keys (e.g., "address.city").
"""
keys = key.split(".")
value = self._persona
for k in keys:
if isinstance(value, dict):
value = value.get(k, None)
else:
return None # If the path is invalid, return None
return value</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.import_fragment"><code class="name flex">
<span>def <span class="ident">import_fragment</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.include_persona_definitions"><code class="name flex">
<span>def <span class="ident">include_persona_definitions</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.internalize_goal"><code class="name flex">
<span>def <span class="ident">internalize_goal</span></span>(<span>self, goal, max_content_length=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Internalizes a goal and updates its internal cognitive state.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@config_manager.config_defaults(max_content_length="max_content_display_length")
def internalize_goal(
self, goal, max_content_length=None
):
"""
Internalizes a goal and updates its internal cognitive state.
"""
return self._observe(
stimulus={
"type": "INTERNAL_GOAL_FORMULATION",
"content": goal,
"source": name_or_empty(self),
},
max_content_length=max_content_length,
)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.iso_datetime"><code class="name flex">
<span>def <span class="ident">iso_datetime</span></span>(<span>self) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the current datetime of the environment, if any.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>datetime</code></dt>
<dd>The current datetime of the environment in ISO forat.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def iso_datetime(self) -> str:
"""
Returns the current datetime of the environment, if any.
Returns:
datetime: The current datetime of the environment in ISO forat.
"""
if self.environment is not None and self.environment.current_datetime is not None:
return self.environment.current_datetime.isoformat()
else:
return None</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.last_remembered_action"><code class="name flex">
<span>def <span class="ident">last_remembered_action</span></span>(<span>self, ignore_done: bool = True)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the last remembered action.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>ignore_done</code></strong> : <code>bool</code></dt>
<dd>Whether to ignore the "DONE" action or not. Defaults to True.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def last_remembered_action(self, ignore_done:bool=True):
"""
Returns the last remembered action.
Args:
ignore_done (bool): Whether to ignore the "DONE" action or not. Defaults to True.
"""
action = None
memory_items_list = self.episodic_memory.retrieve_last(include_omission_info=False, item_type="action")
if len(memory_items_list) > 0:
# iterate from last to first while the action type is not "DONE"
for candidate_item in memory_items_list[::-1]:
if candidate_item["content"]["action"]["type"] != "DONE":
action = candidate_item["content"]["action"]
break
else:
if ignore_done:
continue
else:
action = candidate_item["content"]["action"]
break
return action </code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.listen"><code class="name flex">
<span>def <span class="ident">listen</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.listen_and_act"><code class="name flex">
<span>def <span class="ident">listen_and_act</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.make_agent_accessible"><code class="name flex">
<span>def <span class="ident">make_agent_accessible</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.make_agent_inaccessible"><code class="name flex">
<span>def <span class="ident">make_agent_inaccessible</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.make_agents_accessible"><code class="name flex">
<span>def <span class="ident">make_agents_accessible</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.make_all_agents_inaccessible"><code class="name flex">
<span>def <span class="ident">make_all_agents_inaccessible</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.minibio"><code class="name flex">
<span>def <span class="ident">minibio</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.move_to"><code class="name flex">
<span>def <span class="ident">move_to</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.optimize_memory"><code class="name flex">
<span>def <span class="ident">optimize_memory</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def optimize_memory(self):
pass #TODO</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.pop_actions_and_get_contents_for"><code class="name flex">
<span>def <span class="ident">pop_actions_and_get_contents_for</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.pop_and_display_latest_communications"><code class="name flex">
<span>def <span class="ident">pop_and_display_latest_communications</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Pops the latest communications and displays them.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def pop_and_display_latest_communications(self):
"""
Pops the latest communications and displays them.
"""
communications = self._displayed_communications_buffer
self._displayed_communications_buffer = []
for communication in communications:
print(communication["rendering"])
return communications</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.pop_latest_actions"><code class="name flex">
<span>def <span class="ident">pop_latest_actions</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.pp_current_interactions"><code class="name flex">
<span>def <span class="ident">pp_current_interactions</span></span>(<span>self, simplified=True, skip_system=True, max_content_length=4000, first_n=None, last_n=None, include_omission_info: bool = True)</span>
</code></dt>
<dd>
<div class="desc"><p>Pretty prints the current messages.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def pp_current_interactions(
self,
simplified=True,
skip_system=True,
max_content_length=default["max_content_display_length"],
first_n=None,
last_n=None,
include_omission_info:bool=True
):
"""
Pretty prints the current messages.
"""
print(
self.pretty_current_interactions(
simplified=simplified,
skip_system=skip_system,
max_content_length=max_content_length,
first_n=first_n,
last_n=last_n,
include_omission_info=include_omission_info
)
)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.pp_last_interactions"><code class="name flex">
<span>def <span class="ident">pp_last_interactions</span></span>(<span>self, n=3, simplified=True, skip_system=True, max_content_length=4000, include_omission_info: bool = True)</span>
</code></dt>
<dd>
<div class="desc"><p>Pretty prints the last n messages. Useful to examine the conclusion of an experiment.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def pp_last_interactions(
self,
n=3,
simplified=True,
skip_system=True,
max_content_length=default["max_content_display_length"],
include_omission_info:bool=True
):
"""
Pretty prints the last n messages. Useful to examine the conclusion of an experiment.
"""
print(
self.pretty_current_interactions(
simplified=simplified,
skip_system=skip_system,
max_content_length=max_content_length,
first_n=None,
last_n=n,
include_omission_info=include_omission_info
)
)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.pretty_current_interactions"><code class="name flex">
<span>def <span class="ident">pretty_current_interactions</span></span>(<span>self, simplified=True, skip_system=True, max_content_length=4000, first_n=None, last_n=None, include_omission_info: bool = True)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns a pretty, readable, string with the current messages.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def pretty_current_interactions(self, simplified=True, skip_system=True, max_content_length=default["max_content_display_length"], first_n=None, last_n=None, include_omission_info:bool=True):
"""
Returns a pretty, readable, string with the current messages.
"""
lines = [f"**** BEGIN SIMULATION TRAJECTORY FOR {self.name} ****"]
last_step = 0
for i, message in enumerate(self.episodic_memory.retrieve(first_n=first_n, last_n=last_n, include_omission_info=include_omission_info)):
try:
if not (skip_system and message['role'] == 'system'):
msg_simplified_type = ""
msg_simplified_content = ""
msg_simplified_actor = ""
last_step = i
lines.append(f"Agent simulation trajectory event #{i}:")
lines.append(self._pretty_timestamp(message['role'], message['simulation_timestamp']))
if message["role"] == "system":
msg_simplified_actor = "SYSTEM"
msg_simplified_type = message["role"]
msg_simplified_content = message["content"]
lines.append(
f"[dim] {msg_simplified_type}: {msg_simplified_content}[/]"
)
elif message["role"] == "user":
lines.append(
self._pretty_stimuli(
role=message["role"],
content=message["content"],
simplified=simplified,
max_content_length=max_content_length,
)
)
elif message["role"] == "assistant":
lines.append(
self._pretty_action(
role=message["role"],
content=message["content"],
simplified=simplified,
max_content_length=max_content_length,
)
)
else:
lines.append(f"{message['role']}: {message['content']}")
except:
# print(f"ERROR: {message}")
continue
lines.append(f"The last agent simulation trajectory event number was {last_step}, thus the current number of the NEXT POTENTIAL TRAJECTORY EVENT is {last_step + 1}.")
lines.append(f"**** END SIMULATION TRAJECTORY FOR {self.name} ****\n\n")
return "\n".join(lines)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.read_document_from_file"><code class="name flex">
<span>def <span class="ident">read_document_from_file</span></span>(<span>self, file_path: str)</span>
</code></dt>
<dd>
<div class="desc"><p>Reads a document from a file and loads it into the semantic memory.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def read_document_from_file(self, file_path:str):
"""
Reads a document from a file and loads it into the semantic memory.
"""
logger.info(f"Reading document from file: {file_path}")
self.semantic_memory.add_document_path(file_path)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.read_document_from_web"><code class="name flex">
<span>def <span class="ident">read_document_from_web</span></span>(<span>self, web_url: str)</span>
</code></dt>
<dd>
<div class="desc"><p>Reads a document from a web URL and loads it into the semantic memory.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def read_document_from_web(self, web_url:str):
"""
Reads a document from a web URL and loads it into the semantic memory.
"""
logger.info(f"Reading document from web URL: {web_url}")
self.semantic_memory.add_web_url(web_url)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.read_documents_from_folder"><code class="name flex">
<span>def <span class="ident">read_documents_from_folder</span></span>(<span>self, documents_path: str)</span>
</code></dt>
<dd>
<div class="desc"><p>Reads documents from a directory and loads them into the semantic memory.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def read_documents_from_folder(self, documents_path:str):
"""
Reads documents from a directory and loads them into the semantic memory.
"""
logger.info(f"Setting documents path to {documents_path} and loading documents.")
self.semantic_memory.add_documents_path(documents_path)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.read_documents_from_web"><code class="name flex">
<span>def <span class="ident">read_documents_from_web</span></span>(<span>self, web_urls: list)</span>
</code></dt>
<dd>
<div class="desc"><p>Reads documents from web URLs and loads them into the semantic memory.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def read_documents_from_web(self, web_urls:list):
"""
Reads documents from web URLs and loads them into the semantic memory.
"""
logger.info(f"Reading documents from the following web URLs: {web_urls}")
self.semantic_memory.add_web_urls(web_urls)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.related_to"><code class="name flex">
<span>def <span class="ident">related_to</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.reset_prompt"><code class="name flex">
<span>def <span class="ident">reset_prompt</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def reset_prompt(self):
# render the template with the current configuration
self._init_system_message = self.generate_agent_system_prompt()
# - reset system message
# - make it clear that the provided events are past events and have already had their effects
self.current_messages = [
{"role": "system", "content": self._init_system_message},
{"role": "system", "content": "The next messages refer to past interactions you had recently and are meant to help you contextualize your next actions. "\
+ "They are the most recent episodic memories you have, including stimuli and actions. "\
+ "Their effects already took place and led to your present cognitive state (described above), so you can use them in conjunction "\
+ "with your cognitive state to inform your next actions and perceptions. Please consider them and then proceed with your next actions right after. "}
]
# sets up the actual interaction messages to use for prompting
self.current_messages += self.retrieve_recent_memories()</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.retrieve_memories"><code class="name flex">
<span>def <span class="ident">retrieve_memories</span></span>(<span>self, first_n: int, last_n: int, include_omission_info: bool = True, max_content_length: int = None) ‑> list</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def retrieve_memories(self, first_n: int, last_n: int, include_omission_info:bool=True, max_content_length:int=None) -> list:
episodes = self.episodic_memory.retrieve(first_n=first_n, last_n=last_n, include_omission_info=include_omission_info)
if max_content_length is not None:
episodes = utils.truncate_actions_or_stimuli(episodes, max_content_length)
return episodes</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.retrieve_recent_memories"><code class="name flex">
<span>def <span class="ident">retrieve_recent_memories</span></span>(<span>self, max_content_length: int = None) ‑> list</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def retrieve_recent_memories(self, max_content_length:int=None) -> list:
episodes = self.episodic_memory.retrieve_recent()
if max_content_length is not None:
episodes = utils.truncate_actions_or_stimuli(episodes, max_content_length)
return episodes</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.retrieve_relevant_memories"><code class="name flex">
<span>def <span class="ident">retrieve_relevant_memories</span></span>(<span>self, relevance_target: str, top_k=20) ‑> list</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def retrieve_relevant_memories(self, relevance_target:str, top_k=20) -> list:
relevant = self.semantic_memory.retrieve_relevant(relevance_target, top_k=top_k)
return relevant</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.retrieve_relevant_memories_for_current_context"><code class="name flex">
<span>def <span class="ident">retrieve_relevant_memories_for_current_context</span></span>(<span>self, top_k=7) ‑> list</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def retrieve_relevant_memories_for_current_context(self, top_k=7) -> list:
# current context is composed of th recent memories, plus context, goals, attention, and emotions
context = self._mental_state["context"]
goals = self._mental_state["goals"]
attention = self._mental_state["attention"]
emotions = self._mental_state["emotions"]
recent_memories = "\n".join([f" - {m['content']}" for m in self.retrieve_memories(first_n=10, last_n=20, max_content_length=500)])
# put everything together in a nice markdown string to fetch relevant memories
target = f"""
Current Context: {context}
Current Goals: {goals}
Current Attention: {attention}
Current Emotions: {emotions}
Selected Episodic Memories (from oldest to newest):
{recent_memories}
"""
logger.debug(f"Retrieving relevant memories for contextual target: {target}")
return self.retrieve_relevant_memories(target, top_k=top_k)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.save_specification"><code class="name flex">
<span>def <span class="ident">save_specification</span></span>(<span>self, path, include_mental_faculties=True, include_memory=False, include_mental_state=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Saves the current configuration to a JSON file.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def save_specification(self, path, include_mental_faculties=True, include_memory=False, include_mental_state=False):
"""
Saves the current configuration to a JSON file.
"""
suppress_attributes = []
# should we include the mental faculties?
if not include_mental_faculties:
suppress_attributes.append("_mental_faculties")
# should we include the memory?
if not include_memory:
suppress_attributes.append("episodic_memory")
suppress_attributes.append("semantic_memory")
# should we include the mental state?
if not include_mental_state:
suppress_attributes.append("_mental_state")
self.to_json(suppress=suppress_attributes, file_path=path,
serialization_type_field_name="type")</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.see"><code class="name flex">
<span>def <span class="ident">see</span></span>(<span>self, visual_description, source: Union[~Self, ForwardRef('TinyWorld')] = None, max_content_length=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Perceives a visual stimulus through a description and updates its internal cognitive state.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>visual_description</code></strong> : <code>str</code></dt>
<dd>The description of the visual stimulus.</dd>
<dt><strong><code>source</code></strong> : <code>AgentOrWorld</code>, optional</dt>
<dd>The source of the visual stimulus. Defaults to None.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@config_manager.config_defaults(max_content_length="max_content_display_length")
def see(
self,
visual_description,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Perceives a visual stimulus through a description and updates its internal cognitive state.
Args:
visual_description (str): The description of the visual stimulus.
source (AgentOrWorld, optional): The source of the visual stimulus. Defaults to None.
"""
return self._observe(
stimulus={
"type": "VISUAL",
"content": visual_description,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.see_and_act"><code class="name flex">
<span>def <span class="ident">see_and_act</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.socialize"><code class="name flex">
<span>def <span class="ident">socialize</span></span>(<span>self, social_description: str, source: Union[~Self, ForwardRef('TinyWorld')] = None, max_content_length=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Perceives a social stimulus through a description and updates its internal cognitive state.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>social_description</code></strong> : <code>str</code></dt>
<dd>The description of the social stimulus.</dd>
<dt><strong><code>source</code></strong> : <code>AgentOrWorld</code>, optional</dt>
<dd>The source of the social stimulus. Defaults to None.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@config_manager.config_defaults(max_content_length="max_content_display_length")
def socialize(
self,
social_description: str,
source: AgentOrWorld = None,
max_content_length=None,
):
"""
Perceives a social stimulus through a description and updates its internal cognitive state.
Args:
social_description (str): The description of the social stimulus.
source (AgentOrWorld, optional): The source of the social stimulus. Defaults to None.
"""
return self._observe(
stimulus={
"type": "SOCIAL",
"content": social_description,
"source": name_or_empty(source),
},
max_content_length=max_content_length,
)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.store_in_memory"><code class="name flex">
<span>def <span class="ident">store_in_memory</span></span>(<span>self, value: Any) ‑> list</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def store_in_memory(self, value: Any) -> list:
self.episodic_memory.store(value)
self._current_episode_event_count += 1
logger.debug(f"[{self.name}] Current episode event count: {self._current_episode_event_count}.")
if self._current_episode_event_count >= self.MAX_EPISODE_LENGTH:
# commit the current episode to memory, if it is long enough
logger.warning(f"[{self.name}] Episode length exceeded {self.MAX_EPISODE_LENGTH} events. Committing episode to memory. Please check whether this was expected or not.")
self.consolidate_episode_memories()</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.summarize_relevant_memories_via_full_scan"><code class="name flex">
<span>def <span class="ident">summarize_relevant_memories_via_full_scan</span></span>(<span>self, relevance_target: str, item_type: str = None) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Summarizes relevant memories for a given target by scanning the entire semantic memory.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>relevance_target</code></strong> : <code>str</code></dt>
<dd>The target to retrieve relevant memories for.</dd>
<dt><strong><code>item_type</code></strong> : <code>str</code>, optional</dt>
<dd>The type of items to summarize. Defaults to None.</dd>
<dt><strong><code>max_summary_length</code></strong> : <code>int</code>, optional</dt>
<dd>The maximum length of the summary. Defaults to 1000.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The summary of relevant memories.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def summarize_relevant_memories_via_full_scan(self, relevance_target:str, item_type: str = None) -> str:
"""
Summarizes relevant memories for a given target by scanning the entire semantic memory.
Args:
relevance_target (str): The target to retrieve relevant memories for.
item_type (str, optional): The type of items to summarize. Defaults to None.
max_summary_length (int, optional): The maximum length of the summary. Defaults to 1000.
Returns:
str: The summary of relevant memories.
"""
return self.semantic_memory.summarize_relevant_via_full_scan(relevance_target, item_type=item_type)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.think"><code class="name flex">
<span>def <span class="ident">think</span></span>(<span>self, thought, max_content_length=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Forces the agent to think about something and updates its internal cognitive state.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@config_manager.config_defaults(max_content_length="max_content_display_length")
def think(self, thought, max_content_length=None):
"""
Forces the agent to think about something and updates its internal cognitive state.
"""
return self._observe(
stimulus={
"type": "THOUGHT",
"content": thought,
"source": name_or_empty(self),
},
max_content_length=max_content_length,
)</code></pre>
</details>
</dd>
<dt id="tinytroupe.agent.tiny_person.TinyPerson.think_and_act"><code class="name flex">
<span>def <span class="ident">think_and_act</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result</code></pre>
</details>
</dd>
</dl>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="tinytroupe.utils.json.JsonSerializableRegistry" href="../utils/json.html#tinytroupe.utils.json.JsonSerializableRegistry">JsonSerializableRegistry</a></b></code>:
<ul class="hlist">
<li><code><a title="tinytroupe.utils.json.JsonSerializableRegistry.from_json" href="../utils/json.html#tinytroupe.utils.json.JsonSerializableRegistry.from_json">from_json</a></code></li>
<li><code><a title="tinytroupe.utils.json.JsonSerializableRegistry.to_json" href="../utils/json.html#tinytroupe.utils.json.JsonSerializableRegistry.to_json">to_json</a></code></li>
</ul>
</li>
</ul>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="tinytroupe.agent" href="index.html">tinytroupe.agent</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="tinytroupe.agent.tiny_person.TinyPerson" href="#tinytroupe.agent.tiny_person.TinyPerson">TinyPerson</a></code></h4>
<ul class="">
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.MAX_ACTIONS_BEFORE_DONE" href="#tinytroupe.agent.tiny_person.TinyPerson.MAX_ACTIONS_BEFORE_DONE">MAX_ACTIONS_BEFORE_DONE</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.MAX_ACTION_SIMILARITY" href="#tinytroupe.agent.tiny_person.TinyPerson.MAX_ACTION_SIMILARITY">MAX_ACTION_SIMILARITY</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.MAX_EPISODE_LENGTH" href="#tinytroupe.agent.tiny_person.TinyPerson.MAX_EPISODE_LENGTH">MAX_EPISODE_LENGTH</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.MIN_EPISODE_LENGTH" href="#tinytroupe.agent.tiny_person.TinyPerson.MIN_EPISODE_LENGTH">MIN_EPISODE_LENGTH</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.PP_TEXT_WIDTH" href="#tinytroupe.agent.tiny_person.TinyPerson.PP_TEXT_WIDTH">PP_TEXT_WIDTH</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.accessible_agents" href="#tinytroupe.agent.tiny_person.TinyPerson.accessible_agents">accessible_agents</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.act" href="#tinytroupe.agent.tiny_person.TinyPerson.act">act</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.add_agent" href="#tinytroupe.agent.tiny_person.TinyPerson.add_agent">add_agent</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.add_mental_faculties" href="#tinytroupe.agent.tiny_person.TinyPerson.add_mental_faculties">add_mental_faculties</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.add_mental_faculty" href="#tinytroupe.agent.tiny_person.TinyPerson.add_mental_faculty">add_mental_faculty</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.all_agents" href="#tinytroupe.agent.tiny_person.TinyPerson.all_agents">all_agents</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.all_agents_names" href="#tinytroupe.agent.tiny_person.TinyPerson.all_agents_names">all_agents_names</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.change_context" href="#tinytroupe.agent.tiny_person.TinyPerson.change_context">change_context</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.clear_agents" href="#tinytroupe.agent.tiny_person.TinyPerson.clear_agents">clear_agents</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.clear_communications_buffer" href="#tinytroupe.agent.tiny_person.TinyPerson.clear_communications_buffer">clear_communications_buffer</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.clear_episodic_memory" href="#tinytroupe.agent.tiny_person.TinyPerson.clear_episodic_memory">clear_episodic_memory</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.clear_relationships" href="#tinytroupe.agent.tiny_person.TinyPerson.clear_relationships">clear_relationships</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.communication_display" href="#tinytroupe.agent.tiny_person.TinyPerson.communication_display">communication_display</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.consolidate_episode_memories" href="#tinytroupe.agent.tiny_person.TinyPerson.consolidate_episode_memories">consolidate_episode_memories</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.create_new_agent_from_current_spec" href="#tinytroupe.agent.tiny_person.TinyPerson.create_new_agent_from_current_spec">create_new_agent_from_current_spec</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.decode_complete_state" href="#tinytroupe.agent.tiny_person.TinyPerson.decode_complete_state">decode_complete_state</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.define" href="#tinytroupe.agent.tiny_person.TinyPerson.define">define</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.define_relationships" href="#tinytroupe.agent.tiny_person.TinyPerson.define_relationships">define_relationships</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.encode_complete_state" href="#tinytroupe.agent.tiny_person.TinyPerson.encode_complete_state">encode_complete_state</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.generate_agent_system_prompt" href="#tinytroupe.agent.tiny_person.TinyPerson.generate_agent_system_prompt">generate_agent_system_prompt</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.get" href="#tinytroupe.agent.tiny_person.TinyPerson.get">get</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.get_agent_by_name" href="#tinytroupe.agent.tiny_person.TinyPerson.get_agent_by_name">get_agent_by_name</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.has_agent" href="#tinytroupe.agent.tiny_person.TinyPerson.has_agent">has_agent</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.import_fragment" href="#tinytroupe.agent.tiny_person.TinyPerson.import_fragment">import_fragment</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.include_persona_definitions" href="#tinytroupe.agent.tiny_person.TinyPerson.include_persona_definitions">include_persona_definitions</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.internalize_goal" href="#tinytroupe.agent.tiny_person.TinyPerson.internalize_goal">internalize_goal</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.iso_datetime" href="#tinytroupe.agent.tiny_person.TinyPerson.iso_datetime">iso_datetime</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.last_remembered_action" href="#tinytroupe.agent.tiny_person.TinyPerson.last_remembered_action">last_remembered_action</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.listen" href="#tinytroupe.agent.tiny_person.TinyPerson.listen">listen</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.listen_and_act" href="#tinytroupe.agent.tiny_person.TinyPerson.listen_and_act">listen_and_act</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.load_specification" href="#tinytroupe.agent.tiny_person.TinyPerson.load_specification">load_specification</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.load_specifications_from_folder" href="#tinytroupe.agent.tiny_person.TinyPerson.load_specifications_from_folder">load_specifications_from_folder</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.make_agent_accessible" href="#tinytroupe.agent.tiny_person.TinyPerson.make_agent_accessible">make_agent_accessible</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.make_agent_inaccessible" href="#tinytroupe.agent.tiny_person.TinyPerson.make_agent_inaccessible">make_agent_inaccessible</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.make_agents_accessible" href="#tinytroupe.agent.tiny_person.TinyPerson.make_agents_accessible">make_agents_accessible</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.make_all_agents_inaccessible" href="#tinytroupe.agent.tiny_person.TinyPerson.make_all_agents_inaccessible">make_all_agents_inaccessible</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.minibio" href="#tinytroupe.agent.tiny_person.TinyPerson.minibio">minibio</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.move_to" href="#tinytroupe.agent.tiny_person.TinyPerson.move_to">move_to</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.optimize_memory" href="#tinytroupe.agent.tiny_person.TinyPerson.optimize_memory">optimize_memory</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.pop_actions_and_get_contents_for" href="#tinytroupe.agent.tiny_person.TinyPerson.pop_actions_and_get_contents_for">pop_actions_and_get_contents_for</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.pop_and_display_latest_communications" href="#tinytroupe.agent.tiny_person.TinyPerson.pop_and_display_latest_communications">pop_and_display_latest_communications</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.pop_latest_actions" href="#tinytroupe.agent.tiny_person.TinyPerson.pop_latest_actions">pop_latest_actions</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.pp_current_interactions" href="#tinytroupe.agent.tiny_person.TinyPerson.pp_current_interactions">pp_current_interactions</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.pp_last_interactions" href="#tinytroupe.agent.tiny_person.TinyPerson.pp_last_interactions">pp_last_interactions</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.pretty_current_interactions" href="#tinytroupe.agent.tiny_person.TinyPerson.pretty_current_interactions">pretty_current_interactions</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.read_document_from_file" href="#tinytroupe.agent.tiny_person.TinyPerson.read_document_from_file">read_document_from_file</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.read_document_from_web" href="#tinytroupe.agent.tiny_person.TinyPerson.read_document_from_web">read_document_from_web</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.read_documents_from_folder" href="#tinytroupe.agent.tiny_person.TinyPerson.read_documents_from_folder">read_documents_from_folder</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.read_documents_from_web" href="#tinytroupe.agent.tiny_person.TinyPerson.read_documents_from_web">read_documents_from_web</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.related_to" href="#tinytroupe.agent.tiny_person.TinyPerson.related_to">related_to</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.reset_prompt" href="#tinytroupe.agent.tiny_person.TinyPerson.reset_prompt">reset_prompt</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.retrieve_memories" href="#tinytroupe.agent.tiny_person.TinyPerson.retrieve_memories">retrieve_memories</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.retrieve_recent_memories" href="#tinytroupe.agent.tiny_person.TinyPerson.retrieve_recent_memories">retrieve_recent_memories</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.retrieve_relevant_memories" href="#tinytroupe.agent.tiny_person.TinyPerson.retrieve_relevant_memories">retrieve_relevant_memories</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.retrieve_relevant_memories_for_current_context" href="#tinytroupe.agent.tiny_person.TinyPerson.retrieve_relevant_memories_for_current_context">retrieve_relevant_memories_for_current_context</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.save_specification" href="#tinytroupe.agent.tiny_person.TinyPerson.save_specification">save_specification</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.see" href="#tinytroupe.agent.tiny_person.TinyPerson.see">see</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.see_and_act" href="#tinytroupe.agent.tiny_person.TinyPerson.see_and_act">see_and_act</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.serializable_attributes" href="#tinytroupe.agent.tiny_person.TinyPerson.serializable_attributes">serializable_attributes</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.serializable_attributes_renaming" href="#tinytroupe.agent.tiny_person.TinyPerson.serializable_attributes_renaming">serializable_attributes_renaming</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.set_simulation_for_free_agents" href="#tinytroupe.agent.tiny_person.TinyPerson.set_simulation_for_free_agents">set_simulation_for_free_agents</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.socialize" href="#tinytroupe.agent.tiny_person.TinyPerson.socialize">socialize</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.store_in_memory" href="#tinytroupe.agent.tiny_person.TinyPerson.store_in_memory">store_in_memory</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.summarize_relevant_memories_via_full_scan" href="#tinytroupe.agent.tiny_person.TinyPerson.summarize_relevant_memories_via_full_scan">summarize_relevant_memories_via_full_scan</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.think" href="#tinytroupe.agent.tiny_person.TinyPerson.think">think</a></code></li>
<li><code><a title="tinytroupe.agent.tiny_person.TinyPerson.think_and_act" href="#tinytroupe.agent.tiny_person.TinyPerson.think_and_act">think_and_act</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.10.0</a>.</p>
</footer>
</body>
</html> |