typesafe

package module
v0.0.0-...-661bcea Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 24 Imported by: 0

README

TypeSafe AI SDK for Go

Disclaimer: This project is an independent, community-maintained Go SDK. It is not officially affiliated with, maintained, or endorsed by TypeSafe AI.

CI Go Reference

A Go client SDK for the TypeSafe AI API — typed answers to named questions about any state, in a single request. Zero runtime dependencies (Go standard library only), with feature parity to the Python SDK v0.7.0.

client, err := typesafe.NewClient() // reads TYPESAFE_API_KEY
if err != nil { return err }
defer client.Close()

resp, err := client.SystemOne(ctx, &typesafe.SystemOneParams{
    State: map[string]any{"document": "I was charged twice. Please fix this ASAP."},
    Questions: typesafe.Questions{
        "category": typesafe.Choice{
            Instructions: "What is this ticket about?",
            Criteria:     typesafe.ChoiceCriteria{"billing": nil, "technical": nil, "other": nil},
        },
        "urgent": typesafe.Noul{Instructions: "Is this urgent?"},
        "tone": typesafe.Score{
            Instructions: "How polite is the tone?",
            Criteria:     typesafe.ScoreCriteria{"rude", "neutral", "polite"},
        },
    },
})
if err != nil { return err }

fmt.Println(resp.Choices()["category"].Choice) // "billing"
fmt.Println(resp.Nouls()["urgent"].Noul)       // 0.92
fmt.Println(resp.Scores()["tone"].Score)       // 1.4

The question kind you ask determines the statically-known answer type you get back — that is the "type safety":

Primitive Question Answer
Noul yes/no NoulAnswer{Noul float64} — probability of true, 0..1
Choice classification ChoiceAnswer{Choice, Confidence, Probabilities}
Score rubric scoring ScoreAnswer{Score, Confidence, Legend, Probabilities}

Installation

go get github.com/captain-corgi/typesafe-sdk-go

Requires Go 1.27 or newer. The import path ends in typesafe-sdk-go but the package is named typesafe (like go-openai):

import "github.com/captain-corgi/typesafe-sdk-go" // package typesafe

Configuration

Explicit options beat environment variables, which beat defaults. Environment values are trimmed and ignored when blank. Empty explicit strings inherit; whitespace-only explicit API keys also inherit. Other explicit strings, including base URLs, model names, and nonblank API keys, are preserved verbatim.

Setting Option Environment Default
API key WithAPIKey TYPESAFE_API_KEY — (required)
Base URL WithBaseURL TYPESAFE_BASE_URL https://api.typesafe.ai
Model WithModel TYPESAFE_DEFAULT_MODEL jev-latest
Timeout (per attempt) WithTimeout — 10s
Maximum response body WithMaxResponseBodySize — 16 MiB
Allow loopback HTTP WithAllowInsecureHTTP — disabled
Retry policy WithRetry — DefaultRetryPolicy()
Default headers WithHeaders — —
Underlying HTTP client WithHTTPClient — new http.Client
client, err := typesafe.NewClient(
    typesafe.WithAPIKey("ts_live_..."),
    typesafe.WithBaseURL("https://api.typesafe.ai"),
    typesafe.WithModel("jev-latest"),
    typesafe.WithTimeout(10*time.Second),
)

Questions

Questions are values — build them inline. Optional fields left at their zero value are omitted from the wire; nested values (including explicit nils inside maps and slices) are preserved.

// Yes/no, with outcome descriptions.
typesafe.Noul{
    Instructions: "Is this message spam?",
    Criteria: &typesafe.NoulCriteria{
        True:  "Unsolicited advertising",
        False: "A legitimate conversation",
    },
}

// Classification; criteria labels map to descriptions (nil = label alone).
typesafe.Choice{
    Instructions: "What is the tone?",
    Criteria: typesafe.ChoiceCriteria{
        "angry":   "An upset or hostile message",
        "calm":    "A neutral or polite message",
        "excited": nil,
    },
}

// Rubric scoring; each entry is one level, scored from zero.
typesafe.Score{
    Instructions: "How urgent is this message?",
    Criteria:     typesafe.ScoreCriteria{"can wait", "this week", "today"},
}

Raw dictionaries pass through to the API untouched (unknown fields included) — the API is the schema validator for anything this SDK does not model:

"custom": typesafe.RawQuestion{
    "type": "noul", "instructions": "Spam?", "weight": 3,
},

Questions are validated before any network I/O: an empty question map, a raw question without a non-empty string type, a choice/score question without criteria, or empty score criteria all fail fast with a *typesafe.TypeSafeError.

Raw score criteria may use custom JSON or text marshalers. Their output is left for the API to validate; the SDK encodes them once per call and reuses the body on retries. Ordinary empty criteria and cyclic pointer/interface chains are rejected before network I/O.

Responses

SystemOne groups answers by kind, so the Go types line up with the questions you asked:

resp.Model                       // "jev-latest"
resp.Usage.InputTokens           // *int (nil when unreported)
resp.Answers["category"]         // typesafe.Answer interface
resp.Nouls()["urgent"].Noul      // float64
resp.Choices()["category"].Choice          // string
resp.Choices()["category"].Confidence      // float64
resp.Choices()["category"].Probabilities   // map[string]float64
resp.Scores()["tone"].Score                // float64 (expected value; may be fractional)
resp.Scores()["tone"].Legend               // map[int]any  — level → rubric entry
resp.Scores()["tone"].Probabilities        // map[int]float64
resp.RequestID                   // from the x-typesafe-request-id header
resp.Raw                         // *http.Response with a buffered, readable body

The per-kind views are plain maps, so reading a name with no answer of that kind — the server never answered it, or (only with a misbehaving server) answered a different kind, since the API guarantees answer kinds match question kinds — yields the Go zero value, where Python's result.nouls["urgent"] raises KeyError. Detect absence with the comma-ok form:

if a, ok := resp.Nouls()["urgent"]; ok {
    fmt.Println(a.Noul)
}

Separate single-answer lookup helpers (resp.Noul("urgent")) are deliberately not provided; the map views plus comma-ok are the idiomatic Go analog of the Python accessors.

Answer kinds this SDK version does not model are dropped from Answers (with a warning) but remain readable through resp.Raw.

client.Models.List(ctx, nil) returns *typesafe.ListModelsResponse with each model's Name, Description, and ReleaseDate.

A 2xx body that violates the schema fails with a *typesafe.ResponseValidationError whose FieldPath names the first bad field, e.g. answers.tone.confidence or models[1].name.

Responses captured outside the client (your own transport, a replayed recording) can be decoded with the same taxonomy: typesafe.ParseSystemOneResponse(resp) and typesafe.ParseListModelsResponse(resp) buffer the body, map non-2xx statuses to the typed error classes, and parse 2xx bodies — the counterpart of the Python SDK's Response.from_http_response.

Error handling

Every failure is matched with errors.As:

Error type Meaning
*typesafe.TypeSafeError shared root of every SDK error below; used directly for SDK-side failures (missing key, bad params), wrapping sentinels like ErrMissingAPIKey, ErrClientClosed
*typesafe.APIError any non-2xx response (Status, Body raw wire text, DecodedBody parsed JSON, Headers, Endpoint, RequestID)
*typesafe.BadRequestError … *typesafe.RateLimitError 400 / 401 / 403 / 404 / 422 / 429 subclasses
*typesafe.InternalServerError any status ≥ 500
*typesafe.ResponseValidationError 2xx body that failed schema validation (FieldPath)
*typesafe.ConnectionError no HTTP response; transport cause preserved via Unwrap
*typesafe.TimeoutError attempt exceeded its timeout; satisfies net.Error

