Spaces:
Runtime error
Runtime error
File size: 67,665 Bytes
caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 4e69866 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 4e69866 f389eba caad8d0 f389eba caad8d0 2c503a4 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 566a38d f389eba 566a38d f389eba caad8d0 566a38d caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 4a336a4 caad8d0 f389eba 566a38d f389eba caad8d0 f389eba 4a336a4 f389eba 4a336a4 f389eba 566a38d f389eba 4a336a4 f389eba 3848364 4a336a4 f389eba 4a336a4 f389eba 566a38d 4a336a4 caad8d0 f389eba 4a336a4 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 4a336a4 caad8d0 f389eba 566a38d f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 caad8d0 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 4a336a4 f389eba 566a38d caad8d0 4a336a4 3848364 4a336a4 f389eba 4a336a4 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 4a336a4 f389eba caad8d0 f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba caad8d0 f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 566a38d f389eba caad8d0 566a38d f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba caad8d0 566a38d f389eba caad8d0 f389eba 566a38d caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba 566a38d f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 566a38d f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 f389eba 566a38d f389eba caad8d0 f389eba caad8d0 f389eba caad8d0 | 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 | """
Natural language to WorldSmithAI DSL generation.
This module converts user prompts into ``WorldSpec`` JSON. It is designed for
root-level Hugging Face Spaces ``app.py`` usage and does not assume any
``app/`` package or folder structure.
The SLM's responsibility is strictly:
Natural language -> JSON DSL
The SLM must not generate Python code. The deterministic Python engine consumes
only validated ``WorldSpec`` objects.
Example root-level app.py usage:
from llm.world_generator import generate_world_spec
from factory.world_factory import WorldFactory
def run(prompt: str):
spec = generate_world_spec(prompt)
world = WorldFactory().create_world(spec)
return spec.to_json_string(), world
Using a custom SLM client:
generator = WorldGenerator(client=my_client)
result = generator.generate("A research ecosystem with competing labs")
print(result.json_text)
Future extensibility:
- Add first-class Hugging Face transformers adapters.
- Add constrained decoding when available.
- Add schema-version migrations.
- Add model-specific prompt profiles.
- Add automatic JSON repair loops.
- Add world-quality self-critique before factory construction.
"""
from __future__ import annotations
import copy
import inspect
import json
import logging
import re
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Protocol, runtime_checkable
from dsl.parser import DSLParseError, ParseResult, WorldDSLParser
from dsl.schema import (
AgentSpec,
BehaviorSpec,
EventSpec,
PolicySpec,
ResourceSpec,
SimulationSpec,
SpaceSpec,
WorldSpec,
)
from dsl.validator import ValidationConfig, ValidationReport, ValidationSeverity, validate_world_spec
logger = logging.getLogger(__name__)
DEFAULT_SYSTEM_PROMPT = """
You are WorldSmithAI's world DSL generator.
Your only job is to convert a user's natural language description into a
WorldSmithAI WorldSpec JSON object.
Critical rules:
- Output JSON only.
- Do not include Markdown fences.
- Do not include explanations.
- Do not generate Python code.
- Do not invent classes such as Sheep, Wolf, Scientist, Dragon, City, or Truck.
- You must only use behavior names that are present in the known behavior list.
- If the user asks for hunting, predation, chasing, fighting, or killing, use attack, seek, flee, move, or raid.
- Do not invent behavior names such as hunt, graze, sleep, mate, patrol, forage, guard, chase, or rest unless they are explicitly listed in the known behavior registry.
- Use generic DSL entities: agents, resources, events, behaviors, policies.
- Agents may have any imaginative type string, but the runtime object is still Agent.
- Behaviors must be referenced by registry name.
- Policies must be referenced by registry type.
- Keep the world small enough for a lightweight Gradio demo.
- Prefer 4 to 8 agents unless the user asks for more.
- Prefer 2D positions when possible.
- Include state, memory, goals, behaviors, and policy for each agent.
- Use deterministic values and avoid randomness in the DSL.
""".strip()
WORLD_DSL_FORMAT_GUIDE = """
Return one JSON object with this structure:
{
"schema_version": "1.0",
"id": "short_world_id",
"name": "Human readable world name",
"description": "Short description",
"simulation": {
"steps": 50,
"seed": 0,
"scheduler": "sequential",
"activation": "sequential",
"collect_history": true
},
"space": {
"dimensions": 2,
"bounds": [[0, 10], [0, 10]],
"toroidal": false,
"enforce_bounds": true
},
"agents": [
{
"id": "agent_1",
"type": "generic_type",
"position": [1, 1],
"state": {"energy": 10, "credits": 5},
"memory": {"known_options": {"cooperate": 1.0}},
"goals": [{"id": "survive", "importance": 1.0, "score": 1.0}],
"behaviors": [
{"name": "remember", "params": {"category": "observation", "content": {"note": "initial memory"}}},
{"name": "prioritize", "params": {}},
{"name": "choose_goal", "params": {}},
{"name": "communicate", "params": {"message": "status_update", "max_recipients": 1}},
{"name": "cooperate", "params": {"effort": 1.0}}
],
"policy": {
"type": "rule_policy",
"params": {
"rules": [
{"behavior_name": "choose_goal", "score_delta": 3.0},
{"behavior_name": "communicate", "score_delta": 1.0}
]
}
},
"alive": true,
"metadata": {}
}
],
"resources": [
{
"id": "resource_1",
"type": "generic_resource",
"amount": 10,
"position": [5, 5],
"regeneration_rate": 0,
"max_amount": 20,
"metadata": {}
}
],
"events": [],
"metrics": [
{"name": "diversity", "params": {"collection": "agents", "group_by_path": "type"}}
],
"metadata": {}
}
Known behavior names available in this project include:
move, wander, seek, flee,
eat, harvest, mine, collect,
buy, sell, exchange,
attack, defend, raid,
study, publish, learn,
cooperate, communicate, share, recommend, negotiate,
route, deliver, ship, queue, charge,
build, repair, expand, demolish,
regulate, tax, subsidize, litigate, approve, enforce,
bid, ask, price, discount, forecast, rebalance,
adopt, switch, imitate, abandon, evaluate,
prioritize, schedule, allocate_time, choose_goal,
remember, forget, reinforce, update_belief.
Behavior mapping guidance:
- "hunt" should usually be represented as "attack" plus optionally "seek".
- "run away" should be represented as "flee".
- "look for" or "track" should be represented as "seek".
- "random movement" should be represented as "wander" or "move".
Known policy types include:
rule_policy, contextual_bandit.
""".strip()
DEFAULT_MINIMAL_EXAMPLE = {
"schema_version": "1.0",
"id": "tiny_research_world",
"name": "Tiny Research World",
"description": "A small generic research ecosystem.",
"simulation": {
"steps": 40,
"seed": 0,
"scheduler": "sequential",
"activation": "sequential",
"collect_history": True,
},
"space": {
"dimensions": 2,
"bounds": [[0, 10], [0, 10]],
"toroidal": False,
"enforce_bounds": True,
},
"agents": [
{
"id": "scientist_1",
"type": "scientist",
"position": [1, 1],
"state": {"energy": 10, "credits": 5, "knowledge": 1},
"memory": {"known_options": {"study": 1.0, "communicate": 0.5}},
"goals": [{"id": "discover", "importance": 2.0, "score": 2.0}],
"behaviors": [
{
"name": "remember",
"params": {
"category": "observation",
"content": {"note": "initial research context"},
},
},
{"name": "prioritize", "params": {}},
{"name": "choose_goal", "params": {}},
{"name": "communicate", "params": {"message": "research_update"}},
{"name": "cooperate", "params": {"goal": "discover", "effort": 1.0}},
],
"policy": {
"type": "rule_policy",
"params": {
"rules": [
{"behavior_name": "choose_goal", "score_delta": 3.0},
{"behavior_name": "communicate", "score_delta": 2.0},
{"behavior_name": "cooperate", "score_delta": 1.0},
]
},
},
"alive": True,
"metadata": {},
}
],
"resources": [
{
"id": "knowledge_pool",
"type": "knowledge",
"amount": 12,
"position": [5, 5],
"regeneration_rate": 0.2,
"max_amount": 20,
"metadata": {},
}
],
"events": [],
"metrics": [
{"name": "diversity", "params": {"collection": "agents", "group_by_path": "type"}},
{"name": "entropy", "params": {"collection": "agents", "value_path": "type"}},
{"name": "interestingness", "params": {"collection": "agents", "group_by_path": "type"}},
],
"metadata": {"generated_by": "worldsmithai_example"},
}
class GenerationMode(str, Enum):
"""Supported generation modes."""
MODEL = "model"
FALLBACK = "fallback"
AUTO = "auto"
class ResponseFormat(str, Enum):
"""Expected model response format."""
JSON_OBJECT = "json_object"
TEXT_WITH_JSON = "text_with_json"
class WorldGenerationError(RuntimeError):
"""Raised when natural-language-to-DSL generation fails."""
class ModelClientError(WorldGenerationError):
"""Raised when an SLM client cannot be called successfully."""
class WorldGenerationValidationError(WorldGenerationError):
"""Raised when generated DSL fails strict validation."""
def __init__(self, report: ValidationReport) -> None:
"""Initialize the exception with a semantic validation report."""
self.report = report
super().__init__(report.summary())
@runtime_checkable
class SupportsGenerate(Protocol):
"""Protocol for simple text generation clients."""
def generate(self, *args: Any, **kwargs: Any) -> Any:
"""Generate text from prompt-like arguments."""
@dataclass(frozen=True)
class PromptBundle:
"""Prompt payload sent to an SLM client.
The bundle includes both chat-style messages and flattened prompt text so
many different client APIs can be supported from root-level ``app.py``.
"""
system_prompt: str
user_prompt: str
messages: tuple[Mapping[str, str], ...]
metadata: Mapping[str, Any] = field(default_factory=dict)
@property
def text(self) -> str:
"""Return a flattened prompt for completion-style models."""
return f"{self.system_prompt}\n\nUSER REQUEST:\n{self.user_prompt}"
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-friendly prompt bundle."""
return {
"system_prompt": self.system_prompt,
"user_prompt": self.user_prompt,
"messages": [dict(message) for message in self.messages],
"metadata": dict(self.metadata),
}
@dataclass(frozen=True)
class WorldGenerationResult:
"""Result returned by ``WorldGenerator.generate``.
Attributes:
spec: Validated world specification.
raw_response: Raw text returned by the model, or fallback JSON text.
parse_result: Parser result when available.
validation_report: Optional semantic validation report.
mode: Whether model or deterministic fallback produced the final spec.
prompt_bundle: Prompt used for model generation when available.
metadata: Additional diagnostics useful for Gradio display.
"""
spec: WorldSpec
raw_response: str
parse_result: ParseResult | None = None
validation_report: ValidationReport | None = None
mode: GenerationMode = GenerationMode.MODEL
prompt_bundle: PromptBundle | None = None
metadata: Mapping[str, Any] = field(default_factory=dict)
@property
def json_text(self) -> str:
"""Return the generated world spec as formatted JSON."""
return self.spec.to_json_string(indent=2, exclude_none=True)
@property
def is_semantically_valid(self) -> bool:
"""Return whether semantic validation passed or was not run."""
return self.validation_report is None or self.validation_report.is_valid
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-friendly result summary."""
return {
"world_id": self.spec.id,
"world_name": self.spec.name,
"mode": self.mode.value,
"agent_count": len(self.spec.agents),
"resource_count": len(self.spec.resources),
"event_count": len(self.spec.events),
"behavior_count": len(self.spec.behavior_names),
"is_semantically_valid": self.is_semantically_valid,
"validation_report": None
if self.validation_report is None
else self.validation_report.to_dict(),
"parse_result": None if self.parse_result is None else self.parse_result.to_dict(),
"metadata": copy.deepcopy(dict(self.metadata)),
}
@dataclass
class WorldGenerationConfig:
"""Configuration for ``WorldGenerator``.
Defaults are designed for a Gradio demo:
- model output is parsed strictly,
- semantic validation runs but does not raise by default,
- deterministic fallback is enabled,
- generated worlds stay small enough for interactive simulation.
"""
mode: GenerationMode | str = GenerationMode.AUTO
response_format: ResponseFormat | str = ResponseFormat.JSON_OBJECT
system_prompt: str = DEFAULT_SYSTEM_PROMPT
include_format_guide: bool = True
include_example: bool = True
include_json_schema_excerpt: bool = False
default_steps: int = 60
default_seed: int = 0
max_agents_hint: int = 8
max_resources_hint: int = 6
parser: WorldDSLParser = field(default_factory=WorldDSLParser)
semantic_validation: bool = True
strict_semantic_validation: bool = False
semantic_validation_config: ValidationConfig | None = None
fallback_on_model_error: bool = True
fallback_on_parse_error: bool = True
fallback_on_semantic_error: bool = False
repair_attempts: int = 1
model_kwargs: Mapping[str, Any] = field(default_factory=dict)
metadata: Mapping[str, Any] = field(default_factory=dict)
def resolved_mode(self) -> GenerationMode:
"""Return normalized generation mode."""
if isinstance(self.mode, GenerationMode):
return self.mode
return GenerationMode(str(self.mode))
def resolved_response_format(self) -> ResponseFormat:
"""Return normalized response format."""
if isinstance(self.response_format, ResponseFormat):
return self.response_format
return ResponseFormat(str(self.response_format))
@dataclass
class DeterministicWorldSpecBuilder:
"""Build a valid generic fallback ``WorldSpec`` without an SLM.
This fallback exists so the Gradio demo can still run when no SLM client is
configured or when the model returns invalid JSON.
Unlike the earliest fallback version, this builder preserves important
prompt entities when possible. For example, a prompt mentioning sheep,
wolves, a hunter, and grass will produce sheep agents, wolf agents, a
hunter agent, and grass resources instead of generic farm-support roles.
"""
default_steps: int = 60
default_seed: int = 0
max_agents: int = 6
def build(
self,
prompt: str,
*,
constraints: Mapping[str, Any] | str | None = None,
) -> WorldSpec:
"""Build a deterministic world spec from prompt keywords."""
domain = self._infer_domain(prompt)
max_agents = self._max_agents_from_constraints(constraints) or self.max_agents
max_agents = max(1, int(max_agents))
roles = self._roles_for_prompt(prompt, domain, max_agents=max_agents)
resources = self._resources_for_prompt(prompt, domain)
world_id = _slugify(f"{domain}_world")
agents = tuple(
self._agent_spec(
index=index,
role=role,
domain=domain,
roles=roles,
)
for index, role in enumerate(roles)
)
resource_specs = tuple(
ResourceSpec(
id=self._resource_id(resource_type, index),
type=resource_type,
amount=float(10 + index * 4),
position=self._resource_position_for_index(index),
regeneration_rate=self._resource_regeneration_rate(resource_type),
max_amount=float(30 + index * 5),
metadata={
"domain": domain,
"generated_by": "deterministic_fallback",
"prompt_entity": resource_type in self._prompt_entity_resource_names(prompt),
},
)
for index, resource_type in enumerate(resources)
)
events = self._events_for_prompt(
prompt=prompt,
domain=domain,
roles=roles,
resources=resources,
)
return WorldSpec(
schema_version="1.0",
id=world_id,
name=_title_from_domain(domain),
description=self._description(prompt, domain, constraints),
simulation=SimulationSpec(
steps=max(1, int(self.default_steps)),
seed=self.default_seed,
scheduler="sequential",
activation="sequential",
collect_history=True,
),
space=SpaceSpec(
dimensions=2,
bounds=((0.0, 10.0), (0.0, 10.0)),
toroidal=False,
enforce_bounds=True,
),
agents=agents,
resources=resource_specs,
events=events,
metrics=(
{"name": "diversity", "params": {"collection": "agents", "group_by_path": "type"}},
{"name": "entropy", "params": {"collection": "agents", "value_path": "type"}},
{"name": "stability", "params": {"collection": "agents", "group_by_path": "type"}},
{"name": "interestingness", "params": {"collection": "agents", "group_by_path": "type"}},
),
metadata={
"generated_by": "deterministic_fallback",
"domain": domain,
"source_prompt": prompt,
"entity_aware_fallback": True,
"constraints": constraints if isinstance(constraints, Mapping) else str(constraints or ""),
},
)
def _agent_spec(
self,
*,
index: int,
role: str,
domain: str,
roles: Sequence[str],
) -> AgentSpec:
"""Create one generic fallback agent spec."""
agent_id = self._agent_id_for_roles(roles, index)
target_agent_id = self._next_agent_id_for_roles(roles, index)
goals = self._goals_for_role(role, domain)
goal_records = [
{
"id": goal,
"importance": float(len(goals) - goal_index),
"score": float(len(goals) - goal_index),
"description": f"{role} works toward {goal}",
}
for goal_index, goal in enumerate(goals)
]
x, y = self._position_for_index(index)
role_state = self._state_for_role(role, domain, index)
behaviors = [
BehaviorSpec(
name="remember",
params={
"category": "initial_context",
"content": {
"role": role,
"domain": domain,
"note": f"Seed memory for {role} created by entity-aware fallback generator.",
},
"tags": ["initial", domain, role],
},
),
BehaviorSpec(
name="evaluate",
params={
"category": f"{role}_strategy",
"candidate_options": self._options_for_role(role),
"known_options_path": "memory.known_options",
"adoption_threshold": 0.7,
"write_decision_path": "memory.latest_strategy_decision",
},
),
BehaviorSpec(
name="prioritize",
params={
"source_path": "memory.goals",
"item_attribute_weights": {
"importance": 1.0,
"score": 1.0,
},
},
),
BehaviorSpec(
name="choose_goal",
params={
"source_path": "memory.latest_priorities.items",
"current_goal_path": "state.current_goal",
},
),
BehaviorSpec(
name="communicate",
params={
"target_agent_id": target_agent_id,
"message": f"{role}_status_update",
"max_recipients": 1,
}
if target_agent_id is not None
else {
"message": f"{role}_status_update",
"max_recipients": 1,
},
),
BehaviorSpec(
name="cooperate",
params={
"target_agent_id": target_agent_id,
"goal": goals[0],
"effort": self._effort_for_role(role),
}
if target_agent_id is not None
else {
"goal": goals[0],
"effort": self._effort_for_role(role),
},
),
BehaviorSpec(
name="update_belief",
params={
"belief_id": f"{role}_situation_belief",
"proposition": self._belief_for_role(role),
"evidence_path": self._evidence_path_for_role(role),
"learning_rate": 0.25,
"write_belief_path": "memory.latest_situation_belief",
},
),
]
if role in {"hunter", "farmer"}:
behaviors.append(
BehaviorSpec(
name="recommend",
params={
"target_agent_id": target_agent_id,
"recommendation": "protect_flock_and_monitor_wolves",
"confidence": 0.75,
}
if target_agent_id is not None
else {
"recommendation": "protect_flock_and_monitor_wolves",
"confidence": 0.75,
},
)
)
if role == "wolf":
behaviors.append(
BehaviorSpec(
name="share",
params={
"target_agent_id": target_agent_id,
"content_path": "state.pack_signal",
"share_key": "pack_signal_share",
"relationship_delta": 0.05,
}
if target_agent_id is not None
else {
"content_path": "state.pack_signal",
"share_key": "pack_signal_share",
"relationship_delta": 0.05,
},
)
)
policy_rules = [
{"behavior_name": "choose_goal", "score_delta": 4.0, "priority_delta": 1.0},
{"behavior_name": "prioritize", "score_delta": 3.0},
{"behavior_name": "communicate", "score_delta": 2.0},
{"behavior_name": "cooperate", "score_delta": 1.5},
{"behavior_name": "evaluate", "score_delta": 1.0},
{"behavior_name": "update_belief", "score_delta": 0.8},
{"behavior_name": "remember", "score_delta": 0.5},
]
if role in {"hunter", "farmer"}:
policy_rules.append({"behavior_name": "recommend", "score_delta": 1.2})
if role == "wolf":
policy_rules.append({"behavior_name": "share", "score_delta": 1.2})
return AgentSpec(
id=agent_id,
type=role,
position=(x, y),
state=role_state,
memory={
"goals": goal_records,
"known_options": self._known_options_for_role(role),
"relationships": {},
"source_role": role,
},
goals=goal_records,
behaviors=tuple(behaviors),
policy=PolicySpec(
type="rule_policy",
params={
"selection_strategy": "highest_score",
"rules": policy_rules,
},
),
alive=True,
metadata={
"domain": domain,
"generated_by": "deterministic_fallback",
"prompt_role": role,
},
)
def _roles_for_prompt(
self,
prompt: str,
domain: str,
*,
max_agents: int,
) -> tuple[str, ...]:
"""Return role list that preserves important prompt entities."""
text = prompt.lower()
roles: list[str] = []
if domain == "farm":
roles.append("farmer")
has_sheep = self._contains_any(text, ("sheep", "lamb", "flock"))
has_wolf = self._contains_any(text, ("wolf", "wolves", "pack"))
has_hunter = self._contains_any(text, ("hunter", "ranger", "shepherd"))
if has_sheep:
roles.append("sheep")
if has_wolf:
roles.append("wolf")
if has_hunter:
roles.append("hunter")
if has_sheep and len(roles) < max_agents:
roles.append("sheep")
if has_wolf and len(roles) < max_agents:
roles.append("wolf")
if not has_sheep and not has_wolf and not has_hunter:
roles.extend(self._roles_for_domain(domain))
return tuple(roles[:max_agents])
roles.extend(self._roles_for_domain(domain))
return tuple(roles[:max_agents])
def _resources_for_prompt(self, prompt: str, domain: str) -> tuple[str, ...]:
"""Return resource types that preserve important prompt entities."""
text = prompt.lower()
if domain == "farm":
resources: list[str] = []
if self._contains_any(text, ("grass", "pasture")):
resources.append("grass")
else:
resources.append("food")
if self._contains_any(text, ("sheep", "flock", "lamb")):
resources.append("flock_safety")
resources.append("shelter")
if self._contains_any(text, ("wolf", "wolves", "pack", "hunter")):
resources.append("predator_pressure")
resources.append("water")
if "soil_health" not in resources:
resources.append("soil_health")
return tuple(dict.fromkeys(resources))
return self._resources_for_domain(domain)
def _events_for_prompt(
self,
*,
prompt: str,
domain: str,
roles: Sequence[str],
resources: Sequence[str],
) -> tuple[EventSpec, ...]:
"""Return domain events that preserve important prompt entities."""
text = prompt.lower()
events: list[EventSpec] = []
wolf_ids = [
self._agent_id_for_roles(roles, index)
for index, role in enumerate(roles)
if role == "wolf"
]
sheep_ids = [
self._agent_id_for_roles(roles, index)
for index, role in enumerate(roles)
if role == "sheep"
]
hunter_ids = [
self._agent_id_for_roles(roles, index)
for index, role in enumerate(roles)
if role == "hunter"
]
farmer_ids = [
self._agent_id_for_roles(roles, index)
for index, role in enumerate(roles)
if role == "farmer"
]
resource_ids = {
resource_type: self._resource_id(resource_type, index)
for index, resource_type in enumerate(resources)
}
if domain == "farm" and self._contains_any(text, ("wolf", "wolves", "pack")):
events.append(
EventSpec(
id="wolf_pack_enters",
name="wolf_pack_enters",
trigger_step=max(1, self.default_steps // 4),
payload={
"description": "A pack of wolves enters the farm and increases pressure on the flock.",
"signals": {
"predator_pressure": 0.35,
"flock_fear": 0.25,
},
},
enabled=True,
target_agent_ids=tuple(wolf_ids + sheep_ids + farmer_ids),
target_resource_ids=tuple(
resource_id
for key, resource_id in resource_ids.items()
if key in {"predator_pressure", "flock_safety", "grass"}
),
metadata={
"generated_by": "entity_aware_fallback",
"narrative_hint": "Predator pressure tests flock safety and farm coordination.",
},
)
)
if domain == "farm" and self._contains_any(text, ("hunter", "ranger")):
events.append(
EventSpec(
id="hunter_enters",
name="hunter_enters",
trigger_step=max(2, self.default_steps // 3),
payload={
"description": "A hunter enters the farm area and changes the balance between wolves and sheep.",
"signals": {
"protection_pressure": 0.3,
"wolf_caution": 0.2,
},
},
enabled=True,
target_agent_ids=tuple(hunter_ids + wolf_ids + farmer_ids + sheep_ids),
target_resource_ids=tuple(
resource_id
for key, resource_id in resource_ids.items()
if key in {"predator_pressure", "flock_safety"}
),
metadata={
"generated_by": "entity_aware_fallback",
"narrative_hint": "Hunter arrival adds a stabilizing or disruptive force.",
},
)
)
if not events:
events.append(
EventSpec(
id="midpoint_pressure",
name="midpoint_pressure",
trigger_step=max(1, self.default_steps // 2),
payload={
"description": "A generic pressure event that can be narrated later.",
"domain": domain,
},
enabled=True,
metadata={"generated_by": "fallback_builder"},
)
)
return tuple(events)
def _state_for_role(self, role: str, domain: str, index: int) -> dict[str, Any]:
"""Return role-specific initial state."""
base_state: dict[str, Any] = {
"energy": float(max(3, 10 - index)),
"credits": float(5 + index),
"influence": float(index + 1),
"domain_pressure": 0.2,
"inventory": {},
}
if role == "sheep":
base_state.update(
{
"hunger": 0.4,
"fear": 0.35,
"herd_signal": 0.75,
"grazing_need": 0.8,
"inventory": {"wool": 1},
}
)
return base_state
if role == "wolf":
base_state.update(
{
"hunger": 0.85,
"pack_signal": 0.8,
"caution": 0.3,
"predator_intent": 0.9,
"inventory": {},
}
)
return base_state
if role == "hunter":
base_state.update(
{
"tracking_skill": 0.8,
"protection_signal": 0.7,
"caution": 0.55,
"inventory": {"tools": 2, "supplies": 2},
}
)
return base_state
if role == "farmer":
base_state.update(
{
"flock_care": 0.8,
"grass_management": 0.65,
"protection_signal": 0.5,
"inventory": {"hay": 3, "tools": 2},
}
)
return base_state
base_state.update(
{
"role_signal": 0.6,
"inventory": {},
}
)
return base_state
def _goals_for_role(self, role: str, domain: str) -> tuple[str, ...]:
"""Return role-specific fallback goal ids."""
if role == "sheep":
return ("graze_on_grass", "stay_with_flock", "avoid_wolves")
if role == "wolf":
return ("coordinate_pack", "seek_food_pressure", "avoid_hunter")
if role == "hunter":
return ("protect_flock", "track_wolves", "avoid_unnecessary_harm")
if role == "farmer":
return ("protect_sheep", "maintain_grass", "coordinate_hunter")
return self._goals_for_domain(domain)
def _known_options_for_role(self, role: str) -> dict[str, Any]:
"""Return role-specific known options."""
if role == "sheep":
return {
"graze": {"score": 1.0, "energy": 0.8},
"flock_together": {"score": 1.2, "safety": 0.9},
"avoid_predator": {"score": 1.4, "safety": 1.0},
}
if role == "wolf":
return {
"pack_coordination": {"score": 1.3, "success": 0.8},
"cautious_entry": {"score": 1.0, "safety": 0.7},
"pressure_flock": {"score": 1.2, "food": 0.8},
}
if role == "hunter":
return {
"track_wolves": {"score": 1.2, "protection": 0.9},
"coordinate_farmer": {"score": 1.1, "trust": 0.8},
"guard_pasture": {"score": 1.0, "safety": 0.9},
}
if role == "farmer":
return {
"protect_flock": {"score": 1.2, "safety": 0.9},
"maintain_pasture": {"score": 1.0, "grass": 0.8},
"coordinate_hunter": {"score": 1.1, "protection": 0.8},
}
return {
"cooperate": 1.0,
"communicate": 0.8,
"evaluate": 0.6,
}
def _options_for_role(self, role: str) -> list[str]:
"""Return candidate option ids for evaluation behavior."""
return list(self._known_options_for_role(role).keys())
def _belief_for_role(self, role: str) -> str:
"""Return a role-specific belief proposition."""
if role == "sheep":
return "The flock can stay safe while grazing."
if role == "wolf":
return "The pack can coordinate under farm and hunter pressure."
if role == "hunter":
return "The hunter can reduce wolf pressure without destabilizing the farm."
if role == "farmer":
return "The farm can protect sheep while maintaining grass resources."
return "The current situation is manageable."
def _evidence_path_for_role(self, role: str) -> str:
"""Return a role-specific evidence path."""
if role == "sheep":
return "state.herd_signal"
if role == "wolf":
return "state.pack_signal"
if role == "hunter":
return "state.protection_signal"
if role == "farmer":
return "state.flock_care"
return "state.domain_pressure"
def _effort_for_role(self, role: str) -> float:
"""Return role-specific cooperation effort."""
if role in {"hunter", "farmer", "wolf"}:
return 1.0
if role == "sheep":
return 0.7
return 0.8
@staticmethod
def _resource_position_for_index(index: int) -> tuple[float, float]:
"""Return deterministic in-bounds 2D position for a resource index."""
positions = (
(2.0, 7.0),
(4.0, 6.0),
(6.0, 5.0),
(8.0, 4.0),
(2.0, 3.0),
(4.0, 2.0),
(6.0, 7.0),
(8.0, 6.0),
(5.0, 5.0),
(7.0, 3.0),
)
return positions[index % len(positions)]
def _position_for_index(self, index: int) -> tuple[float, float]:
"""Return deterministic 2D position for agent index."""
positions = (
(1.0, 1.0),
(3.0, 6.5),
(7.5, 6.5),
(8.5, 2.0),
(4.0, 7.5),
(6.5, 2.5),
(2.0, 4.0),
(8.0, 8.0),
)
return positions[index % len(positions)]
def _agent_id_for_roles(self, roles: Sequence[str], index: int) -> str:
"""Return stable id for an agent in a possibly duplicated role list."""
role = roles[index]
ordinal = sum(1 for candidate in roles[: index + 1] if candidate == role)
return f"{role}_{ordinal}"
def _next_agent_id_for_roles(self, roles: Sequence[str], index: int) -> str | None:
"""Return next cyclic target agent id."""
if len(roles) <= 1:
return None
next_index = (index + 1) % len(roles)
return self._agent_id_for_roles(roles, next_index)
def _resource_id(self, resource_type: str, index: int) -> str:
"""Return stable resource id."""
return f"{_slugify(resource_type)}_{index + 1}"
def _resource_regeneration_rate(self, resource_type: str) -> float:
"""Return resource-specific regeneration rate."""
if resource_type in {"grass", "food", "water", "soil_health"}:
return 0.2
if resource_type in {"flock_safety", "predator_pressure"}:
return 0.05
return 0.0
def _max_agents_from_constraints(
self,
constraints: Mapping[str, Any] | str | None,
) -> int | None:
"""Extract max_agents from parsed constraints when available."""
if not isinstance(constraints, Mapping):
return None
value = constraints.get("max_agents")
if value is None:
return None
try:
return max(1, int(value))
except (TypeError, ValueError):
return None
def _prompt_entity_resource_names(self, prompt: str) -> set[str]:
"""Return resource names explicitly suggested by the prompt."""
text = prompt.lower()
names: set[str] = set()
if self._contains_any(text, ("grass", "pasture")):
names.add("grass")
return names
@staticmethod
def _contains_any(text: str, words: Sequence[str]) -> bool:
"""Return whether any word-like string appears in text."""
lowered = text.lower()
return any(word in lowered for word in words)
@staticmethod
def _infer_domain(prompt: str) -> str:
"""Infer a broad fallback domain from prompt keywords."""
text = prompt.lower()
keyword_domains = (
("farm", ("farm", "crop", "soil", "harvest", "animal", "pasture", "sheep", "wolf", "wolves", "grass")),
("medieval", ("medieval", "kingdom", "castle", "guild", "village", "empire")),
("research", ("research", "scientist", "paper", "lab", "study", "knowledge")),
("startup", ("startup", "founder", "investor", "customer", "market", "product")),
("social", ("social", "network", "influencer", "community", "friend", "viral")),
("transport", ("transport", "route", "traffic", "delivery", "ship", "vehicle")),
("power", ("power", "grid", "energy", "battery", "generator", "electric")),
("space", ("space", "colony", "planet", "terraform", "asteroid", "orbital")),
("fantasy", ("fantasy", "dragon", "mana", "mage", "kingdom", "quest")),
)
for domain, keywords in keyword_domains:
if any(keyword in text for keyword in keywords):
return domain
return "generic"
@staticmethod
def _roles_for_domain(domain: str) -> tuple[str, ...]:
"""Return fallback agent roles for a domain."""
roles_by_domain = {
"farm": ("farmer", "pollinator", "soil_guardian", "market_vendor"),
"medieval": ("ruler", "merchant", "artisan", "scholar", "guard"),
"research": ("scientist", "reviewer", "engineer", "curator", "funding_agent"),
"startup": ("founder", "customer", "investor", "operator", "competitor"),
"social": ("creator", "moderator", "member", "recommender", "critic"),
"transport": ("hub", "carrier", "dispatcher", "charger", "passenger"),
"power": ("generator", "storage_node", "consumer", "regulator", "maintainer"),
"space": ("colonist", "engineer", "botanist", "navigator", "miner"),
"fantasy": ("mage", "merchant", "guardian", "dragon", "healer"),
"generic": ("explorer", "builder", "trader", "learner", "coordinator"),
}
return roles_by_domain.get(domain, roles_by_domain["generic"])
@staticmethod
def _resources_for_domain(domain: str) -> tuple[str, ...]:
"""Return fallback resource types for a domain."""
resources_by_domain = {
"farm": ("food", "water", "soil_health"),
"medieval": ("grain", "gold", "craft_materials"),
"research": ("knowledge", "funding", "attention"),
"startup": ("capital", "users", "compute"),
"social": ("attention", "trust", "content"),
"transport": ("capacity", "fuel", "demand"),
"power": ("energy", "storage", "load"),
"space": ("oxygen", "minerals", "habitat_capacity"),
"fantasy": ("mana", "relics", "influence"),
"generic": ("energy", "materials", "knowledge"),
}
return resources_by_domain.get(domain, resources_by_domain["generic"])
@staticmethod
def _goals_for_domain(domain: str) -> tuple[str, ...]:
"""Return fallback goal ids for a domain."""
goals_by_domain = {
"farm": ("sustain_harvest", "share_resources", "adapt_to_weather"),
"medieval": ("maintain_order", "grow_trade", "protect_settlement"),
"research": ("discover", "publish", "collaborate"),
"startup": ("find_users", "improve_product", "raise_capital"),
"social": ("grow_trust", "spread_useful_content", "moderate_conflict"),
"transport": ("deliver_reliably", "reduce_congestion", "balance_capacity"),
"power": ("meet_demand", "prevent_outage", "rebalance_energy"),
"space": ("survive_colony", "expand_habitat", "extract_resources"),
"fantasy": ("protect_realm", "gather_mana", "negotiate_alliances"),
"generic": ("survive", "learn", "cooperate"),
}
return goals_by_domain.get(domain, goals_by_domain["generic"])
@staticmethod
def _description(
prompt: str,
domain: str,
constraints: Mapping[str, Any] | str | None,
) -> str:
"""Build fallback world description."""
constraint_text = ""
if constraints:
constraint_text = f" Constraints: {constraints}"
return (
f"A deterministic entity-aware fallback {domain} world generated from the prompt: "
f"{prompt.strip()[:240]}{constraint_text}"
)
@dataclass
class WorldGenerator:
"""Generate ``WorldSpec`` objects from natural language prompts.
The generator is intentionally adapter-neutral. A client can be any object
exposing ``generate``, ``complete``, ``chat``, or ``__call__``. The module
does not import a specific model SDK.
"""
client: Any | None = None
config: WorldGenerationConfig = field(default_factory=WorldGenerationConfig)
def generate(
self,
prompt: str,
*,
constraints: Mapping[str, Any] | str | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
model_kwargs: Mapping[str, Any] | None = None,
) -> WorldGenerationResult:
"""Generate a validated ``WorldSpec`` from natural language.
Args:
prompt: Natural language world description.
constraints: Optional extra constraints from the UI.
examples: Optional few-shot examples as specs, mappings, or strings.
model_kwargs: Optional generation kwargs for the model client.
Returns:
``WorldGenerationResult``.
Raises:
WorldGenerationError: If generation fails and fallback is disabled.
"""
normalized_prompt = _require_prompt(prompt)
mode = self.config.resolved_mode()
if mode is GenerationMode.FALLBACK or self.client is None:
return self._fallback_result(
normalized_prompt,
constraints=constraints,
reason="fallback_mode" if mode is GenerationMode.FALLBACK else "client_not_configured",
)
prompt_bundle = self.build_prompt(
normalized_prompt,
constraints=constraints,
examples=examples,
)
try:
raw_response = self._call_client(prompt_bundle, model_kwargs=model_kwargs)
except Exception as exc:
if self.config.fallback_on_model_error and mode is GenerationMode.AUTO:
logger.warning("Model client failed; using deterministic fallback: %s", exc)
return self._fallback_result(
normalized_prompt,
constraints=constraints,
reason="model_client_error",
error=exc,
prompt_bundle=prompt_bundle,
)
raise ModelClientError(f"Model client failed: {exc}") from exc
parse_result: ParseResult | None = None
parse_error: BaseException | None = None
current_response = raw_response
for attempt in range(max(1, int(self.config.repair_attempts) + 1)):
try:
parse_result = self.config.parser.parse_result(current_response)
break
except Exception as exc:
parse_error = exc
if attempt >= int(self.config.repair_attempts):
break
current_response = self._repair_response(
prompt_bundle=prompt_bundle,
bad_response=current_response,
error=exc,
model_kwargs=model_kwargs,
)
if parse_result is None:
if self.config.fallback_on_parse_error and mode is GenerationMode.AUTO:
logger.warning("Generated DSL could not be parsed; using fallback: %s", parse_error)
return self._fallback_result(
normalized_prompt,
constraints=constraints,
reason="parse_error",
error=parse_error,
raw_response=raw_response,
prompt_bundle=prompt_bundle,
)
raise WorldGenerationError(f"Generated DSL could not be parsed: {parse_error}") from parse_error
validation_report = self._semantic_validation(parse_result.spec)
if validation_report is not None and not validation_report.is_valid:
if self.config.strict_semantic_validation:
if self.config.fallback_on_semantic_error and mode is GenerationMode.AUTO:
return self._fallback_result(
normalized_prompt,
constraints=constraints,
reason="semantic_validation_error",
raw_response=raw_response,
prompt_bundle=prompt_bundle,
)
raise WorldGenerationValidationError(validation_report)
return WorldGenerationResult(
spec=parse_result.spec,
raw_response=raw_response,
parse_result=parse_result,
validation_report=validation_report,
mode=GenerationMode.MODEL,
prompt_bundle=prompt_bundle,
metadata={
**copy.deepcopy(dict(self.config.metadata)),
"repair_attempts_used": 0 if current_response == raw_response else 1,
},
)
def generate_spec(
self,
prompt: str,
*,
constraints: Mapping[str, Any] | str | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
model_kwargs: Mapping[str, Any] | None = None,
) -> WorldSpec:
"""Generate and return only the ``WorldSpec``."""
return self.generate(
prompt,
constraints=constraints,
examples=examples,
model_kwargs=model_kwargs,
).spec
def generate_json(
self,
prompt: str,
*,
constraints: Mapping[str, Any] | str | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
model_kwargs: Mapping[str, Any] | None = None,
) -> str:
"""Generate and return formatted WorldSpec JSON."""
return self.generate(
prompt,
constraints=constraints,
examples=examples,
model_kwargs=model_kwargs,
).json_text
def build_prompt(
self,
prompt: str,
*,
constraints: Mapping[str, Any] | str | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
) -> PromptBundle:
"""Build the prompt bundle sent to the model client."""
sections: list[str] = []
sections.append(f"World request:\n{prompt.strip()}")
if constraints:
sections.append(f"Additional constraints:\n{_serialize_constraints(constraints)}")
sections.append(
"Return a compact but complete WorldSmithAI WorldSpec JSON object. "
"The JSON must be parseable by Python json.loads."
)
if self.config.include_format_guide:
sections.append(f"WorldSpec format guide:\n{WORLD_DSL_FORMAT_GUIDE}")
if self.config.include_json_schema_excerpt:
sections.append(f"Schema excerpt:\n{world_spec_schema_excerpt()}")
example_payloads = self._example_payloads(examples)
if self.config.include_example and example_payloads:
sections.append("Example valid WorldSpec JSON:\n" + example_payloads[0])
sections.append(
"Final answer requirements:\n"
"- JSON object only.\n"
"- No markdown.\n"
"- No comments.\n"
"- No Python code.\n"
"- No prose before or after the JSON."
)
user_prompt = "\n\n".join(sections)
system_prompt = self.config.system_prompt
return PromptBundle(
system_prompt=system_prompt,
user_prompt=user_prompt,
messages=(
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
),
metadata={
"response_format": self.config.resolved_response_format().value,
"default_steps": self.config.default_steps,
"max_agents_hint": self.config.max_agents_hint,
"max_resources_hint": self.config.max_resources_hint,
},
)
def _example_payloads(
self,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None,
) -> tuple[str, ...]:
"""Return serialized few-shot examples."""
if examples is None:
return (json.dumps(DEFAULT_MINIMAL_EXAMPLE, indent=2),)
payloads: list[str] = []
for example in examples:
if isinstance(example, WorldSpec):
payloads.append(example.to_json_string(indent=2, exclude_none=True))
elif isinstance(example, Mapping):
payloads.append(json.dumps(example, indent=2))
elif isinstance(example, str):
payloads.append(example.strip())
return tuple(payload for payload in payloads if payload)
def _call_client(
self,
prompt_bundle: PromptBundle,
*,
model_kwargs: Mapping[str, Any] | None = None,
) -> str:
"""Call the configured model client and normalize its response to text."""
if self.client is None:
raise ModelClientError("No model client is configured")
kwargs = {
**copy.deepcopy(dict(self.config.model_kwargs)),
**copy.deepcopy(dict(model_kwargs or {})),
}
callable_obj, call_style = self._resolve_client_callable(self.client)
call_kwargs = {
"prompt": prompt_bundle.text,
"system_prompt": prompt_bundle.system_prompt,
"user_prompt": prompt_bundle.user_prompt,
"messages": [dict(message) for message in prompt_bundle.messages],
"response_format": {"type": "json_object"},
**kwargs,
}
if call_style == "chat":
call_kwargs.setdefault("prompt", prompt_bundle.user_prompt)
response = _call_with_supported_kwargs(callable_obj, call_kwargs)
return normalize_model_response(response)
def _repair_response(
self,
*,
prompt_bundle: PromptBundle,
bad_response: str,
error: BaseException,
model_kwargs: Mapping[str, Any] | None,
) -> str:
"""Ask the model client to repair malformed JSON."""
repair_user_prompt = (
"The previous response was not valid WorldSmithAI JSON.\n\n"
f"Parser error:\n{error}\n\n"
"Previous response:\n"
f"{bad_response[:8000]}\n\n"
"Return only a corrected WorldSpec JSON object. No markdown. No prose."
)
repair_bundle = PromptBundle(
system_prompt=prompt_bundle.system_prompt,
user_prompt=repair_user_prompt,
messages=(
{"role": "system", "content": prompt_bundle.system_prompt},
{"role": "user", "content": repair_user_prompt},
),
metadata={"repair": True},
)
return self._call_client(repair_bundle, model_kwargs=model_kwargs)
@staticmethod
def _resolve_client_callable(client: Any) -> tuple[Callable[..., Any], str]:
"""Resolve a callable generation method from a model client."""
for method_name, style in (
("generate", "generate"),
("complete", "complete"),
("chat", "chat"),
):
method = getattr(client, method_name, None)
if callable(method):
return method, style
if callable(client):
return client, "callable"
raise ModelClientError(
"Model client must expose generate, complete, chat, or be callable"
)
def _semantic_validation(self, spec: WorldSpec) -> ValidationReport | None:
"""Run optional semantic validation."""
if not self.config.semantic_validation:
return None
validation_config = self.config.semantic_validation_config
if validation_config is None:
validation_config = ValidationConfig(
require_known_behaviors=True,
require_known_policies=True,
unknown_registry_item_severity=ValidationSeverity.WARNING,
constructor_param_severity=ValidationSeverity.WARNING,
unresolved_reference_severity=ValidationSeverity.WARNING,
)
return validate_world_spec(spec, config=validation_config)
def _fallback_result(
self,
prompt: str,
*,
constraints: Mapping[str, Any] | str | None,
reason: str,
error: BaseException | None = None,
raw_response: str | None = None,
prompt_bundle: PromptBundle | None = None,
) -> WorldGenerationResult:
"""Build a deterministic fallback result."""
builder = DeterministicWorldSpecBuilder(
default_steps=self.config.default_steps,
default_seed=self.config.default_seed,
max_agents=min(max(1, int(self.config.max_agents_hint)), 6),
)
spec = builder.build(prompt, constraints=constraints)
validation_report = self._semantic_validation(spec)
raw = raw_response or spec.to_json_string(indent=2, exclude_none=True)
return WorldGenerationResult(
spec=spec,
raw_response=raw,
parse_result=None,
validation_report=validation_report,
mode=GenerationMode.FALLBACK,
prompt_bundle=prompt_bundle,
metadata={
**copy.deepcopy(dict(self.config.metadata)),
"fallback_reason": reason,
"error": None if error is None else f"{error.__class__.__name__}: {error}",
},
)
def generate_world_spec(
prompt: str,
*,
client: Any | None = None,
constraints: Mapping[str, Any] | str | None = None,
config: WorldGenerationConfig | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
model_kwargs: Mapping[str, Any] | None = None,
) -> WorldSpec:
"""Convenience function that returns a generated ``WorldSpec``.
This is the simplest function to call from root-level ``app.py``.
"""
generator = WorldGenerator(client=client, config=config or WorldGenerationConfig())
return generator.generate_spec(
prompt,
constraints=constraints,
examples=examples,
model_kwargs=model_kwargs,
)
def generate_world_json(
prompt: str,
*,
client: Any | None = None,
constraints: Mapping[str, Any] | str | None = None,
config: WorldGenerationConfig | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
model_kwargs: Mapping[str, Any] | None = None,
) -> str:
"""Convenience function that returns generated WorldSpec JSON."""
generator = WorldGenerator(client=client, config=config or WorldGenerationConfig())
return generator.generate_json(
prompt,
constraints=constraints,
examples=examples,
model_kwargs=model_kwargs,
)
def generate_world_result(
prompt: str,
*,
client: Any | None = None,
constraints: Mapping[str, Any] | str | None = None,
config: WorldGenerationConfig | None = None,
examples: Sequence[WorldSpec | Mapping[str, Any] | str] | None = None,
model_kwargs: Mapping[str, Any] | None = None,
) -> WorldGenerationResult:
"""Convenience function that returns the full generation result."""
generator = WorldGenerator(client=client, config=config or WorldGenerationConfig())
return generator.generate(
prompt,
constraints=constraints,
examples=examples,
model_kwargs=model_kwargs,
)
def build_world_generation_prompt(
prompt: str,
*,
constraints: Mapping[str, Any] | str | None = None,
config: WorldGenerationConfig | None = None,
) -> PromptBundle:
"""Build the prompt bundle without calling a model."""
generator = WorldGenerator(client=None, config=config or WorldGenerationConfig())
return generator.build_prompt(prompt, constraints=constraints)
def normalize_model_response(response: Any) -> str:
"""Normalize common model-client response shapes into text.
Supported shapes:
- plain string
- bytes
- mapping with text/content/generated_text/output
- OpenAI-like mapping with choices[0].message.content
- object with text/content/generated_text attributes
"""
if response is None:
raise ModelClientError("Model client returned None")
if isinstance(response, str):
return response.strip()
if isinstance(response, bytes):
return response.decode("utf-8").strip()
if isinstance(response, Mapping):
direct = _first_present(
response,
("text", "content", "generated_text", "output", "response"),
)
if direct is not None:
return normalize_model_response(direct)
choices = response.get("choices")
if isinstance(choices, Sequence) and choices:
first_choice = choices[0]
if isinstance(first_choice, Mapping):
message = first_choice.get("message")
if isinstance(message, Mapping) and message.get("content") is not None:
return normalize_model_response(message["content"])
if first_choice.get("text") is not None:
return normalize_model_response(first_choice["text"])
if response.get("data") is not None:
return normalize_model_response(response["data"])
for attribute in ("text", "content", "generated_text", "output", "response"):
value = getattr(response, attribute, None)
if value is not None:
return normalize_model_response(value)
raise ModelClientError(
f"Could not extract text from model response of type {response.__class__.__name__}"
)
def world_spec_schema_excerpt() -> str:
"""Return a compact schema guide suitable for small-model prompts."""
excerpt = {
"WorldSpec": {
"required": ["id", "name", "agents", "resources", "events"],
"fields": {
"schema_version": "string",
"id": "string",
"name": "string",
"description": "string|null",
"simulation": "SimulationSpec",
"space": "SpaceSpec|null",
"agents": "AgentSpec[]",
"resources": "ResourceSpec[]",
"events": "EventSpec[]",
"metrics": "MetricSpec[]",
"metadata": "object",
},
},
"AgentSpec": {
"fields": {
"id": "string",
"type": "string",
"position": "number[]|null",
"state": "object",
"memory": "object",
"goals": "JSON",
"behaviors": "BehaviorSpec[]",
"policy": "PolicySpec|null",
"alive": "boolean",
"metadata": "object",
}
},
"BehaviorSpec": {"fields": {"name": "string", "params": "object"}},
"PolicySpec": {"fields": {"type": "string", "params": "object"}},
"ResourceSpec": {
"fields": {
"id": "string",
"type": "string",
"amount": "number",
"position": "number[]|null",
"regeneration_rate": "number",
"max_amount": "number|null",
"metadata": "object",
}
},
"EventSpec": {
"fields": {
"id": "string|null",
"name": "string",
"trigger_step": "integer",
"payload": "object",
"enabled": "boolean",
}
},
}
return json.dumps(excerpt, indent=2)
def extract_json_object_text(text: str) -> str:
"""Extract the first balanced JSON object from text.
This is exposed as a utility for app-level debugging. The parser already
uses equivalent extraction internally.
"""
parser = WorldDSLParser()
return parser.extract_json_text(text)
def _call_with_supported_kwargs(callable_obj: Callable[..., Any], kwargs: Mapping[str, Any]) -> Any:
"""Call a function using only kwargs supported by its signature.
If the callable accepts ``**kwargs``, all supplied kwargs are passed.
Otherwise unsupported kwargs are filtered out. If no matching keyword is
accepted but a positional prompt appears possible, the flattened prompt is
passed positionally.
"""
try:
signature = inspect.signature(callable_obj)
except (TypeError, ValueError):
return callable_obj(**dict(kwargs))
parameters = signature.parameters
accepts_var_keyword = any(
parameter.kind is inspect.Parameter.VAR_KEYWORD
for parameter in parameters.values()
)
if accepts_var_keyword:
return callable_obj(**dict(kwargs))
accepted = {
key: value
for key, value in kwargs.items()
if key in parameters
}
if accepted:
return callable_obj(**accepted)
positional_params = [
parameter
for parameter in parameters.values()
if parameter.kind
in {
inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
}
]
if positional_params and "prompt" in kwargs:
return callable_obj(kwargs["prompt"])
return callable_obj()
def _first_present(mapping: Mapping[str, Any], keys: Sequence[str]) -> Any:
"""Return first present non-null mapping value."""
for key in keys:
if key in mapping and mapping[key] is not None:
return mapping[key]
return None
def _serialize_constraints(constraints: Mapping[str, Any] | str) -> str:
"""Serialize UI constraints for prompt inclusion."""
if isinstance(constraints, str):
return constraints.strip()
return json.dumps(constraints, indent=2, sort_keys=True)
def _require_prompt(prompt: str) -> str:
"""Validate and normalize a user prompt."""
normalized = str(prompt).strip()
if not normalized:
raise WorldGenerationError("World generation prompt must not be empty")
return normalized
def _slugify(value: str) -> str:
"""Return a stable lowercase identifier."""
lowered = value.lower().strip()
slug = re.sub(r"[^a-z0-9]+", "_", lowered)
slug = re.sub(r"_+", "_", slug).strip("_")
return slug or "world"
def _title_from_domain(domain: str) -> str:
"""Return a human-readable fallback world title."""
words = domain.replace("_", " ").split()
return " ".join(word.capitalize() for word in words) + " World"
__all__ = [
"DEFAULT_MINIMAL_EXAMPLE",
"DEFAULT_SYSTEM_PROMPT",
"WORLD_DSL_FORMAT_GUIDE",
"DeterministicWorldSpecBuilder",
"GenerationMode",
"ModelClientError",
"PromptBundle",
"ResponseFormat",
"SupportsGenerate",
"WorldGenerationConfig",
"WorldGenerationError",
"WorldGenerationResult",
"WorldGenerationValidationError",
"WorldGenerator",
"build_world_generation_prompt",
"extract_json_object_text",
"generate_world_json",
"generate_world_result",
"generate_world_spec",
"normalize_model_response",
"world_spec_schema_excerpt",
] |