claude

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Arandu

Claude for Arandu

Claude behind one call an Arandu application can make and a test can replace: a prompt goes in, text or a schema-checked JSON answer comes out, with what it cost.

It is a thin layer over the official Anthropic Go SDK. The SDK keeps the HTTP client, the retries on 408, 409, 429 and 5xx, and the typed errors. This package adds three things an application otherwise writes every time:

  • a configuration refused at boot, not on the first request;
  • an answer returned only when it is whole. A refusal, an answer cut at the token cap, an empty answer or invalid JSON is an error, never a partial result;
  • the Completer interface, with a Fake, so the code that calls Claude is tested without a key or the network.

It owns no table, no route and no policy, and it does not import the framework: an application on any framework version installs it.

Install

go get github.com/hyz-is/arandu-claude@latest

Wire it

The key comes from the application's environment, through its own config; this package never reads the environment.

// bootstrap/app.go
ai, err := claude.New(claude.Config{
    APIKey: cfg.Services.Anthropic.Secret, // ANTHROPIC_API_KEY
    // Model:  "claude-opus-5-5",          // the default
    // Effort: claude.EffortHigh,          // the default
})
if err != nil {
    return App{}, err
}
proposals := services.NewProposals(db, ai) // takes a claude.Completer

Use it

res, err := ai.Complete(ctx, claude.Request{
    System: proposalTemplate, // stable: sent as a cached block
    Prompt: project.Description,
    Schema: map[string]any{
        "type": "object",
        "properties": map[string]any{
            "fit":   map[string]any{"type": "integer"},
            "offer": map[string]any{"type": "integer"},
            "text":  map[string]any{"type": "string"},
        },
        "required":             []string{"fit", "offer", "text"},
        "additionalProperties": false,
    },
})
switch {
case errors.Is(err, claude.ErrRefused):   // declined for policy reasons
case errors.Is(err, claude.ErrTruncated): // reached the token cap
case err != nil:                          // network, API or invalid answer
}
var draft struct{ Fit, Offer int; Text string }
_ = res.Decode(&draft)
log.Info("claude", "model", res.Model, "in", res.Usage.InputTokens, "out", res.Usage.OutputTokens)

Test with it

fake := claude.NewFake(claude.Answer{JSON: `{"fit": 80, "offer": 6000, "text": "…"}`})
svc := services.NewProposals(db, fake)
// … exercise svc …
fake.Requests()[0].Prompt // what the service asked

Config

field default
APIKey required the Anthropic API key
Model claude-opus-5-5 any model id
Effort high low, medium, high, xhigh, max; a Request can override it
MaxTokens 16000 the cap on one answer; a Request can override it
Timeout 2 minutes one request, retries included
MaxRetries the SDK's 2 negative turns retries off
BaseURL, HTTPClient the SDK's for a proxy or a test server
NoFallback false turns off the server-side fallback for policy refusals

The server-side fallback (fallbacks: "default") is on by default: when the model declines a request for policy reasons, the API re-serves it on that model's default substitute, and Result.Model says which model answered.

License

MIT. See LICENSE.md.

Documentation

Overview

Package claude puts Claude behind one call an Arandu application can make and a test can replace: a prompt goes in, text or a schema-checked JSON answer comes out, with what it cost.

It is a thin layer over the official Anthropic Go SDK. The SDK keeps what it already does well -- the HTTP client, retries on 408, 409, 429 and 5xx (529 included), typed errors -- and this package adds the three things an application otherwise writes by hand every time: a configuration that is refused at boot rather than on the first request, the answer read only after the stop reason says it is whole, and an interface so the code that calls Claude is tested without the network.

Index

Constants

View Source
const DefaultMaxTokens = 16000

DefaultMaxTokens bounds one answer when neither Config nor Request says otherwise. It is generous on purpose: an answer cut at the cap is an error here (ErrTruncated), and a retry costs more than the headroom.

View Source
const DefaultModel = "claude-opus-5-5"

DefaultModel is the model asked when Config leaves Model empty.

Variables

View Source
var (
	// ErrRefused: the model declined the request for policy reasons, and no
	// fallback served it. Refusal carries the category.
	ErrRefused = errors.New("claude: the model declined the request")
	// ErrTruncated: the answer reached MaxTokens and stopped mid-way.
	ErrTruncated = errors.New("claude: the answer reached the token cap")
	// ErrEmpty: the answer carried no text.
	ErrEmpty = errors.New("claude: the answer is empty")
)

The ways an answer can fail after the API accepted the request.

View Source
var ErrScriptExhausted = errors.New("claude: the fake has no scripted answer left")

ErrScriptExhausted is what a Fake answers once its script has run out.