Subclasses match both their specific type and *typesafe.APIError; a *typesafe.TimeoutError also matches *typesafe.ConnectionError (like the Python SDK's class hierarchy):

var rl *typesafe.RateLimitError
if errors.As(err, &rl) && rl.RetryAfterMs != nil {
    fmt.Println("retry after ms:", *rl.RetryAfterMs)
}

Every SDK error — API subclasses, response validation, connection, and timeout failures alike — also matches the shared *typesafe.TypeSafeError root, so one catch-all handler sees them all (the counterpart of catching TypeSafeError in the Python SDK):

var root *typesafe.TypeSafeError
if errors.As(err, &root) {
    log.Printf("typesafe call failed: %v", root)
}

Caller cancellation and deadlines return context.Canceled or context.DeadlineExceeded directly; these are not SDK errors and do not match *TypeSafeError. The reverse direction is not symmetric: because an SDK attempt timeout preserves its transport cause chain, it also satisfies errors.Is(err, context.DeadlineExceeded). When you need to tell the two apart, match SDK types with errors.As first (e.g. *TimeoutError) and only treat context.DeadlineExceeded as your own deadline once no SDK type matched.

Error strings follow <METHOD> <url>: <status> <message> (request_id=…), with parts omitted when absent — e.g.

POST https://api.typesafe.ai/v1/systemone: 429 Too many requests (request_id=req_123)

Retries

Every request runs under a RetryPolicy. typesafe.DefaultRetryPolicy() retries twice on statuses {408, 429, 500–599}, connection errors, and timeouts, with 0.5s→5s exponential backoff (25% jitter), honoring Retry-After / retry-after-ms, all inside a 30s per-call budget:

policy := typesafe.DefaultRetryPolicy()
policy.MaxRetries = 4
policy.HTTPStatuses = map[int]struct{}{429: {}, 502: {}, 503: {}}
client, _ := typesafe.NewClient(typesafe.WithAPIKey(key), typesafe.WithRetry(policy))
  • MaxRetries: 0 disables retries; BackoffInitial: 0 disables backoff.
  • Timeout is the total budget per SDK call: the loop stops before a retry whose delay would reach it, surfacing the last error. 0 disables.
  • RetryOn adds selectors: an SDK error instance (&NotFoundError{}) or a typed nil ((*MyError)(nil)) selects by type via errors.As — wrapped, errors.Join-ed, and custom-As errors all match; any other entry is a sentinel matched strictly by identity via errors.Is, so two distinct errors of the same type never match each other. Predicate covers anything else.
  • The policy is snapshotted per call; per-call Retry replaces the client policy for that call only.

Per-call overrides

resp, err := client.SystemOne(ctx, &typesafe.SystemOneParams{
    State: ..., Questions: ...,
    Model:        "jev-latest",                    // per-call model
    Timeout:      5 * time.Second,                 // per-call timeout
    Retry:        &policy,                         // per-call retry policy
    ExtraHeaders: map[string]string{"X-Custom": "v"},
    ExtraBody:    map[string]any{"custom_field": 1}, // state/model/questions cannot be overridden
})

Protected headers (Authorization, Accept, Content-Type, User-Agent, X-TypeSafe-*) are always set by the SDK and cannot be overridden. Retries carry X-TypeSafe-Retry-Count: <n> (never on the first attempt).

ExtraBody is a shallow merge for additional top-level fields. The SDK-owned state, model, and questions fields are reserved and attempting to override any of them returns a *typesafe.TypeSafeError before network I/O.

Logging

The SDK logs through log/slog, tagged typesafe_sdk (the same attribution as the Python SDK's logger), and is silent by default. Set TYPESAFE_LOG_LEVEL=debug for wire dumps (secret headers redacted), or take full control of destination, format, and level with typesafe.SetLogger(yourLogger). Request and response bodies are redacted by default. Set TYPESAFE_LOG_BODY=redacted to preserve JSON structure while masking string values, or TYPESAFE_LOG_BODY=full (or call typesafe.SetLogBodyMode(typesafe.LogBodyFull)) only in controlled environments; full body logging can expose sensitive payloads. Logged bodies are capped at 16 KiB.

Security

  • To report a vulnerability, see SECURITY.md — please do not open a public issue.
  • Responses are bounded to 16 MiB by default. Use WithMaxResponseBodySize to select a positive per-client limit; oversized bodies return ErrResponseTooLarge / *ResponseTooLargeError and are not retried.
  • Base URLs must be absolute https URLs without userinfo, query, or fragments. WithAllowInsecureHTTP permits http only for localhost and loopback IP addresses, such as 127.0.0.1 and ::1, and is intended for local development and tests.
  • Authorization and other secret headers remain redacted in wire logs.
  • ExtraBody cannot override the reserved state, model, or questions fields.

Examples

Runnable cookbook programs live in examples/. The automation-use-cases/ and task-categories/ catalogs mirror the docs use-case map. Additional go-software-use-cases/, api-use-cases/, relational-db-use-cases/, and testing-use-cases/ catalogs implement the proposed patterns in plans/20260923-jev-go-software-use-cases/. Two basics — quickstart and retries-errors — sit at the root. Each example runs against the live API with TYPESAFE_API_KEY set:

TYPESAFE_API_KEY=... go run ./examples/quickstart

Deviations from the Python SDK

This port keeps Python v0.7.0 behavior, with deliberate Go adaptations:

  1. No response_model overload — Go structs are the typed response; there is no runtime schema type to substitute.
  2. One timeout — time.Duration per attempt via context, not httpx-style connect/read/write/pool splits.
  3. Typed questions validate in SystemOne (pre-network) rather than at construction — Go constructors cannot raise validation errors; the same client-side guarantee holds either way. A typed [NoulCriteria] cannot express an explicit JSON null outcome (a nil field omits the key where Python emits "true": null) — use a [RawQuestion] for that wire form. Raw criteria with custom JSON/text marshalers are encoded once and left for API validation; their underlying Go zero values are not used to reject them.
  4. One client — Go's context/goroutine model replaces the sync/async client split.
  5. Slightly laxer JSON decoding — stdlib field matching is case-insensitive and integer literals decode into float fields (documented encoding/json behavior). Response bodies with NaN/Infinity literals or out-of-range numbers like 1e400 (which Python's parser accepts as infinity) are rejected, and usage counts beyond int64 fail response validation.
  6. No APIPromise — meaningless without Promise semantics; resp.Raw *http.Response covers raw access.
  7. Idiomatic Go zero values — resp.RequestID is "" when the header is absent (Python raises on access), and *APIError.Body keeps the raw wire text with the parsed value on DecodedBody (Python exposes only the parsed body as body). The SDK is fully silent by default; Python's stdlib logging happens to print WARNING+ records (such as the unknown-answer drop notice) to stderr out of the box via its last-resort handler — set TYPESAFE_LOG_LEVEL or use SetLogger to see them here.
  8. Cosmetic edge differences — invalid UTF-8 in error bodies collapses to one replacement character per run, non-string FastAPI loc segments, %q-escaped identifiers in validation messages (Python interpolates names raw), and fallback re-serialization of unstructured error bodies use Go formatting, and HTTP-date coverage in Retry-After follows Go's http.ParseTime rather than Python's RFC 2822 parser. None of these are reachable with spec-conforming servers.
  9. Zero-value sentinels — a zero time.Duration timeout means "unset" (inherit) where Python rejects timeout=0; an empty Model string means "use the default" where Python would send it verbatim. WithHTTPClient inherits the supplied client's Timeout — when positive — if WithTimeout is not set; the resolved timeout is then enforced per attempt through its context on an SDK-owned copy of the client (outer Timeout disabled, the caller's client never modified), so a longer SDK timeout is never capped by the injected client's own deadline.
  10. Wire bytes — request/response JSON objects are emitted with sorted keys where Python preserves insertion order, and Go's encoder escapes U+2028/U+2029 that Python emits raw; parsed values are identical. Float number tokens may print differently (1 vs Python's 1.0, 1e+21 vs 1e21) — identical parsed values, and Go matches JavaScript's JSON.stringify here. Close only closes idle connections (Go has no full-close API); the SDK-owned client pools them on a private transport, so closing it never evicts other code's connections, and reuse of a closed client returns a typed ErrClientClosed error rather than a transport panic.
  11. Security hardening — unlike Python, wire bodies are redacted by default, response bodies have a 16 MiB limit, base URLs require HTTPS (with loopback-only opt-in for HTTP), and ExtraBody cannot override SDK-owned fields.

License

MIT

Documentation

Overview

Package typesafe is a community-maintained Go client SDK for the TypeSafe AI API (https://typesafe.ai).

**Disclaimer:** This project is an independent, community-maintained Go SDK. It is not officially affiliated with, maintained, or endorsed by TypeSafe AI.

The API answers typed, named questions about a piece of "state" in a single request ("System One"): you POST a state plus a map of questions, and each answer's type is determined statically by the kind of question you asked.

Questions

There are three question primitives:

  • Noul asks a yes/no question and answers with NoulAnswer, a probability between 0 and 1.
  • Choice classifies state into named labels and answers with ChoiceAnswer, the selected label plus a confidence and per-label probabilities.
  • Score rates state against an ordered rubric and answers with ScoreAnswer, the expected score plus a confidence, a legend mapping score levels to rubric entries, and per-level probabilities.

Questions may also be supplied as raw dictionaries (RawQuestion) for fields this SDK does not model; raw questions are passed through to the API untouched. Raw score criteria implementing JSON or text marshaling are encoded once per call and left for API validation. Ordinary empty criteria and cyclic pointer/interface chains are rejected before network I/O.

Quick start

client, err := typesafe.NewClient() // reads TYPESAFE_API_KEY
if err != nil {
	return err
}
defer client.Close()

resp, err := client.SystemOne(ctx, &typesafe.SystemOneParams{
    State: map[string]any{"document": "I was charged twice. Please fix this ASAP."},
    Questions: typesafe.Questions{
        "urgent": typesafe.Noul{Instructions: "Is this urgent?"},
    },
})
fmt.Println(resp.Nouls()["urgent"].Noul)

Configuration

Explicit client options take precedence over environment variables, which in turn take precedence over defaults. Empty or whitespace-only environment values are ignored.

[TYPESAFE_API_KEY]       API key (required unless WithAPIKey is used)
[TYPESAFE_BASE_URL]      API root (default "https://api.typesafe.ai")
[TYPESAFE_DEFAULT_MODEL] default model (default "jev-latest")
[TYPESAFE_LOG_LEVEL]     debug | info | warn | warning | error | off
[TYPESAFE_LOG_BODY]      off | redacted | full (default off)

Base URLs must use HTTPS. WithAllowInsecureHTTP permits HTTP only for loopback hosts, which is useful for local development and tests. Responses are limited to 16 MiB by default; WithMaxResponseBodySize changes that per-client limit. Wire request and response bodies are redacted by default; use SetLogBodyMode(LogBodyFull) only in controlled environments.

Errors and retries

SDK-classified failures share the TypeSafeError root: a catch-all `errors.As(err, &root)` with a *TypeSafeError target matches them, like catching TypeSafeError in the Python SDK. Caller cancellation and deadlines return context.Canceled or context.DeadlineExceeded directly, without the SDK root; note that an SDK attempt timeout — TimeoutError — also satisfies errors.Is(err, context.DeadlineExceeded) through its preserved transport cause, so match SDK types with errors.As before attributing DeadlineExceeded to your own deadline. Failed HTTP responses map to typed subclasses of APIError such as RateLimitError, matched with errors.As. Every request runs under a RetryPolicy (connection errors, timeouts, and the statuses {408, 429, 500–599} by default). RetryOn entries either select a type — an SDK error instance such as &NotFoundError{}, or a typed nil like (*MyError)(nil), matched with errors.As — or name a sentinel matched strictly by identity with errors.Is; RetryPolicy.Predicate covers custom matching.

Logging

The SDK is silent by default. Set TYPESAFE_LOG_LEVEL (debug | info | warn | warning | error | off) for diagnostics on stderr, or take full control of output and format with SetLogger. Secret headers and request/response bodies are redacted from wire log output by default.

Index

Examples

Constants

View Source
const (
	// EnvAPIKey is the environment variable holding the API key.
	EnvAPIKey = "TYPESAFE_API_KEY"
	// EnvBaseURL is the environment variable overriding the API base URL.
	EnvBaseURL = "TYPESAFE_BASE_URL"
	// EnvDefaultModel is the environment variable overriding the default model.
	EnvDefaultModel = "TYPESAFE_DEFAULT_MODEL"
	// EnvLogLevel is the environment variable selecting the SDK log level
	// (debug | info | warn | warning | error | off).
	EnvLogLevel = "TYPESAFE_LOG_LEVEL"
	// EnvLogBody is the environment variable selecting wire-body logging
	// (off | redacted | full).
	EnvLogBody = "TYPESAFE_LOG_BODY"

	// DefaultBaseURL is the default API base URL.
	DefaultBaseURL = "https://api.typesafe.ai"
	// DefaultModel is the default model name.
	DefaultModel = "jev-latest"
	// DefaultTimeout is the default timeout for each HTTP attempt.
	DefaultTimeout = 10 * time.Second
	// DefaultMaxResponseBodySize is the maximum response body buffered by the
	// SDK and standalone response parsers.
	DefaultMaxResponseBodySize int64 = 16 << 20
)

Public environment-variable names and client defaults.

View Source
const Version = "0.7.0"

Version is the installed SDK version. It signals feature parity with the sibling Python SDK's version of the same number.

Variables

View Source
var ErrClientClosed = errors.New("client is closed")

ErrClientClosed is wrapped by the error returned when a closed client is used again.

View Source
var ErrInvalidBaseURL = errors.New("invalid base URL")

ErrInvalidBaseURL is wrapped when a configured API base URL is unsafe or malformed.

View Source
var ErrMissingAPIKey = errors.New("missing API key")

ErrMissingAPIKey is wrapped by the error returned when no API key resolves from the constructor argument or the TYPESAFE_API_KEY environment variable.

View Source
var ErrResponseTooLarge = errors.New("response body exceeds configured limit")

ErrResponseTooLarge is wrapped when a response body exceeds its configured buffering limit.

Functions

func SetLogBodyMode

func SetLogBodyMode(mode LogBodyMode) error

SetLogBodyMode configures the body policy used by DEBUG wire logs.

func SetLogger

func SetLogger(l *slog.Logger)

SetLogger replaces the SDK's logger, giving full control over output destination, format, and level — the slog equivalent of configuring the "typesafe_sdk" logger in the Python SDK. The logger is tagged with a "logger"="typesafe_sdk" attribute so SDK records stay identifiable; pass nil to restore the silent default. Safe to call at any time.

Types

type APIError

type APIError struct {
	Status      int
	Body        string
	DecodedBody any
	Headers     http.Header
	Endpoint    string
	RequestID   string
	// contains filtered or unexported fields
}

APIError describes an unsuccessful HTTP response with its body and request metadata. Use errors.As to match the typed subclasses: BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, UnprocessableEntityError, RateLimitError, InternalServerError, and ResponseValidationError. Like every SDK error, it also matches the shared TypeSafeError root through errors.As.

func (*APIError) As

func (e *APIError) As(target any) bool

As additionally matches the shared SDK root: errors.As(err, &root) with a *TypeSafeError target succeeds for this error and every subclass (the method is promoted through the embedded *APIError). A subclass built without its embedded *APIError cannot render a message and never matches.

func (*APIError) Error

func (e *APIError) Error() string

Error formats the status and message with the available request context: "<METHOD> <url>: <status> <message> (request_id=<id>)", omitting parts that are absent.

type Answer

type Answer interface {
	// contains filtered or unexported methods
}

Answer is a typed answer to a single question, identified by its concrete type: NoulAnswer, ChoiceAnswer, or ScoreAnswer. Answer kinds this SDK version does not model are dropped from Answers (with a warning) but remain available on SystemOneResponse.Raw.

type AuthenticationError

type AuthenticationError struct{ *APIError }

AuthenticationError reports failed authentication (HTTP 401).

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

Error mirrors APIError.Error.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type BadRequestError

type BadRequestError struct{ *APIError }

BadRequestError reports an invalid request (HTTP 400).

func (*BadRequestError) Error

func (e *BadRequestError) Error() string

Error mirrors APIError.Error.

func (*BadRequestError) Unwrap

func (e *BadRequestError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type Choice

type Choice struct {
	Instructions JSONContent
	Criteria     ChoiceCriteria
}

Choice is a classification question answered by ChoiceAnswer with the selected label, a confidence, and per-label probabilities. Criteria is required; a nil Instructions is omitted from the wire form.

func (Choice) MarshalJSON

func (q Choice) MarshalJSON() ([]byte, error)

MarshalJSON emits the wire form: "type" first, then "instructions" when set, then the required "criteria".

type ChoiceAnswer

type ChoiceAnswer struct {
	Choice        string
	Confidence    float64
	Probabilities map[string]float64
}

ChoiceAnswer is a selected label with its probabilities.

type ChoiceCriteria

type ChoiceCriteria map[string]JSONContent

ChoiceCriteria maps labels to their descriptions (text, object, or array), or nil for undescribed labels. The map is required and may be empty.

type Client

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

Client is an HTTP client for the TypeSafe AI API. Create one with NewClient; it is safe for concurrent use, and per-call state (model, timeout, retry policy, headers) is fully isolated between calls. When finished, call Client.Close to release idle connections; using a closed client returns an error wrapping ErrClientClosed.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a client for the TypeSafe AI API. Explicit options take precedence over environment variables (TYPESAFE_API_KEY, TYPESAFE_BASE_URL, TYPESAFE_DEFAULT_MODEL), which take precedence over defaults. Blank environment values, empty explicit strings, and whitespace-only explicit API keys inherit; other explicit strings are preserved. It returns an error wrapping ErrMissingAPIKey when no API key resolves, and option values are validated before the client is built.

func (*Client) Close

func (c *Client) Close()

Close releases network resources: it closes idle connections of the underlying *http.Client, including one supplied via WithHTTPClient. The SDK-owned default client runs on a private transport, so its Close never evicts connections pooled on the process-global http.DefaultTransport. The client must not be used afterwards; calls on a closed client return an error wrapping ErrClientClosed. Close is idempotent.

func (*Client) SystemOne

func (c *Client) SystemOne(ctx context.Context, params *SystemOneParams) (*SystemOneResponse, error)

SystemOne answers named questions about text or structured state in a single request. Questions are validated before any network I/O; the returned response carries answers keyed by question name, the model used, token usage, the request ID, and the buffered raw HTTP response.

Example

ExampleClient_SystemOne answers a mixed set of typed questions about a support ticket in a single request.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/captain-corgi/typesafe-sdk-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{
		  "model": "jev-latest",
		  "usage": {"input_tokens": 12, "output_tokens": 3},
		  "answers": {
		    "department": {"type": "choice", "choice": "billing", "confidence": 0.93,
		                   "probabilities": {"billing": 0.93, "technical": 0.05, "other": 0.02}},
		    "frustration": {"type": "score", "score": 2.0, "confidence": 0.88,
		                    "legend": {"0": "calm", "1": "annoyed", "2": "upset"},
		                    "probabilities": {"0": 0.05, "1": 0.07, "2": 0.88}},
		    "is_urgent": {"type": "noul", "noul": 0.91}
		  }
		}`)
	}))
	defer server.Close()

	client, err := typesafe.NewClient(
		typesafe.WithAPIKey("demo-key"),
		typesafe.WithBaseURL(server.URL), typesafe.WithAllowInsecureHTTP(),
		typesafe.WithAllowInsecureHTTP(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	resp, err := client.SystemOne(context.Background(), &typesafe.SystemOneParams{
		State: map[string]any{"document": "I was charged twice. Please fix this ASAP."},
		Questions: typesafe.Questions{
			"department": typesafe.Choice{
				Instructions: "What is this ticket about?",
				Criteria:     typesafe.ChoiceCriteria{"billing": nil, "technical": nil, "other": nil},
			},
			"frustration": typesafe.Score{
				Instructions: "How frustrated is the customer?",
				Criteria:     typesafe.ScoreCriteria{"calm", "annoyed", "upset"},
			},
			"is_urgent": typesafe.Noul{Instructions: "Is this urgent?"},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("department:", resp.Choices()["department"].Choice)
	fmt.Println("urgency:", resp.Nouls()["is_urgent"].Noul)
	fmt.Println("frustration:", resp.Scores()["frustration"].Score)
	fmt.Println("input tokens:", *resp.Usage.InputTokens)
}
Output:
department: billing
urgency: 0.91
frustration: 2
input tokens: 12

type ConnectionError

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

ConnectionError reports a request that failed without an HTTP response, with the transport-level cause preserved for errors.Unwrap.

func (*ConnectionError) As

func (e *ConnectionError) As(target any) bool

As additionally matches the shared SDK root: errors.As(err, &root) with a *TypeSafeError target succeeds for connection failures.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error implements the error interface.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap exposes the transport-level cause.

type InternalServerError

type InternalServerError struct{ *APIError }

InternalServerError reports a server failure (any HTTP status >= 500).

func (*InternalServerError) Error

func (e *InternalServerError) Error() string

Error mirrors APIError.Error.

func (*InternalServerError) Unwrap

func (e *InternalServerError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type JSONContent

type JSONContent = any

JSONContent is any value acceptable as request state, instructions, or criteria: a string, a JSON object (map[string]any), a JSON array ([]any), or any nested combination, with null allowed inside nested values.

type JSONValue

type JSONValue = any

JSONValue is any JSON value, used for the free-form ExtraBody fields.

type ListModelsResponse

type ListModelsResponse struct {
	Models []ModelMetadata

	RequestID string
	Raw       *http.Response
}

ListModelsResponse lists the models available to the account. RequestID and Raw are attached to every response created by the client; Raw's body has been buffered, so it is safe to read.

func ParseListModelsResponse

func ParseListModelsResponse(resp *http.Response) (*ListModelsResponse, error)

ParseListModelsResponse decodes an HTTP response from GET /v1/models into a ListModelsResponse; see ParseSystemOneResponse for the contract.

type LogBodyMode

type LogBodyMode string

LogBodyMode controls whether request and response bodies appear in DEBUG wire logs.

const (
	// LogBodyOff prevents wire bodies from appearing in logs.
	LogBodyOff LogBodyMode = "off"
	// LogBodyRedacted logs JSON structure while replacing string values.
	LogBodyRedacted LogBodyMode = "redacted"
	// LogBodyFull logs raw wire bodies, subject to the logging size limit.
	LogBodyFull LogBodyMode = "full"
)

type ModelMetadata

type ModelMetadata struct {
	Name        string
	Description string
	ReleaseDate string
}

ModelMetadata describes a single available model.

type Models

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

Models is the Models API resource, reached through Client.Models.

Example

ExampleModels lists the models available to the account.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/captain-corgi/typesafe-sdk-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{"models": [
		  {"name": "jev-latest", "description": "General-purpose system one model.", "release_date": "2026-09-15"}
		]}`)
	}))
	defer server.Close()

	client, _ := typesafe.NewClient(typesafe.WithAPIKey("demo-key"), typesafe.WithBaseURL(server.URL), typesafe.WithAllowInsecureHTTP())
	defer client.Close()

	models, err := client.Models.List(context.Background(), nil)
	if err != nil {
		log.Fatal(err)
	}
	for _, model := range models.Models {
		fmt.Printf("%s (released %s): %s\n", model.Name, model.ReleaseDate, model.Description)
	}
}
Output:
jev-latest (released 2026-09-15): General-purpose system one model.

