system1go

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 13 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

system1go

A small, dependency-free Go client for native System One and OpenAI Decisions, from 3inch.ai Labs. Go port of system1ts.

同じ Decide(ctx, request) で Jev・OpenAI・ローカル H2O を利用できます。変換できない機能は送信前にエラーにし、回答拒否と不正・欠落回答を区別します。

Install

Go 1.25 or later. Once the reviewed v0.1.0 tag is published:

go get github.com/3inch-ai/system1go@v0.1.0

Quickstart

client, err := system1go.Jev(system1go.Config{APIKey: os.Getenv("TYPESAFE_API_KEY")})
if err != nil { log.Fatal(err) }
decision, err := client.Decide(ctx, system1go.Request{
    Input: "I was charged twice. Please refund the extra charge.",
    Questions: []system1go.Question{
        {Name: "billing", Type: system1go.Predicate, Instructions: "Is this about billing?"},
        {Name: "route", Type: system1go.Choice, Instructions: "Choose a team",
            Choices: []system1go.Option{{Value: "billing"}, {Value: "shipping"}}},
        {Name: "urgency", Type: system1go.Score, Instructions: "How urgent?",
            Levels: []system1go.Level{{Label: "low"}, {Label: "high", Description: "Needs attention today"}}},
    },
})
if err != nil { log.Fatal(err) }
answer := decision.Answers["billing"]
if answer.Status == system1go.OK { fmt.Println(*answer.Probability) }

The snippet belongs inside an application using context, os, log, fmt, and github.com/3inch-ai/system1go. Complete, runnable no-key/no-inference examples:

go run ./examples/quickstart   # real loopback HTTP, synthetic response
go run ./examples/providers    # inspect Jev/OpenAI/H2O wire shapes, no HTTP

For OpenAI use system1go.OpenAI(Config{APIKey: ...}); for an already running native shim use system1go.H2O(Config{}). Defaults: Jev https://api.typesafe.ai / jev-latest; OpenAI https://api.openai.com / gpt-6-luna; H2O http://127.0.0.1:8741 / h2oai/h2o-lightning-4b. An ordinary chat-completions server is not a native shim. No server is started, model downloaded, environment variable read, or HTTP request sent at import/construction.

For explicit composition:

client, err := system1go.NewClient(system1go.Config{
    Protocol: system1go.SystemOne, Provider: "my-deployment",
    BaseURL: "http://localhost:8741/prefix/v1", Model: "verified-model",
    HTTPClient: &http.Client{Transport: myTransport},
    Timeout: 20 * time.Second, MaxResponseBytes: 2 << 20,
    ExtraBodyKeys: []string{"attention_mode"}, // verified compatible-server extension
})

Provider is descriptive, never routing/model rewriting. Root or /v1 URLs both work and custom prefixes survive. Configured http.Client is copied; redirects are disabled even on injected clients. Its Transport and CookieJar remain shared and must be concurrency-safe and honor request contexts. Do not mutate request data during calls.

Results, errors and semantics

  • Answers[name].Status: OK, Refused (only explicit OpenAI refusal), or Invalid. Missing/wrong-type/unaligned answers are not refusals; valid siblings survive. Check status before dereferencing optional numeric pointers.
  • Probability is truth probability, never a thresholded boolean. Choice and distribution values preserve true versus "true"; native System One rejects booleans rather than inventing labels.
  • Score retains the returned score; ComputedScore is separate verification. Levels retains ordered labels/descriptions. Confidence plus ConfidenceSource is provider-specific certainty, not portable correctness probability.
  • Raw retains original response bytes. Metadata retains extra top-level fields, Usage remains nil if absent (explicit JSON null is retained), and requested/actual models remain distinct. Raw evidence and metadata can be sensitive: do not log without review.
  • Request/transport/envelope failures return *system1go.Error; inspect via errors.As. Codes: invalid_request, unsupported, authentication, rate_limit, timeout, aborted, network, http, invalid_response, request_too_large, response_too_large. No retries, batching, fallback or hidden telemetry. errors.Is(err, context.Canceled/DeadlineExceeded) works. Normal error strings never include upstream body, endpoint or credential values. Diagnostics() and Cause() explicitly expose sensitive debugging material.
  • Timeouts default to 30s and cover HTTP headers and body consumption. Request/response budgets default to 32 MiB / 8 MiB (configurable up to 1 GiB). JSON is buffered; budgets do not bound allocations inside caller-provided MarshalJSON or custom transports. Plain HTTP is allowed for local servers; use HTTPS for hosted credentials.
