typesafe

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

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

README

TypeSafe Go SDK

Go Reference

An unofficial community SDK for the TypeSafe v1 API. It provides a small, dependency-free Go client for System One and model discovery.

This project is not affiliated with or endorsed by TypeSafe.

Install

go get github.com/zhirschtritt/typesafe-go

Requires Go 1.23 or later.

Quickstart

package main

import (
	"context"
	"fmt"
	"log"

	typesafe "github.com/zhirschtritt/typesafe-go"
)

func main() {
	client, err := typesafe.NewClient()
	if err != nil {
		log.Fatal(err)
	}

	response, err := client.SystemOne(context.Background(),
		map[string]any{
			"draft": "Ship the migration on Friday.",
			"author": "Avery",
		},
		map[string]typesafe.Question{
			"safe": typesafe.Noul("Is the draft safe to send?", nil),
			"audience": typesafe.Choice("Which audience should receive the draft?", map[string]typesafe.Entry{
				"engineering": "Technical stakeholders",
				"customers":   "External customers",
			}),
			"feasibility": typesafe.Score("How feasible is shipping the migration on Friday?",
				"Not feasible", "At risk", "Feasible",
			),
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	safe, _ := response.NoulAnswer("safe")
	audience, _ := response.ChoiceAnswer("audience")
	feasibility, _ := response.ScoreAnswer("feasibility")
	fmt.Printf("safe=%.2f audience=%s feasibility=%.2f request_id=%s\n",
		safe.Noul, audience.Choice, feasibility.Score, response.RequestID)
}

Configuration

Variable Purpose
TYPESAFE_API_KEY API key (required unless supplied with a client option)
TYPESAFE_BASE_URL API base URL override
TYPESAFE_DEFAULT_MODEL Default model override

Use client options to configure a key, base URL, default model, retry behavior, HTTP transport, and maximum response size. Request options can override request-scoped settings such as the model without mutating the client.

Retries and errors

Transient failures are retried according to the configured retry policy. The client honors server Retry-After responses and never retries a canceled context. Every successful response exposes RequestID; typed HTTP errors include the response status, headers, request ID, and bounded response body for diagnostics.

Releases

Releases use Semantic Versioning and are prepared from Conventional Commits:

  • fix: produces a patch release.
  • feat: produces a minor release.
  • A ! after the type or scope, such as feat!: or feat(api)!:, produces a major release. A BREAKING CHANGE: footer has the same effect.
  • Other commit types do not produce a release by themselves.

See CONTRIBUTING.md for local setup, validation commands, and the Conventional Commit format used by the release workflow.

After CI passes on main, Release Please opens or updates a release pull request. Merging that pull request creates the vX.Y.Z tag and GitHub Release. Release notes are derived from the commits; the repository does not maintain a changelog file. The release pull request also updates Version, which is sent in SDK request headers.

Forward compatibility

The decoder accepts additive JSON fields. If the service returns an answer type newer than this SDK, it is preserved as *typesafe.UnknownAnswer with its raw JSON rather than discarded. Handle it explicitly when consuming evolving API responses.

Future improvements

  • When Go 1.27 is an acceptable minimum version, use generic concrete methods for Client.SystemOne and generic question constructors. This will preserve each call's concrete state and instruction types until JSON encoding while allowing one client to accept different types across calls. JSON compatibility will still require runtime validation because an any constraint cannot exclude values unsupported by encoding/json.

References

Security issues should be reported privately as described in SECURITY.md.

License

MIT

Documentation

Overview

Package typesafe provides an unofficial, dependency-free Go client for the TypeSafe v1 API.

Create a Client with NewClient. By default, NewClient reads the API key from TYPESAFE_API_KEY; WithAPIKey can supply it directly. A client is safe for concurrent use.

Use Client.SystemOne to evaluate JSON-compatible state against one or more typed questions. Noul, Choice, and Score construct the supported question types. The returned Response provides typed answer accessors and token usage. Unknown answer types are preserved as UnknownAnswer, allowing applications to handle API additions without losing the original JSON.

Transient failures are retried according to RetryPolicy. Errors returned by the API can be inspected as TypeSafeError with errors.As.

This project is not affiliated with or endorsed by TypeSafe.

TypeSafe API documentation: https://docs.typesafe.ai/

Index

Examples

Constants

View Source
const (

	// Version identifies this SDK in TypeSafe API requests.
	Version = "0.1.3" // x-release-please-version
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIConnectionError

type APIConnectionError struct {
	Err error
}

APIConnectionError reports a network or response-delivery failure.

func (*APIConnectionError) Error

func (e *APIConnectionError) Error() string

Error implements error.

func (*APIConnectionError) Unwrap

func (e *APIConnectionError) Unwrap() error

Unwrap returns the underlying transport error.

type APIError

type APIError struct {
	StatusCode int
	Body       any
	Headers    http.Header
	RequestID  string
}

APIError reports an unsuccessful HTTP response from the TypeSafe API.

func (*APIError) Error

func (e *APIError) Error() string

Error implements error.

type APITimeoutError

type APITimeoutError struct {
	Timeout time.Duration
	Err     error
}

APITimeoutError reports an attempt that exceeded its configured timeout.

func (*APITimeoutError) Error

func (e *APITimeoutError) Error() string

Error implements error.

func (*APITimeoutError) Unwrap

func (e *APITimeoutError) Unwrap() error

Unwrap makes timeout errors usable as APIConnectionError values through errors.As.

type APIUserAbortError

type APIUserAbortError struct {
	Err error
}

APIUserAbortError reports cancellation by the request context.

func (*APIUserAbortError) Error

func (e *APIUserAbortError) Error() string

Error implements error.

func (*APIUserAbortError) Unwrap

func (e *APIUserAbortError) Unwrap() error

Unwrap returns the context cancellation error.

type Answer

type Answer interface {
	AnswerType() string
}

Answer is a typed System One answer. Decoded responses contain pointers to the concrete answer types.

func DecodeAnswer

func DecodeAnswer(data []byte) (Answer, error)

DecodeAnswer decodes one answer selected by its type discriminator.

type AuthenticationError

type AuthenticationError struct{ *APIError }

AuthenticationError reports HTTP 401.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap returns the underlying API error.

type BadRequestError

type BadRequestError struct{ *APIError }

BadRequestError reports HTTP 400.

func (*BadRequestError) Unwrap

func (e *BadRequestError) Unwrap() error

Unwrap returns the underlying API error.

type ChoiceAnswer

type ChoiceAnswer struct {
	Type          string             `json:"type"`
	Choice        string             `json:"choice"`
	Confidence    float64            `json:"confidence"`
	Probabilities map[string]float64 `json:"probabilities"`
}

ChoiceAnswer is the selected option and its probability distribution.

func (ChoiceAnswer) AnswerType

func (ChoiceAnswer) AnswerType() string

AnswerType returns "choice".

type ChoiceQuestion

type ChoiceQuestion struct {
	Instructions Entry            `json:"instructions"`
	Criteria     map[string]Entry `json:"criteria"`
}

ChoiceQuestion asks the model to select one named option.

func Choice

func Choice(instructions Entry, criteria map[string]Entry) ChoiceQuestion

Choice creates a Choice question. criteria must contain between one and 255 options.

func (ChoiceQuestion) MarshalJSON

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

MarshalJSON adds the immutable Choice wire discriminator.

type Client

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

Client communicates with the TypeSafe v1 API. A Client is safe for concurrent use. The caller retains ownership of its HTTP client.

func NewClient

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

NewClient constructs a TypeSafe API client. Explicit options take precedence over environment variables, then SDK defaults.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context, opts ...RequestOption) (*ModelsResponse, error)

ListModels returns models and aliases available to the authenticated account.

func (*Client) SystemOne

func (c *Client) SystemOne(ctx context.Context, state Entry, questions map[string]Question, opts ...RequestOption) (*Response, error)

SystemOne answers named questions about state using a TypeSafe model.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/zhirschtritt/typesafe-go"
)

func main() {
	transport := roundTripperFunc(func(request *http.Request) (*http.Response, error) {
		return &http.Response{
			StatusCode: http.StatusOK,
			Header:     func() http.Header { h := make(http.Header); h.Set("X-TypeSafe-Request-ID", "req_example"); return h }(),
			Body: io.NopCloser(strings.NewReader(`{
				"model":"jev-latest",
				"answers":{
					"safe":{"type":"noul","noul":0.97},
					"audience":{"type":"choice","choice":"engineering","confidence":0.88,"probabilities":{"engineering":0.88,"customers":0.12}},
					"confidence":{"type":"score","score":1.7,"confidence":0.81,"legend":{"0":"Low","1":"Medium","2":"High"},"probabilities":{"0":0.1,"1":0.1,"2":0.8}}
				},
				"usage":{"input_tokens":42,"output_tokens":9}
			}`)),
		}, nil
	})
	client, err := typesafe.NewClient(
		typesafe.WithAPIKey("example-key"),
		typesafe.WithHTTPClient(&http.Client{Transport: transport}),
	)
	if err != nil {
		panic(err)
	}

	response, err := client.SystemOne(context.Background(),
		map[string]any{"draft": "Ship the migration Friday."},
		map[string]typesafe.Question{
			"safe": typesafe.Noul("Is the draft safe to send?", nil),
			"audience": typesafe.Choice("Who is the best audience?", map[string]typesafe.Entry{
				"engineering": "Technical stakeholders",
				"customers":   "External customers",
			}),
			"confidence": typesafe.Score("How likely is Friday?", "Low", "Medium", "High"),
		},
	)
	if err != nil {
		panic(err)
	}

	safe, _ := response.NoulAnswer("safe")
	audience, _ := response.ChoiceAnswer("audience")
	confidence, _ := response.ScoreAnswer("confidence")
	fmt.Printf("%.2f %s %.1f %s\n", safe.Noul, audience.Choice, confidence.Score, response.RequestID)
}

type roundTripperFunc func(*http.Request) (*http.Response, error)

func (fn roundTripperFunc) RoundTrip(request *http.Request) (*http.Response, error) {
	return fn(request)
}
Output:
0.97 engineering 1.7 req_example

type Entry

type Entry = any

Entry is a JSON-compatible value accepted in TypeSafe state and question fields. Top-level state and instructions must be strings, objects, or arrays; nested values may also contain finite numbers, booleans, and nil.

type InternalServerError

type InternalServerError struct{ *APIError }

InternalServerError reports HTTP 5xx.

func (*InternalServerError) Unwrap

func (e *InternalServerError) Unwrap() error

Unwrap returns the underlying API error.

type Model

type Model struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	ReleaseDate string `json:"release_date"`
}

