This commit is contained in:
2026-09-18 15:21:47 +08:00
parent 0d8c34a2c9
commit aa27d35a47
55 changed files with 2842 additions and 471 deletions
+83 -11
View File
@@ -3,6 +3,7 @@ import logging
from app.models.world import WorldBlueprint, Location, TimeConfig
from app.services.llm import LLMClient, parse_json
from app.services.i18n import language_directive
logger = logging.getLogger(__name__)
@@ -45,14 +46,21 @@ Return ONLY valid JSON. No markdown, no explanation."""
class WorldGenerator:
def __init__(self, llm: LLMClient):
def __init__(self, llm: LLMClient, locale: str = "en"):
self.llm = llm
self._locale = locale
def set_locale(self, locale: str) -> None:
self._locale = locale
async def generate(
self, rules_text: str, population: int = 25, duration_days: int = 365,
proposed_change: str | None = None,
) -> WorldBlueprint:
is_market = proposed_change is not None
head, tail = language_directive(self._locale)
system = head + "\n\n" + SYSTEM_PROMPT + "\n\n" + tail
user_prompt = f"""Create a simulation world based on this context:
"{rules_text}"
@@ -65,10 +73,10 @@ active_agents_per_round_max should be about {max(3, int(population * 0.4))}"""
user_prompt += f'\n\nPROPOSED CHANGE being introduced into this world:\n"{proposed_change}"'
response = await self.llm.generate(
system=SYSTEM_PROMPT,
system=system,
user=user_prompt,
json_mode=True,
max_tokens=1500,
max_tokens=3000,
)
data = parse_json(response)
@@ -76,8 +84,15 @@ active_agents_per_round_max should be about {max(3, int(population * 0.4))}"""
logger.error("World generation produced empty result, using fallback")
return self._fallback_blueprint(rules_text, population, duration_days, proposed_change)
# Some LLMs occasionally return a list (e.g. citizens array) instead of
# a blueprint object. Wrap it defensively so the rest of the code keeps
# working.
if isinstance(data, list):
logger.warning("World blueprint came back as a list, treating as fallback")
return self._fallback_blueprint(rules_text, population, duration_days, proposed_change)
try:
locations = self._default_locations()
locations = self._default_locations(self._locale)
tc = data.get("time_config", {})
time_config = TimeConfig(
@@ -97,10 +112,23 @@ active_agents_per_round_max should be about {max(3, int(population * 0.4))}"""
if r not in resources:
resources.append(r)
# The LLM may still return English names when the user picked a
# Chinese locale — fall back to localized defaults if its output
# doesn't look like Chinese.
name = data.get("name", "")
description = data.get("description", "")
if self._locale == "zh":
name = self._ensure_zh(name, fallback="无名之邦")
description = self._ensure_zh(description, fallback=f"一个这样的社会:{rules_text[:80]}")
fallback_rule = f"一个这样的社会:{rules_text[:80]}"
rules_list = [self._ensure_zh(r, fallback=fallback_rule) for r in data.get("rules", [rules_text])]
else:
rules_list = data.get("rules", [rules_text])
return WorldBlueprint(
name=data.get("name", "Unnamed Society"),
description=data.get("description", f"A society where: {rules_text[:100]}"),
rules=data.get("rules", [rules_text]),
name=name or "Unnamed Society",
description=description or f"A society where: {rules_text[:100]}",
rules=rules_list,
locations=locations,
resources=resources,
initial_tensions=data.get("initial_tensions", ["Order vs Freedom", "Individual vs Collective"]),
@@ -110,9 +138,37 @@ active_agents_per_round_max should be about {max(3, int(population * 0.4))}"""
logger.error("Failed to parse world blueprint: %s", e)
return self._fallback_blueprint(rules_text, population, duration_days, proposed_change)
def _default_locations(self) -> list[Location]:
@staticmethod
def _has_cjk(text: str) -> bool:
return any("\u4e00" <= ch <= "\u9fff" for ch in text)
def _ensure_zh(self, value: str, fallback: str) -> str:
"""In zh locale: require CJK content, otherwise fall back.
In any other locale: always pass through.
"""
if self._locale == "zh":
if value and self._has_cjk(value):
return value
return fallback
return value or fallback
def _default_locations(self, locale: str) -> list[Location]:
if locale == "zh":
return [
Location(
id="community",
name="公共空间",
type="public",
description="居民日常互动、聚集、议事的共享场所。",
),
]
return [
Location(id="community", name="Community", type="public", description="The shared social space"),
Location(
id="community",
name="Community",
type="public",
description="The shared social space",
),
]
def _fallback_blueprint(
@@ -124,11 +180,27 @@ active_agents_per_round_max should be about {max(3, int(population * 0.4))}"""
for r in ["money", "satisfaction"]:
if r not in resources:
resources.append(r)
if self._locale == "zh":
return WorldBlueprint(
name="无名之邦",
description=f"一个这样的社会:{rules_text[:80]}",
rules=[rules_text],
locations=self._default_locations("zh"),
resources=resources,
initial_tensions=["秩序 vs 自由", "个体 vs 集体"],
time_config=TimeConfig(
total_days=duration_days,
rounds_per_day=3,
active_agents_per_round_min=3,
active_agents_per_round_max=max(3, int(population * 0.4)),
),
)
return WorldBlueprint(
name="The Settlement",
description=f"A society where: {rules_text[:100]}",
rules=[rules_text],
locations=[Location(id="community", name="Community", type="public", description="The shared social space")],
locations=self._default_locations("en"),
resources=resources,
initial_tensions=["Order vs Freedom", "Individual vs Collective"],
time_config=TimeConfig(
@@ -137,4 +209,4 @@ active_agents_per_round_max should be about {max(3, int(population * 0.4))}"""
active_agents_per_round_min=3,
active_agents_per_round_max=max(3, int(population * 0.4)),
),
)
)