sdk

package module
v0.0.1-rc2 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 19 Imported by: 1 module, 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.

Documentation

Overview

Package sdk is a Go client for the TypeSafe "System One" decision API (the Jev model family).

It is a hand-written, dependency-light port of the official TypeScript SDK (github.com/typesafe-ai/typesafe-sdk-js), scoped to the single endpoint this project needs: POST {baseURL}/systemone.

Vendor neutrality

Nothing about a particular host is baked in. The client speaks the API shape and nothing more, so BaseURL can point at the official host, at a gateway that re-exposes the same endpoint, at a proxy, or at a local test server, with no other change.

Gateways may add fields to a success response that the official host does not send — "provider", "id", and "usage.cost" are the ones observed so far. Those are decoded when present and left zero when absent, so one client works against both without configuration.

What this model is

Jev does not generate text. You send a state (the material to judge) and a set of typed questions; it returns typed answers with probabilities. Three question primitives exist and may be mixed in one call:

Noul  — a yes/no judgement          returns a probability in [0,1]
Choice— pick one of named options   returns choice + probabilities + confidence
Score — place the state on a rubric returns score + legend + probabilities + confidence

Every question is evaluated independently and in parallel against the same state, so adding questions barely changes latency. Ask several narrow questions rather than one broad one, and combine the answers in your own code.

Wire contract

The schema is the official System One API's, as documented at https://docs.typesafe.ai/api. Every implementation file in this package is written against it; do not guess at it. The behaviour was additionally verified against a live endpoint on 2026-09-21 reached through a gateway, and the two disagreed in the places called out below.

Request:

POST {BaseURL}/systemone
Authorization: Bearer <api key>
Content-Type: application/json

{
  "model": "jev-latest",                // required, non-empty string
  "state": <string | object | array>,   // required; passed through untouched
  "questions": { "<name>": <question> } // required, non-empty
}

Question variants (discriminated by "type"). An <entry> is a string, a JSON object or a JSON array; null is additionally allowed as a choice description, but not as either side of a noul criteria:

{"type":"noul",   "instructions":<entry>, "criteria":{"true":<entry>,"false":<entry>}}
{"type":"choice", "instructions":<entry>, "criteria":{"<label>":<entry|null>}}
{"type":"score",  "instructions":<entry>, "criteria":[<entry>,<entry>,...]}

with these limits:

noul   criteria optional; when present, BOTH true and false are required
choice criteria required, 1..255 options
score  criteria required, 2..10 levels

Three traps the live endpoint exposed, all covered by tests in this package:

  • A noul's "criteria" is all or nothing. Omitting the key entirely is valid; sending the key with a null side, or with only one side, is a hard validation failure, and so is sending the whole criteria as null. In Go the field is a pointer with omitempty, because a nil pointer without it marshals to null and fails every such request.
  • A Score with a single level was accepted by the host used for verification, while the official reference says a Score needs at least two levels and accepts up to ten. The host was not taken as the contract: ValidateQuestions enforces the documented minimum. The official host's own behaviour was never exercised, so treat that gap as gateway variance, not as something settled about the API.
  • The noul "criteria" sides are not interchangeable with a choice's option descriptions: a choice option may be null, a noul side may not.

Success response (HTTP 200), official shape:

{
  "model":   "jev-1.13.0",
  "answers": {
    "<name>": {"type":"noul","noul":0.73}
           |  {"type":"choice","choice":"billing",
               "probabilities":{"other":0,"tech":0,"billing":1},"confidence":1}
           |  {"type":"score","score":0.25,
               "legend":{"0":"none","1":"mild","2":"serious","3":"severe"},
               "probabilities":{"0":0.76,"1":0.24,"2":0,"3":0},"confidence":0.75}
  },
  "usage":   {"input_tokens":405,"output_tokens":68}
}

Three details matter and are easy to get wrong:

  • "legend" and "probabilities" are objects keyed by the decimal score as a STRING ("0".."n"). They are decoded here into slices indexed by score. The legend echoes the criteria descriptions back verbatim; do not assume they are short labels, and do not strip anything from them.
  • "score" is an expectation and may be fractional (0.25 above) even though the legend is discrete. Do not round it into an index.
  • "legend" reflects what you sent, so the number of levels is yours.

Hosts may return fields the official schema does not list. Observed on one: "provider", "id" (a request identifier) and "usage.cost". Result.Provider, Result.ID and Usage.Cost decode them and stay empty or nil when a host omits them, so no configuration is needed either way. Nothing in this package depends on them.

Error response (non-2xx):

{"error":{"message":"Model nope does not exist","code":400}}

The official reference documents 401, 422 (validation), 429 and 529 (overloaded); the host used for verification returned 400 where the reference says 422. Status codes are therefore reported rather than interpreted, with the four codes above only steering retry behaviour.

The "code" field mirrors the status but is not guaranteed to be numeric, so it is decoded as raw JSON. Some responses carry a top-level "user_id" alongside "error"; decoding does not reject unknown fields, so this is tolerated.

A validation failure's "message" is USUALLY a JSON-encoded array of issues, but not always: at least one host returns a plain string with an embedded payload, such as

HTTP 400: {"detail":"Choice question must have at least one choice: q"}

so it is preserved verbatim in APIError.Message and never parsed. Treat it as diagnostic text for a human, not as a stable machine-readable structure.

Public API

The surface below is frozen; every file in this package is written against it.

New(opts ...Option) (*Client, error)
(*Client).Evaluate(ctx, state any, questions Questions, opts ...CallOption) (*Result, error)

Configured through Option values (WithAPIKey, WithBaseURL, WithModel, WithHTTPClient, WithTimeout, WithTotalTimeout, WithMaxResponseBytes, WithRetryPolicy, WithHeader, WithLogger) and overridden per call with CallOption values.

Answers are read through typed accessors that also report whether the name existed and carried the expected answer type:

