phoenix

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package phoenix provides a Go SDK for Arize Phoenix, an open-source LLM observability platform.

Phoenix uses OpenTelemetry for trace collection. This SDK wraps OTEL with Phoenix-specific semantics and convenience methods.

Usage:

client, err := phoenix.NewClient(
	phoenix.WithEndpoint("http://localhost:6006"),
	phoenix.WithAPIKey("..."), // Optional for cloud
)
if err != nil {
	log.Fatal(err)
}
defer client.Shutdown(context.Background())

ctx, trace, _ := client.StartTrace(ctx, "my-trace")
defer trace.End(ctx)

Index

Constants

View Source
const (
	DefaultEndpoint = "http://localhost:6006"
	CloudEndpoint   = "https://app.phoenix.arize.com"
)

Default endpoints.

View Source
const Version = "0.1.0"

Version is the SDK version.

Variables

View Source
var (
	ErrMissingEndpoint = errors.New("phoenix: missing endpoint")
	ErrMissingAPIKey   = errors.New("phoenix: missing API key (required for cloud)")
	ErrNoActiveTrace   = errors.New("phoenix: no active trace in context")
	ErrNoActiveSpan    = errors.New("phoenix: no active span in context")
	ErrTraceNotFound   = errors.New("phoenix: trace not found")
	ErrSpanNotFound    = errors.New("phoenix: span not found")
	ErrDatasetNotFound = errors.New("phoenix: dataset not found")
	ErrProjectNotFound = errors.New("phoenix: project not found")
)

Sentinel errors.

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 context.

func CurrentTraceID

func CurrentTraceID(ctx context.Context) string

CurrentTraceID returns the current trace ID from context.

func EndSpan

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

EndSpan ends the current span in context.

func EndTrace

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

EndTrace ends the current trace in context.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error is a not found error.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited returns true if the error is a rate limit error.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized returns true if the error is an authentication error.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Details    map[string]any
}

APIError represents an error from the Phoenix API.

func (*APIError) Error

func (e *APIError) Error() string

type Annotation