func (*Models) List

func (m *Models) List(ctx context.Context, params *ModelsListParams) (*ListModelsResponse, error)

List returns the models available to the account.

type ModelsListParams

type ModelsListParams struct {
	// Timeout overrides the client per-attempt timeout for this call.
	Timeout time.Duration
	// Retry replaces the client retry policy for this call.
	Retry *RetryPolicy
	// ExtraHeaders are additional request headers for this call.
	ExtraHeaders map[string]string
}

ModelsListParams describes one GET /v1/models call. The zero values of the optional fields inherit the client settings.

type NotFoundError

type NotFoundError struct{ *APIError }

NotFoundError reports a missing resource (HTTP 404).

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error mirrors APIError.Error.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type Noul

type Noul struct {
	Instructions JSONContent
	Criteria     *NoulCriteria
}

Noul is a yes/no question answered by NoulAnswer with a probability of true. Instructions and criteria are optional; a nil Instructions is omitted from the wire form.

func (Noul) MarshalJSON

func (q Noul) MarshalJSON() ([]byte, error)

MarshalJSON emits the wire form: "type" first, then the optional "instructions" and "criteria" when set.

type NoulAnswer

type NoulAnswer struct {
	Noul float64
}

NoulAnswer is a yes/no answer: the probability of a yes or true statement, from 0 to 1.

