Documentation
¶
Overview ¶
Package superbased is the superbased SDK for Go: it sends traces from the LLM apps and agents you build to superbased over OpenTelemetry (OTLP/HTTP).
It is a thin layer over the official OpenTelemetry Go SDK. Anything it sends, a stock OpenTelemetry exporter can send too; the SDK adds the attribute names superbased reads, per-request identity, content capture with a size limit, the Admit pre-flight check, scores, prompts, experiments, trace cost, and the choice of where the data goes (local, online or both).
It behaves like the Python and TypeScript SDKs: the three run the same shared behaviour cases (sdk/contract/sdk-behaviour-cases.json).
ctx := context.Background()
if _, err := superbased.Init(ctx, superbased.Options{ServiceName: "support-bot"}); err != nil {
log.Fatal(err)
}
defer superbased.Shutdown(ctx)
ctx = superbased.PropagateAttributes(ctx, superbased.Attributes{User: "alice", SessionID: "s1"})
err := superbased.WithLLMSpan(ctx, "chat", superbased.LLMOptions{Model: "gpt-5-nano", Provider: "openai"},
func(ctx context.Context, span trace.Span) error {
// call the model
return superbased.SetUsage(span, superbased.Usage{InputTokens: superbased.Int(1200), OutputTokens: superbased.Int(80)})
})
Never set sbo.emitted_by=observer: that is superbased's own echo-guard marker, and a resource carrying it is dropped at ingestion.
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func ContinueTrace(ctx context.Context, carrier map[string]string) context.Context
- func CurrentAttributes(ctx context.Context) map[string]any
- func CurrentSpanID(ctx context.Context) string
- func CurrentTraceID(ctx context.Context) string
- func EndSpan(sp trace.Span, err error)
- func ExperimentGate(r *ExperimentResult, failUnder *float64, strict bool) (bool, []string)
- func Extract(ctx context.Context, carrier map[string]string) context.Context
- func ExtractHeader(ctx context.Context, h http.Header) context.Context
- func Float(v float64) *float64
- func Flush(ctx context.Context) bool
- func GatewayHeaders(ctx context.Context) map[string]string
- func GatewayTransport(base http.RoundTripper) http.RoundTripper
- func Identify(ctx context.Context, a Attributes) context.Context
- func Inject(ctx context.Context, carrier map[string]string) map[string]string
- func InjectHeader(ctx context.Context, h http.Header)
- func Int(v int) *int
- func IsContentKey(key string) bool
- func IsExactCost(source string) bool
- func Observe[T any](ctx context.Context, name, kind string, fn func(context.Context) (T, error)) (T, error)
- func PropagateAttributes(ctx context.Context, a Attributes) context.Context
- func SetContent(sp trace.Span, c Content)
- func SetDocuments(sp trace.Span, docs any)
- func SetInput(sp trace.Span, v any)
- func SetLogger(l *slog.Logger)
- func SetOutput(sp trace.Span, v any)
- func SetRequestParams(sp trace.Span, p RequestParams)
- func SetToolResult(sp trace.Span, v any)
- func SetUsage(sp trace.Span, u Usage) error
- func Shutdown(ctx context.Context) bool
- func StampGatewayRequestID(ctx context.Context, h http.Header, sp trace.Span) bool
- func StartAgentSpan(ctx context.Context, name string, o AgentOptions) (context.Context, trace.Span)
- func StartEmbeddingSpan(ctx context.Context, name string, o EmbeddingOptions) (context.Context, trace.Span)
- func StartLLMSpan(ctx context.Context, name string, o LLMOptions) (context.Context, trace.Span)
- func StartRetrieverSpan(ctx context.Context, name string, o RetrieverOptions) (context.Context, trace.Span)
- func StartSpan(ctx context.Context, name string, opts SpanOptions) (context.Context, trace.Span)
- func StartToolSpan(ctx context.Context, name string, o ToolOptions) (context.Context, trace.Span)
- func Traceparent(ctx context.Context) string
- func WithAgentSpan(ctx context.Context, name string, o AgentOptions, ...) error
- func WithEmbeddingSpan(ctx context.Context, name string, o EmbeddingOptions, ...) error
- func WithLLMSpan(ctx context.Context, name string, o LLMOptions, ...) error
- func WithRetrieverSpan(ctx context.Context, name string, o RetrieverOptions, ...) error
- func WithSpan(ctx context.Context, name string, opts SpanOptions, ...) error
- func WithToolSpan(ctx context.Context, name string, o ToolOptions, ...) error
- type AdmitOptions
- type AgentOptions
- type Attributes
- type Content
- type CostProvenance
- type Dataset
- type DestinationInfo
- type DestinationResult
- type Diagnostics
- type EmbeddingOptions
- type EvalInput
- type Evaluation
- type Evaluator
- type ExperimentError
- type ExperimentGateFailed
- type ExperimentOptions
- type ExperimentResult
- type FeedbackOptions
- type Item
- type ItemResult
- type LLMOptions
- type Message
- type Options
- type Prompt
- func (p *Prompt) Attributes() []attribute.KeyValue
- func (p *Prompt) Cohort() string
- func (p *Prompt) Compile(ctx context.Context, values map[string]any) (any, error)
- func (p *Prompt) CompileMessages(ctx context.Context, values map[string]any) ([]Message, error)
- func (p *Prompt) CompileText(ctx context.Context, values map[string]any) (string, error)
- func (p *Prompt) Stamp(sp trace.Span)
- type PromptCompileError
- type PromptOptions
- type PromptRollout
- type RequestParams
- type RetrieverOptions
- type ScoreError
- type ScoreOptions
- type ScoreResult
- type ScorerSummary
- type Settings
- type SpanCost
- type SpanOptions
- type Task
- type ToolOptions
- type TraceCost
- type Usage
- type Verdict
Constants ¶
const ( DegradedTimeout = "client-timeout" DegradedTransport = "client-transport" DegradedHTTPError = "client-http-error" DegradedBadResponse = "client-bad-response" DegradedAdmissionOff = "admission-off" // the org answered mode off (no policy) )
Client-side degraded reasons (Verdict.Degraded). A server may send its own values; those pass through unchanged.
const ( DefaultEndpoint = "http://127.0.0.1:4318/v1/traces" DefaultServiceName = "custom-app" DefaultMaxContentChars = 8000 DefaultExportTimeout = 5 * time.Second DefaultShutdownTimeout = 2 * time.Second DefaultNodeURL = "http://127.0.0.1:8081" DefaultAPITimeout = 5 * time.Second DefaultPromptCacheTTL = 60 * time.Second )
Built-in defaults (contract sdk-api-surface.md section 8).
const ( CostGatewayExact = "gateway_exact" CostProxyExact = "proxy_exact" CostComputed = "computed" CostReported = "reported" CostUnpriced = "" )
cost_source values (contract cost-source.md section 1).
const ( DestinationLocal = "local" DestinationOnline = "online" DestinationBoth = "both" )
Destination values (contract destination.md section 1).
const ( HeaderRequestID = "X-SBO-Request-Id" HeaderUser = "X-Superbased-User" HeaderService = "X-Superbased-Service" )
The AI gateway's headers (contract cost-source.md section 4, budgets).
const ( KindLLM = "LLM" KindTool = "TOOL" KindRetriever = "RETRIEVER" KindEmbedding = "EMBEDDING" KindChain = "CHAIN" KindAgent = "AGENT" KindGuardrail = "GUARDRAIL" KindEvaluator = "EVALUATOR" )
Span kinds (OpenInference, uppercase). Pass one as SpanOptions.Kind.
const ( LabelProduction = "production" LabelStaging = "staging" )
Prompt labels (contract prompts.md).
const ( SourceSDK = "sdk" SourceFeedback = "feedback" DefaultFeedbackName = "user_feedback" )
Score sources and kinds (contract scores.md section 1).
const ( VendorTracingOff = "off" VendorTracingKept = "kept" )
Vendor tracing states (Diagnostics.VendorTracing).
const DefaultAdmissionEndpoint = "http://127.0.0.1:8081/api/obs/admission/check"
DefaultAdmissionEndpoint is the local machine's admission check.
const DefaultAdmitTimeout = 12 * time.Second
DefaultAdmitTimeout: the client waits longer than the server's judge budget (10 s). A server-advertised recommended timeout overrides it for later calls.
const Version = "0.1.0"
Version is this SDK's version (lockstep with the Python and TypeScript SDKs).
Variables ¶
var ( ErrPromptNotFound = errors.New("superbased: prompt not found") ErrPromptFetch = errors.New("superbased: prompt fetch failed") ErrInvalidArgument = errors.New("superbased: invalid argument") )
Prompt errors. Use errors.Is: GetPrompt's errors wrap ErrPromptNotFound or ErrPromptFetch; a bad argument wraps ErrInvalidArgument.
var CostSourceLabels = map[string]string{ CostGatewayExact: "Gateway exact", CostProxyExact: "Proxy exact", CostComputed: "Computed", CostReported: "Reported", CostUnpriced: "Unpriced", }
CostSourceLabels are the display labels of the cost_source values.
var ErrNegativeCount = errors.New("superbased: a token count must not be negative")
ErrNegativeCount is returned (wrapped) by SetUsage for a negative token count.
Functions ¶
func ContinueTrace ¶
ContinueTrace is Extract plus the per-request values the caller sent as sbo.* baggage, restored into the attribute scope. Spans started from the returned context join the caller's trace.
func CurrentAttributes ¶
CurrentAttributes are the per-request values in effect in ctx, by option name (user, session_id, tenant, release, environment, tags, metadata), present keys only.
func CurrentSpanID ¶
CurrentSpanID is the span id of the span in ctx (16 lowercase hex), or "".
func CurrentTraceID ¶
CurrentTraceID is the trace id of the span in ctx (32 lowercase hex), or "".
func EndSpan ¶
EndSpan ends sp: with err it records the error once and sets ERROR; without, it sets OK unless a status was already set.
func ExperimentGate ¶
func ExperimentGate(r *ExperimentResult, failUnder *float64, strict bool) (bool, []string)
ExperimentGate says whether failUnder fails r and why the strict gate fails before the rate is compared (TS experimentGate). nil failUnder is no gate.
func Extract ¶
Extract returns ctx with the remote span context and baggage carried by W3C headers in carrier (names case-insensitive). A malformed header gives no remote parent.
func ExtractHeader ¶
ExtractHeader is Extract over an http.Header.
func Flush ¶
Flush exports every finished span now. It is bounded by ctx's deadline when ctx has one, else by the Init ShutdownTimeout, and returns true when everything was exported in time. Call it at the end of a serverless handler.
func GatewayHeaders ¶
GatewayHeaders are the headers a request to the AI gateway should carry now: X-Superbased-User (the request scope's end user, else Init's), X-Superbased-Service (the service the app's spans carry, which app budget caps bind on) and a client-minted X-SBO-Request-Id. A value that is empty or not header-safe is left out.
func GatewayTransport ¶
func GatewayTransport(base http.RoundTripper) http.RoundTripper
GatewayTransport wraps base (nil: http.DefaultTransport) for model calls that go through the organization's AI gateway: it adds GatewayHeaders that the request does not already carry, and stamps the answer's X-SBO-Request-Id as request_id on the span in the request's context. Use it as the Transport of the http.Client your model SDK takes (for example the OpenAI Go SDK's option.WithHTTPClient).
func Identify ¶
func Identify(ctx context.Context, a Attributes) context.Context
Identify is PropagateAttributes: a Go context is a value, so the identity lasts as long as the returned context is used (the contract's identify() and reset()).
func Inject ¶
Inject writes traceparent (and tracestate and baggage when present) for ctx into carrier (a new map when nil) and returns it. Always W3C, whatever propagator the host registered.
func InjectHeader ¶
InjectHeader writes the same headers into an http.Header.
func IsContentKey ¶
IsContentKey reports whether key carries prompt, response or tool I/O content: CaptureContent, Mask and MaxContentChars apply to it.
func IsExactCost ¶
IsExactCost reports whether a cost_source is the exact family.
func Observe ¶
func Observe[T any](ctx context.Context, name, kind string, fn func(context.Context) (T, error)) (T, error)
Observe runs fn inside a span of the given kind and returns its result (the Go form of the contract's observe decorator).
func PropagateAttributes ¶
func PropagateAttributes(ctx context.Context, a Attributes) context.Context
PropagateAttributes returns a context whose spans carry a's values (the current span in ctx is tagged too). Nested calls merge: the inner value wins, tags union, metadata merges per key. A value a span already carries is never overwritten.
func SetContent ¶
SetContent attaches request and response bodies. The span's kind decides the keys: TOOL -> gen_ai.tool.call.arguments / .result; otherwise a string goes to input.value / output.value and a message list to gen_ai.input.messages / gen_ai.output.messages. No-op when content capture is off; each body is clipped to MaxContentChars.
func SetDocuments ¶
SetDocuments records retrieved documents (gen_ai.retrieval.documents, a JSON array; a string element becomes {"content": s}).
func SetLogger ¶
SetLogger sets where the SDK writes its few log lines (warnings: a degraded destination, an admit() that got no decision, export failures once a minute; info: discovery notes). nil restores slog.Default().
func SetOutput ¶
SetOutput records a span's output (output.value; on a RETRIEVER span it is SetDocuments).
func SetRequestParams ¶
func SetRequestParams(sp trace.Span, p RequestParams)
SetRequestParams records the model request parameters.
func SetToolResult ¶
SetToolResult records a tool call's result (gen_ai.tool.call.result).
func SetUsage ¶
SetUsage records token usage, ids and the outcome on an LLM (or embedding) span. A negative count returns an error and nothing is written. An InputTokens below CacheReadTokens + CacheWriteTokens cannot be gross: it is read as a NET count (Anthropic's usage.input_tokens is net), recorded as input + cache, counted in Diagnostics.UsageNetInputCorrected and warned about once per process; a TotalTokens equal to that net input + output is raised by the same amount.
func Shutdown ¶
Shutdown flushes and stops the SDK's exporters, bounded like Flush even when an endpoint is down. A host provider the SDK attached to keeps running. A later Init starts exporting again.
func StampGatewayRequestID ¶
StampGatewayRequestID sets request_id on sp from the AI gateway's X-SBO-Request-Id response header (default span: the one in ctx), so the org joins the gateway's exact cost to the span. It returns true when it stamped; a missing header, a span that already has request_id or a non-recording span stamps nothing.
func StartAgentSpan ¶
StartAgentSpan starts an AGENT span (gen_ai.operation.name=invoke_agent).
func StartEmbeddingSpan ¶
func StartEmbeddingSpan(ctx context.Context, name string, o EmbeddingOptions) (context.Context, trace.Span)
StartEmbeddingSpan starts an EMBEDDING span (gen_ai.operation.name=embeddings).
func StartLLMSpan ¶
StartLLMSpan starts an LLM span tagged in the GenAI and OpenInference vocabularies (gen_ai.operation.name, gen_ai.request.model, llm.model_name, gen_ai.provider.name, gen_ai.system, llm.provider).
func StartRetrieverSpan ¶
func StartRetrieverSpan(ctx context.Context, name string, o RetrieverOptions) (context.Context, trace.Span)
StartRetrieverSpan starts a RETRIEVER span (gen_ai.operation.name=retrieval).
func StartSpan ¶
StartSpan starts a span of the given OpenInference kind. End it with EndSpan (or span.End()).
func StartToolSpan ¶
StartToolSpan starts a TOOL span (gen_ai.operation.name=execute_tool).
func Traceparent ¶
Traceparent is the W3C traceparent of the span in ctx, or "".
func WithAgentSpan ¶
func WithAgentSpan(ctx context.Context, name string, o AgentOptions, fn func(context.Context, trace.Span) error) error
WithAgentSpan runs fn inside an AGENT span.
func WithEmbeddingSpan ¶
func WithEmbeddingSpan(ctx context.Context, name string, o EmbeddingOptions, fn func(context.Context, trace.Span) error) error
WithEmbeddingSpan runs fn inside an EMBEDDING span.
func WithLLMSpan ¶
func WithLLMSpan(ctx context.Context, name string, o LLMOptions, fn func(context.Context, trace.Span) error) error
WithLLMSpan runs fn inside an LLM span (see StartLLMSpan and WithSpan).
func WithRetrieverSpan ¶
func WithRetrieverSpan(ctx context.Context, name string, o RetrieverOptions, fn func(context.Context, trace.Span) error) error
WithRetrieverSpan runs fn inside a RETRIEVER span.
func WithSpan ¶
func WithSpan(ctx context.Context, name string, opts SpanOptions, fn func(context.Context, trace.Span) error) error
WithSpan runs fn inside a span and returns fn's error. An error or a panic is recorded once and sets ERROR (the panic continues); success sets OK unless fn set a status.
Types ¶
type AdmitOptions ¶
type AdmitOptions struct {
// Tenant, User and Session: the argument, else the request scope
// (PropagateAttributes), else Init's value.
Tenant, User, Session string
TraceID, RequestID string
// Endpoint is a full admission URL; OrgURL an organization gateway base
// (+ /v1/sdk/admit). Both win over the destination plan.
Endpoint, OrgURL string
// APIKey is sent as Authorization: Bearer (an explicit key goes even to a
// loopback endpoint).
APIKey string
Headers map[string]string
// Timeout defaults to the server-advertised recommended timeout once one
// was seen, else 12 s.
Timeout time.Duration
// FailClosed denies when no decision could be obtained
// (SUPERBASED_ADMISSION_FAIL_CLOSED); the default admits.
FailClosed *bool
}
AdmitOptions are the options of Admit.
type AgentOptions ¶
type AgentOptions struct {
AgentName string // default: the span name
AgentID string
Attributes []attribute.KeyValue
}
AgentOptions are the options of an AGENT span.
type Attributes ¶
type Attributes struct {
User string
SessionID string
Tenant string
Release string
Environment string
// Tags are unioned with the outer scope's (trimmed, empty dropped, sorted,
// at most 32 of at most 128 characters).
Tags []string
// Metadata merges per key over the outer scope's, a nil value deleting the
// key; a value that is not a string is JSON-encoded (compact, sorted keys).
Metadata map[string]any
// Clear removes these options (by name) from the inner scope.
Clear []string
// AsBaggage also puts the values into W3C baggage, so Inject carries them.
AsBaggage bool
}
Attributes are per-request values (contract sdk-api-surface.md section 2). An empty string or nil field keeps the outer scope's value; Clear names the options to clear for the inner scope ("user", "session_id", "tenant", "release", "environment").
type CostProvenance ¶
type CostProvenance struct {
Label string `json:"label"`
Complete bool `json:"complete"`
Sources map[string]int `json:"sources"`
}
CostProvenance says where a trace's cost came from.
type Dataset ¶
type Dataset struct {
ID string
Name string
Side string
ItemCount int
LatestSnapshot int
Raw map[string]any
}
Dataset is a dataset on one destination.
type DestinationInfo ¶
DestinationInfo is one export target in Diagnostics.
type DestinationResult ¶
type DestinationResult struct {
OK bool `json:"ok"`
Status int `json:"status"`
ID string `json:"id"`
Error string `json:"error"`
}
DestinationResult is one destination's answer to a score write.
type Diagnostics ¶
type Diagnostics struct {
Mode string `json:"mode"` // "owned", "attached" or ""
Initialized bool `json:"initialized"`
PendingSpans int64 `json:"pending_spans"` // once per destination
ExportedSpans int64 `json:"exported_spans"`
FailedExports int64 `json:"failed_exports"`
DroppedSpans int64 `json:"dropped_spans"`
LastError string `json:"last_error"`
LastErrorAt time.Time `json:"last_error_at"`
SampledOutSpans int64 `json:"sampled_out_spans"`
FilteredSpans int64 `json:"filtered_spans"`
MaskErrors int64 `json:"mask_errors"`
ShouldExportErrors int64 `json:"should_export_errors"`
VendorSpansDropped int64 `json:"vendor_spans_dropped"`
UsageNetInputCorrected int64 `json:"usage_net_input_corrected"`
LastHookError string `json:"last_hook_error"`
AdmissionDegraded int64 `json:"admission_degraded"`
AdmissionLastError string `json:"admission_last_error"`
AdmissionLastErrorAt time.Time `json:"admission_last_error_at"`
VendorTracing map[string]string `json:"vendor_tracing"`
Destination string `json:"destination"`
DestinationSource string `json:"destination_source"`
Destinations []DestinationInfo `json:"destinations"`
GatewayURL string `json:"gateway_url"`
Degraded string `json:"degraded"`
Warnings []string `json:"warnings"`
Notes []string `json:"notes"`
SignedIn *bool `json:"signed_in"`
CredentialSource string `json:"credential_source"`
}
Diagnostics is a snapshot of the SDK's health (contract sdk-api-surface.md section 1). It never holds the credential.
func GetDiagnostics ¶
func GetDiagnostics() Diagnostics
GetDiagnostics returns a snapshot of the SDK's export health.
type EmbeddingOptions ¶
EmbeddingOptions are the options of an EMBEDDING span.
type EvalInput ¶
type EvalInput struct {
Input, Output, Expected, Metadata any
}
EvalInput is what an evaluator sees.
type Evaluation ¶
Evaluation is one evaluator result: Value is a number, a bool or a short label.
func (Evaluation) Passed ¶
func (e Evaluation) Passed() bool
Passed is the contract's pass rule: true, a number >= 0.5, or a label not in fail/false/no/bad.
type Evaluator ¶
type Evaluator interface {
Name() string
Version() string
Evaluate(ctx context.Context, in EvalInput) (any, error)
}
Evaluator scores one item's output. Evaluate may return a number, a bool, a label, an Evaluation (or a slice of them), a map {name, value, comment, version}, a []any of those, or nil (no score).
func EvaluatorFunc ¶
EvaluatorFunc makes an Evaluator (version "1") from a function.
type ExperimentError ¶
type ExperimentError struct{ Msg string }
ExperimentError is an experiment that could not be set up (dataset, run creation), or GetDataset finding no dataset.
func (*ExperimentError) Error ¶
func (e *ExperimentError) Error() string
type ExperimentGateFailed ¶
type ExperimentGateFailed struct {
Result *ExperimentResult
FailUnder float64
Reasons []string
}
ExperimentGateFailed is a FailUnder gate that failed. Result has the details; Reasons is why the strict gate failed before the rate was compared (empty when the pass rate itself is below FailUnder). A CI program exits 1 on it (errors.As).
func (*ExperimentGateFailed) Error ¶
func (e *ExperimentGateFailed) Error() string
type ExperimentOptions ¶
type ExperimentOptions struct {
// Dataset is a dataset name or id (string), a Dataset / *Dataset, or the
// literal items ([]Item, []map[string]any with input / expected |
// expected_output / metadata / id, or []any of bare inputs). A literal item
// with no id gets one derived from its content.
Dataset any
Task Task
Evaluators []Evaluator
Name string // default "experiment"
Metadata map[string]any
// MaxConcurrency is the number of items run at once (default 4).
MaxConcurrency int
// SnapshotVersion pins the dataset snapshot (nil: freeze a new one).
SnapshotVersion *int
// DatasetName uploads literal items to that dataset (created on the
// machine; on the org it must exist). Without it a literal run stays
// in-process: nothing is posted.
DatasetName string
// FailUnder (0..1) fails the run (an *ExperimentGateFailed error) below
// that pass rate. Strict (default true) also fails it when nothing was
// scored, a destination was skipped or a result was not accepted.
FailUnder *float64
Strict *bool
}
ExperimentOptions are RunExperiment's options.
type ExperimentResult ¶
type ExperimentResult struct {
Name string
RunID string // the first destination's run
Runs map[string]string // destination -> run id
Items []ItemResult
SkippedNoContent int
Server map[string]map[string]any // destination -> GET experiment body
Errors []string
// SkippedSides are the destinations skipped for want of a scope.
SkippedSides []string
// FailedPosts counts results a destination did not accept.
FailedPosts int
}
ExperimentResult is a run's outcome.
func RunExperiment ¶
func RunExperiment(ctx context.Context, o ExperimentOptions) (*ExperimentResult, error)
RunExperiment runs Task over every item of Dataset, scores each output with the evaluators and records the run on the destination(s) chosen at Init (each item in its own trace; results posted as they finish; the run finished and read back). It returns an *ExperimentError when the dataset is not found or a run cannot be created, and the result with an *ExperimentGateFailed when FailUnder fails.
func (*ExperimentResult) PassRate ¶
func (r *ExperimentResult) PassRate() float64
PassRate is the first side's pass rate, else the local rate over scored items; NaN when nothing was scored.
func (*ExperimentResult) Scored ¶
func (r *ExperimentResult) Scored() int
Scored is how many items were scored: the first side's total, else the local count of items with a score or a task error.
func (*ExperimentResult) Summary ¶
func (r *ExperimentResult) Summary() map[string]ScorerSummary
Summary is, per evaluator, the count, passed count and mean.
type FeedbackOptions ¶
type FeedbackOptions struct {
TraceID, SpanID string
Comment string
Name string // default user_feedback
ScoreID string
Timestamp string
}
FeedbackOptions are Feedback's options.
type ItemResult ¶
type ItemResult struct {
ItemID string
Input any
Expected any
Metadata any
Output any
TraceID string
Scores []Evaluation
Error string
EvaluatorErrors []string
}
ItemResult is one item's outcome.
func (ItemResult) Passed ¶
func (r ItemResult) Passed() bool
Passed: no error and every score passing.
type LLMOptions ¶
type LLMOptions struct {
Model string
Provider string
Operation string // default "chat"
// Prompt: a string goes to input.value, a list of message objects to
// gen_ai.input.messages (JSON), a *Prompt from GetPrompt stamps
// sbo.prompt.* and is not request content.
Prompt any
// System goes to gen_ai.system_instructions.
System any
Attributes []attribute.KeyValue
}
LLMOptions are the options of an LLM span.
type Options ¶
type Options struct {
// Endpoint is the local destination's OTLP traces URL
// (SUPERBASED_OTLP_ENDPOINT; under destination local also
// OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and OTEL_EXPORTER_OTLP_ENDPOINT +
// /v1/traces; else the machine's advertised receiver; else
// http://127.0.0.1:4318/v1/traces).
Endpoint string
// Tenant, User and SessionID identify every trace (SUPERBASED_TENANT,
// SUPERBASED_USER, SUPERBASED_SESSION_ID).
Tenant, User, SessionID string
// ServiceName (SUPERBASED_SERVICE_NAME, OTEL_SERVICE_NAME, service.name in
// OTEL_RESOURCE_ATTRIBUTES, else custom-app).
ServiceName string
// Headers are added to every OTLP export (over SUPERBASED_OTLP_HEADERS).
Headers map[string]string
// APIKey is the SDK credential (SUPERBASED_API_KEY, else the machine's
// credential file named by discovery). Sent only to the gateway.
APIKey string
// Console also prints every span to stderr (SUPERBASED_CONSOLE).
Console *bool
// CaptureContent records prompt, response and tool bodies
// (SUPERBASED_CAPTURE_CONTENT, default on).
CaptureContent *bool
// MaxContentChars clips each content body (SUPERBASED_MAX_CONTENT_CHARS,
// default 8000; 0 means no limit).
MaxContentChars *int
// ExportTimeout bounds one export request (SUPERBASED_EXPORT_TIMEOUT_MS,
// OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, OTEL_EXPORTER_OTLP_TIMEOUT; 5 s).
ExportTimeout time.Duration
// ShutdownTimeout bounds Flush and Shutdown (SUPERBASED_SHUTDOWN_TIMEOUT_MS; 2 s).
ShutdownTimeout time.Duration
// Quiet keeps exporter errors out of the OpenTelemetry error handler; they
// are counted in Diagnostics and summarised once a minute (SUPERBASED_QUIET,
// default on).
Quiet *bool
// Release, Environment, Tags and Metadata are process-wide trace identity
// (SUPERBASED_RELEASE, SUPERBASED_ENVIRONMENT, SUPERBASED_TAGS comma list,
// SUPERBASED_METADATA k=v,k2=v2).
Release, Environment string
Tags []string
Metadata map[string]any
// SampleRate is the head-sampling ratio in 0..1 (SUPERBASED_SAMPLE_RATE,
// else OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARG; default 1). A value
// outside 0..1 makes Init return an error.
SampleRate *float64
// ShouldExport drops a finished span when it returns false. A hook that
// panics keeps the span.
ShouldExport func(sdktrace.ReadOnlySpan) bool
// Mask rewrites each content attribute before export; return nil to drop
// it. A hook that returns an error or panics drops that attribute, never
// the span. A value that is not a string, bool, number or slice of those
// is stringified.
Mask func(value any, key string) (any, error)
// Destination is local, online or both (SUPERBASED_DESTINATION, else the
// machine's default over loopback, else local).
Destination string
// OrgURL is the organization's gateway base (SUPERBASED_ORG_URL, else the
// gateway_url line of the machine's credential file).
OrgURL string
// NodeURL is this machine's dashboard API (SUPERBASED_NODE_URL, default
// http://127.0.0.1:8081). Only a loopback address is asked.
NodeURL string
// Discover asks the machine for its default (SUPERBASED_DISCOVER, default on).
Discover *bool
// APITimeout bounds score, prompt, dataset, experiment and trace-cost calls
// (SUPERBASED_API_TIMEOUT_MS; 5 s). Discovery is fixed at 500 ms.
APITimeout time.Duration
// PromptCacheTTL is how long a fetched prompt is fresh
// (SUPERBASED_PROMPT_CACHE_TTL_MS; 60 s). A negative value means 0.
PromptCacheTTL time.Duration
// Exporter replaces the OTLP/HTTP exporter of every destination (tests, a
// custom transport). Exporters gives each destination ("local", "online")
// its own and wins over Exporter.
Exporter sdktrace.SpanExporter
Exporters map[string]sdktrace.SpanExporter
// TracerProvider is an SDK provider to attach to instead of the global one.
TracerProvider *sdktrace.TracerProvider
}
Options are Init's settings. A zero field is unset: the SUPERBASED_* environment variable, then the standard OTEL_* one where it exists, then the machine's default (only Destination) and the built-in default apply. Pointer fields are the ones whose zero value is a real choice (false, 0); use Bool, Int and Float to set them.
type Prompt ¶
type Prompt struct {
Name string
Version int
Type string // text or chat
Text string // the body of a text prompt
Messages []Message // the messages of a chat prompt
Config map[string]any
Labels []string
Label string // the label it was resolved by; "" for a version fetch
ResolvedBy string
Variables []string
Digest string
CommitMessage string
CreatedAt string
IsFallback bool
Source string // online, local or fallback
Rollout *PromptRollout
}
Prompt is one prompt version as the registry served it.
func GetPrompt ¶
GetPrompt fetches prompt name by label (production by default) or version from the registry of the destination chosen at Init (the gateway for online, the machine for local; both tries the gateway, then the machine). It is cached for CacheTTL; after that the cached copy is returned at once and revalidated in the background with If-None-Match. With nothing cached and a failed fetch, Fallback is returned; without one the error wraps ErrPromptNotFound or ErrPromptFetch. The span in ctx is stamped with the prompt's name and version.
func (*Prompt) Attributes ¶
Attributes are the span attributes this prompt stamps (none for a fallback).
func (*Prompt) Cohort ¶
Cohort is the rollout side that served this copy (candidate, base or unkeyed); "" when the label has no rollout.
func (*Prompt) Compile ¶
Compile fills every {{name}} placeholder and returns the text (a text prompt) or a new message list (a chat prompt; each content compiled, other fields untouched). Every missing name is in one *PromptCompileError; extra values are ignored. A value that is not a string renders as JSON.stringify renders it. The span in ctx is stamped with this prompt.
func (*Prompt) CompileMessages ¶
CompileMessages is Compile for a chat prompt.
func (*Prompt) CompileText ¶
CompileText is Compile for a text prompt.
type PromptCompileError ¶
type PromptCompileError struct{ Missing []string }
PromptCompileError is a Compile call missing values; Missing is sorted.
func (*PromptCompileError) Error ¶
func (e *PromptCompileError) Error() string
type PromptOptions ¶
type PromptOptions struct {
// Label (production, the default, or staging) or Version (a positive
// integer); not both.
Label string
Version int
// CacheTTL is how long a fetched prompt is fresh (default Init's
// PromptCacheTTL; negative means 0).
CacheTTL time.Duration
// Fallback (a string or []Message) is returned, unversioned and stamping
// nothing, when nothing is cached and the fetch fails.
Fallback any
// User and SessionID key a staged rollout (default: the trace's end user,
// else its session). Only their SHA-256 is sent.
User, SessionID string
}
PromptOptions are GetPrompt's options.
type PromptRollout ¶
type PromptRollout struct {
BaseVersion int `json:"base_version"`
CandidateVersion int `json:"candidate_version"`
Percent int `json:"percent"`
Cohort string `json:"cohort"` // candidate, base or unkeyed
Key string `json:"key"` // user, session or ""
Salt string `json:"salt"`
}
PromptRollout is a label's staged rollout as the server reported it (prompts.md v2 section 9.3).
type RequestParams ¶
type RequestParams struct {
MaxTokens *int
Temperature *float64
TopP *float64
TopK *float64
StopSequences []string
FrequencyPenalty *float64
PresencePenalty *float64
Seed *int
Stream *bool
ReasoningLevel string
}
RequestParams are the model request parameters (gen_ai.request.<name>).
type RetrieverOptions ¶
type RetrieverOptions struct {
Query any // content: gen_ai.retrieval.query.text
Attributes []attribute.KeyValue
}
RetrieverOptions are the options of a RETRIEVER span.
type ScoreError ¶
ScoreError is a score the rules refuse; Code is the contract's error code.
func (*ScoreError) Error ¶
func (e *ScoreError) Error() string
type ScoreOptions ¶
type ScoreOptions struct {
// TraceID defaults to the current trace; with neither TraceID nor SpanID
// the score is trace-level. Pass SpanID: CurrentSpanID(ctx) to score the span.
TraceID, SpanID string
Comment string
// Kind (numeric, boolean, categorical) is inferred from the value; a
// disagreeing Kind is refused.
Kind string
Scorer, ScorerVersion string
RunID string
// ScoreID is the idempotency id (sdk_<32 hex> by default).
ScoreID string
Timestamp string
}
ScoreOptions are Score's options.
type ScoreResult ¶
type ScoreResult struct {
OK bool `json:"ok"`
ID string `json:"id"` // the first sc_… id returned
ClientID string `json:"client_id"` // the idempotency id sent
Destinations map[string]DestinationResult `json:"destinations"`
Errors []string `json:"errors"`
}
ScoreResult is the outcome of one score write. OK is true only when every destination the call went to accepted it (no destination at all is not OK).
func Feedback ¶
func Feedback(ctx context.Context, value any, o FeedbackOptions) ScoreResult
Feedback records an end user's feedback (source feedback): thumbs as a bool, stars as a number, or a short label. Every call is its own row.
func Score ¶
func Score(ctx context.Context, name string, value any, o ScoreOptions) ScoreResult
Score records a score (source sdk) on a trace or span: value is a number (numeric), a bool (boolean) or a short string (categorical). It is written to the destination(s) chosen at Init and never fails: check ScoreResult.OK and Errors. A write that gets no answer, a 429 or a 5xx is retried once with the same id.
type ScorerSummary ¶
type ScorerSummary struct {
Count int
Passed int
Mean float64 // of the numeric and boolean values
}
ScorerSummary is one evaluator's totals.
type Settings ¶
type Settings struct {
Endpoint string
Headers map[string]string `json:"-"`
APIKey string `json:"-"`
ServiceName string
ResourceAttrs map[string]string
Tenant string
User string
SessionID string
CaptureContent bool
MaxContentChars int
ExportTimeout time.Duration
ShutdownTimeout time.Duration
Quiet bool
Console bool
Release string
Environment string
Tags []string
Metadata map[string]string
SampleRate float64
SampleParentBased bool
Destination string
OrgURL string
NodeURL string
Discover bool
APITimeout time.Duration
PromptCacheTTL time.Duration
}
Settings are the options Init resolved. String never shows the credential or the headers.
func CurrentSettings ¶
func CurrentSettings() *Settings
CurrentSettings are the settings the last Init resolved (nil before Init).
func Init ¶
Init configures tracing to export to superbased over OTLP/HTTP. It is idempotent: a second call with the same settings changes nothing; with different content, sampling or hook options it updates them in place; with different export targets it swaps the exporters (never a second processor).
When the app already registered an OpenTelemetry SDK TracerProvider (or passes Options.TracerProvider), the SDK adds its span processor to it, so the app's and the SDK's spans land in one trace. Otherwise it creates its own provider and, when nothing was registered, registers it globally.
Discovery (the machine's default destination) happens inside Init, bounded by 500 ms. Init returns an error only for a sample rate outside 0..1.
func (Settings) Format ¶
Format redacts the credential and the headers under every fmt verb (%v, %+v, %#v, %s), so a log line or an error message never carries them.
type SpanCost ¶
type SpanCost struct {
SpanID string `json:"span_id"`
Model string `json:"model"`
CostUSD *float64 `json:"cost_usd"`
CostSource string `json:"cost_source"`
ReportedUSD *float64 `json:"reported_usd"`
ComputedUSD *float64 `json:"computed_usd"`
ExactUSD *float64 `json:"exact_usd"`
CostDeltaUSD *float64 `json:"cost_delta_usd"`
GatewayRequestID *string `json:"gateway_request_id"`
}
SpanCost is one span's cost. A nil pointer is a value the server did not have.
type SpanOptions ¶
SpanOptions are the options of StartSpan and WithSpan.
type ToolOptions ¶
type ToolOptions struct {
ToolName string // default: the span name
CallID string
Arguments any // content; a non-string is JSON-encoded
Attributes []attribute.KeyValue
}
ToolOptions are the options of a TOOL span.
type TraceCost ¶
type TraceCost struct {
APIVersion string `json:"api_version,omitempty"` // org only
TraceID string `json:"trace_id"`
CostUSD *float64 `json:"cost_usd"`
CostProvenance CostProvenance `json:"cost_provenance"`
Spans []SpanCost `json:"spans"`
Destination string `json:"destination"`
// Raw is the answer as decoded, for fields this SDK does not know yet.
Raw map[string]any `json:"-"`
}
TraceCost is a trace's cost with the wire field names (contract cost-source.md section 6) plus Destination, the side that answered.
func GetTraceCost ¶
GetTraceCost returns the cost of traceID (default: the trace in ctx), or nil when no destination has it yet, there is no trace, or the read failed (logged at most once a minute). Destination online reads the org, local the machine, both the org and then the machine. A malformed traceID (not 32 hex, or all zero) is an error wrapping ErrInvalidArgument; nothing else is. Call Flush first: a span's cost exists once it was exported and ingested.
type Usage ¶
type Usage struct {
InputTokens, OutputTokens, TotalTokens *int
CacheReadTokens, CacheWriteTokens *int
ReasoningTokens *int
ResponseID, RequestID, ResponseModel string
FinishReasons []string
CostUSD *float64
Prompt, Response any
}
Usage is what SetUsage records. Token counts are pointers (Int(n)) because zero is a real count. InputTokens is GROSS: it includes cache reads and writes, which are subsets of it, never addends; OutputTokens includes ReasoningTokens; TotalTokens is optional (ingest derives input + output).
type Verdict ¶
type Verdict struct {
Allowed bool `json:"allowed"`
Decision string `json:"decision"`
Severity string `json:"severity"`
Criterion string `json:"criterion"`
Reason string `json:"reason"`
Mode string `json:"mode"`
JudgeUsed bool `json:"judge_used"`
Degraded string `json:"degraded"`
EnforceDecision string `json:"enforce_decision"`
LatencyMS int64 `json:"latency_ms"`
VerdictID string `json:"verdict_id"`
HTTPStatus int `json:"http_status"`
Error string `json:"error"`
}
Verdict is the result of an Admit check. Allowed is what the app should honour; Degraded is empty for a clean decision.
func Admit ¶
func Admit(ctx context.Context, message string, o AdmitOptions) (v Verdict)
Admit checks an incoming user message against the app's admission policy BEFORE running the agent and returns an allow/flag/ask/deny verdict. It never fails: with no decision it admits (or denies under FailClosed), counts the verdict in Diagnostics.AdmissionDegraded and warns once a minute per cause with the fix.
Address: Endpoint, else OrgURL + /v1/sdk/admit, else SUPERBASED_ADMISSION_ENDPOINT, else the destination plan of Init (the org gateway under a usable online or both, else this machine), else SUPERBASED_ORG_URL + /v1/sdk/admit, else the local machine. The credential rides only to an org address or a remote explicit endpoint; an explicit APIKey also goes to a loopback endpoint. Redirects are never followed. An org verdict with mode off is no decision: under destination both this machine is asked (without the key); otherwise the verdict is degraded admission-off.