llmobs

package
v2.12.0-dev.3 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: Apache-2.0, BSD-3-Clause, Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultParentID is the parent ID used for root spans.
	DefaultParentID = "undefined"
)
View Source
const (
	// SizeLimitEVPEvent is the EVP event size limit.
	SizeLimitEVPEvent = 5_000_000
)
View Source
const (
	// TagKeySessionID is the tag key used to set the session ID for LLMObs spans.
	TagKeySessionID = "session_id"
)

Variables

This section is empty.

Functions

func AgentNameWireSafe

func AgentNameWireSafe(name string) bool

AgentNameWireSafe reports whether name can safely be written as a propagating-tag value.

  • reject any byte outside the printable ASCII range [0x20, 0x7E]
  • reject comma (x-datadog-tags entry delimiter)
  • reject semicolon and tilde (W3C tracestate characters that composeTracestate sanitizes to "_", which would corrupt the attribution name seen by the downstream service)

Note: dd-trace-js does not reject semicolons or tildes — it relies on the x-datadog-tags encoder alone. Go applies the stricter rule because names may also travel via W3C tracestate.

The length check is delegated to callers.

func ApplySpanEventDefaults

func ApplySpanEventDefaults(event *transport.LLMObsSpanEvent)

func BuildExportSpan

func BuildExportSpan(event transport.LLMObsSpanEvent, cfg *config.Config, service string) *transport.LLMObsSpanEvent

BuildExportSpan clones a validated transport span and applies client defaults.

func ContextWithPropagatedLLMSpan

func ContextWithPropagatedLLMSpan(ctx context.Context, span *PropagatedLLMSpan) context.Context

ContextWithPropagatedLLMSpan returns a new context with the given PropagatedLLMSpan attached.

func DropSpanEventIO

func DropSpanEventIO(ev *transport.LLMObsSpanEvent) bool

DropSpanEventIO drops input and output values from ev.

func EnsureSpanEventMeta

func EnsureSpanEventMeta(event *transport.LLMObsSpanEvent) map[string]any

func Flush

func Flush()

Flush forces a flush of all buffered LLMObs data to the transport.

func FlushSync added in v2.9.0

func FlushSync()

FlushSync flushes all buffered LLMObs data and blocks until the send completes.

func NewSpanEventMeta

func NewSpanEventMeta(kind SpanKind) map[string]any

func PublicResourceBaseURL

func PublicResourceBaseURL() string

PublicResourceBaseURL returns the base URL to access a resource (experiments, projects, etc.)

func ResolveAgentlessEnabled

func ResolveAgentlessEnabled(agentlessEnabled *bool, agentSupportsLLMObs bool) (bool, error)

ResolveAgentlessEnabled resolves the tri-state agentless configuration (nil = not explicitly set) against the agent's advertised LLMObs support. Callers should invoke this before constructing a config.Config to pass into Start.

func SetSpanErrorMeta

func SetSpanErrorMeta(meta map[string]any, msg *transport.ErrorMessage)

func SetSpanModelMeta

func SetSpanModelMeta(meta map[string]any, kind SpanKind, modelName, modelProvider string)

func Start

func Start(cfg config.Config, tracer Tracer, startErr error) (err error)

Start starts the global LLMObs instance with the given configuration and tracer. Returns an error if LLMObs is already running or if configuration is invalid.

func Stop

func Stop()

Stop stops the active LLMObs instance and cleans up resources.

Types

type APMSpan

type APMSpan interface {
	// Finish finishes the span with the given configuration.
	Finish(cfg FinishAPMSpanConfig)
	// AddLink adds a span link to this span.
	AddLink(link SpanLink)
	// SpanID returns the span ID.
	SpanID() string
	// TraceID returns the trace ID.
	TraceID() string
	// SetBaggageItem sets a baggage item on the span.
	SetBaggageItem(key string, value string)
	// BaggageItem returns the baggage item value for the given key.
	BaggageItem(key string) string
}

APMSpan represents the interface for an APM span.

type EmbeddedDocument

type EmbeddedDocument struct {
	// Text is the text content of the document.
	Text string `json:"text"`
	// Name is the name or title of the document.
	Name string `json:"name,omitempty"`
	// Score is the relevance score of the document (typically 0.0-1.0).
	Score float64 `json:"score,omitempty"`
	// ID is the unique identifier of the document.
	ID string `json:"id,omitempty"`
}