Model describes a model available to the authenticated account.

type ModelsResponse

type ModelsResponse struct {
	Models    []Model `json:"models"`
	RequestID string  `json:"-"`
}

ModelsResponse is the response from the models endpoint.

type NotFoundError

type NotFoundError struct{ *APIError }

NotFoundError reports HTTP 404.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the underlying API error.

type NoulAnswer

type NoulAnswer struct {
	Type string  `json:"type"`
	Noul float64 `json:"noul"`
}

NoulAnswer is the probability that a Noul question is true.

func (NoulAnswer) AnswerType

func (NoulAnswer) AnswerType() string

AnswerType returns "noul".

type NoulCriteria

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

NoulCriteria optionally clarifies what true and false mean for a Noul question.

type NoulQuestion

type NoulQuestion struct {
	Instructions Entry         `json:"instructions"`
	Criteria     *NoulCriteria `json:"criteria,omitempty"`
}

NoulQuestion asks a yes-or-no question.

func Noul

func Noul(instructions Entry, criteria *NoulCriteria) NoulQuestion

Noul creates a Noul question. A nil criteria omits criteria from the request.

func (NoulQuestion) MarshalJSON

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

MarshalJSON adds the immutable Noul wire discriminator.

type Option

type Option func(*clientConfig) error

Option configures a Client. Invalid settings cause NewClient to return an error.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API bearer token.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the API root URL.

