telemetry

package
v0.7.28 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 22 Imported by: 1 module, 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.

Documentation

Overview

Package telemetry reports model calls made directly to a provider to an OTLP/HTTP endpoint, relay's receiver or any other backend, in the OpenTelemetry GenAI semantic conventions.

One Call becomes one CLIENT span carrying the request, response and token usage, and, only when message content is sent, one gen_ai.client.inference.operation.details log record with the same trace id and span id that carries the same attributes plus the content. Requests are OTLP/HTTP JSON, gzip-compressed, written by hand so the package depends on nothing beyond the standard library and the SDK's canonical types.

Recording never blocks and never fails a model call: calls wait in a bounded queue, a full queue drops and counts, and one goroutine exports them in batches with bounded retries. Whether content is sent follows the receiving relay's answer in the X-WR-Content-Capture response header when it gives one, the client's opt-in otherwise.

Out of scope: metrics, the per-message events of earlier conventions, OTLP over protobuf or gRPC, and instrumenting third-party HTTP clients.

Index

Constants

View Source
const (
	ContentStore  = "store"
	ContentDrop   = "drop"
	ContentClient = "client"
)

The values of HeaderContentCapture.

View Source
const (
	OperationChat       = "chat"
	OperationEmbeddings = "embeddings"
)

Operation names a model call kind in the conventions' gen_ai.operation.name.

View Source
const (
	ErrorTimeout     = "timeout"
	ErrorCanceled    = "client_canceled"
	ErrorUnreachable = "upstream_unreachable"
	// ErrorOther is the conventions' value for an error with no more specific type.
	ErrorOther = "_OTHER"
)

Error types for a call that failed without an HTTP error status. They are the words relay's receiver classifies, and stable across SDK releases.

View Source
const (
	EnvOTLPEndpoint   = "OTEL_EXPORTER_OTLP_ENDPOINT"
	EnvOTLPHeaders    = "OTEL_EXPORTER_OTLP_HEADERS"
	EnvServiceName    = "OTEL_SERVICE_NAME"
	EnvCaptureContent = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
)

Standard OpenTelemetry environment variables, read first so the emitter works against any OTLP backend.

View Source
const (
	EnvRelayBaseURL = "WR_BASE_URL"
	EnvRelayAPIKey  = "WR_API_KEY"
)

Relay's environment variables, the fallback when no OTLP endpoint is set: the receiver is at WR_BASE_URL + "/otlp" and takes the relay key.

View Source
const (
	DefaultQueueSize     = 2048
	DefaultBatchSize     = 512
	DefaultBatchInterval = 5 * time.Second
)

Defaults of the OpenTelemetry batch span processor.

View Source
const FinishError = "error"

FinishError is the finish reason the conventions ask for when a response ended before its final event.

View Source
const HeaderContentCapture = "X-WR-Content-Capture"

