Heuristic:4thfever Cultivation world simulator LLM Concurrency Semaphore
| Knowledge Sources | |
|---|---|
| Domains | LLM, Optimization, Concurrency |
| Last Updated | 2026-10-22 16:00 GMT |
Overview
Limit concurrent LLM API calls via a lazily-initialized `asyncio.Semaphore` bounded by `max_concurrent_requests` (default 10, max 50) to prevent rate-limit errors and provider overload.
Description
The LLM client uses a module-level semaphore to cap the number of simultaneous in-flight LLM API requests. The semaphore limit is read from the LLM profile's `max_concurrent_requests` setting (validated to be 1-50, default 10). The semaphore is lazily created on first use and dynamically reconfigured if the setting changes. The World Lore rewrite subsystem intentionally uses a higher limit (`max(8, max_concurrent * 2)`) because lore rewriting batches many independent items.
Usage
Use this heuristic when tuning LLM throughput. Increase `max_concurrent_requests` (up to 50) if the provider can handle more parallelism. Decrease if hitting rate limits (429 errors). The semaphore is shared across all LLM tasks except World Lore, which has its own higher limit.
The Insight (Rule of Thumb)
- Action: Set `max_concurrent_requests` in the LLM profile (settings.json) or via `CWS_DEFAULT_LLM_MAX_CONCURRENT_REQUESTS`.
- Value: Default 10, range 1-50. World Lore rewrite uses `max(8, value * 2)`.
- Trade-off: Higher values improve throughput but risk rate-limit errors (429) and quota exhaustion. Lower values are safer but slower for large populations.
- Lazy init: Semaphore is created on first LLM call, not at import time, to respect runtime config changes.
Reasoning
The simulation makes LLM calls for every NPC decision, story event, and sect thinking each tick. Without concurrency limiting, a world with 100+ avatars could fire hundreds of simultaneous API calls, overwhelming the provider. The semaphore caps this at a configurable level. The dynamic reconfiguration check (`_SEMAPHORE_LIMIT != limit`) ensures that runtime setting changes take effect without requiring a restart.
Code Evidence
Semaphore management from `src/utils/llm/client.py:281-293`:
def _get_semaphore() -> asyncio.Semaphore:
global _SEMAPHORE, _SEMAPHORE_LIMIT
if _SEMAPHORE is None:
limit = get_settings_service().get_llm_runtime_config()[0].max_concurrent_requests
_SEMAPHORE = asyncio.Semaphore(limit)
_SEMAPHORE_LIMIT = limit
return _SEMAPHORE
limit = get_settings_service().get_llm_runtime_config()[0].max_concurrent_requests
if _SEMAPHORE_LIMIT != limit:
_SEMAPHORE = asyncio.Semaphore(limit)
_SEMAPHORE_LIMIT = limit
return _SEMAPHORE
Concurrency limit validation from `src/config/settings_schema.py:47`:
max_concurrent_requests: int = Field(default=10, ge=1, le=50)
World Lore override from `src/systems/world_lore_rewrite/runner.py:145-148`:
max_concurrent = int(getattr(profile, "max_concurrent_requests", 10) or 10)
max_concurrent = 10
return max(8, max_concurrent * 2)