opik

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 19 Imported by: 0

README

Go SDK for Comet ML Opik

Build Status Lint Status Go Report Card Docs License Version

Go SDK for Opik - an open-source LLM observability platform by Comet ML.

Current Version: v0.5.0 - See Release Notes

Installation

go get github.com/agentplexus/go-opik

Quick Start

package main

import (
    "context"
    "log"

    "github.com/agentplexus/go-opik"
)

func main() {
    // Create client (uses OPIK_API_KEY and OPIK_WORKSPACE env vars for Opik Cloud)
    client, err := opik.NewClient(
        opik.WithProjectName("My Project"),
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // Create a trace
    trace, _ := client.Trace(ctx, "my-trace",
        opik.WithTraceInput(map[string]any{"prompt": "Hello"}),
    )

    // Create a span for an LLM call
    span, _ := trace.Span(ctx, "llm-call",
        opik.WithSpanType(opik.SpanTypeLLM),
        opik.WithSpanModel("gpt-4"),
    )

    // Do your LLM call here...

    // End span with output
    span.End(ctx, opik.WithSpanOutput(map[string]any{"response": "Hi!"}))

    // End trace
    trace.End(ctx)
}

OmniObserve Integration

The SDK includes a built-in llmops subpackage that implements the OmniObserve llmops.Provider interface. This allows you to use Opik through a unified observability abstraction alongside other providers like Phoenix, Langfuse, etc.

package main

import (
    "context"

    "github.com/agentplexus/omniobserve/llmops"
    _ "github.com/agentplexus/go-opik/llmops" // Register Opik provider
)

func main() {
    // Open the Opik provider through OmniObserve
    provider, err := llmops.Open("opik",
        llmops.WithAPIKey("your-api-key"),
        llmops.WithWorkspace("your-workspace"),
        llmops.WithProjectName("my-project"),
    )
    if err != nil {
        panic(err)
    }
    defer provider.Close()

    ctx := context.Background()

    // Start a trace
    ctx, trace, _ := provider.StartTrace(ctx, "my-operation")
    defer trace.End()

    // Start a span
    ctx, span, _ := provider.StartSpan(ctx, "llm-call",
        llmops.WithSpanType(llmops.SpanTypeLLM),
    )
    span.SetModel("gpt-4")
    span.SetInput("Hello, world!")
    span.SetOutput("Hi there!")
    span.End()
}

This pattern allows you to:

  • Switch between observability providers (Opik, Phoenix, Langfuse) without code changes
  • Use a consistent API across different LLM observability platforms
  • Build provider-agnostic observability tooling
Feature Comparison
Feature Opik (Python) go-opik omniobserve/llmops Tests Notes
Tracing
StartTrace
StartSpan
SetInput/Output
SetModel/Provider
SetUsage (tokens)
AddFeedbackScore
TraceFromContext
SpanFromContext
Nested Spans
Span Types general, llm, tool, guardrail
Duration/Timing
Prompts
CreatePrompt
GetPrompt By name + optional version
ListPrompts
CreatePromptVersion Not in omniobserve interface
ListPromptVersions Not in omniobserve interface
Datasets
CreateDataset
GetDataset By name
AddDatasetItems
ListDatasets
DeleteDataset Not in omniobserve interface
Experiments
CreateExperiment Not in omniobserve interface
LogExperimentItem Not in omniobserve interface
ListExperiments Not in omniobserve interface
Projects
CreateProject
GetProject
ListProjects
SetProject
Evaluation
Evaluate Run metrics
AddFeedbackScore Record results
Advanced
Distributed Tracing Not in omniobserve interface
Streaming Spans Not in omniobserve interface
Attachments Not in omniobserve interface
HTTP Middleware Go SDK extension
Local Recording Go SDK extension
Batching Client Not in omniobserve interface

Running omniobserve/llmops tests:

# Skip tests when no API key is set
go test -v ./llmops/

# Run tests with API key
export OPIK_API_KEY=your-api-key
export OPIK_WORKSPACE=your-workspace  # optional
go test -v ./llmops/

Configuration

Environment Variables
Variable Description
OPIK_URL_OVERRIDE API endpoint URL
OPIK_API_KEY API key for Opik Cloud
OPIK_WORKSPACE Workspace name for Opik Cloud
OPIK_PROJECT_NAME Default project name
OPIK_TRACK_DISABLE Set to "true" to disable tracing
Config File

Create ~/.opik.config:

[opik]
url_override = https://www.comet.com/opik/api
api_key = your-api-key
workspace = your-workspace
project_name = My Project
Programmatic Configuration
client, err := opik.NewClient(
    opik.WithURL("https://www.comet.com/opik/api"),
    opik.WithAPIKey("your-api-key"),
    opik.WithWorkspace("your-workspace"),
    opik.WithProjectName("My Project"),
)

Features

Traces and Spans
// Create a trace
trace, _ := client.Trace(ctx, "my-trace",
    opik.WithTraceInput(input),
    opik.WithTraceMetadata(map[string]any{"key": "value"}),
    opik.WithTraceTags("tag1", "tag2"),
)

// Create spans (supports nesting)
span1, _ := trace.Span(ctx, "outer-span")
span2, _ := span1.Span(ctx, "inner-span")

// End spans and traces
span2.End(ctx, opik.WithSpanOutput(output))
span1.End(ctx)
trace.End(ctx)
Span Types
// LLM spans
span, _ := trace.Span(ctx, "llm-call",
    opik.WithSpanType(opik.SpanTypeLLM),
    opik.WithSpanModel("gpt-4"),
    opik.WithSpanProvider("openai"),
)

// Tool spans
span, _ := trace.Span(ctx, "tool-call",
    opik.WithSpanType(opik.SpanTypeTool),
)

// General spans (default)
span, _ := trace.Span(ctx, "processing",
    opik.WithSpanType(opik.SpanTypeGeneral),
)
Feedback Scores
// Add feedback to traces
trace.AddFeedbackScore(ctx, "accuracy", 0.95, "High accuracy")

// Add feedback to spans
span.AddFeedbackScore(ctx, "relevance", 0.87, "Mostly relevant")
Context Propagation
// Start trace with context
ctx, trace, _ := opik.StartTrace(ctx, client, "my-trace")

// Start nested spans
ctx, span1, _ := opik.StartSpan(ctx, "span-1")
ctx, span2, _ := opik.StartSpan(ctx, "span-2") // Automatically nested under span1

// Get current trace/span from context
currentTrace := opik.TraceFromContext(ctx)
currentSpan := opik.SpanFromContext(ctx)
Listing Traces and Spans
// List recent traces
traces, _ := client.ListTraces(ctx, page, size)
for _, t := range traces {
    fmt.Printf("Trace: %s (ID: %s)\n", t.Name, t.ID)
}

// List spans for a specific trace
spans, _ := client.ListSpans(ctx, traceID, page, size)
for _, s := range spans {
    fmt.Printf("Span: %s (Type: %s, Model: %s)\n", s.Name, s.Type, s.Model)
}
Distributed Tracing
// Inject trace headers into outgoing requests
opik.InjectDistributedTraceHeaders(ctx, req)

// Extract trace headers from incoming requests
headers := opik.ExtractDistributedTraceHeaders(req)

// Continue a distributed trace
ctx, span, _ := client.ContinueTrace(ctx, headers, "handle-request")

// Use propagating HTTP client
httpClient := opik.PropagatingHTTPClient()
Streaming Support
// Start a streaming span
ctx, streamSpan, _ := opik.StartStreamingSpan(ctx, "stream-response",
    opik.WithSpanType(opik.SpanTypeLLM),
)

// Add chunks as they arrive
for chunk := range chunks {
    streamSpan.AddChunk(chunk.Content,
        opik.WithChunkTokenCount(chunk.Tokens),
    )
}

// Mark final chunk
streamSpan.AddChunk(lastChunk, opik.WithChunkFinishReason("stop"))

// End with accumulated data
streamSpan.End(ctx)
Datasets
// Create a dataset
dataset, _ := client.CreateDataset(ctx, "my-dataset",
    opik.WithDatasetDescription("Test data for evaluation"),
    opik.WithDatasetTags("test", "evaluation"),
)

// Insert items
dataset.InsertItem(ctx, map[string]any{
    "input":    "What is the capital of France?",
    "expected": "Paris",
})

// Insert multiple items
items := []map[string]any{
    {"input": "2+2", "expected": "4"},
    {"input": "3+3", "expected": "6"},
}
dataset.InsertItems(ctx, items)

// Retrieve items
items, _ := dataset.GetItems(ctx, 1, 100)

// List datasets
datasets, _ := client.ListDatasets(ctx, 1, 100)

// Get dataset by name
dataset, _ := client.GetDatasetByName(ctx, "my-dataset")

// Delete dataset
dataset.Delete(ctx)
Experiments
// Create an experiment
experiment, _ := client.CreateExperiment(ctx, "my-dataset",
    opik.WithExperimentName("gpt-4-evaluation"),
    opik.WithExperimentMetadata(map[string]any{"model": "gpt-4"}),
)

// Log experiment items
experiment.LogItem(ctx, datasetItemID, traceID,
    opik.WithExperimentItemInput(input),
    opik.WithExperimentItemOutput(output),
)

// Complete or cancel experiments
experiment.Complete(ctx)
experiment.Cancel(ctx)

// List experiments
experiments, _ := client.ListExperiments(ctx, datasetID, 1, 100)

// Delete experiment
experiment.Delete(ctx)
Prompts
// Create a prompt
prompt, _ := client.CreatePrompt(ctx, "greeting-prompt",
    opik.WithPromptDescription("Greeting template"),
    opik.WithPromptTemplate("Hello, {{name}}! Welcome to {{place}}."),
    opik.WithPromptTags("greeting", "template"),
)

// Get prompt by name
version, _ := client.GetPromptByName(ctx, "greeting-prompt", "")

// Render template with variables
rendered := version.Render(map[string]string{
    "name":  "Alice",
    "place": "Wonderland",
})
// Result: "Hello, Alice! Welcome to Wonderland."

// Extract variables from template
vars := version.ExtractVariables()
// Result: ["name", "place"]

// Create new version
newVersion, _ := prompt.CreateVersion(ctx, "Hi, {{name}}!",
    opik.WithVersionChangeDescription("Simplified greeting"),
)

// List all versions
versions, _ := prompt.GetVersions(ctx, 1, 100)

// List all prompts
prompts, _ := client.ListPrompts(ctx, 1, 100)
HTTP Middleware
import "github.com/agentplexus/go-opik/middleware"

// Wrap HTTP handlers with automatic tracing
handler := middleware.TracingMiddleware(client, "api-request")(yourHandler)

// Use tracing HTTP client for outgoing requests
httpClient := middleware.TracingHTTPClient("external-call")
resp, _ := httpClient.Get("https://api.example.com/data")

// Or wrap an existing transport
transport := middleware.NewTracingRoundTripper(http.DefaultTransport, "api-call")
httpClient := &http.Client{Transport: transport}
Local Recording (Testing)
// Record traces locally without sending to server
client := opik.RecordTracesLocally("my-project")
trace, _ := client.Trace(ctx, "test-trace")
span, _ := trace.Span(ctx, "test-span")
span.End(ctx)
trace.End(ctx)

// Access recorded data
traces := client.Recording().Traces()
spans := client.Recording().Spans()
Batching
// Create a batching client for efficient API calls
client, _ := opik.NewBatchingClient(
    opik.WithProjectName("My Project"),
)

// Operations are batched automatically
client.AddFeedbackAsync("trace", traceID, "score", 0.95, "reason")

// Flush pending operations
client.Flush(5 * time.Second)

// Close and flush on shutdown
defer client.Close(10 * time.Second)
Attachments
// Create attachment from file
attachment, _ := opik.NewAttachmentFromFile("/path/to/image.png")

// Create attachment from bytes
attachment := opik.NewAttachmentFromBytes("data.json", jsonBytes, "application/json")

// Create text attachment
attachment := opik.NewTextAttachment("notes.txt", "Some text content")

// Get data URL for embedding
dataURL := attachment.ToDataURL()

Evaluation Framework

Heuristic Metrics
import (
    "github.com/agentplexus/go-opik/evaluation"
    "github.com/agentplexus/go-opik/evaluation/heuristic"
)

// Create metrics
metrics := []evaluation.Metric{
    heuristic.NewEquals(false),           // Case-insensitive equality
    heuristic.NewContains(false),         // Substring check
    heuristic.NewIsJSON(),                // JSON validation
    heuristic.NewLevenshteinSimilarity(false), // Edit distance
    heuristic.NewBLEU(4),                 // BLEU score
    heuristic.NewROUGE(1.0),              // ROUGE-L score
    heuristic.MustRegexMatch(`\d+`),      // Regex matching
}

// Evaluate
engine := evaluation.NewEngine(metrics, evaluation.WithConcurrency(4))
input := evaluation.NewMetricInput("What is 2+2?", "The answer is 4.")
input = input.WithExpected("4")

result := engine.EvaluateOne(ctx, input)
fmt.Printf("Average score: %.2f\n", result.AverageScore())
LLM Judge Metrics
import (
    "github.com/agentplexus/go-opik/evaluation/llm"
    "github.com/agentplexus/go-opik/integrations/openai"
)

// Create LLM provider
provider := openai.NewProvider(openai.WithModel("gpt-4o"))

// Create LLM-based metrics
metrics := []evaluation.Metric{
    llm.NewAnswerRelevance(provider),
    llm.NewHallucination(provider),
    llm.NewFactuality(provider),
    llm.NewCoherence(provider),
    llm.NewHelpfulness(provider),
}

// Custom judge with custom prompt
customJudge := llm.NewCustomJudge("tone_check", `
Evaluate whether the response maintains a professional tone.

User message: {{input}}
AI response: {{output}}

Return JSON: {"score": <0.0-1.0>, "reason": "<explanation>"}
`, provider)
G-EVAL
geval := llm.NewGEval(provider, "fluency and coherence").
    WithEvaluationSteps([]string{
        "Check if the response is grammatically correct",
        "Evaluate logical flow of ideas",
        "Assess clarity of expression",
    })

score := geval.Score(ctx, input)

LLM Provider Integrations

OpenAI
import "github.com/agentplexus/go-opik/integrations/openai"

// Create provider for evaluation
provider := openai.NewProvider(
    openai.WithAPIKey("your-api-key"),
    openai.WithModel("gpt-4o"),
)

// Create tracing provider (auto-traces all calls)
tracingProvider := openai.TracingProvider(opikClient,
    openai.WithModel("gpt-4o"),
)

// Use tracing HTTP client with existing code
httpClient := openai.TracingHTTPClient(opikClient)
Anthropic
import "github.com/agentplexus/go-opik/integrations/anthropic"

// Create provider for evaluation
provider := anthropic.NewProvider(
    anthropic.WithAPIKey("your-api-key"),
    anthropic.WithModel("claude-sonnet-4-20250514"),
)

// Create tracing provider (auto-traces all calls)
tracingProvider := anthropic.TracingProvider(opikClient)

// Use tracing HTTP client with existing code
httpClient := anthropic.TracingHTTPClient(opikClient)

CLI Tool

# Install CLI
go install github.com/agentplexus/go-opik/cmd/opik@latest

# Configure
opik configure -api-key=your-key -workspace=your-workspace

# List projects
opik projects -list

# Create project
opik projects -create="New Project"

# List traces
opik traces -list -project="My Project" -limit=20

# List datasets
opik datasets -list

# Create dataset
opik datasets -create="evaluation-data"

# List experiments
opik experiments -list -dataset="my-dataset"

API Client Access

For advanced usage, access the underlying ogen-generated API client:

api := client.API()
// Use api.* methods for full API access

Error Handling

// Check for specific errors
if opik.IsNotFound(err) {
    // Handle not found
}

if opik.IsUnauthorized(err) {
    // Handle auth failure
}

if opik.IsRateLimited(err) {
    // Handle rate limiting
}

Tutorials

Agentic Observability

For integrating Opik with agent frameworks like Google ADK and Eino, see the Agentic Observability Tutorial. This tutorial covers:

  • Tracing Google ADK agents with tools
  • Tracing Eino workflow graphs
  • Multi-agent orchestration observability
  • Best practices for agent debugging and monitoring

Development

Running Tests
go test ./...
Running Linter
golangci-lint run
Regenerating API Client

The SDK uses ogen to generate a type-safe API client from the Opik OpenAPI specification. When the upstream API changes, regenerate the client:

Prerequisites:

# Install ogen
go install github.com/ogen-go/ogen/cmd/ogen@latest

Update the OpenAPI spec:

# Download latest spec from Opik repository
curl -o openapi/openapi.yaml \
  https://raw.githubusercontent.com/comet-ml/opik/main/sdks/code_generation/fern/openapi/openapi.yaml

Generate the client:

./generate.sh

This script runs ogen, applies necessary fixes, and verifies the build. For detailed documentation on the generation process and troubleshooting, see the Development Guide.

License

MIT License - see LICENSE for details.

Documentation

Index

Constants

View Source
const (
	// DefaultCloudURL is the default URL for Opik Cloud
	DefaultCloudURL = "https://www.comet.com/opik/api"
	// DefaultLocalURL is the default URL for local Opik server
	DefaultLocalURL = "http://localhost:5173/api"
	// DefaultProjectName is the default project name
	DefaultProjectName = "Default Project"
	// DefaultWorkspace is the default workspace name
	DefaultWorkspace = "default"
	// DefaultConfigFile is the default config file path
	DefaultConfigFile = "~/.opik.config"
)
View Source
const (
	EnvURLOverride  = "OPIK_URL_OVERRIDE"
	EnvAPIKey       = "OPIK_API_KEY" //nolint:gosec // G101: This is an environment variable name, not a credential
	EnvWorkspace    = "OPIK_WORKSPACE"
	EnvProjectName  = "OPIK_PROJECT_NAME"
	EnvTraceDisable = "OPIK_TRACK_DISABLE"
)

Environment variable names

View Source
const (
	HeaderTraceID      = "X-Opik-Trace-ID"
	HeaderParentSpanID = "X-Opik-Parent-Span-ID"
)

Header names for distributed tracing.

View Source
const SpanTypeGeneral = "general"

SpanTypeGeneral is the span type for general operations.

View Source
const SpanTypeGuardrail = "guardrail"

SpanTypeGuardrail is the span type for guardrail checks.

View Source
const SpanTypeLLM = "llm"

SpanTypeLLM is the span type for LLM calls.

View Source
const SpanTypeTool = "tool"

SpanTypeTool is the span type for tool calls.

View Source
const Version = "0.1.0"

Version is the SDK version.

Variables

View Source
var (
	// ErrMissingURL is returned when the API URL is not configured.
	ErrMissingURL = errors.New("opik: missing API URL")

	// ErrMissingAPIKey is returned when the API key is required but not provided.
	ErrMissingAPIKey = errors.New("opik: missing API key for Opik Cloud")

	// ErrMissingWorkspace is returned when the workspace is required but not provided.
	ErrMissingWorkspace = errors.New("opik: missing workspace for Opik Cloud")

	// ErrTracingDisabled is returned when tracing is disabled.
	ErrTracingDisabled = errors.New("opik: tracing is disabled")

	// ErrTraceNotFound is returned when a trace cannot be found.
	ErrTraceNotFound = errors.New("opik: trace not found")

	// ErrSpanNotFound is returned when a span cannot be found.
	ErrSpanNotFound = errors.New("opik: span not found")

	// ErrDatasetNotFound is returned when a dataset cannot be found.
	ErrDatasetNotFound = errors.New("opik: dataset not found")

	// ErrExperimentNotFound is returned when an experiment cannot be found.
	ErrExperimentNotFound = errors.New("opik: experiment not found")

	// ErrPromptNotFound is returned when a prompt cannot be found.
	ErrPromptNotFound = errors.New("opik: prompt not found")

	// ErrInvalidInput is returned when input validation fails.
	ErrInvalidInput = errors.New("opik: invalid input")

	// ErrNoActiveTrace is returned when there is no active trace in context.
	ErrNoActiveTrace = errors.New("opik: no active trace in context")

	// ErrNoActiveSpan is returned when there is no active span in context.
	ErrNoActiveSpan = errors.New("opik: no active span in context")
)

Sentinel errors for the Opik SDK.

Functions

func ContextWithClient

func ContextWithClient(ctx context.Context, client *Client) context.Context

ContextWithClient returns a new context with the client attached.

func ContextWithSpan

func ContextWithSpan(ctx context.Context, span *Span) context.Context

ContextWithSpan returns a new context with the span attached.

func ContextWithTrace

func ContextWithTrace(ctx context.Context, trace *Trace) context.Context

ContextWithTrace returns a new context with the trace attached.

func CurrentSpanID

func CurrentSpanID(ctx context.Context) string

CurrentSpanID returns the current span ID from the context, or empty string if none.

func CurrentTraceID

func CurrentTraceID(ctx context.Context) string

CurrentTraceID returns the current trace ID from the context, or empty string if none.

func EndSpan

func EndSpan(ctx context.Context, opts ...SpanOption) error

EndSpan ends the current span in the context.

func EndTrace

func EndTrace(ctx context.Context, opts ...TraceOption) error

EndTrace ends the current trace in the context.

func InjectDistributedTraceHeaders

func InjectDistributedTraceHeaders(ctx context.Context, req *http.Request)

InjectDistributedTraceHeaders adds trace context headers to an HTTP request.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error indicates a resource was not found.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited returns true if the error indicates rate limiting.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized returns true if the error indicates an authentication failure.

func PropagatingHTTPClient

func PropagatingHTTPClient() *http.Client

PropagatingHTTPClient returns an http.Client that automatically propagates distributed trace headers to all outgoing requests.

func SaveConfig

func SaveConfig(cfg *Config) error

SaveConfig saves the configuration to the config file.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Details    string
}

