"""One official Avalon episode with its unmodified Session and game logic.""" import asyncio import json import os from pathlib import Path import random import time from urllib.request import Request, urlopen import numpy as np from src.server.task import Session from src.server.tasks.avalon import AvalonBench from src.typings import AgentOutput from response_format import SYSTEM_PROMPT, format_kind, validate_answer OUT = Path(os.environ['EPISODE_OUT']) OUT.mkdir(parents=True, exist_ok=False) URL = os.environ['MODEL_URL'].rstrip('/') + '/v1/chat/completions' async def main(): random.seed(7) np.random.seed(7) task = AvalonBench(name='AvalonBench-dev-single', concurrency=1, num_players=5, agent_list=['llm', 'naive', 'naive', 'naive', 'naive'], discussion=False, data_file='data/avalon/dev.json', seed=7) session = Session() index = int(os.environ.get('EPISODE_INDEX', '0')) game = asyncio.create_task(task.start_sample(index, session)) response = None calls = 0 started = time.time() result = {'task': 'avalon-dev-single', 'index': index, 'seed': 7, 'agent_protocol': 'v3: format-only system prompt on structured extraction calls; repetition_penalty=1.1; strict validation; at most 3 attempts', 'scope': 'in-process official game and agent session; separate GPU inference', 'agentbench_commit': 'ed013ff9887b0c3d7864c56ae54d41eba54a99d8'} try: while not game.done(): pull = asyncio.create_task(session.controller.agent_pull(response)) done, _ = await asyncio.wait([pull, game], return_when=asyncio.FIRST_COMPLETED) if game in done: pull.cancel() break output = pull.result() messages = [{'role': 'assistant' if h.role == 'agent' else h.role, 'content': h.content} for h in output.history] kind = format_kind(messages[-1]['content']) if kind is not None: messages.insert(0, {'role': 'system', 'content': 'Format the requested answer from the provided text. Return only the exact ' 'Answer: template with concrete values. No prose, markdown, or code fences.'}) for attempt in range(3): if calls >= 150: raise RuntimeError('Model call limit reached') payload = {'model': 'qwen3-coder-30b-awq', 'messages': messages, 'temperature': 0, 'seed': 7, 'max_tokens': 768, 'repetition_penalty': 1.1} before = time.time() with urlopen(Request(URL, data=json.dumps(payload).encode(), headers={'Content-Type': 'application/json'}), timeout=180) as reply: answer = json.load(reply) calls += 1 choice = answer['choices'][0] content = choice['message']['content'] error = None try: if choice['finish_reason'] != 'stop': raise ValueError('Incomplete model response: ' + choice['finish_reason']) validate_answer(kind, content) except ValueError as exc: error = str(exc) with (OUT / 'model-calls.jsonl').open('a') as stream: stream.write(json.dumps({'call': calls, 'started': before, 'finished': time.time(), 'request': payload, 'response': answer, 'format_kind': kind, 'attempt': attempt + 1, 'validation_error': error}) + '\n') if error is None: response = AgentOutput(content=content) break if attempt == 2: raise RuntimeError('Response format failed after 3 attempts: ' + error) messages = messages + [ {'role': 'assistant', 'content': content or ''}, {'role': 'user', 'content': 'Correct only your response format. ' + error + '. Preserve your chosen values. Return the requested answer and nothing else.'}] result['episode'] = (await game).dict() if result['episode']['status'] != 'completed': raise RuntimeError('Benchmark did not complete: ' + str(result['episode']['status'])) except BaseException as exc: result['error'] = repr(exc) raise finally: game.cancel() result.update(model_calls=calls, elapsed_seconds=time.time()-started) (OUT / 'result.json').write_text(json.dumps(result, indent=2, default=str)) task.release() asyncio.run(main())