(*Result).Noul(name)   (NoulAnswer, bool)
(*Result).Choice(name) (ChoiceAnswer, bool)
(*Result).Score(name)  (ScoreAnswer, bool)

Configuration on disk

Settings may live in a directory, by default ~/.Sael, laid out like the other agent CLIs:

~/.Sael/config.json   settings that are safe to read, commit or paste
~/.Sael/auth.json     the credential, in its own file

Two files rather than one, so the half people share is never the half that authenticates them. SaveConfig and SaveAuth create the directory with mode 0700 and write through a temporary file, so a crash cannot leave a truncated file behind. LoadConfig and LoadAuth read it back; both treat a missing file as "not configured" rather than an error, but a file that exists and does not parse IS an error, because silently ignoring a typo in a hand-edited file is how people lose an afternoon.

File modes are a Unix guarantee only

On Unix both files are created with mode 0600 and the directory with 0700, so the credential is readable only by its owner. Windows has no such bits: Chmod there only toggles the read-only attribute, and FileMode.Perm reports a synthesised 0666 or 0777 no matter what was asked for. On Windows the credential is therefore protected by the ACL on the user's profile directory and by nothing this package does. That is a real gap, stated rather than papered over; closing it would mean taking an ACL dependency, which this package does not.

// config.json
{
  "base_url": "https://api.typesafe.ai/v1",
  "model": "jev-latest",
  "timeout": "10s",
  "total_timeout": "3s",
  "max_retries": 2,
  "headers": {"X-Tenant": "acme"}
}

// auth.json
{"api_key": "..."}

Durations are strings such as "3s" or "500ms".

New performs no file I/O. Use NewFromConfigDir to have the directory loaded: an empty directory means DefaultConfigDir, so a command-line tool starts with sdk.NewFromConfigDir("") and needs no path handling of its own. Set SAEL_HOME to relocate the directory. A constructor that silently read a home directory would make every caller's behaviour depend on the machine it runs on, and would make a test suite depend on whoever's laptop is running it.

Defaults

BaseURL https://api.typesafe.ai/v1
Model   jev-latest
Timeout 10s per attempt (mirrors the official SDK)

Layers resolve in order, each overriding the one before it: built-in defaults, then the files, then the environment (TYPESAFE_BASE_URL, TYPESAFE_DEFAULT_MODEL, TYPESAFE_API_KEY), then explicit Option values. Code therefore always beats a file on disk, which is what makes the file safe to treat as a baseline rather than an override. A model id namespaced for a gateway, such as "typesafe/jev-1.13", is just a string here.

The official SDK retries 2 times after the first attempt on 408, 429 and 5xx, backing off from 500ms doubling to 5s with up to 25% jitter subtracted, honouring Retry-After up to 60s. DefaultRetryPolicy returns exactly that.

Note that the official SDK's timeout is per attempt with no overall budget, which can stall a caller for tens of seconds. This client adds WithTotalTimeout for callers that need a bound; see Evaluate.

Index

Examples

Constants

View Source
const (
	// ConfigDirName is the directory created under the user's home directory.
	ConfigDirName = ".Sael"
	// ConfigFileName holds non-secret settings.
	ConfigFileName = "config.json"
	// AuthFileName holds the credential and nothing else.
	AuthFileName = "auth.json"
)
  • Reading is explicit
  • Precedence

Configuration on disk.

Settings live in a directory, by default ~/.Sael, laid out like the other agent CLIs:

~/.Sael/config.json   settings that are safe to read, commit or paste
~/.Sael/auth.json     the credential, in its own file

Two files rather than one, so that the half people share is never the half that authenticates them. Both are JSON. On Unix the directory is created with mode 0700 and both files with 0600; on Windows there are no such bits, so the credential relies on the ACL of the user's profile directory. See the configDirPerm comment for what that means in practice.

Reading is explicit

New performs no file I/O. A constructor that silently read a home directory would make every caller's behaviour depend on the machine it happens to run on, and would make a test suite depend on whoever's laptop is running it. Use NewFromConfigDir to have the directory loaded, or load it with LoadConfig and LoadAuth and pass the resulting Options yourself.

Precedence

Lowest to highest: built-in defaults, the files, environment variables, then explicit Option values. Code therefore always beats a file on disk, which is what makes the file safe to treat as a baseline rather than an override.

View Source
const (
	// DefaultBaseURL is the official System One API root. The endpoint is
	// {BaseURL}/systemone.
	//
	// Nothing about a particular gateway is baked in. Point BaseURL at any host
	// that speaks the same API shape — a gateway, a proxy, or a test server —
	// and everything else stays the same. Gateways may add fields to the
	// response (see Result.ID, Result.Provider, Usage.Cost); those are decoded
	// when present and left zero when absent.
	DefaultBaseURL = "https://api.typesafe.ai/v1"

	// DefaultModel is the Jev model id in the API's own naming. Hosts may
	// namespace it with their own prefix, so this is frequently overridden.
	DefaultModel = "jev-latest"

	// DefaultTimeout bounds a single attempt, not the whole call. This matches
	// the official SDK's 10s default; see WithTotalTimeout for an overall bound.
	DefaultTimeout = 10 * time.Second
)

Defaults applied when neither an Option nor an environment variable supplies a value.

View Source
const (
	EnvAPIKey  = "TYPESAFE_API_KEY"
	EnvBaseURL = "TYPESAFE_BASE_URL"
	EnvModel   = "TYPESAFE_DEFAULT_MODEL"
)

Environment variables consulted by New. Explicit Options always win, then the environment, then the defaults above. The names match the official SDKs.

View Source
const EnvConfigDir = "SAEL_HOME"

EnvConfigDir relocates the configuration directory, which is how tests and multi-profile setups stay out of each other's way.

View Source
const MaxResponseBytes = 32 << 20 // 32 MiB