type Annotation struct {
	ID            string         `json:"id"`
	SpanID        string         `json:"spanId"`
	Name          string         `json:"name"`
	AnnotatorKind string         `json:"annotatorKind"` // HUMAN, LLM
	Score         *float64       `json:"score,omitempty"`
	Label         string         `json:"label,omitempty"`
	Explanation   string         `json:"explanation,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
	CreatedAt     time.Time      `json:"createdAt"`
}

Annotation represents a human or automated annotation on a span.

type AnnotationOption

type AnnotationOption func(*annotationConfig)

AnnotationOption configures annotation creation.

func WithAnnotationExplanation

func WithAnnotationExplanation(explanation string) AnnotationOption

WithAnnotationExplanation sets the annotation explanation.

func WithAnnotationLabel

func WithAnnotationLabel(label string) AnnotationOption

WithAnnotationLabel sets the annotation label.

func WithAnnotationMetadata

func WithAnnotationMetadata(metadata map[string]any) AnnotationOption

WithAnnotationMetadata sets annotation metadata.

type Client

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

Client is the main Phoenix client.

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 Phoenix client.

func (*Client) AddAnnotation

func (c *Client) AddAnnotation(ctx context.Context, spanID string, name string, score float64, opts ...AnnotationOption) error

AddAnnotation adds an annotation/feedback to a span.

func (*Client) AddDatasetItems

func (c *Client) AddDatasetItems(ctx context.Context, datasetID string, items []DatasetItem) error

AddDatasetItems adds items to a dataset.

func (*Client) Close

func (c *Client) Close() error

Close is an alias for Shutdown.

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, datasetID string, name string) (*Experiment, error)

CreateExperiment creates a new experiment.

func (*Client) CreateProject

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

CreateProject creates a new project.

func (*Client) GetDataset

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

GetDataset retrieves a dataset by name.

func (*Client) GetProject

func (c *Client) GetProject(ctx context.Context, name string) (*Project, error)

GetProject retrieves a project by name.

func (*Client) ListDatasets

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

ListDatasets lists all datasets.

func (*Client) ListProjects

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

ListProjects lists all projects.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the client and flushes any pending data.

func (*Client) StartTrace

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

StartTrace starts a new trace.

type Dataset

type Dataset struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	CreatedAt   time.Time      `json:"createdAt"`
	UpdatedAt   time.Time      `json:"updatedAt"`
}

Dataset represents a Phoenix dataset.

type DatasetItem

type DatasetItem struct {
	ID       string         `json:"id"`
	Input    any            `json:"input,omitempty"`
	Output   any            `json:"output,omitempty"`
	Expected any            `json:"expected,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

DatasetItem represents an item in a dataset.

type DatasetOption

type DatasetOption func(*datasetConfig)

DatasetOption configures dataset creation.

func WithDatasetDescription

func WithDatasetDescription(desc string) DatasetOption

WithDatasetDescription sets the dataset description.

func WithDatasetMetadata

func WithDatasetMetadata(metadata map[string]any) DatasetOption

WithDatasetMetadata sets dataset metadata.

type Document

type Document struct {
	ID       string         `json:"id,omitempty"`
	Content  string         `json:"content"`
	Score    float64        `json:"score,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

Document represents a retrieved document.

type Evaluation

type Evaluation struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	TraceID     string         `json:"traceId,omitempty"`
	SpanID      string         `json:"spanId,omitempty"`
	Score       float64        `json:"score"`
	Label       string         `json:"label,omitempty"`
	Explanation string         `json:"explanation,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	CreatedAt   time.Time      `json:"createdAt"`
}

Evaluation represents an evaluation result.

type Experiment

type Experiment struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	DatasetID string         `json:"datasetId"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	CreatedAt time.Time      `json:"createdAt"`
}

Experiment represents an evaluation experiment.

type Message

type Message struct {
	Role       string     `json:"role"`
	Content    string     `json:"content"`
	Name       string     `json:"name,omitempty"`
	ToolCalls  []ToolCall `json:"toolCalls,omitempty"`
	ToolCallID string     `json:"toolCallId,omitempty"`
}

Message represents a chat message.

type Option

type Option func(*Client)

Option configures the client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key for authentication.

func WithDebug

func WithDebug(debug bool) Option

WithDebug enables debug mode.

func WithDisabled

func WithDisabled(disabled bool) Option

WithDisabled disables tracing.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint sets the Phoenix API endpoint.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders sets additional HTTP headers.

func WithProjectID

func WithProjectID(id string) Option

WithProjectID sets the default project ID.

type Project

type Project struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

Project represents a Phoenix project.

type ProjectOption

type ProjectOption func(*projectConfig)

ProjectOption configures project creation.

func WithProjectDescription

func WithProjectDescription(desc string) ProjectOption

WithProjectDescription sets the project description.

func WithProjectMetadata

func WithProjectMetadata(metadata map[string]any) ProjectOption

WithProjectMetadata sets project metadata.

type Span

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

Span represents a span within a trace.

func SpanFromContext

func SpanFromContext(ctx context.Context) *Span

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

func StartLLMSpan

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

StartLLMSpan starts an LLM span from the current context.

func StartSpan

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

StartSpan starts a span from the current context.

func (*Span) AddAnnotation

func (s *Span) AddAnnotation(ctx context.Context, name string, score float64, opts ...AnnotationOption) error

AddAnnotation adds an annotation to the span.

func (*Span) AddEvent

func (s *Span) AddEvent(name string, attrs map[string]any)

AddEvent adds an event to the span.

func (*Span) End

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

End ends the span.

func (*Span) EndTime

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

EndTime returns the end time.

func (*Span) ID

func (s *Span) ID() string

ID returns the span ID.

func (*Span) Kind

func (s *Span) Kind() SpanKind

Kind returns the span kind.

func (*Span) LLMSpan

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

LLMSpan creates an LLM child span.

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.

func (*Span) RetrieverSpan

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

RetrieverSpan creates a retriever child span.

func (*Span) SetDocuments

func (s *Span) SetDocuments(docs []Document) error

SetDocuments sets retrieved documents (for retriever spans).

func (*Span) SetInput

func (s *Span) SetInput(input any) error

SetInput sets the span input.

func (*Span) SetModel

func (s *Span) SetModel(model string) error

SetModel sets the model name.

func (*Span) SetOutput

func (s *Span) SetOutput(output any) error

SetOutput sets the span output.

func (*Span) SetUsage

func (s *Span) SetUsage(prompt, completion, total int) error

SetUsage sets token usage.

func (*Span) Span

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

Span creates a child span.

func (*Span) StartTime

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

StartTime returns the start time.

func (*Span) ToolSpan

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

ToolSpan creates a tool child span.

func (*Span) TraceID

func (s *Span) TraceID() string

TraceID returns the parent trace ID.

func (*Span) Update

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

Update updates the span.

type SpanAttributes

type SpanAttributes struct {
	// LLM attributes
	LLMModelName            string `json:"llm.model_name,omitempty"`
	LLMProvider             string `json:"llm.provider,omitempty"`
	LLMTokenCountPrompt     int    `json:"llm.token_count.prompt,omitempty"`
	LLMTokenCountCompletion int    `json:"llm.token_count.completion,omitempty"`
	LLMTokenCountTotal      int    `json:"llm.token_count.total,omitempty"`

	// Input/Output
	InputValue  any `json:"input.value,omitempty"`
	OutputValue any `json:"output.value,omitempty"`

	// Retrieval attributes
	RetrieverQueryEmbedding []float64 `json:"retriever.query.embedding,omitempty"`
	RetrieverDocumentCount  int       `json:"retriever.document_count,omitempty"`

	// Tool attributes
	ToolName        string `json:"tool.name,omitempty"`
	ToolDescription string `json:"tool.description,omitempty"`

	// Embedding attributes
	EmbeddingModelName string    `json:"embedding.model_name,omitempty"`
	EmbeddingVector    []float64 `json:"embedding.vector,omitempty"`

	// Session attributes
	SessionID string `json:"session.id,omitempty"`
	UserID    string `json:"user.id,omitempty"`

	// Custom metadata
	Metadata map[string]any `json:"metadata,omitempty"`
}

SpanAttributes holds semantic attributes for spans. Phoenix uses OpenTelemetry semantic conventions for LLM observability.

type SpanEvent

type SpanEvent struct {
	Name       string         `json:"name"`
	Timestamp  time.Time      `json:"timestamp"`
	Attributes map[string]any `json:"attributes,omitempty"`
}

SpanEvent represents an event within a span.

type SpanInfo

type SpanInfo struct {
	ID            string         `json:"id"`
	TraceID       string         `json:"traceId"`
	ParentID      string         `json:"parentId,omitempty"`
	Name          string         `json:"name"`
	Kind          SpanKind       `json:"spanKind"`
	StartTime     time.Time      `json:"startTime"`
	EndTime       *time.Time     `json:"endTime,omitempty"`
	Latency       float64        `json:"latencyMs,omitempty"`
	Status        string         `json:"status,omitempty"`
	Attributes    SpanAttributes `json:"attributes,omitempty"`
	Events        []SpanEvent    `json:"events,omitempty"`
	StatusMessage string         `json:"statusMessage,omitempty"`
}

SpanInfo provides read-only information about a span.

type SpanKind

type SpanKind string

SpanKind represents the type of span.

const (
	SpanKindLLM       SpanKind = "LLM"
	SpanKindChain     SpanKind = "CHAIN"
	SpanKindTool      SpanKind = "TOOL"
	SpanKindAgent     SpanKind = "AGENT"
	SpanKindRetriever SpanKind = "RETRIEVER"
	SpanKindEmbedding SpanKind = "EMBEDDING"
	SpanKindReranker  SpanKind = "RERANKER"
	SpanKindGuardrail SpanKind = "GUARDRAIL"
	SpanKindEvaluator SpanKind = "EVALUATOR"
	SpanKindUnknown   SpanKind = "UNKNOWN"
)

type SpanOption

type SpanOption func(*spanConfig)

SpanOption configures span creation.

func WithModel

func WithModel(model string) SpanOption

WithModel sets the model name.

func WithProvider

func WithProvider(provider string) SpanOption

WithProvider sets the provider name.

func WithSpanInput

func WithSpanInput(input any) SpanOption

WithSpanInput sets the span input.

func WithSpanKind

func WithSpanKind(kind SpanKind) SpanOption

WithSpanKind sets the span kind.

func WithSpanMetadata

func WithSpanMetadata(metadata map[string]any) SpanOption

WithSpanMetadata sets span metadata.

func WithSpanOutput

func WithSpanOutput(output any) SpanOption

WithSpanOutput sets the span output.

func WithStartTime

func WithStartTime(t time.Time) SpanOption

WithStartTime sets a custom start time.

func WithUsage

func WithUsage(prompt, completion, total int) SpanOption

WithUsage sets token usage.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCall represents a tool call.

type Trace

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

Trace represents an execution trace.

func TraceFromContext

func TraceFromContext(ctx context.Context) *Trace

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

func (*Trace) AddAnnotation

func (t *Trace) AddAnnotation(ctx context.Context, name string, score float64, opts ...AnnotationOption) error

AddAnnotation adds an annotation to the trace.

func (*Trace) ChainSpan

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

ChainSpan creates a chain span.

func (*Trace) End

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

End ends the trace.

func (*Trace) EndTime

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

EndTime returns the end time.

func (*Trace) ID

func (t *Trace) ID() string

ID returns the trace ID.

func (*Trace) LLMSpan

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

LLMSpan creates an LLM span.

func (*Trace) Name

func (t *Trace) Name() string

Name returns the trace name.

func (*Trace) RetrieverSpan

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

RetrieverSpan creates a retriever span.

func (*Trace) Span

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

Span creates a child span.

func (*Trace) StartTime

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

StartTime returns the start time.

func (*Trace) ToolSpan

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

ToolSpan creates a tool span.

func (*Trace) Update

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

Update updates the trace.

type TraceInfo

type TraceInfo struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	ProjectID string         `json:"projectId,omitempty"`
	StartTime time.Time      `json:"startTime"`
	EndTime   *time.Time     `json:"endTime,omitempty"`
	Latency   float64        `json:"latencyMs,omitempty"`
	Status    string         `json:"status,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	SpanCount int            `json:"numSpans,omitempty"`
}

TraceInfo provides read-only information about a trace.

type TraceOption

type TraceOption func(*traceConfig)

TraceOption configures trace creation.

func WithInput

func WithInput(input any) TraceOption

WithInput sets the trace input.

func WithMetadata

func WithMetadata(metadata map[string]any) TraceOption

WithMetadata sets trace metadata.

func WithOutput

func WithOutput(output any) TraceOption

WithOutput sets the trace output.

func WithSessionID

func WithSessionID(sessionID string) TraceOption

WithSessionID sets the session ID.

func WithUserID

func WithUserID(userID string) TraceOption

WithUserID sets the user ID.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens,omitempty"`
	CompletionTokens int `json:"completion_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens,omitempty"`
}

Usage represents token usage for LLM calls.

Jump to

Keyboard shortcuts

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