Text-Game Action Agent with LLM Retries
Medium · Software Engineering Fundamentals · Machine Learning Engineer · Onsite
Problem Statement
Design and implement the turn-decision wrapper for an LLM-controlled character inside a turn-based text adventure engine. On every turn, the game loop supplies the character's current world state, a chronological log of past turn events, and an LLM client object, and expects back a normalized dictionary describing a single valid move.
Implement get_agent_action(current_state, history, llm_client, max_retries=3) alongside the provided constants MAX_PROMPT_TOKENS = 2000, ALLOWED_ACTIONS = ("move", "use", "talk"), and token estimator count_tokens(text) ((len(text) + 3) // 4):
def get_agent_action(current_state, history, llm_client, max_retries=3):
...
Your implementation must enforce four rules:
- Prompt Token Budgeting (
<= 2000tokens): Every prompt string passed tollm_client.call(prompt)must satisfycount_tokens(prompt) <= MAX_PROMPT_TOKENS(assuming the fixed prompt framing and serializedcurrent_statefit). Includecurrent_stateand keep as many of the most recent contiguous entries fromhistoryas fit in chronological order (oldest kept entry first), dropping older entries from the front when the full log would exceed the budget. - Extraction & Schema Validation:
llm_client.call(prompt)returns raw model output (or may raise a runtime exception). Extract a valid JSON object even when surrounded by conversational text, markdown code fences, or earlier non-action braces/dicts. A JSON object is valid only if:"action"is a string whose whitespace-trimmed, lowercased value is in("move", "use", "talk");"target"is a string that remains non-empty after stripping leading/trailing whitespace;"reasoning", when present, is a string (if omitted, default it to""). Return a clean three-key dictionary{"action": ..., "target": ..., "reasoning": ...}with"action"lowercased and all three strings stripped, discarding any extra keys returned by the model.
- Bounded Retries with Diagnostic Feedback:
max_retriesspecifies the maximum total number of calls tollm_client.callon this turn. Any raised exception fromllm_client.callor any reply that fails extraction/validation consumes one attempt. When a reply fails validation and attempts remain, include brief feedback in the next prompt explaining what failed while still respectingMAX_PROMPT_TOKENS. - Safe Turn Fallback: If all
max_retriesattempts fail (ormax_retries <= 0), return{"action": "pass", "target": "", "reasoning": "<non-crash fallback note>"}so the engine never stalls. Note that"pass"is strictly an engine fallback—if the LLM itself outputs"action": "pass", treat that reply as invalid while retries remain.
Examples
Example 1
Input:
- current_state = {"location": "observatory", "inventory": ["brass_lens"]}
- history = ["Entered the observatory dome.", "Spotted an empty telescope mount."]
- Attempt 1 llm_client.call returns:
'{"action": "use", "target": "telescope mount", "reasoning": "Fit the brass lens into the empty mount."}'
Output:
{"action": "use", "target": "telescope mount", "reasoning": "Fit the brass lens into the empty mount."}
Walk-through: Both history lines and the serialized state fit comfortably under 2000 tokens. The first model response is valid JSON with an allowed action ("use") and a non-empty target ("telescope mount"), so get_agent_action returns immediately after 1 LLM call.
Example 2
Input:
- current_state = {"location": "dockyard", "inventory": ["ferry_ticket"]}
- history = ["Walked onto the pier.", "The harbor captain waved from the gangplank."]
- max_retries = 3
- Attempt 1 returns '{"action": "swim", "target": "island", "reasoning": "Cross the bay."}'
- Attempt 2 returns "Sorry! Valid JSON below:\n```json\n{\"action\": \" TALK \", \"target\": \" harbor captain \", \"extra\": 1}\n```"
Output:
{"action": "talk", "target": "harbor captain", "reasoning": ""}
Walk-through: Attempt 1 is rejected because "swim" is not one of "move", "use", or "talk". Attempt 2 receives validation feedback in the prompt, extracts the JSON dictionary from inside the markdown code fence, normalizes " TALK " to "talk" and " harbor captain " to "harbor captain", supplies "" for the omitted "reasoning" field, and strips out "extra".
Example 3
Input:
- current_state = {"location": "cellar", "inventory": []}
- history = ["Descended the stone steps."]
- max_retries = 2
- Attempt 1 raises TimeoutError("request timed out")
- Attempt 2 returns 'not valid json'
Output:
{"action": "pass", "target": "", "reasoning": "No valid action after retries; passing this turn."}
Walk-through: Both permitted calls fail (one network timeout and one unparseable string), exhausting max_retries = 2, so the function returns the "pass" fallback action with target = "".
Constraints
current_stateis a JSON-serializabledictwhose serialized size plus prompt instructions fits withinMAX_PROMPT_TOKENS = 2000tokens.historyis alist[str]of0to10,000chronological event strings (oldest at index0).count_tokens(text)is defined as(len(text) + 3) // 4.0 <= max_retries <= 10represents the maximum total calls allowed tollm_client.call.- Allowed model actions are strictly
"move","use", and"talk"(case-insensitive before normalization).
Step-by-step walkthrough
Restate the problem and pin down the contract
get_agent_actionsits between a strict game engine and an unpredictable large language model (LLM). On every turn of the adventure game, the engine hands you the NPC'scurrent_stateand pasthistory, and expects back one clean Python dictionary ({"action": ..., "target": ..., "reasoning": ...}) without ever hanging or crashing.Before writing code, clarify three edge rules with your interviewer:
- What
max_retries=3counts:max_retries=3sets the upper bound of 3 total LLM calls per turn before falling back to"pass". "pass"is reserved for the fallback: The LLM's allowed actions are strictly"move","use", and"talk". If the LLM itself outputs"pass", we reject it as an invalid model choice so the model tries to pick a real game move while attempts remain.- How tokens are counted: A token is a sub-word chunk of text (roughly 4 English characters on average) that LLMs read and bill by. In a self-contained sandbox without an external tokenizer package,
count_tokens(text) = (len(text) + 3) // 4computesceiling(len(text) / 4). In production, you swap in the model's exact tokenizer without changing any surrounding logic.
- What
Why a naive one-liner breaks in production
A beginner's first instinct is
return json.loads(llm_client.call(str(current_state) + str(history))). That one-liner fails in four realistic ways:- Context overflow: Every LLM has a fixed context window (maximum input + output token limit). After 500 game events (~13 tokens each), the history alone hits 6,500 tokens—far past our 2,000-token limit.
- Conversational wrappers: Helpful chat models love replying
"Sure! Here is my move:\n```json\n{...}\n```", which crashesjson.loadsimmediately. - Hallucinated actions or types:
{"action": "attack", "target": ""}is valid JSON, yet"attack"is outside("move", "use", "talk")and an empty"target"gives the game engine nothing to act on. - API exceptions: Network timeouts and HTTP 429 rate limits raise exceptions from
llm_client.call.
We solve these cleanly by splitting the pipeline into three small helpers:
build_prompt(context budgeting),parse_action(extraction + schema validation), andget_agent_action(bounded retries with error feedback + fallback).Anchor output format with schema instructions and few-shot examples
The cheapest retry is the one you prevent up front. Including few-shot examples—two concrete sample outputs right inside the instructions—steers an LLM much more reliably than prose rules alone, because models naturally mirror the exact key names, quoting, and lack of markdown fences they see.
Notice that our examples use
"move"and"talk"on generic targets ("north","innkeeper") distinct from the observatory/dockyard samples, teaching the structure without biasing the character toward a specific turn choice:MAX_PROMPT_TOKENS = 2000 ALLOWED_ACTIONS = ("move", "use", "talk") # Safe default returned only after all LLM attempts fail; never accepted from the LLM itself. FALLBACK_ACTION = { "action": "pass", "target": "", "reasoning": "No valid action after retries; passing this turn.", } # System-style instructions with explicit schema and two few-shot examples to anchor output format. INSTRUCTIONS = """You control a character in a text adventure game. Choose the character's next action. Reply with exactly one JSON object and nothing else, in this format: {"action": "move" | "use" | "talk", "target": "<what the action applies to>", "reasoning": "<one short sentence>"} Examples of valid replies: {"action": "move", "target": "north", "reasoning": "The river is to the north."} {"action": "talk", "target": "innkeeper", "reasoning": "She may know where the map is."}"""Fit history into the token budget with a reverse sliding window
A sliding window keeps only the most recent slice of a growing list. In a game, what happened 10 seconds ago ("Spotted an empty telescope mount.") matters far more for the next turn than what happened 400 turns ago, so we keep the newest events and drop the oldest.
Prompt layout (must stay <= 2000 tokens total): +-------------------------------------------------------------------+ | head: INSTRUCTIONS + Current state JSON + "Recent events..." | <- fixed, always kept +-------------------------------------------------------------------+ | marker: "- (359 earlier events omitted)\n" (only if omitted > 0) | <- tells LLM history was cut +-------------------------------------------------------------------+ | kept: newest contiguous events, restored to oldest-first order | <- fills remaining budget +-------------------------------------------------------------------+ | tail: optional retry error feedback + "\nYour JSON reply:" | <- fixed, always kept +-------------------------------------------------------------------+To pack as many recent events as possible without ever exceeding
2000tokens:- Compute
available_tokens = 2000 - count_tokens(head) - count_tokens(tail). - Walk
reversed(history)(newest to oldest), adding lines whileused_tokens + line_cost <= available_tokens. Break on the first line that does not fit—never skip over a long event to include an older short one, or the timeline would have confusing gaps. - If all events fit (
omitted_count == 0), we need no marker at all! If some events were omitted (omitted_count > 0), check whether adding"- (N earlier events omitted)\n"fits in the leftover tokens; if not, pop the oldest kept event until the marker fits too.
Check the exact numbers on 500 events shaped like
"Turn #0000: the explorer checked the brass dial."(48 characters each):head (instructions + observatory state) = 570 chars -> ceil(570 / 4) = 143 tokens tail ("\nYour JSON reply:") = 17 chars -> ceil( 17 / 4) = 5 tokens available_tokens = 2000 - 143 - 5 = 1852 tokens each formatted line "- Turn ... \n" = 51 chars -> ceil( 51 / 4) = 13 tokens phase 1 keeps floor(1852 / 13) = 142 newest events (#0358..#0499), using 1846 tokens (6 left) phase 2 pops #0358 to fit 8-tok marker = 141 newest events (#0359..#0499), using 1833 + 8 = 1841 tokens assembled prompt = 7809 chars -> ceil(7809 / 4) = 1953 tokens <= 2000Why can't concatenating the pieces ever jump above the sum of their token counts here? Because for non-negative integers
aandb,ceil((a + b) / 4) <= ceil(a / 4) + ceil(b / 4).def count_tokens(text: str) -> int: """Rough token count used for the budget: ceiling(len(text) / 4).""" return (len(text) + 3) // 4 def omitted_marker(count: int) -> str: return f"- ({count} earlier events omitted)\n" def build_prompt(current_state: Dict, history: List[str], feedback: str = "") -> str: """Assemble instructions, state, newest fitting history window, and optional retry feedback.""" head = ( INSTRUCTIONS + "\n\nCurrent state: " + json.dumps(current_state, sort_keys=True, default=str) + "\n\nRecent events, oldest first:\n" ) tail = "" if feedback: tail += ( "\nYour previous reply was rejected: " + feedback + "\nAnswer again with only the JSON object.\n" ) tail += "\nYour JSON reply:" available_tokens = MAX_PROMPT_TOKENS - count_tokens(head) - count_tokens(tail) # Phase 1: Walk history from newest to oldest, keeping a contiguous block of recent events. # kept_newest_first: list of formatted "- <event>\n" lines ordered from newest to oldest. kept_newest_first: List[str] = [] used_tokens = 0 for entry in reversed(history): line = "- " + entry + "\n" line_cost = count_tokens(line) # Stop at the first event that overflows so we never leave temporal gaps in the story. if used_tokens + line_cost > available_tokens: break kept_newest_first.append(line) used_tokens += line_cost # Phase 2: If older events were dropped, make room for the "- (N earlier events omitted)" marker. omitted_count = len(history) - len(kept_newest_first) marker = "" if omitted_count > 0: while kept_newest_first: omitted_count = len(history) - len(kept_newest_first) if used_tokens + count_tokens(omitted_marker(omitted_count)) <= available_tokens: break # Pop the oldest kept line (at the end of kept_newest_first) until the marker fits too. oldest_kept_line = kept_newest_first.pop() used_tokens -= count_tokens(oldest_kept_line) omitted_count = len(history) - len(kept_newest_first) candidate_marker = omitted_marker(omitted_count) # Guard against a huge current_state leaving < 8 tokens total: never let the marker overflow 2000. if used_tokens + count_tokens(candidate_marker) <= available_tokens: marker = candidate_marker kept_chronological = list(reversed(kept_newest_first)) return head + marker + "".join(kept_chronological) + tail- Compute
Extract and validate JSON replies against the action whitelist
Even with few-shot examples, an LLM might wrap its JSON in markdown backticks, echo
{action, target}or a helper object like{"zone": "observatory"}in prose before its real answer, or invent"action": "swim".Python's
json.JSONDecoder().raw_decode(reply, start)is purpose-built for this: starting at indexstart, it parses exactly one complete JSON value and ignores any text after the closing}. By scanning every"{"inreplyand checking each parsed dictionary withvalidate_action_object, we accept the first dictionary that satisfies the full schema and otherwise return a clear diagnostic string for the next retry:Model reply parse_action outcome --------------------------------------------------------- ----------------------------------------------------- 'Sorry!\n```json\n{"action":"TALK","target":"captain"}\n```' Valid -> {"action":"talk","target":"captain","reasoning":""} 'Context {"zone":"observatory"} -> {"action":"move",...}' 1st "{" lacks action, 2nd "{" valid -> accepted! '{"action": "use", "target": "telescope mount"' Rejected -> "invalid JSON (Expecting ',' delimiter)" '{"action": "swim", "target": "island"}' Rejected -> "action 'swim' is not one of move, use, talk" '{"action": "use", "target": " "}' Rejected -> "target must be a non-empty string"def validate_action_object(data: Dict) -> Tuple[Optional[Dict[str, str]], str]: """Validate and normalize one parsed JSON dictionary against the game engine's action schema.""" raw_action = data.get("action") if not isinstance(raw_action, str) or raw_action.strip().lower() not in ALLOWED_ACTIONS: return None, f"action {repr(raw_action)[:40]} is not one of move, use, talk" raw_target = data.get("target") if not isinstance(raw_target, str) or not raw_target.strip(): return None, "target must be a non-empty string" # Missing reasoning defaults to ""; non-string reasoning (e.g. an int or list) is rejected. raw_reasoning = data.get("reasoning", "") if not isinstance(raw_reasoning, str): return None, "reasoning must be a string" # Build a fresh 3-key dict so hallucinated extra keys never leak into the game engine. clean_action = { "action": raw_action.strip().lower(), "target": raw_target.strip(), "reasoning": raw_reasoning.strip(), } return clean_action, "" def parse_action(reply) -> Tuple[Optional[Dict[str, str]], str]: """Extract the first valid action JSON object from reply, or return (None, reason) for retry feedback.""" if not isinstance(reply, str): return None, "the reply was not text" decoder = json.JSONDecoder() first_action_error = "" first_json_error = "" first_other_error = "" # Scan every '{' so prose braces, echoed templates, or helper dicts before the real answer are skipped. start = reply.find("{") while start != -1: try: # raw_decode parses one JSON object starting at `start` and ignores trailing prose/code fences. data, _ = decoder.raw_decode(reply, start) clean_action, error = validate_action_object(data) if clean_action is not None: return clean_action, "" if "action" in data and not first_action_error: first_action_error = error elif not first_other_error: first_other_error = error except json.JSONDecodeError as exc: if not first_json_error: first_json_error = f"invalid JSON ({exc.msg})" start = reply.find("{", start + 1) best_error = first_action_error or first_json_error or first_other_error or "no JSON object found" return None, best_errorClose the loop with error-feedback retries and a pass fallback
If you retry a failed LLM call with the exact same prompt, a low-temperature model will often make the exact same mistake three times in a row. Appending
feedback("Your previous reply was rejected: action 'run' is not one of move, use, talk") tells the model specifically what broke—and becausebuild_promptsubtractscount_tokens(tail)before filling history, even retry prompts stay strictly within2000tokens.Two small safeguards complete
get_agent_action: - Wrap onlyllm_client.call(prompt)intry / except Exceptionso network timeouts use up one attempt without hiding bugs in your own Python code. - Returndict(FALLBACK_ACTION)(a fresh shallow copy) when retries run out so a caller that mutates the returned dictionary cannot corruptFALLBACK_ACTIONfor later turns.def get_agent_action(current_state, history, llm_client, max_retries=3): """Ask the LLM for the NPC's next action (up to max_retries calls) with a guaranteed 'pass' fallback.""" feedback = "" for _ in range(max_retries): prompt = build_prompt(current_state, history, feedback) try: reply = llm_client.call(prompt) except Exception: # Network timeouts or rate limits consume one attempt; preserve prior feedback for next try. continue action, error = parse_action(reply) if action is not None: return action # Feed the exact validation failure into the next prompt so the model can self-correct. feedback = error # Return a shallow copy so caller mutations never corrupt the module-level constant. return dict(FALLBACK_ACTION)Trace both a clean turn and a three-strike fallback
Happy path (Example 1):
current_statehas"observatory"and["brass_lens"], andhistoryhas 2 short events (omitted_count == 0, no marker added). Attempt 1 returns'{"action": "use", "target": "telescope mount", "reasoning": "Fit the brass lens into the empty mount."}',parse_actionvalidates all three fields, andget_agent_actionreturns after 1 call.Three-strike failure trace (
max_retries=3):Attempt What happens inside the loop Result of attempt ------- -------------------------------------------------------------------- --------------------------------- 1 feedback = "" LLM replies: '{"action": "use", "target": "telescope mount"' Rejected -> feedback set to "invalid JSON (Expecting ...)" 2 Prompt includes: "Your previous reply was rejected: invalid JSON..." LLM replies: '{"action": "swim", "target": "island"}' Rejected -> feedback set to "action 'swim' is not one of..." 3 Prompt includes: "Your previous reply was rejected: action 'swim'..." llm_client.call raises TimeoutError("slow") Caught -> loop ends after 3 tries Return {"action": "pass", "target": "", "reasoning": "No valid action after retries; passing this turn."}Complete solution
from typing import Dict, List, Optional, Tuple import json MAX_PROMPT_TOKENS = 2000 ALLOWED_ACTIONS = ("move", "use", "talk") # Safe default returned only after all LLM attempts fail; never accepted from the LLM itself. FALLBACK_ACTION = { "action": "pass", "target": "", "reasoning": "No valid action after retries; passing this turn.", } # System-style instructions with explicit schema and two few-shot examples to anchor output format. INSTRUCTIONS = """You control a character in a text adventure game. Choose the character's next action. Reply with exactly one JSON object and nothing else, in this format: {"action": "move" | "use" | "talk", "target": "<what the action applies to>", "reasoning": "<one short sentence>"} Examples of valid replies: {"action": "move", "target": "north", "reasoning": "The river is to the north."} {"action": "talk", "target": "innkeeper", "reasoning": "She may know where the map is."}""" def count_tokens(text: str) -> int: """Rough token count used for the budget: ceiling(len(text) / 4).""" return (len(text) + 3) // 4 def omitted_marker(count: int) -> str: return f"- ({count} earlier events omitted)\n" def build_prompt(current_state: Dict, history: List[str], feedback: str = "") -> str: """Assemble instructions, state, newest fitting history window, and optional retry feedback.""" head = ( INSTRUCTIONS + "\n\nCurrent state: " + json.dumps(current_state, sort_keys=True, default=str) + "\n\nRecent events, oldest first:\n" ) tail = "" if feedback: tail += ( "\nYour previous reply was rejected: " + feedback + "\nAnswer again with only the JSON object.\n" ) tail += "\nYour JSON reply:" available_tokens = MAX_PROMPT_TOKENS - count_tokens(head) - count_tokens(tail) # Phase 1: Walk history from newest to oldest, keeping a contiguous block of recent events. # kept_newest_first: list of formatted "- <event>\n" lines ordered from newest to oldest. kept_newest_first: List[str] = [] used_tokens = 0 for entry in reversed(history): line = "- " + entry + "\n" line_cost = count_tokens(line) # Stop at the first event that overflows so we never leave temporal gaps in the story. if used_tokens + line_cost > available_tokens: break kept_newest_first.append(line) used_tokens += line_cost # Phase 2: If older events were dropped, make room for the "- (N earlier events omitted)" marker. omitted_count = len(history) - len(kept_newest_first) marker = "" if omitted_count > 0: while kept_newest_first: omitted_count = len(history) - len(kept_newest_first) if used_tokens + count_tokens(omitted_marker(omitted_count)) <= available_tokens: break # Pop the oldest kept line (at the end of kept_newest_first) until the marker fits too. oldest_kept_line = kept_newest_first.pop() used_tokens -= count_tokens(oldest_kept_line) omitted_count = len(history) - len(kept_newest_first) candidate_marker = omitted_marker(omitted_count) # Guard against a huge current_state leaving < 8 tokens total: never let the marker overflow 2000. if used_tokens + count_tokens(candidate_marker) <= available_tokens: marker = candidate_marker kept_chronological = list(reversed(kept_newest_first)) return head + marker + "".join(kept_chronological) + tail def validate_action_object(data: Dict) -> Tuple[Optional[Dict[str, str]], str]: """Validate and normalize one parsed JSON dictionary against the game engine's action schema.""" raw_action = data.get("action") if not isinstance(raw_action, str) or raw_action.strip().lower() not in ALLOWED_ACTIONS: return None, f"action {repr(raw_action)[:40]} is not one of move, use, talk" raw_target = data.get("target") if not isinstance(raw_target, str) or not raw_target.strip(): return None, "target must be a non-empty string" # Missing reasoning defaults to ""; non-string reasoning (e.g. an int or list) is rejected. raw_reasoning = data.get("reasoning", "") if not isinstance(raw_reasoning, str): return None, "reasoning must be a string" # Build a fresh 3-key dict so hallucinated extra keys never leak into the game engine. clean_action = { "action": raw_action.strip().lower(), "target": raw_target.strip(), "reasoning": raw_reasoning.strip(), } return clean_action, "" def parse_action(reply) -> Tuple[Optional[Dict[str, str]], str]: """Extract the first valid action JSON object from reply, or return (None, reason) for retry feedback.""" if not isinstance(reply, str): return None, "the reply was not text" decoder = json.JSONDecoder() first_action_error = "" first_json_error = "" first_other_error = "" # Scan every '{' so prose braces, echoed templates, or helper dicts before the real answer are skipped. start = reply.find("{") while start != -1: try: # raw_decode parses one JSON object starting at `start` and ignores trailing prose/code fences. data, _ = decoder.raw_decode(reply, start) clean_action, error = validate_action_object(data) if clean_action is not None: return clean_action, "" if "action" in data and not first_action_error: first_action_error = error elif not first_other_error: first_other_error = error except json.JSONDecodeError as exc: if not first_json_error: first_json_error = f"invalid JSON ({exc.msg})" start = reply.find("{", start + 1) best_error = first_action_error or first_json_error or first_other_error or "no JSON object found" return None, best_error def get_agent_action(current_state, history, llm_client, max_retries=3): """Ask the LLM for the NPC's next action (up to max_retries calls) with a guaranteed 'pass' fallback.""" feedback = "" for _ in range(max_retries): prompt = build_prompt(current_state, history, feedback) try: reply = llm_client.call(prompt) except Exception: # Network timeouts or rate limits consume one attempt; preserve prior feedback for next try. continue action, error = parse_action(reply) if action is not None: return action # Feed the exact validation failure into the next prompt so the model can self-correct. feedback = error # Return a shallow copy so caller mutations never corrupt the module-level constant. return dict(FALLBACK_ACTION)✅ Submit now — all tests should pass.
Intuition & how it works
Think of get_agent_action as a strict translator standing between an imaginative storyteller (the LLM) and a rigid vending machine (the game engine). The LLM reads text measured in tokens (small chunks of roughly 4 characters) up to a hard context window (the maximum input size it can accept at once), so we pack the newest game events using a sliding window (a moving slice that keeps recent items and drops the oldest) and check every reply with schema validation (verifying exact field names, data types, and allowed values before letting data through).
The naive approach concatenates the entire history into one string and calls json.loads(llm_client.call(prompt)). That fails quickly: long games exceed the 2,000-token limit, chatty replies like Sure! ```json {...} ``` crash json.loads, invented actions like "fly" break the game engine, and network errors or repeated bad replies can hang the game forever.
Follow a tiny 4-event trace to see how the three safeguards cooperate:
- Budgeting: Suppose fixed instructions +
current_state+ closing prompt cost148tokens, leaving1,852tokens out of2,000. Ifhistoryhas 4 events costing[900, 900, 400, 400]tokens from oldest to newest, scanning backward keeps the newest three (400 + 400 + 900 = 1,700 <= 1,852) and prepends"- (1 earlier events omitted)"(8tokens), using1,708of the1,852history budget (1,856 <= 2,000total tokens). - Self-correcting retry: If attempt 1 replies
'{"action": "swim", "target": "island"}',parse_actionrejects"swim"and attempt 2 appends"Your previous reply was rejected: action 'swim' is not one of move, use, talk". - Guaranteed termination: If attempt 2 replies
'```json\n{"action": " TALK ", "target": " harbor captain "}\n```',raw_decodeextracts the JSON inside the fence and normalizes it to{"action": "talk", "target": "harbor captain", "reasoning": ""}; if all attempts fail,get_agent_actionreturns{"action": "pass", ...}so the game never stalls.
Complexity
- Time: Building the prompt and parsing the reply takes
O(max_retries * (S + B + L + R^2))Python work, whereSis the serializedcurrent_statesize,Bis the character budget (~8,000chars for 2,000 tokens),Lis the length of the first history entry that does not fit, andRis the model reply length. Because the reverse loop stops at the first overflowing event, it never scans a 100,000-turn history from start to finish;raw_decodescans the reply once (O(R)) in the common case where the first"{"is the action object, and at worstO(R^2)if a short reply contains many stray"{"characters. In real life, network latency tollm_client.calldominates wall-clock runtime. - Space:
O(S + B + R)memory to hold the assembled prompt string, the kept slice of recent history lines, and the current reply string. No extra state is retained across turns.
Edge cases
- All history fits (
omitted_count == 0): Every event is included in oldest-to-newest order and no"earlier events omitted"line is inserted, saving those 7–8 tokens for actual events. - Single newest event exceeds remaining budget:
kept_newest_firststays empty and only the omitted-events marker appears (unlesscurrent_stateitself left fewer than 8 tokens, in which case the marker is skipped too so the prompt still stays<= 2000tokens). max_retries <= 0: Zero LLM calls are made and a copy ofFALLBACK_ACTION("pass") is returned immediately.- Markdown fences, prose braces, or helper JSON before the answer: Scanning every
"{"withJSONDecoder().raw_decodeskips invalid{traveler}text and non-action dictionaries like{"zone": "observatory"}to find the valid action dictionary later in the reply. - Model outputs
"action": "pass": Rejected during retries because"pass"is not inALLOWED_ACTIONS; only exhaustingmax_retriestriggers"pass". - Real BPE tokenizers: A BPE (Byte-Pair Encoding) tokenizer (the sub-word vocabulary splitter used by modern LLMs) can merge characters across string boundaries or use more tokens per character on non-Latin scripts and JSON punctuation, so production code should verify
tokenizer.encode(prompt)on the final string.
Common mistakes
- Truncating by event count (
history[-20:]) instead of token count: Twenty unusually long room descriptions can easily blow past 2,000 tokens. - Slicing the finished prompt string (
prompt[:8000]): Chopping the end of the prompt deletes the newest events and the closing JSON instruction! - Forgetting to count instructions,
current_state, and retryfeedbackagainst the 2,000-token cap: Every character sent tollm_client.callconsumes context budget. - Retrying with an identical prompt: Without telling the model why its previous reply failed, deterministic or low-temperature decoding repeats the exact same invalid output.
- Using a bare
try ... except:around the whole loop body: Catching exceptions outsidellm_client.callsilently masksTypeErrororNameErrorbugs in your own validation code. - Trying to "fix" broken JSON with
eval(): Never runeval()on untrusted model output; usejson.JSONDecoder().raw_decodeand retry cleanly.
Alternative approaches
- Periodic memory summarization: Instead of forgetting old events completely once they fall off the sliding window, ask an LLM every
Nturns to compress evicted events into a short bulleted memory block ("Facts so far: unlocked cellar; innkeeper mentioned a hidden key"). This preserves long-horizon clues at the cost of extra background token spend and occasional summary drift. - Constrained decoding (structured outputs): Many LLM serving engines can mask logits during generation so tokens must follow a strict JSON Schema (
enum: ["move", "use", "talk"]). That eliminates syntax errors and invalid action names, though you still needtry/exceptand the"pass"fallback for network timeouts, max-token cutoffs, and safety refusals.
Follow-up questions
- Which telemetry metrics would you collect to evaluate agent quality and trade off token spend against valid turn completion? Log each turn's attempt count, prompt/completion tokens, latency, validation errors, whether the game engine accepted the move as physically possible, and quest outcomes. Track first-try valid rate, mean calls per turn, fallback (
pass) rate, world-illegal action rate (e.g.,"use telescope mount"when no telescope mount is in the room), tokens per valid turn, and tokens per completed quest. For example, if 1,000 turns produce 940 first-try successes, 45 second-try successes, 10 third-try successes, and 5"pass"fallbacks, you made940*1 + 45*2 + 10*3 + 5*3 = 1,075calls (1.075calls/turn) for995valid actions; at1,950tokens per call, that is1,075 * 1,950 / 995 ≈ 2,107tokens per valid action. SweepingMAX_PROMPT_TOKENSacross500,1,000, and2,000lets you plot quest completion rate against token cost to find the knee of the curve. - Suppose the serialized world state itself grows beyond the prompt budget—how would you surface only task-relevant state to the model? Split the prompt budget into explicit sub-budgets—for example, 300 tokens for instructions, 700 for local state, 500 for retrieved world memory, and 500 for recent history. Always include the immediate local state (current room, visible exits/NPCs, carried inventory), and store distant rooms, lore, and quest logs in an external index retrieved by keyword + embedding similarity (matching numerical meaning vectors to the current room and active goal). Alternatively, expose read-only agent actions like
inspect_inventoryorrecall_roomso the model pulls extra state on demand, and include a marker like"(14 distant rooms omitted)"so the model knows its view is partial. - How would you design an offline regression harness so swapping in a newer model checkpoint cannot silently hurt gameplay? Build a two-tier offline benchmark: (1) a frozen dataset of 200+ single-turn
(state, history, acceptable_actions)snapshots covering tricky cases like locked doors, distractors, and long histories, and (2) end-to-end seeded playthroughs in a deterministic game simulator measuring quest completion rate and turns-to-win. Run both the current and candidate models on the exact same scenarios and check confidence intervals—ranges showing how much a score can wobble from finite sample size alone. On 200 scenarios around an 85% pass rate, the standalone 95% margin of error is1.96 * sqrt(0.85 * 0.15 / 200) ≈ ±4.9percentage points, so use paired per-scenario comparisons (checking specifically which scenarios flipped from pass to fail) and block deployment if schema validity, fallback rate, or quest completion regresses past a pre-set threshold.
Follow-up questions
- Which telemetry metrics would you collect to evaluate agent quality and trade off token spend against valid turn completion?
- Suppose the serialized world state itself grows beyond the prompt budget—how would you surface only task-relevant state to the model?
- How would you design an offline regression harness so swapping in a newer model checkpoint cannot silently hurt gameplay?
Similar questions
- Payment Card Input Controller with Cross-Field Validation
- Migrate a Rule-Based CLI Text Game to LLM Control
- Multi-Source Enterprise Question Answering System
- Critiquing and Defending Your Published ML Research
- Largest Value After Removing One '5'
- End-to-End Post-Training Architecture for a 7B Enterprise Coding Model
More Cohere interview questions
- Multi-Source Enterprise Question Answering System Medium
- Payment Card Input Controller with Cross-Field Validation Medium
- Critiquing and Defending Your Published ML Research Medium Pro
- Largest Value After Removing One '5' Medium Pro
- Teaching an LLM to Handle Post-Cutoff Questions Medium Pro
- Live Comment Threads with Optimistic Client Writes Medium Pro
- End-to-End Post-Training Architecture for a 7B Enterprise Coding Model Medium Pro
- Front-End Architecture for a Live Comment Feed with Optimistic Rendering Medium Pro
- From Pre-Training to Alignment: The LLM Lifecycle Medium Pro
- Top-k and Nucleus (Top-p) Probability Filtering Medium Pro