MaxResponseBytes bounds how much of a response body this package will buffer. A response larger than this is an error rather than an attempt to hold it in memory: the endpoint returns a small JSON document, so a body past this size means something is wrong with the host, not that a bigger answer arrived.

The bound exists to turn a misbehaving host — one that streams endlessly, for example — into a prompt error instead of an out-of-memory kill. 32 MiB leaves enormous headroom over the few hundred bytes a real answer occupies.

Exceeding it is reported as an error wrapping ErrDecode (the body could not be interpreted because it could not be read to its end), and is never retried: retrying would buffer another limit's worth of memory before failing again.

Variables

View Source
var (
	// ErrAPI matches any non-2xx response from the service.
	ErrAPI = errors.New("sdk: api error")
	// ErrRateLimit matches HTTP 429, and additionally carries a RetryAfter.
	ErrRateLimit = errors.New("sdk: rate limited")
	// ErrConnection matches a failure to reach the service at all.
	ErrConnection = errors.New("sdk: connection failed")
	// ErrTimeout matches a request that exceeded an attempt or total deadline.
	ErrTimeout = errors.New("sdk: request timed out")
	// ErrAborted matches cancellation through the caller's context.
	ErrAborted = errors.New("sdk: request aborted by caller")
	// ErrDecode matches a 2xx response whose body could not be interpreted.
	ErrDecode = errors.New("sdk: malformed response")
	// ErrValidation matches a request rejected before it was sent.
	ErrValidation = errors.New("sdk: invalid request")
	// ErrConfig matches a failure reading or writing the configuration
	// directory, or a setting in it that does not parse. It is deliberately
	// distinct from ErrValidation: a caller that falls back on a rejected
	// question set must not also swallow a broken config.json.
	ErrConfig = errors.New("sdk: invalid configuration")
)

Sentinel errors, matchable with errors.Is. Every error this package returns wraps exactly one of these (or is a *APIError, which matches ErrAPI).

Functions

func DefaultConfigDir

func DefaultConfigDir() string

DefaultConfigDir returns $SAEL_HOME when set, otherwise ~/.Sael. It returns "" only when neither is available.

func SaveAuth

func SaveAuth(dir string, auth *Auth) error

SaveAuth writes dir/auth.json with mode 0600, creating the directory if needed. The mode is enforced on Unix only; see the configDirPerm comment.

The credential is written unencrypted, which is the same bargain ssh and the other agent CLIs make: the protection is the file's mode where the platform has one, and the user's profile directory everywhere, not a password.

func SaveConfig

func SaveConfig(dir string, cfg *Config) error

SaveConfig writes dir/config.json, creating the directory if needed.

Example

ExampleSaveConfig shows the layout on disk: settings that are safe to read and share in config.json, and the credential in its own auth.json so that the half people share is never the half that authenticates them.

The temporary directory here stands in for DefaultConfigDir, which reports $SAEL_HOME when set and ~/.Sael otherwise. NewFromConfigDir reads that directory; New deliberately does not, so a library caller is never at the mercy of a file they did not ask for.

package main

import (
	"fmt"
	"os"

	"github.com/cipherTing/sael/sdk"
)

// must panics on a non-nil error.
//
// Examples must not return early: a missing line of output is reported as a
// confusing mismatch rather than a clear failure. log.Fatal is the obvious
// choice and the wrong one, because it calls os.Exit and therefore skips
// deferred cleanup such as the test server's Close. Panicking runs the defers
// and fails the example with the error that caused it.
func must(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	dir, err := os.MkdirTemp("", "sael-example-*")
	if err != nil {
		must(err)
	}
	defer func() { _ = os.RemoveAll(dir) }()

	maxRetries := 2
	err = sdk.SaveConfig(dir, &sdk.Config{
		BaseURL:      "https://api.example.com/v1",
		Model:        "jev-latest",
		TotalTimeout: "3s",
		MaxRetries:   &maxRetries,
		Headers:      map[string]string{"X-Tenant": "acme"},
	})
	if err != nil {
		must(err)
	}
	if err := sdk.SaveAuth(dir, &sdk.Auth{APIKey: "sk-secret"}); err != nil {
		must(err)
	}

	cfg, found, err := sdk.LoadConfig(dir)
	if err != nil {
		must(err)
	}
	auth, _, err := sdk.LoadAuth(dir)
	if err != nil {
		must(err)
	}

	fmt.Println("found:        ", found)
	fmt.Println("base_url:     ", cfg.BaseURL)
	fmt.Println("model:        ", cfg.Model)
	fmt.Println("total_timeout:", cfg.TotalTimeout)
	fmt.Println("max_retries:  ", *cfg.MaxRetries)
	fmt.Println("key loaded:   ", auth.APIKey != "")

}
Output:
found:         true
base_url:      https://api.example.com/v1
model:         jev-latest
total_timeout: 3s
max_retries:   2
key loaded:    true

func UserAgent

func UserAgent() string

UserAgent reports the value sent in the User-Agent header. It identifies the client and the version that produced a request, which is the first thing worth knowing when a request is being investigated.

func ValidateQuestions

func ValidateQuestions(q Questions) error

ValidateQuestions rejects question sets the service would reject.

It mirrors the official SDK's validateQuestions: the set must not be empty, a Score question needs at least two criteria, and a Choice question needs at least one label. It also enforces the two upper bounds the API documents: a Score rubric accepts at most maxScoreLevels (10) levels, and a Choice accepts at most maxChoiceOptions (255) options.

A Noul is checked too, and the rule is all or nothing: criteria may be omitted entirely (NoulQuestion.Criteria == nil), but when it is present both the true and the false side must be non-nil. The live endpoint rejects a null side, or only one side, with HTTP 400 — see validateNoulCriteria for the recorded exchanges. Note that a nil side is never something the client can send accidentally-but-legally: the marshaller always writes an explicit null, so a half-filled criteria is a guaranteed failure.