EmbeddedDocument represents a document used for embedding operations.

type EvalMetricType

type EvalMetricType = transport.EvalMetricType

EvalMetricType represents an evaluation metric value type.

const (
	EvalMetricTypeCategorical EvalMetricType = transport.EvalMetricTypeCategorical
	EvalMetricTypeScore       EvalMetricType = transport.EvalMetricTypeScore
	EvalMetricTypeBoolean     EvalMetricType = transport.EvalMetricTypeBoolean
	EvalMetricTypeJSON        EvalMetricType = transport.EvalMetricTypeJSON
)

type EvaluationConfig

type EvaluationConfig struct {
	SpanID   string
	TraceID  string
	TagKey   string
	TagValue string

	Label      string
	MetricType EvalMetricType

	CategoricalValue *string
	ScoreValue       *float64
	BooleanValue     *bool
	JSONValue        map[string]any

	Tags        []string
	MLApp       string
	TimestampMS int64
	Timestamp   time.Time
	Assessment  string
	Reasoning   string
	Metadata    map[string]any
}

EvaluationConfig contains configuration for submitting evaluation metrics.

type ExperimentInfo added in v2.8.0

type ExperimentInfo struct {
	ID           string
	RunID        string
	RunIteration int
	ProjectID    string
}

ExperimentInfo holds the experiment identifiers propagated via baggage to distributed child spans.

type ExportValidationCode

type ExportValidationCode string

ExportValidationCode identifies why an offline event cannot be exported.

const (
	ExportCodeMissingID     ExportValidationCode = "missing_id"
	ExportCodeMissingKind   ExportValidationCode = "missing_kind"
	ExportCodeInvalidKind   ExportValidationCode = "invalid_kind"
	ExportCodeInvalidStatus ExportValidationCode = "invalid_status"
	ExportCodeInvalidTiming ExportValidationCode = "invalid_timing"
	ExportCodeInvalidLink   ExportValidationCode = "invalid_link"
	ExportCodeMissingLabel  ExportValidationCode = "missing_label"
	ExportCodeInvalidJoin   ExportValidationCode = "invalid_join"
	ExportCodeInvalidValue  ExportValidationCode = "invalid_value"
	ExportCodeTypeMismatch  ExportValidationCode = "type_mismatch"
	ExportCodeNotEncodable  ExportValidationCode = "not_encodable"
	ExportCodeTooLarge      ExportValidationCode = "too_large"
)

type ExportValidationError

type ExportValidationError struct {
	Index  int
	Code   ExportValidationCode
	Reason string
	// contains filtered or unexported fields
}

ExportValidationError describes an offline input row that was not sent.

func BuildExportEvaluation

func BuildExportEvaluation(metric EvaluationConfig, defaultMLApp string) (*transport.LLMObsMetric, *ExportValidationError)

BuildExportEvaluation validates and lowers the existing evaluation config.

func ValidateExportSpan

func ValidateExportSpan(event transport.LLMObsSpanEvent) *ExportValidationError

ValidateExportSpan checks the fields required by the LLM Obs intake.

func (ExportValidationError) Error

func (e ExportValidationError) Error() string

func (ExportValidationError) Unwrap

func (e ExportValidationError) Unwrap() error

type FinishAPMSpanConfig

type FinishAPMSpanConfig struct {
	// FinishTime is the finish time for the span.
	FinishTime time.Time
	// Error is an error to set on the span when finishing.
	Error error
}

FinishAPMSpanConfig contains configuration options for finishing an APM span.

type FinishSpanConfig

type FinishSpanConfig struct {
	// FinishTime sets a custom finish time for the span. If zero, uses current time.
	FinishTime time.Time
	// Error sets an error on the span when finishing.
	Error error
}

FinishSpanConfig contains configuration options for finishing an LLMObs span.

type LLMMessage

type LLMMessage struct {
	// Role is the role of the message sender (e.g., "user", "assistant", "system").
	Role string `json:"role"`
	// Content is the text content of the message.
	Content string `json:"content"`
	// ToolCalls are the tool calls made in this message.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	// ToolResults are the results of tool calls in this message.
	ToolResults []ToolResult `json:"tool_results,omitempty"`
}

LLMMessage represents a message in an LLM conversation.

type LLMObs

type LLMObs struct {
	// Config contains the LLMObs configuration.
	Config *config.Config
	// Transport handles sending data to the Datadog backend.
	Transport *transport.Transport
	// Tracer is the underlying APM tracer.
	Tracer Tracer
	// contains filtered or unexported fields
}