type NoulCriteria

type NoulCriteria struct {
	True  JSONContent
	False JSONContent
}

NoulCriteria optionally describes the yes and no outcomes of a Noul question. A nil field omits the key from the wire form; values may be any JSON content with null allowed inside nested values. An explicit JSON null for an outcome (rather than omitting it) is not expressible with this typed struct — use a RawQuestion for that wire form.

func (NoulCriteria) MarshalJSON

func (c NoulCriteria) MarshalJSON() ([]byte, error)

MarshalJSON emits only the set criteria keys, preserving nested values verbatim.

type Option

type Option func(*clientSettings) error

Option customizes a Client at construction; see the With* functions.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey sets the API key, overriding the TYPESAFE_API_KEY environment variable. An empty or whitespace-only value means "unset".

func WithAllowInsecureHTTP

func WithAllowInsecureHTTP() Option

WithAllowInsecureHTTP permits http URLs only for loopback hosts. HTTPS remains the default and is required for remote hosts.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the API root, overriding the TYPESAFE_BASE_URL environment variable; any trailing slashes are stripped.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient supplies the underlying *http.Client. When WithTimeout is not set, a positive Timeout on the supplied client is inherited as the per-attempt timeout (a zero Timeout — Go's default, meaning no client-level cap — is not inherited, and the 10s SDK default applies). The resolved timeout always governs the whole attempt through its context: the SDK sends on its own copy of the client with the outer Timeout disabled, so an explicit SDK timeout longer than the supplied client's Timeout is honored in full and the caller's client is never modified. The client's Transport, Jar, and CheckRedirect are shared, and its idle connections are closed by Client.Close. A nil client is rejected. Note that the SDK's default client does not follow redirects (3xx responses surface as errors, like the other TypeSafe SDKs); supply your own client here if you want different behavior.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders sets additional default request headers; protected headers (Authorization, Accept, Content-Type, User-Agent, X-TypeSafe-*) can never be overridden this way.

func WithMaxResponseBodySize

func WithMaxResponseBodySize(size int64) Option

WithMaxResponseBodySize sets the maximum response body size buffered by this client. Zero uses DefaultMaxResponseBodySize.

func WithModel

func WithModel(model string) Option

WithModel sets the default model, overriding the TYPESAFE_DEFAULT_MODEL environment variable.

func WithRetry

func WithRetry(policy RetryPolicy) Option

WithRetry sets the client-level retry policy. The policy is validated at construction and snapshotted per call.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the per-attempt timeout, overriding the 10s default. Zero means "unset"; a negative value is rejected.

type PermissionDeniedError

type PermissionDeniedError struct{ *APIError }

PermissionDeniedError reports denied access (HTTP 403).

func (*PermissionDeniedError) Error

func (e *PermissionDeniedError) Error() string

Error mirrors APIError.Error.

func (*PermissionDeniedError) Unwrap

func (e *PermissionDeniedError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type Question

type Question interface {
	// contains filtered or unexported methods
}

Question is a typed or raw question about the request state. The zero interface is implemented only by Noul, Choice, Score, and RawQuestion; the concrete type determines the statically-known answer type.

type Questions

type Questions map[string]Question

Questions maps question names (chosen by the caller, echoed by the answers) to their questions. The map must be non-empty.

type RateLimitError

type RateLimitError struct {
	*APIError
	RetryAfterMs *float64
}

RateLimitError reports an exceeded rate limit (HTTP 429). RetryAfterMs is the server-requested wait in milliseconds, or nil when unavailable.

Example

ExampleRateLimitError shows matching typed errors with errors.As, including the server-requested retry delay on a rate-limit response.

package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/captain-corgi/typesafe-sdk-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Retry-After-Ms", "125")
		w.WriteHeader(http.StatusTooManyRequests)
		fmt.Fprint(w, `{"message": "slow down"}`)
	}))
	defer server.Close()

	policy := typesafe.DefaultRetryPolicy()
	policy.MaxRetries = 0
	client, _ := typesafe.NewClient(
		typesafe.WithAPIKey("demo-key"),
		typesafe.WithBaseURL(server.URL), typesafe.WithAllowInsecureHTTP(),
		typesafe.WithAllowInsecureHTTP(),
		typesafe.WithRetry(policy),
	)
	defer client.Close()

	_, err := client.Models.List(context.Background(), nil)

	var rateLimit *typesafe.RateLimitError
	if errors.As(err, &rateLimit) {
		fmt.Println("rate limited; retry after ms:", *rateLimit.RetryAfterMs)
		return
	}
	fmt.Println("unexpected error:", err)
}
Output:
rate limited; retry after ms: 125

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