APIError represents an error returned by the Opik API.

func (*APIError) Error

func (e *APIError) Error() string

type Attachment

type Attachment struct {
	// Name is the display name of the attachment.
	Name string
	// Type is the attachment type (image, audio, etc.).
	Type AttachmentType
	// MimeType is the MIME type of the attachment.
	MimeType string
	// Data is the raw attachment data.
	Data []byte
	// URL is an optional URL for externally hosted attachments.
	URL string
	// Base64 is the base64-encoded data (for embedding).
	Base64 string
}

Attachment represents a file attachment for a trace or span.

func ImageFromBase64

func ImageFromBase64(name, base64Data, mimeType string) (*Attachment, error)

ImageFromBase64 creates an Attachment from a base64 string.

func ImageFromURL

func ImageFromURL(ctx context.Context, name, url string) (*Attachment, error)

ImageFromURL fetches and creates an Attachment from a URL.

func NewAttachmentFromBytes

func NewAttachmentFromBytes(name string, data []byte, mimeType string) *Attachment

NewAttachmentFromBytes creates an attachment from raw bytes.

func NewAttachmentFromFile

func NewAttachmentFromFile(path string) (*Attachment, error)

NewAttachmentFromFile creates an attachment from a file path.

func NewAttachmentFromReader

func NewAttachmentFromReader(name string, r io.Reader, mimeType string) (*Attachment, error)

NewAttachmentFromReader creates an attachment from an io.Reader.

func NewAttachmentFromURL

func NewAttachmentFromURL(name string, url string, attachType AttachmentType) *Attachment

NewAttachmentFromURL creates an attachment from a URL.

func NewImageAttachment

func NewImageAttachment(name string, data []byte, mimeType string) *Attachment

NewImageAttachment creates an image attachment from bytes.

func NewTextAttachment

func NewTextAttachment(name, content string) *Attachment

NewTextAttachment creates a text attachment.

func (*Attachment) IsEmbeddable

func (a *Attachment) IsEmbeddable(maxSize int) bool

IsEmbeddable returns true if the attachment is small enough to embed inline.

func (*Attachment) Size

func (a *Attachment) Size() int

Size returns the size of the attachment in bytes.

func (*Attachment) ToBase64

func (a *Attachment) ToBase64() string

ToBase64 returns the base64-encoded attachment data.

func (*Attachment) ToDataURL

func (a *Attachment) ToDataURL() string

ToDataURL returns a data URL for the attachment.

type AttachmentExtractor

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

AttachmentExtractor extracts attachments from LLM responses.

func NewAttachmentExtractor

func NewAttachmentExtractor() *AttachmentExtractor

NewAttachmentExtractor creates a new attachment extractor.

func (*AttachmentExtractor) Extract

func (e *AttachmentExtractor) Extract(content any) []*Attachment

Extract extracts attachments from content.

func (*AttachmentExtractor) SetEnabled

func (e *AttachmentExtractor) SetEnabled(enabled bool)

SetEnabled enables or disables attachment extraction.

type AttachmentOption

type AttachmentOption func(*attachmentOptions)

AttachmentOption is a functional option for attachments.

func WithAttachment

func WithAttachment(attachment *Attachment) AttachmentOption

WithAttachment adds an attachment.

func WithFileAttachment

func WithFileAttachment(path string) AttachmentOption

WithFileAttachment adds a file attachment.

func WithImageAttachment

func WithImageAttachment(name string, data []byte) AttachmentOption

WithImageAttachment adds an image attachment.

func WithTextAttachment

func WithTextAttachment(name, content string) AttachmentOption

WithTextAttachment adds a text attachment.

type AttachmentType

type AttachmentType string

AttachmentType represents the type of attachment.

const (
	AttachmentTypeImage    AttachmentType = "image"
	AttachmentTypeAudio    AttachmentType = "audio"
	AttachmentTypeVideo    AttachmentType = "video"
	AttachmentTypeDocument AttachmentType = "document"
	AttachmentTypeText     AttachmentType = "text"
	AttachmentTypeOther    AttachmentType = "other"
)

type AttachmentUploader

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

AttachmentUploader handles uploading attachments to storage.

func NewAttachmentUploader

func NewAttachmentUploader(client *Client) *AttachmentUploader

NewAttachmentUploader creates a new attachment uploader.

func (*AttachmentUploader) SetMaxEmbedSize

func (u *AttachmentUploader) SetMaxEmbedSize(size int)

SetMaxEmbedSize sets the maximum size for inline embedding.

func (*AttachmentUploader) Upload

func (u *AttachmentUploader) Upload(ctx context.Context, attachment *Attachment) (string, error)

Upload uploads an attachment and returns the URL or embedded data.

func (*AttachmentUploader) UploadMultiple

func (u *AttachmentUploader) UploadMultiple(ctx context.Context, attachments []*Attachment) ([]string, error)

UploadMultiple uploads multiple attachments.

type BatchItem

type BatchItem interface {
	// Type returns the type of batch item (e.g., "trace", "span", "feedback").
	Type() string
}

BatchItem represents an item to be batched.

type Batcher

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

Batcher batches operations for efficient API calls.

func NewBatcher

func NewBatcher(client *Client, config BatcherConfig) *Batcher

NewBatcher creates a new batcher with the given configuration.

func (*Batcher) Add

func (b *Batcher) Add(item BatchItem)

Add adds an item to the batch.

func (*Batcher) Close

func (b *Batcher) Close(timeout time.Duration) error

Close stops the batcher and flushes remaining items.

func (*Batcher) Flush

func (b *Batcher) Flush(timeout time.Duration) error

Flush forces a flush of all pending items.

type BatcherConfig

type BatcherConfig struct {
	// MaxBatchSize is the maximum number of items to batch before flushing.
	MaxBatchSize int
	// FlushInterval is the maximum time to wait before flushing a batch.
	FlushInterval time.Duration
	// MaxRetries is the maximum number of retries for failed batches.
	MaxRetries int
	// RetryDelay is the initial delay between retries (doubles each retry).
	RetryDelay time.Duration
	// Workers is the number of background workers for processing batches.
	Workers int
}

BatcherConfig configures the message batcher.

func DefaultBatcherConfig

func DefaultBatcherConfig() BatcherConfig

DefaultBatcherConfig returns the default batcher configuration.

type BatchingClient

type BatchingClient struct {
	*Client
	// contains filtered or unexported fields
}

BatchingClient wraps a Client with batching support.

func NewBatchingClient

func NewBatchingClient(opts ...Option) (*BatchingClient, error)

NewBatchingClient creates a new client with batching enabled.

func NewBatchingClientWithConfig

func NewBatchingClientWithConfig(config BatcherConfig, opts ...Option) (*BatchingClient, error)

NewBatchingClientWithConfig creates a new client with custom batching config.

func (*BatchingClient) AddFeedbackAsync

func (c *BatchingClient) AddFeedbackAsync(entityType, entityID, name string, value float64, reason string)

AddFeedbackAsync adds a feedback score asynchronously via batching.

func (*BatchingClient) Close

func (c *BatchingClient) Close(timeout time.Duration) error

Close closes the batching client and flushes pending operations.

func (*BatchingClient) Flush

func (c *BatchingClient) Flush(timeout time.Duration) error

Flush flushes all pending batched operations.

type BufferingStreamHandler

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

BufferingStreamHandler buffers chunks and calls a callback with complete content.

func NewBufferingStreamHandler

func NewBufferingStreamHandler(onComplete func(content string) error) *BufferingStreamHandler

NewBufferingStreamHandler creates a buffering handler.

func (*BufferingStreamHandler) Accumulator

func (h *BufferingStreamHandler) Accumulator() *StreamAccumulator

Accumulator returns the stream accumulator.

func (*BufferingStreamHandler) Content

func (h *BufferingStreamHandler) Content() string

Content returns the current buffered content.

func (*BufferingStreamHandler) Finalize

func (h *BufferingStreamHandler) Finalize() error

Finalize calls the completion callback with buffered content.

func (*BufferingStreamHandler) HandleChunk

func (h *BufferingStreamHandler) HandleChunk(chunk StreamChunk) error

HandleChunk adds a chunk to the buffer.

func (*BufferingStreamHandler) OnChunk

func (h *BufferingStreamHandler) OnChunk(fn func(chunk StreamChunk) error)

OnChunk sets a callback for each chunk.

type Client

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

Client is the main Opik client for interacting with the Opik API.

func ClientFromContext

func ClientFromContext(ctx context.Context) *Client

ClientFromContext returns the client from the context, or nil if none.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a new Opik client with the given options.

func (*Client) API

func (c *Client) API() *api.Client

API returns the underlying ogen-generated API client for advanced usage.

func (*Client) Config

func (c *Client) Config() *Config

Config returns the client configuration.

func (*Client) ContinueTrace

func (c *Client) ContinueTrace(ctx context.Context, headers DistributedTraceHeaders, spanName string, opts ...SpanOption) (context.Context, *Span, error)

ContinueTrace creates a new span that continues from distributed trace headers. This is used when receiving a request from another service that has trace context.

func (*Client) CreateDataset

func (c *Client) CreateDataset(ctx context.Context, name string, opts ...DatasetOption) (*Dataset, error)

CreateDataset creates a new dataset.

func (*Client) CreateExperiment

func (c *Client) CreateExperiment(ctx context.Context, datasetName string, opts ...ExperimentOption) (*Experiment, error)

CreateExperiment creates a new experiment for a dataset.

func (*Client) CreateProject

func (c *Client) CreateProject(ctx context.Context, name string, opts ...ProjectOption) (*Project, error)

CreateProject creates a new project.

func (*Client) CreatePrompt

func (c *Client) CreatePrompt(ctx context.Context, name string, opts ...PromptOption) (*Prompt, error)

CreatePrompt creates a new prompt.

func (*Client) DeleteDataset

func (c *Client) DeleteDataset(ctx context.Context, datasetID string) error

DeleteDataset deletes a dataset by ID.

func (*Client) DeleteExperiment

func (c *Client) DeleteExperiment(ctx context.Context, experimentID string) error

DeleteExperiment deletes an experiment by ID.

func (*Client) DeletePrompt

func (c *Client) DeletePrompt(ctx context.Context, promptID string) error

DeletePrompt deletes a prompt by ID.

func (*Client) GetDataset

func (c *Client) GetDataset(ctx context.Context, datasetID string) (*Dataset, error)

GetDataset retrieves a dataset by ID.

func (*Client) GetDatasetByName

func (c *Client) GetDatasetByName(ctx context.Context, name string) (*Dataset, error)

GetDatasetByName retrieves a dataset by name.

func (*Client) GetExperiment

func (c *Client) GetExperiment(ctx context.Context, experimentID string) (*Experiment, error)

GetExperiment retrieves an experiment by ID.

func (*Client) GetPrompt

func (c *Client) GetPrompt(ctx context.Context, promptID string) (*Prompt, error)

GetPrompt retrieves a prompt by ID.

func (*Client) GetPromptByName

func (c *Client) GetPromptByName(ctx context.Context, name string, commit string) (*PromptVersion, error)

GetPromptByName retrieves a prompt version by name and optional commit.

func (*Client) GetTrace

func (c *Client) GetTrace(ctx context.Context, traceID string) (*Trace, error)

GetTrace retrieves a trace by ID.

func (*Client) IsTracingEnabled

func (c *Client) IsTracingEnabled() bool

IsTracingEnabled returns true if tracing is enabled.

func (*Client) ListDatasets

func (c *Client) ListDatasets(ctx context.Context, page, size int) ([]*Dataset, error)

ListDatasets lists all datasets.

func (*Client) ListExperiments

func (c *Client) ListExperiments(ctx context.Context, datasetID string, page, size int) ([]*Experiment, error)

ListExperiments lists experiments for a dataset.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context, page, size int) ([]*Project, error)

ListProjects lists all projects.

func (*Client) ListPrompts

func (c *Client) ListPrompts(ctx context.Context, page, size int) ([]*Prompt, error)

ListPrompts lists all prompts.

func (*Client) ListSpans

func (c *Client) ListSpans(ctx context.Context, traceID string, page, size int) ([]*SpanInfo, error)

ListSpans lists spans for a specific trace.

func (*Client) ListTraces

func (c *Client) ListTraces(ctx context.Context, page, size int) ([]*TraceInfo, error)

ListTraces lists recent traces.

func (*Client) ProjectName

func (c *Client) ProjectName() string

ProjectName returns the default project name.

func (*Client) SetProjectName

func (c *Client) SetProjectName(name string)

SetProjectName sets the default project name.

func (*Client) Trace

func (c *Client) Trace(ctx context.Context, name string, opts ...TraceOption) (*Trace, error)

Trace creates a new trace.

type Config

type Config struct {
	// URL is the Opik API endpoint URL.
	// Defaults to DefaultCloudURL if APIKey is set, otherwise DefaultLocalURL.
	URL string

	// APIKey is the API key for authentication with Opik Cloud.
	// Not required for local/self-hosted instances.
	APIKey string

	// Workspace is the workspace name for Opik Cloud.
	// Required for Opik Cloud, ignored for local instances.
	Workspace string

	// ProjectName is the default project name for traces.
	ProjectName string

	// TracingDisabled disables tracing globally when set to true.
	TracingDisabled bool

	// CheckTLSCertificate enables TLS certificate verification.
	// Defaults to true.
	CheckTLSCertificate bool
}

Config holds the configuration for the Opik client.

func LoadConfig

func LoadConfig() *Config

LoadConfig loads configuration from environment variables and config file. Priority order (highest to lowest): 1. Explicitly set values (via options) 2. Environment variables 3. Config file (~/.opik.config) 4. Default values

func NewConfig

func NewConfig() *Config

NewConfig creates a new Config with default values.

func (*Config) IsCloud

func (c *Config) IsCloud() bool

IsCloud returns true if the configuration is for Opik Cloud.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

type Dataset

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

Dataset represents a dataset in Opik for storing test data.

func (*Dataset) Delete

func (d *Dataset) Delete(ctx context.Context) error

Delete deletes this dataset.

func (*Dataset) Description

func (d *Dataset) Description() string

Description returns the dataset description.

func (*Dataset) GetItems

func (d *Dataset) GetItems(ctx context.Context, page, size int) ([]DatasetItem, error)

GetItems retrieves items from the dataset.

func (*Dataset) ID

func (d *Dataset) ID() string

ID returns the dataset ID.

func (*Dataset) InsertItem

func (d *Dataset) InsertItem(ctx context.Context, data map[string]any, opts ...DatasetItemOption) error

InsertItem inserts a single item into the dataset.

func (*Dataset) InsertItems

func (d *Dataset) InsertItems(ctx context.Context, items []map[string]any, opts ...DatasetItemOption) error

InsertItems inserts multiple items into the dataset.

func (*Dataset) Name

func (d *Dataset) Name() string

Name returns the dataset name.

func (*Dataset) Tags

func (d *Dataset) Tags() []string

Tags returns the dataset tags.

type DatasetItem

type DatasetItem struct {
	ID      string
	TraceID string
	SpanID  string
	Data    map[string]any
	Tags    []string
}

DatasetItem represents an item in a dataset.

type DatasetItemOption

type DatasetItemOption func(*datasetItemOptions)

DatasetItemOption is a functional option for configuring a DatasetItem.

func WithDatasetItemTags

func WithDatasetItemTags(tags ...string) DatasetItemOption

WithDatasetItemTags sets the tags for the dataset item.

type DatasetOption

type DatasetOption func(*datasetOptions)

DatasetOption is a functional option for configuring a Dataset.

func WithDatasetDescription

func WithDatasetDescription(description string) DatasetOption

WithDatasetDescription sets the description for the dataset.

func WithDatasetTags

func WithDatasetTags(tags ...string) DatasetOption

WithDatasetTags sets the tags for the dataset.

type DistributedTraceHeaders

type DistributedTraceHeaders struct {
	TraceID      string `json:"opik_trace_id"`
	ParentSpanID string `json:"opik_parent_span_id"`
}

DistributedTraceHeaders contains trace context for cross-service propagation.

func ExtractDistributedTraceHeaders

func ExtractDistributedTraceHeaders(req *http.Request) DistributedTraceHeaders

ExtractDistributedTraceHeaders extracts trace context from HTTP request headers.

func GetDistributedTraceHeaders

func GetDistributedTraceHeaders(ctx context.Context) DistributedTraceHeaders

GetDistributedTraceHeaders returns the current trace context from the context. This can be used to propagate trace context across service boundaries.

type Experiment

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

Experiment represents an experiment in Opik for evaluating models.

func (*Experiment) Cancel

func (e *Experiment) Cancel(ctx context.Context) error

Cancel marks the experiment as cancelled.

func (*Experiment) Complete

func (e *Experiment) Complete(ctx context.Context) error

Complete marks the experiment as completed.

func (*Experiment) DatasetName

func (e *Experiment) DatasetName() string

DatasetName returns the dataset name.

func (*Experiment) Delete

func (e *Experiment) Delete(ctx context.Context) error

Delete deletes this experiment.

func (*Experiment) ID

func (e *Experiment) ID() string

ID returns the experiment ID.

func (*Experiment) LogItem

func (e *Experiment) LogItem(ctx context.Context, datasetItemID, traceID string, opts ...ExperimentItemOption) error

LogItem logs a result for a dataset item in this experiment.

func (*Experiment) Metadata

func (e *Experiment) Metadata() map[string]any

Metadata returns the experiment metadata.

func (*Experiment) Name

func (e *Experiment) Name() string

Name returns the experiment name.

type ExperimentItem

type ExperimentItem struct {
	ID            string
	ExperimentID  string
	DatasetItemID string
	TraceID       string
	Input         any
	Output        any
}

ExperimentItem represents an item result in an experiment.

type ExperimentItemOption

type ExperimentItemOption func(*experimentItemOptions)

ExperimentItemOption is a functional option for configuring an ExperimentItem.

func WithExperimentItemInput

func WithExperimentItemInput(input any) ExperimentItemOption

WithExperimentItemInput sets the input for the experiment item.

func WithExperimentItemOutput

func WithExperimentItemOutput(output any) ExperimentItemOption

WithExperimentItemOutput sets the output for the experiment item.

type ExperimentOption

type ExperimentOption func(*experimentOptions)

ExperimentOption is a functional option for configuring an Experiment.

func WithExperimentMetadata

func WithExperimentMetadata(metadata map[string]any) ExperimentOption

WithExperimentMetadata sets the metadata for the experiment.

func WithExperimentName

func WithExperimentName(name string) ExperimentOption

WithExperimentName sets the name for the experiment.

func WithExperimentStatus

func WithExperimentStatus(status ExperimentStatus) ExperimentOption

WithExperimentStatus sets the initial status for the experiment.

func WithExperimentType

func WithExperimentType(experimentType ExperimentType) ExperimentOption

WithExperimentType sets the type for the experiment.

type ExperimentStatus

type ExperimentStatus string

ExperimentStatus represents the status of an experiment.

const (
	ExperimentStatusRunning   ExperimentStatus = "running"
	ExperimentStatusCompleted ExperimentStatus = "completed"
	ExperimentStatusCancelled ExperimentStatus = "cancelled"
)

type ExperimentType

type ExperimentType string

ExperimentType represents the type of an experiment.

const (
	ExperimentTypeRegular   ExperimentType = "regular"
	ExperimentTypeTrial     ExperimentType = "trial"
	ExperimentTypeMiniBatch ExperimentType = "mini-batch"
)

type FeedbackBatchItem

type FeedbackBatchItem struct {
	EntityType string // "trace" or "span"
	EntityID   string
	Name       string
	Value      float64
	Reason     string
}

FeedbackBatchItem represents a feedback score to be logged.

func (FeedbackBatchItem) Type

func (f FeedbackBatchItem) Type() string

type LocalRecording

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

LocalRecording captures traces and spans locally without sending to the server.

func NewLocalRecording

func NewLocalRecording() *LocalRecording

NewLocalRecording creates a new local recording storage.

func (*LocalRecording) AddFeedback

func (r *LocalRecording) AddFeedback(entityID string, feedback RecordedFeedback)

AddFeedback adds feedback to the recording.

func (*LocalRecording) AddSpan

func (r *LocalRecording) AddSpan(span *RecordedSpan)

AddSpan adds a span to the recording.

func (*LocalRecording) AddTrace

func (r *LocalRecording) AddTrace(trace *RecordedTrace)

AddTrace adds a trace to the recording.

func (*LocalRecording) Clear

func (r *LocalRecording) Clear()

Clear clears all recorded data.

func (*LocalRecording) GetSpan

func (r *LocalRecording) GetSpan(id string) *RecordedSpan

GetSpan returns a specific span by ID.

func (*LocalRecording) GetTrace

func (r *LocalRecording) GetTrace(id string) *RecordedTrace

GetTrace returns a specific trace by ID.

func (*LocalRecording) SpanCount

func (r *LocalRecording) SpanCount() int

SpanCount returns the number of recorded spans.

func (*LocalRecording) Spans

func (r *LocalRecording) Spans() []*RecordedSpan

Spans returns all recorded spans.

func (*LocalRecording) TraceCount

func (r *LocalRecording) TraceCount() int

TraceCount returns the number of recorded traces.

func (*LocalRecording) Traces

func (r *LocalRecording) Traces() []*RecordedTrace

Traces returns all recorded traces.

type Option

type Option func(*clientOptions)

Option is a functional option for configuring the Client.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey sets the API key for authentication.

func WithConfig

func WithConfig(config *Config) Option

WithConfig sets the entire configuration.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithProjectName

func WithProjectName(projectName string) Option

WithProjectName sets the default project name.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the request timeout.

func WithTracingDisabled

func WithTracingDisabled(disabled bool) Option

WithTracingDisabled disables tracing.

func WithURL

func WithURL(url string) Option

WithURL sets the API URL.

func WithWorkspace

func WithWorkspace(workspace string) Option

WithWorkspace sets the workspace name.

type Project

type Project struct {
	ID          string
	Name        string
	Description string
	CreatedAt   time.Time
	LastUpdated time.Time
}

Project represents an Opik project.

type ProjectOption

type ProjectOption func(*projectOptions)

ProjectOption configures a project creation.

func WithProjectDescription

func WithProjectDescription(desc string) ProjectOption

WithProjectDescription sets the project description.

type Prompt

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

Prompt represents a prompt template in Opik.

func (*Prompt) CreateVersion

func (p *Prompt) CreateVersion(ctx context.Context, template string, opts ...PromptVersionOption) (*PromptVersion, error)

CreateVersion creates a new version of this prompt.

func (*Prompt) Delete

func (p *Prompt) Delete(ctx context.Context) error

Delete deletes this prompt.

func (*Prompt) Description

func (p *Prompt) Description() string

Description returns the prompt description.

func (*Prompt) GetVersions

func (p *Prompt) GetVersions(ctx context.Context, page, size int) ([]*PromptVersion, error)

GetVersions retrieves all versions of this prompt.

func (*Prompt) ID

func (p *Prompt) ID() string

ID returns the prompt ID.

func (*Prompt) Name

func (p *Prompt) Name() string

Name returns the prompt name.

func (*Prompt) Tags

func (p *Prompt) Tags() []string

Tags returns the prompt tags.

func (*Prompt) Template

func (p *Prompt) Template() string

Template returns the prompt template.

type PromptOption

type PromptOption func(*promptOptions)

PromptOption is a functional option for configuring a Prompt.

func WithPromptChangeDescription

func WithPromptChangeDescription(changeDescription string) PromptOption

WithPromptChangeDescription sets the change description for the prompt version.

func WithPromptDescription

func WithPromptDescription(description string) PromptOption

WithPromptDescription sets the description for the prompt.

func WithPromptTags

func WithPromptTags(tags ...string) PromptOption

WithPromptTags sets the tags for the prompt.

func WithPromptTemplate

func WithPromptTemplate(template string) PromptOption

WithPromptTemplate sets the template for the prompt.

func WithPromptTemplateStructure

func WithPromptTemplateStructure(structure PromptTemplateStructure) PromptOption

WithPromptTemplateStructure sets the template structure (text or chat).

func WithPromptType

func WithPromptType(promptType PromptType) PromptOption

WithPromptType sets the type for the prompt (mustache, fstring, jinja2).

type PromptTemplateStructure

type PromptTemplateStructure string

PromptTemplateStructure represents the type of prompt template.

const (
	PromptTemplateStructureText PromptTemplateStructure = "text"
	PromptTemplateStructureChat PromptTemplateStructure = "chat"
)

type PromptType

type PromptType string

PromptType represents the type of prompt.

const (
	PromptTypeMustache PromptType = "mustache"
	PromptTypeFString  PromptType = "fstring"
	PromptTypeJinja2   PromptType = "jinja2"
)

type PromptVersion

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

PromptVersion represents a specific version of a prompt.

func (*PromptVersion) ChangeDescription

func (v *PromptVersion) ChangeDescription() string

ChangeDescription returns the version change description.

func (*PromptVersion) Commit

func (v *PromptVersion) Commit() string

Commit returns the version commit hash.

func (*PromptVersion) ExtractVariables

func (v *PromptVersion) ExtractVariables() []string

ExtractVariables returns a list of variable names in the template.

func (*PromptVersion) ID

func (v *PromptVersion) ID() string

ID returns the prompt version ID.

func (*PromptVersion) PromptID

func (v *PromptVersion) PromptID() string

PromptID returns the parent prompt ID.

func (*PromptVersion) Render

func (v *PromptVersion) Render(variables map[string]string) string

Render renders the template with the given variables. Supports mustache-style {{variable}} placeholders.

func (*PromptVersion) RenderWithDefault

func (v *PromptVersion) RenderWithDefault(variables map[string]string, defaultValue string) string

RenderWithDefault renders the template with the given variables, using default values for missing variables.

func (*PromptVersion) Tags

func (v *PromptVersion) Tags() []string

Tags returns the version tags.

func (*PromptVersion) Template

func (v *PromptVersion) Template() string

Template returns the version template.

type PromptVersionOption

type PromptVersionOption func(*promptVersionOptions)

PromptVersionOption is a functional option for configuring a PromptVersion.

func WithVersionChangeDescription

func WithVersionChangeDescription(changeDescription string) PromptVersionOption

WithVersionChangeDescription sets the change description for the version.

func WithVersionTags

func WithVersionTags(tags ...string) PromptVersionOption

WithVersionTags sets the tags for the version.

func WithVersionType

func WithVersionType(promptType PromptType) PromptVersionOption

WithVersionType sets the type for the version.

type PropagatingRoundTripper

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

PropagatingRoundTripper wraps an http.RoundTripper to automatically inject distributed trace headers into outgoing requests.

func NewPropagatingRoundTripper

func NewPropagatingRoundTripper(transport http.RoundTripper) *PropagatingRoundTripper

NewPropagatingRoundTripper creates a new PropagatingRoundTripper.

func (*PropagatingRoundTripper) RoundTrip

func (t *PropagatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type RecordedFeedback

type RecordedFeedback struct {
	Name   string
	Value  float64
	Reason string
}

RecordedFeedback represents a feedback score captured during local recording.

type RecordedSpan

type RecordedSpan struct {
	ID           string
	TraceID      string
	ParentSpanID string
	Name         string
	Type         string
	StartTime    time.Time
	EndTime      time.Time
	Input        any
	Output       any
	Metadata     map[string]any
	Tags         []string
	Model        string
	Provider     string
	Children     []*RecordedSpan
	Feedback     []*RecordedFeedback
}

RecordedSpan represents a span captured during local recording.

type RecordedTrace

type RecordedTrace struct {
	ID        string
	Name      string
	StartTime time.Time
	EndTime   time.Time
	Input     any
	Output    any
	Metadata  map[string]any
	Tags      []string
	Spans     []*RecordedSpan
	Feedback  []*RecordedFeedback
}

RecordedTrace represents a trace captured during local recording.

type RecordingClient

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

RecordingClient is a client that records traces locally instead of sending to server.

func NewRecordingClient

func NewRecordingClient(projectName string) *RecordingClient

NewRecordingClient creates a new recording client for local testing.

func RecordTracesLocally

func RecordTracesLocally(projectName string) *RecordingClient

RecordTracesLocally returns a recording client for local testing. Usage:

client := opik.RecordTracesLocally("my-project")
trace, _ := client.Trace(ctx, "test-trace")
// ... do work ...
trace.End(ctx)
traces := client.Recording().Traces()

func (*RecordingClient) Recording

func (c *RecordingClient) Recording() *LocalRecording

Recording returns the local recording storage.

func (*RecordingClient) Trace

func (c *RecordingClient) Trace(ctx context.Context, name string, opts ...TraceOption) (*RecordingTrace, error)

Trace creates a new trace and records it locally.

type RecordingSpan

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

RecordingSpan is a span that records locally.

func (*RecordingSpan) AddFeedbackScore

func (s *RecordingSpan) AddFeedbackScore(ctx context.Context, name string, value float64, reason string) error

AddFeedbackScore adds a feedback score to this span.

func (*RecordingSpan) End

func (s *RecordingSpan) End(ctx context.Context, opts ...SpanOption) error

End ends the span.

func (*RecordingSpan) ID

func (s *RecordingSpan) ID() string

ID returns the span ID.

func (*RecordingSpan) Name

func (s *RecordingSpan) Name() string

Name returns the span name.

func (*RecordingSpan) Span

func (s *RecordingSpan) Span(ctx context.Context, name string, opts ...SpanOption) (*RecordingSpan, error)

Span creates a child span.

func (*RecordingSpan) TraceID

func (s *RecordingSpan) TraceID() string

TraceID returns the trace ID.

type RecordingTrace

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

RecordingTrace is a trace that records locally.

func (*RecordingTrace) AddFeedbackScore

func (t *RecordingTrace) AddFeedbackScore(ctx context.Context, name string, value float64, reason string) error

AddFeedbackScore adds a feedback score to this trace.

func (*RecordingTrace) End

func (t *RecordingTrace) End(ctx context.Context, opts ...TraceOption) error

End ends the trace.

func (*RecordingTrace) ID

func (t *RecordingTrace) ID() string

ID returns the trace ID.

func (*RecordingTrace) Name

func (t *RecordingTrace) Name() string

Name returns the trace name.

func (*RecordingTrace) Span

func (t *RecordingTrace) Span(ctx context.Context, name string, opts ...SpanOption) (*RecordingSpan, error)

Span creates a new span under this trace.

type Span

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

Span represents a span within a trace in Opik.

func SpanFromContext

func SpanFromContext(ctx context.Context) *Span

SpanFromContext returns the span from the context, or nil if none.

func StartSpan

func StartSpan(ctx context.Context, name string, opts ...SpanOption) (context.Context, *Span, error)

StartSpan creates a new span and attaches it to the context. If there is no parent span in the context, it uses the trace from context. Returns the new context and the span.

func (*Span) AddFeedbackScore

func (s *Span) AddFeedbackScore(ctx context.Context, name string, value float64, reason string) error

AddFeedbackScore adds a feedback score to this span.

func (*Span) End

func (s *Span) End(ctx context.Context, opts ...SpanOption) error

End ends the span with optional output.

func (*Span) EndTime

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

EndTime returns the end time, or nil if not ended.

func (*Span) ID

func (s *Span) ID() string

ID returns the span ID.

func (*Span) Name

func (s *Span) Name() string

Name returns the span name.

func (*Span) ParentSpanID

func (s *Span) ParentSpanID() string

ParentSpanID returns the parent span ID, or empty string if none.

func (*Span) SetUsage

func (s *Span) SetUsage(usage map[string]int)

SetUsage sets LLM usage metrics for this span.

func (*Span) Span

func (s *Span) Span(ctx context.Context, name string, opts ...SpanOption) (*Span, error)

Span creates a child span within this span.

func (*Span) StartTime

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

StartTime returns the start time.

func (*Span) TraceID

func (s *Span) TraceID() string

TraceID returns the trace ID.

func (*Span) Type

func (s *Span) Type() string

Type returns the span type.

func (*Span) Update

func (s *Span) Update(ctx context.Context, opts ...SpanOption) error

Update updates the span with new data.

type SpanBatchItem

type SpanBatchItem struct {
	Span *Span
}

SpanBatchItem represents a span to be created.

func (SpanBatchItem) Type

func (s SpanBatchItem) Type() string

type SpanInfo

type SpanInfo struct {
	ID           string
	TraceID      string
	ParentSpanID string
	Name         string
	Type         string
	StartTime    time.Time
	EndTime      time.Time
	Model        string
	Provider     string
}

SpanInfo represents basic span information.

type SpanOption

type SpanOption func(*spanOptions)

SpanOption is a functional option for configuring a Span.

func WithSpanInput

func WithSpanInput(input any) SpanOption

WithSpanInput sets the input for the span.

func WithSpanMetadata

func WithSpanMetadata(metadata map[string]any) SpanOption

WithSpanMetadata sets the metadata for the span.

func WithSpanModel

func WithSpanModel(model string) SpanOption

WithSpanModel sets the model name for LLM spans.

func WithSpanOutput

func WithSpanOutput(output any) SpanOption

WithSpanOutput sets the output for the span.

func WithSpanProvider

func WithSpanProvider(provider string) SpanOption

WithSpanProvider sets the provider name for LLM spans.

func WithSpanTags

func WithSpanTags(tags ...string) SpanOption

WithSpanTags sets the tags for the span.

func WithSpanType

func WithSpanType(spanType string) SpanOption

WithSpanType sets the type of the span (general, llm, tool, guardrail).

type StreamAccumulator

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

StreamAccumulator accumulates streaming chunks into a complete response.

func NewStreamAccumulator

func NewStreamAccumulator() *StreamAccumulator

NewStreamAccumulator creates a new stream accumulator.

func (*StreamAccumulator) AddChunk

func (a *StreamAccumulator) AddChunk(chunk StreamChunk)

AddChunk adds a chunk to the accumulator.

func (*StreamAccumulator) ChunkCount

func (a *StreamAccumulator) ChunkCount() int

ChunkCount returns the number of chunks received.

func (*StreamAccumulator) Content

func (a *StreamAccumulator) Content() string

Content returns the accumulated content.

func (*StreamAccumulator) Duration

func (a *StreamAccumulator) Duration() time.Duration

Duration returns the duration from first to last chunk.

func (*StreamAccumulator) FinishReason

func (a *StreamAccumulator) FinishReason() string

FinishReason returns the finish reason.

func (*StreamAccumulator) Metadata

func (a *StreamAccumulator) Metadata() map[string]any

Metadata returns the accumulated metadata.

func (*StreamAccumulator) TimeToFirstChunk

func (a *StreamAccumulator) TimeToFirstChunk(streamStart time.Time) time.Duration

TimeToFirstChunk returns the time to first chunk (should be set externally).

func (*StreamAccumulator) ToOutput

func (a *StreamAccumulator) ToOutput() map[string]any

ToOutput returns the accumulator as a span output.

func (*StreamAccumulator) TotalTokens

func (a *StreamAccumulator) TotalTokens() int

TotalTokens returns the total token count.

type StreamChunk

type StreamChunk struct {
	Content      string
	Index        int
	IsFirst      bool
	IsLast       bool
	Timestamp    time.Time
	TokenCount   int
	FinishReason string
	Metadata     map[string]any
}

StreamChunk represents a chunk of streaming data.

type StreamChunkOption

type StreamChunkOption func(*StreamChunk)

StreamChunkOption configures a stream chunk.

func WithChunkFinishReason

func WithChunkFinishReason(reason string) StreamChunkOption

WithChunkFinishReason sets the finish reason.

func WithChunkMetadata

func WithChunkMetadata(key string, value any) StreamChunkOption

WithChunkMetadata adds metadata to a chunk.

func WithChunkTokenCount

func WithChunkTokenCount(count int) StreamChunkOption

WithChunkTokenCount sets the token count for a chunk.

type StreamHandler

type StreamHandler interface {
	// HandleChunk processes a chunk of data.
	HandleChunk(chunk StreamChunk) error
	// Finalize is called when the stream ends.
	Finalize() error
}

StreamHandler is a generic interface for processing streams.

type StreamingSpan

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

StreamingSpan wraps a span for streaming operations.

func NewStreamingSpan

func NewStreamingSpan(span *Span) *StreamingSpan

NewStreamingSpan creates a new streaming span wrapper.

func StartStreamingSpan

func StartStreamingSpan(ctx context.Context, name string, opts ...SpanOption) (context.Context, *StreamingSpan, error)

StartStreamingSpan starts a new span configured for streaming.

func (*StreamingSpan) Accumulator

func (s *StreamingSpan) Accumulator() *StreamAccumulator

Accumulator returns the stream accumulator.

func (*StreamingSpan) AddChunk

func (s *StreamingSpan) AddChunk(content string, opts ...StreamChunkOption)

AddChunk adds a chunk and tracks it.

func (*StreamingSpan) End

func (s *StreamingSpan) End(ctx context.Context, opts ...SpanOption) error

End ends the streaming span with accumulated data.

func (*StreamingSpan) ID

func (s *StreamingSpan) ID() string

ID returns the span ID.

func (*StreamingSpan) OnChunk

func (s *StreamingSpan) OnChunk(fn func(chunk StreamChunk))

OnChunk sets a callback for when chunks are received.

func (*StreamingSpan) Span

func (s *StreamingSpan) Span() *Span

Span returns the underlying span.

func (*StreamingSpan) TraceID

func (s *StreamingSpan) TraceID() string

TraceID returns the trace ID.

type Trace

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

Trace represents an execution trace in Opik.

func StartTrace

func StartTrace(ctx context.Context, client *Client, name string, opts ...TraceOption) (context.Context, *Trace, error)

StartTrace creates a new trace and attaches it to the context. Returns the new context and the trace.

func TraceFromContext

func TraceFromContext(ctx context.Context) *Trace

TraceFromContext returns the trace from the context, or nil if none.

func (*Trace) AddFeedbackScore

func (t *Trace) AddFeedbackScore(ctx context.Context, name string, value float64, reason string) error

AddFeedbackScore adds a feedback score to this trace.

func (*Trace) End

func (t *Trace) End(ctx context.Context, opts ...TraceOption) error

End ends the trace with optional output.

func (*Trace) EndTime

func (t *Trace) EndTime() *time.Time

EndTime returns the end time, or nil if not ended.

func (*Trace) ID

func (t *Trace) ID() string

ID returns the trace ID.

func (*Trace) Name

func (t *Trace) Name() string

Name returns the trace name.

func (*Trace) ProjectName

func (t *Trace) ProjectName() string

ProjectName returns the project name.

func (*Trace) Span

func (t *Trace) Span(ctx context.Context, name string, opts ...SpanOption) (*Span, error)

Span creates a new span within this trace.

func (*Trace) StartTime

func (t *Trace) StartTime() time.Time

StartTime returns the start time.

func (*Trace) Update

func (t *Trace) Update(ctx context.Context, opts ...TraceOption) error

Update updates the trace with new data.

type TraceBatchItem

type TraceBatchItem struct {
	Trace *Trace
}

TraceBatchItem represents a trace to be created.

func (TraceBatchItem) Type

func (t TraceBatchItem) Type() string

type TraceInfo

type TraceInfo struct {
	ID        string
	Name      string
	StartTime time.Time
	EndTime   time.Time
}

TraceInfo represents basic trace information.

type TraceOption

type TraceOption func(*traceOptions)

TraceOption is a functional option for configuring a Trace.

func WithTraceInput

func WithTraceInput(input any) TraceOption

WithTraceInput sets the input for the trace.

func WithTraceMetadata

func WithTraceMetadata(metadata map[string]any) TraceOption

WithTraceMetadata sets the metadata for the trace.

func WithTraceOutput

func WithTraceOutput(output any) TraceOption

WithTraceOutput sets the output for the trace.

func WithTraceProject

func WithTraceProject(projectName string) TraceOption

WithTraceProject sets the project name for the trace.

func WithTraceTags

func WithTraceTags(tags ...string) TraceOption

WithTraceTags sets the tags for the trace.

func WithTraceThreadID

func WithTraceThreadID(threadID string) TraceOption

WithTraceThreadID sets the thread ID for the trace.

type TracingStreamHandler

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

TracingStreamHandler wraps a StreamHandler to add tracing.

func NewTracingStreamHandler

func NewTracingStreamHandler(inner StreamHandler, span *Span) *TracingStreamHandler

NewTracingStreamHandler creates a tracing stream handler.

func (*TracingStreamHandler) Finalize

func (h *TracingStreamHandler) Finalize() error

Finalize ends the stream and the span.

func (*TracingStreamHandler) HandleChunk

func (h *TracingStreamHandler) HandleChunk(chunk StreamChunk) error

HandleChunk processes a chunk and tracks it.

func (*TracingStreamHandler) StreamingSpan

func (h *TracingStreamHandler) StreamingSpan() *StreamingSpan

StreamingSpan returns the streaming span for ending.

Directories

Path Synopsis
cmd
opik command
Package evaluation provides a framework for evaluating LLM outputs.
Package evaluation provides a framework for evaluating LLM outputs.
heuristic
Package heuristic provides rule-based evaluation metrics that don't require LLM calls.
Package heuristic provides rule-based evaluation metrics that don't require LLM calls.
llm
Package llm provides LLM-based evaluation metrics.
Package llm provides LLM-based evaluation metrics.
examples
basic command
connectivity-test command
Package main provides a connectivity test with HTTP debug output.
Package main provides a connectivity test with HTTP debug output.
debug-test command
Package main provides diagnostic tools for testing and debugging Opik traces and spans.
Package main provides diagnostic tools for testing and debugging Opik traces and spans.
integrations
omnillm
Package omnillm provides Opik integration for the omnillm LLM wrapper library.
Package omnillm provides Opik integration for the omnillm LLM wrapper library.
internal
api
Code generated by ogen, DO NOT EDIT.
Code generated by ogen, DO NOT EDIT.
Package llmops provides an omniobserve/llmops adapter for go-opik.
Package llmops provides an omniobserve/llmops adapter for go-opik.
Package testutil provides testing utilities for the Opik SDK.
Package testutil provides testing utilities for the Opik SDK.

Jump to

Keyboard shortcuts

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