LLMObs represents the main LLMObs instance that handles span collection and transport.

func ActiveLLMObs

func ActiveLLMObs() (*LLMObs, error)

ActiveLLMObs returns the current active LLMObs instance, or an error if LLMObs is not enabled or started.

func (*LLMObs) Flush

func (l *LLMObs) Flush()

Flush forces an immediate flush of anything currently buffered. It does not wait for new items to arrive.

func (*LLMObs) FlushSync added in v2.9.0

func (l *LLMObs) FlushSync()

FlushSync flushes all currently buffered data and blocks until the HTTP send completes. If the instance has already been stopped, FlushSync returns immediately instead of blocking forever on the unbuffered flushSyncCh send.

func (*LLMObs) Run

func (l *LLMObs) Run()

Run starts the worker loop that processes span events and metrics.

func (*LLMObs) StartExperimentSpan

func (l *LLMObs) StartExperimentSpan(ctx context.Context, name string, params ExperimentInfo, cfg StartSpanConfig) (*Span, context.Context)

StartExperimentSpan starts a new experiment span with the given name and configuration. ExperimentInfo fields are propagated via baggage so distributed child spans inherit them. Returns the created span and a context containing the span.

func (*LLMObs) StartSpan

func (l *LLMObs) StartSpan(ctx context.Context, kind SpanKind, name string, cfg StartSpanConfig) (*Span, context.Context)

StartSpan starts a new LLMObs span with the given kind, name, and configuration. Returns the created span and a context containing the span.

func (*LLMObs) Stop

func (l *LLMObs) Stop()

Stop requests shutdown, drains what’s already in the channels, flushes, and waits.

func (*LLMObs) SubmitEvaluation

func (l *LLMObs) SubmitEvaluation(cfg EvaluationConfig) (err error)

SubmitEvaluation submits an evaluation metric for a span. The span can be identified either by span/trace IDs or by tag key-value pairs.

type Prompt

type Prompt struct {
	// ID is the unique identifier for the prompt within the ML app.
	ID string `json:"id,omitempty"`
	// Version is the version of the prompt.
	Version string `json:"version,omitempty"`
	// PromptUUID is the backend UUID of the managed prompt.
	PromptUUID string `json:"prompt_uuid,omitempty"`
	// PromptVersionUUID is the backend UUID of the managed prompt version.
	PromptVersionUUID string `json:"prompt_version_uuid,omitempty"`
	// Label is the deployment label (e.g., "production", "staging").
	Label string `json:"label,omitempty"`
	// Template is the prompt template string.
	// Mutually exclusive with ChatTemplate; if both are set, Template is dropped and ChatTemplate is used.
	Template string `json:"template,omitempty"`
	// ChatTemplate is a list of messages forming the prompt.
	// Mutually exclusive with Template; if both are set, Template is dropped and ChatTemplate is used.
	ChatTemplate []LLMMessage `json:"chat_template,omitempty"`
	// Variables contains the variables used in the prompt template.
	Variables map[string]string `json:"variables,omitempty"`
	// Tags contains custom tags for the prompt.
	Tags map[string]string `json:"tags,omitempty"`
	// RAGContextVariables specifies which variables contain RAG context.
	RAGContextVariables []string `json:"_dd_context_variable_keys,omitempty"`
	// RAGQueryVariables specifies which variables contain RAG queries.
	RAGQueryVariables []string `json:"_dd_query_variable_keys,omitempty"`
}

Prompt represents a prompt template used with LLM spans.

type PropagatedLLMSpan

type PropagatedLLMSpan struct {
	// MLApp is the ML application name.
	MLApp string
	// TraceID is the LLMObs trace ID.
	TraceID string
	// SpanID is the span ID.
	SpanID string
	// SessionID is the session ID.
	SessionID string
	// ParentAgentName is the name of the nearest agent ancestor, propagated across
	// process boundaries. Empty when the upstream hop sent an id-only attribution.
	ParentAgentName string
	// ParentAgentSpanID is the span ID of the nearest agent ancestor, propagated
	// across process boundaries. Empty when there is no agent ancestor.
	ParentAgentSpanID string
}

PropagatedLLMSpan represents LLMObs span context that can be propagated across process boundaries.

func PropagatedLLMSpanFromContext

