Documentation
¶
Overview ¶
Package telemetry is Tacklr's OpenTelemetry instrumentation: spans, metrics and log events on the process-wide OpenTelemetry providers, and the Carrier that takes a turn's trace across what a context cannot (a wake, a durable step, a journal, an HTTP request). A turn is one trace from the client's request to the answer (docs/telemetry.md). It depends only on the OpenTelemetry API, so it builds anywhere the harness does. Package telemetry/export installs the SDK providers and exporters (OTLP, Prometheus) a host process sends them to.
Span starters, Instruments.Record*, attribute constants, and EmitEvent are for the harness and the session package. Hosts must not start tacklr spans or record harness metrics; that can break traces and double-count metrics.
Index ¶
- Constants
- func AgentFromContext(ctx context.Context) string
- func ClassifyErrorClass(err error, httpStatus int) string
- func ContextWithAfterTools(ctx context.Context) context.Context
- func ContextWithAgent(ctx context.Context, agent string) context.Context
- func ContextWithModelIdentity(ctx context.Context, id ModelIdentity) context.Context
- func ContextWithSessionID(ctx context.Context, sessionID string) context.Context
- func EmitEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)
- func EmitEventSeverity(ctx context.Context, name string, severity log.Severity, ...)
- func FromHeaders(ctx context.Context, h http.Header) context.Context
- func Logger() log.Logger
- func Meter() metric.Meter
- func PlanInstalled(ctx context.Context, todos, open int, err error)
- func RecordCheckpointAttempt(ctx context.Context, err error)
- func SessionIDFromContext(ctx context.Context) string
- func SetMeterProvider(mp metric.MeterProvider)
- func SetTracerProvider(tp trace.TracerProvider)
- func Step(ctx context.Context, turn Carrier, agent, sessionID string) context.Context
- func Tracer() trace.Tracer
- func Transport(base http.RoundTripper) http.RoundTripper
- func TurnStarted(ctx context.Context, promptLen, resumes int)
- type Carrier
- type HandoffSpan
- type Instruments
- func (i *Instruments) RecordCheckpointSave(ctx context.Context, outcome string)
- func (i *Instruments) RecordCompress(ctx context.Context, agent string)
- func (i *Instruments) RecordConnection(ctx context.Context, protocol string, delta int64)
- func (i *Instruments) RecordFuseMount(ctx context.Context, outcome string)
- func (i *Instruments) RecordInterrupt(ctx context.Context, agent, kind string)
- func (i *Instruments) RecordSessionCreated(ctx context.Context)
- type ModelIdentity
- type ModelSpan
- type ProviderStatus
- type RPCSpan
- type TokenUsage
- type Tool
- type ToolSpan
- type Turn
- type TurnSpan
- type WindowShape
Constants ¶
const ( OperationInvokeAgent = "invoke_agent" OperationChat = "chat" OperationExecuteTool = "execute_tool" )
GenAI operation names (gen_ai.operation.name), which name their spans.
const ( AttrGenAIOperationName = "gen_ai.operation.name" AttrGenAIProviderName = "gen_ai.provider.name" AttrGenAIRequestModel = "gen_ai.request.model" AttrGenAIAgentName = "gen_ai.agent.name" AttrGenAIConversationID = "gen_ai.conversation.id" AttrGenAIToolName = "gen_ai.tool.name" AttrGenAIToolCallID = "gen_ai.tool.call.id" AttrGenAIToolType = "gen_ai.tool.type" AttrGenAITokenType = "gen_ai.token.type" AttrGenAIInputTokens = "gen_ai.usage.input_tokens" AttrGenAIOutputTokens = "gen_ai.usage.output_tokens" AttrGenAICachedTokens = "gen_ai.usage.cached_tokens" AttrGenAICacheWriteTokens = "gen_ai.usage.cache_write_tokens" AttrErrorType = "error.type" AttrHTTPStatus = "http.response.status_code" AttrRPCSystem = "rpc.system" AttrRPCMethod = "rpc.method" AttrJSONRPCError = "rpc.jsonrpc.error_code" )
Attribute keys of the OpenTelemetry semantic conventions. https://opentelemetry.io/docs/specs/semconv/gen-ai/ and .../rpc/
const ( AttrTurnKind = "tacklr.turn.kind" // prompt | resume | continue AttrRuntime = "tacklr.runtime" // temporal | durableobject AttrParentSession = "tacklr.session.parent" AttrToolNS = "tacklr.tool.namespace" AttrModelPhase = "tacklr.model.phase" // turn | handoff | compress AttrInterruptKind = "tacklr.interrupt.kind" AttrOutcome = "tacklr.outcome" AttrErrorCode = "tacklr.error.code" // the provider's error code AttrStopReason = "tacklr.stop_reason" )
Tacklr's own attribute keys (static identifiers and closed enums).
const ( RuntimeTemporal = "temporal" RuntimeDurableObject = "durableobject" )
Runtime values for AttrRuntime (closed enum).
const ( ModelPhaseTurn = "turn" ModelPhaseHandoff = "handoff" ModelPhaseCompress = "compress" )
Model phase values for AttrModelPhase (closed enum).
const ( GenAIProviderAnthropic = "anthropic" GenAIProviderAzure = "azure.openai" GenAIProviderOpenAI = "openai" GenAIProviderUnknown = "unknown" )
GenAI provider values (closed enum).
const ( ToolTypeFunction = "function" ToolTypeExtension = "extension" )
GenAI tool types (gen_ai.tool.type): a host's function, or a tool an MCP server provides.
const ( ErrorClassOK = "ok" ErrorClassProvider4xx = "provider_4xx" ErrorClassProvider5xx = "provider_5xx" ErrorClassMaxTokens = "max_tokens" ErrorClassCancelled = "cancelled" ErrorClassTimeout = "timeout" ErrorClassOther = "other" )
Error class buckets for error.type (closed enum).
const ( HandoffOutcomeOK = "ok" HandoffOutcomeFallback = "fallback" HandoffOutcomeError = "error" )
Handoff outcome values.
const ( EventModelRequest = "gen_ai.request" EventProviderFailed = "provider.failed" EventToolFailed = "tool.failed" EventPlanInstalled = "plan.installed" EventTurnStarted = "turn.started" EventTurnEnded = "turn.ended" EventFuseMount = "vfs.fuse.mount" EventFuseUnmount = "vfs.fuse.unmount" )
Log event names (OTel Logs Record.SetEventName): what happened within an operation, with its dynamic values as attributes.
const ( EventAttrOutcome = "outcome" EventAttrInputItems = "input_items" EventAttrMessages = "context.messages" EventAttrToolPairs = "context.tool_pairs" EventAttrAfterTools = "after_tools" EventAttrSeq = "seq" EventAttrPromptLength = "prompt.length" EventAttrResumes = "resumes" EventAttrTodos = "todos" EventAttrOpenTodos = "todos.open" EventAttrError = "error" )
Attribute keys on log events (dynamic values).
const ( AreaRuntime = "runtime" AreaHarness = "harness" AreaModelTasks = "model_tasks" AreaContext = "context" )
Area values for the "area" field of Tacklr's slog records: which part of Tacklr logged it.
const ( OutcomeOK = "ok" OutcomeError = "error" OutcomeCancelled = "cancelled" OutcomeYield = "yield" )
Outcome values for AttrOutcome / EventAttrOutcome.
const ( MetricTurnDuration = "tacklr.turn.duration" MetricTurnTotal = "tacklr.turn.total" MetricTurnActive = "tacklr.turn.active" MetricToolCalls = "tacklr.tool.calls" MetricToolDuration = "tacklr.tool.duration" MetricInterruptTotal = "tacklr.interrupt.total" MetricHandoffTotal = "tacklr.context.handoff.total" MetricCompressTotal = "tacklr.context.compress.total" MetricSessionCreated = "tacklr.session.created.total" MetricCheckpointSave = "tacklr.checkpoint.save.total" MetricFuseMount = "tacklr.fuse.mount.total" MetricConnections = "tacklr.server.connections" MetricModelDuration = "gen_ai.client.operation.duration" MetricTokenUsage = "gen_ai.client.token.usage" MetricRPCCallDuration = "rpc.server.call.duration" )
Metric names. The model's and the protocol server's are the semantic conventions' (gen_ai.client.*, rpc.server.*); the rest are Tacklr's. Prometheus export writes '.' as '_'.
const ( LabelAgent = AttrGenAIAgentName LabelTurnKind = AttrTurnKind LabelOutcome = "outcome" LabelTool = AttrGenAIToolName LabelToolNS = AttrToolNS LabelStatus = "status" LabelKind = "kind" // interrupt kind LabelModelPhase = AttrModelPhase LabelErrorType = AttrErrorType LabelProtocol = "protocol" )
Label keys: closed enums and configuration ids only, never free text or a session id.
const ( FuseMountOutcomeOK = "ok" FuseMountOutcomeError = "error" )
Fuse mount outcomes for RecordFuseMount (closed enum).
const InstrumentationName = "github.com/ryanaldo34/tacklr"
InstrumentationName is the OpenTelemetry instrumentation scope for Tacklr.
const RPCSystemJSONRPC = "jsonrpc"
RPC system of a protocol (rpc.system).
const (
SpanHandoff = "tacklr.context.handoff"
)
Span names. A turn is one trace, from the client's request to the answer, across every process and runtime it touches:
session/prompt SERVER the protocol request (rpc.*)
invoke_agent {agent} INTERNAL the turn (gen_ai.* invoke_agent)
chat {model} CLIENT one model request (gen_ai.* chat)
execute_tool {tool} INTERNAL one tool call (gen_ai.* execute_tool)
tacklr.context.handoff INTERNAL a plan handoff, with its model request
invoke_agent {specialist} INTERNAL a child session's turn
session/request_permission CLIENT a question the agent asks the client
The span names of the turn, the model request and the tool call are the OpenTelemetry GenAI semantic conventions'; the protocol request's are the RPC conventions' (rpc.system jsonrpc). Each name is the operation and its static target, so names stay few.
Attributes on spans are static and searchable: identifiers, closed enums, and the outcome and error.type set at the end. Values that change within an operation or are free text (lengths, counts, error messages, answers) go on span-correlated logs (EmitEvent, slog with the context), never on spans. Metric labels are closed enums and configuration ids only: never a session id.
Variables ¶
This section is empty.
Functions ¶
func AgentFromContext ¶ added in v0.5.0
AgentFromContext is the agent's name, or "".
func ClassifyErrorClass ¶ added in v0.2.0
ClassifyErrorClass buckets err into a closed error.class enum.
func ContextWithAfterTools ¶
ContextWithAfterTools marks the next model request as the one after a reply's tool calls.
func ContextWithAgent ¶ added in v0.5.0
ContextWithAgent attaches the agent's name.
func ContextWithModelIdentity ¶
func ContextWithModelIdentity(ctx context.Context, id ModelIdentity) context.Context
ContextWithModelIdentity attaches the model's identity for its spans.
func ContextWithSessionID ¶ added in v0.2.0
ContextWithSessionID attaches the session id (gen_ai.conversation.id).
func EmitEvent ¶
EmitEvent emits an OTel log record with EventName set (span-correlated). Severity defaults to Info; use EmitEventSeverity for errors.
func EmitEventSeverity ¶
func EmitEventSeverity(ctx context.Context, name string, severity log.Severity, attrs ...attribute.KeyValue)
EmitEventSeverity is EmitEvent with an explicit severity.
func FromHeaders ¶ added in v0.5.0
FromHeaders is ctx with the trace context of an incoming request's headers, for a server that continues the trace of its caller.
func PlanInstalled ¶ added in v0.5.0
PlanInstalled logs the install of a plan document into the window, with how many todos it has and how many are open.
func RecordCheckpointAttempt ¶ added in v0.2.0
RecordCheckpointAttempt records one harness snapshot persist (ok or error).
func SessionIDFromContext ¶ added in v0.2.0
SessionIDFromContext returns the session id or "".
func SetMeterProvider ¶
func SetMeterProvider(mp metric.MeterProvider)
SetMeterProvider installs mp as the process-wide MeterProvider and rebuilds the cached global Instruments so later Init/SetMeterProvider calls take effect. Hosts usually get this from export.Init (package telemetry/export). Pass nil for noop.
func SetTracerProvider ¶
func SetTracerProvider(tp trace.TracerProvider)
SetTracerProvider installs tp as the process-wide TracerProvider.
func Step ¶ added in v0.5.0
Step is the context one step of a turn runs in: the turn's span (from turn, the context its runtime recorded), the session and its agent, so the step's spans are children of the turn's span and carry the session.
func Transport ¶ added in v0.5.0
func Transport(base http.RoundTripper) http.RoundTripper
Transport sends each request with its context's trace context in its headers (W3C traceparent), so the system it reaches (a model provider or a gateway before one, an MCP server) continues the trace. It starts no span: the operation's own span (chat, execute_tool) is the client span. A nil base is http.DefaultTransport.
func TurnStarted ¶ added in v0.5.0
TurnStarted logs a turn's start with its dynamic values: the prompt's length and how many answers it resumed with.
Types ¶
type Carrier ¶ added in v0.5.0
Carrier is a trace context (W3C traceparent, tracestate and baggage) as plain data: how a turn's trace crosses what a context cannot, such as a wake to a session, a step of a durable runtime, a journal, or a message between objects. It is nil when there is no trace.
func Inject ¶ added in v0.5.0
Inject is ctx's trace context as a Carrier, by the process-wide propagator (export.Init installs W3C trace context and baggage). It is nil when ctx has no span.
type HandoffSpan ¶
type HandoffSpan struct {
// contains filtered or unexported fields
}
HandoffSpan is an in-flight tacklr.context.handoff span. Call End once.
func StartHandoffSpan ¶
StartHandoffSpan starts a context-handoff span: the model request that writes the handoff is its child. openTodos goes on its log.
func (*HandoffSpan) End ¶
func (s *HandoffSpan) End(outcome string, err error)
End ends the handoff span and records the handoff metric. outcome is HandoffOutcomeOK, HandoffOutcomeFallback, or HandoffOutcomeError.
type Instruments ¶
type Instruments struct {
// contains filtered or unexported fields
}
Instruments holds cached metric instruments for one Meter.
func Metrics ¶ added in v0.5.0
func Metrics() *Instruments
Metrics is Tacklr's metric instruments on the process-wide MeterProvider (SetMeterProvider rebuilds them).
func MustInstruments ¶
func MustInstruments(m metric.Meter) *Instruments
MustInstruments builds instruments from m. Names are constants; the SDK only errors on invalid names, which would be a compile-time programmer error.
func (*Instruments) RecordCheckpointSave ¶
func (i *Instruments) RecordCheckpointSave(ctx context.Context, outcome string)
RecordCheckpointSave counts a checkpoint save by outcome.
func (*Instruments) RecordCompress ¶
func (i *Instruments) RecordCompress(ctx context.Context, agent string)
RecordCompress counts a collapse of the context window.
func (*Instruments) RecordConnection ¶ added in v0.5.0
func (i *Instruments) RecordConnection(ctx context.Context, protocol string, delta int64)
RecordConnection adds delta (1 or -1) to the open connections of protocol.
func (*Instruments) RecordFuseMount ¶ added in v0.2.0
func (i *Instruments) RecordFuseMount(ctx context.Context, outcome string)
RecordFuseMount increments tacklr.fuse.mount.total{outcome=...}.
func (*Instruments) RecordInterrupt ¶
func (i *Instruments) RecordInterrupt(ctx context.Context, agent, kind string)
RecordInterrupt counts a park of a tool call on an interrupt of kind.
func (*Instruments) RecordSessionCreated ¶
func (i *Instruments) RecordSessionCreated(ctx context.Context)
RecordSessionCreated counts a session a protocol server created.
type ModelIdentity ¶
type ModelIdentity struct {
// Provider is a closed enum: anthropic | azure.openai | openai | unknown.
Provider string
// Model is the deployment or model id (configuration, low cardinality).
Model string
}
ModelIdentity is the static identity of a model's requests.
func NewModelIdentity ¶
func NewModelIdentity(model, baseURL string) ModelIdentity
NewModelIdentity builds GenAI identity from deployment config (model id + API base URL).
type ModelSpan ¶
type ModelSpan struct {
// contains filtered or unexported fields
}
ModelSpan is an in-flight chat span. Call End once.
func StartModelSpan ¶
func StartModelSpan(ctx context.Context, phase string, seq int, shape WindowShape) (context.Context, *ModelSpan)
StartModelSpan starts the chat span of one model request (the GenAI semantic conventions' client span, chat {model}), and logs the request's dynamic shape: its sequence in the session, the window it sends, and whether it follows a reply's tool calls.
func (*ModelSpan) End ¶
func (m *ModelSpan) End(err error, usage TokenUsage)
End ends the chat span with its outcome and, on failure, error.type (a closed class), the provider's HTTP status and error code; it records the provider-reported usage on the span and in the GenAI metrics.
type ProviderStatus ¶ added in v0.5.0
ProviderStatus is HTTP metadata a provider error may carry. A model span reads it with errors.As when the request fails.
type RPCSpan ¶ added in v0.5.0
type RPCSpan struct {
// contains filtered or unexported fields
}
RPCSpan is a protocol request's span (the RPC semantic conventions, rpc.system jsonrpc): a request the server answers (SERVER), or one it sends the client (CLIENT), such as a permission it asks. End it once, when the response is sent or received.
func StartRPC ¶ added in v0.5.0
func StartRPC(ctx context.Context, kind trace.SpanKind, method, session string, extra ...attribute.KeyValue) (context.Context, *RPCSpan)
StartRPC starts the span of a protocol request named by its method. A server request's parent is the client's trace context in ctx (its _meta.traceparent, or the connection's); session is the request's session (gen_ai.conversation.id), when it names one.
type TokenUsage ¶
TokenUsage is provider-reported token consumption for one model invoke.
type Tool ¶ added in v0.5.0
type Tool struct {
Name string
Namespace string
// CallID is the model's id of the call (gen_ai.tool.call.id), to find
// the span of one call.
CallID string
// Type is ToolTypeFunction for a host's tool, ToolTypeExtension for an
// MCP server's.
Type string
}
Tool is the static identity of one tool call's span.
type ToolSpan ¶
type ToolSpan struct {
// contains filtered or unexported fields
}
ToolSpan is an in-flight execute_tool span. Call Finish once.
func StartToolSpan ¶
StartToolSpan starts the execute_tool span of one tool call.
type Turn ¶ added in v0.5.0
type Turn struct {
Agent string
Session string
// Parent is the parent session of a child session.
Parent string
// Kind is prompt, resume or continue (a turn a runtime restarted).
Kind string
Runtime string
}
Turn is the static identity of one turn's span: invoke_agent of the session's agent (a specialist's name for a specialist session).
type TurnSpan ¶
type TurnSpan struct {
// contains filtered or unexported fields
}
TurnSpan is a turn's running invoke_agent span. End it once.
func StartTurn ¶ added in v0.5.0
StartTurn starts a turn's span as a child of the span in ctx (the client's request, or the parent session's turn), with a link to each span of links (the request that resumed it), and counts it as running. A durable runtime starts it once for each turn it runs, and records the span's context (Inject) so a replay of the turn reuses it without starting another.
type WindowShape ¶
WindowShape is a snapshot of the context window a model request sends. It changes with each request, so its model.request log carries it.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package export installs the OpenTelemetry SDK providers a Tacklr host process sends its telemetry to: OTLP traces, metrics and logs (Init), or a Prometheus scrape (PrometheusMeterProvider).
|
Package export installs the OpenTelemetry SDK providers a Tacklr host process sends its telemetry to: OTLP traces, metrics and logs (Init), or a Prometheus scrape (PrometheusMeterProvider). |
|
Package otlpjson sends spans to an OTLP/HTTP endpoint in OTLP's JSON encoding (POST {endpoint}/v1/traces, application/json), over net/http alone.
|
Package otlpjson sends spans to an OTLP/HTTP endpoint in OTLP's JSON encoding (POST {endpoint}/v1/traces, application/json), over net/http alone. |