Two further checks in the TypeScript implementation have no Go counterpart because the type system makes them unrepresentable at compile time: ChoiceQuestion.Criteria is a map[string]Entry and ScoreQuestion.Criteria is a []Entry, so criteria can never be "a list where a map belongs" or the reverse.

The Score minimum is deliberate, and not a bug to "fix". The API documentation says a Score has at least two levels, and the official TS SDK requires two; some hosts validate more loosely and accept one (an observed gateway rejects only zero levels). A single level carries no ordering and means the same thing as a Noul, so this client stays with the documented minimum and asks for a NoulQuestion instead. Do not relax it to match a host that is more permissive than the API it proxies.

An unknown question type cannot be constructed outside this package (the Question interface is sealed), and a nil question is rejected defensively.

Every error wraps ErrValidation, because the caller's request is what is wrong: errors.Is(err, ErrValidation) reports a question set that was never worth sending, and Client.Evaluate returns the error before any network call.

func Version

func Version() string

Version reports the version this binary was built with, or "devel" when there is nothing honest to report.

A version string that has silently drifted from the code is worse than no version string, because it is the one thing a bug report will quote.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Code       json.RawMessage // the server's "code" field; number or string
	Body       []byte
}

APIError is a non-2xx response from the service.

Body holds the raw response payload because that is often the only usable diagnostic: validation failures return HTTP 400 with Message set to a JSON-encoded array of issues rather than a human sentence.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether target is ErrAPI.

type AbortError

type AbortError struct {
	Err error
}

AbortError wraps cancellation through the caller's context.

func (*AbortError) Error

func (e *AbortError) Error() string

func (*AbortError) Is

func (e *AbortError) Is(target error) bool

Is reports whether target is ErrAborted.

func (*AbortError) Unwrap

func (e *AbortError) Unwrap() error

Unwrap exposes the underlying cause.

type Answer

type Answer interface {

	// AnswerType is the wire discriminator: "noul", "choice" or "score".
	AnswerType() string
	// contains filtered or unexported methods
}

Answer is one typed answer. The interface is sealed by the unexported isAnswer method: the only implementations are NoulAnswer, ChoiceAnswer and ScoreAnswer.

type Auth

type Auth struct {
	APIKey string `json:"api_key,omitempty"`
}

Auth is the contents of auth.json. It holds the credential and nothing else, so that the file which must never be shared is also the file that is trivial to read and to rotate.

func LoadAuth

func LoadAuth(dir string) (*Auth, bool, error)

LoadAuth reads dir/auth.json. Missing and unparsable are treated the same way as in LoadConfig.

func (*Auth) Options

func (a *Auth) Options() []Option

Options converts the stored credential into an Option.

type CallOption

type CallOption func(*callConfig)

A CallOption overrides client settings for one call.

func WithCallHeaders

func WithCallHeaders(h http.Header) CallOption

WithCallHeaders adds headers for one call. They cannot override Authorization, Content-Type or Accept.

func WithCallModel

func WithCallModel(model string) CallOption

WithCallModel overrides the model for one call.

func WithCallRetryPolicy

func WithCallRetryPolicy(p RetryPolicy) CallOption

WithCallRetryPolicy overrides the retry policy for one call.

func WithCallTimeout

func WithCallTimeout(d time.Duration) CallOption

WithCallTimeout overrides the per-attempt timeout for one call.

type ChoiceAnswer

type ChoiceAnswer struct {
	// Choice is the selected label. It is one of the keys of the question's
	// criteria.
	Choice string

	// Confidence is the reported confidence in the selection, in [0,1].
	Confidence float64

	// Probabilities is keyed by label. Choice labels are arbitrary strings, so
	// unlike a Score rubric they stay a map.
	Probabilities map[string]float64
}

ChoiceAnswer is the selected label with a probability for every label.

func (ChoiceAnswer) AnswerType

func (ChoiceAnswer) AnswerType() string

AnswerType implements Answer.

type ChoiceQuestion

type ChoiceQuestion struct {
	// Instructions is the question itself. Always written, null when unset.
	Instructions Entry `json:"instructions"`

	// Criteria maps each label to its description. A nil value leaves the label
	// undescribed.
	//
	// Between one and maxChoiceOptions (255) labels are required; an empty or
	// nil map is rejected by the service with HTTP 400 ("Choice question must
	// have at least one choice"). See ValidateQuestions, which enforces both
	// bounds before the request is sent.
	Criteria map[string]Entry `json:"criteria"`
}

ChoiceQuestion picks one of several named alternatives. The answer names the selected label and carries a probability for every label.

func (ChoiceQuestion) MarshalJSON

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

MarshalJSON writes {"type":"choice","instructions":<entry>,"criteria":{...}}.

A map value of nil becomes JSON null, which the service reads as an undescribed label.

func (ChoiceQuestion) QuestionType

func (ChoiceQuestion) QuestionType() string

QuestionType implements Question.

type Client

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

Client calls the System One endpoint. It is safe for concurrent use: it holds no per-request state, and the underlying http.Client is safe by contract.

Create one with New and reuse it. Creating a Client per request throws away connection pooling.

func New

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

New builds a Client from its arguments and the environment.

It performs no file I/O. Settings come from three layers, each overriding the one before it: built-in defaults, then environment variables (TYPESAFE_BASE_URL, TYPESAFE_DEFAULT_MODEL, TYPESAFE_API_KEY), then explicit Option values. Reading a configuration directory is a separate, deliberate step; see NewFromConfigDir and LoadConfig.

It returns an error wrapping ErrValidation when no API key can be found or the base URL is not absolute, so misconfiguration fails at construction rather than on the first request.

Example

ExampleNew shows the smallest useful client: a key, a target, and a deadline.

In real code the key comes from the environment through EnvAPIKey rather than being written into source; it is spelled out here so the example is self-contained.