Explicit provider options

OpenAI Request.Options accepts prompt_cache_key, prompt_cache_options (mode: implicit/explicit/null, ttl: 30m), safety_identifier, and inputTextCacheBreakpoint (text-only explicit end marker). Nullable top-level controls preserve explicit null. Unknown options fail before HTTP. Example:

Options: map[string]any{
    "prompt_cache_key": "support-v1",
    "prompt_cache_options": map[string]any{"mode": "explicit", "ttl": "30m"},
    "inputTextCacheBreakpoint": true,
},

System One options are direct extra body keys, not nested extraBody. Only Config.ExtraBodyKeys declared keys pass; protected model/state/questions/assets cannot be overridden. Official Jev allows none by default. Long-context opt-in uses Config.Headers. Caller-declared extensions/limits are promises about a separately verified deployment, not new server compatibility claims.

Scope and verification

Common surface Native System One OpenAI Decisions
Text / JSON input state string/object/array text or native input_json object/object-array
Predicate noul, optional structured/null instructions and criteria text instructions, no native predicate criteria
Choice 1–255 string options, structured descriptions 2–255 distinct typed string/boolean options, text descriptions
Score 1–10 ordered structured criteria 2–10 labeled levels, text descriptions
Questions no default fixed count cap 1–400, ordered with echoed names checked
Refusal no assumed variant explicit refusal supported

No rich media, Box, conversations/tool histories, model management, proxy, automatic retries or pricing estimator. Complete probability coverage, sums (absolute tolerance .01), maximum-probability choice, and weighted-score consistency (.02) are SDK semantic validation policies; OpenAI's response schema alone does not guarantee all of these. No normalization or missing-value filling occurs. See API contracts, design, competitor evidence, verification, and release steps.

Synthetic HTTP tests are not provider/model tests. No live Jev, OpenAI, or H2O inference has been run for this Go port. Upstream TypeScript live results do not establish Go compatibility. GitHub CI is configured for Linux/macOS/Windows; hosted runs require publication and must be checked separately.

Development

go test -race ./...
go vet ./...
go test -coverprofile=coverage.out ./...
go run ./examples/quickstart
go run ./examples/providers

See contributing, security, roadmap and changelog. MIT license.

Documentation

Overview

Package system1go provides explicit, lossless System One and Decisions clients.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Answer

type Answer struct {
	ConfidenceSource Protocol
	Status           Status
	Type             Kind
	Probability      *float64
	Choice           any
	Score            *float64
	ComputedScore    *float64
	Confidence       *float64
	Probabilities    []Distribution
	Levels           []Level
	Issues           []string
	Raw              json.RawMessage
}

Answer is usable only when Status is OK. Numeric pointers preserve absence. Confidence is provider-specific certainty, not a universal correctness probability. Score is original; ComputedScore is separate verification, never an overwrite.

type Capabilities

type Capabilities struct {
	MinChoices, MaxChoices, MinLevels, MaxLevels, MaxQuestions int
	BooleanChoices, StructuredInstructions, Refusal            bool
}

Capabilities declares the implemented common surface, not all server features.

type Client

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

Client is safe for concurrent calls with independently owned request data.

func H2O

func H2O(c Config) (*Client, error)

H2O connects to an existing native shim. It never starts or downloads models.

func Jev

func Jev(c Config) (*Client, error)

Jev defaults to the official TypeSafe endpoint and mutable jev-latest alias.

func NewClient

func NewClient(c Config) (*Client, error)

NewClient validates configuration without network I/O or environment access.

func OpenAI

func OpenAI(c Config) (*Client, error)

OpenAI defaults to the official Decisions endpoint; this is not chat completions.

func (*Client) Capabilities

func (c *Client) Capabilities() Capabilities

Capabilities returns a copy of this client's declared protocol limits.

func (*Client) Decide

func (c *Client) Decide(ctx context.Context, r Request) (*Decision, error)

Decide validates and snapshots the request, then makes exactly one HTTP request. The context and configured timeout cover response body consumption.

