Browse documentation

Reference

Go SDK API

Interfaces, functions, options, parameters, return values, and helpers for the Teml Go SDK.

This is the application-developer API for github.com/getteml/teml/sdks/go. The SDK is safe for concurrent use and follows Go/OpenTelemetry context conventions.

Use ingest:write for traces, metrics, logs, and errors. Add analytics:write for identity, groups, events, and flag exposures; add flags:read for decisions.

Construct and run a client

client, err := teml.New(
	 teml.WithAPIKey(os.Getenv("TEML_API_KEY")),
	 teml.WithServiceName("orders-api"),
)
if err != nil {
	return err
}
if err := client.Start(ctx); err != nil {
	return err
}
defer client.Stop(shutdownCtx)
API Parameters Returns Behavior
New(opts ...Option) functional options (Client, error) Creates an unstarted client or returns a configuration or transport-initialization error.
Start(ctx) lifecycle context error Validates config and starts enabled transports.
Stop(ctx) deadline/cancellation context error Flushes and releases client-owned providers.
IsRunning() bool Whether the client accepts telemetry.
Health() HealthStatus State, recent errors, uptime, and per-signal counters.
Stats() ClientStats Processed/dropped/export-failure counters and timestamps.

Keep one client per service. Pass request contexts through all instrumentation so trace and person correlation remain intact.

Core Client methods

Method Parameters Returns Behavior
Tracer() OTel trace.Tracer Underlying tracer for advanced instrumentation.
Meter() OTel metric.Meter Underlying meter for advanced instrumentation.
Logger() *slog.Logger Structured logger backed by the Teml log provider. Use context-aware methods for request work.
StartSpan(ctx, name, opts...) context; name; OTel options (context.Context, trace.Span) Starts a span and returns the child context. Caller must end the span.
RecordMetric(name, value, labels) name; float; string map Records one metric observation. It has no context parameter.
LogEvent(level, message, attrs...) slog.Level; message; attributes Convenience log using a background context. Use Logger().LogAttrs(ctx, ...) for correlation.
RecordLLMCall(ctx, opts) context; LLMCallOptions Records one completed model call as a gen_ai span.
RecordToolCall(ctx, name, opts) context; tool name/options Records one completed tool execution.
StartAgentRun(ctx, agent, opts) context; agent name/options (context.Context, trace.Span) Starts an agent span and returns its child context. Caller must end the span.
WrapHTTPClient(client) *http.Client *http.Client Returns a client that propagates trace and Teml identity context. Restrict its destinations.
WrapHTTPTransport(base) http.RoundTripper http.RoundTripper Wraps a transport for outbound propagation/instrumentation.
GRPCDialOptions() []grpc.DialOption Client interceptors/stats options for gRPC propagation.

LLMCallOptions.Model is required. Other fields are ResponseModel, Provider, Operation, token counts, CostUSD, FinishReason, IsError, StartTime, and EndTime. Messages and Output are opt-in content. ToolCallOptions provides Type, CallID, ConversationID, AgentName, IsError, and opt-in Arguments/Result. AgentRunOptions provides AgentID and ConversationID.

Package-level WrapHTTPClient, WrapHTTPTransport, GRPCDialOptions, and GRPCClientStatsHandler provide the same integration helpers when a Client reference is not available.

Errors, messages, users, and breadcrumbs

Method Parameters Returns Behavior
CaptureError(ctx, err, opts...) context; error; ErrorOptions string Captures an error and returns its generated ID; returns empty when capture is unavailable/sampled out.
CaptureMessage(ctx, message, level, opts...) context; text; ErrorLevel; options string Captures a diagnostic message.
AddBreadcrumb(category, message, opts...) category/message; breadcrumb options Buffers trail context for the next captured error.
SetUser(user) *User Sets process-global error user context.
GetUser(ctx) request context *User Returns context-local user first, then global user.
ClearUser() Clears global error user context.

User contains ID, Email, Username, IPAddress, Segment, and Data. Use ContextWithUser(ctx, user) for concurrent request-local error context.

Error option Purpose
WithLevel Override debug, info, warning, error, or fatal.
WithTag Add one indexed tag.
WithTags Add multiple indexed tags.
WithExtra(key, value) Add one unindexed context value.
WithErrorExtra(map) Add several unindexed context values in one option.
WithUser Override user for one capture.
WithFingerprint(parts...) Override grouping; comma separates components and {{default}} includes automatic grouping.
WithStackTrace(pcs) Supply program counters rather than capture the current stack.
WithErrorTimestamp(time) Supply the event timestamp.

WithBreadcrumbLevel(level) sets severity and WithBreadcrumbData(map) attaches structured breadcrumb context.

Identity and groups

