Coverage for app / services / simulator.py: 85%

169 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Simulation runner — sandboxed multi-agent execution with graph state threading. 

3 

4State model 

5----------- 

6``SimulationState`` accumulates the full LangChain message trace across every 

7agent turn in every round. This means: 

8 

9- Agents receive prior synthesis AIMessages as real conversation history (not 

10 truncated text), so the LLM sees proper Human→AI turns from past rounds. 

11- Tool call scaffolding (intermediate AIMessages + ToolMessages) is stored in 

12 state but filtered before passing to the next agent, matching the same 

13 _synthesis_messages pattern used in AgentGraphBuilder. 

14- ToolMessage results are extracted as ``artifacts`` on each RoundResult, so 

15 callers and downstream agents have explicit access to what tools found. 

16 

17Turn-order modes 

18---------------- 

19sequential – agents act in declaration order; each sees all prior-round 

20 synthesis plus the current round's already-completed agents 

21simultaneous – all agents act in parallel on the same prior-round synthesis; 

22 current-round messages are not shared within the round 

23 

24Isolation 

25--------- 

26Each SimulationWorld gets a per-world asyncio.Semaphore (default: 4 concurrent 

27simulations per world). 

28 

29Termination 

30----------- 

311. max_rounds reached (world.rules["max_rounds"], default 5) 

322. Equilibrium detected (identical outputs two rounds in a row; stub) 

333. Unhandled exception → status="failed" 

34""" 

35 

36from __future__ import annotations 

37 

38import asyncio 

39import logging 

40from dataclasses import dataclass, field 

41from typing import Any 

42 

43from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage 

44 

45from opentelemetry import trace as _otel_trace 

46 

47from app.agents.enums import AgentRole 

48from app.agents.factory import SimpleWorkerAgent 

49from app.models.simulation import ( 

50 RoundResult, 

51 SimulationAgentSpec, 

52 SimulationRunRequest, 

53 SimulationRunResult, 

54 SimulationScenarioSpec, 

55 SimulationWorldSpec, 

56) 

57from app.models.spec import ModelConfig 

58from app.services.llm import build_langchain_llm 

59from app.tools.registry import resolve_tool 

60 

61logger = logging.getLogger(__name__) 

62 

63_tracer = _otel_trace.get_tracer(__name__) 

64 

65_WORLD_SEMAPHORES: dict[str, asyncio.Semaphore] = {} 

66_MAX_CONCURRENT_PER_WORLD = 4 

67 

68 

69# ── Semaphore registry ──────────────────────────────────────────────────────── 

70 

71 

72def _world_semaphore(world_id: str) -> asyncio.Semaphore: 

73 if world_id not in _WORLD_SEMAPHORES: 

74 _WORLD_SEMAPHORES[world_id] = asyncio.Semaphore(_MAX_CONCURRENT_PER_WORLD) 

75 return _WORLD_SEMAPHORES[world_id] 

76 

77 

78# ── Simulation state ────────────────────────────────────────────────────────── 

79 

80 

81@dataclass 

82class SimulationState: 

83 """ 

84 Carries state across all rounds of a simulation. 

85 

86 ``messages`` accumulates every BaseMessage produced by every agent turn — 

87 including intermediate AIMessages with tool calls and ToolMessages with 

88 results. Callers filter this list with ``_synthesis_messages`` before 

89 passing it as conversation history to the next agent. 

90 

91 ``context`` is a free-form dict for any inter-agent/inter-round data that 

92 agents write into (e.g. current world state, scores, flags). 

93 """ 

94 

95 world_context: str 

96 messages: list[BaseMessage] = field(default_factory=list) 

97 rounds: list[RoundResult] = field(default_factory=list) 

98 context: dict[str, Any] = field(default_factory=dict) 

99 

100 

101# ── Message helpers ─────────────────────────────────────────────────────────── 

102 

103 

104def _synthesis_messages(messages: list[BaseMessage]) -> list[BaseMessage]: 

105 """ 

106 Filter to final synthesis AIMessages only. 

107 

108 Strips tool-calling scaffolding (intermediate AIMessages with pending 

109 tool_calls and ToolMessages) so downstream agents receive a clean 

110 Human→AI conversation thread without mismatched tool_call_ids. 

111 

