Documentation
¶
Overview ¶
Package typesafe is an unofficial Go SDK for the TypeSafe System One API (https://docs.typesafe.ai/api).
System One evaluates a piece of content ("state") against one or more typed questions — Noul (yes/no), Choice (pick one option) or Score (rate against ordered levels) — and returns calibrated, probability-backed answers.
Quick start ¶
client, err := typesafe.NewClient() // reads TYPESAFE_API_KEY
if err != nil {
log.Fatal(err)
}
resp, err := client.SystemOne(ctx, &typesafe.Request{
State: "Hi, I've been trying to connect my Stripe account for 3 days...",
Questions: map[string]typesafe.Question{
"is_urgent": typesafe.Noul{
Instructions: "The message conveys urgency or time-sensitivity",
},
},
})
if err != nil {
var rl *typesafe.RateLimitError
if errors.As(err, &rl) {
time.Sleep(rl.RetryAfter)
}
log.Fatal(err)
}
fmt.Println(resp.Answers["is_urgent"].(typesafe.NoulAnswer).Noul)
The client never logs or echoes the API key, retries idempotent failures with jittered exponential backoff by default, and every network call accepts a context.Context so callers control cancellation and deadlines.
Index ¶
- Constants
- Variables
- type APIConnectionError
- type APIError
- type APITimeoutError
- type Answer
- type AuthenticationError
- type BadRequestError
- type Choice
- type ChoiceAnswer
- type Client
- type InternalServerError
- type NotFoundError
- type Noul
- type NoulAnswer
- type NoulCriteria
- type Option
- func WithAPIKey(apiKey string) Option
- func WithBaseURL(baseURL string) Option
- func WithDefaultModel(model string) Option
- func WithHTTPClient(httpClient *http.Client) Option
- func WithMaxRequestBodySize(maxBytes int) Option
- func WithMaxResponseBodySize(maxBytes int) Option
- func WithRetryPolicy(policy RetryPolicy) Option
- func WithTimeout(timeout time.Duration) Option
- func WithUserAgent(userAgent string) Option
- type PermissionDeniedError
- type Question
- type RateLimitError
- type RawAnswer
- type Request
- type Response
- type RetryPolicy
- type Score
- type ScoreAnswer
- type UnprocessableEntityError
- type Usage
Constants ¶
const DefaultBaseURL = "https://api.typesafe.ai/v1/systemone"
DefaultBaseURL is the production TypeSafe API endpoint.
const DefaultModel = "jev-latest"
DefaultModel is the model alias the SDK sends when Request.Model is left empty. It always resolves to TypeSafe's most recent stable release.
const Version = "0.1.0"
Version is the SDK version, sent as part of the User-Agent header.
Variables ¶
var ErrMissingAPIKey = errors.New("typesafe: no API key provided (use WithAPIKey or set TYPESAFE_API_KEY)")
ErrMissingAPIKey is returned by NewClient when no API key was supplied via WithAPIKey or the TYPESAFE_API_KEY environment variable.
Functions ¶
This section is empty.
Types ¶
type APIConnectionError ¶
type APIConnectionError struct{ Err error }
APIConnectionError indicates the request never reached the API, or its response never came back — a DNS failure, refused connection, or a closed connection mid-response. Err holds the underlying network error.
func (*APIConnectionError) Error ¶
func (e *APIConnectionError) Error() string
func (*APIConnectionError) Unwrap ¶
func (e *APIConnectionError) Unwrap() error
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status code returned by the API.
StatusCode int
// Message is a human-readable description of the failure. It is
// extracted from the response body on a best-effort basis (the exact
// error body shape isn't part of TypeSafe's published API reference),
// falling back to the raw body text.
Message string
// Code is the API's machine-readable error code, if the response body
// included one. May be empty.
Code string
// Body is the raw, unparsed response body, for callers that need
// access to fields this SDK doesn't surface.
Body []byte
// Header is the response's HTTP headers.
Header http.Header
}
APIError is returned for any non-2xx response from the TypeSafe API. Use errors.As to check for one of the more specific subtypes below, which all wrap *APIError:
var rl *typesafe.RateLimitError
if errors.As(err, &rl) {
time.Sleep(rl.RetryAfter)
}
type APITimeoutError ¶
type APITimeoutError struct{ Err error }
APITimeoutError indicates the request exceeded the client's configured timeout or the request context's deadline.
func (*APITimeoutError) Error ¶
func (e *APITimeoutError) Error() string
func (*APITimeoutError) Unwrap ¶
func (e *APITimeoutError) Unwrap() error
type Answer ¶
type Answer interface {
// AnswerType returns the API's discriminator value: "noul", "choice"
// or "score" (or the raw value verbatim for a RawAnswer).
AnswerType() string
// contains filtered or unexported methods
}
Answer is the result for one question: a NoulAnswer, ChoiceAnswer, ScoreAnswer, or RawAnswer for an answer type this SDK version does not yet recognize.
Type-switch on the concrete type to read a result:
switch a := resp.Answers["is_urgent"].(type) {
case typesafe.NoulAnswer:
fmt.Println(a.Noul)
case typesafe.ChoiceAnswer:
fmt.Println(a.Choice)
case typesafe.ScoreAnswer:
fmt.Println(a.Score)
}
type AuthenticationError ¶
type AuthenticationError struct{ *APIError }
AuthenticationError is returned for HTTP 401: the API key is missing or invalid.
func (*AuthenticationError) Unwrap ¶
func (e *AuthenticationError) Unwrap() error
Unwrap allows errors.As(err, &(*APIError)(nil)) to match the embedded base error; embedding *APIError alone does not provide this for free.
type BadRequestError ¶
type BadRequestError struct{ *APIError }
BadRequestError is returned for HTTP 400: the request was malformed.
func (*BadRequestError) Unwrap ¶
func (e *BadRequestError) Unwrap() error
type Choice ¶
type Choice struct {
// Instructions tells the model how to choose. Accepts a string or a
// structured object/array with backtick data references.
Instructions any
// Criteria maps each option name to a description of what it means.
// A description may be nil if the option name is self-explanatory.
// Must contain between 1 and 255 entries.
Criteria map[string]any
}
Choice asks the model to select exactly one option from a fixed set. The API returns the selected option along with a probability for every option and a derived confidence score.
func (Choice) MarshalJSON ¶
type ChoiceAnswer ¶
type ChoiceAnswer struct {
// Choice is the selected option name, one of the keys from the
// request's Choice.Criteria.
Choice string `json:"choice"`
// Probabilities maps every offered option to its probability.
Probabilities map[string]float64 `json:"probabilities"`
// Confidence is a 0-1 certainty metric derived from Probabilities.
Confidence float64 `json:"confidence"`
}
ChoiceAnswer is the result of a Choice question.
func (ChoiceAnswer) AnswerType ¶
func (ChoiceAnswer) AnswerType() string
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls the TypeSafe System One API. Construct one with NewClient. A *Client is safe for concurrent use by multiple goroutines.
func NewClient ¶
NewClient builds a Client. Without WithAPIKey, it reads the API key from the TYPESAFE_API_KEY environment variable and returns ErrMissingAPIKey if that's also unset.
type InternalServerError ¶
type InternalServerError struct{ *APIError }
InternalServerError is returned for HTTP 5xx, including 529 (service overloaded).
func (*InternalServerError) Unwrap ¶
func (e *InternalServerError) Unwrap() error
type NotFoundError ¶
type NotFoundError struct{ *APIError }
NotFoundError is returned for HTTP 404.
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
type Noul ¶
type Noul struct {
// Instructions tells the model what to evaluate. It accepts a plain
// string or a structured object/array that references fields of State
// using backtick notation, e.g. "Does `complaint_text` convey urgency?".
Instructions any
// Criteria optionally clarifies what counts as true/false. Either field
// may be omitted.
Criteria *NoulCriteria
}
Noul asks a yes/no question. The API returns a 0-1 probability that the answer is "yes".
func (Noul) MarshalJSON ¶
type NoulAnswer ¶
type NoulAnswer struct {
// Noul is the probability, from 0 to 1, that the answer is "yes".
Noul float64 `json:"noul"`
}
NoulAnswer is the result of a Noul (yes/no) question.
func (NoulAnswer) AnswerType ¶
func (NoulAnswer) AnswerType() string
type NoulCriteria ¶
NoulCriteria clarifies the true/false boundary for a Noul question.
type Option ¶
type Option func(*Client)
Option configures a Client. Pass one or more to NewClient.
func WithAPIKey ¶
WithAPIKey sets the API key explicitly, overriding TYPESAFE_API_KEY.
func WithBaseURL ¶
WithBaseURL overrides the API endpoint. Mainly useful for testing against a local mock server.
func WithDefaultModel ¶
WithDefaultModel overrides the model used when a Request leaves Model empty (default: DefaultModel, "jev-latest"). A Request that sets its own Model still takes precedence over this client-level default.
func WithHTTPClient ¶
WithHTTPClient replaces the underlying *http.Client, e.g. to install a custom transport, proxy, or TLS configuration. Combine with WithTimeout (rather than setting httpClient.Timeout yourself) if you also want the SDK's per-attempt timeout applied — WithTimeout always wins regardless of which of the two options is passed first.
func WithMaxRequestBodySize ¶
WithMaxRequestBodySize overrides the client-side cap on the encoded request body (default 4MB, sized for the model's ~64k token context window). Requests larger than this fail locally instead of round-tripping to the API only to be rejected there.
func WithMaxResponseBodySize ¶
WithMaxResponseBodySize overrides the cap on how much of a response body the client will read (default 64MB). Guards against unbounded memory use if a response is unexpectedly huge, e.g. WithBaseURL pointed somewhere untrusted or misbehaving.
func WithRetryPolicy ¶
func WithRetryPolicy(policy RetryPolicy) Option
WithRetryPolicy overrides the default retry behavior. Pass NoRetry() to disable retries entirely.
func WithTimeout ¶
WithTimeout sets the per-attempt HTTP timeout (default 60s). It does not bound retries as a whole — wrap the call's context with context.WithTimeout for that. Order-independent with WithHTTPClient: it always applies last, whichever order the two options are passed in.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent header sent with every request.
type PermissionDeniedError ¶
type PermissionDeniedError struct{ *APIError }
PermissionDeniedError is returned for HTTP 403: the API key is valid but not authorized for this operation.
func (*PermissionDeniedError) Unwrap ¶
func (e *PermissionDeniedError) Unwrap() error
type Question ¶
type Question interface {
// contains filtered or unexported methods
}
Question is one named question sent to the System One API. The three concrete implementations are Noul, Choice and Score. The set is closed — there is no need to implement this interface yourself.
type RateLimitError ¶
RateLimitError is returned for HTTP 429. RetryAfter is parsed from the response's Retry-After header when present; the SDK's built-in retry logic already honors it, so most callers only need this when they've disabled retries.
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
type RawAnswer ¶
type RawAnswer struct {
Type string
Raw json.RawMessage
}
RawAnswer preserves an answer whose "type" this SDK version does not recognize, so that upgrading the API server never breaks decoding of responses to older SDK clients. Inspect Raw yourself, or upgrade the SDK.
func (RawAnswer) AnswerType ¶
type Request ¶
type Request struct {
// State is the content to evaluate. It may be a string, or a
// structured map/slice — anything JSON-serializable. Required.
State any
// Model selects the model version. Defaults to DefaultModel
// ("jev-latest") when empty.
Model string
// Questions maps a caller-chosen question ID to a Noul, Choice or
// Score question. Required, must be non-empty.
Questions map[string]Question
}
Request is the body of a POST /v1/systemone call: a piece of content ("state") evaluated against one or more named questions.
func (Request) MarshalJSON ¶
MarshalJSON implements json.Marshaler, applying DefaultModel when Model is unset.
type Response ¶
type Response struct {
// Model is the specific versioned model ID that produced the answers
// (e.g. "jev-1.13.0"), even when the request used an alias.
Model string
// Answers holds one entry per question ID from the request. Each
// value is a NoulAnswer, ChoiceAnswer, ScoreAnswer, or — for
// forward-compatibility with answer types this SDK version doesn't
// know about yet — a RawAnswer.
Answers map[string]Answer
Usage Usage
}
Response is the body of a successful System One call.
func (*Response) UnmarshalJSON ¶
type RetryPolicy ¶
type RetryPolicy struct {
// MaxRetries is the number of retry attempts after the initial try.
// 0 disables retrying entirely.
MaxRetries int
// RetryableStatusCodes lists HTTP status codes worth retrying.
// Anything else fails immediately.
RetryableStatusCodes []int
// BaseDelay is the delay before the first retry.
BaseDelay time.Duration
// MaxDelay caps the exponential backoff delay, before jitter.
MaxDelay time.Duration
}
RetryPolicy controls how the client retries failed requests. The zero value is not usable directly — start from DefaultRetryPolicy().
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy retries connection failures, timeouts, HTTP 429 (rate limited) and 5xx responses (including 529, "service overloaded") up to twice, with jittered exponential backoff starting at 500ms and capped at 8s — matching the retry behavior TypeSafe's own SDKs document.
func NoRetry ¶
func NoRetry() RetryPolicy
NoRetry disables retries: every request is attempted exactly once.
type Score ¶
type Score struct {
// Instructions tells the model how to rate. Accepts a string or a
// structured object/array with backtick data references.
Instructions any
// Criteria lists each level's description in ascending order, e.g.
// []any{"poor", "fair", "good", "excellent"}. Must contain between 2
// and 10 entries.
Criteria []any
}
Score asks the model to rate the state against an ordered list of descriptive levels, from lowest to highest. The API returns a probability-weighted score plus a per-level probability distribution.
func (Score) MarshalJSON ¶
type ScoreAnswer ¶
type ScoreAnswer struct {
// Score is the probability-weighted rating across the requested
// levels.
Score float64 `json:"score"`
// Legend maps each level's index (as a string) to its description
// from the request's Score.Criteria.
Legend map[string]string `json:"legend"`
// Probabilities maps each level's index (as a string) to its
// probability.
Probabilities map[string]float64 `json:"probabilities"`
// Confidence is a 0-1 certainty metric derived from Probabilities.
Confidence float64 `json:"confidence"`
}
ScoreAnswer is the result of a Score question.
func (ScoreAnswer) AnswerType ¶
func (ScoreAnswer) AnswerType() string
type UnprocessableEntityError ¶
type UnprocessableEntityError struct{ *APIError }
UnprocessableEntityError is returned for HTTP 422: the request was well-formed JSON but failed validation (missing fields, malformed questions, criteria out of bounds, etc).
func (*UnprocessableEntityError) Unwrap ¶
func (e *UnprocessableEntityError) Unwrap() error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
Command basic shows the minimal Noul (yes/no) question flow.
|
Command basic shows the minimal Noul (yes/no) question flow. |
|
choice
command
Command choice shows classifying content into one of several categories, with per-option probabilities and a confidence score.
|
Command choice shows classifying content into one of several categories, with per-option probabilities and a confidence score. |
|
score
command
Command score shows rating content against an ordered set of levels.
|
Command score shows rating content against an ordered set of levels. |