Functions

This section is empty.

Types

type Answer

type Answer struct {
	Text string
	JSON string
	Err  error
}

Answer is one scripted answer: the text, or the JSON for a structured request, or an error.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls the Anthropic API.

func New

func New(cfg Config) (*Client, error)

New builds the client, refusing a configuration that cannot work.

func (*Client) Complete

func (c *Client) Complete(ctx context.Context, req Request) (Result, error)

Complete asks one question and answers only a whole answer: a refusal, a cut answer or an empty one is an error, never a partial Result.

func (*Client) Model

func (c *Client) Model() string

Model is the model the client asks by default.

type Completer

type Completer interface {
	Complete(ctx context.Context, req Request) (Result, error)
}

Completer is what calls Claude. *Client implements it against the API and *Fake in memory, so the code that depends on it is tested without either a key or the network.

type Config

type Config struct {
	// APIKey is the Anthropic API key. Required.
	APIKey string
	// Model is the model id; empty means DefaultModel.
	Model string
	// Effort is the default effort; empty means EffortHigh. A Request can
	// ask for another.
	Effort Effort
	// MaxTokens is the default cap on one answer; zero means DefaultMaxTokens.
	MaxTokens int64
	// Timeout bounds one request, retries included; zero means two minutes.
	Timeout time.Duration
	// MaxRetries is how many times the SDK retries a retryable failure; a
	// negative value means none, zero means the SDK's default of two.
	MaxRetries int
	// BaseURL replaces the API's address, for a proxy or a test server.
	BaseURL string
	// HTTPClient replaces the SDK's HTTP client.
	HTTPClient *http.Client
	// NoFallback turns off the server-side fallback that re-serves a request
	// the model declined for policy reasons on the model's default
	// substitute. It is on by default.
	NoFallback bool
}

Config is what the application passes when it builds the client. The key comes from the application's own environment; this package never reads the environment itself.

type Effort

type Effort string

Effort is how much the model should put into an answer: "low", "medium", "high", "xhigh" or "max".

const (
	EffortLow    Effort = "low"
	EffortMedium Effort = "medium"
	EffortHigh   Effort = "high"
	EffortXHigh  Effort = "xhigh"
	EffortMax    Effort = "max"
)

The effort levels the API accepts.

type Fake

type Fake struct {
	// contains filtered or unexported fields
}

Fake answers from a script, in memory, and records what it was asked. It is what an application's tests pass where production passes *Client.

fake := claude.NewFake(claude.Answer{JSON: `{"fit": 80}`})
svc := services.NewProposals(db, fake)
...
fake.Requests()[0].Prompt // what the service asked

func NewFake

func NewFake(answers ...Answer) *Fake

NewFake builds a fake that gives the answers in order.

func (*Fake) Complete

func (f *Fake) Complete(_ context.Context, req Request) (Result, error)

Complete records the request and gives the next scripted answer.

func (*Fake) Push

func (f *Fake) Push(answers ...Answer)

Push appends answers to the script.

func (*Fake) Requests

func (f *Fake) Requests() []Request

Requests are the requests received, in order.

type Refusal

type Refusal struct {
	Category    string
	Explanation string
}

Refusal is ErrRefused with what the API said about it.

func (*Refusal) Error

func (r *Refusal) Error() string

func (*Refusal) Unwrap

func (r *Refusal) Unwrap() error

Unwrap makes errors.Is(err, ErrRefused) hold.

type Request

type Request struct {
	// System is the instruction that frames every answer: who is answering,
	// the rules, the template. It is sent as a cached system block, so a
	// long and stable System costs less from the second request on.
	System string
	// Prompt is the question itself. Required.
	Prompt string
	// Schema, when set, is the JSON schema the answer must satisfy; the
	// answer then arrives in Result.JSON. Objects in it need
	// "additionalProperties": false.
	Schema map[string]any
	// Effort and MaxTokens override the client's defaults for this request.
	Effort    Effort
	MaxTokens int64
}

Request is one question.

type Result

type Result struct {
	// Text is the answer's text. For a structured request it is the JSON.
	Text string
	// JSON is the answer for a request with a Schema; empty otherwise.
	JSON json.RawMessage
	// Model is the model that answered, which can differ from the one asked
	// when the server-side fallback served the request.
	Model string
	// ID is the message id, for correlating with the Anthropic console.
	ID    string
	Usage Usage
}

Result is a whole answer.

func (Result) Decode

func (r Result) Decode(v any) error

Decode reads a structured answer into v.

type Usage

type Usage struct {
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
}

Usage is what a request cost, in tokens.

Jump to

Keyboard shortcuts

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