Error mirrors APIError.Error.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type RawQuestion

type RawQuestion map[string]any

RawQuestion is a wire passthrough for question shapes this SDK does not model: it is sent to the API untouched (unknown fields included), and the API is the schema validator. The client only checks the minimal shape: a non-empty string "type", plus "criteria" for choice and score questions.

Example

ExampleRawQuestion shows the raw dictionary passthrough for question fields this SDK does not model.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/captain-corgi/typesafe-sdk-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{"model": "jev-latest", "usage": {},
		  "answers": {"spam": {"type": "noul", "noul": 0.02}}}`)
	}))
	defer server.Close()

	client, _ := typesafe.NewClient(typesafe.WithAPIKey("demo-key"), typesafe.WithBaseURL(server.URL), typesafe.WithAllowInsecureHTTP())
	defer client.Close()

	resp, err := client.SystemOne(context.Background(), &typesafe.SystemOneParams{
		State: "You have won a free prize, click here!",
		Questions: typesafe.Questions{
			"spam": typesafe.RawQuestion{
				"type":         "noul",
				"instructions": "Is this message spam?",
				"weight":       3,
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("spam probability:", resp.Nouls()["spam"].Noul)
}
Output:
spam probability: 0.02

type ResponseTooLargeError

type ResponseTooLargeError struct {
	Limit int64
}

ResponseTooLargeError reports a response body that exceeded the configured maximum size.

func (*ResponseTooLargeError) As

func (e *ResponseTooLargeError) As(target any) bool

As additionally matches the shared SDK root.

func (*ResponseTooLargeError) Error

func (e *ResponseTooLargeError) Error() string

func (*ResponseTooLargeError) Unwrap

func (e *ResponseTooLargeError) Unwrap() error

type ResponseValidationError

type ResponseValidationError struct {
	*APIError
	FieldPath string
}

ResponseValidationError reports a successful HTTP response whose body was missing or structurally invalid required data. FieldPath is the dotted path to the offending field, such as "answers.tone.confidence".

func (*ResponseValidationError) Error

func (e *ResponseValidationError) Error() string

Error mirrors APIError.Error.

func (*ResponseValidationError) Unwrap

func (e *ResponseValidationError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type RetryPolicy

type RetryPolicy struct {
	// MaxRetries is the number of retries after the initial attempt; 0
	// disables retries (total attempts = MaxRetries + 1).
	MaxRetries int

	// BackoffInitial is the first backoff delay, doubled each attempt up to
	// BackoffMax; 0 disables backoff (immediate re-attempt).
	BackoffInitial time.Duration

	// BackoffMax caps the un-jittered exponential backoff; 0 disables backoff.
	BackoffMax time.Duration

	// BackoffJitter is the fraction of each backoff delay randomly
	// subtracted, between 0 and 1.
	BackoffJitter float64

	// HTTPStatuses are the *APIError statuses that are retried.
	HTTPStatuses map[int]struct{}

	// RespectRetryAfter makes the server-requested delay (Retry-After /
	// retry-after-ms) win over backoff.
	RespectRetryAfter bool

	// APIConnectionError retries *ConnectionError.
	APIConnectionError bool

	// APITimeoutError retries *TimeoutError.
	APITimeoutError bool

	// RetryOn names additional errors that trigger a retry. An entry of an
	// SDK error type (such as [&NotFoundError{}]) or a typed-nil pointer
	// (such as (*MyError)(nil)) selects by type: any matching error in the
	// tree — including wrapped, joined, and custom-As errors — retries, via
	// [errors.As]. Any other entry is a sentinel matched only by identity
	// through [errors.Is]: two distinct errors of the same concrete type
	// never match each other, so give a sentinel a custom Is method or use
	// Predicate for class-based matching of custom errors.
	RetryOn []error

	// Predicate, when non-nil, is called with the raised error; returning
	// true triggers a retry in addition to the other rules. Like the Python
	// policy, it runs once per failed attempt — including the final attempt
	// that exceeds MaxRetries and is never retried — so counting or logging
	// predicates observe every failure. (One deliberate difference from
	// Python: a caller-canceled context returns before the predicate runs,
	// where tenacity would call it with CancelledError.)
	Predicate func(error) bool

	// Timeout is the total budget per SDK call, including the initial
	// attempt and all delays; 0 means unlimited. The loop stops before a
	// retry whose delay would reach the budget, re-raising the last error.
	Timeout time.Duration
}

RetryPolicy configures SDK retry behavior. The zero value is valid but retries nothing; start from DefaultRetryPolicy and adjust fields.

policy := typesafe.DefaultRetryPolicy()
policy.MaxRetries = 4
client, err := typesafe.NewClient(typesafe.WithRetry(policy))
Example

ExampleRetryPolicy configures a client with a custom retry policy and per-call overrides.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/captain-corgi/typesafe-sdk-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{"models": []}`)
	}))
	defer server.Close()

	policy := typesafe.DefaultRetryPolicy()
	policy.MaxRetries = 4
	policy.BackoffInitial = 200 * time.Millisecond
	policy.HTTPStatuses = map[int]struct{}{429: {}, 503: {}}

	client, err := typesafe.NewClient(
		typesafe.WithAPIKey("demo-key"),
		typesafe.WithBaseURL(server.URL), typesafe.WithAllowInsecureHTTP(),
		typesafe.WithAllowInsecureHTTP(),
		typesafe.WithRetry(policy),
		typesafe.WithTimeout(5*time.Second),
		typesafe.WithHeaders(map[string]string{"X-Team": "search"}),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// A single call can loosen the timeout and extend the retry budget.
	extended := typesafe.DefaultRetryPolicy()
	extended.Timeout = 2 * time.Minute
	if _, err := client.Models.List(context.Background(), &typesafe.ModelsListParams{
		Timeout: 30 * time.Second,
		Retry:   &extended,
	}); err != nil {
		log.Fatal(err)
	}
	fmt.Println("done")
}
Output:
done

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default retry configuration: two retries, 0.5s→5s exponential backoff with 25% jitter, statuses {408, 429, 500–599}, Retry-After honored, connection and timeout errors retried, and a 30s per-call budget.

func (RetryPolicy) Validate

func (p RetryPolicy) Validate() error

Validate checks retry counts, delays, jitter, and the optional budget.

type Score

type Score struct {
	Instructions JSONContent
	Criteria     ScoreCriteria
}

Score is a rubric-scoring question answered by ScoreAnswer with the expected score, a confidence, a legend, and per-level probabilities. Criteria is required and non-empty; a nil Instructions is omitted from the wire form.

func (Score) MarshalJSON

func (q Score) MarshalJSON() ([]byte, error)

MarshalJSON emits the wire form: "type" first, then "instructions" when set, then the required "criteria".

type ScoreAnswer

type ScoreAnswer struct {
	Score         float64
	Confidence    float64
	Legend        map[int]any
	Probabilities map[int]float64
}

ScoreAnswer is an expected score with its rubric and probabilities.

type ScoreCriteria

type ScoreCriteria []JSONContent

ScoreCriteria is the ordered, non-empty rubric for a Score question: one entry (text, object, or array) per score level, starting at zero.

type SystemOneParams

type SystemOneParams struct {
	// State is the content all questions refer to: text, a JSON object, or
	// an array.
	State JSONContent
	// Questions is the non-empty mapping of names to questions.
	Questions Questions
	// Model overrides the client default model for this call.
	Model string
	// Timeout overrides the client per-attempt timeout for this call.
	Timeout time.Duration
	// Retry replaces the client retry policy for this call.
	Retry *RetryPolicy
	// ExtraHeaders are additional request headers for this call.
	ExtraHeaders map[string]string
	// ExtraBody holds additional top-level request-body fields. SDK-owned
	// fields (state, model, and questions) cannot be overridden; other fields
	// are shallow-merged and object values are replaced rather than deep-merged.
	ExtraBody map[string]JSONValue
}

SystemOneParams describes one POST /v1/systemone call. The zero values of the optional fields inherit the client settings.

type SystemOneResponse

type SystemOneResponse struct {
	Model   string
	Usage   Usage
	Answers map[string]Answer

	RequestID string
	Raw       *http.Response
	// contains filtered or unexported fields
}

SystemOneResponse carries answers grouped by question type, with model and usage metadata. RequestID and Raw are attached to every response created by the client; Raw's body has been buffered, so it is safe to read.

func ParseSystemOneResponse

func ParseSystemOneResponse(resp *http.Response) (*SystemOneResponse, error)

ParseSystemOneResponse decodes an HTTP response from POST /v1/systemone into a SystemOneResponse — the Go counterpart of the Python SDK's SystemOneResponse.from_http_response. The body is buffered and re-attached, so resp stays readable; a nil response is rejected. Non-2xx statuses map to the typed error taxonomy, and invalid 2xx bodies produce a *ResponseValidationError.

func (*SystemOneResponse) Choices

func (r *SystemOneResponse) Choices() map[string]ChoiceAnswer

Choices returns the choice answers keyed by question name. The view is memoized; do not mutate the returned map.

func (*SystemOneResponse) Nouls

func (r *SystemOneResponse) Nouls() map[string]NoulAnswer