WithTotalTimeout is worth setting. The retry policy allows three attempts and the per-attempt timeout defaults to ten seconds, so without an overall budget a call can occupy a request path for far longer than the caller intended.

package main

import (
	"fmt"
	"log/slog"
	"os"
	"time"

	"github.com/cipherTing/sael/sdk"
)

// clearEnv removes an environment variable and returns a function that puts it
// back, so an example can write `defer clearEnv("NAME")()`.
//
// Examples have no *testing.T and therefore no t.Setenv, which is the whole
// reason this exists.
func clearEnv(name string) func() {
	value, existed := os.LookupEnv(name)
	_ = os.Unsetenv(name)

	return func() {
		if existed {
			_ = os.Setenv(name, value)
			return
		}
		_ = os.Unsetenv(name)
	}
}

// must panics on a non-nil error.
//
// Examples must not return early: a missing line of output is reported as a
// confusing mismatch rather than a clear failure. log.Fatal is the obvious
// choice and the wrong one, because it calls os.Exit and therefore skips
// deferred cleanup such as the test server's Close. Panicking runs the defers
// and fails the example with the error that caused it.
func must(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	// The default model is only jev-latest when nothing overrides it, so the
	// variable that would is cleared: an example's output has to be the same on
	// every machine.
	defer clearEnv("TYPESAFE_DEFAULT_MODEL")()

	client, err := sdk.New(
		sdk.WithAPIKey("sk-example"),
		sdk.WithBaseURL("https://api.typesafe.ai/v1"),
		sdk.WithTotalTimeout(2*time.Second),
		sdk.WithLogger(slog.New(slog.NewTextHandler(os.Stderr, nil))),
	)
	if err != nil {
		must(err)
	}
	fmt.Println(client.BaseURL(), client.DefaultModel())
}
Output:
https://api.typesafe.ai/v1 jev-latest

func NewFromConfigDir

func NewFromConfigDir(dir string, opts ...Option) (*Client, error)

NewFromConfigDir builds a client whose settings come from dir, then from the environment, then from opts.

An empty dir means DefaultConfigDir, so a command-line tool starts with sdk.NewFromConfigDir("") and needs no path handling of its own. A missing directory or missing files are not errors; a file that exists and does not parse is.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL reports the configured API root.

func (*Client) DefaultModel

func (c *Client) DefaultModel() string

DefaultModel reports the model used when a call does not override it.

func (*Client) Evaluate

func (c *Client) Evaluate(ctx context.Context, state any, questions Questions, opts ...CallOption) (*Result, error)

Evaluate sends state and questions to the service and returns the typed answers.

state is marshalled as JSON and passed through untouched: a string, a struct, a map, or a slice are all valid. Send only the material the questions need — accuracy falls as unrelated content grows.

The returned *Result holds every answer under the name its question was given. Read them with Result.Noul, Result.Choice and Result.Score, which report whether the name existed and carried the expected type.

Example

ExampleClient_Evaluate asks three kinds of question in one call and reads the typed answers back.

One request carries every question, which is the point of the API: the questions are evaluated in parallel against the same state, so adding questions costs a few tokens rather than another round trip. Ask several narrow questions and combine them in your own code, where the thresholds belong.

package main

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

	"github.com/cipherTing/sael/sdk"
)

// must panics on a non-nil error.
//
// Examples must not return early: a missing line of output is reported as a
// confusing mismatch rather than a clear failure. log.Fatal is the obvious
// choice and the wrong one, because it calls os.Exit and therefore skips
// deferred cleanup such as the test server's Close. Panicking runs the defers
// and fails the example with the error that caused it.
func must(err error) {
	if err != nil {
		panic(err)
	}
}

// fail panics on a broken assumption, for the cases where the failure is a
// missing answer rather than a returned error.
func fail(format string, args ...any) {
	panic(fmt.Errorf(format, args...))
}

