chatanthropic

package module
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 12 Imported by: 0

README

chat-anthropic

Anthropic Claude provider for the chat multi-provider AI client

Go Reference Pipeline phpboyscout Go toolkit

Part of the phpboyscout Go toolkit. Docs: chat.go.phpboyscout.uk


gitlab.com/phpboyscout/go/chat-anthropic registers the Anthropic Claude provider (claude) for gitlab.com/phpboyscout/go/chat. It is a thin adapter over anthropics/anthropic-sdk-go — too tightly coupled to the core to warrant its own docs site, so all narrative documentation lives on the core chat docs site; this README plus the runnable Example tests are the module's reference.

Usage

Activate the provider with a blank import, then talk to Claude through the core chat API:

import (
    "gitlab.com/phpboyscout/go/chat"
    _ "gitlab.com/phpboyscout/go/chat-anthropic" // registers provider "claude"
)

client, err := chat.New(ctx, chat.Settings{
    Config: chat.Config{Provider: chat.ProviderClaude, Token: apiKey},
})
if err != nil {
    return err
}
answer, err := client.Chat(ctx, "Summarise this diff in one line.")

The blank import runs this module's init(), which registers the claude provider factory and an HTTP-status extractor so the core's cross-provider fallback can classify Anthropic errors. Importing it links anthropics/anthropic-sdk-go — and nothing else beyond the core.

Capabilities

  • ReAct tool-calling loop with automatic tool dispatch (sequential or parallel)
  • Streaming via StreamChat (text deltas, tool-call start/end, completion)
  • Structured output through Ask, enforced with a forced tool call
  • Image and PDF media blocks on the user turn
  • Conversation Save/Restore snapshots
  • Token-usage accounting via client.Usage()
  • Stateless one-shot calls via Config.Stateless — each call carries only its own turns, so one client can serve a batch of independent documents across goroutines instead of re-sending the accumulated prefix every time

Keeping up with Anthropic

Two generators, both run deliberately rather than automatically applied.

internal/genmodels regenerates the per-model capability table. It reads /v1/models and probes for the one thing that endpoint will not tell you — whether a model still accepts temperature — then you commit the result:

ANTHROPIC_API_KEY=... go run ./internal/genmodels > models_generated.go

internal/detectmodels watches for Anthropic shipping something chat.DefaultModelClaude does not reflect, and raises an issue in this project when it does. It reports candidates with their capability data; it never picks one, because nothing Anthropic publishes ranks models. The constant itself lives in go/chat, and the issue body says so.

ANTHROPIC_API_KEY=... go run ./internal/detectmodels -dry-run

It runs weekly — 03:00 Europe/London on Mondays — from a DETECT_MODELS=true scheduled pipeline. Neither -dry-run nor -update-snapshot touches the forge — only a plain run raises. internal/detectmodels/snapshot.json is the committed baseline, and it moves when a human resolves the issue, not when CI runs.

Credentials

The API key resolves through the core's cascade: Config.TokenConfig.Credentials (env-var ref / OS keychain / literal) → the well-known ANTHROPIC_API_KEY environment variable.

Only the core chat module and anthropics/anthropic-sdk-go. A depfootprint_test.go guard fails the build if go-tool-base, the sibling provider SDKs (OpenAI, Gemini), or any CLI/observability weight leaks into the dependency graph.

Version compatibility

chat-anthropic requires the core version named in its own go.mod, and is built and tested against exactly that version. Do not compare the two version numbers — each module releases when that module changes, so they move independently.

Install this module and let it bring the core with it:

go get gitlab.com/phpboyscout/go/chat-anthropic
go mod tidy

See version compatibility for what a mismatch does, and why requiring chat directly at @latest is the way to break it.

Licence

MIT — see LICENSE.

Documentation

Index

Constants

View Source
const EnvClaudeKey = "ANTHROPIC_API_KEY"

EnvClaudeKey is the well-known unprefixed environment variable used as the ecosystem fallback when no explicit credential is configured.

Variables

This section is empty.

Functions

This section is empty.

Types

type Claude

type Claude struct {
	chat.UsageTracker
	// contains filtered or unexported fields
}