func (*Client) Decode

func (c *Client) Decode(raw []byte, questions []Question) (*Decision, error)

Decode preserves the original JSON and absent usage.

func (*Client) Encode

func (c *Client) Encode(r Request) ([]byte, error)

Encode performs pure protocol conversion without network access.

type Config

type Config struct {
	Protocol         Protocol
	Provider         string
	BaseURL          string
	Model            string
	APIKey           string
	Headers          http.Header
	HTTPClient       *http.Client
	Timeout          time.Duration
	MaxResponseBytes int64
	MaxRequestBytes  int64
	ExtraBodyKeys    []string
	MaxQuestions     int
	MaxChoices       int
	MaxLevels        int
}

Config is snapshotted by NewClient. Zero timeout and byte budgets use safe defaults. MaxQuestions/MaxChoices/MaxLevels and ExtraBodyKeys apply to native deployments only. HTTPClient is copied; its shared Transport/Jar must obey normal net/http concurrency rules.

type Decision

type Decision struct {
	Protocol       Protocol
	Provider       string
	Answers        map[string]Answer
	Raw            json.RawMessage
	Metadata       map[string]json.RawMessage
	Usage          json.RawMessage
	ActualModel    string
	RequestedModel string
	Issues         []string
	HTTP           HTTPMetadata
}

Decision retains normalized answers and original response evidence. Usage is nil when absent; Raw and Metadata may contain sensitive input.

type Distribution

type Distribution struct {
	Value       any
	Label       string
	Probability float64
}

Distribution preserves typed choice values or zero-based integer score indices.

type Error

type Error struct {
	Protocol Protocol
	Provider string
	Code     string
	Question string
	Feature  string
	Status   int
	HTTP     HTTPMetadata
	// contains filtered or unexported fields
}

Error is a safe ordinary error; explicit Diagnostics and Cause may be sensitive. Use errors.As to inspect Code, Question, Feature and HTTP status.

func (*Error) Cause

func (e *Error) Cause() error

Cause explicitly exposes the original transport error; it may contain sensitive URLs.

func (*Error) Diagnostics

func (e *Error) Diagnostics() []byte

Diagnostics explicitly returns potentially sensitive upstream bytes. Never log automatically.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

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

Is supports context cancellation checks without exposing unsafe transport error strings.

type HTTPMetadata

type HTTPMetadata struct {
	Status    int
	RequestID string
	Headers   http.Header
}

HTTPMetadata includes only status and an allowlisted subset of response headers.

type Kind

type Kind string

Kind is a common decision primitive.

const (
	Predicate Kind = "predicate"
	Choice    Kind = "choice"
	Score     Kind = "score"
)

type Level

type Level struct {
	Label       string `json:"label"`
	Description any    `json:"description,omitempty"`
}

Level is an ordered score criterion. Description may be structured natively.

type Option

type Option struct {
	Value       any `json:"value"`
	Description any `json:"description,omitempty"`
}

Option has a string or boolean Value. Native System One permits strings only.

type Protocol

type Protocol string

Protocol identifies a wire contract independently of provider or model.

const (
	SystemOne       Protocol = "system-one"
	OpenAIDecisions Protocol = "openai-decisions"
)

type Question

type Question struct {
	Name         string
	Type         Kind
	Instructions any
	Criteria     map[string]any
	Choices      []Option
	Levels       []Level
}

Question is a named primitive. Only fields appropriate to Type may be set. Native Instructions may be nil or structured; OpenAI requires text.

type Request

type Request struct {
	Input     any
	Questions []Question
	Options   map[string]any
}

Request supplies shared text/JSON evidence and uniquely named ordered questions. Options accepts only explicitly implemented or declared provider fields.

type Status

type Status string

Status distinguishes usable answers, explicit refusals and invalid answers.

const (
	OK      Status = "ok"
	Refused Status = "refused"
	Invalid Status = "invalid"
)

Directories

Path Synopsis
examples
providers command
Inspect provider-specific wire shapes offline.
Inspect provider-specific wire shapes offline.
quickstart command
This runnable example uses synthetic loopback HTTP, never a real model.
This runnable example uses synthetic loopback HTTP, never a real model.

Jump to

Keyboard shortcuts

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