func PropagatedLLMSpanFromContext(ctx context.Context) (*PropagatedLLMSpan, bool)

PropagatedLLMSpanFromContext retrieves a PropagatedLLMSpan from the context. Returns the span and true if found, nil and false otherwise.

type RetrievedDocument

type RetrievedDocument struct {
	// Text is the text content of the document.
	Text string `json:"text"`
	// Name is the name or title of the document.
	Name string `json:"name,omitempty"`
	// Score is the relevance score of the document (typically 0.0-1.0).
	Score float64 `json:"score,omitempty"`
	// ID is the unique identifier of the document.
	ID string `json:"id,omitempty"`
}

RetrievedDocument represents a document for retrieval operations.

type Span

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

Span represents an LLMObs span with its associated metadata and context.

func ActiveLLMSpanFromContext

func ActiveLLMSpanFromContext(ctx context.Context) (*Span, bool)

ActiveLLMSpanFromContext retrieves the active LLMObs span from the context. Returns the span and true if found, nil and false otherwise.

func (*Span) APMTraceID

func (s *Span) APMTraceID() string

APMTraceID returns the trace ID of the underlying APM span.

func (s *Span) AddLink(link SpanLink)

AddLink adds a span link to this span.

func (*Span) Annotate

func (s *Span) Annotate(a SpanAnnotations)

Annotate adds annotations to the span using the provided SpanAnnotations.

func (*Span) Finish

func (s *Span) Finish(cfg FinishSpanConfig)

Finish finishes the span with the provided configuration.

func (*Span) FinishTime

func (s *Span) FinishTime() time.Time

FinishTime returns the finish time of this span.

func (*Span) Kind

func (s *Span) Kind() string

func (*Span) MLApp

func (s *Span) MLApp() string

MLApp returns the ML application name for this span.

func (*Span) Name

func (s *Span) Name() string

func (*Span) PropagatedParentAgentName

func (s *Span) PropagatedParentAgentName() string

PropagatedParentAgentName returns the parent-agent name that a downstream process should inherit via the x-datadog-tags header. If this span is itself an Agent it IS the parent for any downstream child, so its own name is returned. Otherwise the already-resolved attribution is forwarded unchanged.

func (*Span) PropagatedParentAgentSpanID

func (s *Span) PropagatedParentAgentSpanID() string

PropagatedParentAgentSpanID returns the parent-agent span ID that a downstream process should inherit via the x-datadog-tags header. If this span is an Agent its own span ID is returned; otherwise the already-resolved span ID is forwarded.

func (*Span) SessionID

func (s *Span) SessionID() string

SessionID returns the resolved session ID for this span.

func (*Span) SpanID

func (s *Span) SpanID() string

SpanID returns the span ID of the underlying APM span.

func (*Span) StartTime

func (s *Span) StartTime() time.Time

StartTime returns the start time of this span.

func (*Span) TraceID

func (s *Span) TraceID() string

TraceID returns the LLMObs trace ID for this span.

type SpanAnnotations

type SpanAnnotations struct {
	// InputText is the text input for the span.
	InputText string
	// InputMessages are the input messages for LLM spans.
	InputMessages []LLMMessage
	// InputEmbeddedDocs are the input documents for embedding spans.
	InputEmbeddedDocs []EmbeddedDocument

	// OutputText is the text output for the span.
	OutputText string
	// OutputMessages are the output messages for LLM spans.
	OutputMessages []LLMMessage
	// OutputRetrievedDocs are the output documents for retrieval spans.
	OutputRetrievedDocs []RetrievedDocument

	// ExperimentInput is the input data for experiment spans.
	ExperimentInput any
	// ExperimentOutput is the output data for experiment spans.
	ExperimentOutput any
	// ExperimentExpectedOutput is the expected output for experiment spans.
	ExperimentExpectedOutput any

	// Prompt is the prompt information for LLM spans.
	Prompt *Prompt
	// ToolDefinitions are the tool definitions for LLM spans.
	ToolDefinitions []ToolDefinition

	// Intent is a description of a reason for calling an MCP tool on tool spans
	Intent string

	// AgentManifest is the agent manifest for agent spans.
	AgentManifest string

	// Metadata contains arbitrary metadata key-value pairs.
	Metadata map[string]any
	// Metrics contains numeric metrics key-value pairs.
	Metrics map[string]float64
	// Tags contains string tags key-value pairs.
	Tags map[string]string
	// CostTags contains tag keys to propagate to LLMObs cost and token metrics.
	// Each key must reference a tag already present on the span.
	CostTags []string
}