Nouls returns the yes/no answers keyed by question name. The view is memoized; do not mutate the returned map.

func (*SystemOneResponse) Scores

func (r *SystemOneResponse) Scores() map[string]ScoreAnswer

Scores returns the score answers keyed by question name. The view is memoized; do not mutate the returned map.

type TimeoutError

type TimeoutError struct {
	Duration time.Duration
	// contains filtered or unexported fields
}

TimeoutError reports a request that exceeded its configured timeout. It satisfies net.Error, and Duration carries the resolved per-attempt timeout. Like the Python SDK — where the timeout error subclasses the connection error — [Unwrap] exposes a *ConnectionError carrying the transport-level cause, so a *TimeoutError also matches errors.As(err, &connErr). Because the transport cause chain is preserved, the error also satisfies errors.Is(err, context.DeadlineExceeded): when distinguishing SDK attempt timeouts from your own deadline, match SDK types with errors.As first and only treat DeadlineExceeded as caller-side once no SDK type matched.

func (*TimeoutError) As

func (e *TimeoutError) As(target any) bool

As additionally matches the shared SDK root: errors.As(err, &root) with a *TypeSafeError target succeeds for timeout failures.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

func (*TimeoutError) Temporary

func (e *TimeoutError) Temporary() bool

Temporary reports that a timeout is transient; it always holds true.

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Timeout reports that this error represents a timeout; it always holds true.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap exposes the connection error wrapping the transport-level cause.

type TypeSafeError

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

TypeSafeError is the root of every SDK error, like the Python SDK's TypeSafeError base class: API failures (APIError and its subclasses, including ResponseValidationError), transport failures (ConnectionError), timeouts (TimeoutError), and SDK-side failures all match `errors.As(err, &root)` with root of type *TypeSafeError, so a single catch-all handler sees every SDK-classified failure. Caller cancellation and deadlines are returned as unwrapped context errors and do not match this root. SDK-side failures — invalid arguments, configuration, request encoding — use this type directly and may wrap a sentinel such as ErrMissingAPIKey or ErrClientClosed, which errors.Is matches.

func (*TypeSafeError) Error

func (e *TypeSafeError) Error() string

Error implements the error interface.

func (*TypeSafeError) Unwrap

func (e *TypeSafeError) Unwrap() error

Unwrap exposes the wrapped cause, if any.

type UnprocessableEntityError

type UnprocessableEntityError struct{ *APIError }

UnprocessableEntityError reports failed server-side validation (HTTP 422).

func (*UnprocessableEntityError) Error

func (e *UnprocessableEntityError) Error() string

Error mirrors APIError.Error.

func (*UnprocessableEntityError) Unwrap

func (e *UnprocessableEntityError) Unwrap() error

Unwrap matches the embedded APIError for errors.As.

type Usage

type Usage struct {
	InputTokens  *int
	OutputTokens *int
}

Usage holds the token counts for a request; a nil field means the API did not report that count.

Directories