func WithDefaultModel

func WithDefaultModel(model string) Option

WithDefaultModel sets the model used unless a request supplies WithModel.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the HTTP client used for requests. The caller retains ownership of it.

func WithHeaders

func WithHeaders(headers http.Header) Option

WithHeaders sets headers sent with every request. A later WithHeaders option replaces an earlier one. Protected TypeSafe headers cannot be overridden.

func WithResponseBodyLimit

func WithResponseBodyLimit(limit int64) Option

WithResponseBodyLimit sets the maximum response body size in bytes.

func WithRetryPolicy

func WithRetryPolicy(policy RetryPolicy) Option

WithRetryPolicy sets the complete retry policy for the client.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the timeout for each HTTP attempt.

type PermissionDeniedError

type PermissionDeniedError struct{ *APIError }

PermissionDeniedError reports HTTP 403.

func (*PermissionDeniedError) Unwrap

func (e *PermissionDeniedError) Unwrap() error

Unwrap returns the underlying API error.

type Question

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

Question describes a typed System One question.

type RateLimitError

type RateLimitError struct {
	*APIError
	RetryAfter time.Duration
}

RateLimitError reports HTTP 429 and includes a parsed retry delay when supplied.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the underlying API error.

type RequestOption

type RequestOption func(*requestConfig) error

RequestOption configures a single API call. Invalid settings cause that call to return an error.

func WithModel

func WithModel(model string) RequestOption

WithModel chooses the model for one SystemOne request.

func WithRequestHeaders

func WithRequestHeaders(headers http.Header) RequestOption

WithRequestHeaders sets headers sent with one API call. A later WithRequestHeaders option replaces an earlier one. Protected TypeSafe headers cannot be overridden.

func WithRequestRetryPolicy

func WithRequestRetryPolicy(policy RetryPolicy) RequestOption

WithRequestRetryPolicy sets the complete retry policy for one API call.