// cannedServer stands in for the API so the examples run offline and
// deterministically. A real caller talks to the real endpoint.
func cannedServer() *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
		  "model": "jev-1.13.0",
		  "answers": {
		    "urgent": {"type": "noul", "noul": 0.97},
		    "team":   {"type": "choice", "choice": "billing",
		               "probabilities": {"billing": 0.9, "technical": 0.1}, "confidence": 0.8}
		  },
		  "usage": {"input_tokens": 312, "output_tokens": 48}
		}`))
	}))
}

func main() {
	srv := cannedServer()
	defer srv.Close()

	client, err := sdk.New(
		sdk.WithAPIKey("example-key"),
		sdk.WithBaseURL(srv.URL),
	)
	if err != nil {
		must(err)
	}

	result, err := client.Evaluate(context.Background(),
		map[string]any{
			"subject": "Duplicate charge",
			"message": "I was charged twice and I need this fixed today.",
		},
		sdk.Questions{
			"urgent": sdk.NoulQuestion{
				Instructions: "Does this message convey urgency?",
			},
			"team": sdk.ChoiceQuestion{
				Instructions: "Which team should handle this?",
				Criteria: map[string]sdk.Entry{
					"billing":   "Payments, invoicing, refunds",
					"technical": "Bugs, outages, integrations",
				},
			},
		},
	)
	if err != nil {
		must(err)
	}

	// The model id in the response is the version that actually answered, which
	// is what to record when a decision is later questioned.
	fmt.Println("model:", result.Model)

	urgent, ok := result.Noul("urgent")
	if !ok {
		fail("no noul answer named urgent")
	}
	fmt.Printf("urgent: %.2f\n", urgent.Noul)

	team, ok := result.Choice("team")
	if !ok {
		fail("no choice answer named team")
	}
	fmt.Printf("team: %s (confidence %.1f)\n", team.Choice, team.Confidence)

	fmt.Println("input tokens:", result.Usage.InputTokens)

}
Output:
model: jev-1.13.0
urgent: 0.97
team: billing (confidence 0.8)
input tokens: 312
Example (Errors)

ExampleClient_Evaluate_errors shows the three failures a caller has to tell apart: a rejected request, a refused credential, and a service that is simply unreachable.

Every error matches one of the package's sentinels, so a single errors.Is switch is enough to decide between failing the user's request, failing over to another backend, or failing open.

package main

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

	"github.com/cipherTing/sael/sdk"
)

// must panics on a non-nil error.
//
// Examples must not return early: a missing line of output is reported as a
// confusing mismatch rather than a clear failure. log.Fatal is the obvious
// choice and the wrong one, because it calls os.Exit and therefore skips
// deferred cleanup such as the test server's Close. Panicking runs the defers
// and fails the example with the error that caused it.
func must(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusUnauthorized)
		_, _ = w.Write([]byte(`{"error":{"message":"invalid api key","code":401}}`))
	}))
	defer srv.Close()

	client, err := sdk.New(sdk.WithAPIKey("bad-key"), sdk.WithBaseURL(srv.URL))
	if err != nil {
		must(err)
	}

	_, err = client.Evaluate(context.Background(), "text", sdk.Questions{
		"q": sdk.NoulQuestion{Instructions: "Is this a greeting?"},
	})

	switch {
	case errors.Is(err, sdk.ErrRateLimit):
		// Back off; the retry policy already honoured Retry-After.
		var rate *sdk.RateLimitError
		_ = errors.As(err, &rate)
		fmt.Println("rate limited for", rate.RetryAfter)

	case errors.Is(err, sdk.ErrAPI):
		var api *sdk.APIError
		_ = errors.As(err, &api)
		fmt.Println("rejected with status", api.StatusCode)

	case errors.Is(err, sdk.ErrTimeout), errors.Is(err, sdk.ErrConnection):
		fmt.Println("service unreachable")

	case errors.Is(err, sdk.ErrValidation):
		fmt.Println("the question set itself is invalid")
	}

}
Output:
rejected with status 401

type Config

type Config struct {
	// BaseURL is the API root; the client appends "/systemone".
	BaseURL string `json:"base_url,omitempty"`
	// Model is the default model id.
	Model string `json:"model,omitempty"`
	// Timeout bounds a single attempt, for example "10s".
	Timeout string `json:"timeout,omitempty"`
	// TotalTimeout bounds the whole call including retries, for example "3s".
	TotalTimeout string `json:"total_timeout,omitempty"`
	// MaxRetries is a pointer so an explicit 0 disables retries rather than
	// being indistinguishable from an absent field.
	MaxRetries *int `json:"max_retries,omitempty"`
	// MaxResponseBytes bounds how much of a response body is buffered.
	MaxResponseBytes int64 `json:"max_response_bytes,omitempty"`
	// Headers are sent on every request. Authorization, Content-Type and Accept
	// cannot be set here.
	Headers map[string]string `json:"headers,omitempty"`
}

Config is the contents of config.json.

Every field is optional; an absent field leaves the layer below it in place. Durations are strings, because a bare JSON number leaves it ambiguous whether 3 means seconds or milliseconds — and a hand-edited file is exactly where that ambiguity turns into a bug.

func LoadConfig

func LoadConfig(dir string) (*Config, bool, error)

LoadConfig reads dir/config.json.

A missing file is not an error: it returns (nil, false, nil), which is the ordinary state on a machine that has never been configured. A file that exists but cannot be parsed is an error, because silently ignoring a typo in a hand-edited file is how people lose an afternoon.

func (*Config) Options

func (c *Config) Options() ([]Option, error)

Options converts the file settings into Option values, in an order the caller can insert wherever their own layering wants.

It returns an error rather than deferring it: a duration that cannot be parsed is a fault in a hand-edited file, and reporting it where the file is read is far more useful than reporting it later as a mysterious request timeout.

type ConnectionError

type ConnectionError struct {
	Err error
}

ConnectionError wraps a transport-level failure to reach the service.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Is

func (e *ConnectionError) Is(target error) bool

Is reports whether target is ErrConnection.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap exposes the underlying cause.

type Entry

type Entry = any

Entry is one piece of question or criterion material: text, a JSON object, a JSON array, or null.

It is deliberately an alias for any rather than a narrower type, because the TypeScript SDK's EntryType is a union and callers legitimately pass structs, maps and slices directly. Whatever is stored here is handed to encoding/json unchanged, so the usual encoding/json rules decide what is legal.

type NoulAnswer

type NoulAnswer struct {
	Noul float64
}

NoulAnswer is the probability that the Noul question was answered "true", in [0,1].

func (NoulAnswer) AnswerType

func (NoulAnswer) AnswerType() string

AnswerType implements Answer.

type NoulCriteria

type NoulCriteria struct {
	True  Entry `json:"true"`
	False Entry `json:"false"`
}

NoulCriteria describes the two outcomes of a Noul question.

Both sides are required whenever the criteria object is sent at all, and neither may be null: an explicit null on either side is rejected by the live endpoint with HTTP 400. A nil field here therefore cannot be put on the wire, and ValidateQuestions rejects it before the request is built. To leave an outcome undescribed, pass a description like "" — or omit the whole criteria object by leaving NoulQuestion.Criteria nil.

type NoulQuestion

type NoulQuestion struct {
	// Instructions is the question itself. It is always written, as null when
	// unset: the official SDK's builder defaults it to null.
	Instructions Entry `json:"instructions"`

	// Criteria optionally describes what "true" and "false" mean.
	//
	// It is all or nothing. Nil omits the "criteria" key entirely, which is the
	// common shape and is valid — it must never become an explicit null, because
	// the host rejects "criteria":null with HTTP 400 (zod: expected "object",
	// received null); that is why this field is omitempty, matching the
	// TypeScript SDK's optional criteria. When the pointer is set, both True and
	// False must be non-nil: the host rejects a null on either side with HTTP
	// 400. See ValidateQuestions, which enforces that before sending.
	//
	// The contrast with Instructions is deliberate: the TS builder defaults
	// Instructions to null and always sends it, while criteria is a key that is
	// either fully present or absent.
	Criteria *NoulCriteria `json:"criteria,omitempty"`
}

NoulQuestion is a yes/no judgement. The answer is a probability in [0,1].

func (NoulQuestion) MarshalJSON

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

MarshalJSON writes {"type":"noul","instructions":<entry>[,"criteria":{...}]}.

"instructions" is always present and is null when unset: the official SDK defaults it to null rather than omitting it, so the key is written unconditionally. "criteria" is omitted when nil — never null, which the service rejects with HTTP 400.

func (NoulQuestion) QuestionType

func (NoulQuestion) QuestionType() string

QuestionType implements Question.

type Option

type Option func(*config)

An Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the bearer token. When unset, New reads EnvAPIKey.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets the API root; the client appends "/systemone". Use this to target a gateway, a proxy, or a local test server.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient supplies the underlying client.

The default client sets no Timeout, because deadlines are applied per attempt through the context, and refuses to follow redirects: this endpoint is a single POST to a fixed URL, and following a 3xx silently rewrites the request into a GET without a body while replaying credentials at a location the server chose. Supplying a client here replaces that policy with whatever it carries, so a caller who passes one takes over responsibility for redirect handling.

func WithHeader

func WithHeader(key, value string) Option

WithHeader adds a header sent on every request, for caller-specific needs such as gateway attribution or a tracing id. It is a general escape hatch, not an accommodation for any particular host: this API ignores unknown request headers, so most callers never need it. Headers added here cannot override Authorization, Content-Type or Accept.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets a structured logger. The default discards all output.

Credential headers are never logged. Request and response bodies are logged at debug level when a logger is supplied, which is the same trade-off the official SDK makes; do not enable debug logging on untrusted content.

func WithMaxResponseBytes

func WithMaxResponseBytes(n int64) Option

WithMaxResponseBytes bounds how much of a response body is buffered before the call fails. Zero or negative means MaxResponseBytes.

The bound exists so that a host which keeps sending cannot exhaust memory. It is not a rate limit, and the real responses are kilobytes, so lowering it is only worth doing if a caller wants to be stricter than the default.

func WithModel

func WithModel(model string) Option

WithModel sets the default model id, overridable per call with WithCallModel.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) Option

WithRetryPolicy replaces the retry policy. Use DefaultRetryPolicy() as a base.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds a single attempt. Zero disables the per-attempt deadline.

func WithTotalTimeout

func WithTotalTimeout(d time.Duration) Option

WithTotalTimeout bounds the whole call, retries included.

The official SDK has no equivalent: its timeout is per attempt, so three attempts of a 10s timeout can stall a caller for 30s or more. On a request path that is usually unacceptable, so set this. Zero means no overall bound.

type Question

type Question interface {

	// QuestionType is the wire discriminator: "noul", "choice" or "score".
	QuestionType() string
	// contains filtered or unexported methods
}

Question is a single typed question in a request. The interface is sealed by the unexported isQuestion method: the only implementations are NoulQuestion, ChoiceQuestion and ScoreQuestion.

type Questions

type Questions map[string]Question

Questions maps the name of each question to the question. The name is the key under which the answer comes back, so Result accessors take the same string.

type RateLimitError

type RateLimitError struct {
	APIError
	// RetryAfter is the wait the server asked for, or 0 when it asked for none.
	RetryAfter time.Duration
}

RateLimitError is an APIError for HTTP 429.

func (*RateLimitError) As

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

As lets errors.As reach the embedded *APIError.

Embedding APIError by value does not make *RateLimitError assignable to *APIError, so without this a caller cannot handle "any HTTP error" uniformly and then special-case rate limiting.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Is

func (e *RateLimitError) Is(target error) bool

Is reports whether target is ErrRateLimit or ErrAPI.

type Result

type Result struct {
	Model    string
	Provider string
	ID       string
	Usage    Usage

	// Answers holds every answer the service returned, keyed by question name.
	// An answer whose type this client does not understand is skipped, so the
	// rest still decode.
	Answers map[string]Answer
}

Result is one successful response.

Model is the resolved, versioned model id, which may differ from the string requested (an alias such as "jev-latest" resolves to a pinned version): log it, because answer behaviour is tied to that version. Provider and ID are optional metadata: a host may omit either or both, and they then stay empty rather than failing the decode.

func (*Result) Choice

func (r *Result) Choice(name string) (ChoiceAnswer, bool)

Choice returns the answer stored under name if it is a choice answer. The bool is false when the name is absent, the answer has a different type, or r is nil.

func (*Result) Noul

func (r *Result) Noul(name string) (NoulAnswer, bool)

Noul returns the answer stored under name if it is a noul answer. The bool is false when the name is absent, the answer has a different type, or r is nil.

func (*Result) Score

func (r *Result) Score(name string) (ScoreAnswer, bool)

Score returns the answer stored under name if it is a score answer. The bool is false when the name is absent, the answer has a different type, or r is nil.

Example

ExampleResult_Score reads a Score answer, which reports an expectation across an ordered rubric rather than a single level.

Score is fractional, so it can land between levels. Index Legend and Probabilities with the score to read the distribution around it.

package main

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

	"github.com/cipherTing/sael/sdk"
)

// must panics on a non-nil error.
//
// Examples must not return early: a missing line of output is reported as a
// confusing mismatch rather than a clear failure. log.Fatal is the obvious
// choice and the wrong one, because it calls os.Exit and therefore skips
// deferred cleanup such as the test server's Close. Panicking runs the defers
// and fails the example with the error that caused it.
func must(err error) {
	if err != nil {
		panic(err)
	}
}

// fail panics on a broken assumption, for the cases where the failure is a
// missing answer rather than a returned error.
func fail(format string, args ...any) {
	panic(fmt.Errorf(format, args...))
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
		  "model": "jev-1.13.0",
		  "answers": {"severity": {
		    "type": "score", "score": 1.2, "confidence": 0.9,
		    "legend": {"0": "none", "1": "mild", "2": "serious"},
		    "probabilities": {"0": 0.1, "1": 0.6, "2": 0.3}
		  }},
		  "usage": {"input_tokens": 100, "output_tokens": 20}
		}`))
	}))
	defer srv.Close()

	client, err := sdk.New(sdk.WithAPIKey("example-key"), sdk.WithBaseURL(srv.URL))
	if err != nil {
		must(err)
	}

	result, err := client.Evaluate(context.Background(), "some text", sdk.Questions{
		"severity": sdk.ScoreQuestion{
			Instructions: "How much harm would complying do?",
			Criteria:     []sdk.Entry{"none", "mild", "serious"},
		},
	})
	if err != nil {
		must(err)
	}

	severity, ok := result.Score("severity")
	if !ok {
		fail("no score answer named severity")
	}
	for level, label := range severity.Legend {
		fmt.Printf("%d %-8s %.1f\n", level, label, severity.Probabilities[level])
	}
}
Output:
0 none     0.1
1 mild     0.6
2 serious  0.3