Path Synopsis
examples
api-use-cases/graphql-claim-predicate command
Command graphql-claim-predicate models a nullable Document.supportsClaim(claim: String!): Boolean resolver.
Command graphql-claim-predicate models a nullable Document.supportsClaim(claim: String!): Boolean resolver.
api-use-cases/graphql-deprecated-field command
Command graphql-deprecated-field suggests a replacement field in a persisted query only after exact signature checks and two semantic gates.
Command graphql-deprecated-field suggests a replacement field in a persisted query only after exact signature checks and two semantic gates.
api-use-cases/graphql-legacy-union command
Command graphql-legacy-union models abstract type resolution for a union with Incident, MaintenanceNotice, and UnknownRecord members.
Command graphql-legacy-union models abstract type resolution for a union with Incident, MaintenanceNotice, and UnknownRecord members.
api-use-cases/graphql-report-category command
Command graphql-report-category models a Report.category enum resolver.
Command graphql-report-category models a Report.category enum resolver.
api-use-cases/graphql-topic-subscription command
Command graphql-topic-subscription demonstrates a bounded subscription source adapter that checks ambiguous event summaries before delivery.
Command graphql-topic-subscription demonstrates a bounded subscription source adapter that checks ambiguous event summaries before delivery.
api-use-cases/legacy-webhook-routing command
Command legacy-webhook-routing verifies a sample webhook before routing an underspecified description to a bounded internal handler.
Command legacy-webhook-routing verifies a sample webhook before routing an underspecified description to a bounded internal handler.
api-use-cases/narrative-field-agreement command
Command narrative-field-agreement checks a deployment reason against typed fields before an API handler performs a deployment.
Command narrative-field-agreement checks a deployment reason against typed fields before an API handler performs a deployment.
api-use-cases/natural-language-filters command
Command natural-language-filters converts a bounded search hint into allowlisted filters; Go still enforces tenant scope, time, and result limits.
Command natural-language-filters converts a bounded search hint into allowlisted filters; Go still enforces tenant scope, time, and result limits.
api-use-cases/openapi-description-drift command
Command openapi-description-drift flags semantic prose changes only after an exact operation and schema comparison has passed.
Command openapi-description-drift flags semantic prose changes only after an exact operation and schema comparison has passed.
api-use-cases/upstream-problem-types command
Command upstream-problem-types maps opaque upstream prose to a reviewed public RFC 9457 problem type while preserving a trusted HTTP status.
Command upstream-problem-types maps opaque upstream prose to a reviewed public RFC 9457 problem type while preserving a trusted HTTP status.
automation-use-cases/advertising command
Command advertising demonstrates creative review: an ad evaluated for brand safety, claim substantiation, and ad-to-landing-page alignment, plus a creative-quality Score and audience fit, deciding between approve, revise, and reject in plain Go.
Command advertising demonstrates creative review: an ad evaluated for brand safety, claim substantiation, and ad-to-landing-page alignment, plus a creative-quality Score and audience fit, deciding between approve, revise, and reject in plain Go.
automation-use-cases/customer-support command
Command customer-support demonstrates the speculative fan-out pattern: six questions about one ticket in a single request (including a raw question passthrough), followed by a plain Go decision tree over the typed answers.
Command customer-support demonstrates the speculative fan-out pattern: six questions about one ticket in a single request (including a raw question passthrough), followed by a plain Go decision tree over the typed answers.
automation-use-cases/demand-forecasting command
Command demand-forecasting demonstrates enriching a forecast with semantic signals: each sales note or review is mapped to demand signals (intent, urgency, supply worries, competitive pressure) in its own call, then reduced into an aggregate signal line a forecasting model can join on.
Command demand-forecasting demonstrates enriching a forecast with semantic signals: each sales note or review is mapped to demand signals (intent, urgency, supply worries, competitive pressure) in its own call, then reduced into an aggregate signal line a forecasting model can join on.
automation-use-cases/ecommerce-marketplaces command
Command ecommerce-marketplaces demonstrates listing moderation and normalization: a raw listing classified into category and condition, checked for prohibited items and counterfeit signals, and routed to publish, hold, or remove in plain Go.
Command ecommerce-marketplaces demonstrates listing moderation and normalization: a raw listing classified into category and condition, checked for prohibited items and counterfeit signals, and routed to publish, hold, or remove in plain Go.
automation-use-cases/financial-crime command
Command financial-crime demonstrates alert triage for anti-money- laundering workflows: a transaction narrative matched against typologies, entity-name variants resolved across inconsistent records, and the alert prioritized into a plain Go routing decision.
Command financial-crime demonstrates alert triage for anti-money- laundering workflows: a transaction narrative matched against typologies, entity-name variants resolved across inconsistent records, and the alert prioritized into a plain Go routing decision.
automation-use-cases/gaming command
Command gaming demonstrates player-support automation: a report plus chat log assessed for credible cheating, toxic chat, and churn signals, producing sorted plain-Go actions from anti-cheat escalation to win-back outreach.
Command gaming demonstrates player-support automation: a report plus chat log assessed for credible cheating, toxic chat, and churn signals, producing sorted plain-Go actions from anti-cheat escalation to win-back outreach.
automation-use-cases/insurance-claims command
Command insurance-claims demonstrates FNOL triage: first-notice-of-loss reports classified by claim type and complexity in one call, with missing-information and fraud-indicator checks deciding between straight-through processing, adjuster review, and SIU investigation.
Command insurance-claims demonstrates FNOL triage: first-notice-of-loss reports classified by claim type and complexity in one call, with missing-information and fraud-indicator checks deciding between straight-through processing, adjuster review, and SIU investigation.
automation-use-cases/knowledge-graphs command
Command knowledge-graphs demonstrates annotating a knowledge graph with typed semantic decisions: for each subject-object-sentence triple, one call classifies the relation and checks it against the edge already in the graph; a confidence gate in plain Go commits the edge, flags the contradiction, or queues the triple for human curation.
Command knowledge-graphs demonstrates annotating a knowledge graph with typed semantic decisions: for each subject-object-sentence triple, one call classifies the relation and checks it against the edge already in the graph; a confidence gate in plain Go commits the edge, flags the contradiction, or queues the triple for human curation.
automation-use-cases/lead-generation command
Command lead-generation demonstrates composite scoring: several Score questions about a structured lead, merged into a weighted composite and cut into priority buckets in plain Go.
Command lead-generation demonstrates composite scoring: several Score questions about a structured lead, merged into a weighted composite and cut into priority buckets in plain Go.
automation-use-cases/legal-compliance command
Command legal-compliance demonstrates marketing-copy review: a battery of Noul checks for prohibited claims and missing disclaimers, plus a severity Score, deciding between approval, revision, and escalation to legal — in plain Go.
Command legal-compliance demonstrates marketing-copy review: a battery of Noul checks for prohibited claims and missing disclaimers, plus a severity Score, deciding between approval, revision, and escalation to legal — in plain Go.
automation-use-cases/llm-guardrails command
Command llm-guardrails demonstrates LLM guardrails: a battery of Noul hazard checks plus a harm-severity Score, evaluated against threshold policies with pass/review/block/support routing and precedence.
Command llm-guardrails demonstrates LLM guardrails: a battery of Noul hazard checks plus a harm-severity Score, evaluated against threshold policies with pass/review/block/support routing and precedence.
automation-use-cases/model-routing command
Command model-routing demonstrates a custom LLM router: every prompt is classified by domain, difficulty, and reasoning need, and a plain Go routing table picks the cheapest model that can handle it — with a confidence gate that falls back to the standard tier.
Command model-routing demonstrates a custom LLM router: every prompt is classified by domain, difficulty, and reasoning need, and a plain Go routing table picks the cheapest model that can handle it — with a confidence gate that falls back to the standard tier.
automation-use-cases/moderation-trust-safety command
Command moderation-trust-safety demonstrates community moderation with company-specific criteria: a battery of Noul checks (toxicity, harassment, spam, unsafe advice, personal-data exposure) plus a severity Score, combined into an allow / warn / review / block decision.
Command moderation-trust-safety demonstrates community moderation with company-specific criteria: a battery of Noul checks (toxicity, harassment, spam, unsafe advice, personal-data exposure) plus a severity Score, combined into an allow / warn / review / block decision.
automation-use-cases/predictive-features command
Command predictive-features demonstrates feature extraction for predictive modeling: free-text reviews turned into a deterministic feature vector of Noul probabilities plus a normalized sentiment Score — the kind of signal a classical ML model (churn, propensity, forecast) can train on directly.
Command predictive-features demonstrates feature extraction for predictive modeling: free-text reviews turned into a deterministic feature vector of Noul probabilities plus a normalized sentiment Score — the kind of signal a classical ML model (churn, propensity, forecast) can train on directly.
automation-use-cases/recruiting command
Command recruiting demonstrates candidate evaluation: a resume checked against a role's competency rubric and hard requirements in one call, scored into a plain Go decision that is compared with the model's own recommendation — taking the conservative side when they disagree.
Command recruiting demonstrates candidate evaluation: a resume checked against a role's competency rubric and hard requirements in one call, scored into a plain Go decision that is compared with the model's own recommendation — taking the conservative side when they disagree.
automation-use-cases/risk-assessment command
Command risk-assessment demonstrates turning an unstructured incident report into a risk-register entry: a risk-type classification, a four-level severity rubric, and control-failure / recurrence checks, composed into a priority in plain Go.
Command risk-assessment demonstrates turning an unstructured incident report into a risk-register entry: a risk-type classification, a four-level severity rubric, and control-failure / recurrence checks, composed into a priority in plain Go.
automation-use-cases/scientific-discovery command
Command scientific-discovery demonstrates literature screening: paper abstracts evaluated against systematic-review inclusion and exclusion criteria in one call each, plus a reporting-quality check, with a plain Go verdict of include, exclude, or needs review.
Command scientific-discovery demonstrates literature screening: paper abstracts evaluated against systematic-review inclusion and exclusion criteria in one call each, plus a reporting-quality check, with a plain Go verdict of include, exclude, or needs review.
automation-use-cases/search-and-retrieval command
Command search-and-retrieval demonstrates semantic search feeding a RAG pipeline: each candidate passage gets a Noul "does it answer the query?" gate plus a graded relevance Score, and a plain Go reduce turns the two into a ranked context window — a cheap supplement or replacement for embedding-based retrieval.
Command search-and-retrieval demonstrates semantic search feeding a RAG pipeline: each candidate passage gets a Noul "does it answer the query?" gate plus a graded relevance Score, and a plain Go reduce turns the two into a ranked context window — a cheap supplement or replacement for embedding-based retrieval.
automation-use-cases/semantic-code-linting command
Command semantic-code-linting demonstrates team-convention lints that grep cannot express: a battery of Noul violation checks plus a worst-case severity Score over one code snippet, with CI semantics — a nonzero exit when any convention is violated.
Command semantic-code-linting demonstrates team-convention lints that grep cannot express: a battery of Noul violation checks plus a worst-case severity Score over one code snippet, with CI semantics — a nonzero exit when any convention is violated.
go-software-use-cases/01-semantic-command-switch command
Command semantic-command-switch routes a natural-language command to a fixed Go handler.
Command semantic-command-switch routes a natural-language command to a fixed Go handler.
go-software-use-cases/02-bind-closed-set-arguments command
Command bind-closed-set-arguments maps a request to allowlisted functions and enum arguments.
Command bind-closed-set-arguments maps a request to allowlisted functions and enum arguments.
go-software-use-cases/03-semantic-lint command
Command semantic-lint checks a contextual Go convention after deterministic syntax parsing.
Command semantic-lint checks a contextual Go convention after deterministic syntax parsing.
go-software-use-cases/04-select-runtime-strategy command
Command select-runtime-strategy combines semantic signals with Go policy constraints.
Command select-runtime-strategy combines semantic signals with Go policy constraints.
go-software-use-cases/05-rerank-search-shortlist command
Command rerank-search-shortlist reorders results from a deterministic lexical search.
Command rerank-search-shortlist reorders results from a deterministic lexical search.
go-software-use-cases/06-classify-ci-failures command
Command classify-ci-failures selects a diagnostic runbook from a CI log excerpt.
Command classify-ci-failures selects a diagnostic runbook from a CI log excerpt.
go-software-use-cases/07-correlate-duplicate-reports command
Command correlate-duplicate-reports suggests duplicate links from a preselected issue shortlist.
Command correlate-duplicate-reports suggests duplicate links from a preselected issue shortlist.
go-software-use-cases/08-compare-acceptance-tests command
Command compare-acceptance-tests points reviewers to likely requirement coverage gaps.
Command compare-acceptance-tests points reviewers to likely requirement coverage gaps.
go-software-use-cases/09-semantic-reviewer-routing command
Command semantic-reviewer-routing adds a cross-cutting reviewer to CODEOWNERS results.
Command semantic-reviewer-routing adds a cross-cutting reviewer to CODEOWNERS results.
go-software-use-cases/10-normalize-release-notes command
Command normalize-release-notes turns human prose into a bounded changelog record.
Command normalize-release-notes turns human prose into a bounded changelog record.
go-software-use-cases/11-select-id-from-log command
Command select-id-from-log assigns a role to exact IDs extracted by regexp.
Command select-id-from-log assigns a role to exact IDs extracted by regexp.
go-software-use-cases/12-parse-relative-dates command
Command parse-relative-dates resolves bounded date parts against an explicit clock.
Command parse-relative-dates resolves bounded date parts against an explicit clock.
go-software-use-cases/13-navigate-codebase command
Command navigate-codebase chooses only among known repository paths at each level.
Command navigate-codebase chooses only among known repository paths at each level.
go-software-use-cases/14-suggest-tool command
Command suggest-tool proposes one installed capability from a fixed registry.
Command suggest-tool proposes one installed capability from a fixed registry.
go-software-use-cases/15-screen-untrusted-input command
Command screen-untrusted-input applies an input-side semantic guardrail before an LLM call.
Command screen-untrusted-input applies an input-side semantic guardrail before an LLM call.
go-software-use-cases/16-check-generated-output command
Command check-generated-output screens a draft before returning it to a user.
Command check-generated-output screens a draft before returning it to a user.
go-software-use-cases/17-filter-retrieved-context command
Command filter-retrieved-context routes passages into evidence and contradiction blocks.
Command filter-retrieved-context routes passages into evidence and contradiction blocks.
go-software-use-cases/18-verify-proposed-tool-call command
Command verify-proposed-tool-call checks semantic alignment after exact Go validation.
Command verify-proposed-tool-call checks semantic alignment after exact Go validation.
go-software-use-cases/19-check-documentation-citations command
Command check-documentation-citations verifies an exact quote before semantic support.
Command check-documentation-citations verifies an exact quote before semantic support.
go-software-use-cases/20-incident-semantic-features command
Command incident-semantic-features joins semantic probabilities with measured incident facts.
Command incident-semantic-features joins semantic probabilities with measured incident facts.
quickstart command
Command quickstart is the minimal TypeSafe AI client: one call asking all three question primitives about a support ticket.
Command quickstart is the minimal TypeSafe AI client: one call asking all three question primitives about a support ticket.
relational-db-use-cases/allowlisted-select command
Command allowlisted-select maps prose to a tenant-scoped, parameterized PostgreSQL SELECT.
Command allowlisted-select maps prose to a tenant-scoped, parameterized PostgreSQL SELECT.
relational-db-use-cases/controlled-dimension command
Command controlled-dimension maps an incoming description to an existing category code and shows the parameterized transactional insert.
Command controlled-dimension maps an incoming description to an existing category code and shows the parameterized transactional insert.
relational-db-use-cases/entity-alignment command
Command entity-alignment scores SQL-shortlisted import candidates and writes match proposals for curator review.
Command entity-alignment scores SQL-shortlisted import candidates and writes match proposals for curator review.
relational-db-use-cases/existing-foreign-key command
Command existing-foreign-key selects among existing, SQL-shortlisted deployment rows and prints a scoped association insert.
Command existing-foreign-key selects among existing, SQL-shortlisted deployment rows and prints a scoped association insert.
relational-db-use-cases/migration-worklist command
Command migration-worklist classifies a keyset page of legacy rows into bounded migration buckets.
Command migration-worklist classifies a keyset page of legacy rows into bounded migration buckets.
relational-db-use-cases/semantic-sort-column command
Command semantic-sort-column derives a rubric score for a work item, to be stored as nullable enrichment and used by a later PostgreSQL ORDER BY.
Command semantic-sort-column derives a rubric score for a work item, to be stored as nullable enrichment and used by a later PostgreSQL ORDER BY.
relational-db-use-cases/semantic-tags command
Command semantic-tags asks independent yes/no questions, then maps positive answers to existing tag IDs for a many-to-many PostgreSQL join table.
Command semantic-tags asks independent yes/no questions, then maps positive answers to existing tag IDs for a many-to-many PostgreSQL join table.
relational-db-use-cases/structured-update-guard command
Command structured-update-guard checks whether a proposed resolution note contradicts the structured status before proposing an atomic database update.
Command structured-update-guard checks whether a proposed resolution note contradicts the structured status before proposing an atomic database update.
relational-db-use-cases/typed-join-relation command
Command typed-join-relation classifies the relationship between two SQL-selected rows, then applies fixed endpoint, type, direction, and cycle checks before proposing a parameterized join-table insert.
Command typed-join-relation classifies the relationship between two SQL-selected rows, then applies fixed endpoint, type, direction, and cycle checks before proposing a parameterized join-table insert.
relational-db-use-cases/version-contradictions command
Command version-contradictions compares two adjacent, immutable versions selected by SQL and proposes a conflict review row without changing history.
Command version-contradictions compares two adjacent, immutable versions selected by SQL and proposes a conflict review row without changing history.
retries-errors command
Command retries-errors demonstrates the SDK's operational surface: errors.As across the whole taxonomy (including RateLimitError.RetryAfterMs), a custom RetryPolicy (statuses and budget), per-call model/timeout/header overrides, and TYPESAFE_LOG_LEVEL=debug wire logging.
Command retries-errors demonstrates the SDK's operational surface: errors.As across the whole taxonomy (including RateLimitError.RetryAfterMs), a custom RetryPolicy (statuses and budget), per-call model/timeout/header overrides, and TYPESAFE_LOG_LEVEL=debug wire logging.
task-categories/classification command
Command classification demonstrates the Classification task category: exactly one category wins.
Command classification demonstrates the Classification task category: exactly one category wins.
task-categories/detection command
Command detection demonstrates the Detection task category: the probability that one property is present.
Command detection demonstrates the Detection task category: the probability that one property is present.
task-categories/ml-feature-extraction command
Command ml-feature-extraction demonstrates the ML Feature Extraction task category: a downstream classical model needs semantic signals.
Command ml-feature-extraction demonstrates the ML Feature Extraction task category: a downstream classical model needs semantic signals.
task-categories/ranking command
Command ranking demonstrates re-ranking with map-reduce: score the relevance of each retrieved passage to a query in separate SystemOne calls, sort by expected score, and reduce into a top-k result list.
Command ranking demonstrates re-ranking with map-reduce: score the relevance of each retrieved passage to a query in separate SystemOne calls, sort by expected score, and reduce into a top-k result list.
task-categories/retrieval command
Command retrieval demonstrates the Retrieval task category: a workflow (here, RAG) needs relevant context.
Command retrieval demonstrates the Retrieval task category: a workflow (here, RAG) needs relevant context.
task-categories/routing command
Command routing demonstrates intent routing with confidence-gated branching: classify a voice-banking utterance, then let the choice confidence decide between auto-action, confirmation, and human handoff.
Command routing demonstrates intent routing with confidence-gated branching: classify a voice-banking utterance, then let the choice confidence decide between auto-action, confirmation, and human handoff.
task-categories/scoring command
Command scoring demonstrates the Scoring task category: an ordered rubric answer.
Command scoring demonstrates the Scoring task category: an ordered rubric answer.
task-categories/search command
Command search demonstrates the Search task category: find the items that match a natural-language query.
Command search demonstrates the Search task category: find the items that match a natural-language query.
task-categories/structured-data-extraction command
Command structured-data-extraction demonstrates the Structured Data Extraction task category: recovering known fields from unstructured input.
Command structured-data-extraction demonstrates the Structured Data Extraction task category: recovering known fields from unstructured input.
task-categories/verification command
Command verification demonstrates the Verification task category: checking an artifact for failure modes.
Command verification demonstrates the Verification task category: checking an artifact for failure modes.
testing-use-cases/audit-note-state command
Command audit-note-state screens an audit note against state read back after a transaction.
Command audit-note-state screens an audit note against state read back after a transaction.
testing-use-cases/cli-help-meaning command
Command cli-help-meaning reviews whether help text explains its flags.
Command cli-help-meaning reviews whether help text explains its flags.
testing-use-cases/duplicate-scenarios command
Command duplicate-scenarios suggests semantic duplicate test rows after comparing exact inputs and assertions in Go.
Command duplicate-scenarios suggests semantic duplicate test rows after comparing exact inputs and assertions in Go.
testing-use-cases/error-message-contract command
Command error-message-contract reviews error wording after deterministic wrapping, stable-token, and redaction checks.
Command error-message-contract reviews error wording after deterministic wrapping, stable-token, and redaction checks.
testing-use-cases/fuzz-failure-triage command
Command fuzz-failure-triage labels a saved reproducing fuzz failure for routing.
Command fuzz-failure-triage labels a saved reproducing fuzz failure for routing.
testing-use-cases/fuzz-seed-curation command
Command fuzz-seed-curation maps a bug report to a reviewed byte fixture.
Command fuzz-seed-curation maps a bug report to a reviewed byte fixture.
testing-use-cases/fuzz-symptom-clusters command
Command fuzz-symptom-clusters suggests a symptom cluster after exact stack/input hash grouping.
Command fuzz-symptom-clusters suggests a symptom cluster after exact stack/input hash grouping.
testing-use-cases/graphql-error-code command
Command graphql-error-code compares a bounded reading of error prose with the stable GraphQL extension code after deterministic JSON checks.
Command graphql-error-code compares a bounded reading of error prose with the stable GraphQL extension code after deterministic JSON checks.
testing-use-cases/localized-message command
Command localized-message screens one translation for semantic drift after Go verifies placeholder preservation.
Command localized-message screens one translation for semantic drift after Go verifies placeholder preservation.
testing-use-cases/mock-fixture-intent command
Command mock-fixture-intent checks whether mock response prose fits the intended failure after deterministic status and JSON checks in Go.
Command mock-fixture-intent checks whether mock response prose fits the intended failure after deterministic status and JSON checks in Go.
testing-use-cases/negative-case-gaps command
Command negative-case-gaps reviews named failure requirements against a table-driven test plan.
Command negative-case-gaps reviews named failure requirements against a table-driven test plan.
testing-use-cases/question-regression-evaluation command
Command question-regression-evaluation records per-class errors and abstentions for a versioned Noul question on labeled fixtures.
Command question-regression-evaluation records per-class errors and abstentions for a versioned Noul question on labeled fixtures.
testing-use-cases/requirement-coverage-review command
Command requirement-coverage-review annotates a claimed requirement-to-test link.
Command requirement-coverage-review annotates a claimed requirement-to-test link.
testing-use-cases/rest-message-result command
Command rest-message-result screens REST prose for a contradiction after Go checks status and JSON structure.
Command rest-message-result screens REST prose for a contradiction after Go checks status and JSON structure.
testing-use-cases/router-fixture-evaluation command
Command router-fixture-evaluation runs an opt-in live evaluation over labeled routing fixtures.
Command router-fixture-evaluation runs an opt-in live evaluation over labeled routing fixtures.
testing-use-cases/surviving-mutation-review command
Command surviving-mutation-review prioritizes one mutation that compiled and survived the Go suite.
Command surviving-mutation-review prioritizes one mutation that compiled and survived the Go suite.
testing-use-cases/test-log-triage command
Command test-log-triage adds a tentative label to a failed go test -json excerpt.
Command test-log-triage adds a tentative label to a failed go test -json excerpt.
testing-use-cases/test-name-assertions command
Command test-name-assertions flags a test name that promises more than its assertion checks.
Command test-name-assertions flags a test name that promises more than its assertion checks.
testing-use-cases/webhook-route-review command
Command webhook-route-review compares a verified legacy webhook's semantic route with a human label.
Command webhook-route-review compares a verified legacy webhook's semantic route with a human label.
testing-use-cases/workflow-narrative command
Command workflow-narrative compares two short event excerpts after Go verifies trace identity, order, delivery, and resulting state.
Command workflow-narrative compares two short event excerpts after Go verifies trace identity, order, delivery, and resulting state.

Jump to

Keyboard shortcuts

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