# Generate Talk to Knight or Queen about chess, with or without a position. Every move the reply names comes back checked and legal, as a Line you can show on a board. `POST /v1/generate` sends a conversation to Knight or Queen and returns the reply in Markdown. Give it a position and the reply is grounded in that position: every move it names is checked against the board and returned as a Line. Leave the position out and it is a plain chess conversation. Coaching, explaining a position and picking a move are all Generate calls with their own `system` prompt; the [Recipes](/docs/recipes) have one for each. [Review a game](/docs/recipes/review-a-game) pairs Generate with Engine to explain a whole game's mistakes. ## 1. Ask about a position `model` is required. `knight-1` is the cheaper, faster Model and `queen-1` the stronger one; the bare aliases `knight` and `queen` always point at the latest version, and the response names the version that answered. `position` is a FEN, or a PGN with a `ply`: the position after that many half-moves of the PGN's main line, where `ply` 0 is the start. Variations and comments in the PGN are ignored. `system` sets the Model's role and tone, and `messages` is the conversation, ending with the user's turn. ```bash curl curl https://api.chessdrive.io/v1/generate \ -H "Authorization: Bearer $CHESSDRIVE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "knight-1", "system": "You are a friendly chess coach for club players.", "position": { "pgn": "1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6", "ply": 10 }, "messages": [{ "role": "user", "content": "What are White'\''s main plans here?" }] }' ``` ```python Python import os import requests r = requests.post( "https://api.chessdrive.io/v1/generate", headers={"Authorization": f"Bearer {os.environ['CHESSDRIVE_API_KEY']}"}, json={ "model": "knight-1", "system": "You are a friendly chess coach for club players.", "position": {"pgn": "1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6", "ply": 10}, "messages": [{"role": "user", "content": "What are White's main plans here?"}], }, ) r.raise_for_status() print(r.json()["content"]) ``` ```js JavaScript const res = await fetch("https://api.chessdrive.io/v1/generate", { method: "POST", headers: { Authorization: `Bearer ${process.env.CHESSDRIVE_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "knight-1", system: "You are a friendly chess coach for club players.", position: { pgn: "1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6", ply: 10 }, messages: [{ role: "user", content: "What are White's main plans here?" }], }), }); if (!res.ok) throw new Error(await res.text()); console.log((await res.json()).content); ``` ## 2. Read the Lines The reply is `content`, in Markdown. Each move it names is a link of the form `[text](line:L1)`, and the link's target is a Line in `lines`: - `from_fen` is the position the Line starts from. - `moves` are played in order from there, each with its `san`, its `uci` and the `fen` after it, so you can step through a Line on a board without a chess library. - A single move is a Line of one move. Every move in `lines` is legal. If the Model names an illegal move, its Line is cut just before it, and a Line left with no moves is dropped. `content` is never rewritten, so a link whose Line was dropped has no match in `lines`: show its text as plain text. The Model judges positions in words, never numbers: "White is better", "a mistake". For an evaluation in centipawns, ask [Engine](/docs/engine). ```json Response { "id": "req_01M4FZ3N7Q8KX2D5TB6VJRH0CE", "model": "knight-1", "content": "White has two main plans. The English Attack starts with [6.Be3](line:L1): after 6...e5 7.Nb3, White follows with f3, Qd2 and a kingside pawn storm. The sharper [6.Bg5 e6 7.f4](line:L2) aims at the e5 break and pins Black's knight first.", "lines": [ { "id": "L1", "from_fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6", "moves": [ { "san": "Be3", "uci": "c1e3", "fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N1B3/PPP2PPP/R2QKB1R b KQkq - 1 6" }, { "san": "e5", "uci": "e7e5", "fen": "rnbqkb1r/1p3ppp/p2p1n2/4p3/3NP3/2N1B3/PPP2PPP/R2QKB1R w KQkq - 0 7" }, { "san": "Nb3", "uci": "d4b3", "fen": "rnbqkb1r/1p3ppp/p2p1n2/4p3/4P3/1NN1B3/PPP2PPP/R2QKB1R b KQkq - 1 7" } ] }, { "id": "L2", "from_fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6", "moves": [ { "san": "Bg5", "uci": "c1g5", "fen": "rnbqkb1r/1p2pppp/p2p1n2/6B1/3NP3/2N5/PPP2PPP/R2QKB1R b KQkq - 1 6" }, { "san": "e6", "uci": "e7e6", "fen": "rnbqkb1r/1p3ppp/p2ppn2/6B1/3NP3/2N5/PPP2PPP/R2QKB1R w KQkq - 0 7" }, { "san": "f4", "uci": "f2f4", "fen": "rnbqkb1r/1p3ppp/p2ppn2/6B1/3NPP2/2N5/PPP3PP/R2QKB1R b KQkq - 0 7" } ] } ], "finish_reason": "end", "usage": { "input_tokens": 1412, "output_tokens": 118, "cached_tokens": 0, "grounding_tokens": 1180, "reasoning_tokens": 0 }, "cost_usd": "0.001502" } ``` ## 3. Show the Lines To render the reply, find each `line:` link and look its Line up by `id`. This turns every link into its text plus the moves in SAN; in an app you would make it a button that plays the Line on a board. ```python Python import os import re import requests r = requests.post( "https://api.chessdrive.io/v1/generate", headers={"Authorization": f"Bearer {os.environ['CHESSDRIVE_API_KEY']}"}, json={ "model": "knight-1", "position": {"fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6"}, "messages": [{"role": "user", "content": "What are White's main plans here?"}], }, ) r.raise_for_status() reply = r.json() lines = {line["id"]: line for line in reply["lines"]} def show(link): text, line_id = link.group(1), link.group(2) line = lines.get(line_id) if line is None: return text # its Line was dropped: plain text return f"{text} [{' '.join(m['san'] for m in line['moves'])}]" print(re.sub(r"\[([^\]]+)\]\(line:([^)]+)\)", show, reply["content"])) ``` ```js JavaScript const res = await fetch("https://api.chessdrive.io/v1/generate", { method: "POST", headers: { Authorization: `Bearer ${process.env.CHESSDRIVE_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "knight-1", position: { fen: "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6" }, messages: [{ role: "user", content: "What are White's main plans here?" }], }), }); if (!res.ok) throw new Error(await res.text()); const reply = await res.json(); const lines = new Map(reply.lines.map((line) => [line.id, line])); const shown = reply.content.replace(/\[([^\]]+)\]\(line:([^)]+)\)/g, (_, text, id) => { const line = lines.get(id); if (!line) return text; // its Line was dropped: plain text return `${text} [${line.moves.map((m) => m.san).join(" ")}]`; }); console.log(shown); ``` ## 4. Continue the conversation Generate keeps no state: send the whole conversation each time. Append the Model's reply as an `assistant` turn exactly as you received it, `line:` links included, then the user's next question. Keep sending the same `position` while the conversation is about it; to move on, send the new one. ```python Python import os import requests url = "https://api.chessdrive.io/v1/generate" headers = {"Authorization": f"Bearer {os.environ['CHESSDRIVE_API_KEY']}"} position = {"fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6"} messages = [{"role": "user", "content": "What are White's main plans here?"}] first = requests.post(url, headers=headers, json={"model": "knight-1", "position": position, "messages": messages}) first.raise_for_status() messages.append({"role": "assistant", "content": first.json()["content"]}) messages.append({"role": "user", "content": "Which one suits a positional player?"}) second = requests.post(url, headers=headers, json={"model": "knight-1", "position": position, "messages": messages}) second.raise_for_status() print(second.json()["content"]) ``` ```js JavaScript const url = "https://api.chessdrive.io/v1/generate"; const position = { fen: "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6" }; const messages = [{ role: "user", content: "What are White's main plans here?" }]; async function generate() { const res = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${process.env.CHESSDRIVE_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "knight-1", position, messages }), }); if (!res.ok) throw new Error(await res.text()); return res.json(); } const first = await generate(); messages.push({ role: "assistant", content: first.content }); messages.push({ role: "user", content: "Which one suits a positional player?" }); console.log((await generate()).content); ``` ## 5. Chat without a position `position` is optional. Without one, Generate is a chess conversation about anything: openings, history, training plans, the rules. There is no board to check moves against, so `lines` is always empty and the reply's moves are plain text. ```bash curl curl https://api.chessdrive.io/v1/generate \ -H "Authorization: Bearer $CHESSDRIVE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "knight-1", "messages": [{ "role": "user", "content": "Suggest a solid opening repertoire for Black against 1.e4." }] }' ``` ```python Python import os import requests r = requests.post( "https://api.chessdrive.io/v1/generate", headers={"Authorization": f"Bearer {os.environ['CHESSDRIVE_API_KEY']}"}, json={ "model": "knight-1", "messages": [{"role": "user", "content": "Suggest a solid opening repertoire for Black against 1.e4."}], }, ) r.raise_for_status() print(r.json()["content"]) ``` ```js JavaScript const res = await fetch("https://api.chessdrive.io/v1/generate", { method: "POST", headers: { Authorization: `Bearer ${process.env.CHESSDRIVE_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "knight-1", messages: [{ role: "user", content: "Suggest a solid opening repertoire for Black against 1.e4." }], }), }); if (!res.ok) throw new Error(await res.text()); console.log((await res.json()).content); ``` ## 6. Stream the reply With `"stream": true` the response is Server-Sent Events, so you can show the text as it is written: the reply's opening is held until its first sentence after about 40 words has passed our checks, then the rest streams as the Model writes it. The events come in this order: 1. `message_start`, with the request `id` and the `model`. 2. `text_delta`, any number of them, each with the next piece of `text`. 3. `line`, one per Line, after the text: moves are checked on the finished reply. 4. `message_end`, with `usage`, `cost_usd` and `finish_reason`. If something fails after the stream has started, an `error` event with the usual error body ends it, even after some text, and the call is not billed. If you close the connection early, you are billed for the tokens processed until then. ```bash curl curl -N https://api.chessdrive.io/v1/generate \ -H "Authorization: Bearer $CHESSDRIVE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "knight-1", "stream": true, "position": { "fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6" }, "messages": [{ "role": "user", "content": "What are White'\''s main plans here?" }] }' ``` ```python Python import json import os import requests with requests.post( "https://api.chessdrive.io/v1/generate", headers={"Authorization": f"Bearer {os.environ['CHESSDRIVE_API_KEY']}"}, json={ "model": "knight-1", "stream": True, "position": {"fen": "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6"}, "messages": [{"role": "user", "content": "What are White's main plans here?"}], }, stream=True, ) as r: r.raise_for_status() event = None for raw in r.iter_lines(decode_unicode=True): if raw.startswith("event: "): event = raw[len("event: "):] elif raw.startswith("data: "): data = json.loads(raw[len("data: "):]) if event == "text_delta": print(data["text"], end="", flush=True) elif event == "line": print(f"\n{data['line']['id']}:", " ".join(m["san"] for m in data["line"]["moves"])) elif event == "message_end": print("\ncost:", data["cost_usd"]) elif event == "error": raise RuntimeError(data["error"]["message"]) ``` ```js JavaScript const res = await fetch("https://api.chessdrive.io/v1/generate", { method: "POST", headers: { Authorization: `Bearer ${process.env.CHESSDRIVE_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "knight-1", stream: true, position: { fen: "rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6" }, messages: [{ role: "user", content: "What are White's main plans here?" }], }), }); if (!res.ok) throw new Error(await res.text()); const decoder = new TextDecoder(); let buffer = ""; let event = ""; for await (const chunk of res.body) { buffer += decoder.decode(chunk, { stream: true }); let end; while ((end = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, end).trimEnd(); buffer = buffer.slice(end + 1); if (line.startsWith("event: ")) event = line.slice("event: ".length); if (!line.startsWith("data: ")) continue; const data = JSON.parse(line.slice("data: ".length)); if (event === "text_delta") process.stdout.write(data.text); if (event === "line") console.log(`\n${data.line.id}:`, data.line.moves.map((m) => m.san).join(" ")); if (event === "message_end") console.log("\ncost:", data.cost_usd); if (event === "error") throw new Error(data.error.message); } } ``` ```text Events event: message_start data: {"id":"req_01M4FZ3N7Q8KX2D5TB6VJRH0CE","model":"knight-1"} event: text_delta data: {"text":"White has two main plans. The English Attack starts with "} event: text_delta data: {"text":"[6.Be3](line:L1): after 6...e5 7.Nb3, White follows with f3, Qd2 and a kingside pawn storm."} event: line data: {"line":{"id":"L1","from_fen":"rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6","moves":[{"san":"Be3","uci":"c1e3","fen":"rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N1B3/PPP2PPP/R2QKB1R b KQkq - 1 6"}]}} event: message_end data: {"usage":{"input_tokens":1412,"output_tokens":40,"cached_tokens":0,"grounding_tokens":1180,"reasoning_tokens":0},"cost_usd":"0.001209","finish_reason":"end"} ``` ## Length and context | Field | Default | Range | |---|---|---| | `max_tokens` | 1,024 on Knight, 4,096 on Queen | 1 to the Model's output cap: 3,072 on Knight, 4,096 on Queen. A reply cut off there ends with `finish_reason` `max_tokens`. It counts all output, reasoning included, so leave room for the reply. A reply with no text when it was cut off is retried, then answered `503 upstream_unavailable`, unbilled. | | `temperature` | 1 | 0 to 1. Accepted, but it has no effect on Knight or Queen. | The whole request has to fit the Model's context window: 32K tokens on Knight and 128K on Queen, as `GET /v1/models` lists them. The input, our grounding and `max_tokens` together over the window is a 400 `context_too_long`; the request is never silently shortened. In a long conversation, drop or summarise the oldest turns before you resend it. ## What you pay for Every token the Model processes is billed, and `usage` shows them all: - `input_tokens` includes `grounding_tokens`, what we add to ground the Model in the position: the FEN, the side to move, the moves so far and the legal moves. - `cached_tokens`, also part of `input_tokens`, are input read from cache, usually the earlier turns of a conversation you resend. They cost less than the rest of the input. - `output_tokens` includes `reasoning_tokens`, any the Model spent thinking before it answered. `cost_usd` is what the call drew from your Balance. Failed calls are free. Prices per Model are on [Pricing](/pricing).