Claude implements the chat.ChatClient interface using Anthropic's official Go SDK.

func (*Claude) Add

func (c *Claude) Add(_ context.Context, prompt string, media ...chat.Media) error

func (*Claude) AddCached added in v0.5.0

func (c *Claude) AddCached(_ context.Context, prompt string, media ...chat.Media) error

AddCached appends a user turn carrying a cache_control marker.

The marker goes on this block and no other. In particular it never lands on a per-call turn, which would write a cache entry keyed to content that changes every request — paying the write premium for something that can never be read back.

func (*Claude) ApplyPolicyNow added in v0.11.0

func (c *Claude) ApplyPolicyNow(ctx context.Context, policy chat.HistoryPolicy) (int, error)

ApplyPolicyNow bounds the retained conversation immediately, rather than waiting for the next request to do it.

It is the same three steps this client already runs before every request — describe the turns, ask the policy, rewrite from the result — with the difference that there is no pending turn to hold out of the budget. Every retained turn is a candidate, because nothing is about to be answered.

A nil policy means the configured one. With none configured there is nothing to apply and it returns zero rather than an error: a caller typing /compact on a client with no policy has asked for something reasonable that happens to be a no-op.

func (*Claude) Ask

func (c *Claude) Ask(ctx context.Context, question string, target any, media ...chat.Media) error

Ask sends a question to the Claude chat client and expects a structured response.

func (*Claude) Chat

func (c *Claude) Chat(ctx context.Context, prompt string, media ...chat.Media) (string, error)

func (*Claude) History added in v0.9.0

func (c *Claude) History() chat.History

History reports the conversation this client will re-send, counting both the committed turns and any buffered by Add and not yet sent.

Known is true: this provider owns its transcript, so the count is authoritative. A stateless client retains nothing between calls and reports only what is currently buffered.

func (*Claude) Model added in v0.6.0

func (c *Claude) Model() string

Model implements chat.ModelIdentifier, reporting the model this client will actually use — the configured one, or the default it fell back to.

func (*Claude) Provider added in v0.6.0

func (c *Claude) Provider() chat.Provider

Provider implements chat.ModelIdentifier.

func (*Claude) Restore

func (c *Claude) Restore(snapshot *chat.Snapshot) error

Restore replaces the current conversation state with a previously saved snapshot.

func (*Claude) Save

func (c *Claude) Save() (*chat.Snapshot, error)

Save captures the current Claude conversation state as a snapshot.

A stateless client retains no conversation, so its snapshot carries an empty message list. That is honest rather than useless: the provider, model and system prompt still round-trip.

func (*Claude) SetTools

func (c *Claude) SetTools(tools []chat.Tool) error

SetTools configures the tools available to the AI.

func (*Claude) StreamChat

func (c *Claude) StreamChat(ctx context.Context, prompt string, callback chat.StreamCallback, media ...chat.Media) (string, error)

StreamChat implements StreamingChatClient.

func (*Claude) SupportsEffort added in v0.3.0

func (c *Claude) SupportsEffort()

SupportsEffort marks Claude as able to carry Config.Effort, via output_config.effort. The API's ladder is low/medium/high/xhigh/max, which is exactly the neutral ladder, so nothing is clamped or invented.

func (*Claude) SupportsSampling added in v0.3.0

func (c *Claude) SupportsSampling()

SupportsSampling marks Claude as able to carry Config.Temperature and TopP.

Structural only. Whether the selected *model* accepts them is a separate question that cannot be answered here — claude-opus-4-8 reports temperature as deprecated while claude-sonnet-4-5 accepts it — and surfaces as chat.ErrModelRejectedParameter when the request is made.

func (*Claude) SupportsStateless added in v0.2.0

func (c *Claude) SupportsStateless()

SupportsStateless marks Claude as honouring chat.Config.Stateless.

Directories

Path Synopsis
internal
detectmodels command
Command detectmodels reports when Anthropic has shipped something the module's default model does not reflect.
Command detectmodels reports when Anthropic has shipped something the module's default model does not reflect.
genmodels command
Command genmodels regenerates the per-model capability table.
Command genmodels regenerates the per-model capability table.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL