trace

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithHandler

func WithHandler(ctx context.Context, h Handler) context.Context

WithHandler stores the Handler in the context.

Types

type EventData

type EventData struct {
	Kind string `json:"kind"`
	Data any    `json:"data"`
}

EventData holds data specific to a strategy event span. Kind is a string defined by each Strategy implementation. Data is any JSON-serializable value defined by the Strategy.

type FileRepository

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

FileRepository persists trace data as JSON files.

func NewFileRepository

func NewFileRepository(dir string) *FileRepository

NewFileRepository creates a new FileRepository that writes to the given directory.

func (*FileRepository) Save

func (r *FileRepository) Save(_ context.Context, trace *Trace) error

Save writes the trace as JSON to {dir}/{trace_id}.json.

type FunctionCall

type FunctionCall struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

FunctionCall represents a function call in the trace (simplified from gollem.FunctionCall).

type Handler

type Handler interface {
	// StartAgentExecute starts the root agent execution span.
	StartAgentExecute(ctx context.Context) context.Context
	// EndAgentExecute ends the root agent execution span.
	EndAgentExecute(ctx context.Context, err error)

	// StartLLMCall starts an LLM call span.
	StartLLMCall(ctx context.Context) context.Context
	// EndLLMCall ends an LLM call span with the given data.
	EndLLMCall(ctx context.Context, data *LLMCallData, err error)

	// StartToolExec starts a tool execution span.
	StartToolExec(ctx context.Context, toolName string, args map[string]any) context.Context
	// EndToolExec ends a tool execution span with the result.
	EndToolExec(ctx context.Context, result map[string]any, err error)

	// StartSubAgent starts a sub-agent span.
	StartSubAgent(ctx context.Context, name string) context.Context
	// EndSubAgent ends a sub-agent span.
	EndSubAgent(ctx context.Context, err error)

	// StartChildAgent starts a child agent execution span.
	// Unlike StartSubAgent (for gollem-internal sub-agents),
	// this creates a SpanKindAgentExecute span as a child of the current span.
	StartChildAgent(ctx context.Context, name string) context.Context
	// EndChildAgent ends a child agent execution span.
	EndChildAgent(ctx context.Context, err error)

	// AddEvent adds an event to the current span.
	AddEvent(ctx context.Context, kind string, data any)

	// Finish completes the trace and performs any final operations.
	Finish(ctx context.Context) error
}

Handler is the interface for trace backends. Implementations receive lifecycle events during agent execution and can record, export, or forward them as needed.

func AsChildAgent

func AsChildAgent(parent Handler, name string) Handler

AsChildAgent creates a Handler that wraps a parent Handler, mapping StartAgentExecute/EndAgentExecute to StartChildAgent/EndChildAgent.

This is useful when running multiple gollem Agents that should appear as child agents in a single trace tree. The child agents are recorded with SpanKindAgentExecute, distinguishing them from gollem-internal sub-agents (SpanKindSubAgent).

Pass the returned Handler to gollem.WithTrace() when creating the child agent.

Example:

recorder := trace.New(trace.WithRepository(repo))
// ... recorder is used as trace handler for the root agent ...

// For each child agent:
childHandler := trace.AsChildAgent(recorder, "task-1")
childAgent := gollem.New(llmClient,
    gollem.WithTrace(childHandler),
    gollem.WithToolSets(tools...),
)
resp, err := childAgent.Execute(ctx, inputs...)

func HandlerFrom

func HandlerFrom(ctx context.Context) Handler

HandlerFrom retrieves the Handler from the context. Returns nil if not set.

func Multi

func Multi(handlers ...Handler) Handler

Multi creates a Handler that forwards all events to the given handlers. Each handler maintains its own context state, so multiple Recorders or any combination of handlers work correctly without interference.

type LLMCallData

type LLMCallData struct {
	InputTokens  int    `json:"input_tokens"`
	OutputTokens int    `json:"output_tokens"`
	Model        string `json:"model,omitempty"`

	Request  *LLMRequest  `json:"request"`
	Response *LLMResponse `json:"response"`
}

LLMCallData holds data specific to an LLM call span.

type LLMRequest

type LLMRequest struct {
	SystemPrompt string     `json:"system_prompt,omitempty"`
	Messages     []Message  `json:"messages"`
	Tools        []ToolSpec `json:"tools,omitempty"`
}