type RetryPolicy

type RetryPolicy struct {
	// MaxRetries is the number of retries *after* the first attempt. A value of
	// 2 means the request is attempted at most 3 times. Negative values are
	// treated as 0.
	MaxRetries int

	// InitialBackoff is the delay before the second attempt.
	InitialBackoff time.Duration

	// MaxBackoff caps the exponential backoff interval. A non-positive value
	// means "uncapped".
	MaxBackoff time.Duration

	// BackoffJitter is the fraction (0..1) randomly subtracted from each
	// computed backoff interval, so the actual wait is
	// interval*(1 - jitter*rand[0,1)). Values outside 0..1 are clamped.
	BackoffJitter float64

	// RetryStatuses lists the HTTP status codes that should be retried.
	RetryStatuses []int

	// RespectRetryAfter honours a Retry-After response header instead of the
	// computed backoff.
	RespectRetryAfter bool

	// MaxRetryAfter is the largest Retry-After the transport is willing to
	// honour. A non-positive value means "no limit": any Retry-After is used as
	// given.
	MaxRetryAfter time.Duration

	// RetryConnectionErrors retries transport-level failures (dial failures,
	// connection resets, truncated bodies, ...).
	RetryConnectionErrors bool

	// RetryTimeoutErrors retries attempts that ran into the per-attempt timeout.
	RetryTimeoutErrors bool
}

