Add an Explain button that has Claude explain a problem
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]>
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
// Package claude is the site's one way of calling Claude: a fixed system
|
||||
// prompt and one user message in, a reply constrained to a JSON schema out.
|
||||
//
|
||||
// It follows web_server's python/app/claude.py (the key is CLAUDE_API_KEY,
|
||||
// a missing key only switches the Claude features off, and the errors shown
|
||||
// to the admin are fixed strings while the detail goes to the log) but is
|
||||
// tuned for the opposite kind of call: a long, considered answer rather than
|
||||
// a few hundred tokens of extraction. Hence streaming (a non-streaming
|
||||
// request this size risks the HTTP timeout), high effort, and structured
|
||||
// outputs instead of parsing JSON out of free text.
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
"github.com/anthropics/anthropic-sdk-go/shared/constant"
|
||||
)
|
||||
|
||||
// DefaultModel is used when CLAUDE_MODEL is blank.
|
||||
const DefaultModel = "claude-opus-5-5"
|
||||
|
||||
// ErrNotConfigured is a server with no CLAUDE_API_KEY.
|
||||
var ErrNotConfigured = errors.New("CLAUDE_API_KEY is not set")
|
||||
|
||||
// Failure is a call that did not produce an answer. Msg is safe to show the
|
||||
// admin; Err (logged, never sent) says why.
|
||||
type Failure struct {
|
||||
Msg string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (f *Failure) Error() string { return f.Msg }
|
||||
func (f *Failure) Unwrap() error { return f.Err }
|
||||
|
||||
// Request is one call.
|
||||
type Request struct {
|
||||
System string
|
||||
User string
|
||||
Schema map[string]any
|
||||
MaxTokens int64
|
||||
}
|
||||
|
||||
// Client calls the API with one model.
|
||||
type Client struct {
|
||||
api anthropic.Client
|
||||
model string
|
||||
}
|
||||
|
||||
// New builds a client, or returns ErrNotConfigured for a blank key. opts
|
||||
// are for tests (a fake server's base URL).
|
||||
func New(key, model string, opts ...option.RequestOption) (*Client, error) {
|
||||
if key == "" {
|
||||
return nil, ErrNotConfigured
|
||||
}
|
||||
if model == "" {
|
||||
model = DefaultModel
|
||||
}
|
||||
return &Client{api: anthropic.NewClient(append([]option.RequestOption{option.WithAPIKey(key)}, opts...)...), model: model}, nil
|
||||
}
|
||||
|
||||
// Model is the model every call uses.
|
||||
func (c *Client) Model() string { return c.model }
|
||||
|
||||
// JSON makes the call and unmarshals the reply into out.
|
||||
func (c *Client) JSON(ctx context.Context, req Request, out any) error {
|
||||
params := anthropic.BetaMessageNewParams{
|
||||
Model: c.model,
|
||||
MaxTokens: req.MaxTokens,
|
||||
// The system prompt is the same on every call, so it is worth
|
||||
// caching; the problem goes in the user message after it.
|
||||
System: []anthropic.BetaTextBlockParam{{
|
||||
Text: req.System,
|
||||
CacheControl: anthropic.NewBetaCacheControlEphemeralParam(),
|
||||
}},
|
||||
Messages: []anthropic.BetaMessageParam{
|
||||
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(req.User)),
|
||||
},
|
||||
// Explaining a problem well is the whole point, so effort is set
|
||||
// explicitly: claude-opus-5-5 defaults to medium. Thinking is left
|
||||
// unset, which is adaptive on every model this is meant for.
|
||||
OutputConfig: anthropic.BetaOutputConfigParam{
|
||||
Effort: anthropic.BetaOutputConfigEffortHigh,
|
||||
Format: anthropic.BetaJSONOutputFormatParam{Schema: req.Schema},
|
||||
},
|
||||
// A request the safety classifiers decline is retried on whichever
|
||||
// model the API picks for that category, inside the same call.
|
||||
Fallbacks: anthropic.BetaFallbacksParamUnion{OfDefault: constant.ValueOf[constant.Default]()},
|
||||
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaServerSideFallback2026_07_01},
|
||||
}
|
||||
|
||||
stream := c.api.Beta.Messages.NewStreaming(ctx, params)
|
||||
msg := anthropic.BetaMessage{}
|
||||
for stream.Next() {
|
||||
if err := msg.Accumulate(stream.Current()); err != nil {
|
||||
return &Failure{"Claude's reply could not be read", err}
|
||||
}
|
||||
}
|
||||
if err := stream.Err(); err != nil {
|
||||
return apiFailure(err)
|
||||
}
|
||||
|
||||
u := msg.Usage
|
||||
log.Printf("[claude] %s: %d in (%d cached, %d written), %d out, stop %s",
|
||||
msg.Model, u.InputTokens, u.CacheReadInputTokens, u.CacheCreationInputTokens, u.OutputTokens, msg.StopReason)
|
||||
|
||||
switch msg.StopReason {
|
||||
case anthropic.BetaStopReasonRefusal:
|
||||
return &Failure{"Claude declined to answer", fmt.Errorf("refusal: %s %s", msg.StopDetails.Category, msg.StopDetails.Explanation)}
|
||||
case anthropic.BetaStopReasonMaxTokens:
|
||||
return &Failure{"Claude's answer ran past the length limit", errors.New("max_tokens")}
|
||||
}
|
||||
// With thinking on, the reply's first block can be a thinking block, so
|
||||
// the answer is the text block, wherever it is.
|
||||
for _, b := range msg.Content {
|
||||
if b.Type == "text" {
|
||||
if err := json.Unmarshal([]byte(b.Text), out); err != nil {
|
||||
return &Failure{"Claude's reply could not be read", err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return &Failure{"Claude's reply was empty", errors.New("no text block")}
|
||||
}
|
||||
|
||||
func apiFailure(err error) error {
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return &Failure{"Claude took too long", err}
|
||||
}
|
||||
var apiErr *anthropic.Error
|
||||
if errors.As(err, &apiErr) {
|
||||
switch {
|
||||
case apiErr.StatusCode == 401 || apiErr.StatusCode == 403:
|
||||
return &Failure{"the Claude API key was refused", err}
|
||||
case apiErr.StatusCode == 429:
|
||||
return &Failure{"Claude is rate limited; try again in a minute", err}
|
||||
case apiErr.StatusCode >= 500:
|
||||
return &Failure{"Claude is unavailable; try again later", err}
|
||||
}
|
||||
return &Failure{"the request to Claude was rejected", err}
|
||||
}
|
||||
return &Failure{"could not reach Claude", err}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// sse is a minimal streamed reply: one text block holding text.
|
||||
func sse(text, stop string) string {
|
||||
ev := func(typ string, data any) string {
|
||||
b, _ := json.Marshal(data)
|
||||
return fmt.Sprintf("event: %s\ndata: %s\n\n", typ, b)
|
||||
}
|
||||
return ev("message_start", map[string]any{"type": "message_start", "message": map[string]any{
|
||||
"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-opus-5-5", "content": []any{},
|
||||
"usage": map[string]any{"input_tokens": 10, "output_tokens": 0}}}) +
|
||||
ev("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}) +
|
||||
ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": text}}) +
|
||||
ev("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) +
|
||||
ev("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop}, "usage": map[string]any{"output_tokens": 5}}) +
|
||||
ev("message_stop", map[string]any{"type": "message_stop"})
|
||||
}
|
||||
|
||||
func fake(t *testing.T, status int, reply string, got *map[string]any, header *http.Header) *Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
if got != nil {
|
||||
json.Unmarshal(b, got)
|
||||
}
|
||||
if header != nil {
|
||||
*header = r.Header.Clone()
|
||||
}
|
||||
if status != 200 {
|
||||
w.WriteHeader(status)
|
||||
w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Write([]byte(reply))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
c, err := New("k", "", option.WithBaseURL(srv.URL), option.WithMaxRetries(0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func TestNotConfigured(t *testing.T) {
|
||||
if _, err := New("", ""); !errors.Is(err, ErrNotConfigured) {
|
||||
t.Fatalf("blank key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONRequestAndReply(t *testing.T) {
|
||||
var body map[string]any
|
||||
var hdr http.Header
|
||||
c := fake(t, 200, sse(`{"a":"hi"}`, "end_turn"), &body, &hdr)
|
||||
var out struct{ A string }
|
||||
err := c.JSON(context.Background(), Request{System: "sys", User: "u", Schema: map[string]any{"type": "object"}, MaxTokens: 100}, &out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.A != "hi" {
|
||||
t.Errorf("decoded %+v", out)
|
||||
}
|
||||
|
||||
if body["model"] != DefaultModel || body["stream"] != true || body["fallbacks"] != "default" {
|
||||
t.Errorf("model/stream/fallbacks = %v %v %v", body["model"], body["stream"], body["fallbacks"])
|
||||
}
|
||||
oc, _ := body["output_config"].(map[string]any)
|
||||
format, _ := oc["format"].(map[string]any)
|
||||
if oc["effort"] != "high" || format["type"] != "json_schema" || format["schema"] == nil {
|
||||
t.Errorf("output_config = %v", oc)
|
||||
}
|
||||
if !strings.Contains(hdr.Get("Anthropic-Beta"), "server-side-fallback-2026-07-01") {
|
||||
t.Errorf("beta header = %q", hdr.Get("Anthropic-Beta"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
reply string
|
||||
want string
|
||||
}{
|
||||
{"refusal", 200, sse("", "refusal"), "declined"},
|
||||
{"cut off", 200, sse(`{"a":`, "max_tokens"), "length limit"},
|
||||
{"not json", 200, sse("plain words", "end_turn"), "could not be read"},
|
||||
{"bad key", 401, "", "key was refused"},
|
||||
{"overloaded", 529, "", "unavailable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
c := fake(t, tc.status, tc.reply, nil, nil)
|
||||
var out map[string]any
|
||||
err := c.JSON(context.Background(), Request{System: "s", User: "u", Schema: map[string]any{}, MaxTokens: 10}, &out)
|
||||
var f *Failure
|
||||
if !errors.As(err, &f) || !strings.Contains(f.Msg, tc.want) {
|
||||
t.Errorf("%s: err = %v, want a Failure mentioning %q", tc.name, err, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user