LLMRequest represents the request sent to an LLM.

type LLMResponse

type LLMResponse struct {
	Texts         []string        `json:"texts,omitempty"`
	FunctionCalls []*FunctionCall `json:"function_calls,omitempty"`
}

LLMResponse represents the response from an LLM.

type Message

type Message struct {
	Role     string           `json:"role"`
	Contents []MessageContent `json:"contents"`
}

Message represents a message in the trace with structured content blocks.

type MessageContent

type MessageContent struct {
	Type string `json:"type"`

	// Text content (type: "text")
	Text string `json:"text,omitempty"`

	// Tool call content (type: "tool_call")
	ID        string         `json:"id,omitempty"`
	Name      string         `json:"name,omitempty"`
	Arguments map[string]any `json:"arguments,omitempty"`

	// Tool response content (type: "tool_response")
	ToolCallID string         `json:"tool_call_id,omitempty"`
	Result     map[string]any `json:"result,omitempty"`

	// Media content (type: "image", "pdf", "document", "file")
	MediaType string `json:"media_type,omitempty"`
	URL       string `json:"url,omitempty"`
	Title     string `json:"title,omitempty"`
}

MessageContent represents a single content block within a trace message.

func NewMediaContent

func NewMediaContent(contentType, mediaType string) MessageContent

NewMediaContent creates a media content block (image, pdf, etc.) for trace messages.

func NewRedactedThinkingContent

func NewRedactedThinkingContent() MessageContent

NewRedactedThinkingContent creates a redacted reasoning content block for trace messages.

func NewTextContent

func NewTextContent(text string) MessageContent

NewTextContent creates a text content block for trace messages.

func NewThinkingContent

func NewThinkingContent(reasoning string) MessageContent

NewThinkingContent creates a reasoning content block for trace messages.

func NewToolCallContent

func NewToolCallContent(id, name string, args map[string]any) MessageContent

NewToolCallContent creates a tool call content block for trace messages.

func NewToolResponseContent

func NewToolResponseContent(toolCallID, name string, result map[string]any) MessageContent

NewToolResponseContent creates a tool response content block for trace messages.

type Option

type Option func(*Recorder)

Option is a functional option for configuring a Recorder.

func WithMetadata

func WithMetadata(meta TraceMetadata) Option

WithMetadata sets the metadata for the trace.

func WithRepository

func WithRepository(repo Repository) Option

WithRepository sets the repository for persisting trace data.

func WithStackTrace

func WithStackTrace() Option

WithStackTrace enables capturing call stack traces for each span. Stack traces are useful for debugging but add overhead, so they are disabled by default.

func WithTraceID

func WithTraceID(id string) Option

WithTraceID sets a custom trace ID. If not set or set to an empty string, a UUID v7 is generated automatically.

type Recorder

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

Recorder collects tracing data during agent execution into an in-memory Trace structure. It implements the Handler interface and provides access to the collected Trace via Trace().

func New

func New(opts ...Option) *Recorder

New creates a new Recorder with the given options.

func (*Recorder) AddEvent

func (r *Recorder) AddEvent(ctx context.Context, kind string, data any)

AddEvent adds an event span as a child of the current span. kind is an arbitrary string defined by the Strategy implementation. data is any JSON-serializable value defined by the Strategy.

func (*Recorder) EndAgentExecute

func (r *Recorder) EndAgentExecute(ctx context.Context, err error)

EndAgentExecute ends the root agent_execute span.

func (*Recorder) EndChildAgent

func (r *Recorder) EndChildAgent(ctx context.Context, err error)

EndChildAgent ends a child agent_execute span.

func (*Recorder) EndLLMCall

func (r *Recorder) EndLLMCall(ctx context.Context, data *LLMCallData, err error)

EndLLMCall ends the llm_call span with the given data.

func (*Recorder) EndSubAgent

func (r *Recorder) EndSubAgent(ctx context.Context, err error)

EndSubAgent ends the sub_agent span.

func (*Recorder) EndToolExec

func (r *Recorder) EndToolExec(ctx context.Context, result map[string]any, err error)

EndToolExec ends the tool_exec span with the result.

func (*Recorder) Finish

func (r *Recorder) Finish(ctx context.Context) error

Finish completes the trace and persists it to the Repository.

