Documentation
¶
Overview ¶
Package typesafe provides a small, dependency-free Go client for the hosted TypeSafe API.
This is an unofficial community SDK maintained by FelineStateMachine. It sends state and questions to TypeSafe's hosted service; inference is performed by that service. See Client and SystemOneRequest for the main entry points.
Index ¶
- Constants
- Variables
- type APIError
- type Answer
- type ChoiceAnswer
- type ChoiceQuestion
- type Client
- type ListModelsResponse
- type ModelCard
- type NoulAnswer
- type NoulCriteria
- type NoulQuestion
- type Option
- func WithAPIKey(key string) Option
- func WithBaseURL(baseURL string) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeaders(headers http.Header) Option
- func WithMaxRetries(maxRetries int) Option
- func WithModel(model string) Option
- func WithRetryPolicy(policy RetryPolicy) Option
- func WithTimeout(timeout time.Duration) Option
- type Question
- type ResponseError
- type RetryPolicy
- type ScoreAnswer
- type ScoreQuestion
- type SystemOneRequest
- type SystemOneResponse
- func (r SystemOneResponse) Answer[T Answer](name string) (T, error)
- func (r SystemOneResponse) Choice(name string) (ChoiceAnswer, error)
- func (r SystemOneResponse) Noul(name string) (NoulAnswer, error)
- func (r SystemOneResponse) Score(name string) (ScoreAnswer, error)
- func (r *SystemOneResponse) UnmarshalJSON(data []byte) error
- type UnknownAnswer
- type Usage
Examples ¶
Constants ¶
const ( // MaxChoiceOptions is the maximum number of labels in a ChoiceQuestion. MaxChoiceOptions = 255 // MaxScoreLevels is the maximum number of levels in a ScoreQuestion. MaxScoreLevels = 10 )
API limits enforced by the hosted service.
const DefaultBaseURL = "https://api.typesafe.ai"
DefaultBaseURL is the hosted TypeSafe API root.
const DefaultModel = "jev-latest"
DefaultModel is used when neither the request nor the client specifies a model.
const Version = "0.2.0"
Version is the SDK version sent in diagnostic request headers.
Variables ¶
var ErrAnswerNotFound = errors.New("answer not found")
ErrAnswerNotFound indicates that a named answer is absent.
var ErrAnswerType = errors.New("answer has unexpected type")
ErrAnswerType indicates that an answer exists but has another type.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
RequestID string
Header http.Header
Body []byte
Method string
URL string
Message string
}
APIError describes a non-2xx HTTP response. Use errors.AsType to inspect it. Body and Header retain the server response and may contain sensitive data. Error deliberately excludes the body, credentials, and full URL.
type Answer ¶
Answer is a discriminated answer returned by System One.
func UnmarshalAnswer ¶
UnmarshalAnswer decodes a discriminated answer and preserves unknown types.
type ChoiceAnswer ¶
type ChoiceAnswer struct {
Choice string `json:"choice"`
Confidence float64 `json:"confidence"`
Probabilities map[string]float64 `json:"probabilities"`
}
ChoiceAnswer contains the selected label, confidence, and label probabilities.
func (ChoiceAnswer) MarshalJSON ¶
func (a ChoiceAnswer) MarshalJSON() ([]byte, error)
MarshalJSON encodes a ChoiceAnswer with its discriminator.
type ChoiceQuestion ¶
type ChoiceQuestion struct {
Instructions any `json:"instructions"`
Criteria map[string]any `json:"criteria"`
}
ChoiceQuestion selects one label from Criteria, which must contain between 2 and MaxChoiceOptions labels. A label's description may be nil.
func (ChoiceQuestion) MarshalJSON ¶
func (q ChoiceQuestion) MarshalJSON() ([]byte, error)
MarshalJSON encodes a ChoiceQuestion with its discriminator.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls the TypeSafe hosted API. A client can be shared by concurrent goroutines. Caller-owned request values and custom transports must also be safe for their usage; do not mutate a request while it is being marshaled. Construct clients with NewClient; the zero value is not ready for use.
func NewClient ¶
NewClient constructs a client using environment variables and options. Explicit options take precedence. An API key is required. Configuration is validated locally; construction does not make any network requests.
func (*Client) ListModels ¶
func (c *Client) ListModels(ctx context.Context) (*ListModelsResponse, error)
ListModels lists models available to the authenticated account. An empty Models slice is a valid response.
func (*Client) SystemOne ¶
func (c *Client) SystemOne(ctx context.Context, request SystemOneRequest) (*SystemOneResponse, error)
SystemOne evaluates named questions against a shared state. Questions are validated before sending. A blank model uses the client's configured model. The context bounds the entire operation, including retries and backoff.
Example ¶
package main
import (
"context"
json "encoding/json/v2"
"fmt"
"net/http"
"net/http/httptest"
"github.com/FelineStateMachine/typesafe-go"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
if err := json.MarshalWrite(writer, map[string]any{
"model": "jev-latest",
"answers": map[string]any{
"ready": map[string]any{"type": "noul", "noul": 0.9},
"kind": map[string]any{"type": "choice", "choice": "stable", "confidence": 0.8, "probabilities": map[string]float64{"stable": 0.8, "beta": 0.2}},
"score": map[string]any{"type": "score", "score": 1.6, "confidence": 0.7, "legend": map[string]any{"0": "not ready", "1": "review", "2": "ready"}, "probabilities": map[string]float64{"0": 0.1, "1": 0.2, "2": 0.7}},
},
"usage": map[string]int{"input_tokens": 12, "output_tokens": 3},
}); err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
}))
defer server.Close()
client, err := typesafe.NewClient(
typesafe.WithAPIKey("test-key"),
typesafe.WithBaseURL(server.URL),
)
if err != nil {
panic(err)
}
response, err := client.SystemOne(context.Background(), typesafe.SystemOneRequest{
State: map[string]any{"text": "ready"},
Questions: map[string]typesafe.Question{
"ready": typesafe.NoulQuestion{Instructions: "Is it ready?", Criteria: &typesafe.NoulCriteria{True: "yes", False: "no"}},
"kind": typesafe.ChoiceQuestion{Instructions: "Which kind?", Criteria: map[string]any{"stable": "stable", "beta": "beta"}},
"score": typesafe.ScoreQuestion{Instructions: "How ready?", Criteria: []any{"not ready", "review", "ready"}},
},
})
if err != nil {
panic(err)
}
ready, err := response.Noul("ready")
if err != nil {
panic(err)
}
kind, err := response.Choice("kind")
if err != nil {
panic(err)
}
score, err := response.Score("score")
if err != nil {
panic(err)
}
fmt.Printf("%.1f %s %.1f\n", ready.Noul, kind.Choice, score.Score)
}
Output: 0.9 stable 1.6
type ListModelsResponse ¶
ListModelsResponse contains the models available to the account.
func (*ListModelsResponse) UnmarshalJSON ¶
func (r *ListModelsResponse) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes and validates a model list response.
type ModelCard ¶
type ModelCard struct {
Name string `json:"name"`
Description string `json:"description"`
ReleaseDate string `json:"release_date"`
}
ModelCard describes an available model.
type NoulAnswer ¶
type NoulAnswer struct {
Noul float64 `json:"noul"`
}
NoulAnswer contains the probability of a yes answer.
func (NoulAnswer) MarshalJSON ¶
func (a NoulAnswer) MarshalJSON() ([]byte, error)
MarshalJSON encodes a NoulAnswer with its discriminator.
type NoulCriteria ¶
NoulCriteria describes the true and false outcomes of a Noul question.
type NoulQuestion ¶
type NoulQuestion struct {
Instructions any `json:"instructions"`
Criteria *NoulCriteria `json:"criteria"`
}
NoulQuestion asks for the probability of a yes answer. It requires Instructions, a non-null criterion, or both.
func (NoulQuestion) MarshalJSON ¶
func (q NoulQuestion) MarshalJSON() ([]byte, error)
MarshalJSON encodes a NoulQuestion with its discriminator.
type Option ¶
type Option func(*clientConfig) error
Option configures a client. Use the With functions to construct options. Options are applied in order, after environment variables and defaults.
func WithAPIKey ¶
WithAPIKey sets the API key, overriding TYPESAFE_API_KEY.
func WithBaseURL ¶
WithBaseURL sets the API root, overriding TYPESAFE_BASE_URL. A path prefix is supported. The URL must use HTTP or HTTPS and contain no credentials, query, or fragment. Use HTTPS for remote services.
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client. The SDK takes a shallow copy and disables redirects; it does not mutate or close the caller's client or transport. A shorter HTTP client timeout also applies to each attempt.
func WithHeaders ¶
WithHeaders copies additional headers. Authentication, JSON content headers, SDK identity headers, and retry count are always controlled by the SDK.
func WithMaxRetries ¶
WithMaxRetries sets retries after the initial attempt. Zero disables retries. It changes only MaxRetries in the current retry policy.
func WithModel ¶
WithModel sets the default model, overriding TYPESAFE_DEFAULT_MODEL. A nonempty SystemOneRequest.Model takes precedence over this setting.
func WithRetryPolicy ¶
func WithRetryPolicy(policy RetryPolicy) Option
WithRetryPolicy replaces the complete retry policy. Start from DefaultRetryPolicy to change selected settings while retaining the defaults.
func WithTimeout ¶
WithTimeout sets the positive timeout for one HTTP attempt, including reading the response body. The default is 10 seconds. Use a context deadline to bound the whole operation, including retries and backoff.
type Question ¶
Question is a typed System One question.
The concrete question types are NoulQuestion, ChoiceQuestion, and ScoreQuestion. Question values always include their wire type discriminator.
func UnmarshalQuestion ¶
UnmarshalQuestion decodes a discriminated question.
type ResponseError ¶
ResponseError reports an invalid or oversized API response. RequestID can be used to correlate the failure with the API service.
func (*ResponseError) Error ¶
func (e *ResponseError) Error() string
Error returns a summary. Inspect Unwrap for the detailed decoding error.
func (*ResponseError) Unwrap ¶
func (e *ResponseError) Unwrap() error
Unwrap exposes the underlying response decoding or validation error.
type RetryPolicy ¶
type RetryPolicy struct {
MaxRetries int
InitialDelay time.Duration
MaxDelay time.Duration
MaxRetryAfter time.Duration
Jitter float64
RetryConnectionErrors bool
RetryTimeouts bool
}
RetryPolicy controls retries after transient failures. All delays must be nonnegative, MaxDelay must be at least InitialDelay, and Jitter is in [0, 1]. Retryable HTTP statuses are 408, 429, and 500–599. A caller's cancellation or deadline always stops the operation, regardless of this policy.
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy returns an independent copy of the default settings: two retries, 500ms initial backoff, 5s maximum backoff, up to 25% downward jitter, and server-requested delays up to 60s. Network failures and attempt timeouts are retried. No total time budget is imposed; use a context deadline.
type ScoreAnswer ¶
type ScoreAnswer struct {
Score float64 `json:"score"`
Confidence float64 `json:"confidence"`
Legend map[string]any `json:"legend"`
Probabilities map[string]float64 `json:"probabilities"`
}
ScoreAnswer contains an expected score, rubric legend, confidence, and probabilities.
func (ScoreAnswer) MarshalJSON ¶
func (a ScoreAnswer) MarshalJSON() ([]byte, error)
MarshalJSON encodes a ScoreAnswer with its discriminator.
type ScoreQuestion ¶
type ScoreQuestion struct {
Instructions any `json:"instructions"`
Criteria []any `json:"criteria"`
}
ScoreQuestion estimates a score using ordered rubric levels in Criteria, which must contain between 2 and MaxScoreLevels non-null levels.
func (ScoreQuestion) MarshalJSON ¶
func (q ScoreQuestion) MarshalJSON() ([]byte, error)
MarshalJSON encodes a ScoreQuestion with its discriminator.
type SystemOneRequest ¶
type SystemOneRequest struct {
State any `json:"state"`
Questions map[string]Question `json:"questions"`
Model string `json:"model,omitempty"`
}
SystemOneRequest contains state and named questions to evaluate.
func (SystemOneRequest) Validate ¶
func (r SystemOneRequest) Validate() error
Validate checks the locally enforceable System One request constraints.
type SystemOneResponse ¶
type SystemOneResponse struct {
Model string `json:"model"`
Answers map[string]Answer `json:"answers"`
Usage Usage `json:"usage"`
RequestID string `json:"-"`
}
SystemOneResponse contains all named answers and request usage metadata.
func (SystemOneResponse) Answer ¶
func (r SystemOneResponse) Answer[T Answer](name string) (T, error)
Answer returns a named answer as the requested concrete answer type.
func (SystemOneResponse) Choice ¶
func (r SystemOneResponse) Choice(name string) (ChoiceAnswer, error)
Choice returns the named Choice answer.
func (SystemOneResponse) Noul ¶
func (r SystemOneResponse) Noul(name string) (NoulAnswer, error)
Noul returns the named Noul answer.
func (SystemOneResponse) Score ¶
func (r SystemOneResponse) Score(name string) (ScoreAnswer, error)
Score returns the named Score answer.
func (*SystemOneResponse) UnmarshalJSON ¶
func (r *SystemOneResponse) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes and validates a SystemOneResponse.
type UnknownAnswer ¶
UnknownAnswer preserves an answer type this SDK does not know yet.
func (UnknownAnswer) MarshalJSON ¶
func (a UnknownAnswer) MarshalJSON() ([]byte, error)