func WithRequestTimeout

func WithRequestTimeout(timeout time.Duration) RequestOption

WithRequestTimeout sets the timeout for each attempt of one API call.

type Response

type Response struct {
	Model     string            `json:"model"`
	Answers   map[string]Answer `json:"answers"`
	Usage     Usage             `json:"usage"`
	RequestID string            `json:"-"`
	// contains filtered or unexported fields
}

Response is the result of a System One request.

func (*Response) ChoiceAnswer

func (r *Response) ChoiceAnswer(id string) (*ChoiceAnswer, bool)

ChoiceAnswer returns the Choice answer with id, if it is a Choice answer.

func (*Response) NoulAnswer

func (r *Response) NoulAnswer(id string) (*NoulAnswer, bool)

NoulAnswer returns the Noul answer with id, if it is a Noul answer.

func (*Response) ScoreAnswer

func (r *Response) ScoreAnswer(id string) (*ScoreAnswer, bool)

ScoreAnswer returns the Score answer with id, if it is a Score answer.

func (*Response) UnknownAnswer

func (r *Response) UnknownAnswer(id string) (*UnknownAnswer, bool)

UnknownAnswer returns the unknown answer with id, if its type is not known by this SDK.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a System One response and its discriminated answers.

type ResponseBodyTooLargeError

type ResponseBodyTooLargeError struct {
	Limit int64
}

ResponseBodyTooLargeError reports a response whose body exceeded the configured limit.

func (*ResponseBodyTooLargeError) Error

func (e *ResponseBodyTooLargeError) Error() string

Error implements error.

type ResponseValidationError

type ResponseValidationError struct {
	RequestID string
	Body      []byte
	Err       error
}

ResponseValidationError reports an invalid successful API response.

func (*ResponseValidationError) Error

func (e *ResponseValidationError) Error() string

Error implements error.

func (*ResponseValidationError) Unwrap

func (e *ResponseValidationError) Unwrap() error

Unwrap returns the response decoding or validation error.

type RetryPolicy

type RetryPolicy struct {
	MaxRetries         int
	BackoffInitial     time.Duration
	BackoffMax         time.Duration
	BackoffJitter      float64
	HTTPStatuses       map[int]struct{}
	RespectRetryAfter  bool
	MaxRetryAfter      time.Duration
	RetryConnectionErr bool
	RetryTimeoutErr    bool
}

RetryPolicy controls which failed attempts are retried and how long the SDK waits.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns an independent copy of the SDK's default retry settings.

type ScoreAnswer

type ScoreAnswer struct {
	Type          string             `json:"type"`
	Score         float64            `json:"score"`
	Confidence    float64            `json:"confidence"`
	Legend        map[string]Entry   `json:"legend"`
	Probabilities map[string]float64 `json:"probabilities"`
}

ScoreAnswer is a probability-weighted score and its level distribution.

func (ScoreAnswer) AnswerType

func (ScoreAnswer) AnswerType() string

AnswerType returns "score".

type ScoreQuestion

type ScoreQuestion struct {
	Instructions Entry   `json:"instructions"`
	Criteria     []Entry `json:"criteria"`
}

ScoreQuestion asks the model to score state against ordered criteria.

func Score

func Score(instructions Entry, criteria ...Entry) ScoreQuestion

Score creates a Score question. criteria must contain between two and 10 ordered levels.

func (ScoreQuestion) MarshalJSON

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

MarshalJSON adds the immutable Score wire discriminator.

type TypeSafeError

type TypeSafeError struct {
	Message string
	Err     error
}

TypeSafeError reports an SDK configuration or input error.

func (*TypeSafeError) Error

func (e *TypeSafeError) Error() string

func (*TypeSafeError) Unwrap

func (e *TypeSafeError) Unwrap() error

Unwrap returns the underlying error, when present.

type UnknownAnswer

type UnknownAnswer struct {
	Type string
	Raw  json.RawMessage
}

UnknownAnswer preserves an answer whose type is not yet known by this SDK.

func (UnknownAnswer) AnswerType

func (a UnknownAnswer) AnswerType() string

AnswerType returns the unrecognized wire discriminator.

func (UnknownAnswer) MarshalJSON

func (a UnknownAnswer) MarshalJSON() ([]byte, error)

MarshalJSON returns the original unknown answer payload.

type UnprocessableEntityError

type UnprocessableEntityError struct{ *APIError }

UnprocessableEntityError reports HTTP 422.

func (*UnprocessableEntityError) Unwrap

func (e *UnprocessableEntityError) Unwrap() error

Unwrap returns the underlying API error.

type Usage

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

Usage reports token consumption for a System One request.

Jump to

Keyboard shortcuts

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