func (*Recorder) StartAgentExecute

func (r *Recorder) StartAgentExecute(ctx context.Context) context.Context

StartAgentExecute starts the root agent_execute span. If a trace already exists, it falls back to creating a child agent span instead of overwriting the existing trace. This prevents silent data loss when a single Recorder is shared across multiple Agent.Execute calls.

func (*Recorder) StartChildAgent

func (r *Recorder) StartChildAgent(ctx context.Context, name string) context.Context

StartChildAgent starts a child agent_execute span as a child of the current span.

func (*Recorder) StartLLMCall

func (r *Recorder) StartLLMCall(ctx context.Context) context.Context

StartLLMCall starts an llm_call span as a child of the current span.

func (*Recorder) StartSubAgent

func (r *Recorder) StartSubAgent(ctx context.Context, name string) context.Context

StartSubAgent starts a sub_agent span as a child of the current span.

func (*Recorder) StartToolExec

func (r *Recorder) StartToolExec(ctx context.Context, toolName string, args map[string]any) context.Context

StartToolExec starts a tool_exec span as a child of the current span.

func (*Recorder) Trace

func (r *Recorder) Trace() *Trace

Trace returns the current trace data. Returns nil if no trace is active.

type Repository

type Repository interface {
	Save(ctx context.Context, trace *Trace) error
}

Repository is the interface for persisting trace data.

type Span

type Span struct {
	SpanID     string        `json:"span_id"`
	ParentID   string        `json:"parent_id,omitempty"`
	Kind       SpanKind      `json:"kind"`
	Name       string        `json:"name"`
	StartedAt  time.Time     `json:"started_at"`
	EndedAt    time.Time     `json:"ended_at"`
	Duration   time.Duration `json:"duration"`
	Status     SpanStatus    `json:"status"`
	Error      string        `json:"error,omitempty"`
	Children   []*Span       `json:"children,omitempty"`
	StackTrace []StackFrame  `json:"stack_trace,omitempty"`

	// Kind-specific data (only one is non-nil based on Kind)
	LLMCall  *LLMCallData  `json:"llm_call,omitempty"`
	ToolExec *ToolExecData `json:"tool_exec,omitempty"`
	Event    *EventData    `json:"event,omitempty"`
}

Span represents a single unit of operation in the trace hierarchy.

type SpanKind

type SpanKind string

SpanKind represents the type of a span.

const (
	SpanKindAgentExecute SpanKind = "agent_execute"
	SpanKindLLMCall      SpanKind = "llm_call"
	SpanKindToolExec     SpanKind = "tool_exec"
	SpanKindSubAgent     SpanKind = "sub_agent"
	SpanKindEvent        SpanKind = "event"
)

type SpanStatus

type SpanStatus string

SpanStatus represents the status of a span.

const (
	SpanStatusOK    SpanStatus = "ok"
	SpanStatusError SpanStatus = "error"
)

type StackFrame

type StackFrame struct {
	Function string `json:"function"`
	File     string `json:"file"`
	Line     int    `json:"line"`
}

StackFrame represents a single frame in a call stack trace.

type ToolExecData

type ToolExecData struct {
	ToolName string         `json:"tool_name"`
	Args     map[string]any `json:"args"`
	Result   map[string]any `json:"result,omitempty"`
	Error    string         `json:"error,omitempty"`
}

ToolExecData holds data specific to a tool execution span.

type ToolSpec

type ToolSpec struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

ToolSpec represents a tool specification in the trace (simplified from gollem.ToolSpec).

type Trace

type Trace struct {
	TraceID   string        `json:"trace_id"`
	RootSpan  *Span         `json:"root_span"`
	Metadata  TraceMetadata `json:"metadata"`
	StartedAt time.Time     `json:"started_at"`
	EndedAt   time.Time     `json:"ended_at"`
}

Trace represents the root tracing data for an agent execution.

type TraceMetadata

type TraceMetadata struct {
	Model    string            `json:"model,omitempty"`
	Strategy string            `json:"strategy,omitempty"`
	Labels   map[string]string `json:"labels,omitempty"`
}

TraceMetadata holds metadata for a trace.

Directories

Path Synopsis
Package otel provides an OpenTelemetry trace handler for gollem.
Package otel provides an OpenTelemetry trace handler for gollem.

Jump to

Keyboard shortcuts

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