API Parameters Returns Behavior
client.Identify(ctx, distinctID, props) context; stable ID; person properties error Sets shared identity and synchronously sends the identity event.
client.Group(ctx, groupType, groupKey, props) context; account type/key; properties error Records membership and $groupidentify.
client.Reset(ctx) context error Logout: rotates anonymous identity, clears groups, and clears global user context.
ContextWithDistinctID(ctx, id) context; stable ID context.Context Sets request-local identity for concurrency-safe server work.
DistinctIDFromContext(ctx) context (string, bool) Reads request-local identity.
AdoptDistinctIDFromBaggage(ctx) context context Promotes trusted inbound baggage into request scope.
DiscardDistinctIDFromBaggage(ctx) context context Removes untrusted Teml identity baggage while preserving other context.

Never adopt a public client’s identity baggage until a trusted gateway has authenticated the request and recreated that baggage.

Diagnostic events: Analytics

events := teml.NewAnalytics(teml.AnalyticsConfig{
	Endpoint: "https://api.teml.io",
	APIKey:   os.Getenv("TEML_API_KEY"),
})
defer events.Stop(ctx)

AnalyticsConfig fields are Endpoint, APIKey, FlushAt (default 20), Interval (zero means 5 seconds; negative disables the timer), and optional HTTPClient (default timeout 10 seconds).

API Parameters Returns Behavior
NewAnalytics(config) AnalyticsConfig *Analytics Starts a background flusher using a background lifecycle context.
NewAnalyticsWithContext(ctx, config) lifecycle context/config *Analytics Stops the background flusher when context is canceled; still call Stop to flush.
Capture(ctx, event, props, opts...) context; name; properties; capture options error Queues an event using shared identity unless overridden.
Identify(ctx, distinctID, props, opts...) context; ID; properties; options error Queues identity merge and switches shared identity.
Group(ctx, type, key, props, opts...) context; group; properties; options error Queues membership and switches shared group state.
Flush(ctx) deadline context error Sends queued events in chunks, requeuing retryable failures.
Reset(ctx) context error Rotates shared anonymous identity.
Stop(ctx) deadline context error Stops the flusher and sends the remaining queue. Capture after stop returns ErrAnalyticsClosed.

Per-call options are WithDistinctID, WithAnonDistinctID, and WithSessionID.

Feature flags: Flags

FlagsConfig fields are Endpoint, APIKey, optional HTTPClient, optional Bootstrap, and an optional Capture(ctx, event, props, distinctID) callback for exposures. The key needs flags:read; the exposure callback usually calls Analytics.Capture and therefore needs analytics:write.

Method Parameters Returns Behavior
NewFlags(config) FlagsConfig *Flags Builds a concurrency-safe in-memory decision client.
Reload(ctx, distinctID, personProperties, groups) targeting context error Calls /api/v1/decide; nil groups use shared memberships.
GetFeatureFlag(ctx, key, distinctID) context; key; ID any Returns bool/variant/nil and emits one deduplicated exposure.
IsFeatureEnabled(ctx, key, distinctID) context; key; ID bool True for true or a non-empty string variant.
GetFeatureFlagPayload(key) key json.RawMessage Returns a copy of the payload or nil.
GetAllFlags() map[string]any Returns a copy of cached decisions.
HadEvaluationErrors() bool Whether the last decision used a fallback.
Reset() Clears exposure dedup after identity changes.

Configuration options

Options apply in order. WithConfig(config) is normally first; later options override its fields.

Option family Functions and effect
Identity WithServiceName, WithServiceVersion, WithEnvironment, WithProjectID.
Authentication WithAPIKey selects API-key auth; WithJWTToken selects JWT auth. Application integrations should use a project API key.
Endpoint/transport WithEndpoint, WithProtocol("grpc"|"http"), WithInsecure, WithHeaders, WithHeader.
TLS WithTLS, WithTLSCerts(cert,key,ca), WithTLSCA, WithTLSServerName; WithInsecureTLS skips verification and is development-only.
Batching WithBatchTimeout, WithBatchSize, WithMaxQueueSize, WithExportTimeout, WithShutdownTimeout, WithRetryConfig.
Signals/sampling WithTraceSampleRate, WithTraces, WithMetrics, WithLogs, WithAllTelemetry.
Diagnostics WithDebug, WithLogLevel, WithLogOutput.
Resources WithResourceAttribute, WithResourceAttributes.
Errors WithErrorCapture, WithErrorSampleRate, WithMaxStackTraceFrames, WithAttachStackTrace, WithErrorEnvironment, WithErrorRelease.
Providers WithTracerProvider uses a caller-owned OTel provider and enables traces; the caller shuts it down after the Teml client.
Presets WithProductionDefaults, WithDevelopmentDefaults, WithTestingDefaults, WithKubernetesDefaults, WithDockerDefaults. Apply a preset before options that should override it.

Defaults include gRPC, a 10% trace sample rate, 100% captured errors, batch size 512, queue size 2048, 5-second batch/shutdown timeouts, 30-second exports, and three retry attempts. DefaultConfig() reads the equivalent TEML_* and OTEL_* environment variables; Config.Validate() checks required values and bounds.

Authentication and error helpers

