# Turn a blunder into a puzzle Make a puzzle from the position right after a blunder. Engine finds the one winning reply and checks it is the only one, and Knight writes a hint. A puzzle from a real game: the position right after a blunder, where the player to move has exactly one move that wins. It is a [Recipe](/docs/recipes): copy it, then change the checks and the hint to suit your app. **Calls:** one Engine call to find and check the solution, and one Generate call on Knight for the hint, about $0.0028 a puzzle. ## The puzzle Start from a blunder you already know about, such as one that [Review a game](/docs/recipes/review-a-game) or [Grade a game's accuracy](/docs/recipes/game-accuracy) found. The puzzle is the position right after it, sent as the game's PGN and the `ply` after the blunder. 1. **Engine once, with `lines` 2.** One call answers both questions: the top Line is the solution, and the second Line says whether anything else works too. `depth` 16 is enough to check a tactic, for a fraction of depth 20's Engine time. 2. **Turn both Lines into win chances** for the player to move, from −1 to +1, the way [Review a game](/docs/recipes/review-a-game) does: `2 / (1 + exp(−0.00368208 × cp)) − 1`, ±1 for a mate, and the sign flipped when Black is to move. 3. **Keep it only if one move wins:** the top Line at 0.5 or more, and the second Line at least 0.3 behind it. A position with two winning moves, or with only one legal move, makes a poor puzzle. 4. **Generate on Knight for a hint**, given the solution and told not to name it, so the solver gets a nudge rather than the answer. This checks the first move only. For a puzzle of several moves, run the same check again at each of the solver's later moves, one more Engine call each. The game below falls into the Elephant trap: White's 6.Nxd5 looks like it wins a pawn, but 6...Nxd5 7.Bxd8 Bb4+ 8.Qd2 Kxd8 wins Black a piece. The curl tab shows the two calls; the Python and JavaScript tabs check the puzzle and print it. **Reading the response:** the answer is Engine's `lines[0].moves[0]`; once the solver finds it, play out the rest of that Line to show why it works. Knight's `lines` should be empty, since the hint names no move. If it isn't, the hint gives the answer away: ask again, or show the puzzle without one. ```text System prompt You write hints for chess puzzles. You are given the puzzle's solution. In one or two sentences, point the solver at the idea without naming the winning move, the piece that plays it or the square it goes to. Never show any moves. ``` ```bash curl # Engine on the position after 6.Nxd5 (ply 11), with the two best Lines. curl https://api.chessdrive.io/v1/engine \ -H "Authorization: Bearer $CHESSDRIVE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "engine": "stockfish", "position": { "pgn": "1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. cxd5 exd5 6. Nxd5", "ply": 11 }, "depth": 16, "lines": 2 }' # Only 6...Nxd5 wins, so Knight writes the hint. curl https://api.chessdrive.io/v1/generate \ -H "Authorization: Bearer $CHESSDRIVE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "knight-1", "system": "You write hints for chess puzzles. You are given the puzzle'\''s solution.\nIn one or two sentences, point the solver at the idea without naming the winning move, the piece that plays it or the square it goes to.\nNever show any moves.", "position": { "pgn": "1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. cxd5 exd5 6. Nxd5", "ply": 11 }, "messages": [{ "role": "user", "content": "The solution is Nxd5 Bxd8 Bb4+ Qd2 Kxd8. Write the hint." }] }' ``` ```python Python import math import os import requests API = "https://api.chessdrive.io/v1" HEADERS = {"Authorization": f"Bearer {os.environ['CHESSDRIVE_API_KEY']}"} # The position right after the blunder, 6.Nxd5: Black to move. POSITION = {"pgn": "1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. cxd5 exd5 6. Nxd5", "ply": 11} HINT = """You write hints for chess puzzles. You are given the puzzle's solution. In one or two sentences, point the solver at the idea without naming the winning move, the piece that plays it or the square it goes to. Never show any moves.""" def post(path, body): r = requests.post(f"{API}/{path}", headers=HEADERS, json=body) r.raise_for_status() return r.json() def win_chance(line): """White's chance from -1 to +1, as Lichess computes it.""" if line["mate"] is not None: return 1 if line["mate"] > 0 else -1 return 2 / (1 + math.exp(-0.00368208 * line["cp"])) - 1 analysis = post("engine", {"engine": "stockfish", "position": POSITION, "depth": 16, "lines": 2}) side = 1 if analysis["fen"].split()[1] == "w" else -1 chances = [side * win_chance(line) for line in analysis["lines"]] if len(chances) < 2 or chances[0] < 0.5 or chances[0] - chances[1] < 0.3: print("not a puzzle: no single winning move") else: solution = " ".join(m["san"] for m in analysis["lines"][0]["moves"][:5]) hint = post("generate", { "model": "knight-1", "system": HINT, "position": POSITION, "messages": [{"role": "user", "content": f"The solution is {solution}. Write the hint."}], }) print("puzzle:", analysis["fen"]) print("hint:", hint["content"] if not hint["lines"] else "(none: it named a move)") print("solution:", solution) ``` ```js JavaScript const API = "https://api.chessdrive.io/v1"; // The position right after the blunder, 6.Nxd5: Black to move. const POSITION = { pgn: "1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. cxd5 exd5 6. Nxd5", ply: 11 }; const HINT = `You write hints for chess puzzles. You are given the puzzle's solution. In one or two sentences, point the solver at the idea without naming the winning move, the piece that plays it or the square it goes to. Never show any moves.`; async function post(path, body) { const res = await fetch(`${API}/${path}`, { method: "POST", headers: { Authorization: `Bearer ${process.env.CHESSDRIVE_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(body), }); if (!res.ok) throw new Error(await res.text()); return res.json(); } // White's chance from -1 to +1, as Lichess computes it. const winChance = (line) => line.mate !== null ? Math.sign(line.mate) : 2 / (1 + Math.exp(-0.00368208 * line.cp)) - 1; const analysis = await post("engine", { engine: "stockfish", position: POSITION, depth: 16, lines: 2 }); const side = analysis.fen.split(" ")[1] === "w" ? 1 : -1; const chances = analysis.lines.map((line) => side * winChance(line)); if (chances.length < 2 || chances[0] < 0.5 || chances[0] - chances[1] < 0.3) { console.log("not a puzzle: no single winning move"); } else { const solution = analysis.lines[0].moves.slice(0, 5).map((m) => m.san).join(" "); const hint = await post("generate", { model: "knight-1", system: HINT, position: POSITION, messages: [{ role: "user", content: `The solution is ${solution}. Write the hint.` }], }); console.log("puzzle:", analysis.fen); console.log("hint:", hint.lines.length ? "(none: it named a move)" : hint.content); console.log("solution:", solution); } ``` ```json Engine response { "id": "req_01M4G7P2K8DX5R3NW9TQ6BHE4J", "engine": "stockfish", "version": "Stockfish 19", "network": null, "fen": "r1bqkb1r/pppn1ppp/5n2/3N2B1/3P4/8/PP2PPPP/R2QKBNR b KQkq - 0 6", "depth": 16, "seldepth": 21, "nodes": 2798029, "time_ms": 1990, "stop_reason": "limit", "best_move": { "san": "Nxd5", "uci": "f6d5" }, "lines": [ { "rank": 1, "depth": 16, "cp": -546, "mate": null, "wdl": { "win": 0, "draw": 0, "loss": 1000 }, "moves": [ { "san": "Nxd5", "uci": "f6d5" }, { "san": "Bxd8", "uci": "g5d8" }, { "san": "Bb4+", "uci": "f8b4" }, { "san": "Qd2", "uci": "d1d2" }, { "san": "Kxd8", "uci": "e8d8" }, { "san": "e4", "uci": "e2e4" }, { "san": "Bxd2+", "uci": "b4d2" } ] }, { "rank": 2, "depth": 16, "cp": 84, "mate": null, "wdl": { "win": 337, "draw": 663, "loss": 0 }, "moves": [ { "san": "h6", "uci": "h7h6" }, { "san": "Bxf6", "uci": "g5f6" }, { "san": "Nxf6", "uci": "d7f6" }, { "san": "Nc3", "uci": "d5c3" }, { "san": "Bd7", "uci": "c8d7" } ] } ], "usage": { "engine_ms": 1990 }, "cost_usd": "0.002488" } ``` ```json Hint response { "id": "req_01M4G8C5V2NJ7T4QX8RD3KW6PA", "model": "knight-1", "content": "White's last move counts on the pin against your queen. Ask whether losing the queen is so bad if a check follows.", "lines": [], "finish_reason": "end", "usage": { "input_tokens": 1420, "output_tokens": 28, "cached_tokens": 0, "grounding_tokens": 1190, "reasoning_tokens": 0 }, "cost_usd": "0.001170" } ``` ```text Output puzzle: r1bqkb1r/pppn1ppp/5n2/3N2B1/3P4/8/PP2PPPP/R2QKBNR b KQkq - 0 6 hint: White's last move counts on the pin against your queen. Ask whether losing the queen is so bad if a check follows. solution: Nxd5 Bxd8 Bb4+ Qd2 Kxd8 ```