When stuck, the admin can ask Claude for an intuitive explanation of a problem. It is committed as explain.md and shown as folded sections, so the reader opens only as much as they need: the key observation, hints that get stronger, the approach, a walkthrough with an SVG diagram per step, complexity, pitfalls and a pseudocode sketch. - internal/claude: streamed call with a JSON-schema reply, high effort, the server-side refusal fallback, fixed error messages and logged token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5); without a key only this feature is off. - internal/explain: the prompt, the schema, rendering to markdown, and a per-problem job tracker. The request starts a job and the page polls, since a call outlasts nginx's 120s timeout. - internal/statement: fetches statements from LeetCode's GraphQL API and USACO's problem pages. Others (Codeforces is behind Cloudflare) are pasted. - problem.md holds the statement, editable from the meta editor and shown only to the admin. Diagrams are sanitized with DOMPurify. Co-Authored-By: Claude Opus 5.5 <[email protected]>
192 lines
8.9 KiB
Go
192 lines
8.9 KiB
Go
// Package explain turns a problem the admin is stuck on into explain.md: an
|
|
// intuitive walkthrough of the solution, written by Claude, with SVG
|
|
// diagrams of the idea running on the sample.
|
|
//
|
|
// The reply is a fixed JSON shape (Result) so the page can lay it out as a
|
|
// ladder the reader climbs only as far as they need: the key observation,
|
|
// hints that get stronger, then the approach, the walkthrough, and a sketch.
|
|
// It is stored as markdown, not JSON, so it reads fine on Gitea and can be
|
|
// edited by hand like notes.md.
|
|
package explain
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"adam-french.co.uk/usaco-site/internal/claude"
|
|
"adam-french.co.uk/usaco-site/internal/index"
|
|
)
|
|
|
|
// Asker is the part of claude.Client used here, so tests can fake it.
|
|
type Asker interface {
|
|
JSON(ctx context.Context, req claude.Request, out any) error
|
|
Model() string
|
|
}
|
|
|
|
// Example is one sample case shown to Claude.
|
|
type Example struct {
|
|
In, Out string
|
|
}
|
|
|
|
// Input is what Claude is told about the problem.
|
|
type Input struct {
|
|
Name string
|
|
Statement string
|
|
Note string // what the admin says they are stuck on
|
|
Code *index.File // their current attempt, when they chose to send it
|
|
Examples []Example
|
|
}
|
|
|
|
// Step is one frame of the walkthrough.
|
|
type Step struct {
|
|
Caption string `json:"caption"`
|
|
SVG string `json:"svg"`
|
|
}
|
|
|
|
// Result is the reply's shape; Schema is the same thing for the API.
|
|
type Result struct {
|
|
Observation string `json:"observation"`
|
|
Hints []string `json:"hints"`
|
|
Approach string `json:"approach"`
|
|
Walkthrough []Step `json:"walkthrough"`
|
|
Complexity string `json:"complexity"`
|
|
Pitfalls []string `json:"pitfalls"`
|
|
Sketch string `json:"sketch"`
|
|
}
|
|
|
|
func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
|
|
|
|
func strs(desc string) map[string]any {
|
|
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": desc}
|
|
}
|
|
|
|
// Schema constrains the reply to Result. Structured outputs need every
|
|
// object closed and every property required.
|
|
var Schema = map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"observation": str("The single key insight the solution rests on, in one or two sentences of markdown. Name the insight without describing the algorithm."),
|
|
"hints": strs("Two to four hints in markdown, each a step stronger than the last. The first only nudges; the last leaves the reader one step from the approach."),
|
|
"approach": str("Markdown. The algorithm explained intuitively: how you would think of it from the problem, why it is correct, and what each piece of state means."),
|
|
"walkthrough": map[string]any{
|
|
"type": "array",
|
|
"description": "Two to six steps tracing the approach on a small example, ideally the sample.",
|
|
"items": map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"caption": str("Markdown: what is happening at this step and why."),
|
|
"svg": str("One complete <svg> element showing the state at this step, following the diagram rules."),
|
|
},
|
|
"required": []string{"caption", "svg"},
|
|
"additionalProperties": false,
|
|
},
|
|
},
|
|
"complexity": str("Markdown. Time and memory, with a one-line reason for each."),
|
|
"pitfalls": strs("Markdown. The mistakes that commonly break this problem: edge cases, overflow, off-by-ones, wrong greedy choices."),
|
|
"sketch": str("Language-agnostic pseudocode for the core of the solution, without any I/O boilerplate. Plain text, no code fence."),
|
|
},
|
|
"required": []string{"observation", "hints", "approach", "walkthrough", "complexity", "pitfalls", "sketch"},
|
|
"additionalProperties": false,
|
|
}
|
|
|
|
// maxTokens leaves room for adaptive thinking at high effort on top of the
|
|
// reply, which is a few thousand tokens of prose plus the SVGs.
|
|
const maxTokens = 32000
|
|
|
|
// System is the same on every call, so it is cached.
|
|
const System = `You are a patient competitive-programming coach. Someone is stuck on a problem and wants to understand how to solve it, not just to be handed a solution. Your answer will be shown as a ladder they climb only as far as they need: the key observation, hints of increasing strength, then the full approach, a diagrammed walkthrough, complexity, pitfalls, and a pseudocode sketch.
|
|
|
|
How to explain:
|
|
- Lead with intuition. Explain how someone could arrive at the idea from the problem's structure: what about the constraints or the question suggests it, and what simpler approach fails and why.
|
|
- Make every part of the state concrete. When you introduce a DP table, a heap, a union-find or two pointers, say exactly what each entry or pointer means.
|
|
- Justify correctness informally but convincingly, especially for greedy choices.
|
|
- If they describe what they are stuck on, or include their attempt, address that directly: say what in their attempt is on the right track and where it goes wrong. Do not rewrite their code.
|
|
- Never give a complete solution in any real programming language. The sketch is short pseudocode for the core idea only.
|
|
- Write in plain, direct prose. Use markdown for emphasis, lists and inline code. Use $...$ only if the problem statement does.
|
|
|
|
Diagram rules for each walkthrough step's svg:
|
|
- Show the actual mechanism on a small concrete example (the sample if it is small enough): array cells with index labels and pointer arrows, grid cells with their values and the current frontier, a DP table filling in, a graph with visited nodes and the edge being relaxed, a stack or heap's contents. Successive steps should show the state changing.
|
|
- One self-contained <svg> element with xmlns="http://www.w3.org/2000/svg", a viewBox at most 640 wide and 400 tall, and no width or height attributes, so it scales to the page.
|
|
- The page has light and dark themes. Draw lines and text with currentColor; fill shapes with none or with these accents only: #3b82f6 (current or active), #22c55e (done or chosen), #f59e0b (being compared or considered), #ef4444 (rejected or invalid). Put text over an accent fill only if it stays readable there.
|
|
- Text at least 13px, in font-family="ui-monospace, monospace" for values and sans-serif for labels. Keep labels short; the caption carries the explanation.
|
|
- No scripts, event handlers, <foreignObject>, external links, images or CSS @import. Use only basic shapes, paths, lines, text, groups and markers.`
|
|
|
|
// Prompt is the user message: the problem and what the admin has given.
|
|
func Prompt(in Input) string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
|
|
for i, ex := range in.Examples {
|
|
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
|
|
if ex.Out != "" {
|
|
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
|
|
}
|
|
b.WriteString("</example>\n")
|
|
}
|
|
if in.Code != nil {
|
|
fmt.Fprintf(&b, "\n<my_attempt file=%q>\n%s\n</my_attempt>\n", in.Code.Name, strings.TrimRight(in.Code.Content, "\n"))
|
|
}
|
|
if note := strings.TrimSpace(in.Note); note != "" {
|
|
fmt.Fprintf(&b, "\n<where_i_am_stuck>\n%s\n</where_i_am_stuck>\n", note)
|
|
}
|
|
b.WriteString("\nExplain how to solve this problem.")
|
|
return b.String()
|
|
}
|
|
|
|
// Generate asks Claude and returns explain.md.
|
|
func Generate(ctx context.Context, a Asker, in Input, now time.Time) (string, error) {
|
|
var r Result
|
|
err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return Render(r, a.Model(), now), nil
|
|
}
|
|
|
|
// Render lays a Result out as markdown. The page folds each "## " section
|
|
// away; the line above the first one stays visible.
|
|
func Render(r Result, model string, now time.Time) string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "_Explained by %s on %s._\n", model, now.Format("2 January 2006"))
|
|
section := func(title, body string) {
|
|
if body = strings.TrimSpace(body); body != "" {
|
|
fmt.Fprintf(&b, "\n## %s\n\n%s\n", title, body)
|
|
}
|
|
}
|
|
section("Key observation", r.Observation)
|
|
for i, h := range r.Hints {
|
|
section(fmt.Sprintf("Hint %d", i+1), h)
|
|
}
|
|
section("Approach", r.Approach)
|
|
var walk strings.Builder
|
|
for i, s := range r.Walkthrough {
|
|
if i > 0 {
|
|
walk.WriteString("\n\n")
|
|
}
|
|
fmt.Fprintf(&walk, "**Step %d.** %s", i+1, strings.TrimSpace(s.Caption))
|
|
// A fence inside the SVG would end the block early; an SVG never
|
|
// needs one.
|
|
if svg := strings.TrimSpace(strings.ReplaceAll(s.SVG, "```", "")); svg != "" {
|
|
fmt.Fprintf(&walk, "\n\n```svg\n%s\n```", svg)
|
|
}
|
|
}
|
|
section("Walkthrough", walk.String())
|
|
section("Complexity", r.Complexity)
|
|
section("Pitfalls", bullets(r.Pitfalls))
|
|
if sk := strings.TrimSpace(strings.ReplaceAll(r.Sketch, "```", "")); sk != "" {
|
|
section("Solution sketch", "```text\n"+sk+"\n```")
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func bullets(items []string) string {
|
|
var b strings.Builder
|
|
for _, it := range items {
|
|
if it = strings.TrimSpace(it); it != "" {
|
|
b.WriteString("- " + strings.ReplaceAll(it, "\n", "\n ") + "\n")
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|