SpanAnnotations contains data to annotate an LLMObs span with.

type SpanKind

type SpanKind = transport.SpanKind

SpanKind represents the type of an LLMObs span.

const (
	// SpanKindExperiment represents an experiment span for testing and evaluation.
	SpanKindExperiment SpanKind = transport.SpanKindExperiment
	// SpanKindWorkflow represents a workflow span that orchestrates multiple operations.
	SpanKindWorkflow SpanKind = transport.SpanKindWorkflow
	// SpanKindLLM represents a span for Large Language Model operations.
	SpanKindLLM SpanKind = transport.SpanKindLLM
	// SpanKindEmbedding represents a span for embedding generation operations.
	SpanKindEmbedding SpanKind = transport.SpanKindEmbedding
	// SpanKindAgent represents a span for AI agent operations.
	SpanKindAgent SpanKind = transport.SpanKindAgent
	// SpanKindRetrieval represents a span for document retrieval operations.
	SpanKindRetrieval SpanKind = transport.SpanKindRetrieval
	// SpanKindTask represents a span for general task operations.
	SpanKindTask SpanKind = transport.SpanKindTask
	// SpanKindTool represents a span for tool usage operations.
	SpanKindTool SpanKind = transport.SpanKindTool
)

func SpanEventKind

func SpanEventKind(event *transport.LLMObsSpanEvent) SpanKind
type SpanLink struct {
	TraceID     uint64            `json:"trace_id"`
	TraceIDHigh uint64            `json:"trace_id_high,omitempty"`
	SpanID      uint64            `json:"span_id"`
	Attributes  map[string]string `json:"attributes,omitempty"`
	Tracestate  string            `json:"tracestate,omitempty"`
	Flags       uint32            `json:"flags,omitempty"`
}

SpanLink represents a link between spans.

type StartAPMSpanConfig

type StartAPMSpanConfig struct {
	// SpanType is the type of the APM span.
	SpanType string
	// StartTime is the start time for the span.
	StartTime time.Time
}

StartAPMSpanConfig contains configuration options for starting an APM span.

type StartSpanConfig

type StartSpanConfig struct {
	// SessionID sets the session ID for the span.
	SessionID string
	// ModelName sets the model name for LLM and embedding spans.
	ModelName string
	// ModelProvider sets the model provider for LLM and embedding spans.
	ModelProvider string
	// MLApp sets the ML application name for the span.
	MLApp string
	// StartTime sets a custom start time for the span. If zero, uses current time.
	StartTime time.Time
	// Name of the tracing integration.
	Integration string
}

StartSpanConfig contains configuration options for starting an LLMObs span.

type ToolCall

type ToolCall struct {
	// Name is the name of the tool being called.
	Name string `json:"name"`
	// Arguments are the JSON-encoded arguments passed to the tool.
	Arguments json.RawMessage `json:"arguments"`
	// ToolID is the unique identifier for this tool call.
	ToolID string `json:"tool_id,omitempty"`
	// Type is the type of the tool call.
	Type string `json:"type,omitempty"`
}

ToolCall represents a call to a tool within an LLM message.

type ToolDefinition

type ToolDefinition struct {
	// Name is the name of the tool.
	Name string `json:"name"`
	// Description is the description of what the tool does.
	Description string `json:"description,omitempty"`
	// ToolVersion is the version of the tool.
	ToolVersion string `json:"version,omitempty"`
	// Schema is the JSON schema defining the tool's parameters.
	Schema json.RawMessage `json:"schema,omitempty"`
}

ToolDefinition represents a tool definition for LLM spans.

type ToolResult

type ToolResult struct {
	// Result is the result returned by the tool.
	Result any `json:"result"`
	// Name is the name of the tool that was called.
	Name string `json:"name,omitempty"`
	// ToolID is the unique identifier for the tool call this result corresponds to.
	ToolID string `json:"tool_id,omitempty"`
	// Type is the type of the tool result.
	Type string `json:"type,omitempty"`
}

ToolResult represents the result of a tool call within an LLM message.

type Tracer

type Tracer interface {
	// StartSpan starts a new APM span with the given name and configuration.
	StartSpan(ctx context.Context, name string, cfg StartAPMSpanConfig) (APMSpan, context.Context)
}

Tracer represents the interface for the underlying APM tracer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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