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 ¶
- Constants
- type APIConnectionError
- type APIError
- type APITimeoutError
- type APIUserAbortError
- type Answer
- type AuthenticationError
- type BadRequestError
- type ChoiceAnswer
- type ChoiceQuestion
- type Client
- type Entry
- type InternalServerError
- type Model
- type ModelsResponse
- type NotFoundError
- type NoulAnswer
- type NoulCriteria
- type NoulQuestion
- type Option
- func WithAPIKey(key string) Option
- func WithBaseURL(baseURL string) Option
- func WithDefaultModel(model string) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeaders(headers http.Header) Option
- func WithResponseBodyLimit(limit int64) Option
- func WithRetryPolicy(policy RetryPolicy) Option
- func WithTimeout(timeout time.Duration) Option
- type PermissionDeniedError
- type Question
- type RateLimitError
- type RequestOption
- type Response
- func (r *Response) ChoiceAnswer(id string) (*ChoiceAnswer, bool)
- func (r *Response) NoulAnswer(id string) (*NoulAnswer, bool)
- func (r *Response) ScoreAnswer(id string) (*ScoreAnswer, bool)
- func (r *Response) UnknownAnswer(id string) (*UnknownAnswer, bool)
- func (r *Response) UnmarshalJSON(data []byte) error
- type ResponseBodyTooLargeError
- type ResponseValidationError
- type RetryPolicy
- type ScoreAnswer
- type ScoreQuestion
- type TypeSafeError
- type UnknownAnswer
- type UnprocessableEntityError
- type Usage
Examples ¶
Constants ¶
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 APITimeoutError ¶
APITimeoutError reports an attempt that exceeded its configured timeout.
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 ¶
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 ¶
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 ¶
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 ¶
NoulAnswer is the probability that a Noul question is true.
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 WithDefaultModel ¶
WithDefaultModel sets the model used unless a request supplies WithModel.
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client used for requests. The caller retains ownership of it.
func WithHeaders ¶
WithHeaders sets headers sent with every request. A later WithHeaders option replaces an earlier one. Protected TypeSafe headers cannot be overridden.
func WithResponseBodyLimit ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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.