ValidateAPIKey, IsAPIKeyFormat, and MaskAPIKey support configuration UIs. IsAuthError, IsNetworkError, IsRetryableError, GetErrorSuggestion, and WrapGRPCError support custom transports. Prefer returning these errors rather than matching their strings.

Advanced configuration and utility API

API Parameters Returns/behavior
DefaultConfig() *Config populated from supported TEML_*/OTEL_* variables and safe defaults.
config.Validate() error for missing credentials/identity or inconsistent protocol, sampling, queues, timeouts, and TLS.
config.GetEndpointForSignal(signal) traces, metrics, or logs Signal-specific OTLP endpoint.
config.GetHeadersForSignal(signal) signal name Copy of headers including active authentication.
config.Logger() SDK diagnostic *slog.Logger.
NewTransport(config) validated *Config (Transport, error) for custom lifecycle ownership; most applications should use Client.
TLSConfig.Validate() Rejects incomplete certificate pairs and unsafe/inconsistent TLS bounds.
TLSConfig.GetStandardTLSConfig() (*tls.Config, error) for HTTP transports.
TLSConfig.GetTLSCredentials() (credentials.TransportCredentials, error) for gRPC.
ContextWithUser(ctx, user) context; *User Request-local error user.
UserFromContext(ctx) context Request-local *User or nil.
user.ToOTelAttributes() OpenTelemetry enduser.* and user.data.* attributes.
CaptureStackTrace(skip) number of caller frames to skip Structured []StackFrame for a custom error integration.
GetPoolStats() / ResetPoolStats() SDK allocation-pool counters, and a test/debug reset.

Config exposes the same fields represented by the functional options: service identity, credentials, endpoint/protocol/headers/TLS, batch and retry values, signal switches, sampling, logging, resources, and error settings. TLSConfig additionally accepts Enabled, InsecureSkipVerify, certificate/key/CA files, ServerName, TLS version bounds, and cipher suites. The package’s typed sentinel errors (ErrUnauthorized, ErrForbidden, ErrInvalidAPIKey, ErrExpiredToken, ErrRateLimited, ErrInvalidCredentials, ErrConnectionFailed, ErrTimeout, and ErrServiceUnavailable) are compatible with errors.Is.

Framework and model-provider packages

Package/API Parameters Returns Behavior
instrumentation/openai.WrapClient(temlClient, client, opts...) Teml client; official OpenAI client; options instrumented client Wraps non-streaming Chat.Completions.New calls and preserves provider results/errors.
instrumentation/openai.WithCaptureContent() wrapper option Opts into prompt/completion content; off by default.
instrumentation/anthropic.WrapClient(temlClient, client, opts...) Teml client; official Anthropic client; options instrumented client Wraps non-streaming Messages.New calls and preserves provider results/errors.
instrumentation/anthropic.WithCaptureContent() wrapper option Opts into prompt/completion content; off by default.
instrumentation/gin.Middleware(client) / MiddlewareWithOptions(client, opts) Teml client; optional Options Gin handler Creates inbound request spans and request-scoped propagation.
instrumentation/echo.Middleware(client) / MiddlewareWithOptions(client, opts) Teml client; optional Options Echo middleware Creates inbound request spans and request-scoped propagation. DefaultSkipper is the exported standard skip predicate.
instrumentation/fiber.Middleware(client) / MiddlewareWithOptions(client, opts) Teml client; optional Options Fiber handler Creates inbound request spans and request-scoped propagation. DefaultNext skips standard health paths; GetSpan(ctx) reads the active request span.
instrumentation/grpc.UnaryServerInterceptor(client) / UnaryServerInterceptorWithOptions(client, opts) client; optional ServerOptions unary server interceptor Extracts trace context, creates the server span, and optionally adopts trusted identity.
instrumentation/grpc.StreamServerInterceptor(client) / StreamServerInterceptorWithOptions(client, opts) client; optional ServerOptions stream server interceptor Instruments stream lifetime and propagation.
instrumentation/grpc.UnaryClientInterceptor(client) / StreamClientInterceptor(client) client client interceptor Injects outbound context and traces RPCs.
instrumentation/grpc.CombinedServerInterceptors(client) client []grpc.ServerOption Installs both server interceptors.
instrumentation/grpc.CombinedClientInterceptors(client) client []grpc.DialOption Installs both client interceptors.

Streaming OpenAI/Anthropic methods are not wrapped. Content capture can record sensitive text.

Gin Options supports TrustIncomingIdentity, SkipPaths, request/response body capture, MaxBodySize, custom attributes, span naming, filtering, captured-header allowlists, and sensitive header redaction. Echo provides the same controls through Skipper (rather than SkipPaths and a filter). Fiber supports Next, custom attributes, span naming, and header controls. Every HTTP package exports WithSkipHealthCheck() and WithCaptureAllHeaders() presets. Body or header capture can collect secrets; keep it disabled unless a reviewed debugging need requires it. gRPC ServerOptions contains TrustIncomingIdentity and an explicit CaptureMetadata allowlist.