HeaderContentCapture is the response header in which relay's receiver says whether it stores the content of this credential's calls: "store" (a governing policy stores it), "drop" (a policy or an operator switch does not), "client" (no policy governs; the client's opt-in decides). Mirrors relay's httpheader.HeaderContentCapture; this module imports nothing of the server.

Variables

This section is empty.

Functions

func ContextWithConversation

func ContextWithConversation(ctx context.Context, id string) context.Context

ContextWithConversation returns ctx carrying a conversation (session, thread) id, reported as gen_ai.conversation.id.

func ContextWithTraceparent

func ContextWithTraceparent(ctx context.Context, traceparent string) context.Context

ContextWithTraceparent returns ctx carrying a W3C traceparent header value. A call made with it joins that trace, its span a child of the traceparent's span. A malformed value is ignored when the call is recorded.

func ConversationFromContext

func ConversationFromContext(ctx context.Context) string

ConversationFromContext returns the id ContextWithConversation stored, or "".

func TraceparentFromContext

func TraceparentFromContext(ctx context.Context) string

TraceparentFromContext returns the traceparent ContextWithTraceparent stored, or "".

Types

type Call

type Call struct {
	// Operation is OperationChat or OperationEmbeddings; empty means chat.
	Operation string
	// Provider is the provider name, a catalog provider slug where one is known.
	Provider string
	// Host is the catalog host slug the call was resolved to, so relay prices it at that host.
	Host string
	// ServerAddress is the host name the call was sent to.
	ServerAddress string

	RequestModel  string
	ResponseModel string
	ResponseID    string
	FinishReasons []string
	Stream        bool
	// TimeToFirstChunk is measured from Start; streams only.
	TimeToFirstChunk time.Duration

	Start time.Time
	End   time.Time

	// StatusCode is the provider's HTTP status, 0 when no response arrived.
	StatusCode int
	// ErrorType is set when the call failed: the HTTP error status as text, or one of the Error constants.
	ErrorType string

	// Usage is the canonical token map the SDK's translators produce.
	Usage usage.Tokens

	// Parent is a W3C traceparent the call's span joins; see ContextWithTraceparent.
	Parent         string
	ConversationID string

	// Content is the call's message content, nil when none is sent.
	Content *Content
}

Call is one model call as it is reported. Fields left zero are not reported.

type Content

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

Content is a call's message content, already in the conventions' shapes. Build it on the goroutine that owns the request and the response: everything is copied, so both may be reused afterwards.

func NewContent

func NewContent(req *v1.Request) *Content

NewContent returns the input side of a call made with req: its instructions, input messages and tool definitions.

func (*Content) SetOutput

func (c *Content) SetOutput(output []v1.Item, finish v1.FinishReason)

SetOutput adds the model's output items, which ended with finish, as the output messages.

type Emitter

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

Emitter exports recorded calls in the background. Build it once per process with New and share it; call Close before the process exits so queued calls are sent.

func New

func New(opts ...Option) *Emitter

New returns an Emitter configured by opts, then by the environment (see the Env constants). Missing or malformed configuration does not panic: Err reports it, Record drops, and Flush returns it.

func (*Emitter) Close

func (e *Emitter) Close(ctx context.Context) error

Close exports what is queued, then stops the Emitter; later calls are dropped. It returns when the queue is sent, with the first export error, or when ctx ends: then the export in flight is abandoned, what is still queued is dropped and counted, and the export goroutine exits all the same.

func (*Emitter) Dropped

func (e *Emitter) Dropped() uint64

Dropped reports how many reports were lost: calls refused by a full queue, a closed or misconfigured Emitter, and spans or content events whose export failed.

func (*Emitter) Err

func (e *Emitter) Err() error

Err reports the configuration error the Emitter was built with, nil when it exports.

func (*Emitter) Flush

func (e *Emitter) Flush(ctx context.Context) error

Flush exports every call recorded so far and returns the first export error, or the configuration error.

func (*Emitter) LastWarning

func (e *Emitter) LastWarning() string

LastWarning returns the last message an export response carried in its partial success, "" when none did. Relay uses it, for example, to say content was not stored.

func (*Emitter) Record

func (e *Emitter) Record(c Call)

Record queues one call for export. It never blocks: when the queue is full, or the Emitter is closed or misconfigured, the call is dropped and counted in Dropped. Record copies what it needs from c before it returns.

func (*Emitter) SendsContent

func (e *Emitter) SendsContent() bool

SendsContent reports whether the content of a call recorded now would be sent, so a caller builds Content only then. Relay's last answer decides: "store" sends even without the client's opt-in, "drop" never sends. An answer older than the cache window still decides while a fresh one is learned. Otherwise (never learned, "client", or a server that does not answer) the opt-in (WithContent or the environment) decides.

type Option

type Option func(*config)

Option configures an Emitter. Explicit options win over the environment.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sends key as "Authorization: Bearer <key>", the relay key for relay's receiver.

func WithBatch

func WithBatch(size int, interval time.Duration) Option

WithBatch sets the most calls one export carries and how long a call may wait for its batch to fill.

func WithContent

func WithContent(on bool) Option

WithContent sets the client's opt-in to sending message content. Relay may override it either way; see Emitter.SendsContent.

func WithEndpoint

func WithEndpoint(url string) Option

WithEndpoint sets the OTLP/HTTP base URL; "/v1/traces" and "/v1/logs" are appended. For relay it is the inference URL plus "/otlp".

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient sets the client exports are sent with.

func WithHeader

func WithHeader(k, v string) Option

WithHeader sets one header sent on every export.

func WithQueueSize

func WithQueueSize(n int) Option

WithQueueSize sets how many recorded calls may wait for export before new ones are dropped.

func WithServiceName

func WithServiceName(name string) Option

WithServiceName sets the service.name resource attribute.

Jump to

Keyboard shortcuts

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