112 (The agent graph no longer replays node messages at all: it replays only 

113 the caller's conversation — see ``graph._history_messages``.) 

114 """ 

115 return [ 

116 msg 

117 for msg in messages 

118 if not isinstance(msg, ToolMessage) 

119 and not (isinstance(msg, AIMessage) and getattr(msg, "tool_calls", None)) 

120 ] 

121 

122 

123def _extract_artifacts(messages: list[BaseMessage]) -> list[str]: 

124 """Return the content of every ToolMessage in a message list.""" 

125 return [str(msg.content) for msg in messages if isinstance(msg, ToolMessage)] 

126 

127 

128# ── Agent builder ───────────────────────────────────────────────────────────── 

129 

130 

131def _build_agent(spec: SimulationAgentSpec) -> SimpleWorkerAgent: 

132 model_dict = spec.model or {} 

133 model_cfg = ModelConfig( 

134 provider=model_dict.get("provider", "openai"), # "anthropic"), 

135 model=model_dict.get("model", "gpt-4o"), # "claude-haiku-4-5-20251001"), 

136 temperature=float(model_dict.get("temperature", 0.7)), 

137 max_tokens=int(model_dict.get("max_tokens", 1024)), 

138 system_prompt=spec.system_prompt or "", 

139 ) 

140 llm = build_langchain_llm(model_cfg) 

141 tools = [] 

142 for tc in spec.tools: 

143 try: 

144 tools.append(resolve_tool(tc.get("name", ""), tc.get("config", {}))) 

145 except Exception: 

146 pass 

147 return SimpleWorkerAgent( 

148 name=spec.name, 

149 role=AgentRole.WORKER, 

150 llm=llm, 

151 system_prompt=spec.system_prompt, 

152 tools=tools or None, 

153 ) 

154 

155 

156# ── Context builders ────────────────────────────────────────────────────────── 

157 

158 

159def _world_context( 

160 world: SimulationWorldSpec, 

161 scenario: SimulationScenarioSpec | None, 

162 initial_prompt: str | None, 

163) -> str: 

164 parts: list[str] = [] 

165 if initial_prompt: 

166 parts.append(f"## Task\n{initial_prompt}") 

167 parts.append(f"## World: {world.name}") 

168 if world.description: 

169 parts.append(world.description) 

170 if world.rules: 

171 parts.append(f"Rules: {world.rules}") 

172 if world.logic: 

173 parts.append(f"Logic: {world.logic}") 

174 if scenario: 

175 parts.append(f"\n## Scenario: {scenario.name}") 

176 if scenario.description: 

177 parts.append(scenario.description) 

178 parts.append(f"Strategy: {scenario.strategy}") 

179 if scenario.config: 

180 parts.append(f"Config: {scenario.config}") 

181 return "\n".join(parts) 

182 

183 

184def _build_task( 

185 spec: SimulationAgentSpec, 

186 round_num: int, 

187 world_ctx: str, 

188 prior_rounds: list[RoundResult], 

189) -> str: 

190 """ 

191 Build the HumanMessage task content for an agent's turn. 

192 

193 Prior round outputs are included in full (no truncation) so agents have 

194 complete context. Tool artifacts found in prior rounds are listed 

195 explicitly under each round. The conversation history passed via 

196 ``prior_messages`` already carries the actual message objects, so this 

197 task string is a structured summary that anchors the agent's reasoning 

198 rather than the sole source of truth. 

199 """ 

200 parts = [world_ctx] 

201 

202 if prior_rounds: 

203 parts.append("\n## Round History") 

204 for r in prior_rounds: 

205 parts.append(f"\n### Round {r.round_number}") 

206 for aid, out in r.agent_outputs.items(): 

207 parts.append(f"**Agent {aid[:8]}**: {out}") 

208 for aid, tool_results in r.artifacts.items(): 

209 if tool_results: 

210 artifact_lines = "\n".join(f" - {tr}" for tr in tool_results) 

211 parts.append(f"**Tool findings from {aid[:8]}**:\n{artifact_lines}") 

212 

213 parts.append( 

214 f"\nYou are **{spec.name}** (agent {str(spec.agent_id)[:8]}…). " 

215 f"Your prior outputs and tool results are threaded in the conversation history. " 

216 f"Provide your action/decision for round {round_num}." 

217 ) 

218 return "\n".join(parts) 

219 

220 

221# ── Round execution ─────────────────────────────────────────────────────────── 

222 

223 

224async def _sequential_round( 

225 round_num: int, 

226 specs: list[SimulationAgentSpec], 

227 state: SimulationState, 

228) -> RoundResult: 

229 """ 

230 Sequential turn order. 

231 

232 Each agent sees: 

233 - Synthesis messages from ALL prior rounds (conversation history) 

234 - Synthesis messages from agents that have already acted THIS round 

235 

236 Tool scaffolding (tool_call AIMessages + ToolMessages) is kept in 

237 ``state.messages`` for auditability but excluded from prior_messages so 

238 later agents don't receive mismatched tool_call_ids. 

239 """ 

240 # Clean synthesis view of everything before this round 

241 pre_round_synthesis = _synthesis_messages(state.messages) 

242 

243 agent_outputs: dict[str, str] = {} 

244 agent_artifacts: dict[str, list[str]] = {} 

245 within_round_messages: list[BaseMessage] = [] 

246 

247 for spec in specs: 

248 # Anchor: original world context as the first human message 

249 anchor = [HumanMessage(content=state.world_context)] 

250 # Prior rounds (clean) + current round synthesis so far 

251 prior_messages = ( 

252 anchor + pre_round_synthesis + _synthesis_messages(within_round_messages) 

253 ) 

254 

255 task = _build_task(spec, round_num, state.world_context, state.rounds) 

256 agent = _build_agent(spec) 

257 output, new_messages = await agent.process_with_history(task, prior_messages) 

258 

259 aid = str(spec.agent_id) 

260 agent_outputs[aid] = output 

261 agent_artifacts[aid] = _extract_artifacts(new_messages) 

262 within_round_messages.extend(new_messages) 

263 

264 logger.info( 

265 "Simulation round %d — agent %s done (%d artifact(s))", 

266 round_num, 

267 spec.name, 

268 len(agent_artifacts[aid]), 

269 ) 

270 

271 state.messages.extend(within_round_messages) 

272 

273 return RoundResult( 

274 round_number=round_num, 

275 agent_outputs=agent_outputs, 

276 artifacts=agent_artifacts, 

277 ) 

278 

279 

280async def _simultaneous_round( 

281 round_num: int, 

282 specs: list[SimulationAgentSpec], 

283 state: SimulationState, 

284) -> RoundResult: 

285 """ 

286 Simultaneous turn order. 

287 

288 All agents see the same prior-round synthesis snapshot. Current-round 

289 messages from other agents are NOT visible (they act simultaneously). 

290 """ 

291 anchor = [HumanMessage(content=state.world_context)] 

292 prior_synthesis = anchor + _synthesis_messages(state.messages) 

293 

294 async def run_one(spec: SimulationAgentSpec) -> tuple[str, str, list[BaseMessage]]: 

295 task = _build_task(spec, round_num, state.world_context, state.rounds) 

296 agent = _build_agent(spec) 

297 output, new_messages = await agent.process_with_history(task, prior_synthesis) 

298 return str(spec.agent_id), output, new_messages 

299 

300 all_results = await asyncio.gather(*[run_one(spec) for spec in specs]) 

301 

302 agent_outputs: dict[str, str] = {} 

303 agent_artifacts: dict[str, list[str]] = {} 

304 for aid, output, new_messages in all_results: 

305 agent_outputs[aid] = output 

306 agent_artifacts[aid] = _extract_artifacts(new_messages) 

307 state.messages.extend(new_messages) 

308 logger.info( 

309 "Simulation round %d — agent %s done (%d artifact(s))", 

310 round_num, 

311 aid[:8], 

312 len(agent_artifacts[aid]), 

313 ) 

314 

315 return RoundResult( 

316 round_number=round_num, 

317 agent_outputs=agent_outputs, 

318 artifacts=agent_artifacts, 

319 ) 

320 

321 

322# ── Termination ─────────────────────────────────────────────────────────────── 

323 

324 

325def _should_terminate( 

326 rounds: list[RoundResult], 

327 max_rounds: int, 

328 termination: str, 

329) -> tuple[bool, str]: 

330 if len(rounds) >= max_rounds: 

331 return True, "max_rounds" 

332 if termination in ("max_rounds_or_equilibrium", "equilibrium") and len(rounds) >= 2: 

333 if rounds[-1].agent_outputs == rounds[-2].agent_outputs: 

334 return True, "equilibrium" 

335 return False, "" 

336 

337 

338# ── Main execution ──────────────────────────────────────────────────────────── 

339 

340 

341async def _execute(request: SimulationRunRequest) -> SimulationRunResult: 

342 world_ctx = _world_context(request.world, request.scenario, request.initial_prompt) 

343 max_rounds: int = int(request.world.rules.get("max_rounds", 5)) 

344 turn_order: str = request.world.logic.get("turn_order", "sequential") 

345 termination: str = request.world.logic.get("termination", "max_rounds") 

346 

347 state = SimulationState(world_context=world_ctx) 

348 

349 with _tracer.start_as_current_span("simulation.run") as root_span: 

350 if root_span.is_recording(): 

351 root_span.set_attribute("simulation.id", str(request.simulation_id)) 

352 root_span.set_attribute("simulation.world_id", str(request.world.id)) 

353 root_span.set_attribute("simulation.max_rounds", max_rounds) 

354 root_span.set_attribute("simulation.turn_order", turn_order) 

355 root_span.set_attribute("simulation.termination", termination) 

356 root_span.set_attribute("simulation.agents", len(request.agents)) 

357 

358 try: 

359 for round_num in range(1, max_rounds + 1): 

360 logger.info( 

361 "Simulation %s — round %d/%d (turn_order=%s, messages_so_far=%d)", 

362 request.simulation_id, 

363 round_num, 

364 max_rounds, 

365 turn_order, 

366 len(state.messages), 

367 ) 

368 

369 with _tracer.start_as_current_span("simulation.round") as round_span: 

370 if round_span.is_recording(): 

371 round_span.set_attribute("simulation.round_num", round_num) 

372 round_span.set_attribute("simulation.turn_order", turn_order) 

373 

374 if turn_order == "simultaneous": 

375 result = await _simultaneous_round( 

376 round_num, request.agents, state 

377 ) 

378 else: 

379 result = await _sequential_round( 

380 round_num, request.agents, state 

381 ) 

382 

383 if round_span.is_recording(): 

384 round_span.set_attribute( 

385 "simulation.agent_count", len(result.agent_outputs) 

386 ) 

387 round_span.set_attribute( 

388 "simulation.artifacts", 

389 sum(len(a) for a in result.artifacts.values()), 

390 ) 

391 if result.termination_reason: 

392 round_span.set_attribute( 

393 "simulation.termination_reason", 

394 result.termination_reason, 

395 ) 

396 

397 state.rounds.append(result) 

398 

399 terminated, reason = _should_terminate( 

400 state.rounds, max_rounds, termination 

401 ) 

402 if terminated: 

403 result.terminated = True 

404 result.termination_reason = reason 

405 break 

406 

407 total_artifacts = sum( 

408 len(arts) for r in state.rounds for arts in r.artifacts.values() 

409 ) 

410 summary = ( 

411 f"Completed {len(state.rounds)} round(s) with " 

412 f"{total_artifacts} tool artifact(s) collected." 

413 ) 

414 if state.rounds and state.rounds[-1].termination_reason: 

415 summary += f" Terminated: {state.rounds[-1].termination_reason}." 

416 

417 if root_span.is_recording(): 

418 root_span.set_attribute( 

419 "simulation.completed_rounds", len(state.rounds) 

420 ) 

421 root_span.set_attribute("simulation.total_artifacts", total_artifacts) 

422 

423 return SimulationRunResult( 

424 simulation_id=request.simulation_id, 

425 status="completed", 

426 rounds=state.rounds, 

427 final_summary=summary, 

428 ) 

429 

430 except Exception as exc: 

431 logger.exception("Simulation %s failed", request.simulation_id) 

432 if root_span.is_recording(): 

433 root_span.record_exception(exc) 

434 return SimulationRunResult( 

435 simulation_id=request.simulation_id, 

436 status="failed", 

437 rounds=state.rounds, 

438 error=f"{type(exc).__name__}: {exc}", 

439 ) 

440 

441 

442async def run_simulation(request: SimulationRunRequest) -> SimulationRunResult: 

443 """Run a simulation under the world's concurrency semaphore.""" 

444 sem = _world_semaphore(str(request.world.id)) 

445 async with sem: 

446 return await _execute(request)