RetryPolicy describes when and how the transport retries a request.

The zero value is valid and means "never retry": MaxRetries is 0, so a single attempt is made (RetryStatuses being empty also disables status-based retries, and both error classes are off).

The defaults mirror the official TypeScript SDK exactly; see DefaultRetryPolicy.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the retry policy of the official TypeScript SDK: 2 retries after the first attempt, on 408, 429 and 5xx, backing off from 500ms doubling to 5s with up to 25% jitter subtracted, honouring Retry-After up to 60s.

Every call returns a fresh RetryStatuses slice, so callers may mutate the result without affecting other callers.

type ScoreAnswer

type ScoreAnswer struct {
	// Score is the expected score. It may fall between rubric levels — the live
	// sample in doc.go reports 0.25 for a four-level rubric — so it is never
	// rounded into an index into Legend.
	Score float64

	// Confidence is the reported confidence in the score, in [0,1].
	Confidence float64

	// Legend holds the rubric descriptions indexed by score. A level missing
	// from the response is an empty string.
	Legend []string

	// Probabilities holds the probability of each score, indexed the same way. A
	// level missing from the response is zero.
	Probabilities []float64
}

ScoreAnswer places the state on the rubric.

Legend and Probabilities are indexed by score: Legend[i] describes score i and Probabilities[i] is the probability mass at score i. The wire format keys both by the decimal score as a string; the decoder densifies them into slices.

func (ScoreAnswer) AnswerType

func (ScoreAnswer) AnswerType() string

AnswerType implements Answer.

type ScoreQuestion

type ScoreQuestion struct {
	// Instructions is the question itself. Always written, null when unset.
	Instructions Entry `json:"instructions"`

	// Criteria are the ordered rubric levels. Written as a JSON array, never a
	// map.
	//
	// The API documents between minScoreLevels (2) and maxScoreLevels (10)
	// levels; see ValidateQuestions for why the minimum is not relaxed to match
	// hosts that accept one.
	Criteria []Entry `json:"criteria"`
}

ScoreQuestion places the state on an ordered rubric. Criteria are indexed by score from zero; entries may be nil.

The answer is an expected score, which may fall between rubric levels, plus a probability for each level.

func (ScoreQuestion) MarshalJSON

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

MarshalJSON writes {"type":"score","instructions":<entry>,"criteria":[...]}.

func (ScoreQuestion) QuestionType

func (ScoreQuestion) QuestionType() string

QuestionType implements Question.

type TimeoutError

type TimeoutError struct {
	Err     error
	Timeout time.Duration
}

TimeoutError wraps a request that ran past its deadline.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Is

func (e *TimeoutError) Is(target error) bool

Is reports whether target is ErrTimeout.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap exposes the underlying cause.

type Usage

type Usage struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`

	// Cost is present only on hosts that report billing per request; it is nil
	// when the host reports token counts alone. A pointer keeps "not reported"
	// distinct from a reported cost of zero.
	Cost *float64 `json:"cost,omitempty"`
}

Usage reports token accounting for one request.

Directories

Path Synopsis
examples
quickstart command
Command quickstart runs one classification through the sdk client.
Command quickstart runs one classification through the sdk client.

Jump to

Keyboard shortcuts

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