Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
go/claude-api/README.md
1# Claude API — Go23> **Note:** The Go SDK supports the Claude API and beta tool use with `BetaToolRunner`. Agent SDK is not yet available for Go.45## Installation67```bash8go get github.com/anthropics/anthropic-sdk-go9```1011## Client Initialization1213```go14import (15"github.com/anthropics/anthropic-sdk-go"16"github.com/anthropics/anthropic-sdk-go/option"17)1819// Default (uses ANTHROPIC_API_KEY env var)20client := anthropic.NewClient()2122// Explicit API key23client := anthropic.NewClient(24option.WithAPIKey("your-api-key"),25)26```2728---2930## Model Constants3132The Go SDK provides typed model constants: `anthropic.ModelClaudeFable5`, `anthropic.ModelClaudeOpus4_8`, `anthropic.ModelClaudeOpus4_7`, `anthropic.ModelClaudeSonnet4_6`, `anthropic.ModelClaudeHaiku4_5_20251001`. Use `ModelClaudeOpus4_8` unless the user specifies otherwise; if they ask for Fable or the most powerful model, use `anthropic.ModelClaudeFable5` (see `shared/models.md` for the full resolution table).3334---3536## Basic Message Request3738```go39response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{40Model: anthropic.ModelClaudeOpus4_8,41MaxTokens: 16000,42Messages: []anthropic.MessageParam{43anthropic.NewUserMessage(anthropic.NewTextBlock("What is the capital of France?")),44},45})46if err != nil {47log.Fatal(err)48}49for _, block := range response.Content {50switch variant := block.AsAny().(type) {51case anthropic.TextBlock:52fmt.Println(variant.Text)53}54}55```5657---5859## Thinking6061Enable Claude's internal reasoning by setting `Thinking` in `MessageNewParams`. The response will contain `ThinkingBlock` content before the final `TextBlock`.6263**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think. Combine with the `effort` parameter for cost-quality control.6465Derived from `anthropic-sdk-go/message.go` (`ThinkingConfigParamUnion`, `ThinkingConfigAdaptiveParam`).6667```go68// There is no ThinkingConfigParamOfAdaptive helper — construct the union69// struct-literal directly and take the address of the variant.70adaptive := anthropic.ThinkingConfigAdaptiveParam{}71params := anthropic.MessageNewParams{72Model: anthropic.ModelClaudeSonnet4_6,73MaxTokens: 16000,74Thinking: anthropic.ThinkingConfigParamUnion{OfAdaptive: &adaptive},75Messages: []anthropic.MessageParam{76anthropic.NewUserMessage(anthropic.NewTextBlock("How many r's in strawberry?")),77},78}7980resp, err := client.Messages.New(context.Background(), params)81if err != nil {82log.Fatal(err)83}8485// ThinkingBlock(s) precede TextBlock in content86for _, block := range resp.Content {87switch b := block.AsAny().(type) {88case anthropic.ThinkingBlock:89fmt.Println("[thinking]", b.Thinking)90case anthropic.TextBlock:91fmt.Println(b.Text)92}93}94```9596> **Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6:** Use adaptive thinking (above). `ThinkingConfigParamOfEnabled(budgetTokens)` is removed on Fable 5, Opus 4.8, and 4.7 (400 if sent); deprecated on Opus 4.6 and Sonnet 4.6.97> **Older models:** Use `anthropic.ThinkingConfigParamOfEnabled(N)` (budget must be < `MaxTokens`, min 1024).9899To disable: `anthropic.ThinkingConfigParamUnion{OfDisabled: &anthropic.ThinkingConfigDisabledParam{}}`.100101---102103## Prompt Caching104105`System` is `[]TextBlockParam`; set `CacheControl` on the last block to cache tools + system together. For placement patterns and the silent-invalidator audit checklist, see `shared/prompt-caching.md`.106107```go108System: []anthropic.TextBlockParam{{109Text: longSystemPrompt,110CacheControl: anthropic.NewCacheControlEphemeralParam(), // default 5m TTL111}},112```113114For 1-hour TTL: `anthropic.CacheControlEphemeralParam{TTL: anthropic.CacheControlEphemeralTTLTTL1h}`. There's also a top-level `CacheControl` on `MessageNewParams` that auto-places on the last cacheable block.115116Verify hits via `resp.Usage.CacheCreationInputTokens` / `resp.Usage.CacheReadInputTokens`.117118---119120## Stop Details121122When `StopReason` is `anthropic.StopReasonRefusal`, the response includes structured `StopDetails`:123124```go125if resp.StopReason == anthropic.StopReasonRefusal {126fmt.Println("Category:", resp.StopDetails.Category) // e.g. "cyber", "bio", "reasoning_extraction", "frontier_llm", or "" — see docs for the full set127fmt.Println("Explanation:", resp.StopDetails.Explanation)128}129```130131**Refusal fallbacks (Claude Fable 5) — opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. In `claude-fable-5` code, include `Fallbacks: []anthropic.BetaFallbackParam{{Model: "claude-opus-4-8"}}` plus the `anthropic.AnthropicBetaServerSideFallback2026_06_01` beta on `client.Beta.Messages.New` by default — a policy decline is re-served by the fallback model inside the same call. Not available on Amazon Bedrock, Vertex AI, or Microsoft Foundry — register the client-side middleware there: `option.WithMiddleware(betafallback.BetaRefusalFallbackMiddleware(...))` from `lib/betafallback`, with per-conversation state via `betafallback.WithBetaFallbackState(&betafallback.BetaFallbackState{})`. Full semantics (billing, sticky routing, streaming) and a runnable example: `shared/model-migration.md` → Migrating to Claude Fable 5 → `refusal` stop reason, and the Go SDK repo's `examples/` (WebFetch via `shared/live-sources.md`).132133---134135## PDF / Document Input136137`NewDocumentBlock` generic helper accepts any source type. `MediaType`/`Type` are auto-set.138139```go140b64 := base64.StdEncoding.EncodeToString(pdfBytes)141142msg := anthropic.NewUserMessage(143anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{Data: b64}),144anthropic.NewTextBlock("Summarize this document"),145)146```147148Other sources: `URLPDFSourceParam{URL: "https://..."}`, `PlainTextSourceParam{Data: "..."}`.149150---151152## Context Editing / Compaction (Beta)153154Use `Beta.Messages.New` with `ContextManagement` on `BetaMessageNewParams`. There is no `NewBetaAssistantMessage` — use `.ToParam()` for the round-trip.155156```go157params := anthropic.BetaMessageNewParams{158Model: anthropic.ModelClaudeOpus4_8, // also supported: ModelClaudeSonnet4_6159MaxTokens: 16000,160Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},161ContextManagement: anthropic.BetaContextManagementConfigParam{162Edits: []anthropic.BetaContextManagementConfigEditUnionParam{163{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},164},165},166Messages: []anthropic.BetaMessageParam{ /* ... */ },167}168169resp, err := client.Beta.Messages.New(ctx, params)170if err != nil {171log.Fatal(err)172}173174// Round-trip: append response to history via .ToParam()175params.Messages = append(params.Messages, resp.ToParam())176177// Read compaction blocks from the response178for _, block := range resp.Content {179if c, ok := block.AsAny().(anthropic.BetaCompactionBlock); ok {180fmt.Println("compaction summary:", c.Content)181}182}183```184185Other edit types: `BetaClearToolUses20250919EditParam`, `BetaClearThinking20251015EditParam` — these need `Betas: []anthropic.AnthropicBeta{"context-management-2025-06-27"}`, not `compact-2026-01-12`.186